branch_name
stringclasses 149
values | text
stringlengths 23
89.3M
| directory_id
stringlengths 40
40
| languages
listlengths 1
19
| num_files
int64 1
11.8k
| repo_language
stringclasses 38
values | repo_name
stringlengths 6
114
| revision_id
stringlengths 40
40
| snapshot_id
stringlengths 40
40
|
---|---|---|---|---|---|---|---|---|
refs/heads/master | <repo_name>cturner5/rottenpotatoes-rails-intro<file_sep>/app/controllers/movies_controller.rb
class MoviesController < ApplicationController
before_action :set_movie, only: [:show, :edit, :update, :destroy, :similar]
# GET /movies
# GET /movies.json
def index
if params[:sort]
session[:sort] = params[:sort]
end
if params[:ratings]
session[:ratings] = params[:ratings]
else
if session[:ratings]
redirect_to movies_path(Hash[session[:ratings].map { |k, v| ["ratings[#{k}]", v]}])
else
session[:ratings] = Hash[Movie.all_ratings.map {|r| [r, 1]}]
end
end
@movies = Movie.all
@movies = Movie.order session[:sort]
@movies = @movies.where(rating: session[:ratings].keys)
@all_ratings = Movie.all_ratings
end
# GET /movies/1
# GET /movies/1.json
def show
end
# GET /movies/new
def new
@movie = Movie.new
end
# GET /movies/1/edit
def edit
end
# POST /movies
# POST /movies.json
def create
@movie = Movie.new(movie_params)
respond_to do |format|
if @movie.save
format.html { redirect_to @movie, notice: 'Movie was successfully created.' }
format.json { render action: 'show', status: :created, location: @movie }
else
format.html { render action: 'new' }
format.json { render json: @movie.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /movies/1
# PATCH/PUT /movies/1.json
def update
respond_to do |format|
if @movie.update(movie_params)
format.html { redirect_to @movie, notice: 'Movie was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: 'edit' }
format.json { render json: @movie.errors, status: :unprocessable_entity }
end
end
end
# DELETE /movies/1
# DELETE /movies/1.json
def destroy
@movie.destroy
respond_to do |format|
format.html { redirect_to movies_url }
format.json { head :no_content }
end
end
def similar
@movies = @movie.similar_movies
if @movies
render "similar"
else
redirect_to :root, notice: "'#{@movie.title}' has no director info"
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_movie
@movie = Movie.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def movie_params
params.require(:movie).permit(:title, :rating, :description, :release_date, :director)
end
end<file_sep>/app/models/movie.rb
class Movie < ActiveRecord::Base
def self.all_ratings
Movie.uniq.pluck(:rating)
end
def similar_movies
if self.director
movies = Movie.where director: self.director
if movies.count > 1
movies
end
end
end
end<file_sep>/app/views/movies/show.json.jbuilder
json.extract! @movie, :title, :rating, :description, :release_date, :created_at, :updated_at
| 536abb31a133d2353e6815abd7e838d31d3d45b3 | [
"Ruby"
]
| 3 | Ruby | cturner5/rottenpotatoes-rails-intro | 4cd396189a0ccab058fcc8052c554b2aa569f826 | d6a2c6cf80c93f0038414ca1bbf31a8f0a72e103 |
refs/heads/master | <repo_name>LachlanVaughan/CP2406_Assignment2<file_sep>/TopTrumps/src/com/company/Main.java
package com.company;
import static com.company.GameController.getCurrentPlayer;
import static java.lang.Thread.sleep;
public class Main{
public static boolean latch = false;
public static boolean keepPlaying = true;
public static void main(String[] args) {
GameController.cleavageRankingMap.makeRanking(GameController.possibleCleavageValues);
GameController.crystalAbundanceRankingMap.makeRanking(GameController.possibleCrystalAbundanceValues);
GameController.economicValuesRankingMap.makeRanking(GameController.possibleEconomicValues);
while(keepPlaying){
Options optionsForm = new Options();
listenerLatch();
GameForm gameForm = new GameForm();
GameController gameController = new GameController(Integer.parseInt(optionsForm.optionsTextField.getText()));
GameController.populatePlayerList();
GameController.d1.populateDeckFromXML();
GameController.d1.shuffleDeck();
gameController.shufflePlayerList();
gameController.setDealer();
gameController.populatePlayerHands();
gameController.nextPlayer();
GameController.setCurrentPlayer();
gameForm.currentPlayerLabel.setText(getCurrentPlayer().getPlayerName());
gameForm.cardsLeftLabel.setText(Integer.toString(GameController.d1.deck.size()));
new PlayOrderDialogue();
MenuController.displayPlayOrder();
while(!gameController.checkWinStatus()){
gameForm.currentPlayerLabel.setText(getCurrentPlayer().getPlayerName());
if (getCurrentPlayer().getPlayerName().equals("Player 1")) {
listenerLatch();
} else {
listenerLatch();
}
gameController.nextPlayer();
GameController.setCurrentPlayer();
}
GameOver gameOver = new GameOver();
gameForm.dispose();
}
}
public static void listenerLatch(){
while(!latch){
try {
sleep(200);
} catch(InterruptedException e) {
}
} latch = false;
}
public static void gWait(int time){
try {
sleep(time);
} catch(InterruptedException e) {
}
}
}<file_sep>/TopTrumps/src/com/company/GameOver.java
package com.company;
import javax.swing.*;
import java.awt.event.*;
public class GameOver extends JDialog implements ActionListener{
private JPanel contentPane;
private JButton buttonOK;
private JButton agianButton;
public GameOver() {
setContentPane(contentPane);
setModal(true);
pack();
buttonOK.addActionListener(this);
agianButton.addActionListener(this);
setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == buttonOK){
Main.keepPlaying = false;
dispose();
}
if(e.getSource() == agianButton){
dispose();
}
}
}
| d0eab3f72cdc0a4dd38e43431d16091a2c5526a0 | [
"Java"
]
| 2 | Java | LachlanVaughan/CP2406_Assignment2 | 10225d294f64981723b513219af74f5f29c12657 | 99cbdf0c9566cfbd6f9f39a272637dd3b5a8a86f |
refs/heads/master | <file_sep># SL-Lab-Part-B<file_sep>from collections import Counter
from functools import reduce
def word_count(fname):
with open(fname) as f:
return Counter(f.read().split())
myDict = word_count("myFile.txt")
print(myDict)
sorted_dict = {}
for w in sorted(myDict, key=myDict.get, reverse=True):
sorted_dict[w] = myDict[w]
print(sorted_dict)
print(list(sorted_dict.keys())[0:10])
list_number = list(sorted_dict.values())
print(list_number)
print('Average Length',reduce(lambda x,y:x+y,list_number)/(len(list_number)))
print('Squares of ODD numbers',[x*x for x in list_number if x%2!=0])
<file_sep>list = [int(x) for x in input().split()]
print("The list is",list)
s = set(list)
print(s)
new_list = []
for i in range(len(list)):
if list[i]%2==0:
new_list.append(list[i])
print(new_list)
reverse = list[::-1]
print(reverse)
<file_sep>import operator
class py_solution():
def reverse_words(self,s):
return " ".join(reversed(s.split()))
def vowel_count(self,s):
vowel = 0
for i in range(len(s)):
if s[i]=="a" or s[i]=="e" or s[i]=="i" or s[i]=="o" or s[i]=="u"or s[i]=="A"or s[i]=="E"or s[i]=="I" or s[i]=="O" or s[i]=="O":
vowel+=1
return vowel
myDict = {}
firstString = input("Enter the first string\n")
firstStringReverse = py_solution().reverse_words(firstString)
firstStringVowels = py_solution().vowel_count(firstString)
secondString = input("Enter the second string\n")
secondStringReverse = py_solution().reverse_words(secondString)
secondStringVowels = py_solution().vowel_count(secondString)
thirdString = input("Enter the third string\n")
thirdStringReverse = py_solution().reverse_words(thirdString)
thirdStringVowels = py_solution().vowel_count(thirdString)
myDict[firstStringReverse] = firstStringVowels
myDict[secondStringReverse] = secondStringVowels
myDict[thirdStringReverse] = thirdStringVowels
sorted_dict = {}
for w in sorted(myDict,key=myDict.get,reverse=True):
sorted_dict[w] = myDict[w]
print(sorted_dict)
<file_sep>def c2k():
celcius = int(input("Enter the tempearature in Celcius\n"))
return celcius+273
def k2c():
kelvin = int(input("Enter the tempearature in Kelvin\n"))
return kelvin-273
choice =0
while choice!=3:
choice = int(input("Enter 1 to convert from Celcius to Kelvin\nEnter 2 to convert from Kelvin to Celcius\nEnter 3 to exit\n"))
if choice == 1:
print(c2k())
elif choice == 2:
print(k2c())
elif choice == 3:
exit()
<file_sep>def maximum(list):
length = len(list)
if length==1:
return list
elif list[length-1]>=list[length-2]:
del list[length-2]
elif list[length-1]<=list[length-2]:
del list[length-1]
return maximum(list)
print("Enter the numbers to be considered below")
list = [int(x) for x in input().split()]
print("The entered elements are",list)
print(maximum(list))
| c3546dd122cd51dcd0f6679baf2163cd11f23b4b | [
"Markdown",
"Python"
]
| 6 | Markdown | cruzer3008/SL-Lab-Part-B | f4bc1380f0b28777ceae137ada1101f36aa5df02 | b04085b23968cd2220e14c02c3e3937c4ec27b26 |
refs/heads/main | <repo_name>pignolr/CPP_zia_2018<file_sep>/solution/src/server/ShellServer.cpp
/*
** EPITECH PROJECT, 2021
** zia
** File description:
** ShellServer.cpp
*/
#include <boost/algorithm/string.hpp>
#include "server/ShellServer.hpp"
#include "server/Request.hpp"
namespace zia::server {
const ShellServer::ShellCommandFuncMap ShellServer::initShellCommandFuncMap()
{
ShellServer::ShellCommandFuncMap map;
map.emplace("run", [this](ShellCommand &&command)
{ runServer(std::move(command)); });
map.emplace("stop", [this](ShellCommand &&command)
{ stopServer(std::move(command)); });
map.emplace("reload", [this](ShellCommand &&command)
{ reloadConfig(std::move(command)); });
map.emplace("help", [this](ShellCommand &&command)
{ affHelp(std::move(command)); });
return map;
}
ShellServer::ShellServer(std::string &&configFile):
_configFile(configFile),
_configManager(_configFile),
_config(std::move(_configManager.getConfig())),
_modulesManager(_config),
_server(nullptr),
_shellCommandFuncMap(initShellCommandFuncMap())
{}
ShellServer::ShellServer():
_configFile(),
_configManager(),
_config(std::move(_configManager.getConfig())),
_modulesManager(_config),
_server(nullptr),
_shellCommandFuncMap(initShellCommandFuncMap())
{}
void ShellServer::affHelp(ShellCommand &&)
{
std::cout << "Command:" << std::endl;
std::cout << "run" << "\t\t\t" << "run the server" << std::endl;
std::cout << "stop" << "\t\t\t" << "stop the server" << std::endl;
std::cout << "reload config_file" << "\t" << "reload the config file of the server (server must be stopped)" << std::endl;
std::cout << "help" << "\t\t\t" << "show the list of command" << std::endl;
}
void ShellServer::runServer(ShellCommand &&)
{
if (_server && _server->isRunning()) {
std::cerr << "The server is already running." << std::endl;
} else {
_server = std::make_unique<Server>(_config);
auto handleRequest = zia::server::Callback(std::bind(
[](dems::config::Config &config, dems::StageManager &stageManager, zia::server::SocketPtr socket)-> void{
// lambda who handle a request
try {
Request request(config, stageManager, std::move(socket));
request.handleRequest();
request.handleDisconnect();
}
catch (const std::exception &e){
std::cerr << "Error in Request socket: " << e.what() << std::endl;
}
}, _config, _modulesManager.getStageManager(), std::placeholders::_1));
_server->run(handleRequest);
}
}
void ShellServer::stopServer(ShellCommand &&)
{
if (_server && !_server->isRunning()) {
std::cerr << "The server is already stopped." << std::endl;
} else {
_server->stop();
_server.reset(nullptr);
}
}
void ShellServer::reloadConfig(ShellCommand &&command)
{
if (command.size() != 2) {
std::cerr << "Invalid number of argument: reload config_file" << std::endl;
} else {
_configFile = std::move(command[1]);
_configManager.reloadConfig(_configFile);
_config = std::move(_configManager.getConfig());
_modulesManager.reloadConfig(_config);
}
}
void ShellServer::run()
{
std::string input;
std::string command;
ShellCommand args;
while (!std::cin.eof()) {
/* print shell */
std::cout << "> ";
/* get input from user */
std::getline(std::cin, input);
/* separate input */
boost::algorithm::trim(input);
boost::algorithm::split(args, input, boost::is_any_of("\t "),boost::token_compress_on);
command = args[0];
/* execute command */
if (command.empty())
continue;
else if(_shellCommandFuncMap.count(command))
_shellCommandFuncMap.at(command)(std::move(args));
else if (command == "exit" || command =="quit")
break;
else
std::cerr << "Invalid Command: " << command << std::endl;
}
}
}
<file_sep>/module/ssl/src/ssl.cpp
/*
** EPITECH PROJECT, 2021
** zia
** File description:
** ssl.cpp
*/
#include <iostream>
#include "SSLConnection.hpp"
namespace zia::ssl_module {
dems::CodeStatus ModuleReadSSL(dems::Context &context)
{
SSLConnection sslConnection(context);
if (!sslConnection.isSSL())
return dems::CodeStatus::HTTP_ERROR;
sslConnection.read();
return dems::CodeStatus::OK;
}
dems::CodeStatus ModuleWriteSSL(dems::Context &context)
{
SSLConnection sslConnection(context);
if (!sslConnection.isSSL())
return dems::CodeStatus::HTTP_ERROR;
sslConnection.write();
return dems::CodeStatus::OK;
}
dems::CodeStatus ModuleDisconnectSSL(dems::Context &context)
{
SSLConnection sslConnection(context);
if (!sslConnection.isSSL())
return dems::CodeStatus::HTTP_ERROR;
sslConnection.disconnect();
return dems::CodeStatus::OK;
}
}
extern "C" {
std::string registerHooks(dems::StageManager &manager)
{
SSL_library_init();
SSL_load_error_strings();
OpenSSL_add_all_algorithms();
manager.connection().hookToEnd(0, "SSL Read", zia::ssl_module::ModuleReadSSL);
manager.chunks().hookToFirst(0, "SSL Read", zia::ssl_module::ModuleReadSSL);
manager.disconnect().hookToFirst(90000, "SSL Write", zia::ssl_module::ModuleWriteSSL);
manager.disconnect().hookToMiddle(0, "SSL Disconnect", zia::ssl_module::ModuleDisconnectSSL);
return "SSL";
}
}
<file_sep>/solution/inc/default_module/ModuleHttpResponseParser.hpp
/*
** EPITECH PROJECT, 2021
** zia
** File description:
** HttpResponseParser.hpp
*/
#pragma once
#include "api/Stage.hpp"
#include "server/Headers.hpp"
namespace zia::default_module {
dems::CodeStatus HttpResponse(dems::Context &cont);
dems::CodeStatus HttpResponseChunked(dems::Context &cont);
class HttpResponseParser
{
std::string _rest;
size_t _length;
size_t _left;
bool _chunked;
dems::Context &_cont;
std::vector<std::string> _heads;
dems::header::HTTPMessage _mess;
dems::header::Response _res;
//enlever le header du rawdata
void cleanRawData(size_t);
public:
HttpResponseParser(dems::Context &cont);
~HttpResponseParser();
dems::CodeStatus setResponse();
//remettre tout en string et en fonction de chunked ou pas choisir la bonne fonction
dems::CodeStatus getChunk(std::vector<uint8_t> &data);
ssize_t getChunkSize(std::string &body);
dems::CodeStatus getStandardBody(std::vector<uint8_t> &data);
static void mySplit(std::vector<std::string> &dest, std::string &line, std::string const &delim);
static int checkFirstline(std::string &, dems::Context &);
};
inline std::string registerHttpResponseHooks(dems::StageManager &manager) {
manager.request().hookToEnd(99999, "HttpResponse", HttpResponse);
return "HttpResponse";
}
}
<file_sep>/module/ssl/inc/SSLConnection.hpp
/*
** EPITECH PROJECT, 2021
** zia
** File description:
** SSLConnection.hpp
*/
#pragma once
#include <openssl/ssl.h>
#include <openssl/err.h>
#include "api/Stage.hpp"
namespace zia::ssl_module {
class SSLConnection {
constexpr static char CONF_SSL_PTR[] = "SSL_ptr";
constexpr static char CONF_SSL_CTX[] = "SSL_ctx";
constexpr static char CONF_IS_SSL[] = "is_SSL";
dems::Context &_context;
std::string _certificate;
std::string _certificate_key;
SSL *_ssl;
SSL_CTX *_ssl_ctx;
bool _is_ssl;
bool initCertificate();
bool checkIsSSL();
bool initSSL_CTX();
bool initSSL();
public:
explicit SSLConnection(dems::Context &);
~SSLConnection();
bool read();
bool write();
bool isSSL() const;
void disconnect();
};
}
<file_sep>/solution/inc/server/Headers.hpp
/*
** EPITECH PROJECT, 2021
** zia
** File description:
** Html.hpp
*/
#pragma once
#include "api/Stage.hpp"
namespace zia::server {
class Headers : public dems::header::IHeaders
{
std::map<std::string, std::string> _content;
std::string _dummy;
public:
Headers();
~Headers() = default;
std::string &operator[](const std::string &headerName);
std::string const &getHeader(const std::string &headerName) const;
std::string getWholeHeaders() const;
void setHeader(const std::string &headerName, const std::string &value);
};
}<file_sep>/solution/src/default_module/ModuleContextConverter.cpp
/*
** EPITECH PROJECT, 2019
** zia
** File description:
** code status
*/
#include <iostream>
#include "default_module/ModuleContextConverter.hpp"
namespace zia::default_module {
dems::CodeStatus ModuleContextConverter(dems::Context &context)
{
std::string tmp;
auto &response = context.response;
try {
auto &firstLine = std::get<dems::header::Response>(response.firstLine);
tmp = firstLine.httpVersion + ' ' + firstLine.statusCode
+ ' ' + firstLine.message + "\r\n";
} catch (std::exception &) {
return dems::CodeStatus::HTTP_ERROR;
}
if (response.headers != nullptr) {
tmp += response.headers->getWholeHeaders();
}
tmp += "\r\n" + response.body;
context.rawData.clear();
for (auto &it : tmp)
context.rawData.push_back(it);
return dems::CodeStatus::OK;
}
}
<file_sep>/module/ssl/src/SSLConnection.cpp
/*
** EPITECH PROJECT, 2021
** zia
** File description:
** SSLConnection.cpp
*/
#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <fcntl.h>
#ifdef __linux__
#include <unistd.h>
#endif
#include "SSLConnection.hpp"
namespace zia::ssl_module {
int my_ssl_verify_peer(int, X509_STORE_CTX*) {
return 1;
}
bool SSLConnection::initCertificate()
{
// check certificate
try {
if (!_context.config.count("modules"))
return true;
auto &confModule = std::get<dems::config::ConfigObject>(_context.config["modules"].v);
if (!confModule.count("SSL"))
return true;
auto &confSSL = std::get<dems::config::ConfigObject>(confModule["SSL"].v);
if (!confSSL.count("certificate") || !confSSL.count("certificate-key"))
return true;
_certificate = std::get<std::string>(confSSL["certificate"].v);
_certificate_key = std::get<std::string>(confSSL["certificate-key"].v);
} catch (std::exception &) {
return true;
}
return false;
}
bool SSLConnection::checkIsSSL()
{
// check if the first character is uppercase letter
char c;
recv(_context.socketFd, &c, 1, MSG_PEEK);
bool is_ssl = !std::isupper(c);
return is_ssl;
}
bool SSLConnection::initSSL_CTX()
{
_ssl_ctx = SSL_CTX_new(TLSv1_2_server_method());
if (!_ssl_ctx) {
std::cerr << "Error SSL: SSL_CTX_new" << std::endl;
return true;
}
int err = SSL_CTX_set_cipher_list(_ssl_ctx, "ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
if(err != 1) {
std::cerr << "Error SSL CTX: cannot set the cipher list" << std::endl;
return true;
}
// set un callback bidon
SSL_CTX_set_verify(_ssl_ctx, SSL_VERIFY_PEER, my_ssl_verify_peer);
/* enable srtp */
err = SSL_CTX_set_tlsext_use_srtp(_ssl_ctx, "SRTP_AES128_CM_SHA1_80");
if(err != 0) {
std::cerr << "Error SSL CTX: cannot setup srtp" << std::endl;
return true;
}
err = SSL_CTX_use_certificate_file(_ssl_ctx, _certificate.c_str(), SSL_FILETYPE_PEM);
if(err != 1) {
std::cerr << "Error SSL CTX: cannot load certificate file: " << _certificate.c_str() << std::endl;
return true;
}
err = SSL_CTX_use_PrivateKey_file(_ssl_ctx, _certificate_key.c_str(), SSL_FILETYPE_PEM);
if(err != 1) {
std::cerr << "Error SSL CTX: cannot load certificate-key file: " << _certificate_key.c_str() << std::endl;
return true;
}
err = SSL_CTX_check_private_key(_ssl_ctx);
if(err != 1) {
std::cerr << "Error SSL CTX: checking the private key failed" << std::endl;
return true;
}
return false;
}
bool SSLConnection::initSSL()
{
_ssl = SSL_new(_ssl_ctx);
if (!_ssl) {
std::cerr << "Error: SSL new" << std::endl;
return true;
}
SSL_set_accept_state(_ssl);
if (!SSL_is_server(_ssl)) {
std::cerr << "Error: SSL is not server" << std::endl;
return true;
}
if (SSL_set_fd(_ssl, _context.socketFd) <= 0) {
std::cerr << "Error: SSL set fd" << std::endl;
return true;
}
int ret = SSL_accept(_ssl);
if (!ret) {
std::cerr << "Error: SSL accept" << std::endl;
return true;
} else if (ret < 0) {
char msg[1024];
switch (SSL_get_error(_ssl, ret)) {
case SSL_ERROR_WANT_WRITE:
std::cerr << "Error in init_SSL: SSL_ERROR_WANT_WRITE" << std::endl;
return true;
case SSL_ERROR_WANT_READ:
std::cerr << "Error in init_SSL: SSL_ERROR_WANT_READ" << std::endl;
return true;
case SSL_ERROR_ZERO_RETURN:
std::cerr << "Error in init_SSL: SSL_ERROR_ZERO_RETURN" << std::endl;
return true;
case SSL_ERROR_SYSCALL:
std::cerr << "Error in init_SSL: SSL_ERROR_SYSCALL: " << ret << "-" << errno<< std::endl;
return true;
case SSL_ERROR_SSL:
ERR_error_string_n(ERR_get_error(), msg, sizeof(msg));
std::cerr << "Error in init_SSL: SSL_ERROR_SSL: " << msg << std::endl;
return true;
default:
std::cerr << "Error in init_SSL: SSL Connect fatal error: " << std::endl;
return true;
}
}
// Bloque jusqu'a ce que des données entrent
char c;
recv(_context.socketFd, &c, 1, MSG_PEEK);
// Rend la socket non-bloquante
#ifdef WIN32
unsigned long mode = 1;
if (static_cast<boost>(ioctlsocket(_context.socketFd, FIONBIO, &mode)))
return true;
#else
int flags = fcntl(_context.socketFd, F_GETFL, 0);
if (flags < 0)
return true;
if (static_cast<bool>(fcntl(_context.socketFd, F_SETFL, flags | O_NONBLOCK)))
return true;
#endif
return false;
}
SSLConnection::SSLConnection(dems::Context &context):
_context(context),
_certificate(),
_certificate_key(),
_ssl(nullptr),
_ssl_ctx(nullptr)
{
if (_context.config.count(CONF_IS_SSL)
&& _context.config.count(CONF_SSL_CTX)
&& _context.config.count(CONF_SSL_PTR)) {
_is_ssl = std::get<bool>(_context.config[CONF_IS_SSL].v);
_ssl_ctx = reinterpret_cast<SSL_CTX*>(std::get<long long>(_context.config[CONF_SSL_CTX].v));
_ssl = reinterpret_cast<SSL*>(std::get<long long>(_context.config[CONF_SSL_PTR].v));
} else {
_is_ssl = checkIsSSL();
if (!_is_ssl || initCertificate() || initSSL_CTX() || initSSL()) {
_is_ssl = false;
_context.config[CONF_IS_SSL].v = false;
_context.config[CONF_SSL_CTX].v = 0ll;
_context.config[CONF_SSL_PTR].v = 0ll;
}
_context.config[CONF_IS_SSL].v = _is_ssl;
_context.config[CONF_SSL_CTX].v = reinterpret_cast<long long>(_ssl_ctx);
_context.config[CONF_SSL_PTR].v = reinterpret_cast<long long>(_ssl);
}
}
SSLConnection::~SSLConnection()
{}
bool SSLConnection::isSSL() const
{
return _is_ssl;
}
bool SSLConnection::read()
{
int readByte;
constexpr size_t BUFFER_SIZE = 256;
uint8_t buffer[BUFFER_SIZE];
// read
while ((readByte = SSL_read(_ssl, buffer, BUFFER_SIZE)) > 0) {
for (int i = 0; i < readByte; ++i) {
_context.rawData.push_back(buffer[i]);
}
}
if (readByte < 0) {
int err = SSL_get_error(_ssl, readByte);
switch (err) {
case SSL_ERROR_WANT_WRITE:
return false;
case SSL_ERROR_WANT_READ:
return false;
case SSL_ERROR_ZERO_RETURN:
case SSL_ERROR_SYSCALL:
case SSL_ERROR_SSL:
default:
return true;
}
}
return false;
}
bool SSLConnection::write()
{
auto size = static_cast<int>(_context.rawData.size() * sizeof(uint8_t));
int err = SSL_write(_ssl, _context.rawData.data(), size);
_context.rawData.clear();
if (err < 0) {
err = SSL_get_error(_ssl, err);
switch (err) {
case SSL_ERROR_WANT_WRITE:
return false;
case SSL_ERROR_WANT_READ:
return false;
case SSL_ERROR_ZERO_RETURN:
case SSL_ERROR_SYSCALL:
case SSL_ERROR_SSL:
default:
return true;
}
}
return false;
}
void SSLConnection::disconnect()
{
if (_ssl) {
SSL_shutdown(_ssl);
SSL_free(_ssl);
_ssl = nullptr;
_context.config[CONF_SSL_PTR].v = 0ll;
}
if (_ssl_ctx) {
SSL_CTX_free(_ssl_ctx);
_ssl_ctx = nullptr;
_context.config[CONF_SSL_CTX].v = 0ll;
}
if (_is_ssl) {
_is_ssl = false;
_context.config[CONF_IS_SSL].v = false;
}
}
}<file_sep>/solution/src/server/Headers.cpp
/*
** EPITECH PROJECT, 2021
** zia
** File description:
** Headers.cpp
*/
#include <iostream>
#include "server/Headers.hpp"
namespace zia::server {
Headers::Headers(): _content(), _dummy()
{}
std::string &Headers::operator[](const std::string &headerName)
{
return (_content[headerName]);
}
std::string const &Headers::getHeader(const std::string &headerName) const
{
if (_content.count(headerName))
return _content.at(headerName);
else
return _dummy;
}
std::string Headers::getWholeHeaders() const
{
std::string tmp;
for (auto & x : _content)
{
tmp += x.first;
tmp += ": ";
tmp += x.second;
tmp += "\r\n";
}
return (tmp);
}
void Headers::setHeader(const std::string &headerName,
const std::string &value)
{
//check if headerName == trucs en particuler
_content[headerName] = value;
}
}<file_sep>/solution/src/default_module/ModuleHttpRequestParser.cpp
/*
** EPITECH PROJECT, 2021
** zia
** File description:
** HttpRequestParser.cpp
*/
#include <cstdlib>
#include <cstring>
#include <variant>
#include "default_module/ModuleHttpRequestParser.hpp"
namespace zia::default_module {
dems::CodeStatus HttpRequest(dems::Context &cont)
{
HttpRequestParser request(cont);
auto ret = request.setRequest();
return ret;
}
dems::CodeStatus HttpRequestChunked(dems::Context &cont)
{
HttpRequestParser request(cont);
auto ret = request.setRequest();
if (ret != dems::CodeStatus::OK)
return (ret);
while ((ret = request.getChunk(cont.rawData)) != dems::CodeStatus::DECLINED)
if (ret == dems::CodeStatus::HTTP_ERROR)
return (dems::CodeStatus::DECLINED);
return (dems::CodeStatus::OK);
}
HttpRequestParser::HttpRequestParser(dems::Context &cont) :
_length(0), _left(0), _chunked(false), _cont(cont)
{
std::string data = "";
if (!_cont.rawData.size())
return;
for (auto &x : _cont.rawData)
data += x;
_rest = data;
zia::default_module::HttpRequestParser::mySplit(_heads, data, "\r\n");
}
HttpRequestParser::~HttpRequestParser()
{ }
dems::CodeStatus HttpRequestParser::setRequest()
{
size_t i;
std::vector<std::string> line;
if (!_heads.size())
return dems::CodeStatus::DECLINED;
if (zia::default_module::HttpRequestParser::checkFirstline(_heads[0], _cont) == 1)
return (dems::CodeStatus::HTTP_ERROR);
_heads.erase(_heads.begin());
for (i = 0; i < _heads.size(); ++i)
{
if (_heads[i] == "")
break;
zia::default_module::HttpRequestParser::mySplit(line, _heads[i], ": ");
if (line[0].compare("Content-Length"))
{
_length = std::atoi(line[1].c_str());
_left = _length;
}
if (line[0].compare("Transfer-Encoding") && line[1].compare("chunked"))
_chunked = true;
_cont.request.headers->setHeader(line[0], line[1]);
line.clear();
}
cleanRawData(++i);
if (_chunked == false)
getStandardBody(_cont.rawData);
return (dems::CodeStatus::OK);
}
void HttpRequestParser::cleanRawData(size_t i)
{
_rest.clear();
if (i <= _heads.size())
_heads.erase(_heads.begin(), _heads.begin() + i);
for (auto & line : _heads)
{
_rest += line;
_rest += "\r\n";
}
_cont.rawData.clear();
if (_length && _rest.size() > _length)
std::copy(_rest.begin(), _rest.begin() + _length, std::back_inserter(_cont.rawData));
else
std::copy(_rest.begin(), _rest.end(), std::back_inserter(_cont.rawData));
}
dems::CodeStatus HttpRequestParser::getChunk(std::vector<uint8_t> &data)
{
std::string body;
size_t chunkSize;
size_t total;
for (auto & c : data)
body += c;
total = body.substr(0, body.find_first_of("\r\n")).length();
if ((chunkSize = getChunkSize(_cont.rawData)) == 0)
{
data.clear();
return (dems::CodeStatus::DECLINED);
}
try
{
if (!body.substr(chunkSize - 2).compare("\r\n"))
return (dems::CodeStatus::HTTP_ERROR);
}
catch (const std::exception& e)
{
return (dems::CodeStatus::HTTP_ERROR);
}
_rest += body.substr(body.find_first_of("\r\n") + 2, chunkSize);
_cont.request.body = _rest;
data.erase(data.begin(), data.begin() + total + 2 + chunkSize);
return (dems::CodeStatus::OK);
}
ssize_t HttpRequestParser::getChunkSize(std::vector<uint8_t> &data)
{
std::string body;
size_t chunkSize;
for (auto & c : data)
body += c;
try
{
chunkSize = std::stoul(body.substr(0, body.find_first_of("\r\n")), nullptr, 16);
}
catch (const std::exception& e)
{
return (0);
}
if (chunkSize == 0)
return (0);
return (chunkSize);
}
dems::CodeStatus HttpRequestParser::getStandardBody(std::vector<uint8_t> &data)
{
std::string body;
for (auto & c : data)
body += c;
if (_length != 0 && _length != body.length())
return (dems::CodeStatus::DECLINED);
_cont.request.body = body;
data.clear();
return (dems::CodeStatus::OK);
}
void HttpRequestParser::mySplit(std::vector<std::string> &dest, std::string &line, std::string const &delim)
{
std::string token = "";
bool reg;
for (size_t current = 0; current < line.length(); ++current)
{
reg = false;
token += line[current];
if (line[current] == delim[0])
{
reg = true;
for (size_t j = 0; j < delim.length(); ++j)
if ((current + j) < line.length() && line[current + j] != delim[j])
reg = false;
if (reg == true)
{
dest.push_back(token.substr(0, token.length() - 1));
current += delim.length() - 1;
token.clear();
}
}
}
if (token.length() > delim.length())
dest.push_back(token);
}
int HttpRequestParser::checkFirstline(std::string &line, dems::Context &cont)
{
std::vector<std::string> Firstline;
std::vector<std::string> methods = {"GET", "HEAD", "POST", "PUT", "DELETE", "CONNECT", "OPTIONS", "TRACE"};
std::vector<std::string> versions = {"HTTP/0.9", "HTTP/1.0", "HTTP/1.1"};
std::string splitChar = " ";
zia::default_module::HttpRequestParser::mySplit(Firstline, line, splitChar);
std::get<dems::header::Request>(cont.request.firstLine).method = "";
for (auto &method : methods)
if (Firstline[0].compare(method))
{
std::get<dems::header::Request>(cont.request.firstLine).method = Firstline[0];
break ;
}
if (std::get<dems::header::Request>(cont.request.firstLine).method == "")
return (1);
std::get<dems::header::Request>(cont.request.firstLine).path = Firstline[1];
std::get<dems::header::Request>(cont.request.firstLine).httpVersion = "";
for (auto &v : versions)
if (Firstline[2].compare(v))
{
std::get<dems::header::Request>(cont.request.firstLine).httpVersion = Firstline[2];
break ;
}
if (std::get<dems::header::Request>(cont.request.firstLine).httpVersion == "")
return (1);
return (0);
}
}
<file_sep>/module/DeflateZipper/CMakeLists.txt
cmake_minimum_required(VERSION 3.1.0)
project(module_DeflateZipper DESCRIPTION "module de compression deflate pour le zia")
set(LIBRARY_NAME module_DeflateZipper)
set(CMAKE_CXX_STANDARD 17)
set(SRCS
src/ModuleDeflateZipper.cpp
)
set(HDRS
inc/ModuleDeflateZipper.hpp
)
include(${CMAKE_BINARY_DIR}/conanbuildinfo.cmake)
conan_basic_setup()
add_library(${LIBRARY_NAME} SHARED ${SRCS} ${HDRS})
target_include_directories(${LIBRARY_NAME} PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/inc)
target_link_libraries(${LIBRARY_NAME} ${CONAN_LIBS})
<file_sep>/module/ssl/CMakeLists.txt
cmake_minimum_required(VERSION 3.1.0)
project(module_ssl DESCRIPTION "module ssl pour le zia")
set(LIBRARY_NAME module_ssl)
set(CMAKE_CXX_STANDARD 17)
set(SRCS
src/ssl.cpp
src/SSLConnection.cpp)
set(HDRS
inc/SSLConnection.hpp)
set(LIBS
"-L/usr/lib -lssl -lcrypto")
add_library(${LIBRARY_NAME} SHARED ${SRCS} ${HDRS})
target_link_libraries(${LIBRARY_NAME} ${LIBS})
target_include_directories(${LIBRARY_NAME} PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/inc)
<file_sep>/solution/inc/default_module/ModuleReader.hpp
/*
** EPITECH PROJECT, 2021
** zia
** File description:
** ModuleReader.hpp
*/
#pragma once
#include "api/Stage.hpp"
namespace zia::default_module {
dems::CodeStatus ModuleReader(dems::Context &context);
inline std::string registerReaderHooks(dems::StageManager &manager) {
manager.connection().hookToEnd(100000, "DefaultReader", ModuleReader);
manager.chunks().hookToFirst(100000, "DefaultReader", ModuleReader);
return "DefaultReader";
}
}
<file_sep>/module/DeflateZipper/src/ModuleDeflateZipper.cpp
/*
** EPITECH PROJECT, 2021
** zia
** File description:
** ModuleDeflateZipper.cpp
*/
#include <cstdio>
#include <iostream>
#include <sstream>
#include <string>
#include <boost/iostreams/filtering_streambuf.hpp>
#include <boost/iostreams/copy.hpp>
#include <boost/iostreams/filter/zlib.hpp>
#include "ModuleDeflateZipper.hpp"
dems::CodeStatus ModuleDeflateZipper(dems::Context &context)
{
auto &request = context.request;
auto &response = context.response;
auto &accept_encoding = request.headers->getHeader("Accept-Encoding");
if (accept_encoding.empty() || accept_encoding.find("deflate") == accept_encoding.npos)
return dems::CodeStatus::DECLINED;
else
{
auto &content_encoding = (*response.headers)["content-encoding"];
if (!content_encoding.empty())
content_encoding += ", ";
content_encoding += "deflate";
std::stringstream compressed;
std::stringstream new_body;
new_body << response.body;
boost::iostreams::filtering_streambuf<boost::iostreams::input> out;
out.push(boost::iostreams::zlib_compressor());
out.push(new_body);
boost::iostreams::copy(out, compressed);
response.body = compressed.str();
}
return dems::CodeStatus::OK;
}
extern "C" {
std::string registerHooks(dems::StageManager &manager)
{
manager.request().hookToEnd(50000, "DeflateZipper", ModuleDeflateZipper);
return "DeflateZipper";
}
}<file_sep>/module/DeflateZipper/inc/ModuleDeflateZipper.hpp
/*
** EPITECH PROJECT, 2021
** zia
** File description:
** ModuleDeflateZipper.hpp
*/
#pragma once
#include "api/Stage.hpp"
<file_sep>/module/CMakeLists.txt
cmake_minimum_required(VERSION 3.1.0)
project(module_zia DESCRIPTION "compile tous les modules pour le zia")
add_subdirectory("${CMAKE_CURRENT_SOURCE_DIR}/php")
add_subdirectory("${CMAKE_CURRENT_SOURCE_DIR}/ssl")
add_subdirectory("${CMAKE_CURRENT_SOURCE_DIR}/tester")
add_subdirectory("${CMAKE_CURRENT_SOURCE_DIR}/DeflateZipper")
add_subdirectory("${CMAKE_CURRENT_SOURCE_DIR}/GZipper")
<file_sep>/solution/inc/default_module/ModuleContextConverter.hpp
/*
** EPITECH PROJECT, 2021
** zia
** File description:
** ModuleContextConverter.hpp
*/
#pragma once
#include "api/Stage.hpp"
namespace zia::default_module {
dems::CodeStatus ModuleContextConverter(dems::Context &context);
inline std::string registerContextConverterHooks(dems::StageManager &manager) {
manager.request().hookToEnd(100000, "ContextConverter", ModuleContextConverter);
return "ContextConverter";
}
}
<file_sep>/solution/src/default_module/ModuleReader.cpp
/*
** EPITECH PROJECT, 2021
** zia
** File description:
** ModuleReader.cpp
*/
#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <fcntl.h>
#ifdef __linux__
#include <unistd.h>
#endif
#include "default_module/ModuleReader.hpp"
namespace zia::default_module {
bool is_readable(dems::Context &context)
{
char c;
// check if the first character is uppercase letter
recv(context.socketFd, &c, 1, MSG_PEEK);
return std::isupper(c);
}
dems::CodeStatus ModuleReader(dems::Context &context)
{
constexpr size_t BUFFER_SIZE = 256;
unsigned char buffer[BUFFER_SIZE];
ssize_t readByte;
int flags;
if (!context.rawData.empty() || !is_readable(context))
return dems::CodeStatus::OK;
#ifdef __linux__
// récupère les flags du fd
flags = fcntl(context.socketFd, F_GETFL, 0);
// rend le read non-bloquant
fcntl(context.socketFd, F_SETFL, flags | O_NONBLOCK);
// lis la socket
while ((readByte = read(context.socketFd, buffer, BUFFER_SIZE))) {
if (readByte == -1 && errno == EAGAIN) {
break;
} else if (readByte == -1) {
fcntl(context.socketFd, F_SETFL, flags);
return dems::CodeStatus::HTTP_ERROR;
}
for (int i = 0; i < readByte; ++i) {
context.rawData.push_back(buffer[i]);
}
}
// remet les anciens flags
fcntl(context.socketFd, F_SETFL, flags);
#else
// active le socket en non-bloquant
flags = 1;
ioctlsocket(socket, FIONBIO, &flags);
readByte = recv(context.socketFd, buffer, BUFFER_SIZE, );
while ((readByte = read(context.socketFd, buffer, BUFFER_SIZE))) {
if (readByte < 0 && WSAGetLastError() != WSAEWOULDBLOCK)
break;
else if (readByte < 0) {
flags = 0;
ioctlsocket(socket, FIONBIO, &flags);
return dems::CodeStatus::HTTP_ERROR;
}
for (int i = 0; i < readByte; ++i)
context.rawData.push_back(buffer[i]);
}
// remet en bloquant
flags = 0;
ioctlsocket(socket, FIONBIO, &flags);
#endif
return dems::CodeStatus::OK;
}
}
<file_sep>/solution/inc/server/ConfigManager.hpp
/*
** EPITECH PROJECT, 2021
** zia
** File description:
** ConfigManager.hpp
*/
#pragma once
#include <iostream>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
#include "api/Config.hpp"
namespace zia::server {
class ConfigManager {
dems::config::Config _config;
dems::config::ConfigValue deduce_value(const std::string &);
void provideConfigObject(const boost::property_tree::ptree &node,
dems::config::ConfigObject &config);
void provideConfigArray(const boost::property_tree::ptree &node,
dems::config::ConfigArray &config);
public:
ConfigManager(const std::string &configFile);
ConfigManager();
dems::config::Config &&getConfig();
void reloadConfig(const std::string &configFile);
};
}
<file_sep>/solution/src/main.cpp
/*
** EPITECH PROJECT, 2021
** Zia
** File description:
** main.cpp
*/
#include <iostream>
#include "server/ShellServer.hpp"
zia::server::ShellServer init_shell(int ac, char **av)
{
if (ac > 1)
return zia::server::ShellServer(av[1]);
else
return zia::server::ShellServer();
}
int main(int ac, char **av)
{
signal(SIGPIPE, SIG_IGN);
if (ac > 2){
std::cerr << "Error: Invalid number of argument" << std::endl;
return EXIT_FAILURE;
}
try {
auto shell = init_shell(ac, av);
shell.run();
} catch (const std::exception &e) {
std::cerr << "Error: " << e.what() << std::endl;
return EXIT_FAILURE;
}
std::cout << "Bye." << std::endl;
return EXIT_SUCCESS;
}
<file_sep>/solution/inc/server/Request.hpp
/*
** EPITECH PROJECT, 2021
** zia
** File description:
** Request.hpp
*/
#pragma once
#include "api/Stage.hpp"
#include "server/Server.hpp"
namespace zia::server {
class Request {
zia::server::SocketPtr _socket;
dems::StageManager &_stageManager;
dems::Context _context;
void handleChunks();
public:
/* Suppression des constructeur par copie */
Request& operator=(const Request &) = delete;
Request(const Request &) = delete;
/* ctor and dtor */
explicit Request(dems::config::Config &config, dems::StageManager &stageManager, zia::server::SocketPtr &&);
~Request() = default;
/* method */
void handleRequest();
void handleDisconnect();
};
}
<file_sep>/solution/inc/dlloader/ModulesManager.hpp
/*
** EPITECH PROJECT, 2021
** zia
** File description:
** ModulesManager.hpp
*/
#pragma once
#include <unordered_map>
#include "api/AModulesManager.hpp"
#include "dlloader/IDynamicLibrary.hpp"
#include "server/ConfigManager.hpp"
typedef std::string (*RegisterFunction)(dems::StageManager &&);
namespace zia::dlloader {
class ModulesManager: public dems::AModulesManager {
using IDynamicLibraryPtr = std::unique_ptr<IDynamicLibrary>;
std::unordered_map<std::string, IDynamicLibraryPtr> _modules;
void loadBasicModules();
void loadModulesFromConfig(const dems::config::ConfigObject &modulesConfig);
void loadOneModuleFromSettings(const dems::config::ConfigObject &moduleSettings);
void loadConfig(const dems::config::Config &config);
public:
/* Suppression des constructeur par copie */
ModulesManager& operator=(const ModulesManager &) = delete;
ModulesManager(const ModulesManager &) = delete;
/* Destructor */
~ModulesManager() override = default;
/* Constructor */
ModulesManager(const dems::config::Config &);
ModulesManager();
void loadModules(const std::string &directoryPath) override;
void loadOneModule(const std::string &filePath) override;
void unloadModule(const std::string &moduleName) override;
void reloadConfig(const dems::config::Config &config);
};
}
<file_sep>/solution/src/dlloader/linux/DynamicLibrary.cpp
/*
** EPITECH PROJECT, 2021
** zia
** File description:
** DynamicLibrary.cpp
*/
/* Code Linux */
#ifdef __linux__
#include <iostream>
#include "dlloader/linux/DynamicLibrary.hpp"
namespace zia::dlloader::unix_compatibility {
DynamicLibrary::DynamicLibrary(const std::string &&library_name)
:_handle(nullptr)
{
_handle = dlopen(library_name.c_str(), RTLD_LAZY);
if (_handle == nullptr) {
throw DynamicLibraryError(dlerror());
}
}
DynamicLibrary::~DynamicLibrary()
{
if (dlclose(_handle)) {
std::cerr << dlerror() << std::endl;
}
}
void *DynamicLibrary::loadSymbol(const std::string &&symbolName)
{
void *symbol;
symbol = dlsym(_handle, symbolName.c_str());
if (symbol == nullptr) {
throw DynamicLibraryError(dlerror());
}
return symbol;
}
}
#endif // __linux__
<file_sep>/solution/inc/dlloader/windows/DynamicLibrary.hpp
/*
** EPITECH PROJECT, 2021
** zia
** File description:
** DynamicLibrary.hpp
*/
/* Code Windows */
#ifdef _WIN32
#pragma once
#include <windows.h>
#include <stdexcept>
#include "dlloader/IDynamicLibrary.hpp"
namespace zia::dlloader::windows_compatibility {
class DynamicLibrary: public IDynamicLibrary {
/* Exception lié à Dynamic Library */
class DynamicLibraryError: public std::runtime_error {
public:
explicit DynamicLibraryError(const std::string &&message)
: std::runtime_error("Error in DynamicLibrary: " + message)
{}
~DynamicLibraryError() override = default;
};
/* Attricbuts de la classe */
HMODULE *_handle;
std::string getLastErrorAsString();
public:
/* Suppression des constructeur par copie */
DynamicLibrary& operator=(const DynamicLibrary &) = delete;
DynamicLibrary(const DynamicLibrary &) = delete;
/* Méthodes de la classe */
explicit DynamicLibrary(const std::string &&);
~DynamicLibrary() override;
void *loadSymbol(const std::string &&symbolName);
};
}
#endif // _WIN32
<file_sep>/solution/src/server/Server.cpp
/*
** EPITECH PROJECT, 2021
** zia
** File description:
** Server.cpp
*/
#include <boost/bind.hpp>
#include <iostream>
#include "server/Server.hpp"
namespace zia::server {
Server::Server(dems::config::Config &config):
_io_service(),
_signals(_io_service),
_ip(),
_port(),
_endpoint(),
_acceptor(_io_service),
_threadPool(THREAD_NB),
_isRunning(false)
{
_signals.add(SIGINT);
_signals.add(SIGTERM);
#if defined(SIGQUIT)
_signals.add(SIGQUIT);
#endif // defined(SIGQUIT)
_signals.async_wait(
[this](boost::system::error_code, int) {
if (_isRunning)
stop();
});
reloadConfig(config);
}
Server::~Server()
{
std::cerr << "destroy server" << std::endl;
if (_isRunning)
stop();
}
void Server::loadDefaultConfig(dems::config::Config &config)
{
_ip = boost::asio::ip::address_v4();
_port = 8080;
config["server"].v = dems::config::ConfigObject();
auto &configServer = std::get<dems::config::ConfigObject>(config["server"].v);
configServer["ip"].v = _ip.to_string();
configServer["port"].v = static_cast<long long>(_port);
}
void Server::reloadConfig(dems::config::Config &config)
{
std::cout << "Setting up server..." << std::endl;
if (!config.count("server"))
loadDefaultConfig(config);
else
try {
auto &configServer = std::get<dems::config::ConfigObject>(config["server"].v);
if (!configServer.count("ip")) {
_ip = boost::asio::ip::address_v4();
configServer["ip"].v = _ip.to_string();
} else
try {
auto &ip = std::get<std::string>(configServer["ip"].v);
_ip = boost::asio::ip::address_v4::from_string(ip);
} catch (const std::exception &) {
_ip = boost::asio::ip::address_v4::from_string("");
}
if (!configServer.count("port")) {
_port = 8080;
configServer["port"].v = static_cast<long long>(_port);
} else
try {
_port = std::get<long long>(configServer["port"].v);
} catch (const std::exception &) {
_port = 8080;
}
} catch (const std::exception &) {
loadDefaultConfig(config);
}
boost::asio::ip::tcp::resolver resolver(_io_service);
_endpoint = *resolver.resolve({_ip, _port});
std::cout << "Server address: " << _ip << ":" << _port << std::endl;
_acceptor.close();
_acceptor.open(_endpoint.protocol());
_acceptor.set_option(boost::asio::ip::tcp::acceptor::reuse_address(true));
_acceptor.bind(_endpoint);
std::cout << "Server is set up" << std::endl;
}
void Server::waitForConnection(const Callback &cb)
{
auto socket = SocketPtr(new boost::asio::ip::tcp::socket(_io_service));
_acceptor.async_accept(*socket,
boost::bind<void>([this, socket](const Callback &callback, const boost::system::error_code &err) {
if (!_acceptor.is_open() || err)
return;
boost::asio::post(_threadPool, boost::bind(callback, socket));
waitForConnection(callback);
}, cb, boost::asio::placeholders::error));
}
void Server::run(const Callback &cb)
{
std::cout << "Running server..." << std::endl;
_isRunning = true;
_acceptor.listen();
waitForConnection(cb);
_io_thread = boost::thread([this](){
try {
_io_service.run();
} catch (std::exception &){}
});
std::cout << "Server is running" << std::endl;
}
void Server::stop()
{
std::cout << "Closing server..." << std::endl;
_isRunning = false;
_acceptor.close();
_io_service.stop();
if (_io_thread.joinable())
_io_thread.join();
std::cout << "Server is closed" << std::endl;
}
bool Server::isRunning() const
{
return _isRunning;
}
}
<file_sep>/solution/inc/default_module/ModuleWriter.hpp
/*
** EPITECH PROJECT, 2021
** zia
** File description:
** ModuleWriter.hpp
*/
#pragma once
#include "api/Stage.hpp"
namespace zia::default_module {
dems::CodeStatus ModuleWriter(dems::Context &context);
inline std::string registerWriterHooks(dems::StageManager &manager) {
manager.disconnect().hookToFirst(100000, "DefaultWriter", ModuleWriter);
return "DefaultWriter";
}
}
<file_sep>/solution/src/dlloader/ModulesManager.cpp
/*
** EPITECH PROJECT, 2021
** zia
** File description:
** ModulesManager.cpp
*/
#include <functional>
#include <experimental/filesystem>
#include "dlloader/ModulesManager.hpp"
#include "dlloader/linux/DynamicLibrary.hpp"
#include "dlloader/windows/DynamicLibrary.hpp"
#include "default_module/ModuleContextConverter.hpp"
#include "default_module/ModuleReader.hpp"
#include "default_module/ModuleWriter.hpp"
#include "default_module/ModuleDefaultPage.hpp"
#include "default_module/ModuleHttpService.hpp"
#include "default_module/ModuleHttpRequestParser.hpp"
#include "default_module/ModuleHttpResponseParser.hpp"
namespace zia::dlloader {
void ModulesManager::loadModules(const std::string &directoryPath)
{
namespace fs = std::experimental::filesystem;
for (const auto & entry: fs::directory_iterator(directoryPath))
loadOneModule(entry.path());
}
void ModulesManager::loadOneModule(const std::string &filePath)
{
if (_modules.count(filePath))
return;
#ifdef _WIN32
_modules[filePath] = IDynamicLibraryPtr(new windows_compatibility::DynamicLibrary
(std::forward<const std::string &&>(filePath)));
#else
_modules[filePath] = IDynamicLibraryPtr(new unix_compatibility::DynamicLibrary
(std::forward<const std::string &&>(filePath)));
#endif // _WIN32
auto registerFunc = reinterpret_cast<RegisterFunction>
(_modules[filePath]->loadSymbol("registerHooks"));
(*registerFunc)(std::move(getStageManager()));
}
void ModulesManager::unloadModule(const std::string &)
{}
void ModulesManager::loadBasicModules()
{
std::cout << "Loading of Basic Modules..." << std::endl;
zia::default_module::registerReaderHooks(getStageManager());
zia::default_module::registerWriterHooks(getStageManager());
zia::default_module::registerContextConverterHooks(getStageManager());
zia::default_module::registerDefaultPageHooks(getStageManager());
zia::default_module::registerHttpServiceHooks(getStageManager());
zia::default_module::registerHttpResponseHooks(getStageManager());
zia::default_module::registerHttpRequestHooks(getStageManager());
std::cout << "End of loading basic modules..." << std::endl;
}
void ModulesManager::loadOneModuleFromSettings(const dems::config::ConfigObject &moduleSettings)
{
if (moduleSettings.count("path")) {
try {
loadOneModule(std::get<std::string>(moduleSettings.at("path").v));
}
catch (const std::bad_variant_access&) {
std::cerr << "Error: can not loading this module: invalid path" << std::endl;
}
} else
std::cerr << "Error: can not loading this module: no path given" << std::endl;
}
void ModulesManager::loadModulesFromConfig(const dems::config::ConfigObject &modulesConfig)
{
std::cout << "Loading "<< modulesConfig.size() <<" module(s)..." << std::endl;
for (auto &it: modulesConfig) {
std::cout << "Loading " << it.first << "..." << std::endl;
try {
auto &moduleSettings = std::get<dems::config::ConfigObject>(it.second.v);
loadOneModuleFromSettings(moduleSettings);
}
catch (const std::bad_variant_access&) {
std::cerr << "Error: can not loading this module: no settings given" << std::endl;
}
catch (const std::exception &e){
std::cerr << "Error: can not loading this module: " << e.what() << std::endl;
}
}
std::cout << "Modules is loaded." << std::endl;
}
void ModulesManager::loadConfig(const dems::config::Config &config)
{
try {
// get modules config
auto modulesConfig = std::get<dems::config::ConfigObject>
(config.at("modules").v);
loadModulesFromConfig(modulesConfig);
}
catch (const std::bad_variant_access&) {
}
}
void ModulesManager::reloadConfig(const dems::config::Config &config)
{
std::cout << "Reloading modules..." << std::endl;
/* clear all Modules*/
getStageManager().connection().clearHooks();
getStageManager().request().clearHooks();
getStageManager().chunks().clearHooks();
getStageManager().disconnect().clearHooks();
_modules.clear();
/* load new config */
loadBasicModules();
loadConfig(config);
std::cout << "Modules is reloaded." << std::endl;
}
ModulesManager::ModulesManager(const dems::config::Config &config)
: ModulesManager()
{
loadConfig(config);
}
ModulesManager::ModulesManager()
{
loadBasicModules();
}
}
<file_sep>/solution/src/server/Request.cpp
/*
** EPITECH PROJECT, 2021
** zia
** File description:
** Request.cpp
*/
#include <iostream>
#include <boost/chrono.hpp>
#include <boost/thread/thread.hpp>
#include "server/Request.hpp"
#include "server/Headers.hpp"
#include "default_module/ModuleHttpRequestParser.hpp"
namespace zia::server {
Request::Request(dems::config::Config &config, dems::StageManager &stageManager, zia::server::SocketPtr &&socket):
_socket(std::move(socket)),
_stageManager(stageManager),
_context(dems::Context{
std::vector<uint8_t>(),
dems::header::HTTPMessage{
dems::header::Request{"", "", ""},
std::make_unique<Headers>(),
"" },
dems::header::HTTPMessage{
dems::header::Response{"", "", ""},
std::make_unique<Headers>(),
"" },
_socket->native_handle(),
config })
{
for (auto &func: _stageManager.connection().firstHooks()) {
func.second.callback(_context);
}
for (auto &func: _stageManager.connection().middleHooks()) {
func.second.callback(_context);
}
for (auto &func: _stageManager.connection().endHooks()) {
func.second.callback(_context);
}
const auto &transferEncoding = (*_context.request.headers).getHeader("Transfer-Encoding");
if (transferEncoding == "chunked")
handleChunks();
}
void Request::handleChunks()
{
std::size_t timeOut = 0;
std::size_t chunkSize = 0;
do {
for (auto &func: _stageManager.chunks().firstHooks()) {
func.second.callback(_context);
}
if (_context.rawData.empty()) {
boost::this_thread::sleep_for(boost::chrono::milliseconds(1));
if (timeOut++ >= 3000)
break;
else
continue;
}
timeOut = 0;
// get chunksize;
chunkSize = default_module::HttpRequestParser::getChunkSize(_context.rawData);
for (auto &func: _stageManager.chunks().middleHooks()) {
func.second.callback(_context);
}
for (auto &func: _stageManager.chunks().endHooks()) {
func.second.callback(_context);
}
} while (chunkSize);
}
void Request::handleRequest()
{
_context.rawData.clear();
for (auto &func: _stageManager.request().firstHooks()) {
func.second.callback(_context);
}
for (auto &func: _stageManager.request().middleHooks()) {
func.second.callback(_context);
}
for (auto &func: _stageManager.request().endHooks()) {
func.second.callback(_context);
}
}
void Request::handleDisconnect()
{
for (auto &func: _stageManager.disconnect().firstHooks()) {
func.second.callback(_context);
}
for (auto &func: _stageManager.disconnect().middleHooks()) {
func.second.callback(_context);
}
for (auto &func: _stageManager.disconnect().endHooks()) {
func.second.callback(_context);
}
}
}
<file_sep>/solution/inc/dlloader/IDynamicLibrary.hpp
/*
** EPITECH PROJECT, 2021
** zia
** File description:
** IDynamicLibrary.hpp
*/
#pragma once
#include <string>
namespace zia::dlloader {
class IDynamicLibrary {
public:
/* Méthodes de la classe */
virtual ~IDynamicLibrary() {};
virtual void *loadSymbol(const std::string &&symbolName) = 0;
};
}
<file_sep>/module/GZipper/CMakeLists.txt
cmake_minimum_required(VERSION 3.1.0)
project(module_GZipper DESCRIPTION "module de compression gzip pour le zia")
set(LIBRARY_NAME module_GZipper)
set(CMAKE_CXX_STANDARD 17)
set(SRCS
src/GZipper.cpp
)
set(HDRS
inc/GZipper.hpp
)
include(${CMAKE_BINARY_DIR}/conanbuildinfo.cmake)
conan_basic_setup()
add_library(${LIBRARY_NAME} SHARED ${SRCS} ${HDRS})
target_include_directories(${LIBRARY_NAME} PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/inc)
target_link_libraries(${LIBRARY_NAME} ${CONAN_LIBS})
<file_sep>/module/php/CMakeLists.txt
cmake_minimum_required(VERSION 3.1.0)
project(module_php DESCRIPTION "module PhP pour le zia")
set(LIBRARY_NAME module_php)
set(CMAKE_CXX_STANDARD 17)
set(SRCS
src/php.cpp
)
set(HDRS)
set(LIBS
"-lstdc++fs")
add_library(${LIBRARY_NAME} SHARED ${SRCS} ${HDRS})
target_include_directories(${LIBRARY_NAME} PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/inc)
target_link_libraries(${LIBRARY_NAME} ${LIBS})
<file_sep>/solution/src/default_module/ModuleHttpService.cpp
/*
** EPITECH PROJECT, 2021
** zia
** File description:
** ModuleHttpService.cpp
*/
#include <experimental/filesystem>
#include <iostream>
#include <fstream>
#include <streambuf>
#include "default_module/ModuleHttpService.hpp"
namespace zia::default_module {
namespace fs = std::experimental::filesystem;
dems::CodeStatus getRequestedFile(dems::Context &context, fs::path &&path)
{
std::ifstream file;
try {
file.open(path);
} catch (std::exception &) {
return dems::CodeStatus::HTTP_ERROR;
}
std::string content;
file.seekg(0, std::ios::end);
content.reserve(file.tellg());
file.seekg(0, std::ios::beg);
content.assign((std::istreambuf_iterator<char>(file)),
std::istreambuf_iterator<char>());
context.response.firstLine = dems::header::Response{"Http/1.1", "200", "OK"};
if (std::get<dems::header::Request>(context.request.firstLine).method != "HEAD")
context.response.body = content;
return dems::CodeStatus::OK;
}
dems::CodeStatus ModuleHttpService(dems::Context &context)
{
if (!context.rawData.empty()
|| !std::get<dems::header::Response>(context.response.firstLine).statusCode.empty())
return dems::CodeStatus::OK;
std::string requestFile;
fs::path path;
try {
auto &requestFirstLine = std::get<dems::header::Request>(context.request.firstLine);
requestFile = requestFirstLine.path;
auto &serverConfig = std::get<dems::config::ConfigObject>(context.config["server"].v);
fs::path root = std::get<std::string>(serverConfig["root"].v);
if (root.is_absolute()) {
path = root;
} else {
path = fs::current_path();
path /= root;
}
if (!fs::exists(path))
path = fs::current_path();
}
catch (std::exception &) {
path = fs::current_path();
}
path += requestFile;
if (!fs::is_regular_file(path)) {
path /= "index.html";
if (!fs::exists(path) || !fs::is_regular_file(path))
return dems::CodeStatus::HTTP_ERROR;
}
return getRequestedFile(context, std::move(path));
}
}
<file_sep>/solution/src/server/ConfigManager.cpp
/*
** EPITECH PROJECT, 2021
** zia
** File description:
** ConfigManager.cpp
*/
#include <cstring>
#include <fstream>
#include "server/ConfigManager.hpp"
namespace zia::server {
ConfigManager::ConfigManager(const std::string &configFile):
_config()
{
reloadConfig(configFile);
}
ConfigManager::ConfigManager():
_config()
{
_config["modules"].v = dems::config::ConfigObject();
_config["server"].v = dems::config::ConfigObject();
auto &serverConfig = std::get<dems::config::ConfigObject>(_config["server"].v);
serverConfig["ip"].v = "127.0.0.1";
serverConfig["port"].v = 8080ll;
// create default config file
std::ofstream defaultConfigFile("default_server_config.json");
defaultConfigFile << "{" << std::endl;
defaultConfigFile << "\t\"server\": {" << std::endl;
defaultConfigFile << "\t\t\"ip\": \"127.0.0.1\"," << std::endl;
defaultConfigFile << "\t\t\"port\": \"8080\"" << std::endl;
defaultConfigFile << "\t}," << std::endl;
defaultConfigFile << "\t\"modules\": {" << std::endl;
defaultConfigFile << "\t\t}" << std::endl;
defaultConfigFile << "\t}" << std::endl;
defaultConfigFile << "}" << std::endl;
}
void ConfigManager::reloadConfig(const std::string &configFile)
{
_config = dems::config::Config();
boost::property_tree::ptree root;
try {
boost::property_tree::read_json(configFile, root);
}
catch(std::exception & e) {
std::cerr << "Error: Invalid config file" << std::endl;
_config["modules"].v = dems::config::ConfigObject();
_config["server"].v = dems::config::ConfigObject();
auto &serverConfig = std::get<dems::config::ConfigObject>(_config["server"].v);
serverConfig["ip"].v = "127.0.0.1";
serverConfig["port"].v = 8080ll;
return;
}
provideConfigObject(root, _config);
}
dems::config::ConfigValue ConfigManager::deduce_value(const std::string &s)
{
const char *p;
char *end;
dems::config::ConfigValue value;
// check is long long
p = s.c_str();
value.v = std::strtoll(p, &end, 10);
if (!p)
return std::move(value);
// check is double
p = s.c_str();
value.v = std::strtod(p, &end);
if (!p)
return std::move(value);
if (s == "true") {
value.v = true;
return std::move(value);
} else if (s == "false") {
value.v = false;
return std::move(value);
} else if (s == "null") {
value.v = nullptr;
return std::move(value);
} else {
value.v = s;
return std::move(value);
}
}
void ConfigManager::provideConfigObject(const boost::property_tree::ptree &node,
dems::config::ConfigObject &config)
{
for(auto &v: node) {
if (v.second.data().empty()) {
// it's an array or a node
if (!v.second.empty() && v.second.begin()->first.empty()) {
// it's an array
config[v.first].v = dems::config::ConfigArray();
auto &configArray = std::get<dems::config::ConfigArray>
(config[v.first].v);
provideConfigArray(v.second, configArray);
} else {
// it's a node
config[v.first].v = dems::config::ConfigObject();
auto &configNode = std::get<dems::config::ConfigObject>
(config[v.first].v);
if (!v.second.empty())
provideConfigObject(v.second, configNode);
}
} else {
auto value = deduce_value(v.second.data());
config.emplace(v.first, std::move(value));
}
}
}
void ConfigManager::provideConfigArray(const boost::property_tree::ptree &node,
dems::config::ConfigArray &config)
{
for(auto &v: node) {
if (v.second.data().empty()) {
// it's an array or a node
if (!v.second.empty() && v.second.begin()->first.empty()) {
// it's an array
dems::config::ConfigValue value = {dems::config::ConfigArray()};
config.push_back(std::move(value));
auto &it = config.back();
auto &configArray = std::get<dems::config::ConfigArray>(it.v);
provideConfigArray(v.second, configArray);
} else {
// it's a node
dems::config::ConfigValue value = {dems::config::ConfigObject()};
config.push_back(std::move(value));
auto &it = config.back();
auto &configNode = std::get<dems::config::ConfigObject>(it.v);
if (!v.second.empty())
provideConfigObject(v.second, configNode);
}
} else {
auto value = deduce_value(v.second.data());
config.push_back(std::move(value));
}
}
}
dems::config::Config &&ConfigManager::getConfig()
{
return std::move(_config);
}
}
<file_sep>/solution/CMakeLists.txt
cmake_minimum_required(VERSION 3.1.0)
project("zia_solution" DESCRIPTION "Solution Zia")
set(BINARY_NAME zia)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_INCLUDE_CURRENT_DIR ON)
set(CMAKE_AUTOMOC ON)
set(CMAKE_CXX_FLAGS "-Wall -Wextra -Wcast-align -Wunused \
-Wpedantic -Wlogical-op")
set(INCLUDE inc)
set(SRCS
src/main.cpp
src/dlloader/linux/DynamicLibrary.cpp
src/dlloader/windows/DynamicLibrary.cpp
src/server/Server.cpp
src/dlloader/ModulesManager.cpp
src/server/Request.cpp
src/server/ConfigManager.cpp
src/server/ShellServer.cpp
src/server/Headers.cpp
src/default_module/ModuleReader.cpp
src/default_module/ModuleContextConverter.cpp
src/default_module/ModuleWriter.cpp
src/default_module/ModuleDefaultPage.cpp
src/default_module/ModuleHttpService.cpp
src/default_module/ModuleHttpRequestParser.cpp
src/default_module/ModuleHttpResponseParser.cpp
)
set(HDRS
inc/zia.hpp
inc/api/AModulesManager.hpp
inc/api/Heading.hpp
inc/api/Stage.hpp
inc/dlloader/IDynamicLibrary.hpp
inc/dlloader/linux/DynamicLibrary.hpp
inc/dlloader/windows/DynamicLibrary.hpp
inc/dlloader/ModulesManager.hpp
inc/server/Server.hpp
inc/server/Request.hpp
inc/server/ConfigManager.hpp
inc/server/ShellServer.hpp
inc/server/Headers.hpp
inc/default_module/ModuleReader.hpp
inc/default_module/ModuleContextConverter.hpp
inc/default_module/ModuleWriter.hpp
inc/default_module/ModuleDefaultPage.hpp
inc/default_module/ModuleHttpService.hpp
inc/default_module/ModuleHttpRequestParser.hpp
inc/default_module/ModuleHttpResponseParser.hpp
)
set(LIBS
"-ldl -lstdc++fs")
include(${CMAKE_BINARY_DIR}/conanbuildinfo.cmake)
conan_basic_setup()
message(STATUS ${SRCS_CLIENT})
message(STATUS ${SRCS_SERVER})
add_executable(${BINARY_NAME} ${SRCS} ${HDRS})
target_include_directories(${BINARY_NAME} PRIVATE ${INCLUDE})
target_link_libraries(${BINARY_NAME} ${CONAN_LIBS} ${LIBS})
<file_sep>/solution/inc/default_module/ModuleHttpRequestParser.hpp
/*
** EPITECH PROJECT, 2021
** zia
** File description:
** HttpRequestParser.hpp
*/
#pragma once
#include "api/Stage.hpp"
#include "server/Headers.hpp"
namespace zia::default_module {
dems::CodeStatus HttpRequest(dems::Context &cont);
dems::CodeStatus HttpRequestChunked(dems::Context &cont);
class HttpRequestParser
{
std::string _rest;
size_t _length;
size_t _left;
bool _chunked;
dems::Context &_cont;
std::vector<std::string> _heads;
dems::header::HTTPMessage _mess;
dems::header::Request _req;
//enlever le header du rawdata
void cleanRawData(size_t);
public:
HttpRequestParser(dems::Context &cont);
~HttpRequestParser();
dems::CodeStatus setRequest();
//remettre tout en string et en fonction de chunked ou pas choisir la bonne fonction
dems::CodeStatus getChunk(std::vector<uint8_t> &data);
static ssize_t getChunkSize(std::vector<uint8_t> &data);
dems::CodeStatus getStandardBody(std::vector<uint8_t> &data);
static void mySplit(std::vector<std::string> &dest, std::string &line, std::string const &delim);
static int checkFirstline(std::string &, dems::Context &);
};
inline std::string registerHttpRequestHooks(dems::StageManager &manager) {
manager.connection().hookToEnd(200000, "HttpRequest", HttpRequest);
manager.chunks().hookToMiddle(200000, "HttpRequestChunked", HttpRequestChunked);
return "HttpRequest";
}
}
<file_sep>/module/php/src/php.cpp
/*
** EPITECH PROJECT, 2021
** zia
** File description:
** php.c
*/
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
#include <stdio.h>
#include <experimental/filesystem>
#include "api/Stage.hpp"
#include <iostream>
#include <ctime>
#include <cstring>
#include <sstream>
#define PROG "/usr/bin/php"
extern char **environ;
std::vector<std::string> GetEnvForPhp(dems::Context &context)
{
std::vector<std::string> tmp_env(environ, environ+std::strlen((char *)environ));
std::stringstream ss;
auto &firstLine = std::get<dems::header::Request>(context.request.firstLine);
ss << "PHP_SELF=" << firstLine.path;
tmp_env.push_back(ss.str());
ss.str(std::string());
ss << "REQUEST_URI=" << firstLine.path;
tmp_env.push_back(ss.str());
ss.str(std::string());
try {
auto &confServer = std::get<dems::config::ConfigObject>(context.config["server"].v);
try {
auto &ip = std::get<std::string>(context.config["ip"].v);
ss << "SERVER_ADDR=" << ip;
tmp_env.push_back(ss.str());
ss.str(std::string());
} catch (std::exception &) {}
try {
auto &port = std::get<long long>(context.config["port"].v);
ss << "SERVER_PORT=" << port;
tmp_env.push_back(ss.str());
ss.str(std::string());
} catch (std::exception &) {}
try {
auto &root = std::get<std::string>(context.config["root"].v);
ss << "DOCUMENT_ROOT=" << root;
tmp_env.push_back(ss.str());
ss.str(std::string());
} catch (std::exception &) {}
} catch (std::exception &) {}
tmp_env.push_back("SERVER_SOFTWARE=ZIA");
tmp_env.push_back("SERVER_PROTOCOL=HTTP/1.1");
ss << "REQUEST_METHOD=" << firstLine.method;
tmp_env.push_back(ss.str());
ss.str(std::string());
ss << "REQUEST_TIME=" << std::time(0);
tmp_env.push_back(ss.str());
ss.str(std::string());
ss << "HTTP_ACCEPT=" << context.request.headers->getHeader("Accept");
tmp_env.push_back(ss.str());
ss.str(std::string());
ss << "HTTP_ACCEPT_CHARSET=" << context.request.headers->getHeader("Accept-Charset");
tmp_env.push_back(ss.str());
ss.str(std::string());
ss << "HTTP_ACCEPT_ENCODING=" << context.request.headers->getHeader("Accept-Encoding");
tmp_env.push_back(ss.str());
ss.str(std::string());
ss << "HTTP_ACCEPT_LANGUAGE=" << context.request.headers->getHeader("Accept-Language");
tmp_env.push_back(ss.str());
ss.str(std::string());
ss << "HTTP_CONNECTION=" << context.request.headers->getHeader("Connection");
tmp_env.push_back(ss.str());
ss.str(std::string());
ss << "HTTP_HOST=" << context.request.headers->getHeader("Host");
tmp_env.push_back(ss.str());
ss.str(std::string());
ss << "HTTP_REFERER=" << context.request.headers->getHeader("Referer");
tmp_env.push_back(ss.str());
ss.str(std::string());
ss << "HTTP_USER_AGENT=" << context.request.headers->getHeader("User_Agent");
tmp_env.push_back(ss.str());
ss.str(std::string());
try {
if (std::get<bool>(context.config["is_SSL"].v))
tmp_env.push_back("HTTPS=true");
}catch(std::exception&){}
return tmp_env;
}
std::string GetFilePath(dems::Context &context)
{
namespace fs = std::experimental::filesystem;
std::string requestFile;
fs::path path;
try {
auto &requestFirstLine = std::get<dems::header::Request>(context.request.firstLine);
requestFile = requestFirstLine.path;
auto &serverConfig = std::get<dems::config::ConfigObject>(context.config["server"].v);
fs::path root = std::get<std::string>(serverConfig["root"].v);
if (root.is_absolute()) {
path = root;
} else {
path = fs::current_path();
path /= root;
}
if (!fs::exists(path))
path = fs::current_path();
}
catch (std::exception &) {
path = fs::current_path();
}
path += requestFile;
if (!fs::is_regular_file(path)) {
path /= "index.html";
if (!fs::exists(path) || !fs::is_regular_file(path))
return "";
}
return path;
}
int phpCaller(dems::Context &context)
{
int pipefd[2];
pipe(pipefd);
dems::config::ConfigObject phpConf;
std::string phpPath = PROG;
std::string phpIniPath;
try {
auto &confModule = std::get<dems::config::ConfigObject>(context.config["modules"].v);
phpConf = std::get<dems::config::ConfigObject>(context.config["PHP"].v);
try {
phpPath = std::get<std::string>(context.config["EXE"].v);
} catch (std::exception &) {}
} catch (std::exception &) {}
auto file = GetFilePath(context);
char* a[] = { phpPath.data(), file.data(), nullptr };
auto tmp_env = GetEnvForPhp(context);
std::vector<char*> new_env;
new_env.reserve(tmp_env.size());
for(size_t i = 0; i < tmp_env.size(); ++i)
new_env.push_back(const_cast<char*>(tmp_env[i].c_str()));
new_env.push_back(nullptr);
int forkId = fork();
if (forkId == -1)
{
printf("Fork failed\n");
return (1);
}
else if (forkId == 0)
{
close(pipefd[0]);
dup2(pipefd[1], 1);
dup2(pipefd[1], 2);
close(pipefd[1]);
if (execve(phpPath.c_str(), a, new_env.data()) == -1)
{
std::cerr << "Execve failed: " << strerror(errno) << std::endl;
exit(1);
}
}
else
{
uint8_t buffer[1024];
close(pipefd[1]);
int size = read(pipefd[0], buffer, sizeof(buffer));
context.response.body.clear();
while (size > 0)
{
for (int i = 0; i < size; ++i)
context.response.body.push_back(buffer[i]);
size = read(pipefd[0], buffer, sizeof(buffer));
}
if (!context.response.body.empty())
context.response.firstLine = dems::header::Response{ "HTTP/1.1", "200", "OK" };
}
}
dems::CodeStatus ModulePhp(dems::Context &context)
{
phpCaller(context);
return dems::CodeStatus::OK;
}
extern "C" {
std::string registerHooks(dems::StageManager &manager)
{
manager.request().hookToMiddle(0, "php module", ModulePhp);
return "PHP";
}
}
<file_sep>/module/tester/CMakeLists.txt
cmake_minimum_required(VERSION 3.1.0)
project(module_tester DESCRIPTION "module tester pour le zia")
set(LIBRARY_NAME module_tester)
set(CMAKE_CXX_STANDARD 17)
set(SRCS
src/tester.cpp
)
set(HDRS
inc/tester.hpp
)
add_library(${LIBRARY_NAME} SHARED ${SRCS} ${HDRS})
target_include_directories(${LIBRARY_NAME} PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/inc)
<file_sep>/solution/src/default_module/ModuleDefaultPage.cpp
/*
** EPITECH PROJECT, 2021
** zia
** File description:
** ModuleDefaultPage.cpp
*/
#include "default_module/ModuleDefaultPage.hpp"
namespace zia::default_module {
dems::CodeStatus ModuleDefaultPage(dems::Context &context)
{
if (!context.rawData.empty()
|| !std::get<dems::header::Response>(context.response.firstLine).statusCode.empty())
return dems::CodeStatus::OK;
context.response.firstLine = dems::header::Response{"HTTP/1.1", "404", "Not Found"};
if (std::get<dems::header::Request>(context.request.firstLine).method != "HEAD")
context.response.body = "<head></head><body><h1>Page Not Found</h1></body>";
return dems::CodeStatus::OK;
}
}
<file_sep>/solution/inc/server/ShellServer.hpp
/*
** EPITECH PROJECT, 2021
** zia
** File description:
** ShellServer.hpp
*/
#pragma once
#include "dlloader/ModulesManager.hpp"
#include "server/Server.hpp"
#include "server/ConfigManager.hpp"
namespace zia::server {
class ShellServer {
using ShellCommand = std::vector<std::string>;
using ShellCommandFunc = std::function<void(ShellCommand &&)>;
using ShellCommandFuncMap = std::unordered_map<std::string, ShellCommandFunc>;
const ShellCommandFuncMap initShellCommandFuncMap();
void runServer(ShellCommand &&);
void stopServer(ShellCommand &&);
void reloadConfig(ShellCommand &&);
void affHelp(ShellCommand &&);
std::string _configFile;
zia::server::ConfigManager _configManager;
dems::config::Config _config;
dlloader::ModulesManager _modulesManager;
std::unique_ptr<Server> _server;
const ShellCommandFuncMap _shellCommandFuncMap;
public:
/* Suppression des constructeur par copie */
ShellServer& operator=(const ShellServer &) = delete;
ShellServer(const ShellServer &) = delete;
/* ctor */
ShellServer(std::string &&);
ShellServer();
virtual ~ShellServer() = default;
void run();
};
}
<file_sep>/module/tester/src/tester.cpp
/*
** EPITECH PROJECT, 2021
** zia
** File description:
** tester.cpp
*/
#include <iostream>
#include "tester.hpp"
extern "C" {
void registerHooks(dems::StageManager &manager)
{
(void)manager;
std::cout << "module tester is loaded" << std::endl;
}
}
<file_sep>/solution/src/dlloader/windows/DynamicLibrary.cpp
/*
** EPITECH PROJECT, 2021
** zia
** File description:
** DynamicLibrary.cpp
*/
/* Code Windows */
#ifdef _WIN32
#include <iostream>
#include "dlloader/linux/DynamicLibrary.hpp"
namespace zia::dlloader::unix_compatibility {
DynamicLibrary::getLastErrorAsString()
{
DWORD errorMessageID = ::GetLastError();
if(errorMessageID == 0)
return std::string(); //No error message has been recorded
LPSTR messageBuffer = nullptr;size_t size = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
NULL, errorMessageID, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&messageBuffer, 0, NULL);
std::string message(messageBuffer, size);
//Free the buffer.
LocalFree(messageBuffer);
return message;
}
DynamicLibrary::DynamicLibrary(const std::string &&library_name)
: _handle(nullptr)
{
_handle = LoadLibrary(library_name.c_str());
if (_handle == nullptr) {
throw DynamicLibraryError(getLastErrorAsString());
}
}
DynamicLibrary::~DynamicLibrary()
{
if (FreeLibrary(_handle)) {
std::cerr << getLastErrorAsString() << std::endl;
}
}
void *DynamicLibrary::loadSymbol(const std::string &&symbolName)
{
void *symbol;
symbol = GetProcAddress(_handle, symbolName.c_str());
if (symbol == nullptr) {
throw getLastErrorAsString(GetLastError());
}
return symbol;
}
}
#endif // _WIN32
<file_sep>/solution/inc/default_module/ModuleDefaultPage.hpp
/*
** EPITECH PROJECT, 2021
** zia
** File description:
** ModuleDefaultPage.hpp
*/
#pragma once
#include "api/Stage.hpp"
namespace zia::default_module {
dems::CodeStatus ModuleDefaultPage(dems::Context &context);
inline std::string registerDefaultPageHooks(dems::StageManager &manager) {
manager.request().hookToMiddle(100000, "DefaultPage", ModuleDefaultPage);
return "DefaultPage";
}
}
<file_sep>/module/php/inc/php.hpp
/*
** EPITECH PROJECT, 2021
** zia
** File description:
** php.hpp
*/
#pragma once
<file_sep>/solution/src/default_module/ModuleWriter.cpp
/*
** EPITECH PROJECT, 2021
** zia
** File description:
** ModuleWriter.cpp
*/
#ifdef __linux__
#include <unistd.h>
#endif // __linux__
#include "default_module/ModuleWriter.hpp"
namespace zia::default_module {
dems::CodeStatus ModuleWriter(dems::Context &context)
{
#ifdef __linux__
write(context.socketFd, context.rawData.data(), context.rawData.size());
#else
send(context.socketFd, context.rawData.data(), context.rawData.size(), 0);
#endif //__linux
return dems::CodeStatus::OK;
}
}
<file_sep>/solution/inc/server/Server.hpp
/*
** EPITECH PROJECT, 2021
** zia
** File description:
** Server.hpp
*/
#pragma once
#include <boost/asio.hpp>
#include <boost/thread.hpp>
#include "api/Config.hpp"
namespace zia::server {
using SocketPtr = boost::shared_ptr<boost::asio::ip::tcp::socket>;
using Callback = std::function<void(SocketPtr)>;
class Server {
static constexpr std::size_t THREAD_NB = 256;
/* paramètres boost pour le server Tcp */
boost::asio::io_service _io_service;
boost::thread _io_thread;
boost::asio::signal_set _signals;
boost::asio::ip::address_v4 _ip;
unsigned short _port;
boost::asio::ip::tcp::endpoint _endpoint;
boost::asio::ip::tcp::acceptor _acceptor;
boost::asio::thread_pool _threadPool;
bool _isRunning;
void waitForConnection(const Callback &cb);
void reloadConfig(dems::config::Config &);
void loadDefaultConfig(dems::config::Config &);
public:
/* Suppression des constructeur par copie */
Server& operator=(const Server &) = delete;
Server(const Server &) = delete;
/* ctor et dtor */
explicit Server(dems::config::Config &);
~Server();
void run(const Callback &cb);
void stop();
bool isRunning() const;
};
}
<file_sep>/solution/inc/default_module/ModuleHttpService.hpp
/*
** EPITECH PROJECT, 2021
** zia
** File description:
** ModuleHttpService.hpp
*/
#pragma once
#include "api/Stage.hpp"
namespace zia::default_module {
dems::CodeStatus ModuleHttpService(dems::Context &context);
inline std::string registerHttpServiceHooks(dems::StageManager &manager) {
manager.request().hookToMiddle(99999, "HttpService", ModuleHttpService);
return "HttpService";
}
}
<file_sep>/CMakeLists.txt
cmake_minimum_required(VERSION 3.1.0)
project(zia)
add_subdirectory("${PROJECT_SOURCE_DIR}/solution")
add_subdirectory("${PROJECT_SOURCE_DIR}/module")
| 01b084803be4ec8e2e9c3d826cc42b165fb674a4 | [
"CMake",
"C++"
]
| 46 | C++ | pignolr/CPP_zia_2018 | f2eedc2e04fcb7993578b87990f5eaedde2540b2 | 783b26095358fce32001f5546ee83002632dd797 |
refs/heads/master | <file_sep>import BaseQueryBuilder from './BaseQueryBuilder';
import {NotFound} from '../../Errors';
let debug = require('debug')('AgencyQueryBuilder');
export default class AgencyQueryBuilder extends BaseQueryBuilder {
constructor(app) {
super(app, 'Agency');
}
findBySlug(slug) {
this._queries.push((callback) => {
let cursor = this.Model.findOne({
slug: slug,
deletedAt: null
});
this._configurePopulationForCursor(cursor);
cursor.exec((err, agency) => {
debug('findBySlug', agency.title);
if (err) {
debug('Got error', err);
return callback(err);
}
if (!agency) {
debug('No agency found');
return callback(new NotFound('Agency not found'));
}
this._loadedModel = agency;
this.result.model = agency;
this.result.models = [agency];
this.result.agency = agency;
callback();
});
});
return this;
}
initialize() {
}
}
<file_sep>import React from 'react';
import NeighborhoodContainer from './NeighborhoodContainer';
import NeighborhoodHomeFilter from './NeighborhoodHomeFilter';
import NeighborhoodStore from '../../stores/NeighborhoodStore';
let debug = require('../../../common/debugger')('NeighborhoodHomeFilterContainer');
export default class NeighborhoodHomeFilterContainer extends NeighborhoodContainer {
render() {
debug('Render');
if (this.state.error) {
return this.handleErrorState();
}
if (NeighborhoodStore.isLoading() || !this.state.neighborhood) {
return this.handlePendingState();
}
return (
<NeighborhoodHomeFilter neighborhood={this.state.neighborhood} />
);
}
}
<file_sep>import alt from '../alt';
import _debugger from '../debugger';
import {enumerate} from '../Helpers';
export default {
generate: function generate(storeName, structure = {}) {
let debug = _debugger(storeName);
if (!structure.actions) {
throw new Error(`no actions defined for ListStore ${storeName}`);
}
if (!structure.source) {
throw new Error(`no source defined for ListStore ${storeName}`);
}
let listeners = {
handleFetchItems: structure.actions.FETCH_ITEMS,
handleUpdateItems: structure.actions.UPDATE_ITEMS,
handleRemoveItem: structure.actions.REMOVE_ITEM,
handleRemoveSuccess: structure.actions.REMOVE_SUCCESS,
handleRequestFailed: structure.actions.REQUEST_FAILED
};
if (structure.listeners) {
for (let [name, definition] of enumerate(structure.listeners)) {
listeners[name] = definition.action;
}
}
let store = class CommonListStore {
constructor() {
this.debug = debug;
this.on('bootstrap', () => {
debug('bootstrapping');
});
if (structure.listeners) {
for (let [name, definition] of enumerate(structure.listeners)) {
this[name] = definition.method.bind(this);
}
}
this.bindListeners(listeners);
this.items = [];
this.error = null;
this.removed = false;
let publicMethods = {
getItem: this.getItem
};
if (structure.publicMethods) {
for (let [name, method] of enumerate(structure.publicMethods)) {
publicMethods[name] = method.bind(this);
}
}
this.exportPublicMethods(publicMethods);
this.exportAsync(structure.source);
}
getItem(id) {
debug('getItem', id);
let { items } = this.getState();
for (let item of items) {
if (item.id === id) {
return item;
}
}
return null;
}
handleFetchItems() {
debug('handleFetchItems');
this.items = [];
this.error = null;
this.removed = false;
}
handleUpdateItems(items) {
debug('handleUpdateItems', items);
this.items = items;
this.error = null;
this.removed = false;
}
handleRemoveItem(id) {
debug('handleRemoveItem', id);
this.error = null;
if (!this.getInstance().isLoading()) {
setTimeout(() => {
this.getInstance().removeItem(id);
});
}
}
handleRemoveSuccess(id) {
debug('handleRemoveSuccess', id);
this.removed = true;
this.error = null;
this.emitChange();
}
handleRequestFailed(error) {
debug('handleRequestFailed', error);
this.error = error;
this.removed = false;
}
};
return alt.createStore(store, storeName);
}
};
<file_sep># MongoDB (Click-To-Deploy)
## Options
| Name | Zone | Server Node count | Arbiter Node count |
| :--- | :--- | :--- |
| mongodb2 | europe-west1-c | 2 | 1 |
| Server Machine type | Data Disk Type | Data diks size (GB) | Arbiter Machine Type |
| :--- | :--- | :--- |
| n1-standard-2 | Solid State Drive | 1000 | f1-micro |
[x] Enable Cloud monitoring
| Server name prefix | Arbiter name prefix | Replica set name |
| :--- | :--- | :--- |
| hhmdb | hhmdbarb | rs0 |
## After Deployment
* Remove public IPs from the Mongo nodes
* Add "project-noip" tag to the nodes
# Node configurations
Documentation variables used:
| Variable key | Description |
| :--- | :--- |
| user | username of the user you use to login to the |
| project-name | Name of the project (no spaces or special characters) |
| primary-node | name of the created mongodb node which currently acts as PRIMARY |
| secondary-node | name of the created mongodb node(s) which currently acts as SECONDARY |
| arbiter-node | name of the created mongodb node(s) which currently acts as ARBITER |
| project-db | name of the database used for project |
| project-staging-db | name of the database used for staging project |
| project-db-password | <PASSWORD> for project production db user |
| project-stg-db-password | <PASSWORD> for project <PASSWORD> |
| site-user-admin-pwd | password for mongo site admin |
| cluster-admin-pwd | password for mongo cluster admin |
| stackdriver-user-pwd | password for mongo stackdriver agent user |
| stackdriver-api-key | API key for Stackdriver |
Project values:
| Variable key | Value |
| :--- | :--- |
| user | homehapp |
| project-name | homehapp |
| primary-node | mongodb2-hhmdb-1 |
| secondary-node | mongodb2-hhmdb-2 |
| arbiter-node | mongodb2-hhmdbarb-1 |
| project-db | homehapp |
| project-staging-db | homehapp-staging |
| project-db-password | <PASSWORD> |
| project-stg-db-password | <PASSWORD> |
| site-user-admin-pwd | <PASSWORD> |
| cluster-admin-pwd | <PASSWORD> |
| stackdriver-user-pwd | <PASSWORD> |
| stackdriver-api-key | <KEY> |
* You can get the stackdriver API key by ssh:ing to any node and running:
echo $(curl -s "http://metadata.google.internal/computeMetadata/v1/project/attributes/stackdriver-agent-key" -H "Metadata-Flavor: Google")
We will do some after deployment optimizations to the Nodes following best practises from:
https://docs.mongodb.org/ecosystem/platforms/google-compute-engine/
## Execute the Deploy
After the deployment is done,
remove the public IPs form the nodes. (This ofcourse means you have to SSH to them through maintainance node)
Add the following tag to all the instances: "project-noip"
## Configure Nodes
After initial SSH connection to the node:
Add following to the end of ~/.bashrc -file
```
export LC_ALL=en_US.UTF-8
```
Logout and Login again
### Optimize Primary and Secondary nodes
Edit /etc/fstab and add the following after the "defaults" setting:
,auto,noatime,noexec
Ie.
/dev/disk/by-id/google-hhmongo-db-9kx9-data /mnt/mongodb ext4 defaults,auto,noatime,noexec 0 0
Edit /etc/mongod.conf (append to the end)
```
# Qvik config
auth = true
nohttpinterface = true
keyFile=/mnt/mongodb/.mongodb-key.pem
```
NOTE! Following command is only done in Primary node. Copy the contents to other nodes
sudo su
openssl rand -base64 741 > /mnt/mongodb/.mongodb-key.pem
exit
sudo chown mongodb:mongodb /mnt/mongodb/.mongodb-key.pem
sudo chmod 0600 /mnt/mongodb/.mongodb-key.pem
Edit /etc/security/limits.conf (append)
```
mongodb soft nofile 64000
mongodb hard nofile 64000
mongodb soft nproc 32000
mongodb hard nproc 32000
```
Edit /etc/security/limits.d/90-nproc.conf
```
mongodb soft nproc 32000
mongodb hard nproc 32000
```
sudo blockdev --setra 32 /dev/sdb
echo 'ACTION=="add", KERNEL=="sdb", ATTR{bdi/read_ahead_kb}="16"' | sudo tee -a /etc/udev/rules.d/85-mongod.rules
echo 300 | sudo tee /proc/sys/net/ipv4/tcp_keepalive_time
echo "net.ipv4.tcp_keepalive_time = 300" | sudo tee -a /etc/sysctl.conf
sudo service mongod stop
sudo service mongod start
### Configure Primary mongodb
mongo
```
use admin
db.createUser(
{
user: "siteUserAdmin",
pwd: "[<PASSWORD>]",
roles:
[
{
role: "userAdminAnyDatabase",
db: "admin"
}
]
}
)
exit
```
mongo -u siteUserAdmin -p '[site-user-admin-pwd]' --authenticationDatabase admin
mongo -u siteUserAdmin -p 'JHEofC/L+W0OyKbpo5UsSj+urvj62NlH' --authenticationDatabase admin
```
use admin
db.createUser(
{
user: "clusterAdmin",
pwd: "[<PASSWORD>]",
roles:
[
{
role: "clusterAdmin",
db: "admin"
}
]
}
)
db.createUser(
{
user: "stackdriverUser",
pwd: "[<PASSWORD>]",
roles: [
{role: "dbAdminAnyDatabase", db: "admin"},
{role: "clusterAdmin", db: "admin"},
{role: "readAnyDatabase", db: "admin"}
]
}
)
use [project-db]
db.createUser(
{
user: "[project-name]",
pwd: "[<PASSWORD>]",
roles: [ "dbAdmin", "readWrite" ]
}
)
use [project-staging-db]
db.createUser(
{
user: "[project-name]",
pwd: "[<PASSWORD>]",
roles: [ "dbAdmin", "readWrite" ]
}
)
```
### Configure Arbiter node
Edit /etc/mongod.conf (append to the end)
```
# Qvik config
auth = true
keyFile=/home/[user]/.mongodb-key.pem
```
Copy .mongodb-key.pem from Primary to /home/[user]/.mongodb-key.pem
sudo chown mongodb:mongodb /home/[user]/.mongodb-key.pem
sudo chmod 0600 /home/[user]/.mongodb-key.pem
sudo service mongod stop
sudo service mongod start
# Configure Stackdriver agent on nodes (PRIMARY, SECONDARY)
export STACKDRIVER_API_KEY=$(curl -s "http://metadata.google.internal/computeMetadata/v1/project/attributes/stackdriver-agent-key" -H "Metadata-Flavor: Google")
curl -O https://repo.stackdriver.com/stack-install.sh
sudo bash stack-install.sh --api-key=$STACKDRIVER_API_KEY
Get your API key from https://app.google.stackdriver.com/settings/apikeys
Edit /etc/default/stackdriver-agent
```
STACKDRIVER_API_KEY="[stackdriver-api-key]"
```
Edit /opt/stackdriver/collectd/etc/collectd.d/mongodb.conf
```
LoadPlugin mongodb
<Plugin "mongodb">
Host "localhost"
Port "27017"
# If you restricted access to the database, you can
# set the username and password here
User "stackdriverUser"
Password "<PASSWORD>"
# For performance/eventually consistent trade-offs you may add this line
# PreferSecondaryQuery true
</Plugin>
```
sudo service stackdriver-agent restart
# Dump staging data to production
mongodump -u homehapp -p 'hSXDuC2VX850FjfQEV+5HFYYrPfw55F0' --db homehapp-staging
mongorestore -u homehapp -p 'NPUPZZD6Qocrh2o8diDhkXO4KtkXRRmp' --db homehapp dump/homehapp-staging
mongo -u homehapp -p 'NPUPZZD6Qocrh2o8diDhkXO4KtkXRRmp' homehapp
mongo -u stackdriverUser -p 'b4LShj3XstyGZWdtLAHCYXAXmKzRZZtB' --authenticationDatabase admin<file_sep>import alt from '../../common/alt';
import HomeListActions from '../actions/HomeListActions';
import HomeListSource from '../sources/HomeListSource';
// import Cache from '../../common/Cache';
// let debug = require('../../common/debugger')('HomeListStore');
@alt.createStore
class HomeListStore {
constructor() {
this.bindListeners({
handleUpdateHomes: HomeListActions.UPDATE_HOMES,
handleFetchHomes: HomeListActions.FETCH_HOMES,
handleFetchFailed: HomeListActions.FETCH_FAILED
});
this.homes = [];
this.error = null;
this.exportPublicMethods({
getHome: this.getHome
});
this.exportAsync(HomeListSource);
}
getHome(id) {
let { homes } = this.getState();
for (let home of homes) {
if (!id) {
return home;
}
if (home.id === id) {
return home;
}
}
this.error = 'No matching id found in homes';
}
handleUpdateHomes(homes) {
this.homes = homes;
this.error = null;
}
handleFetchHomes() {
this.homes = [];
this.error = null;
}
handleFetchFailed(error) {
this.error = error;
}
}
module.exports = HomeListStore;
<file_sep>let debug = require('debug')('PageListActions');
export default require('../../common/actions/BaseListActions')
.generate('PageListActions', {
updateItem(model) {
debug('updateItem', model);
this.dispatch(model);
}
});
<file_sep>/*global window */
import React from 'react';
// import { Link } from 'react-router';
import Row from 'react-bootstrap/lib/Row';
import Nav from 'react-bootstrap/lib/Nav';
import TabbedArea from 'react-bootstrap/lib/TabbedArea';
import TabPane from 'react-bootstrap/lib/TabPane';
import SubNavigationWrapper from '../Navigation/SubNavigationWrapper';
import NavItemLink from 'react-router-bootstrap/lib/NavItemLink';
import EditDetails from './EditDetails';
import EditStory from './EditStory';
import EditModel from '../Shared/EditModel';
import ChooseAgents from './ChooseAgents';
import ViewMetadata from '../Shared/ViewMetadata';
import { setPageTitle } from '../../../common/Helpers';
// let debug = require('debug')('HomesEdit');
export default class HomesEdit extends EditModel {
static propTypes = {
home: React.PropTypes.object.isRequired,
tab: React.PropTypes.oneOfType([
React.PropTypes.number,
React.PropTypes.string
])
}
constructor(props) {
super(props);
this.tabs.agents = 4;
}
componentDidMount() {
setPageTitle([`Edit ${this.props.home.homeTitle}`, 'Homes']);
}
render() {
let openTab = this.resolveOpenTab();
return (
<SubNavigationWrapper>
<Nav sidebar>
<h2 className='navigation-title'>Edit Home</h2>
<NavItemLink to='homes'>
< Back
</NavItemLink>
</Nav>
<Row>
<h1><i className='fa fa-home'></i> Edit {this.props.home.homeTitle}</h1>
<TabbedArea defaultActiveKey={openTab}>
<TabPane eventKey={1} tab='Details'>
<EditDetails home={this.props.home} />
</TabPane>
<TabPane eventKey={2} tab='Story'>
<EditStory home={this.props.home} />
</TabPane>
<TabPane eventKey={3} tab='Metadata'>
<ViewMetadata object={this.props.home} />
</TabPane>
<TabPane eventKey={4} tab='Agents'>
<ChooseAgents home={this.props.home} />
</TabPane>
</TabbedArea>
</Row>
</SubNavigationWrapper>
);
}
}
<file_sep>/*eslint-env es6 */
import React from 'react';
// Internal components
import HomeListStore from '../../stores/HomeListStore';
import ErrorPage from '../../../common/components/Layout/ErrorPage';
// Home List
import HomeList from './HomeList';
// Story widgets
import BigImage from '../../../common/components/Widgets/BigImage';
import LargeText from '../../../common/components/Widgets/LargeText';
import { setPageTitle } from '../../../common/Helpers';
let debug = require('debug')('HomeSearch');
export default class HomeSearch extends React.Component {
static propTypes = {
params: React.PropTypes.object
}
constructor(props) {
super(props);
this.storeListener = this.onChange.bind(this);
}
state = {
error: null,
homes: HomeListStore.getState().homes
}
componentDidMount() {
HomeListStore.listen(this.storeListener);
HomeListStore.fetchItems({type: 'story'});
setPageTitle(`Our home stories`);
}
componentWillUnmount() {
HomeListStore.unlisten(this.storeListener);
}
onChange(state) {
debug('onChange', state);
this.setState({
error: state.error,
homes: state.items
});
}
handleErrorState() {
let error = {
title: 'Error loading homes!',
message: this.state.error.message
};
return (
<ErrorPage {...error} />
);
}
render() {
if (this.state.error) {
return handleErrorState();
}
let homes = this.state.homes || [];
let placeholder = {
url: 'https://res.cloudinary.com/homehapp/image/upload/v1439564093/london-view.jpg',
alt: ''
};
return (
<div id='propertyFilter'>
<BigImage gradient='green' fixed image={placeholder} proportion={0.8}>
<LargeText align='center' valign='middle' proportion={0.8}>
<div className='splash'>
<h1>Our home stories</h1>
</div>
</LargeText>
</BigImage>
<HomeList items={homes} />
</div>
);
}
}
<file_sep>import QueryBuilder from '../server/lib/QueryBuilder';
import app from "../server/app";
import should from 'should';
import expect from 'expect.js';
let debug = require('debug')('MockupData');
export default class MockupData {
constructor(app) {
this.qb = new QueryBuilder(app);
}
user = {
firstname: 'Test',
lastname: 'Testicle',
username: '<EMAIL>',
password: '<PASSWORD>',
active: true
}
home = {
slug: 'TESTHOME',
title: 'Test home',
story: {
blocks: [],
enabled: true
},
location: {
coordinates: [0, 0],
neighborhood: null
}
}
neighborhood = {
title: 'Test neighborhood',
story: {
blocks: [],
enabled: true
},
enabled: true,
area: []
}
city = {
title: 'Testoborough',
slug: 'testoborough'
}
populate = {
neighborhood: {
'location.city': {}
},
home: {
'location.neighborhood': {}
}
}
createModel(model) {
if (typeof this[model.toLowerCase()] === 'undefined') {
throw new Error(`Trying to create a mockup object '${model}' but it is not available`);
}
let data = this[model.toLowerCase()];
return new Promise((resolve, reject) => {
this.qb
.forModel(model)
.createNoMultiset(data)
.then((obj) => {
this[model] = obj;
resolve(obj);
})
.catch((err) => {
reject(err);
});
});
}
getPopulateData(model) {
if (typeof this.populate[model.toLowerCase()] !== 'undefined') {
return this.populate[model.toLowerCase()];
}
return {};
}
updateModel(model, obj, data) {
if (typeof this[model.toLowerCase()] === 'undefined') {
throw new Error(`Trying to create a mockup object '${model}' but it is not available`);
}
return new Promise((resolve, reject) => {
this.qb
.forModel(model)
.findByUuid(obj.uuid || obj.id)
.populate(this.getPopulateData(model))
.update(data)
.then((result) => {
resolve(result);
})
.catch((err) => {
reject(err);
});
});
}
verify(model, object) {
if (typeof this[model.toLowerCase()] === 'undefined') {
throw new Error(`Trying to verify a mockup object '${model}' but it is not available`);
}
let data = this[model.toLowerCase()];
this.compare(data, object);
}
/**
* Deep check for source that has to include all the target properties
*/
static compare(source, target) {
for (let key in source) {
should(target).have.property(key);
let value = source[key];
switch (typeof value) {
case 'object':
if (Array.isArray(value)) {
expect(value).to.eql(target[key], `Key "${key} failed"`);
} else {
this.compare(value, target[key]);
}
break;
default:
expect(value).to.eql(target[key]);
}
}
}
verifyHome(object) {
this.verify('Home', object);
should(object).have.property('location');
should(object.location).have.property('coordinates');
should(object.location).have.property('neighborhood');
if (object.location && object.location.neighborhood) {
this.verifyNeighborhood(object.location.neighborhood);
}
}
verifyNeighborhood(object) {
this.verify('Neighborhood', object);
should(object).have.property('location');
should(object.location).have.property('city');
if (object.location && object.location.city) {
this.verifyCity(object.location.city);
}
}
verifyCity(object) {
this.verify('City', object);
}
remove(model) {
return new Promise((resolve, reject) => {
model
.remove()
.then((data) => {
resolve(data);
});
});
}
removeAll(model, query = null) {
if (!query) {
query = {};
}
return new Promise((resolve, reject) => {
this.qb
.forModel(model)
.query(query)
.findAll()
.fetch()
.then((result) => {
if (!result.models.length) {
resolve();
}
let promises = result.models.map((home) => {
return new Promise((res, rej) => {
home
.remove()
.then(() => {
res();
});
});
});
return Promise.all(promises)
})
.then(() => {
resolve();
})
.catch((err) => {
reject(err);
});
});
}
removeHomes() {
return this.removeAll('Home');
}
removeNeighborhoods() {
return this.removeAll('Neighborhood');
}
removeCities() {
return this.removeAll('City');
}
}
<file_sep>import React from 'react';
import UserListStore from '../../stores/UserListStore';
import UsersDelete from './Delete';
import Loading from '../../../common/components/Widgets/Loading';
let debug = require('debug')('DeleteContainer');
export default class UsersDeleteContainer extends React.Component {
static propTypes = {
params: React.PropTypes.object
}
constructor(props) {
super(props);
this.storeListener = this.onChange.bind(this);
}
state = {
error: null,
user: UserListStore.getUser(this.props.params.id)
}
componentDidMount() {
UserListStore.listen(this.storeListener);
if (!UserListStore.getUser(this.props.params.id)) {
UserListStore.fetchUsers();
}
}
componentWillUnmount() {
UserListStore.unlisten(this.storeListener);
}
onChange(state) {
debug('state', state, UserListStore.getState());
this.setState({
error: UserListStore.getState().error,
user: UserListStore.getUser(this.props.params.id)
});
}
handlePendingState() {
return (
<Loading>
<h3>Loading user...</h3>
</Loading>
);
}
handleErrorState() {
return (
<div className='users-error'>
<h3>Error loading user!</h3>
<p>{this.state.error.message}</p>
</div>
);
}
render() {
if (this.state.error) {
return this.handleErrorState();
}
debug('User', this.state.user);
if (UserListStore.isLoading() || !this.state.user) {
return this.handlePendingState();
}
return (
<UsersDelete user={this.state.user} />
);
}
}
<file_sep>import path from 'path';
import Configuration from './lib/Configuration';
let Migrator = null;
let PROJECT_NAME = 'site';
const PROJECT_ROOT = path.resolve(__dirname, '..');
let debug = require('debug')('migration');
exports.run = function run(projectName, action, ...args) {
console.log('Migrate run', action, args);
PROJECT_NAME = projectName || 'site';
Configuration.load(PROJECT_ROOT, PROJECT_NAME, path.join(PROJECT_ROOT, 'config'), {}, function (configError, config) {
if (configError) {
throw configError;
}
let app = {
config: config,
PROJECT_ROOT: PROJECT_ROOT,
PROJECT_NAME: PROJECT_NAME
};
function connectToDatabase() {
return new Promise((resolve, reject) => {
debug('connectToDatabase');
if (!config.database.adapter) {
debug('no database adapter configured');
return resolve();
}
require('./lib/Database').configure(app, config.database)
.then( () => {
if (!app.db.migrationSupport) {
return Promise.reject(`No migration support in adapter ${config.database.adaptor}`);
}
let MigratorClass = app.db.getMigrator();
Migrator = new MigratorClass(app);
resolve();
})
.catch( (err) => reject(err) );
});
}
connectToDatabase()
//.then( () => setupStaticRoutes() )
.then( () => {
debug('Migration initialization flow done!');
return Migrator.execute(action, args);
})
.then( () => {
debug('Migration execution finished!');
})
.catch(err => {
console.error('Error on migration', err);
console.error(err.stack);
throw err;
});
});
};
<file_sep>import React from 'react';
import { Link } from 'react-router';
import Navbar from 'react-bootstrap/lib/Navbar';
import Nav from 'react-bootstrap/lib/Nav';
import DropdownButton from 'react-bootstrap/lib/DropdownButton';
// import NavItem from 'react-bootstrap/lib/NavItem';
import MenuItem from 'react-bootstrap/lib/MenuItem';
import CollapsibleNav from 'react-bootstrap/lib/CollapsibleNav';
import NavItemLink from 'react-router-bootstrap/lib/NavItemLink';
import MenuItemLink from 'react-router-bootstrap/lib/MenuItemLink';
class Navigation extends React.Component {
static propTypes = {
user: React.PropTypes.object
}
render() {
let userName = '';
if (this.props.user && this.props.user.displayName) {
userName = this.props.user.displayName;
}
return (
<Navbar brand={<Link to='app'>Homehapp Admin</Link>} inverse fixedTop fluid toggleNavKey={0}>
<CollapsibleNav eventKey={0}>
<Nav navbar>
<NavItemLink eventKey={1} to='homes'>Homes</NavItemLink>
<NavItemLink eventKey={2} to='neighborhoods'>Neighborhoods</NavItemLink>
<NavItemLink eventKey={3} to='pages'>Content pages</NavItemLink>
<NavItemLink eventKey={4} to='agents'>Agents</NavItemLink>
<NavItemLink eventKey={5} to='contacts'>Contact requests</NavItemLink>
<NavItemLink eventKey={6} to='users'>Users</NavItemLink>
</Nav>
<Nav navbar right>
<DropdownButton eventKey={1} title={userName}>
<MenuItemLink eventKey='1' to='app'>Profile</MenuItemLink>
<MenuItem divider />
<MenuItem eventKey='2' href='/auth/logout'>Logout</MenuItem>
</DropdownButton>
</Nav>
</CollapsibleNav>
</Navbar>
);
}
}
export default Navigation;
<file_sep>import request from '../request';
import AuthActions from '../actions/AuthActions';
let debug = require('../debugger')('AuthSource');
let AuthSource = {
fetchUser: () => {
return {
remote(/*storeState*/) {
debug('fetchUser:remote', arguments);
return request.get(`/api/auth/user`)
.then((response) => {
//debug('got response', response);
if (!response.data || !response.data.user) {
let err = new Error('Invalid response');
return Promise.reject(err);
}
return Promise.resolve(response.data.user);
})
.catch((response) => {
if (response instanceof Error) {
return Promise.reject(response);
}
if (response.status && response.status === 403) {
return Promise.resolve(null);
}
let msg = 'unexpected error';
if (response.data.error) {
msg = response.data.error;
}
let error = new Error(msg);
return Promise.reject(error);
});
},
local(/*storeState*/) {
return null;
},
success: AuthActions.updateUser,
error: AuthActions.fetchFailed,
loading: AuthActions.fetchUser
};
}
};
export default AuthSource;
<file_sep>import NeighborhoodActions from '../actions/NeighborhoodActions';
import NeighborhoodSource from '../sources/NeighborhoodSource';
import ModelStore from '../../common/stores/BaseModelStore';
export default ModelStore.generate('NeighborhoodStore', {
actions: NeighborhoodActions,
source: NeighborhoodSource,
listeners: {}
});
<file_sep>import request from '../../common/request';
import HomeListActions from '../actions/HomeListActions';
let debug = require('../../common/debugger')('HomeListSource');
let HomeListSource = {
fetchHomes: () => {
return {
remote(/*storeState*/) {
debug('fetchHomes:remote', arguments);
return request.get(`/api/homes`)
.then((response) => {
debug('got response', response);
if (!response.data || !response.data.homes) {
let err = new Error('Invalid response');
return Promise.reject(err);
}
return Promise.resolve(response.data.homes);
})
.catch((response) => {
if (response instanceof Error) {
return Promise.reject(response);
} else {
let msg = 'unexpected error';
if (response.data.error) {
msg = response.data.error;
}
return Promise.reject(new Error(msg));
}
return Promise.reject(response);
});
},
local(/*storeState, slug*/) {
return null;
},
success: HomeListActions.updateHomes,
error: HomeListActions.fetchFailed,
loading: HomeListActions.fetchHomes
};
}
};
export default HomeListSource;
<file_sep>'use strict';
import should from 'should';
import expect from 'expect.js';
import request from 'supertest';
import testUtils from '../utils';
import MockupData from '../../MockupData';
let app = null;
let debug = require('debug')('Neighborhood API paths');
let mockup = null;
describe('Neighborhood API paths', () => {
before((done) => {
testUtils.createApp((err, appInstance) => {
app = appInstance;
mockup = new MockupData(app);
mockup.removeAll('Neighborhood')
.then(() => {
return mockup.removeAll('City');
})
.then(() => {
done(err);
})
.catch((err) => {
console.error('Failed to delete neighborhoods');
done(err);
});
});
});
let body = null;
let home = null;
let city = null;
let neighborhood = null;
it('Should respond to /api/neighborhoods with correct structure', (done) => {
request(app)
.get('/api/neighborhoods')
.expect(200)
.end((err, res) => {
should.not.exist(err);
body = res.body;
done();
});
});
it('Response of /api/neighborhoods should have the correct structure', (done) => {
should(body).have.property('status', 'ok');
should(body).have.property('items');
should(body.items).be.instanceof(Array);
should(body.items).be.empty;
done();
});
it('Response of /api/neighborhoods should have the mockup neighborhood', (done) => {
mockup.createModel('Neighborhood')
.then((rval) => {
neighborhood = rval;
// Create the city
return mockup.createModel('City')
})
.then((rval) => {
city = rval;
// Create the home
return mockup.createModel('Home')
})
.then((rval) => {
home = rval;
request(app)
.get('/api/neighborhoods')
.expect(200)
.end((err, res) => {
should.not.exist(err);
body = res.body;
should(body).have.property('status', 'ok');
should(body).have.property('items');
should(body.items).be.instanceof(Array);
should(body.items).not.be.empty;
expect(body.items.length).to.eql(1);
body.items.map((item) => {
mockup.verify('Neighborhood', item);
});
done();
});
})
.catch((err) => {
done(err);
});
});
it('Response of /api/neighborhood/:city/:slug does not give the object before neighborhood city is saved', (done) => {
let urls = [
`/neighborhoods/${city.slug}/${neighborhood.slug}`,
`/api/neighborhoods/${city.slug}/${neighborhood.slug}`
];
let promises = urls.map((url) => {
request(app)
.get(url)
.expect(404)
.end((err, res) => {
console.log(res.body);
should.not.exist(err, `'${url}' should not exist yet`);
});
});
Promise.all(promises)
.then(() => {
done();
});
});
it('Response of /api/neighborhoods/:city/:slug gives the correct object', (done) => {
let url = `/api/neighborhoods/${city.slug}/${neighborhood.slug}`;
mockup
.updateModel('Neighborhood', neighborhood, {
location: {
city: city.id
}
})
.then((model) => {
request(app)
.get(url)
.expect(200)
.end((err, res) => {
body = res.body;
should.not.exist(err, `'${url}' should exist`);
should(body).have.property('status', 'ok');
should(body).have.property('neighborhood');
mockup.verifyNeighborhood(body.neighborhood);
done();
});
})
.catch((err) => {
done(err);
});
});
it('Should not exist any homes in the newly created neighborhood', (done) => {
let url = `/api/neighborhoods/${city.slug}/${neighborhood.slug}/homes`;
request(app)
.get(url)
.expect(200)
.end((err, res) => {
should.not.exist(err, `'${url}' should exist`);
should(res.body).have.property('status', 'ok');
should(res.body).have.property('homes');
should(res.body.homes).be.instanceof(Array);
expect(res.body.homes.length).to.eql(0);
done();
});
});
it('Check the URL space to verify that the newly created neighborhood is available', (done) => {
let urls = [
`/neighborhoods/${city.slug}/${neighborhood.slug}`,
`/neighborhoods/${city.slug}/${neighborhood.slug}/homes`
];
let promises = urls.map((url) => {
return new Promise((resolve, reject) => {
request(app)
.get(url)
.expect(200)
.end((err, res) => {
should.not.exist(err, `URL '${url}' should exist`);
resolve();
});
});
});
Promise.all(promises)
.then(() => {
done();
});
});
it('Should have a home in the neighborhood listing', (done) => {
mockup
.updateModel('Home', home, {
location: {
neighborhood: neighborhood.id
}
})
.then((rval) => {
let url = `/api/neighborhoods/${city.slug}/${neighborhood.slug}/homes`;
request(app)
.get(url)
.expect(200)
.end((err, res) => {
should.not.exist(err, `URL '${url}' should exist`);
should(res.body).have.property('homes');
expect(res.body.homes.length).to.eql(1);
console.log('res.body', res.body.homes[0].slug, home.slug);
expect(res.body.homes[0].slug).to.eql(home.slug);
done();
});
})
.catch((err) => {
done(err);
});
});
it('Neighborhood should not be listed when it is not enabled', (done) => {
let url = `/api/neighborhoods/${city.slug}`;
mockup
.updateModel('Neighborhood', neighborhood, {
enabled: false
})
.then((rval) => {
neighborhood = rval;
request(app)
.get(url)
.expect(200)
.end((err, res) => {
should.not.exist(err, `'${url}' should exist`);
expect(res.body.items.length).to.be(0);
done();
});
})
.catch((err) => {
done(err);
});;
});
it('Neighborhood can be deleted', (done) => {
mockup
.remove(neighborhood)
.then(() => {
done();
})
.catch((err) => {
done(err);
});
});
it('Check the URL space to verify that the deleted neighborhood is no longer available', (done) => {
let urls = [
`/neighborhoods/${city.slug}/${neighborhood.slug}`,
`/neighborhoods/${city.slug}/${neighborhood.slug}/homes`
];
let promises = urls.map((url) => {
return new Promise((resolve, reject) => {
request(app)
.get(url)
.expect(404)
.end((err, res) => {
should.not.exist(err, `URL '${url}' should not exist anymore`);
body = res.text;
resolve();
});
});
});
Promise.all(promises)
.then(() => {
done();
});
});
});
<file_sep>import QueryBuilder from '../../../lib/QueryBuilder';
import NeighborhoodsAPI from '../../../api/NeighborhoodsAPI';
let debug = require('debug')('app');
exports.registerRoutes = (app) => {
const QB = new QueryBuilder(app);
let api = new NeighborhoodsAPI(app, QB);
app.get('/api/neighborhoods', function(req, res, next) {
api.listNeighborhoods(req, res, next)
.then((neighborhoods) => {
res.json({
status: 'ok',
items: neighborhoods
});
})
.catch(next);
});
app.get('/api/neighborhoods/:city', function(req, res, next) {
api.listNeighborhoodsByCity(req, res, next)
.then((neighborhoods) => {
res.json({
status: 'ok',
items: neighborhoods
});
})
.catch(next);
});
app.get('/api/neighborhoods/:city/:neighborhood', function(req, res, next) {
api.getNeighborhoodBySlug(req, res, next)
.then((neighborhood) => {
res.json({
status: 'ok',
neighborhood: neighborhood
});
})
.catch(() => {
res.status(404);
next();
});
});
app.get('/api/neighborhoods/:city/:neighborhood/homes', function(req, res, next) {
QB
.forModel('City')
.findBySlug(req.params.city)
.parseRequestArguments(req)
.fetch()
.then((resultCity) => {
let city = resultCity.city;
QB
.forModel('Neighborhood')
.findBySlug(req.params.neighborhood)
.fetch()
.then((resultNeighborhood) => {
debug('Neighborhood by slug', resultNeighborhood);
let neighborhood = resultNeighborhood.models[0];
if (String(neighborhood.location.city) !== String(city.id)) {
throw new Error('City mismatch');
}
neighborhood.location.city = city;
QB
.forModel('Home')
.findByNeighborhood(neighborhood)
.parseRequestArguments(req)
.sort({
'metadata.score': -1
})
.fetch()
.then((resultHome) => {
let homes = [];
for (let home of resultHome.models) {
home.location.neighborhood = neighborhood;
homes.push(home);
}
res.json({
status: 'ok',
homes: homes
});
})
.catch(next);
})
.catch(next);
})
.catch(next);
});
};
<file_sep>import QueryBuilder from '../../../lib/QueryBuilder';
import {BadRequest} from '../../../lib/Errors';
let debug = require('debug')('/api/agents');
exports.registerRoutes = (app) => {
const QB = new QueryBuilder(app);
let updateAgent = function updateAgent(uuid, data) {
debug('Data', data);
return QB
.forModel('Agent')
.findByUuid(uuid)
.updateNoMultiset(data);
};
let prepareAgentModelForReturn = function prepareAgentModelForReturn(model) {
let agent = model.toJSON();
agent.realPhoneNumber = model._realPhoneNumber;
agent.realPhoneNumberType = model._realPhoneNumberType;
return agent;
};
app.get('/api/agents', app.authenticatedRoute, function(req, res, next) {
debug('API fetch agents');
debug('req.query', req.query);
QB
.forModel('Agent')
.parseRequestArguments(req)
.findAll()
.fetch()
.then((result) => {
let agents = result.models.map((model) => {
return prepareAgentModelForReturn(model);
});
res.json({
status: 'ok',
items: agents,
agents: agents // TODO: Remove me once the clients stops behaving weirdly
});
})
.catch(next);
});
let validateInput = function validateInput(data) {
if (!data.firstname) {
throw new Error('Missing firstname');
}
if (!data.lastname) {
throw new Error('Missing lastname');
}
// if (!data.email) {
// throw new Error('Missing email address');
// }
// if (!data.phone) {
// throw new Error('Missing phone number');
// }
return true;
};
app.post('/api/agents', app.authenticatedRoute, function(req, res, next) {
debug('API update agent with uuid', req.params.uuid);
//debug('req.body', req.body);
let data = req.body.agent;
try {
validateInput(data);
} catch (error) {
debug('Validate failed', error);
return next(new BadRequest(error.message));
}
QB
.forModel('Agent')
.createNoMultiset(data)
.then((model) => {
if (model._realPhoneNumber && !model.contactNumber) {
app.twilio.registerNumberForAgent(model)
.then((results) => {
let updateData = {
contactNumber: results.phoneNumber,
_contactNumberSid: results.sid
};
updateAgent(model.uuid, updateData)
.then((updModel) => {
res.json({
status: 'ok', agent: prepareAgentModelForReturn(updModel)
});
})
.catch(next);
})
.catch(next);
} else {
res.json({
status: 'ok', agent: model
});
}
})
.catch((error) => {
debug('Create failed', error);
return next(new BadRequest(error.message));
});
});
app.get('/api/agents/:uuid', app.authenticatedRoute, function(req, res, next) {
debug('API fetch agent with uuid', req.params.uuid);
debug('req.query', req.query);
if (req.params.uuid === 'blank') {
debug('Create a blank agent');
let model = new (QB.forModel('Agent')).Model();
debug('created a blank', model);
res.json({
status: 'ok',
agent: model
});
return null;
}
QB
.forModel('Agent')
.findByUuid(req.params.uuid)
.fetch()
.then((result) => {
res.json({
status: 'ok', agent: prepareAgentModelForReturn(result.model)
});
})
.catch(next);
});
app.put('/api/agents/:uuid', app.authenticatedRoute, function(req, res, next) {
debug('API update agent with uuid', req.params.uuid);
debug('req.body', req.body);
let data = req.body.agent;
try {
validateInput(data);
} catch (error) {
return next(new BadRequest(error.message));
}
updateAgent(req.params.uuid, data)
.then((model) => {
if (model._realPhoneNumber && !model.contactNumber) {
app.twilio.registerNumberForAgent(model)
.then((results) => {
let updateData = {
contactNumber: results.phoneNumber,
_contactNumberSid: results.sid
};
updateAgent(model.uuid, updateData)
.then((updModel) => {
res.json({
status: 'ok', agent: prepareAgentModelForReturn(updModel)
});
})
.catch(next);
})
.catch(next);
} else {
res.json({
status: 'ok', agent: model
});
}
})
.catch(next);
});
// app.patch('/api/agents/:uuid', app.authenticatedRoute, function(req, res, next) {
// debug('API update agent with uuid', req.params.uuid);
// //debug('req.body', req.body);
//
// let data = req.body.agent;
//
// updateAgent(req.params.uuid, data)
// .then((model) => {
// res.json({
// status: 'ok', agent: model
// });
// })
// .catch(next);
// });
app.delete('/api/agents/:uuid', app.authenticatedRoute, function(req, res, next) {
QB
.forModel('Agent')
.findByUuid(req.params.uuid)
.remove()
.then((result) => {
app.twilio.unregisterNumberForAgent(result.model)
.then((removeResults) => {
debug('removeResults', removeResults);
QB
.forModel('Agent')
.findById(result.model._id)
.updateNoMultiset({
contactNumber: '',
_contactNumberSid: null
})
.then((model) => {
res.json({
status: 'ok', agent: prepareAgentModelForReturn(model)
});
})
.catch(next);
})
.catch(next);
})
.catch(next);
});
app.delete('/api/agents/:uuid/contactnumber', app.authenticatedRoute, function(req, res, next) {
QB
.forModel('Agent')
.findByUuid(req.params.uuid)
.fetch()
.then((result) => {
app.twilio.unregisterNumberForAgent(result.model)
.then((removeResults) => {
debug('removeResults', removeResults);
QB
.forModel('Agent')
.findByUuid(req.params.uuid)
.updateNoMultiset({
contactNumber: '',
_contactNumberSid: null
})
.then((model) => {
res.json({
status: 'ok', agent: prepareAgentModelForReturn(model)
});
})
.catch(next);
})
.catch(next);
})
.catch(next);
});
};
<file_sep>import QueryBuilder from '../../../lib/QueryBuilder';
let debug = require('debug')('/migrations/thumbnails');
exports.registerRoutes = (app) => {
const QB = new QueryBuilder(app);
app.get('/migrations/thumbnails', app.authenticatedRoute, function(req, res, next) {
QB
.forModel('Home')
.parseRequestArguments(req)
//.populate(populate)
.select('uuid images story')
.findAll()
.fetch()
.then((result) => {
let payload = {
token: req.csrfToken(),
homes: result.modelsJson
};
app.getLocals(req, res, {
includeClient: true,
bodyClass: 'adminMigrate',
csrfToken: req.csrfToken(),
includeJS: [
'//code.jquery.com/jquery-1.11.3.min.js',
`${app.revisionedStaticPath}/js/migrators/thumbnailer.js`
],
payload: payload
})
.then((locals) => {
//locals.layout = null;
res.render('migration/thumbnails', locals);
});
})
.catch(next);
});
};
<file_sep>import fs from 'fs';
import path from 'path';
import util from 'util';
import uuid from 'uuid';
import { merge } from '../../clients/common/Helpers';
let semver = require('semver');
exports.randomString = function randomString(len = 8) {
let chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz';
let randomStr = '';
let cc = 0;
while (cc < len) {
cc++;
var rnum = Math.floor(Math.random() * chars.length);
randomStr += chars.substring(rnum, rnum + 1);
}
return randomStr;
};
let typeOf = exports.typeOf = function typeOf(input) {
return ({}).toString.call(input).slice(8, -1).toLowerCase();
};
exports.toTitleCase = function toTitleCase(str) {
return str.replace(/\w\S*/g, (txt) => {
return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
});
};
exports.clone = function clone(input) {
let output = input,
type = typeOf(input),
index, size;
if (type === 'array') {
output = [];
size = input.length;
for (index = 0; index < size; ++index) {
output[index] = clone(input[index]);
}
} else if (type === 'object') {
output = {};
for (index in input) {
output[index] = clone(input[index]);
}
}
return output;
};
exports.walkDirSync = function walkDirSync(dir, opts={}) {
if (opts.ext) {
if (!util.isArray(opts.ext)) {
opts.ext = [opts.ext];
}
}
let results = [];
fs.readdirSync(dir).forEach((file) => {
file = path.join(dir, file);
let stat = fs.statSync(file);
if (stat.isDirectory()) {
results = results.concat(walkDirSync(file, opts));
} else {
if (opts.ext && !(opts.ext.indexOf(path.extname(file)) !== -1)) {
return;
}
results.push(file);
}
});
return results;
};
exports.listDirSync = function listDirSync(srcpath) {
return fs.readdirSync(srcpath).filter(function(file) {
return fs.statSync(path.join(srcpath, file)).isDirectory();
});
};
exports.merge = function merge(...argv) {
let target = Object.assign({}, argv.shift());
argv.forEach((a) => {
for (let [key, value] of enumerate(a)) {
if (a.hasOwnProperty(key)) {
if (require('util').isArray(target[key])) {
target[key] = target[key].concat(value);
} else if (typeof target[key] === 'object'
&& typeof target[key] !== 'undefined'
&& target[key] !== null)
{
target[key] = merge(target[key], value);
} else {
target[key] = value;
}
}
}
});
return target;
};
exports.getEnvironmentValue = function getEnvironmentValue(envKey, defaultValue) {
let value = defaultValue;
if (process.env[envKey]) {
value = process.env[envKey];
}
return value;
};
exports.generateUUID = function generateUUID() {
return uuid.v4();
};
exports.pick = function pick (obj, keys) {
let res = {};
let i = 0;
if (typeof obj !== 'object') {
return res;
}
if (typeof keys === 'string') {
if (keys in obj) {
res[keys] = obj[keys];
}
return res;
}
let len = keys.length;
while (len--) {
var key = keys[i++];
if (key in obj) {
res[key] = obj[key];
}
}
return res;
};
exports.union = function union(x, y) {
var obj = {};
for (var i = x.length - 1; i >= 0; --i) {
obj[x[i]] = x[i];
}
for (var z = y.length - 1; x >= 0; --z) {
obj[y[z]] = y[i];
}
var res = [];
for (var k in obj) {
if (obj.hasOwnProperty(k)) {
res.push(obj[k]);
}
}
return res;
};
exports.isEmpty = function isEmpty(val) {
if (val === null) {
return true;
}
if (require('util').isArray(val) || val.constructor === String) {
return !val.length;
}
return false;
};
exports.getId = function getId(obj) {
if (typeof obj === 'string' || !obj) {
return obj;
}
if (typeof obj.uuid === 'string') {
return obj.uuid;
}
if (typeof obj.id === 'string') {
return obj.id;
}
return obj;
};
let enumerate = exports.enumerate = function* enumerate(obj) {
for (let key of Object.keys(obj)) {
yield [key, obj[key]];
}
};
let defaultVersion = '1.0.1';
// Strip the model from Mongoose features and normalize UUIDs
exports.exposeHome = function exposeHome(home, version = null, currentUser = null) {
if (!home) {
return null;
}
home = JSON.parse(JSON.stringify(home));
if (!version || semver.satisfies(version, '~0.0')) {
version = defaultVersion;
}
switch (true) {
case semver.satisfies(version, '<=1.0.0'):
home.createdBy = exports.getId(home.createdBy);
home.updatedBy = exports.getId(home.updatedBy);
break;
case semver.satisfies(version, '<=1.0.1'):
default:
home.createdBy = exports.exposeUser(home.createdBy, version, currentUser);
home.updatedBy = exports.getId(home.updatedBy);
}
return home;
};
// Strip the model from
exports.exposeUser = function exposeUser(user, version = null, currentUser = null) {
if (!version || semver.satisfies(version, '~0.0')) {
version = defaultVersion;
}
let rval = user;
if (!rval) {
return null;
}
if (rval.publicData) {
rval = rval.publicData;
}
if (typeof rval.toJSON === 'function') {
rval = rval.toJSON();
} else {
rval = merge({}, rval);
}
// if (currentUser && (user.id === currentUser.id || user.id === currentUser.uuid)) {
// rval.contact = user.contact;
// } else if (rval.contact && rval.contact.address) {
// rval.contact.address.street = '';
// rval.contact.address.apartment = '';
// }
delete rval.username;
delete rval.metadata;
delete rval.name;
delete rval.rname;
delete rval.deviceId;
delete rval.active;
delete rval.createdAt;
delete rval.createdAtTS;
delete rval.updatedAt;
delete rval.updatedAtTS;
delete rval.updatedBy;
delete rval.createdBy;
if (rval.displayName === user.username || rval.displayName === user.email) {
rval.displayName = '';
}
return rval;
};
<file_sep>export default require('../../common/actions/BaseListActions')
.generate('NeighborhoodListActions', {
updateItem(model) {
this.dispatch(model);
}
});
<file_sep>import QueryBuilder from '../../lib/QueryBuilder';
import { setLastMod, initMetadata } from '../../../clients/common/Helpers';
import HomesAPI from '../../api/HomesAPI';
let debug = require('debug')('/homes');
exports.registerRoutes = (app) => {
const QB = new QueryBuilder(app);
let api = new HomesAPI(app, QB);
app.get('/home', function(req, res) {
debug('Redirecting the GUI call to deprecated /home');
return res.redirect(301, '/homes');
});
app.get('/home/:slug', function(req, res) {
debug('Redirecting the GUI call to deprecated /home/:slug');
return res.redirect(301, `/homes/${req.params.slug}`);
});
app.get('/homes', function(req, res, next) {
debug('GET /homes');
api.listHomes(req, res, next)
.then((homes) => {
initMetadata(res);
res.locals.page = {
title: 'Homes',
description: 'Our exclusive homes'
};
res.locals.data.HomeListStore = {
items: homes
};
setLastMod(homes, res);
next();
})
.catch(next);
});
app.get('/search', function(req, res, next) {
debug('GET /search');
api.listHomes(req, res, next)
.then((homes) => {
initMetadata(res);
res.locals.page = {
title: 'Homes',
description: 'Our exclusive homes'
};
res.locals.data.HomeListStore = {
items: homes
};
next();
})
.catch(next);
});
app.get('/search/:type', function(req, res, next) {
debug(`GET /search/${req.params.type}`);
let types = ['buy', 'rent', 'story', 'stories'];
let titles = {
buy: 'Homes for sale',
rent: 'Homes for rent',
story: 'Our storified homes',
stories: 'Our storified homes'
};
if (types.indexOf(req.params.type) === -1) {
return next();
}
api.listHomes(req, res, next)
.then((homes) => {
res.locals.page = {
title: titles[req.params.type],
description: titles[req.params.type]
};
res.locals.data.HomeListStore = {
items: homes
};
next();
})
.catch(next);
});
let returnHomeBySlug = (req, res, next) => {
let neighborhood = null;
let slug = req.params.slug;
api.getHome(req, res, next)
.then((home) => {
if (home.location.neighborhood) {
neighborhood = home.location.neighborhood;
}
res.locals.data.title = [home.homeTitle];
let images = [];
if (home.images) {
for (let i = 0; i < home.images.length; i++) {
let src = home.images[i].url || home.images[i].src;
if (src) {
images.push(src.replace(/upload\//, 'upload/c_fill,h_526,w_1000/g_south_west,l_homehapp-logo-horizontal-with-shadow,x_20,y_20/'));
}
}
}
initMetadata(res);
let title = [home.homeTitle];
let description = home.description || title.join('; ');
if (description.length > 200) {
description = description.substr(0, 200) + '…';
}
res.locals.openGraph['og:image'] = images.concat(res.locals.openGraph['og:image']);
res.locals.page = {
title: title.join(' | '),
description: description
};
setLastMod([home, neighborhood], res);
api.populateCityForHome(home)
.then(() => {
res.locals.data.HomeStore = {
home: home
};
next();
});
})
.catch(() => {
debug('Home not found by slug, try if the identifier was its UUID', slug);
QB
.forModel('Home')
.findByUuid(slug)
.fetch()
.then((result) => {
let regexp = new RegExp(req.params.slug.replace(/\-/, '\\-'));
let href = req.url.replace(regexp, result.model.slug);
debug('Redirecting the UUID based call to slug based URL', href);
return res.redirect(301, href);
})
.catch(() => {
res.status(404);
next();
});
})
.catch(() => {
res.status(404);
next();
});
};
app.get('/homes/:slug', function(req, res, next) {
debug(`GET /homes/${req.params.slug}`);
returnHomeBySlug(req, res, next);
});
app.get('/homes/:slug/:type(details|story|contact)', function(req, res, next) {
returnHomeBySlug(req, res, next);
});
};
<file_sep>import React from 'react';
//import HomeListStore from '../../stores/HomeListStore';
import HomeStore from '../../stores/HomeStore';
import HomesCreate from './Create';
import Loading from '../../../common/components/Widgets/Loading';
export default class HomesCreateContainer extends React.Component {
constructor(props) {
super(props);
this.storeListener = this.onChange.bind(this);
}
state = {
error: null,
home: null
}
componentDidMount() {
HomeStore.listen(this.storeListener);
}
componentWillUnmount() {
HomeStore.unlisten(this.storeListener);
}
onChange(/*state*/) {
this.setState({
error: HomeStore.getState().error,
home: HomeStore.getState().home
});
}
handlePendingState() {
return (
<Loading>
<h3>Creating a new home...</h3>
</Loading>
);
}
handleErrorState() {
return (
<div className='homes-error'>
<h3>Error creating a new home!</h3>
<p>{this.state.error.message}</p>
</div>
);
}
render() {
if (this.state.error) {
return this.handleErrorState();
}
if (HomeStore.isLoading()) {
return this.handlePendingState();
}
return (
<HomesCreate home={this.state.home} />
);
}
}
<file_sep>import React from 'react';
import NeighborhoodListStore from '../../stores/NeighborhoodListStore';
import NeighborhoodsEdit from './Edit';
import Loading from '../../../common/components/Widgets/Loading';
class NeighborhoodsEditContainer extends React.Component {
static propTypes = {
params: React.PropTypes.object
}
constructor(props) {
super(props);
this.storeListener = this.onChange.bind(this);
}
state = {
error: null,
neighborhood: NeighborhoodListStore.getItem(this.props.params.id)
}
componentDidMount() {
NeighborhoodListStore.listen(this.storeListener);
if (!NeighborhoodListStore.getItem(this.props.params.id)) {
NeighborhoodListStore.fetchAllItems();
}
}
componentWillUnmount() {
NeighborhoodListStore.unlisten(this.storeListener);
}
onChange(/*state*/) {
this.setState({
error: NeighborhoodListStore.getState().error,
neighborhood: NeighborhoodListStore.getItem(this.props.params.id)
});
}
handlePendingState() {
return (
<Loading>
<h3>Loading neighborhoods...</h3>
</Loading>
);
}
handleErrorState() {
return (
<div className='neighborhoods-error'>
<h3>Error loading neighborhoods!</h3>
<p>{this.state.error.message}</p>
</div>
);
}
render() {
if (this.state.error) {
return this.handleErrorState();
}
if (NeighborhoodListStore.isLoading() || !this.state.neighborhood) {
return this.handlePendingState();
}
let tab = this.props.params.tab || 1;
return (
<NeighborhoodsEdit neighborhood={this.state.neighborhood} tab={tab} />
);
}
}
export default NeighborhoodsEditContainer;
<file_sep>"use strict";
module.exports = function (projectRoot) {
var config = {
logging: {
Console: {
level: "debug"
}
}
};
return config;
};
<file_sep>import React from 'react';
import Table from 'react-bootstrap/lib/Table';
import InputWidget from '../Widgets/Input';
import Button from 'react-bootstrap/lib/Button';
import ApplicationStore from '../../../common/stores/ApplicationStore';
import {setCDNUrlProperties} from '../../../common/Helpers';
let debug = require('../../../common/debugger')('ImageList');
function getFullImageUrl(url) {
if (!url.match(/^http/)) {
url = `${ApplicationStore.getState().config.cloudinary.baseUrl}${url}`;
}
return url;
}
export default class ImageList extends React.Component {
static propTypes = {
images: React.PropTypes.array,
onRemove: React.PropTypes.func.isRequired,
onChange: React.PropTypes.func.isRequired,
storageKey: React.PropTypes.string,
label: React.PropTypes.string,
max: React.PropTypes.number,
types: React.PropTypes.object
};
static defaultProps = {
images: [],
storageKey: 'images',
label: null,
max: Infinity,
types: null
};
getValue() {
debug('getValue for ImageList', this.props.images);
return this.props.images;
}
getTypes(image) {
if (!this.props.types) {
return null;
}
// JS event for the type changing
let typeChange = (event) => {
image.tag = event.target.value || null;
this.props.onChange(event);
debug('set type', image);
};
// Create an array map
let types = [];
for (let k in this.props.types) {
types.push({value: k, label: this.props.types[k]});
}
// Sort the types alphabetically
types.sort((a, b) => {
if (a.label > b.label) {
return 1;
}
if (a.label > b.label) {
return -1;
}
return 0;
});
return (
<InputWidget
type='select'
defaultValue={image.tag}
onChange={typeChange}
>
<option value=''>Select type...</option>
{
types.map((type, index) => {
return (
<option value={type.value} key={`imagelist-type-${index}`}>{type.label}</option>
);
})
}
</InputWidget>
);
}
render() {
// Get the last images of the stack when the max quantity is defined
if (this.props.images.length > this.props.max) {
let d = this.props.images.length - this.props.max;
this.props.images = this.props.images.splice(d, this.props.max);
}
return (
<Table>
<thead>
<tr>
<th>Thumbnail</th>
<th>Description</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{
this.props.images.map((image, idx) => {
if (!image.url) {
return null;
}
let imageUrl = getFullImageUrl(image.url);
let thumbnailUrl = setCDNUrlProperties(imageUrl, {
w: 80,
h: 80,
c: 'fill'
});
// Always use a web compatible image suffix
if (!thumbnailUrl.match(/\.(png|jpe?g|gif)$/i)) {
thumbnailUrl = thumbnailUrl.replace(/\.[a-z0-9]{2,4}$/, '.jpg');
}
let altChange = (event) => {
image.alt = event.target.value;
this.props.onChange(event);
};
return (
<tr key={`homeImage-${idx}`}>
<td>
<a href={imageUrl} target='_blank'>
<img src={thumbnailUrl} alt={image.alt} />
</a>
</td>
<td>
<InputWidget
type='text'
ref='alt'
placeholder='(description, recommended strongly)'
defaultValue={image.alt}
onChange={altChange}
/>
{this.getTypes(image)}
</td>
<td>
<Button
bsStyle='danger'
bsSize='small'
onClick={() => this.props.onRemove(idx, this.props.storageKey)}>
Remove
</Button>
</td>
</tr>
);
})
}
</tbody>
</Table>
);
}
}
<file_sep>import alt from '../../common/alt';
let debug = require('../../common/debugger')('UserListActions');
@alt.createActions
class UserListActions {
updateUsers(users) {
this.dispatch(users);
}
fetchUsers(skipCache) {
debug('fetchUsers', skipCache);
this.dispatch(skipCache);
}
fetchFailed(error) {
debug('fetchFailed', error);
this.dispatch(error);
}
}
module.exports = UserListActions;
<file_sep>import React from 'react';
import UserListStore from '../../stores/UserListStore';
import UsersIndex from './index';
import Loading from '../../../common/components/Widgets/Loading';
let debug = require('../../../common/debugger')('UsersIndexContainer');
class UsersIndexContainer extends React.Component {
static propTypes = {
params: React.PropTypes.object
}
constructor(props) {
super(props);
this.storeListener = this.onChange.bind(this);
}
state = {
error: null,
users: UserListStore.getState().users
}
componentDidMount() {
debug('componentDidMount');
UserListStore.listen(this.storeListener);
UserListStore.fetchUsers();
}
componentWillUnmount() {
UserListStore.unlisten(this.storeListener);
}
onChange(state) {
debug('onChange', state);
this.setState({
users: UserListStore.getState().users
});
}
handlePendingState() {
return (
<Loading>
<h3>Loading users...</h3>
</Loading>
);
}
handleErrorState() {
return (
<div className='users-error'>
<h3>Error loading users!</h3>
<p>{this.state.error.message}</p>
</div>
);
}
render() {
if (this.state.error) {
return this.handleErrorState();
}
if (UserListStore.isLoading() || !this.state.users) {
return this.handlePendingState();
}
return (
<UsersIndex users={this.state.users} />
);
}
}
export default UsersIndexContainer;
<file_sep>exports.configure = function(app, config = {}) {
app.use((req, res, next) => {
req.originalUrl = req.url;
let re = new RegExp(config.pathRegexp);
req.version = 0;
if (req.url.match(re)) {
let version = re.exec(req.url)[1];
if (version) {
req.version = parseInt(version);
}
req.url = req.url.replace(/\/v[0-9]/, '');
}
if (req.headers && req.headers[config.headerKey.toLowerCase()]) {
req.version = req.headers[config.headerKey.toLowerCase()];
}
next();
});
return Promise.resolve();
};
<file_sep>import Helpers from '../../Helpers';
import alt from '../../alt';
let debug = require('../../debugger')('UploadAreaUtils');
@alt.createActions
class UploadActions {
updateUpload(data) {
this.dispatch(data);
}
}
exports.UploadActions = UploadActions;
@alt.createStore
class UploadStore {
constructor() {
this.bindListeners({
handleUpdateUpload: UploadActions.UPDATE_UPLOAD
});
this.uploads = {};
}
handleUpdateUpload(data) {
if (!this.uploads[data.instanceId]) {
this.uploads[data.instanceId] = {};
}
if (!this.uploads[data.instanceId][data.id]) {
this.uploads[data.instanceId][data.id] = {};
}
this.uploads[data.instanceId][data.id] = Helpers.merge(this.uploads[data.instanceId][data.id], data.data);
debug('this.uploads', this.uploads);
}
}
exports.UploadStore = UploadStore;
<file_sep>import React from 'react';
import { Link } from 'react-router';
import cookie from 'react-cookie';
let debug = require('debug')('CookiePolicy');
export default class CookiePolicy extends React.Component {
constructor() {
super();
this.approveCookieUsage = this.approveCookieUsage.bind(this);
this.cookieName = 'acceptcookies';
}
state = {
approved: cookie.load('approved')
}
componentDidMount() {
let node = React.findDOMNode(this.refs.close);
if (node) {
debug('Bind click & touch');
node.addEventListener('click', this.approveCookieUsage, true);
node.addEventListener('touch', this.approveCookieUsage, true);
}
}
approveCookieUsage() {
debug('approveCookieUsage');
let dt = (new Date()).toISOString();
cookie.save(this.cookieName, dt);
this.setState({
approved: dt
});
}
render() {
if (cookie.load(this.cookieName)) {
debug('Cookie saved, do not display the consent screen');
return null;
}
return (
<div id='cookiePolicy'>
<p>
<span className='close' ref='close'>×</span>
This site uses cookies. By continuing to browse the site you are
agreeing to our use of cookies. <Link to='page' params={{slug: 'privacy'}}>Find out more ›</Link>
</p>
</div>
);
}
}
<file_sep>import {merge} from '../Helpers';
class BaseAdapter {
constructor(app, config, defaults = {}) {
this.app = app;
this._schemas = {};
this.config = merge(defaults, config);
this.migrationSupport = false;
}
}
module.exports = BaseAdapter;
<file_sep>import BaseQueryBuilder from './BaseQueryBuilder';
import {NotFound} from '../../Errors';
let debug = require('debug')('AgentQueryBuilder');
export default class AgentQueryBuilder extends BaseQueryBuilder {
constructor(app) {
super(app, 'Agent');
}
initialize() {
}
findBySlug(slug) {
this._queries.push((callback) => {
let cursor = this.Model.findOne({
slug: slug,
deletedAt: null
});
this._configurePopulationForCursor(cursor);
cursor.exec((err, model) => {
if (err) {
return callback(err);
}
if (!model) {
debug(`No agents found with slug '${slug}'`);
return callback(new NotFound('agent not found'));
}
this.result.agent = model;
this.result.agentJson = model.toJSON();
this.result.model = model;
this.result.models = [model];
this._loadedModel = model;
callback();
});
});
return this;
}
findByNeighborhood(neighborhood) {
let query = {
deletedAt: null,
'location.neighborhood': neighborhood
};
this._queries.push((callback) => {
let cursor = this.Model.find(query);
this._configurePopulationForCursor(cursor);
cursor.exec((err, agents) => {
if (err) {
debug('Got error', err);
return callback(err);
}
if (!agents) {
agents = [];
}
this.result.models = agents;
this.result.agents = agents;
callback();
});
});
return this;
}
findByUuid(uuid) {
this._queries.push((callback) => {
let cursor = this.Model.findOne({
uuid: uuid,
deletedAt: null
});
this._configurePopulationForCursor(cursor);
cursor.exec((err, model) => {
if (err) {
return callback(err);
}
if (!model) {
return callback(new NotFound('agent not found'));
}
this.result.model = model;
this.result.models = [model];
this.result.agent = model;
this.result.agents = [model];
this.result.agentJson = model.toJSON();
this._loadedModel = model;
callback();
});
});
return this;
}
}
<file_sep>import React from 'react';
import { merge } from '../../Helpers';
import classNames from 'classnames';
import Image from './Image';
import BigBlock from './BigBlock';
export default class BigImage extends BigBlock {
static propTypes = {
image: React.PropTypes.object.isRequired,
fixed: React.PropTypes.bool,
gradient: React.PropTypes.string,
proportion: React.PropTypes.number,
aspectRatio: React.PropTypes.number,
children: React.PropTypes.oneOfType([
React.PropTypes.null,
React.PropTypes.array,
React.PropTypes.object
]),
align: React.PropTypes.string,
valign: React.PropTypes.string,
className: React.PropTypes.string
};
static defaultProps = {
fixed: false,
proportion: null,
aspectRatio: null,
align: 'center',
valign: 'middle',
className: null,
zIndex: -10
};
getRelativeHeight(width, height) {
if (!this.props.aspectRatio) {
return height;
}
return Math.round(width / this.props.aspectRatio);
}
getBigImage(image) {
let width = 1920;
let height = this.getRelativeHeight(width, 800);
return (
<Image {...image} className='show-for-large' width={width} height={height} />
);
}
getMediumImage(image) {
let width = 1000;
let height = this.getRelativeHeight(width, 800);
return (
<Image {...image} className='show-for-medium' width={width} height={height} />
);
}
getSmallImage(image) {
let width = 600;
let height = this.getRelativeHeight(width, 400);
return (
<Image {...image} className='show-for-small' width={width} height={height} />
);
}
render() {
let classes = ['widget', 'big-image'];
let classesText = ['image-text'];
let textProps = {};
if (this.props.fixed) {
classes.push('fixed');
}
if (this.props.className) {
classes.push(this.props.className);
}
let image = merge({}, this.props.image);
image.mode = 'fill';
let props = {
'data-gradient': this.props.gradient,
'data-align': this.props.align,
'data-valign': this.props.valign
};
if (this.props.proportion) {
props['data-proportion'] = this.props.proportion;
textProps['data-proportion'] = this.props.proportion;
}
if (this.props.aspectRatio) {
props['data-aspect-ratio'] = this.props.aspectRatio;
textProps['data-aspect-ratio'] = this.props.aspectRatio;
classes.push('aspect-ratio');
classesText.push('aspect-ratio');
} else {
classes.push('full-height');
classesText.push('full-height');
}
props.className = classNames(classes);
let author = null;
if (this.props.image.author) {
author = (<div className='image-author'>© {this.props.image.author}</div>);
}
let x = this.props.image.align || this.props.align;
let y = this.props.image.valign || this.props.valign;
y = y.replace(/middle/, 'center');
let imageStyle = {
backgroundPosition: `${x} ${y}`
};
return (
<div {...props}>
<div className='image-content' ref='container' style={imageStyle}>
{this.getBigImage(image)}
{this.getMediumImage(image)}
{this.getSmallImage(image)}
</div>
{author}
<div className={classesText.join(' ')} {...textProps}>
{this.props.children}
</div>
</div>
);
}
}
<file_sep>import alt from '../alt';
import _debugger from '../debugger';
import {merge} from '../Helpers';
export default {
generate: function generate(name, definitions = {}) {
let debug = _debugger(name);
let actions = merge({
updateItems(items) {
debug('updateItems', items);
this.dispatch(items);
},
fetchItems(query) {
debug('fetchItems', query);
this.dispatch(query);
},
removeItem(id) {
debug('removeItem', id);
this.dispatch(id);
},
removeSuccess(id) {
debug('removeSuccess', id);
this.dispatch(id);
},
requestFailed(error) {
debug('requestFailed', error);
this.dispatch(error);
}
}, definitions);
return alt.createActions(actions);
}
};
<file_sep>/*global window */
import React from 'react';
// import { Link } from 'react-router';
import Row from 'react-bootstrap/lib/Row';
import Nav from 'react-bootstrap/lib/Nav';
import TabbedArea from 'react-bootstrap/lib/TabbedArea';
import TabPane from 'react-bootstrap/lib/TabPane';
import SubNavigationWrapper from '../Navigation/SubNavigationWrapper';
import NavItemLink from 'react-router-bootstrap/lib/NavItemLink';
import EditDetails from './EditDetails';
import EditModel from '../Shared/EditModel';
import ViewMetadata from '../Shared/ViewMetadata';
import { setPageTitle } from '../../../common/Helpers';
// let debug = require('debug')('UsersEdit');
export default class UsersEdit extends EditModel {
static propTypes = {
user: React.PropTypes.object.isRequired,
tab: React.PropTypes.oneOfType([
React.PropTypes.number,
React.PropTypes.string
])
}
constructor(props) {
super(props);
}
componentDidMount() {
setPageTitle([this.props.user.rname, 'Users']);
}
render() {
let openTab = this.resolveOpenTab();
return (
<SubNavigationWrapper>
<Nav sidebar>
<h2 className='navigation-title'>Edit User</h2>
<NavItemLink to='users'>
< Back
</NavItemLink>
</Nav>
<Row>
<h1><i className='fa fa-user'></i> Edit {this.props.user.displayName}</h1>
<TabbedArea defaultActiveKey={openTab}>
<TabPane eventKey={1} tab='Details'>
<EditDetails user={this.props.user} />
</TabPane>
<TabPane eventKey={3} tab='Metadata'>
<ViewMetadata object={this.props.user} />
</TabPane>
</TabbedArea>
</Row>
</SubNavigationWrapper>
);
}
}
<file_sep>// let debug = require('debug')('Server root');
exports.registerRoutes = (app) => {
app.get('*', app.authenticatedRoute, function(req, res, next) {
return next();
});
};
<file_sep>import React from 'react';
import { Link } from 'react-router';
import Row from 'react-bootstrap/lib/Row';
import Col from 'react-bootstrap/lib/Col';
import Panel from 'react-bootstrap/lib/Panel';
import InputWidget from '../Widgets/Input';
import Button from 'react-bootstrap/lib/Button';
import Well from 'react-bootstrap/lib/Well';
import UserStore from '../../stores/UserStore';
import UserActions from '../../actions/UserActions';
import { merge, createNotification } from '../../../common/Helpers';
import EditDetails from '../Shared/EditDetails';
let debug = require('../../../common/debugger')('UsersEditDetails');
export default class UsersEditDetails extends EditDetails {
static propTypes = {
user: React.PropTypes.object.isRequired,
context: React.PropTypes.object
}
static contextTypes = {
router: React.PropTypes.func
}
constructor(props) {
super(props);
this.storeListener = this.onUserStoreChange.bind(this);
debug('Constructor', this);
}
state = {
error: null
}
componentDidMount() {
UserStore.listen(this.storeListener);
}
componentWillUnmount() {
UserStore.unlisten(this.storeListener);
}
onUserStoreChange(state) {
debug('onUserStoreChange', state);
this.setState(state);
}
onFormChange(/*event*/) {
// let {type, target} = event;
// TODO: Validation could be done here
//debug('onFormChange', event, type, target);
//this.props.user.facilities = this.refs.facilities.getValue().split("\n");
}
verifyPassword(userProps) {
let password = this.refs.password.getValue();
// User exists, no password change requested
if (userProps.id && !password) {
return true;
}
if (password !== this.refs.password2.getValue()) {
createNotification({
message: 'Password mismatch',
type: 'danger',
duration: 5
});
return false;
}
if (password.length < 8) {
createNotification({
message: 'Please use at least 8 characters for your password',
type: 'danger',
duration: 5
});
return false;
}
userProps.password = <PASSWORD>;
return true;
}
onSave() {
debug('Save');
let id = null;
if (this.props.user) {
id = this.props.user.id;
}
let userProps = {
id: id,
firstname: this.refs.firstname.getValue(),
lastname: this.refs.lastname.getValue(),
username: this.refs.username.getValue(),
email: this.refs.email.getValue().toLowerCase()
};
if (!this.verifyPassword(userProps)) {
debug('Password verification failed');
return null;
}
debug('userProps', userProps);
this.saveUser(userProps);
}
saveUser(userProps) {
debug('saveUser', userProps);
if (userProps.id) {
return UserActions.updateItem(userProps);
}
return UserActions.createItem(userProps);
}
onCancel() {
React.findDOMNode(this.refs.userDetailsForm).reset();
}
render() {
this.handleErrorState();
if (UserStore.isLoading()) {
this.handlePendingState();
return null;
}
this.handleRenderState();
let user = merge({
firstname: null,
lastname: null,
email: null,
password: <PASSWORD>,
username: null
}, this.props.user || {});
let deleteLink = null;
if (this.props.user) {
deleteLink = (<Link to='userDelete' params={{id: this.props.user.id}} className='pull-right btn btn-danger btn-preview'>Delete</Link>);
}
debug('Render', user);
//debug('Neighborhood of this user', this.props.userLocation.neighborhood);
return (
<Row>
<form name='userDetails' ref='userDetailsForm' method='POST'>
<Col md={10} sm={10}>
<Panel header='Common'>
<InputWidget
type='text'
ref='firstname'
label='Firstname'
placeholder='Firstname'
required
defaultValue={user.firstname}
onChange={this.onFormChange.bind(this)}
/>
<InputWidget
type='text'
ref='lastname'
label='Lastname'
placeholder='Lastname'
required
defaultValue={user.lastname}
onChange={this.onFormChange.bind(this)}
/>
<InputWidget
type='email'
ref='email'
label='Email'
placeholder='<EMAIL>'
required
defaultValue={user.email}
onChange={this.onFormChange.bind(this)}
/>
</Panel>
<Panel header='Login credentials'>
<InputWidget
type='email'
ref='username'
label='Username'
placeholder='<EMAIL>'
defaultValue={user.username}
onChange={this.onFormChange.bind(this)}
/>
<InputWidget
type='password'
ref='password'
label='Password'
placeholder='<PASSWORD>'
onChange={this.onFormChange.bind(this)}
/>
<InputWidget
type='password'
ref='password2'
label='Retype the password'
placeholder='Retype your password'
onChange={this.onFormChange.bind(this)}
/>
</Panel>
<Well>
<Row>
<Col md={6}>
<Button bsStyle='success' accessKey='s' onClick={this.onSave.bind(this)}>Save</Button>
</Col>
<Col md={6} pullRight>
{deleteLink}
</Col>
</Row>
</Well>
</Col>
</form>
</Row>
);
}
}
<file_sep>import alt from '../alt';
import _debugger from '../debugger';
import {enumerate} from '../Helpers';
export default {
generate: function generate(storeName, structure = {}) {
let debug = _debugger(storeName);
if (!structure.actions) {
throw new Error(`no actions defined for ModelStore ${storeName}`);
}
if (!structure.source) {
throw new Error(`no source defined for ModelStore ${storeName}`);
}
let listeners = {
handleCreateItem: structure.actions.CREATE_ITEM,
handleCreateSuccess: structure.actions.CREATE_SUCCESS,
handleUpdateItem: structure.actions.UPDATE_ITEM,
handleUpdateSuccess: structure.actions.UPDATE_SUCCESS,
handleRequestFailed: structure.actions.REQUEST_FAILED
};
if (structure.listeners) {
for (let [name, definition] of enumerate(structure.listeners)) {
listeners[name] = definition.action;
}
}
let store = class CommonModelStore {
constructor() {
this.debug = debug;
this.on('bootstrap', () => {
debug('bootstrapping');
});
if (structure.listeners) {
for (let [name, definition] of enumerate(structure.listeners)) {
this[name] = definition.method.bind(this);
}
}
this.bindListeners(listeners);
this.model = null;
this.created = false;
this.error = null;
if (structure.publicMethods) {
let publicMethods = {};
for (let [name, method] of enumerate(structure.publicMethods)) {
publicMethods[name] = method.bind(this);
}
this.exportPublicMethods(publicMethods);
}
this.exportAsync(structure.source);
}
handleCreateItem(model) {
debug('handleCreateItem', model);
this.error = null;
this.model = null;
if (!this.getInstance().isLoading()) {
setTimeout(() => {
this.getInstance().createItem(model);
});
}
}
handleCreateSuccess(model) {
debug('handleCreateSuccess', model);
this.error = null;
this.model = model;
this.created = true;
}
handleUpdateItem(model) {
debug('handleUpdateItem', model);
this.error = null;
this.created = false;
if (!this.getInstance().isLoading()) {
setTimeout(() => {
this.getInstance().updateItem(model);
});
}
}
handleUpdateSuccess(model) {
debug('handleUpdateSuccess', model);
this.error = null;
this.model = model;
}
handleRequestFailed(error) {
debug('handleRequestFailed', error);
this.error = error;
this.created = false;
}
};
return alt.createStore(store, storeName);
}
};
<file_sep>import React from 'react';
let debug = require('debug')('BaseWidget');
export default class BaseWidget extends React.Component {
static validate(props) {
debug('Default validate used, overriding is mandatory');
return false;
}
static isNumeric(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
renderWidget() {
debug('Default render widget, please override');
return null;
}
render() {
try {
if (typeof this.constructor.validate !== 'function') {
debug('Validate method missing', this);
} else {
this.constructor.validate(this.props);
}
} catch (err) {
debug('Validation failed', this.props, err.message);
return null;
}
return this.renderWidget();
}
}
<file_sep>import CityListActions from '../actions/CityListActions';
import CityListSource from '../sources/CityListSource';
import ListStore from '../../common/stores/BaseListStore';
// let debug = require('debug')('CityListStore');
export default ListStore.generate('CityListStore', {
actions: CityListActions,
source: CityListSource,
listeners: {}
});
<file_sep>import React from 'react';
// import ContentBlock from './ContentBlock';
export default class Loading extends React.Component {
static propTypes = {
children: React.PropTypes.oneOfType([
React.PropTypes.null,
React.PropTypes.object,
React.PropTypes.array
])
};
render() {
return null;
// return (
// <ContentBlock className='widget loading padded centered'>
// <img src="data:image/svg+xml;base64,<KEY> alt="..." />
// {this.props.children}
// </ContentBlock>
// );
}
}
<file_sep>import request from '../../common/request';
import HomeActions from '../actions/HomeActions';
let debug = require('../../common/debugger')('HomeSource');
let HomeSource = {
createItem: function () {
return {
remote(storeState, data) {
debug('createItem:remote', arguments, data);
let postData = {
home: data
};
let disallowed = ['uuid', 'id', '_id'];
for (let key of disallowed) {
if (typeof data[key] !== 'undefined') {
delete data[key];
}
}
return request.post(`/api/homes`, postData)
.then((response) => {
debug('got response', response);
if (!response.data || response.data.status !== 'ok') {
let err = new Error(response.data.error || 'Invalid response');
return Promise.reject(err);
}
return Promise.resolve(response.data.home);
})
.catch((response) => {
if (response instanceof Error) {
return Promise.reject(response);
} else {
let msg = 'unexpected error';
if (response.data && response.data.error) {
msg = response.data.error;
}
return Promise.reject(new Error(msg));
}
return Promise.reject(response);
});
},
local(storeState, data) {
debug('createItem:local', arguments, data);
return null;
},
shouldFetch(state) {
debug('createItem:shouldFetch', arguments, state);
return true;
},
success: HomeActions.createSuccess,
error: HomeActions.requestFailed,
loading: HomeActions.createItem
};
},
updateItem: function () {
return {
remote(storeState, data) {
debug('updateItem:remote', arguments, data);
let putData = {
home: data
};
let id = data.uuid || data.id;
delete data.id;
delete data.uuid;
return request.put(`/api/homes/${id}`, putData)
.then((response) => {
debug('got response', response);
if (!response.data || response.data.status !== 'ok') {
let err = new Error(response.data.error || 'Invalid response');
return Promise.reject(err);
}
return Promise.resolve(response.data.home);
})
.catch((response) => {
if (response instanceof Error) {
return Promise.reject(response);
} else {
let msg = 'unexpected error';
if (response.data && response.data.error) {
msg = response.data.error;
}
return Promise.reject(new Error(msg));
}
return Promise.reject(response);
});
},
local(storeState, data) {
debug('createItem:local', arguments, data);
return null;
},
shouldFetch(state) {
debug('createItem:shouldFetch', arguments, state);
return true;
},
success: HomeActions.updateSuccess,
error: HomeActions.requestFailed,
loading: HomeActions.updateItem
};
},
deleteItem: function() {
debug('deleteItem', arguments);
return {
remote(storeState, data) {
debug('deleteItem:remote', arguments, data);
let id = data.id;
return request.delete(`/api/homes/${id}`)
.then((response) => {
debug('Got response when deleting', response);
if (!response.data || response.data.status !== 'deleted') {
let err = new Error(response.data.error || 'Invalid response');
return Promise.reject(err);
}
return Promise.resolve(null);
})
.catch((response) => {
if (response instanceof Error) {
return Promise.reject(response);
} else {
let msg = 'unexpected error';
if (response.data && response.data.error) {
msg = response.data.error;
}
return Promise.reject(new Error(msg));
}
return Promise.reject(response);
});
},
local(storeState, data) {
debug('deleteItem:local', arguments, data);
},
shouldFetch() {
debug('deleteItem should always fetch from the server side');
return true;
},
success: HomeActions.deleteSuccess,
error: HomeActions.requestFailed,
loading: HomeActions.deleteItem
};
}
};
export default HomeSource;
<file_sep>import React from 'react';
import Row from 'react-bootstrap/lib/Row';
import Col from 'react-bootstrap/lib/Col';
import Panel from 'react-bootstrap/lib/Panel';
import Well from 'react-bootstrap/lib/Well';
import Button from 'react-bootstrap/lib/Button';
import InputWidget from '../Widgets/Input';
let debug = require('../../../common/debugger')('ViewMetadata');
export default class ViewMetadata extends React.Component {
static propTypes = {
object: React.PropTypes.object.isRequired,
store: React.PropTypes.object,
actions: React.PropTypes.object
}
static defaultProps = {
store: null,
actions: null
}
constructor() {
super();
this.storeListener = this.onStoreChange.bind(this);
}
componentDidMount() {
if (this.props.store && typeof this.props.store.listen === 'function') {
this.props.store.listen(this.storeListener);
} else {
debug('No store provided for this object, use readonly mode');
}
}
componentWillUnmount() {
if (this.props.store && typeof this.props.store.unlisten === 'function') {
this.props.store.unlisten(this.storeListener);
}
}
onStoreChange(store) {
this.setState(store);
}
createdBy() {
if (!this.props.object.createdBy) {
return null;
}
return (
<InputWidget
type='text'
label='Created by'
defaultValue={this.props.object.createdBy.name}
readOnly
/>
);
}
updatedBy() {
if (!this.props.object.updatedBy) {
return null;
}
return (
<InputWidget
type='text'
label='Updated by'
defaultValue={this.props.object.updatedBy.name}
readOnly
/>
);
}
onSave() {
let data = {
id: this.props.object.id,
metadata: {
description: this.refs.description.getValue()
}
};
this.saveMetadata(data);
}
saveMetadata(data) {
if (typeof this.props.actions.updateItem === 'function') {
debug('Default save metadata called with data', data);
this.props.actions.updateItem(data);
} else {
debug('No actions provided, cannot save');
}
}
render() {
if (!this.props.object) {
return null;
}
debug('Metadata object', this.props.object);
let save = null;
if (this.props.object.id && this.props.actions) {
save = (
<Well>
<Row>
<Col md={6}>
<Button bsStyle='success' accessKey='s' onClick={this.onSave.bind(this)}>Save</Button>
</Col>
</Row>
</Well>
);
}
return (
<Row>
<Col>
<Panel header='Editing statistics'>
{this.createdBy()}
<InputWidget
type='text'
label='Created at'
defaultValue={this.props.object.createdAt.toString()}
readOnly
/>
{this.updatedBy()}
<InputWidget
type='text'
label='Last updated at'
defaultValue={this.props.object.updatedAt.toString()}
readOnly
/>
</Panel>
<Panel header='Description'>
<InputWidget
type='textarea'
label='Meta description'
ref='description'
defaultValue={this.props.object.metadata.description}
readOnly={(this.props.store) ? false : true}
placeholder='A brief description of the object'
/>
</Panel>
{save}
</Col>
</Row>
);
}
}
<file_sep>import React from 'react';
import ContentBlock from '../../../common/components/Widgets/ContentBlock';
import ContactStore from '../../stores/ContactStore';
import ContactActions from '../../actions/ContactActions';
let debug = require('debug')('PartnersForm');
export default class PartnersForm extends React.Component {
static propTypes = {
context: React.PropTypes.object,
onClose: React.PropTypes.func
}
static contextTypes = {
router: React.PropTypes.func,
onClose: null
};
constructor() {
super();
this.sendRequest = this.sendRequest.bind(this);
this.storeListener = this.onContactStoreChange.bind(this);
this.sent = false;
}
state = {
error: null,
contact: null
}
componentDidMount() {
ContactStore.listen(this.storeListener);
}
componentWillUnmount() {
ContactStore.unlisten(this.storeListener);
}
onContactStoreChange(state) {
debug('onContactStoreChange', state);
this.setState(state);
}
sendRequest(event) {
event.preventDefault();
event.stopPropagation();
let props = {
sender: {
name: React.findDOMNode(this.refs.name).value,
email: React.findDOMNode(this.refs.email).value
},
type: 'email',
subType: 'Partners',
message: React.findDOMNode(this.refs.message).value,
tags: ['contact', 'email', 'partners']
};
if (!props.sender.name) {
return this.setState({
error: {
message: 'Name is required'
}
});
}
if (!props.sender.email) {
return this.setState({
error: {
message: 'Email is required'
}
});
}
ContactActions.createItem(props);
}
handleErrorState() {
if (!this.state.error) {
return null;
}
return (
<p className='error'>{this.state.error.message}</p>
);
}
render() {
if (this.props.context) {
this.context = this.props.context;
}
let error = this.handleErrorState();
if (this.state.contact) {
if (typeof this.props.onClose === 'function') {
setTimeout(() => {
this.props.onClose();
}, 3000);
}
return (
<ContentBlock className='partners contact-form'>
<h2>Your message was received</h2>
<p className='centered'>
We thank you for your message and will get back at you promptly!
</p>
</ContentBlock>
);
}
return (
<ContentBlock className='partners contact-form'>
<h2>Please send us a message</h2>
{error}
<form method='post' onSubmit={this.sendRequest}>
<div className='form'>
<label className='control'>
<input
type='text'
name='name'
placeholder='Your name'
ref='name'
required
/>
</label>
<label className='control'>
<input
type='email'
name='email'
placeholder='<EMAIL>'
required
ref='email'
/>
</label>
<label className='control'>
<textarea name='message' ref='message' placeholder='Type your message here'></textarea>
</label>
</div>
<div className='buttons'>
<input type='submit' className='button' value='Send message' />
</div>
</form>
</ContentBlock>
);
}
}
<file_sep>export default require('../../common/actions/BaseListActions')
.generate('NeighborhoodListActions', {});
<file_sep>let populate = function populate(migrator) {
return migrator.getFixtureData().execute(migrator);
};
module.exports = {
populate: populate
};
<file_sep>## Generating CSR
```sh
mkdir -p certs/homehapp_com
cd certs/homehapp_com
openssl req -nodes -newkey rsa:2048 -keyout star_homehapp_com.key -out star_homehapp_com.csr
```
```
Country Name (2 letter code) [AU]:GB
State or Province Name (full name) [Some-State]:uk
Locality Name (eg, city) []:London
Organization Name (eg, company) [Internet Widgits Pty Ltd]:Homehapp
Organizational Unit Name (eg, section) []:Development
Common Name (e.g. server FQDN or YOUR name) []:*.homehapp.com
Email Address []:<EMAIL>
```
## To Create .pem -file
Append following files together:
* star_homehapp_com.crt
* DigiCertCA.crt
cat star_homehapp_com.crt >> star_homehapp_com.pem && cat DigiCertCA.crt >> star_homehapp_com.pem
Create the DHE Parameter:
```sh
openssl dhparam -out star_homehapp_com_dhp.pem 2048
```
lb-production-ip-common: 192.168.3.11
# Create Cluster
./support/production/createCluster.sh admin
# Setup Load Balancing
gcloud compute addresses create lb-production-ip-common --global
Find instance group name:
```sh
gcloud compute instance-groups managed list --project $PROJECT_ID | awk '{print $1}' | grep "admin-prod"
```
Create HTTP Health checks:
```sh
gcloud compute http-health-checks create http-basic-check
```
Add named port to instance group:
```sh
gcloud compute instance-groups managed set-named-ports gke-homehapp-admin-prod-5652e395-group \
--named-ports http:80
```
Create Backend Service:
```sh
gcloud compute backend-services create admin-be-service \
--protocol HTTP --http-health-check http-basic-check
```
Add Instance groups to backend service
```sh
gcloud compute backend-services add-backend admin-be-service \
--balancing-mode UTILIZATION --max-utilization 0.8 \
--capacity-scaler 1 --instance-group gke-homehapp-admin-prod-5652e395-group
```
Create a URL map:
```sh
gcloud compute url-maps create www-map \
--default-service admin-be-service
```
Add a path matcher to URL map and define request path mappings:
```sh
gcloud compute url-maps add-path-matcher www-map \
--default-service admin-be-service --path-matcher-name pathmap \
--path-rules=/admin=admin-be-service
```
Create target HTTP Proxy to route requests to URL Map:
```sh
gcloud compute target-http-proxies create http-lb-proxy \
--url-map www-map
```
Get Load Balancer static IP address:
```sh
gcloud compute addresses list | grep "lb-production-ip-common" | awk '{print $2}'
```
Create a global forwarding rule:
```sh
gcloud compute forwarding-rules create http-app-gfr \
--address 192.168.3.11 --global \
--target-http-proxy http-lb-proxy --port-range 80
```
## Create self-signed certificate for testing
Create the private key:
```sh
mkdir -p certs/selfsigned
cd certs/selfsigned
openssl genrsa -out homehapp.key 2048
```
Create Certificate Signing Request:
```sh
openssl req -new -key homehapp.key -out homehapp.csr
```
-> FI
-> Uusimaa
-> Helsinki
-> Qvik Oy
-> Development
-> homehapp.qvik.fi
-> <EMAIL>
-> hhcertificate1
Create the Self-Signed Certificate:
```sh
openssl x509 -req -days 365 -in homehapp.csr -signkey homehapp.key -out homehapp.crt
```
Upload Certificate to Google Cloud:
```sh
export RESOURCE_NAME=hhsscert
gcloud beta compute ssl-certificates create $RESOURCE_NAME --certificate homehapp.crt \
--private-key homehapp.key
```
To remove certificate:
```sh
gcloud beta compute ssl-certificates delete $RESOURCE_NAME
```
<file_sep>let debug = require('debug')('MongooseMigrator');
class MongooseMigrator {
constructor(app) {
this.app = app;
this.version = 0;
}
getSchemas() {
let schemas = this.app.db.getSchemas();
return schemas;
}
getModels() {
let schemas = this.app.db.getModels();
return schemas;
}
getFixtureData() {
return this.app.db.getFixturesData();
}
execute(action, args) {
debug('execute', action, args);
let actionMethod = require(`./action.${action}`);
return actionMethod(this, args);
}
}
module.exports = MongooseMigrator;
<file_sep>import HomesEditDetails from './EditDetails';
import HomeStore from '../../stores/HomeStore';
let debug = require('../../../common/debugger')('HomesCreateDetails');
export default class HomesCreateDetails extends HomesEditDetails {
onHomeStoreChange(state) {
debug('onHomeStoreChange', state);
let error = HomeStore.getState().error;
let home = HomeStore.getState().home;
if (error) {
this.setState({
error: error
});
}
if (home && home.slug) {
debug('Redirect to the newly created home');
let href = this.context.router.makeHref('homeEdit', {id: state.home.id});
debug('Redirect url', href);
window.location.href = href;
}
}
}
<file_sep>import React from 'react';
export default class ObjectNotFound extends React.Component {
render() {
return (
<div className='errorPage'>
<h1>Not found</h1>
<p>The object you have requested was not found</p>
</div>
);
}
}
<file_sep>import Bluebird from 'bluebird';
import BaseAdapter from './BaseAdapter';
import Helpers from '../Helpers';
import mongoose from 'mongoose';
import async from 'async';
Bluebird.promisifyAll(mongoose);
class MongooseAdapter extends BaseAdapter {
static defaults() {
return {
schemaRootPaths: [
require('path').join(__dirname, '/../../schemas/mongoose')
]
};
}
constructor(app, config) {
super(app, config, MongooseAdapter.defaults());
this.migrationSupport = true;
}
connect(cb) {
if (!this.config.uri) {
err = new Error('Unable to find proper configuration for Mongoose!');
return cb(err);
}
let conn = null;
let connect = (next) => {
let opts = this.config.options;
if (!opts) {
opts = {};
}
if (opts.debug) {
mongoose.set('debug', opts.debug);
}
let uri = this.config.uri;
if (require('util').isArray(uri)) {
uri = uri.join(',');
}
try {
conn = mongoose.createConnection(
uri, opts
);
} catch(err) {
return next(err);
}
conn.on('error', function (err) {
console.error(`Error occurred on Mongoose: ${err.message}`, err.stack);
});
conn.once('open', () => {
next(null);
});
};
let loadSchemas = (next) => {
let tasks = [];
let schemaPaths = [];
if (!this.config.schemaRootPaths) {
return next(new Error('No schemaRootPaths defined in config!'));
}
this.config.schemaRootPaths.forEach((rootPath) => {
rootPath = require('path').normalize(rootPath);
let paths = Helpers.walkDirSync(rootPath, {
ext: ['.js']
});
if (paths) {
schemaPaths = schemaPaths.concat(paths);
}
});
schemaPaths.forEach((schemaPath) => {
tasks.push((ccb) => {
let sp;
try {
sp = require(schemaPath);
} catch(err) {
console.error(`Error loading schema: ${schemaPath}`, err);
return ccb();
}
if (sp.loadSchemas) {
sp.loadSchemas(mongoose, (schemas) => {
this._schemas = require('util')._extend(this._schemas, schemas);
// Read each schema as model once, so mongoose populates its internal index properly
Object.keys(this._schemas).forEach((name) => {
this.getModel(name);
});
ccb();
});
} else {
ccb();
}
});
});
async.series(tasks, function (err) {
next(err);
});
};
connect((err) => {
if (err) {
return cb(err);
}
this.connection = conn;
loadSchemas(function(serr) {
if (serr) {
return cb(serr);
}
cb(null, conn);
});
});
}
getSchema(name) {
return this._schemas[name];
}
getSchemas() {
return this._schemas;
}
getModel(name, dbName) {
if (!dbName) {
dbName = name;
}
try {
return this.connection.model(dbName, this.getSchema(name));
} catch (err) {
return this.connection.model(dbName);
}
}
getModels() {
let models = {};
Object.keys(this._schemas).forEach((name) => {
models[name] = this.getModel(name);
});
return models;
}
getMigrator() {
return require('./Migrators/Mongoose');
}
getFixturesData() {
return require(require('path').join(this.app.PROJECT_ROOT, 'fixtures', 'mongoose'));
}
}
module.exports = MongooseAdapter;
<file_sep>import React from 'react';
import Row from 'react-bootstrap/lib/Row';
import Panel from 'react-bootstrap/lib/Panel';
import Table from 'react-bootstrap/lib/Table';
import ListItem from './ListItem';
import CreateEdit from './CreateEdit';
export default class AgentsList extends React.Component {
static propTypes = {
items: React.PropTypes.array.isRequired
}
constructor(props) {
super(props);
}
state = {
underEdit: null
}
onItemSelected(item) {
console.log('onItemSelected', item);
this.setState({
underEdit: item
});
}
onItemSaved() {
window.location.reload();
}
render() {
let editorBlock = null;
if (this.state.underEdit) {
editorBlock = (
<Panel bsStyle='info' header='Edit Agent'>
<CreateEdit
model={this.state.underEdit}
onSave={this.onItemSaved.bind(this)}
onCancel={() => {
this.setState({underEdit: null});
}}
/>
</Panel>
);
}
return (
<Row>
<h1><i className='fa fa-user'></i> {this.props.items.length} agents</h1>
<Table striped hover>
<thead>
<tr>
<th>Name</th>
<th>Agency</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{this.props.items.map((item) => {
return (
<ListItem
key={item.id}
item={item}
onSelected={this.onItemSelected.bind(this)} />
);
})}
</tbody>
</Table>
{editorBlock}
</Row>
);
}
}
<file_sep>#! /bin/sh
# Do not change these
REV=`git rev-parse --short HEAD`
CWD=`pwd`
CONTAINER_REGISTRY_HOST=eu.gcr.io
ENV=$1
PNAME="$2-$ENV"
PBNAME="$2"
CERT_PATH_PREFIX=$3
CLUSTER_NAME="homehapp-$ENV"
CLUSTER_GOOGLE_NAME=""
function printUsage() {
echo "Required environment variables:"
echo " PROJECT_ID: Google Project ID"
echo ""
echo "Usage PROJECT_ID=id ./support/setupCluster.sh [stg,prod] [project_name] [cert_path_prefix (prod only)]"
echo "Add -d for dry-run"
}
function printUsageAndExit() {
printUsage
exit
}
if [ "$PROJECT_ID" = "" ]; then
echo "No Google Project ID defined!"
printUsageAndExit
fi
if [ "$ENV" = "" ]; then
echo "No environment defined!"
printUsageAndExit
fi
if [ "$2" = "" ]; then
echo "No project name defined!"
printUsageAndExit
fi
if [ "$ENV" = "prod" ]; then
if [ "$3" = "" ]; then
echo "No cert path prefix defined!"
printUsageAndExit
fi
fi
if [ ! -d "$CWD/tmp" ]; then
mkdir "$CWD/tmp"
fi
function setContext() {
if [ "$CLUSTER_GOOGLE_NAME" = "" ]; then
CLUSTER_GOOGLE_NAME=`kubectl config view | awk '{print $2}' | grep $CLUSTER_NAME | tail -n 1`
fi
if [ "$1" = "-d" ]; then
echo "Execute: 'kubectl config use-context $CLUSTER_GOOGLE_NAME'"
else
kubectl config use-context $CLUSTER_GOOGLE_NAME
fi
}
function createController() {
local SOURCE_CONFIG="$CWD/infrastructure/configs/$ENV/project-controller-tpl.json"
local TARGET_CONFIG="$CWD/tmp/$PNAME-controller.json"
local TMP_FILE="/tmp/$PNAME-controller.json"
sed "s/:PROJECT_NAME/$PNAME/g" $SOURCE_CONFIG > $TARGET_CONFIG
sed "s/:PROJECT_BASE_NAME/$PBNAME/g" $TARGET_CONFIG > $TMP_FILE && mv $TMP_FILE $TARGET_CONFIG
sed "s/:PROJECT_ID/$PROJECT_ID/g" $TARGET_CONFIG > $TMP_FILE && mv $TMP_FILE $TARGET_CONFIG
sed "s/:CONTROLLER_NAME/$PNAME-controller-$REV/g" $TARGET_CONFIG > $TMP_FILE && mv $TMP_FILE $TARGET_CONFIG
sed "s/:REV/$REV/g" $TARGET_CONFIG > $TMP_FILE && mv $TMP_FILE $TARGET_CONFIG
sed "s/:ENV/$ENV/g" $TARGET_CONFIG > $TMP_FILE && mv $TMP_FILE $TARGET_CONFIG
if [ "$1" = "-d" ]; then
echo "Execute: 'kubectl create -f $CWD/tmp/$PNAME-controller.json'"
else
kubectl create -f "$CWD/tmp/$PNAME-controller.json"
rm $TARGET_CONFIG
fi
}
function createService() {
local SOURCE_CONFIG="$CWD/infrastructure/configs/$ENV/project-service-tpl.json"
local TARGET_CONFIG="$CWD/tmp/$PNAME-service.json"
local TMP_FILE="/tmp/$PNAME-service.json"
sed "s/:PROJECT_NAME/$PNAME/g" $SOURCE_CONFIG > $TARGET_CONFIG
sed "s/:PROJECT_BASE_NAME/$PBNAME/g" $TARGET_CONFIG > $TMP_FILE && mv $TMP_FILE $TARGET_CONFIG
sed "s/:PROJECT_ID/$PROJECT_ID/g" $TARGET_CONFIG > $TMP_FILE && mv $TMP_FILE $TARGET_CONFIG
sed "s/:REV/$REV/g" $TARGET_CONFIG > $TMP_FILE && mv $TMP_FILE $TARGET_CONFIG
sed "s/:ENV/$ENV/g" $TARGET_CONFIG > $TMP_FILE && mv $TMP_FILE $TARGET_CONFIG
if [ "$1" = "-d" ]; then
echo "Execute: 'kubectl create -f $CWD/tmp/$PNAME-service.json'"
else
kubectl create -f "$CWD/tmp/$PNAME-service.json"
rm $TARGET_CONFIG
fi
}
function createProxySecret() {
local SOURCE_CONFIG="$CWD/infrastructure/configs/$ENV/proxy-secret-tpl.json"
local TARGET_CONFIG="$CWD/tmp/$PNAME-proxy-secret.json"
local TMP_FILE="/tmp/$PNAME-proxy-secret.json"
local PROXY_CERT=`base64 -i $CERT_PATH_PREFIX.pem`
local PROXY_KEY=`base64 -i $CERT_PATH_PREFIX.key`
local PROXY_DHP=`base64 -i ${CERT_PATH_PREFIX}_dhp.pem`
sed "s/:PROXY_CERT/$PROXY_CERT/g" $SOURCE_CONFIG > $TARGET_CONFIG
sed "s/:PROXY_KEY/$PROXY_KEY/g" $TARGET_CONFIG > $TMP_FILE && mv $TMP_FILE $TARGET_CONFIG
sed "s/:PROXY_DHP/$PROXY_DHP/g" $TARGET_CONFIG > $TMP_FILE && mv $TMP_FILE $TARGET_CONFIG
if [ "$1" = "-d" ]; then
echo "Execute: 'kubectl create -f $CWD/tmp/$PNAME-proxy-secret.json'"
else
kubectl create -f "$CWD/tmp/$PNAME-proxy-secret.json"
rm $TARGET_CONFIG
fi
}
function createProxyController() {
local SOURCE_CONFIG="$CWD/infrastructure/configs/$ENV/proxy-controller-tpl.json"
local TARGET_CONFIG="$CWD/tmp/$PNAME-proxy-controller.json"
local TMP_FILE="/tmp/$PNAME-proxy-controller.json"
local UC_PNAME=`echo "${PBNAME}_${ENV}" | awk '{print toupper($0)}'`
local SERVICE_HOST="${UC_PNAME}_SERVICE_HOST"
local SERVICE_PORT="${UC_PNAME}_SERVICE_PORT_ENDPOINT"
sed "s/:PROJECT_NAME/$PNAME-proxy/g" $SOURCE_CONFIG > $TARGET_CONFIG
sed "s/:PROJECT_ID/$PROJECT_ID/g" $TARGET_CONFIG > $TMP_FILE && mv $TMP_FILE $TARGET_CONFIG
sed "s/:CONTROLLER_NAME/$PNAME-proxy-controller-$REV/g" $TARGET_CONFIG > $TMP_FILE && mv $TMP_FILE $TARGET_CONFIG
sed "s/:REV/$REV/g" $TARGET_CONFIG > $TMP_FILE && mv $TMP_FILE $TARGET_CONFIG
sed "s/:ENV/$ENV/g" $TARGET_CONFIG > $TMP_FILE && mv $TMP_FILE $TARGET_CONFIG
sed "s/:SERVICE_HOST/$SERVICE_HOST/g" $TARGET_CONFIG > $TMP_FILE && mv $TMP_FILE $TARGET_CONFIG
sed "s/:SERVICE_PORT/$SERVICE_PORT/g" $TARGET_CONFIG > $TMP_FILE && mv $TMP_FILE $TARGET_CONFIG
if [ "$1" = "-d" ]; then
echo "Execute: 'kubectl create -f $CWD/tmp/$PNAME-proxy-controller.json'"
else
kubectl create -f "$CWD/tmp/$PNAME-proxy-controller.json"
rm $TARGET_CONFIG
fi
}
function createProxyService() {
local SOURCE_CONFIG="$CWD/infrastructure/configs/$ENV/proxy-service-tpl.json"
local TARGET_CONFIG="$CWD/tmp/$PNAME-proxy-service.json"
local TMP_FILE="/tmp/$PNAME-proxy-service.json"
sed "s/:PROJECT_NAME/$PNAME-proxy/g" $SOURCE_CONFIG > $TARGET_CONFIG
sed "s/:PROJECT_ID/$PROJECT_ID/g" $TARGET_CONFIG > $TMP_FILE && mv $TMP_FILE $TARGET_CONFIG
sed "s/:REV/$REV/g" $TARGET_CONFIG > $TMP_FILE && mv $TMP_FILE $TARGET_CONFIG
sed "s/:ENV/$ENV/g" $TARGET_CONFIG > $TMP_FILE && mv $TMP_FILE $TARGET_CONFIG
if [ "$1" = "-d" ]; then
echo "Execute: 'kubectl create -f $CWD/tmp/$PNAME-proxy-service.json'"
else
kubectl create -f "$CWD/tmp/$PNAME-proxy-service.json"
rm $TARGET_CONFIG
fi
}
function configureProxyFirewall() {
if [ "$1" = "-d" ]; then
echo "Execute: 'gcloud compute firewall-rules create ${CLUSTER_NAME}-${PBNAME}-public --allow TCP:80,TCP:443 --source-ranges 0.0.0.0/0 --target-tags gke-${CLUSTER_NAME}-node'"
else
gcloud compute firewall-rules create ${CLUSTER_NAME}-${PBNAME}-public --project $PROJECT_ID --allow TCP:80,TCP:443 --source-ranges 0.0.0.0/0 --target-tags gke-${CLUSTER_NAME}-node
fi
}
function tagClusterNodes() {
if [ "$1" = "-d" ]; then
echo "Execute: gcloud compute instances list --project $PROJECT_ID -r "^gke-${CLUSTER_NAME}.*node.*$" | tail -n +2 | cut -f1 -d' ' | xargs -L 1 -I '{}'"
echo "Execute: 'gcloud compute instances add-tags {} --project $PROJECT_ID --tags gke-${CLUSTER_NAME}-node'"
else
gcloud compute instances list --project $PROJECT_ID -r "^gke-${CLUSTER_NAME}.*node.*$" | tail -n +2 | cut -f1 -d' ' | xargs -L 1 -I '{}' gcloud compute instances add-tags {} --project $PROJECT_ID --tags gke-${CLUSTER_NAME}-node
fi
}
if [ "$4" = "-d" ]; then
echo "In Dry-Run mode"
fi
setContext $4
echo ""
echo "Creating Replication Controller $PNAME-controller"
createController $4
echo ""
echo "Creating Service $PNAME-service"
createService $4
if [ "$ENV" = "prod" ]; then
echo ""
echo "Creating Proxy Secret $PNAME-proxy-secret"
createProxySecret $4
echo ""
echo "Creating Proxy Replication Controller $PNAME-proxy-controller"
createProxyController $4
echo ""
echo "Creating Proxy Service $PNAME-proxy-service"
createProxyService $4
echo ""
echo "Tagging Cluster nodes for $CLUSTER_NAME"
tagClusterNodes $4
echo ""
echo "Configuring Firewall for $PNAME-proxy"
configureProxyFirewall $4
fi
echo ""
echo "Cluster created!"
echo ""
if [ "$4" = "" ]; then
echo "Execute following script after few minutes to find out the external IP."
if [ "$ENV" = "prod" ]; then
echo "kubectl describe services $PNAME-proxy --context=$CLUSTER_GOOGLE_NAME | grep 'LoadBalancer Ingress'"
else
echo "kubectl describe services $PNAME --context=$CLUSTER_GOOGLE_NAME | grep 'LoadBalancer Ingress'"
fi
fi
<file_sep>import React from 'react';
import Button from 'react-bootstrap/lib/Button';
import AgentListActions from '../../actions/AgentListActions';
export default class AgentsListItem extends React.Component {
static propTypes = {
item: React.PropTypes.object.isRequired,
onSelected: React.PropTypes.func.isRequired
}
constructor(props) {
super(props);
}
onEdit() {
this.props.onSelected(this.props.item);
}
onDelete() {
AgentListActions.removeItem(this.props.item.id);
}
render() {
let agencyName = 'Not set';
if (this.props.item.agency && this.props.item.agency.title) {
agencyName = this.props.item.agency.title;
}
return (
<tr className='agentItem'>
<td>
{this.props.item.rname}
</td>
<td>
{agencyName}
</td>
<td>
<Button
bsStyle='primary'
bsSize='medium'
onClick={this.onEdit.bind(this)}>
Edit
</Button>
<Button
bsStyle='danger'
bsSize='medium'
onClick={this.onDelete.bind(this)}>
Delete
</Button>
</td>
</tr>
);
}
}
<file_sep>import React from 'react';
export default class SocialMedia extends React.Component {
static propTypes = {
className: React.PropTypes.string
}
static defaultProps = {
className: null
}
render() {
let classes = ['social'];
if (this.props.className) {
classes.push(this.props.className);
}
return (
<ul className={classes.join(' ')}>
<li>
<a href='https://www.facebook.com/homehapp' target='_blank'>
<i className='fa fa-facebook-square'>
<span className='alt'>Facebook</span>
</i>
</a>
</li>
<li>
<a href='https://www.pinterest.com/homehapp' target='_blank'>
<i className='fa fa-pinterest'>
<span className='alt'>Pinterest</span>
</i>
</a>
</li>
<li>
<a href='https://www.instagram.com/homehapp' target='_blank'>
<i className='fa fa-instagram'>
<span className='alt'>Instagram</span>
</i>
</a>
</li>
<li>
<a href='https://www.twitter.com/homehapp' target='_blank'>
<i className='fa fa-twitter'>
<span className='alt'>Twitter</span>
</i>
</a>
</li>
</ul>
);
}
}
// <li>
// <a href='https://www.pinterest.com' target='_blank'>
// <i className='fa fa-pinterest'></i>
// </a>
// </li>
// <li>
// <a href='https://www.youtube.com' target='_blank'>
// <i className='fa fa-youtube-square'></i>
// </a>
// </li>
<file_sep>import React from 'react';
import NeighborhoodStore from '../../stores/NeighborhoodStore';
import NeighborhoodStory from './NeighborhoodStory';
import Loading from '../../../common/components/Widgets/Loading';
import ErrorPage from '../../../common/components/Layout/ErrorPage';
import { setPageTitle } from '../../../common/Helpers';
let debug = require('../../../common/debugger')('NeighborhoodContainer');
export default class NeighborhoodContainer extends React.Component {
static propTypes = {
params: React.PropTypes.object
};
constructor() {
super();
this.neighborhoodStoreListener = this.neighborhoodStoreOnChange.bind(this);
}
state = {
error: null,
neighborhood: NeighborhoodStore.getState().neighborhood
}
componentDidMount() {
NeighborhoodStore.listen(this.neighborhoodStoreListener);
NeighborhoodStore.fetchNeighborhoodBySlug(this.props.params.city, this.props.params.neighborhood, true);
}
componentWillUnmount() {
NeighborhoodStore.unlisten(this.neighborhoodStoreListener);
}
neighborhoodStoreOnChange(state) {
this.setState(state);
}
handlePendingState() {
return (
<Loading>
<p>Loading story data</p>
</Loading>
);
}
handleErrorState() {
debug('Failed to load neighborhood', this.state.error);
let error = {
title: 'Error loading story!',
message: this.state.error.message
};
return (
<ErrorPage {...error} />
);
}
render() {
if (this.state.error) {
return this.handleErrorState();
}
if (NeighborhoodStore.isLoading() || !this.state.neighborhood) {
return this.handlePendingState();
}
setPageTitle(this.state.neighborhood.pageTitle);
return (
<NeighborhoodStory neighborhood={this.state.neighborhood} />
);
}
}
<file_sep>import {loadCommonPlugins, commonJsonTransform, getImageFields, getAddressFields, getImageSchema, getStoryBlockSchema, getMainImage, populateMetadata} from './common';
exports.loadSchemas = function (mongoose, next) {
let Schema = mongoose.Schema;
let ObjectId = Schema.Types.ObjectId;
let schemas = {};
schemas.HomeAttribute = new Schema({
name: String,
value: Schema.Types.Mixed,
valueType: {
type: String,
default: 'string'
}
});
schemas.HomeImage = getImageSchema(Schema);
schemas.HomeStoryBlock = getStoryBlockSchema(Schema);
schemas.Home = new Schema(populateMetadata({
uuid: {
type: String,
index: true,
unique: true
},
slug: {
type: String,
index: true,
required: true
},
enabled: {
type: Boolean,
default: true
},
// Details
title: {
type: String,
default: ''
},
announcementType: {
type: String,
enum: ['buy', 'rent', 'story'],
default: 'story'
},
description: {
type: String,
default: ''
},
details: {
area: {
type: Number,
default: null
},
},
location: {
address: getAddressFields(),
coordinates: {
type: [],
default: null
},
neighborhood: {
type: ObjectId,
ref: 'Neighborhood',
index: true,
default: null
}
},
costs: {
currency: {
type: String,
enum: ['EUR', 'GBP', 'USD'],
default: 'GBP'
},
sellingPrice: {
type: Number
},
rentalPrice: {
type: Number
},
councilTax: {
type: Number
}
},
properties: {
type: String,
default: ''
},
// This is free object defined by clients
// Example value: {bedrooms: 4, bathrooms: 2, otherRooms: 1}
rooms: {
type: Schema.Types.Mixed,
default: {}
},
// attributes: [schemas.HomeAttribute],
amenities: [String],
// facilities: [String],
// Story
story: {
enabled: {
type: Boolean,
default: false
},
blocks: [schemas.HomeStoryBlock]
},
neighborhoodStory: {
enabled: {
type: Boolean,
default: false
},
blocks: [schemas.HomeStoryBlock]
},
myNeighborhood: {
type: ObjectId,
ref: 'Neighborhood'
},
images: [schemas.HomeImage],
_image: getImageFields(),
epc: getImageFields(),
floorplans: [schemas.HomeImage],
brochures: [schemas.HomeImage],
// Like related
likes: {
total: {
type: Number,
default: 0
},
users: {
type: [String],
default: []
}
},
// Flags
visible: {
type: Boolean,
index: true,
default: true
},
agents: [{
type: ObjectId,
ref: 'Agent',
index: true,
default: null
}]
}));
schemas.Home.virtual('image').get(function() {
if (this._image && this._image.url) {
return this._image;
}
return null;
});
schemas.Home.virtual('image').set(function(image) {
if (!image.url || !image.width || !image.height) {
this._image = null;
}
this._image = image;
});
schemas.Home.virtual('mainImage').get(function() {
return getMainImage(this);
});
schemas.Home.virtual('homeTitle').get(function () {
if (this.title && this.title.length) {
return this.title;
}
let title = [];
if (this.location.address.street) {
title.push(`${this.location.address.street} ${this.location.address.apartment}`);
}
if (this.location.neighborhood && typeof this.location.neighborhood.title !== 'undefined') {
title.push(`neighborhood ${this.location.neighborhood.title}`);
}
if (this.location.address.street) {
title.push(`street ${this.location.address.city}`);
}
if (!title.length) {
title.push('Unnamed');
}
return title.join(', ').trim();
});
schemas.Home.virtual('pageTitle').get(function () {
let title = [this.homeTitle];
if (this.location.neighborhood && typeof this.location.neighborhood.title !== 'undefined') {
title.push(this.location.neighborhood.title);
}
if (this.location.address.city) {
title.push(this.location.address.city);
}
return title.join(' | ');
});
schemas.Home.virtual('waterChargeSuffix').get(function () {
let suffix = `${this.costs.waterChargePerType} / month`;
return suffix;
});
schemas.Home.virtual('formattedPrice').get(function() {
let price = null;
if (this.costs.sellingPrice) {
price = this.costs.sellingPrice;
}
if (this.costs.rentalPrice) {
price = this.costs.rentalPrice;
}
if (!price) {
return null;
}
return `${String(Math.round(price)).replace(/(\d)(?=(\d{3})+$)/g, '$1,')}`;
});
schemas.Home.statics.editableFields = function () {
return [
'title', 'description', 'location', 'costs', 'story', 'neighborhoodStory',
'amenities', 'facilities', 'attributes', 'images', 'announcementType',
'brochures', 'image', 'epc', 'floorplans', 'properties', 'enabled'
];
};
schemas.HomeAction = new Schema({
type: {
type: String,
default: 'like',
index: true
},
user: {
type: ObjectId,
ref: 'User',
index: true
},
home: {
type: ObjectId,
ref: 'Home',
index: true
},
createdAt: {
type: Date
}
});
Object.keys(schemas).forEach((name) => {
loadCommonPlugins(schemas[name], name, mongoose);
schemas[name].options.toJSON.transform = (doc, ret) => {
ret = commonJsonTransform(ret);
if (ret.mainImage) {
delete ret.mainImage.id;
}
if (ret.images && ret.images.length) {
ret.images = ret.images.map((img) => {
delete img.id;
return img;
});
}
if (ret.attributes && ret.attributes.length) {
ret.attributes = ret.attributes.map((attr) => {
delete attr._id;
return attr;
});
}
return ret;
};
if (name === 'HomeStoryBlock' || name === 'HomeAttribute') {
schemas[name].options.toJSON.transform = (doc, ret) => {
ret = commonJsonTransform(ret);
delete ret.id;
return ret;
};
}
});
next(schemas);
};
<file_sep>import ReactUpdates from 'react/lib/ReactUpdates';
import DOMManipulator from './DOMManipulator';
let debug = require('debug')('Helpers');
exports.floor = function floor(v) {
v = Math.floor(v * 100) / 100;
if ('#{v}'.match(/\./)) {
let vp = `${v}`.split('.');
let n = vp[0];
let d = vp[1];
if (d < 10) {
d = `${d}0`;
}
v = `${n}.${d}`;
}
return v;
};
exports.setCDNUrlProperties = function setCDNUrlProperties(url, props) {
let propStr = '';
for (let [key, val] of enumerate(props)) {
propStr += `${key}_${val},`;
}
propStr = propStr.substr(0, propStr.length - 1);
let re = /^(https?:\/\/res.cloudinary.com\/\w+\/\w+\/upload\/)(\w+)/;
url = url.replace(re, `$1${propStr}/$2`);
return url;
};
exports.merge = function merge(...argv) {
let target = Object.assign({}, argv.shift());
argv.forEach((a) => {
for (let [key, value] of enumerate(a)) {
if (a.hasOwnProperty(key)) {
if (Array.isArray(target[key])) {
target[key] = target[key].concat(value);
} else if (typeof target[key] === 'object'
&& typeof target[key] !== 'undefined'
&& target[key] !== null)
{
target[key] = merge(target[key], value);
} else {
target[key] = value;
}
}
}
});
return target;
};
exports.batchedCallback = function batchedCallback(callback) {
return function(err, res) {
ReactUpdates.batchedUpdates(callback.bind(null, err, res));
};
};
exports.debounce = function debounce(fn, wait) {
var timeout;
return function() {
var context = this, args = arguments;
let later = function() {
timeout = null;
fn.apply(context, args);
};
clearTimeout(timeout);
timeout = setTimeout(later, wait);
};
};
let getPageOffset = exports.getPageOffset = function getPageOffset() {
return window.pageYOffset || document.documentElement.scrollTop;
};
exports.checkElementInViewport = function checkElementInViewport(element, viewportHeight, lazyOffset) {
let elementOffsetTop = 0;
let offset = getPageOffset() + lazyOffset;
if (element.offsetParent) {
while (element) {
elementOffsetTop += element.offsetTop;
element = element.offsetParent;
}
}
return elementOffsetTop < (viewportHeight + offset);
};
exports.scrollTop = function scrollTop(offset = null, speed = 500) {
if (offset === null) {
return window.pageYOffset || document.documentElement.scrollTop;
}
let f = 5;
let init = document.documentElement.scrollTop + document.body.scrollTop;
let c = Math.ceil(speed / f);
let i = 0;
// Invalid count
if (c <= 0) {
return null;
}
if (speed < 10) {
window.scrollTo(0, init + dy * i);
return null;
}
let dy = (offset - init) / c;
let nextHop = function() {
i++;
window.scrollTo(0, init + dy * i);
if (i < c) {
setTimeout(nextHop, f);
}
};
nextHop();
};
let orientation = null;
exports.getOrientation = function getOrientation() {
if (window.innerHeight > window.innerWidth) {
return 'portrait';
}
return 'landscape';
};
exports.setFullHeight = function setFullHeight() {
let height = window.innerHeight;
let iosHeights = [
1302, // iPad Pro portrait,
960, // iPad retina portrait, iPad Pro landscape
704, // iPad retina landscape,
628, // iPhone 6(s)+ portrait
414, // iPhone 6(s)+ landscape
559, // iPhone 6(s) portrait
375, // iPhone 6(s) landscape
460, // iPhone 5(s) portrait
320, // iPhone 5(s) landscape
372, // iPhone 4(s) portrait
320 // iPhone 4(s) landscape
];
// Prevent resizing the iOS device full heights, because scrolling will
// otherwise cause a nasty side effect
if (/iPad|iPhone|iPod/.test(navigator.platform)) {
if (orientation === exports.getOrientation()) {
return null;
}
orientation = exports.getOrientation();
let closest = iosHeights[0];
for (let h of iosHeights) {
if (Math.abs(h - height) < Math.abs(closest - height)) {
closest = h;
}
}
height = closest;
}
let setHeight = function(item, strict = false, max = 650) {
let h = height;
if (item.hasAttribute('data-proportion')) {
let prop = Number(item.getAttribute('data-proportion'));
if (prop > 0) {
h = Math.round(h * prop);
}
}
h = Math.max(max, h);
let dh = h / item.offsetHeight;
// Don't change anything, if the changed height differs less
// than 10% of the previous. Especially on iPad and iPhone
// the flickering caused by the lack of this looks very bad
if (Math.abs(dh - 1) < 0.1) {
return;
}
if (strict) {
item.style.height = `${h}px`;
} else {
item.style.minHeight = `${h}px`;
}
};
let items = document.getElementsByClassName('aspect-ratio');
for (let item of items) {
let ar = Number(item.getAttribute('data-aspect-ratio'));
if (!ar) {
continue;
}
item.style.height = `${Math.round(window.innerWidth / ar)}px`;
}
items = document.getElementsByClassName('full-height-always');
for (let item of items) {
setHeight(item, false, 0);
}
if (window && window.innerWidth <= 640) {
items = document.getElementsByClassName('full-height-small');
for (let item of items) {
setHeight(item, false, 0);
}
items = document.getElementsByClassName('full-height');
for (let item of items) {
if (item.className.match(/full-height-(always|small)/)) {
continue;
}
item.style.height = null;
item.style.minHeight = null;
}
items = document.getElementsByClassName('full-height-strict');
for (let item of items) {
if (item.className.match(/full-height-always/)) {
continue;
}
item.style.height = null;
item.style.minHeight = null;
}
return null;
}
items = document.getElementsByClassName('full-height');
for (let item of items) {
setHeight(item, false);
}
items = document.getElementsByClassName('full-height-strict');
for (let item of items) {
setHeight(item, true);
}
};
exports.itemViews = function itemViews() {
let tmp = document.getElementsByClassName('item');
let items = [];
if (!tmp.length) {
return null;
}
for (let i = 0; i < tmp.length; i++) {
if (!tmp[i].className.match(/\bfixed\b/)) {
continue;
}
items.push(tmp[i]);
}
for (let i = 0; i < items.length; i++) {
let item = new DOMManipulator(items[i]);
// Check if the element is in the viewport with a small tolerance AFTER
// the element should be displayed
if (!item.visible() && items.length > 1) {
item.addClass('outside-viewport');
} else {
item.removeClass('outside-viewport');
}
}
};
exports.literals = function literals(q, type = 'base') {
let rval = (type === 'ordinal') ? `${q}th` : String(q);
switch (q % 10) {
case 1:
if (q < 10) {
rval = (type === 'ordinal') ? 'first' : 'one';
} else if (q > 20 && type === 'ordinal') {
rval = `${q}st`;
}
break;
case 2:
if (q < 10) {
rval = (type === 'ordinal') ? 'second' : 'two';
} else if (q > 20 && type === 'ordinal') {
rval = `${q}nd`;
}
break;
case 3:
if (q < 10) {
rval = (type === 'ordinal') ? 'third' : 'three';
} else if (q > 20 && type === 'ordinal') {
rval = `${q}rd`;
}
break;
}
return rval;
};
exports.capitalize = function capitalize(str) {
return str && str[0].toUpperCase() + str.slice(1);
};
// The contents of this function are open for discussion. Currently
// this method extrapolates some values, trying to make sane results
exports.primaryHomeTitle = function primaryHomeTitle(home) {
if (home.title) {
return home.title;
}
let parts = [];
let attributes = home.attributes || [];
for (let c of attributes) {
switch (c.name) {
case 'rooms':
parts.push(`${exports.literals(c.value)} room apartment`);
break;
// case 'floor':
// parts.push(`${exports.literals(c.value, 'ordinal')} floor`);
// break;
}
}
let location = [];
if (home.location.address.street) {
location.push(` on ${home.location.address.street}`);
}
if (home.location.neighborhood) {
location.push(` in ${home.location.neighborhood.title}`);
}
if (home.location.address.city) {
location.push(`, ${home.location.address.city}`);
}
return exports.capitalize(`${parts.join(', ')}${location.join('')}`);
};
let enumerate = exports.enumerate = function* enumerate(obj) {
for (let key of Object.keys(obj)) {
yield [key, obj[key]];
}
};
exports.randomNumericId = function randomNumericId() {
return Math.round((new Date()).getTime() + (Math.random(0, 1000) * 100));
};
exports.moveToIndex = function moveToIndex(arr, currentIndex, newIndex) {
if (newIndex >= arr.length) {
var k = newIndex - arr.length;
while ((k--) + 1) {
arr.push(undefined);
}
}
arr.splice(newIndex, 0, arr.splice(currentIndex, 1)[0]);
return arr;
};
exports.setPageTitle = function setPageTitle(title = '') {
if (typeof document === 'undefined' || typeof document.title === 'undefined') {
return null;
}
if (!Array.isArray(title)) {
title = [title];
}
// Always append with the site title
if (title.indexOf('Homehapp') === -1) {
title.push('Homehapp');
}
document.title = title.join(' | ');
};
exports.initMetadata = function initMetadata(res) {
if (typeof res.locals === 'undefined') {
res.locals = {};
}
if (typeof res.locals.openGraph === 'undefined') {
res.locals.openGraph = {
'og:image': []
};
}
if (typeof res.locals.metadatas === 'undefined') {
res.locals.metadatas = [];
}
};
exports.setLastMod = function setLastMod(objects, res) {
let lastMod = null;
if (!Array.isArray(objects)) {
objects = [objects];
}
for (let object of objects) {
if (!object || typeof object.updatedAt === 'undefined') {
continue;
}
try {
lastMod = Math.max(lastMod, object.updatedAt);
} catch (error) {
debug('Failed to use object.updatedAt, but continue as it is nothing fatal');
}
}
if (!res) {
debug('Cannot set the last modified meta tags, missing argument `res`');
}
if (lastMod && res) {
exports.initMetadata(res);
let date = new Date(lastMod);
try {
res.locals.openGraph['og:updated_time'] = date.toISOString();
res.locals.metadatas.push({
'http-equiv': 'last-modified',
'content': res.locals.openGraph['og:updated_time']
});
} catch (error) {
debug('Failed to set the last-modified', error.message);
}
}
return lastMod;
};
exports.createNotification = function createNotification(d) {
if (typeof document === 'undefined') {
console.error('document is not defined');
return null;
}
let container = document.getElementById('notifications');
let data = {
type: d.type || 'info',
label: d.label || null,
message: d.message || '',
duration: d.duration || 5
};
// Translate table for wider support range of type keywords
let translate = {
error: 'danger'
};
if (typeof translate[data.type] !== 'undefined') {
data.type = translate[data.type];
}
// Set duration to zero if the original duration was not set for
// danger type
if (data.type === 'danger' && !d.duration) {
data.duration = 0;
}
let notification = document.createElement('div');
notification.className = 'notification';
let alert = document.createElement('div');
alert.className = `data alert-${data.type} alert`;
let message = document.createElement('message');
if (data.label) {
message.innerHTML = `<strong>${data.label}:</strong> ${data.message}`;
} else {
message.innerHTML = data.message;
}
let closeNotification = function closeNotification() {
if (notification.hover) {
setTimer();
return false;
}
notification.className += ' away';
// Remove the DOM node after a delay, allowing the animations to finish
// setTimeout(function() {
// if (notification.parentNode) {
// // notification.parentNode.removeChild(notification);
// }
// }, 2000);
};
let forceCloseNotification = function forceCloseNotification() {
notification.hover = false;
closeNotification();
};
let setTimer = function setTimer() {
if (data.duration > 0) {
setTimeout(closeNotification, data.duration * 1000);
}
};
setTimer();
let close = document.createElement('span');
close.className = 'close';
close.textContent = '×';
close.addEventListener('click', forceCloseNotification);
alert.appendChild(message);
alert.appendChild(close);
notification.appendChild(alert);
container.appendChild(notification);
notification.addEventListener('mouseover', () => {
notification.hover = true;
});
notification.addEventListener('mouseout', () => {
notification.hover = false;
});
// Close with a slight delay to give user time to see the notification
// at least once
notification.close = function() {
setTimeout(forceCloseNotification, 500);
};
return notification;
};
let cloudinaryParamMap = {
w: 'width',
h: 'height',
f: 'format',
c: 'mode',
q: 'quality',
g: 'gravity'
};
exports.parseCloudinaryTransformation = function parseCloudinaryTransformation(url) {
let paramMap = cloudinaryParamMap;
let regs;
let rval = {};
if (regs = url.match(/upload\/([^\/]+?)\/v[0-9]+/)) {
regs[1].split(',').map((attr) => {
let parts = attr.split('_');
let k = parts[0];
if (typeof paramMap[k] === 'undefined') {
return null;
}
let key = paramMap[k];
switch (key) {
case 'width':
case 'height':
rval[key] = Number(parts[1]);
break;
default:
rval[key] = parts[1];
}
});
}
return rval;
};
exports.toCloudinaryTransformation = function toCloudinaryTransformation(transformations) {
if (typeof transformations === 'string') {
return transformations;
}
if (Array.isArray(transformations)) {
return transformations.map((transformation) => {
return exports.toCloudinaryTransformation(transformation);
}).join('|');
}
let paramMap = {};
for (let k in cloudinaryParamMap) {
paramMap[cloudinaryParamMap[k]] = k;
}
try {
let rval = [];
for (let k in transformations) {
let v = transformations[k];
if (typeof paramMap[k] !== 'undefined') {
key = paramMap[k];
} else {
key = k;
}
rval.push(`${k}_${v}`);
}
return rval;
} catch (error) {
return '';
}
return String(transformations) || '';
};
<file_sep>import QueryBuilder from '../../../lib/QueryBuilder';
//import {/*NotImplemented, */BadRequest} from '../../../lib/Errors';
let debug = require('debug')('/api/homes');
exports.registerRoutes = (app) => {
const QB = new QueryBuilder(app);
let populate = {
'location.neighborhood': {
select: 'uuid title slug area'
},
agents: {},
createdBy: {},
updatedBy: {}
};
app.get('/api/homes', app.authenticatedRoute, function(req, res, next) {
QB
.forModel('Home')
.parseRequestArguments(req)
.populate(populate)
.findAll()
.fetch()
.then((result) => {
res.json({
status: 'ok',
homes: result.models.map((home) => {
return home.toJSON();
})
});
})
.catch(next);
});
app.get('/api/homes/orphans', app.authenticatedRoute, function(req, res, next) {
let rval = [];
QB
.forModel('home')
.query({
createdBy: null
})
.findAll()
.fetch()
.then((result) => {
let promises = result.models.map((home) => {
let createdBy = home.updatedBy || req.user.id();
debug('Update', home.homeTitle, home.slug, home.updatedBy, createdBy);
return QB
.forModel('Home')
.populate(populate)
.findByUuid(home.uuid)
.updateNoMultiset({
createdBy: createdBy
})
.then((model) => {
debug('updated');
rval.push(model);
Promise.resolve();
})
.catch((err) => {
debug('update failed', err);
Promise.reject(err);
});
});
Promise.all(promises)
.then(() => {
res.json({
status: 'ok',
homes: rval
});
});
})
.catch(next);
});
app.post('/api/homes', app.authenticatedRoute, function(req, res, next) {
debug('Admin create home');
//debug('req.body', req.body);
let data = req.body.home;
// if (!data.description) {
// return next(new BadRequest('invalid request body'));
// }
if (req.user) {
data.createdBy = req.user.id;
data.updatedBy = req.user.id;
}
function createHome() {
return QB
.forModel('Home')
.populate(populate)
.createNoMultiset(data)
.then((model) => {
res.json({
status: 'ok',
home: model
});
})
.catch(next);
}
if (data.location.neighborhood) {
let neighborhoodUuid = data.location.neighborhood;
data.location.neighborhood = null;
QB
.forModel('Neighborhood')
.findByUuid(neighborhoodUuid)
.fetch()
.then((result) => {
debug('Got neighborhood', result.model.title, result.model.id);
data.location.neighborhood = result.model.id;
createHome(data);
})
.catch((nhError) => {
app.log.error(`Error fetching Neighborhood: ${nhError.message}`);
createHome(data);
});
} else {
createHome(data);
}
});
app.get('/api/homes/:uuid', app.authenticatedRoute, function(req, res, next) {
debug('API fetch home with uuid', req.params.uuid);
QB
.forModel('Home')
.populate(populate)
.findByUuid(req.params.uuid)
.fetch()
.then((result) => {
res.json({
status: 'ok',
home: result.home
});
})
.catch(next);
});
let updateHome = function updateHome(uuid, data) {
debug('Update home with data', data);
if (data.agents) {
//let agents = [];
debug('Get agents');
let ids = [];
let uuids = [];
for (let agent of data.agents) {
if (typeof agent === 'object' && agent.id) {
agent = agent.id;
}
if (agent.toString().match(/^[0-9a-f]{8}\-[0-9a-f]{4}\-[0-9a-f]{4}\-[0-9a-f]{4}\-[0-9a-f]{12}$/)) {
// a7b4ca90-6ce4-40a2-bf49-bca9f6219700
debug('Matched UUID', agent);
uuids.push(agent.toString());
} else {
debug('Did not match UUID', agent);
ids.push(agent);
}
}
debug('Get for', uuids);
if (uuids.length) {
debug('Got UUIDS', uuids);
return new Promise((resolve) => {
QB.forModel('Agent')
.query({
uuid: {
$in: uuids
}
})
.findAll()
.fetch()
.then((result) => {
for (let agent of result.models) {
debug('Got agent', agent);
ids.push(agent.id);
}
data.agents = ids;
debug('Update with agents', data.agents);
updateHome(uuid, data)
.then((model) => {
resolve(model);
});
})
.catch((err) => {
debug('Failed', err);
});
});
}
}
if (data.location && data.location.neighborhood && String(data.location.neighborhood).match(/[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{8}/)) {
debug('Get neighborhood', data.location.neighborhood);
return new Promise((resolve) => {
QB
.forModel('Neighborhood')
.findByUuid(data.location.neighborhood)
.fetch()
.then((result) => {
debug('Got neighborhood', result.model.title, result.model.id);
data.location.neighborhood = result.model;
QB
.forModel('Home')
.findByUuid(uuid)
.updateNoMultiset(data)
.then((model) => {
debug('Updated', model);
resolve(model);
})
.catch((err) => {
debug('Failed', err);
});
});
});
}
return QB
.forModel('Home')
.findByUuid(uuid)
.updateNoMultiset(data);
};
app.put('/api/homes/:uuid', app.authenticatedRoute, function(req, res, next) {
debug('API update home with uuid', req.params.uuid);
//debug('req.body', req.body);
let data = req.body.home;
if (req.user) {
data.updatedBy = req.user.id;
}
updateHome(req.params.uuid, data)
.then((model) => {
res.json({
status: 'ok',
home: model
});
})
.catch(next);
});
// app.patch('/api/homes/:uuid', function(req, res, next) {
// debug('API update home with uuid', req.params.uuid);
// //debug('req.body', req.body);
//
// let data = req.body.home;
//
// updateHome(req.params.uuid, data)
// .then((model) => {
// res.json({
// status: 'ok', home: model
// });
// })
// .catch(next);
// });
app.delete('/api/homes/:uuid', app.authenticatedRoute, function(req, res, next) {
QB
.forModel('Home')
.findByUuid(req.params.uuid)
.remove()
.then((result) => {
res.json({
status: 'deleted',
home: result.model
});
})
.catch(next);
});
};
<file_sep>import Alt from 'alt';
// import { snapshot } from 'alt/lib/utils/StateFunctions';
//import chromeDebug from 'alt/utils/chromeDebug';
const alt = new Alt({
serialize: function(data) {
// Custom serializer that eliminates circular references
let cache = [];
let val = JSON.stringify(data, function(key, value) {
if (typeof value === 'object' && value !== null) {
if (cache.indexOf(value) !== -1) {
// Circular reference found, discard key
return;
}
// Store value in our collection
cache.push(value);
}
return value;
});
// Send cache to garbage collector
cache = [];
return val;
}
});
// if (process.env.DEBUG) {
// chromeDebug(alt);
// }
module.exports = alt;
<file_sep>import BaseQueryBuilder from './BaseQueryBuilder';
import {NotFound} from '../../Errors';
import {merge} from '../../Helpers';
import async from 'async';
class UserQueryBuilder extends BaseQueryBuilder {
constructor(app) {
super(app, 'User');
}
initialize() {
}
// findAll() {
// this._queries.push((callback) => {
// let cursor = this.Model.find({
// deletedAt: null
// });
//
// if (this._opts.limit) {
// cursor.limit(this._opts.limit);
// }
// if (this._opts.sort) {
// cursor.sort(this._opts.sort);
// }
// if (this._opts.skip) {
// cursor.skip(this._opts.skip);
// }
// this._configurePopulationForCursor(cursor);
//
// cursor.exec((err, users) => {
// if (err) {
// return callback(err);
// }
// this.result.users = users;
// this.result.usersJson = users.map(user => {
// return user.toJSON();
// });
// callback();
// });
// });
//
// return this;
// }
findById(id) {
this._queries.push((callback) => {
let cursor = this.Model.findById(id);
this._configurePopulationForCursor(cursor);
cursor.exec((err, user) => {
if (err) {
return callback(err);
}
if (!user) {
return callback(new NotFound('user not found'));
}
this.result.model = user;
this.result.models = [user];
this.result.user = user;
this.result.userJson = user.toJSON();
this._loadedModel = user;
callback();
});
});
return this;
}
findByUuid(uuid) {
this._queries.push((callback) => {
let cursor = this.Model.findOne({
uuid: uuid,
deletedAt: null
});
this._configurePopulationForCursor(cursor);
cursor.exec((err, user) => {
if (err) {
return callback(err);
}
if (!user) {
return callback(new NotFound('user not found'));
}
this.result.user = user;
this.result.userJson = user.toJSON();
this._loadedModel = user;
callback();
});
});
return this;
}
findByUsername(username) {
this._queries.push((callback) => {
let cursor = this.Model.findOne({
username: username,
deletedAt: null
});
this._configurePopulationForCursor(cursor);
cursor.exec((err, user) => {
if (err) {
return callback(err);
}
if (!user) {
return callback(new NotFound('user not found'));
}
this.result.user = user;
this.result.userJson = user.toJSON();
this._loadedModel = user;
callback();
});
});
return this;
}
findByIdOrUsername(idOrUsername) {
this._queries.push((callback) => {
async.seq(
(cb) => {
this.Model.findOne({
uuid: idOrUsername,
deletedAt: null
}).exec((err, user) => {
cb(err, user);
});
},
(user, cb) => {
if (user) {
return cb(null, user);
}
this.Model.findOne({
username: idOrUsername,
deletedAt: null
}).exec((err, user2) => {
cb(err, user2);
});
}
)((err, user) => {
if (err) {
return callback(err);
}
if (!user) {
return callback(new NotFound('user not found'));
}
this.result.user = user;
this.result.userJson = user.toJSON();
this._loadedModel = user;
callback();
});
});
return this;
}
findByDeviceId(deviceId) {
this._queries.push((callback) => {
let findQuery = {
$or: [
{'deviceId.ios': deviceId},
{'deviceId.android': deviceId}
],
deletedAt: null
};
if (this._opts.query) {
findQuery = merge(findQuery, this._opts.query);
}
this.Model.findOne(findQuery).exec((err, user) => {
if (err) {
return callback(err);
}
if (!user) {
return callback(new NotFound('user not found'));
}
this.result.user = user;
this.result.userJson = user.toJSON();
this._loadedModel = user;
callback();
});
});
return this;
}
findByServiceId(service, id) {
this._queries.push((callback) => {
let findQuery = {
deletedAt: null
};
findQuery[`_service.${service}.id`] = id;
if (this._opts.query) {
findQuery = merge(findQuery, this._opts.query);
}
this.Model.findOne(findQuery).exec((err, user) => {
if (err) {
return callback(err);
}
if (!user) {
return callback(new NotFound('user not found'));
}
this.result.user = user;
this.result.userJson = user.toJSON();
this._loadedModel = user;
callback();
});
});
return this;
}
}
module.exports = UserQueryBuilder;
<file_sep>/* global ga, window */
import React from 'react';
let debug = require('debug')('GoogleAnalytics');
export default class GoogleAnalytics extends React.Component {
constructor() {
super();
this.init = false;
}
componentDidMount() {
debug('componentDidMount');
}
// shouldComponentUpdate() {
// debug('shouldComponentUpdate');
// return false;
// }
render() {
if (typeof ga !== 'undefined' && typeof window !== 'undefined') {
ga('send', 'pageview', window.location.pathname);
}
return null;
}
}
<file_sep>import QueryBuilder from '../../../lib/QueryBuilder';
// import {NotImplemented, BadRequest} from '../../../lib/Errors';
let debug = require('debug')('/api/contact');
exports.registerRoutes = (app) => {
const QB = new QueryBuilder(app);
let createContact = function createContact(res, next, data) {
QB
.forModel('Contact')
.create(data)
.then((model) => {
res.json({
status: 'ok',
contact: model
});
})
.catch(next);
};
app.post('/api/contacts', function(req, res, next) {
debug('Create a new contact request');
//debug('req.body', req.body);
let data = req.body.contact;
if (req.user) {
data.createdBy = req.user.id;
data.updatedBy = req.user.id;
}
if (data.home) {
QB
.forModel('Home')
.findByUuid(data.home)
.fetch()
.then((result) => {
data.home = result.model;
debug('Link the contact request to home', result.model.homeTitle);
createContact(res, next, data);
})
.catch(next);
} else {
createContact(res, next, data);
}
});
};
<file_sep>exports.registerRoutes = (app) => {
/**
* @apiDefine ImageSuccess
* @apiVersion 1.0.1
*
* @apiSuccess {String} url Image URL
* @apiSuccess {String} alt Brief image description
* @apiSuccess {Number} width Width of the image
* @apiSuccess {Number} height Height of the image
* @apiSuccess {Number} aspectRatio Width/height ratio of the image
*/
/**
* @apiDefine ImageSuccessJSON
* @apiVersion 1.0.1
*
* @apiSuccessExample {json} Image JSON
* {
* "url": "https://...",
* "alt": "...",
* "width": ...,
* "height": ...,
* "aspectRatio": ...,
* "align": "...",
* "valign": "...",
* }
*/
/**
* @apiDefine ImageRequestJSON
* @apiVersion 1.0.1
* @apiParamExample {json} Request-Example
* {
* "url": "https://...",
* "alt": "...",
* "width": 1920,
* "height": 1080,
* "fixed": false,
* "align": "center",
* "valign": "middle"
* }
*/
/**
* @api {any} /api/* Images
* @apiVersion 1.0.1
* @apiName Images
* @apiGroup Shared
* @apiUse ImageSuccess
* @apiUse ImageSuccessJSON
* @apiUse ImageRequestJSON
*
* @apiDescription Every Image uses the following definition
*
* @apiParam {String} url Image URL
* @apiParam {String} [alt] Alt text or brief description
* @apiParam {Number} [width] Image width
* @apiParam {Number} [height] Image height
* @apiParam {Number} [aspectRatio] Aspect ratio
* @apiParam {Boolean} [fixed] Flag for fixing the image position for parallax scrolling
* @apiParam {String='left', 'center', 'right'} [align='center'] Horizontal position of the image
* @apiParam {String='top', 'middle', 'bottom'} [valign='middle'] Vertical position of the image
*/
/**
* @apiDefine VideoSuccess
* @apiVersion 1.0.1
*
* @apiSuccess {String} url Video URL
* @apiSuccess {String} alt Brief video description
* @apiSuccess {Number} width Width of the video
* @apiSuccess {Number} height Height of the video
* @apiSuccess {Array} derived An array of derived video objects
* @apiSuccess {Object} derived.0 An example of a derived video object
* @apiSuccess {String} derived.0.url Derived video URL
* @apiSuccess {String} derived.0.format Derived video format
* @apiSuccess {Number} derived.0.width Derived video width
* @apiSuccess {Number} derived.0.height Derived video height
*/
/**
* @apiDefine VideoSuccessJSON
* @apiVersion 1.0.1
*
* @apiSuccessExample {json} Video JSON
* {
* "url": "https://...",
* "alt": "...",
* "width": ...,
* "height": ...,
* "derived": [
* {
* "url": "https://...",
* "width": ...,
* "height": ...,
* "format": "webm"
* },
* ...,
* {
* "url": "https://...",
* "width": ...,
* "height": ...,
* "format": "mp4"
* }
* ]
* }
*/
/**
* @apiDefine VideoRequestJSON
* @apiVersion 1.0.1
* @apiParamExample {json} Request-Example
* {
* "url": "https://...",
* "alt": "...",
* "width": 1920,
* "height": 1080,
* "fixed": false,
* "align": "center",
* "valign": "middle",
* "derived": [
* {
* "url": "https://...",
* "width": ...,
* "height": ...,
* "format": "webm"
* },
* {
* "url": "https://...",
* "width": ...,
* "height": ...,
* "format": "mp4"
* ]
* }
*/
/**
* @api {any} /api/* Videos
* @apiVersion 1.0.1
* @apiName Videos
* @apiGroup Shared
* @apiUse VideoSuccess
* @apiUse VideoSuccessJSON
* @apiUse VideoRequestJSON
*
* @apiDescription Every Video uses the following definition
*
* @apiParam {String} url Video URL
* @apiParam {String} [alt] Alt text or brief description
* @apiParam {Number} [width] Video width
* @apiParam {Number} [height] Video height
* @apiParam {boolean} [fixed] Flag for fixing the video position for parallax scrolling
* @apiParam {Array} [derived] Derived videos
* @apiParam {Object} [derived.0] Derived video object, which - when presented - has to fulfill its required fields
* @apiParam {String} derived.0.video.url Derived video URL
* @apiParam {String} derived.0.video.format Derived video format
* @apiParam {Number} [derived.0.video.width] Derived video width
* @apiParam {Number} [derived.0.video.height] Derived video height
*/
};
<file_sep>import { loadCommonPlugins, commonJsonTransform, getImageSchema, getStoryBlockSchema, populateMetadata } from './common';
exports.loadSchemas = function (mongoose, next) {
let Schema = mongoose.Schema;
let schemas = {};
schemas.CityImage = getImageSchema(Schema);
schemas.CityStoryBlock = getStoryBlockSchema(Schema);
// schemas.CityImage.virtual('aspectRatio').get(function () {
// return this.width / this.height;
// });
schemas.City = new Schema(populateMetadata({
uuid: {
type: String,
index: true,
unique: true
},
slug: {
type: String,
index: true,
required: true
},
// Details
title: {
type: String,
default: ''
},
aliases: {
type: [String],
default: []
},
description: {
type: String,
default: ''
},
location: {
country: {
type: String,
default: 'Great Britain'
},
coordinates: {
type: [Number],
default: [],
index: '2dsphere'
}
},
// story: {
// enabled: {
// type: Boolean,
// default: false
// },
// blocks: [schemas.CityStoryBlock]
// },
// Flags
visible: {
type: Boolean,
index: true,
default: true
}
}));
schemas.City.virtual('pageTitle').get(function () {
let title = [this.CityTitle];
if (this.location.city) {
title.push(this.location.city.title);
}
return title.join(' | ');
});
schemas.City.statics.editableFields = function () {
return [
'title', 'description', 'location', 'images'
];
};
Object.keys(schemas).forEach((name) => {
loadCommonPlugins(schemas[name], name, mongoose);
schemas[name].options.toJSON.transform = (doc, ret) => {
return commonJsonTransform(ret);
};
if (name === 'CityStoryBlock' || name === 'CityAttribute') {
schemas[name].options.toJSON.transform = (doc, ret) => {
ret = commonJsonTransform(ret);
delete ret.id;
return ret;
};
}
});
next(schemas);
};
<file_sep>#!/bin/bash
# Env says we're using SSL
if [ -n "${ENABLE_SSL+1}" ] && [ "${ENABLE_SSL,,}" = "true" ]; then
echo "Enabling SSL..."
cp /usr/src/proxy_ssl.conf /etc/nginx/conf.d/proxy.conf
else
# No SSL
cp /usr/src/proxy_nossl.conf /etc/nginx/conf.d/proxy.conf
fi
# If the SERVICE_HOST_ENV_NAME and SERVICE_PORT_ENV_NAME vars are provided,
# they point to the env vars set by Kubernetes that contain the actual
# target address and port. Override the default with them.
if [ -n "${SERVICE_HOST_ENV_NAME+1}" ]; then
TARGET_SERVICE=${!SERVICE_HOST_ENV_NAME}
fi
if [ -n "${SERVICE_PORT_ENV_NAME+1}" ]; then
TARGET_SERVICE="$TARGET_SERVICE:${!SERVICE_PORT_ENV_NAME}"
fi
echo "Using target service ${TARGET_SERVICE}"
# Tell nginx the address and port of the service to proxy to
sed -i "s/{{TARGET_SERVICE}}/${TARGET_SERVICE}/g;" /etc/nginx/conf.d/proxy.conf
echo "Starting nginx..."
nginx -g 'daemon off;'
<file_sep>import React from 'react';
import RouteNotFound from './RouteNotFound';
import ErrorPage from '../../../common/components/Layout/ErrorPage';
import ContentBlock from '../../../common/components/Widgets/ContentBlock';
export default class HomeRouteNotFound extends RouteNotFound {
componentWillMount() {
super.componentWillMount();
this.error.message = 'Home not found';
}
render() {
let error = this.error;
return (
<ErrorPage {...error}>
<ContentBlock>
<h2>Now what?</h2>
<p>You can always:</p>
<ul>
<li>Lorem ipsum</li>
</ul>
</ContentBlock>
</ErrorPage>
);
}
}
<file_sep>exports.registerRoutes = (app) => {
/**
* @apiDefine MobileRequestHeaders
* @apiVersion 1.0.1
*
* @apiHeader {String} X-Homehapp-Api-Key Api key for this project
* @apiHeader {String} X-Homehapp-Client Client identifier. In format: platform/manufacturer;deviceType;model;OS version/deviceID/deviceLanguageCode
* @apiHeader {String} [X-Homehapp-Auth-Token] Unique session token for logged in user
* @apiHeader {String} [X-Homehapp-Api-Version=0] Version of the API in use
*
* @apiHeaderExample {json} Required headers with authentication:
* {
* "X-Homehapp-Api-Key": "API KEY",
* "X-Homehapp-Client": "IOS/Apple;iPhone Simulator;x86_64;8.4.0/C9853654-3EBF-4BB5-9039-23DD0404A968/en",
* "X-Homehapp-Auth-Token": "USER TOKEN (IF APPLICAPLE)"
* }
*
* @apiHeaderExample {json} Required headers without authentication:
* {
* "X-Homehapp-Api-Key": "API KEY",
* "X-Homehapp-Client": "IOS/Apple;iPhone Simulator;x86_64;8.4.0/C9853654-3EBF-4BB5-9039-23DD0404A968/en"
* }
*/
/**
* @apiDefine MobileRequestHeadersUnauthenticated
* @apiVersion 1.0.1
*
* @apiHeader {String} X-Homehapp-Api-Key Api key for this project
* @apiHeader {String} X-Homehapp-Client Client identifier. In format: platform/manufacturer;deviceType;model;OS version/deviceID/deviceLanguageCode
* @apiHeader {String} [X-Homehapp-Api-Version=0] Version of the API in use
*
* @apiHeaderExample {json} Required headers:
* {
* "X-Homehapp-Api-Key": "API KEY",
* "X-Homehapp-Client": "IOS/Apple;iPhone Simulator;x86_64;8.4.0/C9853654-3EBF-4BB5-9039-23DD0404A968/en"
* }
*/
/**
* @apiDefine MobileRequestHeadersAuthenticated
* @apiVersion 1.0.1
*
* @apiHeader {String} X-Homehapp-Api-Key Api key for this project
* @apiHeader {String} X-Homehapp-Client Client identifier. In format: platform/manufacturer;deviceType;model;OS version/deviceID/deviceLanguageCode
* @apiHeader {String} X-Homehapp-Auth-Token Unique session token for logged in user
* @apiHeader {String} [X-Homehapp-Api-Version=0] Version of the API in use
*
* @apiHeaderExample {json} Required headers:
* {
* "X-Homehapp-Api-Key": "API KEY",
* "X-Homehapp-Client": "IOS/Apple;iPhone Simulator;x86_64;8.4.0/C9853654-3EBF-4BB5-9039-23DD0404A968/en",
* "X-Homehapp-Auth-Token": "USER TOKEN (IF APPLICAPLE)"
* }
*/
// perform device info logging
app.all('/api/*', app.logDevices);
};
<file_sep>import alt from '../../common/alt';
@alt.createActions
class ContactListActions {
updateContacts(contacts) {
this.dispatch(contacts);
}
fetchContacts(skipCache) {
this.dispatch(skipCache);
}
fetchFailed(error) {
this.dispatch(error);
}
}
module.exports = ContactListActions;
<file_sep>import React from 'react';
import ContentBlock from '../Widgets/ContentBlock';
export default class HTMLContent extends React.Component {
static propTypes = {
content: React.PropTypes.string.isRequired,
className: React.PropTypes.string
};
static defaultProps = {
className: null
};
render() {
let classes = [
'widget',
'content-block'
];
if (this.props.className) {
classes.push(this.props.className);
}
return (
<ContentBlock>
<div className='widget html-content' dangerouslySetInnerHTML={{__html: this.props.content}}></div>
</ContentBlock>
);
}
}
<file_sep>import PageListActions from '../actions/PageListActions';
import PageListSource from '../sources/PageListSource';
import ListStore from '../../common/stores/BaseListStore';
// let debug = require('debug')('PageListStore');
export default ListStore.generate('PageListStore', {
actions: PageListActions,
source: PageListSource,
listeners: {
handleUpdateItem: {
action: PageListActions.UPDATE_ITEM,
method: function handleUpdateItem(model) {
this.error = null;
if (!this.getInstance().isLoading()) {
setTimeout(() => {
this.getInstance().updateItem(model);
});
}
}
}
}
});
<file_sep>import React from 'react';
import ContentBlock from '../../../common/components/Widgets/ContentBlock';
import ApplicationStore from '../../../common/stores/ApplicationStore';
let debug = require('debug')('Login');
export default class Login extends React.Component {
static propTypes = {
context: React.PropTypes.object
}
static contextTypes = {
router: React.PropTypes.func
}
constructor() {
super();
this.stateListener = this.onStateChange.bind(this);
}
componentDidMount() {
if (!this.state.csrf) {
ApplicationStore.getState();
}
}
onStateChange(state) {
debug('got state', state);
this.setState(state);
}
state = {
csrf: ApplicationStore.getState().csrf,
redirectUrl: ApplicationStore.getState().redirectUrl
}
getRedirectUrl() {
if (typeof window !== 'undefined' && window.location && window.location.search) {
let regs = window.location.search.match(/redirectUrl=(.+?)(&|$)/);
if (regs && regs[1]) {
return decodeURIComponent(regs[1]);
}
}
if (this.state.redirectUrl) {
return this.state.redirectUrl;
}
if (this.context && this.context.router) {
return this.context.router.makeHref('homepage');
}
return '/';
}
render() {
let url = this.getRedirectUrl();
return (
<ContentBlock>
<div id='loginForm'>
<h3>Login</h3>
<form method='POST' action='/auth/login'>
<div className='form'>
<input type='hidden' name='_csrf' defaultValue={this.state.csrf} />
<input type='hidden' name='redirectTo' defaultValue={url} />
<input type='email' name='username' required placeholder='Username' />
<input type='<PASSWORD>' name='password' required placeholder='<PASSWORD>' />
<input type='submit' value='Login ›' />
</div>
</form>
</div>
</ContentBlock>
);
}
}
<file_sep>import SourceBuilder from '../../common/sources/Builder';
import CityListActions from '../actions/CityListActions';
// let debug = require('debug')('CityListSource');
export default SourceBuilder.build({
name: 'CityListSource',
actions: {
base: CityListActions,
error: CityListActions.requestFailed
},
methods: {
fetchItems: {
remote: {
method: 'get',
uri: '/api/cities',
params: null,
response: {
key: 'cities'
}
},
local: null,
actions: {
success: CityListActions.updateItems
}
}
}
});
<file_sep>import QueryBuilder from '../../lib/QueryBuilder';
exports.registerRoutes = (app) => {
const QB = new QueryBuilder(app);
app.get('/neighborhoods', app.authenticatedRoute, function(req, res, next) {
console.log('fetch neighborhoods');
console.log('req.query', req.query);
QB
.forModel('Neighborhood')
.parseRequestArguments(req)
.findAll()
.fetch()
.then((result) => {
res.locals.data.NeighborhoodListStore = {
neighborhoods: result.neighborhoodsJson
};
next();
})
.catch(next);
});
let redirectBySlug = (req, res, next) => {
QB
.forModel('Neighborhood')
.parseRequestArguments(req)
.findBySlug(req.params.slug)
.fetch()
.then((result) => {
res.redirect(301, `/neighborhoods/${result.model.uuid}`);
})
.catch(() => {
next();
});
};
app.get('/neighborhoods/:city/:slug', app.authenticatedRoute, function(req, res, next) {
return redirectBySlug(req, res, next);
});
app.get('/neighborhoods/:slug', app.authenticatedRoute, function(req, res, next) {
return redirectBySlug(req, res, next);
});
};
<file_sep>import React from 'react';
export default class CityContainer extends React.Component {
componentDidMount() {
window.location.href = '/neighborhoods/london';
}
render() {
return null;
}
}
<file_sep>import React from 'react';
import { Link } from 'react-router';
import Row from 'react-bootstrap/lib/Row';
import Col from 'react-bootstrap/lib/Col';
import Panel from 'react-bootstrap/lib/Panel';
import InputWidget from '../Widgets/Input';
import Button from 'react-bootstrap/lib/Button';
import Well from 'react-bootstrap/lib/Well';
import HomeStore from '../../stores/HomeStore';
import HomeActions from '../../actions/HomeActions';
import UploadArea from '../../../common/components/UploadArea';
import UploadAreaUtils from '../../../common/components/UploadArea/utils';
import { randomNumericId, merge, createNotification } from '../../../common/Helpers';
import ImageList from '../Widgets/ImageList';
import NeighborhoodSelect from '../Widgets/NeighborhoodSelect';
import ApplicationStore from '../../../common/stores/ApplicationStore';
import EditDetails from '../Shared/EditDetails';
import PlacePicker from '../../../common/components/Widgets/PlacePicker';
let debug = require('../../../common/debugger')('HomesEditDetails');
let marked = require('marked');
export default class HomesEditDetails extends EditDetails {
static propTypes = {
home: React.PropTypes.object.isRequired,
context: React.PropTypes.object
}
static contextTypes = {
router: React.PropTypes.func
}
constructor(props) {
super(props);
this.storeListener = this.onHomeStoreChange.bind(this);
this.uploadListener = this.onUploadChange.bind(this);
this.imageUploaderInstanceId = randomNumericId();
this.floorPlanUploaderInstanceId = randomNumericId();
this.onRemoveImageClicked = this.onRemoveImageClicked.bind(this);
this.setCoordinates = this.setCoordinates.bind(this);
this.onFormChange = this.onFormChange.bind(this);
if (props.home) {
this.setInitialLocation(props.home.location);
this.state.currentAttributes = props.home.attributes || [
{
name: '', value: '', valueType: 'string'
}
];
this.state.images = props.home.images || [];
this.state.brochures = props.home.brochures || [];
}
}
state = {
error: null,
uploads: UploadAreaUtils.UploadStore.getState().uploads,
home: null,
currentAttributes: [],
images: [],
brochures: [],
coordinates: [],
lat: null,
lng: null
}
componentDidMount() {
HomeStore.listen(this.storeListener);
this.setState({home: this.home});
}
componentWillReceiveProps(props) {
debug('componentWillReceiveProps', props);
if (props.home) {
if (props.home.location.neighborhood) {
this.onNeighborhoodChange(props.home.location.neighborhood);
}
this.setState({
currentAttributes: props.home.attributes || {},
images: props.home.images || []
});
}
}
componentWillUnmount() {
HomeStore.unlisten(this.storeListener);
}
brochureTypes = {
floorplan: 'Floorplan',
epc: 'EPC',
brochure: 'Brochure'
}
onHomeStoreChange(state) {
debug('onHomeStoreChange', state);
this.setState(state);
}
onUploadChange(state) {
debug('onUploadChange', state);
this.setState({
uploads: UploadAreaUtils.UploadStore.getState().uploads
});
}
onFormChange(/*event*/) {
// let {type, target} = event;
// TODO: Validation could be done here
//debug('onFormChange', event, type, target);
//this.props.home.facilities = this.refs.facilities.getValue().split("\n");
}
onNeighborhoodChange(neighborhood) {
if (!this.home) {
return null;
}
if (!this.refs.placePicker) {
return null;
}
this.refs.placePicker.setArea(neighborhood.area);
}
onSave() {
debug('save', this.refs);
for (let key in this.refs) {
let ref = this.refs[key];
if (typeof ref.isValid !== 'function') {
continue;
}
if (!ref.isValid()) {
debug('Validation failed', ref);
let label = ref.props.label || 'Validation error';
let message = ref.message || 'Field failed the validation';
createNotification({
type: 'danger',
duration: 10,
label: label,
message: message
});
return false;
}
}
let images = [];
let brochures = [];
// Clean broken images
this.state.images.forEach((image) => {
if (image.url) {
images.push(image);
}
});
// Clean broken images
this.state.brochures.forEach((image) => {
if (image.url) {
brochures.push(image);
}
});
let id = null;
if (this.props.home) {
id = this.props.home.id;
}
debug('Coordinates', this.getCoordinates());
let homeProps = {
id: id,
title: this.refs.title.getValue(),
enabled: this.state.home.enabled,
announcementType: this.refs.announcementType.getValue(),
description: this.refs.description.getValue(),
location: {
address: {
street: this.refs.addressStreet.getValue(),
apartment: this.refs.addressApartment.getValue(),
city: this.refs.addressCity.getValue(),
zipcode: this.refs.addressZipcode.getValue(),
country: this.refs.addressCountry.getValue()
},
neighborhood: this.refs.addressNeighborhood.getValue(),
coordinates: this.getCoordinates()
},
costs: {
currency: this.refs.costsCurrency.getValue(),
sellingPrice: Number(this.refs.costsSellingPrice.getValue()),
councilTax: Number(this.refs.costsCouncilTax.getValue())
},
details: {
area: Number(this.refs.detailsArea.getValue())
},
properties: this.refs.properties.getValue(),
images: images,
brochures: brochures
};
this.saveHome(homeProps);
}
saveHome(homeProps) {
debug('saveHome', homeProps);
if (homeProps.id) {
return HomeActions.updateItem(homeProps);
}
return HomeActions.createItem(homeProps);
}
onCancel() {
React.findDOMNode(this.refs.homeDetailsForm).reset();
}
onRemoveAttributeClicked(index) {
let newAttributes = [];
this.state.currentAttributes.forEach((item, idx) => {
if (idx !== index) {
newAttributes.push(item);
}
});
if (!newAttributes.length) {
newAttributes.push({
name: '', value: '', valueType: 'string'
});
}
this.setState({currentAttributes: newAttributes});
}
onAddAttributeClicked(/*event*/) {
this.state.currentAttributes.push({
name: '', value: '', valueType: 'string'
});
this.setState({currentAttributes: this.state.currentAttributes});
}
onAttributeValueChanged(event, index, field) {
let newAttributes = this.state.currentAttributes;
if (!newAttributes[index]) {
newAttributes[index] = {
name: '', value: '', valueType: 'string'
};
}
newAttributes[index][field] = event.currentTarget.value;
this.setState({
currentAttributes: newAttributes
});
}
renderAttributeRow(index, attr, isLast) {
let actions = (
<Col md={2}>
<Button
bsStyle='danger'
bsSize='small'
onClick={() => this.onRemoveAttributeClicked(index)}>
-
</Button>
</Col>
);
if (isLast) {
actions = (
<Col md={2}>
<Button
bsStyle='danger'
bsSize='small'
onClick={() => this.onRemoveAttributeClicked(index)}>
-
</Button>
<Button
bsStyle='success'
bsSize='small'
ref='addAttributeButton'
onClick={this.onAddAttributeClicked.bind(this)}>
+
</Button>
</Col>
);
}
return (
<Row key={'attribute-' + index + '-' + attr.name}>
<Col md={4}>
<InputWidget
type='select'
addonBefore='Name'
placeholder='Select Attribute'
name={'attributes[' + index + '][name]'}
defaultValue={attr.name}
onChange={(event) => this.onAttributeValueChanged(event, index, 'name')}
>
<option value=''>Select Attribute</option>
<option value='floor'>Floor</option>
<option value='rooms'>Rooms</option>
<option value='elevator'>Elevator</option>
</InputWidget>
</Col>
<Col md={4}>
<InputWidget
type='text'
addonBefore='Value'
name={'attributes[' + index + '][value]'}
defaultValue={attr.value}
onChange={(event) => this.onAttributeValueChanged(event, index, 'value')}
/>
</Col>
{actions}
</Row>
);
}
propertiesChange(event) {
// debug('event', event.target.value);
let markdown = marked(event.target.value);
let node = React.findDOMNode(this.refs.propertiesPreview);
node.innerHTML = marked(markdown);
}
changeStatus(event) {
debug('changeStatus', event.target.value);
// this.onFormChange(event);
this.home = this.state.home || this.props.home;
let home = this.home;
home.announcementType = event.target.value;
this.setState({
home: home
});
return true;
}
toggleEnabled(event) {
this.home = this.state.home || this.props.home;
let home = this.home;
home.enabled = !(home.enabled);
this.setState({
home: home
});
return true;
}
render() {
debug('this.brochureTypes', this.brochureTypes);
this.handleErrorState();
if (HomeStore.isLoading()) {
this.handlePendingState();
return null;
}
this.handleRenderState();
let home = merge({
costs: {
currency: 'GBP'
},
details: '',
properties: ''
}, this.state.home || this.props.home || {});
let homeLocation = merge({
address: {
street: null,
apartment: null,
zipcode: null,
city: null,
country: 'GB'
},
coordinates: [this.state.lat, this.state.lng],
neighborhood: null
}, home.location || {});
this.home = home;
if (this.props.home) {
home.title = this.props.home.homeTitle;
}
if (this.state.home) {
home.title = this.state.home.homeTitle;
}
let countrySelections = this.getCountryOptions();
let lat = this.state.lat || 0;
let lng = this.state.lng || 0;
let area = null;
if (homeLocation.neighborhood && homeLocation.neighborhood.area) {
area = homeLocation.neighborhood.area;
if (!lat && homeLocation.neighborhood && homeLocation.neighborhood.location && homeLocation.neighborhood.location.coordinates && homeLocation.neighborhood.location.coordinates.length >= 2) {
lat = homeLocation.neighborhood.location.coordinates[0];
lng = homeLocation.neighborhood.location.coordinates[1];
}
}
debug('lat', lat, 'lng', lng, 'area', area);
let deleteLink = null;
let previewLink = null;
if (this.props.home) {
deleteLink = (<Link to='homeDelete' params={{id: this.props.home.id}} className='pull-right btn btn-danger btn-preview'>Delete</Link>);
previewLink = (
<a href={`${ApplicationStore.getState().config.siteHost}/homes/${this.props.home.slug}`}
target='_blank'
className='btn btn-primary'>
Preview
</a>
);
}
let propertiesPreview = marked(home.properties);
let properties = home.properties;
if (!properties && home.amenities && home.amenities.length) {
properties = home.amenities.join(`\n`);
}
debug('Render', home);
//debug('Neighborhood of this home', this.props.homeLocation.neighborhood);
let markdownExample = (
<p>Building<br />
<br />
- built in 1823<br />
- solid brick walls<br />
<br />
Amenities<br />
<br />
- sauna<br />
- gym<br />
</p>
);
let enabled = {};
if (home.enabled) {
enabled.checked = true;
}
return (
<Row>
<form name='homeDetails' ref='homeDetailsForm' method='POST'>
<Col md={10} sm={10}>
<Panel header='Common'>
<InputWidget
type='text'
ref='title'
label='Title'
placeholder='Title (optional)'
defaultValue={home.title}
onChange={this.onFormChange.bind(this)}
/>
{this.getSlug(home)}
<InputWidget
type='select'
ref='announcementType'
label='Announcement type'
defaultValue={home.announcementType}
onChange={this.changeStatus.bind(this)}
>
<option value='story'>This home has a story, but is not for sale or rent</option>
<option value='buy'>This home is for sale</option>
<option value='rent'>This home is for rent</option>
</InputWidget>
<InputWidget
type='checkbox'
ref='enabled'
label='Is the story published'
{...enabled}
onChange={this.toggleEnabled.bind(this)}
/>
<InputWidget
type='textarea'
ref='description'
label='Description'
placeholder='Write description'
defaultValue={home.description}
onChange={this.onFormChange.bind(this)}
required
/>
</Panel>
<Panel header='Location'>
<InputWidget
type='text'
ref='addressStreet'
label='Street Address'
placeholder='ie. Kauppakartanonkuja 3 B'
defaultValue={homeLocation.address.street}
onChange={this.onFormChange.bind(this)}
/>
<InputWidget
type='text'
ref='addressApartment'
label='Apartment'
placeholder='ie. 22'
defaultValue={homeLocation.address.apartment}
onChange={this.onFormChange.bind(this)}
/>
<NeighborhoodSelect
ref='addressNeighborhood'
selected={homeLocation.neighborhood}
onChange={this.onNeighborhoodChange.bind(this)}
/>
<InputWidget
type='text'
ref='addressCity'
label='City'
placeholder='ie. Helsinki'
defaultValue={homeLocation.address.city}
onChange={this.onFormChange.bind(this)}
/>
<InputWidget
type='text'
ref='addressZipcode'
label='Post code'
placeholder=''
defaultValue={homeLocation.address.zipcode}
onChange={this.onFormChange.bind(this)}
/>
<InputWidget
type='select'
ref='addressCountry'
label='Country'
placeholder='Select Country'
defaultValue={homeLocation.address.country}
onChange={this.onFormChange.bind(this)}>
<option value=''>Select country</option>
{countrySelections}
</InputWidget>
<PlacePicker lat={this.state.lat} lng={this.state.lng} area={area} onChange={this.setCoordinates} ref='placePicker' />
<InputWidget
label='Coordinates'
help='Optional coordinates for the home' wrapperClassName='wrapper'>
<Row>
<Col xs={6}>
<InputWidget
type='text'
ref='locationLatitude'
addonBefore='Latitude:'
value={this.state.lat}
readOnly
/>
</Col>
<Col xs={6}>
<InputWidget
type='text'
ref='locationLongitude'
addonBefore='Longitude:'
value={this.state.lng}
readOnly
/>
</Col>
</Row>
</InputWidget>
</Panel>
<Panel header='Specifications'>
<InputWidget
type='text'
ref='detailsArea'
label='Living area (square feet)'
placeholder='1000'
defaultValue={home.details.area}
onChange={this.onFormChange.bind(this)}
pattern='([0-9]*)(\.[0-9]+)?'
patternError='Please enter a valid number (e.g. 123.45) without any units'
/>
<InputWidget
type='textarea'
ref='properties'
label='Amenities'
placeholder='(optional)'
className='xlarge'
defaultValue={properties}
onInput={this.propertiesChange.bind(this)}
onChange={this.onFormChange.bind(this)}
/>
<Row>
<Col md={6}>
<p>Preview:</p>
<div ref='propertiesPreview' className='markdown-preview' dangerouslySetInnerHTML={{__html: propertiesPreview}}></div>
</Col>
<Col md={6}>
<p>Example</p>
<code className='preline markdown-example'>{markdownExample}</code>
</Col>
</Row>
</Panel>
<Panel header='Pricing information' className={(home.announcementType === 'story') ? 'hidden' : ''}>
<InputWidget
type='select'
ref='costsCurrency'
label='Used currency'
placeholder='Select Applied Currency'
defaultValue={home.costs.currency}
onChange={this.onFormChange.bind(this)}>
<option value='GBP'>British Pounds</option>
<option value='EUR'>Euro</option>
<option value='SUD'>US Dollars</option>
</InputWidget>
<div className={(home.announcementType === 'rent') ? 'hidden' : ''}>
<InputWidget
type='text'
ref='costsSellingPrice'
label='Selling price'
placeholder='(optional)'
defaultValue={home.costs.sellingPrice}
onChange={this.onFormChange.bind(this)}
pattern='([0-9]*)(\.[0-9]+)?'
patternError='Please enter a valid number (e.g. 123.45) without any units'
/>
</div>
<div className={(home.announcementType !== 'rent') ? 'hidden' : ''}>
<InputWidget
type='text'
ref='costsRentalPrice'
label='Rental price'
placeholder='1234.56'
onChange={this.onFormChange.bind(this)}
pattern='([0-9]*)(\.[0-9]+)?'
patternError='Please enter a valid number (e.g. 123.45) without any units'
/>
</div>
<InputWidget
type='text'
ref='costsCouncilTax'
label='Council tax'
placeholder='(optional)'
defaultValue={home.costs.councilTax}
onChange={this.onFormChange.bind(this)}
pattern='([0-9]*)(\.[0-9]+)?'
patternError='Please enter a valid number (e.g. 123.45) without any units'
/>
</Panel>
<Panel header='Images'>
<Row>
<Col md={6}>
<h2>Images</h2>
<ImageList images={this.state.images} onRemove={this.onRemoveImageClicked} onChange={this.onFormChange} storageKey='images' />
</Col>
<Col md={6}>
<UploadArea
className='uploadarea image-uploadarea'
signatureFolder='homeImage'
width='100%'
height='80px'
onUpload={this.onImageUpload.bind(this)}
acceptedMimes='image/*'
instanceId='images'>
<Well>
<p>Drag new image here, or click to select from filesystem.</p>
</Well>
</UploadArea>
</Col>
</Row>
<Row>
<Col md={6}>
<h2>Brochures</h2>
<ImageList
images={this.state.brochures}
onRemove={this.onRemoveImageClicked}
onChange={this.onFormChange}
storageKey='brochures'
types={this.brochureTypes}
/>
</Col>
<Col md={6}>
<UploadArea
className='uploadarea image-uploadarea'
signatureFolder='homeImage'
width='100%'
height='80px'
onUpload={(file, data) => {
this.onImageUpload(file, data, 'brochures');
}}
acceptedMimes='image/*,application/pdf'
instanceId='brochures'>
<Well>
<p>Drag new image here, or click to select from filesystem.</p>
</Well>
</UploadArea>
</Col>
</Row>
</Panel>
<Well>
<Row>
<Col md={6}>
<Button bsStyle='success' accessKey='s' onClick={this.onSave.bind(this)}>Save</Button>
{previewLink}
</Col>
<Col md={6} pullRight>
{deleteLink}
</Col>
</Row>
</Well>
</Col>
</form>
</Row>
);
}
}
<file_sep>// import React from 'react';
import BaseBlock from '../Widgets/BaseBlock';
export default class AdminContentBlock extends BaseBlock {
blockProperties = {
title: {
label: 'Title (optional)',
type: 'text',
required: false
},
content: {
label: 'Content',
type: 'textarea',
required: true
},
align: {
label: 'Alignment',
type: 'select',
options: [
['left', 'Left'], ['center', 'Center'], ['right', 'Right']
]
}
}
}
<file_sep># nginx-ssl-proxy
#
# VERSION 0.0.1
FROM nginx
MAINTAINER <NAME> <<EMAIL>>
RUN rm /etc/nginx/conf.d/*.conf
WORKDIR /usr/src
ADD start.sh /usr/src/
ADD nginx/nginx.conf /etc/nginx/
ADD nginx/proxy*.conf /usr/src/
ENTRYPOINT ./start.sh
<file_sep>import QueryBuilder from '../../../lib/QueryBuilder';
import Api from '../../../api/HomesAPI';
let debug = require('debug')('/api/homes');
let url = require('url');
exports.registerRoutes = (app) => {
const QB = new QueryBuilder(app);
let api = new Api(app, QB);
app.get('/api/home', function(req, res) {
debug('Redirecting the API call to deprecated /api/home');
return res.redirect(301, '/api/homes');
});
app.get('/api/home/:slug', function(req, res) {
debug('Redirecting the API call to deprecated /api/home/:slug');
return res.redirect(301, `/api/homes/${req.params.slug}`);
});
app.get('/api/homes/:slug', function(req, res, next) {
api.getHome(req, res, next)
.then((home) => {
debug('Home fetched', home.homeTitle);
api.populateCityForHome(home)
.then((home) => {
res.json({
status: 'ok',
home: home
});
});
})
.catch(next);
});
app.get('/api/homes/:slug/story', function(req, res, next) {
api.getHome(req, res, next)
.then((home) => {
res.json({
status: 'ok',
story: (home.story && home.story.blocks) ? home.story.blocks : []
});
})
.catch(next);
});
app.get('/api/homes', function(req, res, next) {
api.listHomes(req, res, next)
.then((homes) => {
app.log.debug(`/api/homes Got ${homes.length} homes`);
res.json({
status: 'ok',
homes: homes
});
})
.catch(next);
});
};
<file_sep>import React from 'react';
import Row from 'react-bootstrap/lib/Row';
import Col from 'react-bootstrap/lib/Col';
import SubNavigation from './SubNavigation';
class SubNavigationWrapper extends React.Component {
static propTypes = {
children: React.PropTypes.oneOfType([
React.PropTypes.array,
React.PropTypes.object,
React.PropTypes.null
])
};
render() {
return (
<Row>
<SubNavigation>
{this.props.children[0]}
</SubNavigation>
<Col sm={9} smOffset={3} md={10} mdOffset={2} className='main'>
{this.props.children[1]}
</Col>
</Row>
);
}
}
export default SubNavigationWrapper;
<file_sep>import {toTitleCase} from '../Helpers';
exports.configure = function(app, config) {
return new Promise((resolve, reject) => {
let adapterClassName = `${toTitleCase(config.adapter)}Adapter`;
let DatabaseAdapter = require(`./${adapterClassName}`);
let instance = new DatabaseAdapter(app, config.adapterConfig);
app.db = instance;
instance.connect(err => {
if (err) {
return reject(err);
}
resolve();
});
});
};
<file_sep>import React from 'react';
import BaseWidget from './BaseWidget';
import ApplicationStore from '../../stores/ApplicationStore';
import { merge } from '../../Helpers';
import DOMManipulator from '../../DOMManipulator';
// import classNames from 'classnames';
let debug = require('../../../common/debugger')('Image');
export default class Image extends BaseWidget {
static propTypes = {
src: React.PropTypes.string,
url: React.PropTypes.string,
alt: React.PropTypes.string.isRequired,
width: React.PropTypes.oneOfType([
React.PropTypes.number,
React.PropTypes.string
]),
height: React.PropTypes.oneOfType([
React.PropTypes.number,
React.PropTypes.string
]),
aspectRatio: React.PropTypes.number,
title: React.PropTypes.string,
type: React.PropTypes.string,
variant: React.PropTypes.string,
mode: React.PropTypes.string,
linked: React.PropTypes.oneOfType([
React.PropTypes.string,
React.PropTypes.bool,
React.PropTypes.null
]),
gravity: React.PropTypes.string,
className: React.PropTypes.string,
applySize: React.PropTypes.bool,
align: React.PropTypes.string,
valign: React.PropTypes.string
}
static defaultProps = {
width: null,
height: null,
alt: '',
title: '',
className: null,
type: 'content',
mode: null,
applySize: false,
gravity: 'center',
linked: '',
align: null,
valign: null
}
constructor() {
super();
this.storeListener = this.onStateChange.bind(this);
this.attributes = {};
}
state = {
config: ApplicationStore.getState().config
}
componentDidMount() {
ApplicationStore.listen(this.storeListener);
let img = new DOMManipulator(this.refs.image);
img.addClass('loading');
img.node.onload = function() {
img.removeClass('loading');
};
img.node.onerror = function() {
img.addClass('load-error');
if (!img.attr('data-src')) {
img.attr('data-src', img.attr('src'));
}
// Replace the broken src with pixel.gif
// img.attr('src', 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7');
};
}
componentWillUnmount() {
ApplicationStore.unlisten(this.storeListener);
}
onStateChange() {
this.setState({
config: ApplicationStore.getState().config
});
}
static validate(props) {
if (!props.url && !props.src) {
throw new Error('Missing attribute "url"');
}
if (props.width && !BaseWidget.isNumeric(props.width)) {
throw new Error('Attribute "width" fails type check');
}
if (props.height && !BaseWidget.isNumeric(props.height)) {
throw new Error('Attribute "height" fails type check');
}
}
resolveParams() {
let params = {};
params.src = this.resolveSrc(this.props.variant);
return params;
}
getClass() {
let classes = ['image-widget', `type-${this.props.type}`];
if (this.props.className) {
classes.push(this.props.className);
}
return classes.join(' ');
}
setAspectRatio() {
if (this.props.width && this.props.height) {
this.aspectRatio = this.props.width / this.props.height;
}
if (this.props.aspectRatio) {
this.aspectRatio = this.props.aspectRatio;
}
if (this.aspectRatio) {
this.attributes['data-aspect-ratio'] = this.aspectRatio;
}
}
resolveAttributes() {
if (this.props.width && this.props.applySize !== false) {
this.attributes.width = this.props.width;
}
if (this.props.height && this.props.applySize !== false) {
this.attributes.height = this.props.height;
}
this.attributes.alt = this.props.alt || '';
this.attributes.title = this.props.title || this.attributes.alt;
if (this.props.align) {
this.attributes['data-align'] = this.props.align;
}
if (this.props.valign) {
this.attributes['data-valign'] = this.props.valign;
}
this.attributes.className = this.getClass();
this.setAspectRatio();
return this.attributes;
}
setByAspectRatio(d) {
if (!this.props.aspectRatio) {
return null;
}
if (d.width) {
d.height = Math.round(d.width / this.props.aspectRatio);
} else if (d.height) {
d.width = Math.round(d.height * this.props.aspectRatio);
}
}
applySize() {
let d = {
width: this.attributes.width || this.props.width,
height: this.attributes.height || this.props.height
};
let apply = !!(this.props.applySize);
if (this.props.variant) {
let variant = this.state.config.cloudinary.transformations[this.props.variant] || {};
if (typeof variant.applySize !== 'undefined') {
apply = variant.applySize;
}
if (!d.width && variant.width) {
d.width = variant.width;
}
if (!d.height && variant.height) {
d.height = variant.height;
}
}
this.setByAspectRatio(d);
if (apply) {
this.propagateAttributes(d);
}
}
propagateAttributes(d) {
for (let i in d) {
if (d[i]) {
this.attributes[i] = d[i];
}
}
}
resolveSrc(variant) {
let src = this.props.src || this.props.url;
let rval = null;
src = src.replace(/^\//, '');
switch (this.props.type) {
case 'asset':
let assetPath = this.state.config.revisionedStaticPath.replace(/\/raw\//, '/image/');
rval = `${assetPath.replace(/\/$/, '')}/${src}`;
break;
case 'content':
rval = this.resolveContentSrc(src, variant);
break;
default:
debug('Tried to use an undefined image type', this.props.type, this.props);
throw new Error(`Undefined image type '${this.props.type.toString()}'`);
}
return rval;
}
getBaseUrl(src) {
// Not prefixed with Cloudinary path
if (!src.match(/^(https?:)?\/\//i)) {
// In case the cloudinary path isn't available, use the hard coded one
let p = this.state.config.cloudinary.basePath || 'https://res.cloudinary.com/homehapp/image/upload';
return p.replace(/\/$/, '');
}
let regs = src.match(/^((https?:)?\/\/res.cloudinary.com\/.+upload\/)/);
if (!regs) {
return '';
}
return regs[1].replace(/\/$/, '').replace(/http:\/\//, 'https://');
}
getPath(src) {
return src.replace(/^(https?:)?\/\/.+(v[0-9]+)/, '$2');
}
getOption(i, v) {
let rval = null;
switch (i) {
case 'width':
if (v === 'auto') {
break;
}
rval = `w_${v}`;
break;
case 'height':
if (v === 'auto') {
break;
}
rval = `h_${v}`;
break;
case 'mode':
rval = `c_${v}`;
break;
case 'gravity':
rval = `g_${v}`;
break;
}
return rval;
}
getOptions(params) {
let options = [];
for (let i in params) {
if (!params[i]) {
continue;
}
let val = this.getOption(i, params[i]);
if (val) {
options.push(val);
}
}
return options;
}
resolveContentSrc(src, variant) {
let mask = '';
let params = merge({}, this.props);
this.getVariant(params, variant);
let options = this.getOptions(params);
this.applySize();
if (params.mask) {
mask = `/l_${params.mask},fl_cutter`;
if (src.match(/\.jpe?g$/i)) {
src = src.replace(/\.jpe?g$/i, '.png');
}
}
// Load everything in interlaced/progressive mode to show
// content to the users as quickly as possible
options.push('fl_progressive');
return `${this.getBaseUrl(src)}/${options.join(',')}${mask}/${this.getPath(src)}`;
}
getVariant(params, variant) {
if (variant) {
let d = this.state.config.cloudinary.transformations[variant];
for (let i in d) {
// Override only null and undefined
if (typeof params[i] === 'undefined' || params[i] === null) {
params[i] = d[i];
}
}
}
}
renderImage() {
// Linked, i.e. refer usually to a larger version of the same image
if (this.props.linked) {
let href = this.resolveSrc(this.props.linked);
return (
<a href={href} data-linked={this.props.linked}>
<img {...this.attributes} ref='image' />
</a>
);
}
return (
<img {...this.attributes} ref='image' />
);
}
renderWidget() {
if (!this.state.config) {
return null;
}
if (!this.props.url && !this.props.src) {
debug('No image url or src provided, use a placeholder instead', this.props);
this.props.url = 'https://res.cloudinary.com/homehapp/image/upload/v1441913472/site/images/content/content-placeholder.jpg';
this.props.alt = 'Placeholder';
}
let params = this.resolveParams();
this.resolveAttributes();
this.attributes.src = params.src;
return this.renderImage();
}
}
<file_sep>import { loadCommonPlugins, commonJsonTransform, populateMetadata } from './common';
exports.loadSchemas = function (mongoose, next) {
let Schema = mongoose.Schema;
let schemas = {};
schemas.Contact = new Schema(populateMetadata({
uuid: {
type: String,
index: true,
unique: true
},
// Details
title: {
type: String,
default: ''
},
message: {
type: String,
default: ''
},
type: {
type: String,
default: 'email',
enum: ['email', 'phone']
},
subType: {
type: String,
default: null
},
sender: {
name: {
type: String,
default: null
},
email: {
type: String,
default: null
},
phone: {
type: String,
default: null
},
country: {
type: String,
default: null
}
},
home: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Home',
default: null
},
recipient: {
agent: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Agent'
},
name: {
type: String,
default: null
},
email: {
type: String,
default: null
},
phone: {
type: String,
default: null
}
},
// Store the related tags (e.g. home ID and such) here
tags: []
}));
schemas.Contact.virtual('contactTitle').get(function () {
return this.createdAt.toString();
});
schemas.Contact.statics.editableFields = function () {
return [
'title', 'message', 'type', 'sender', 'recipient', 'tags',
'home', 'subType'
];
};
Object.keys(schemas).forEach((name) => {
loadCommonPlugins(schemas[name], name, mongoose);
schemas[name].options.toJSON.transform = (doc, ret) => {
return commonJsonTransform(ret);
};
});
next(schemas);
};
<file_sep>import React from 'react';
import BaseWidget from './BaseWidget';
import DOMManipulator from '../../DOMManipulator';
import { merge } from '../../Helpers';
export default class Video extends BaseWidget {
static propTypes = {
src: React.PropTypes.string.isRequired,
mode: React.PropTypes.string,
aspectRatio: React.PropTypes.oneOfType([
React.PropTypes.number,
React.PropTypes.string
]),
className: React.PropTypes.string,
formats: React.PropTypes.array,
poster: React.PropTypes.string,
autoPlay: React.PropTypes.bool,
loop: React.PropTypes.bool,
controls: React.PropTypes.bool,
standalone: React.PropTypes.bool,
width: React.PropTypes.oneOfType([
React.PropTypes.null,
React.PropTypes.number,
React.PropTypes.string
]),
height: React.PropTypes.oneOfType([
React.PropTypes.null,
React.PropTypes.number,
React.PropTypes.string
]),
derived: React.PropTypes.array
};
static validate(props) {
if (!props.src) {
throw new Error('Attribute "src" missing');
}
if (props.width && !BaseWidget.isNumeric(props.width)) {
throw new Error('Attribute "width" fails type check');
}
if (props.height && !BaseWidget.isNumeric(props.height)) {
throw new Error('Attribute "height" fails type check');
}
if (props.derived) {
if (!Array.isArray(props.derived)) {
throw new Error('Attribute "derived" has to be an array');
}
props.derived.map((derived) => {
if (!derived.url) {
throw new Error('Derived video is missing "url" attribute');
}
if (!derived.format) {
throw new Error('Derived video is missing "format" attribute');
}
if (derived.width && !BaseWidget.isNumeric(derived.width)) {
throw new Error('Derived video attribute "width" has to be numeric');
}
if (derived.height && !BaseWidget.isNumeric(derived.height)) {
throw new Error('Derived video attribute "height" has to be numeric');
}
});
}
}
static defaultProps = {
mode: 'html5',
aspectRatio: 16 / 9,
className: null,
formats: [
'webm',
'mp4',
'ogg'
],
poster: null,
autoPlay: false,
loop: false,
controls: true,
standalone: false,
width: '100%',
height: '100%',
derived: []
};
constructor() {
super();
this.resize = this.resize.bind(this);
}
componentDidMount() {
if (!this.refs.container) {
return;
}
this.container = new DOMManipulator(this.refs.container);
window.addEventListener('resize', this.resize);
this.resize();
}
componentWillUnmount() {
window.removeEventListener('resize', this.resize);
}
resize() {
let width = this.container.parent().width();
let height = width / this.aspectRatio;
if (this.aspectRatio < 1) {
height = this.container.width();
width = height * this.aspectRatio;
}
this.container.css({
width: `${width}px`,
height: `${height}px`
});
}
resolveAspectRatio() {
let aspectRatio = Number(this.props.aspectRatio);
if (isNaN(aspectRatio)) {
let regs = this.props.aspectRatio.match(/^([0-9]+):([0-9]+)$/);
if (regs) {
aspectRatio = Number(regs[1]) / Number(regs[2]);
} else {
aspectRatio = 16 / 9;
console.warn('Invalid aspect ratio, fall back to 16:9');
}
}
// Normalize between 1:10 and 10:1 to keep some sanity
this.aspectRatio = Math.min(10, Math.max(aspectRatio, 1 / 10));
}
getBaseUrl() {
let regexp = new RegExp(`\.(mov|avi|mpe?g|${this.props.formats.join('|')})$`, 'i');
return this.props.src.replace(regexp, '');
}
getPoster(params) {
params = merge({
width: 100,
height: 100,
mode: 'fit',
gravity: 'center'
}, params || {});
let poster = this.props.poster || `${this.getBaseUrl()}.png`;
return poster.replace(/upload\//, `upload/w_${params.width},h_${params.height},c_${params.mode},g_${params.gravity}/`);
}
getVideo() {
let classes = ['video'];
if (this.props.className) {
classes.push(this.props.className);
}
if (this.props.mode === 'iframe') {
classes.push('iframe');
return (<iframe src={this.props.src} width='100%' height='100%' frameBorder='0' webkitallowfullscreen mozallowfullscreen allowFullScreen className={classes.join(' ')}></iframe>);
}
if (this.props.mode === 'html5') {
classes.push('inline');
let baseUrl = this.getBaseUrl();
let video = {
poster: this.getPoster(),
controls: this.props.controls,
autoPlay: this.props.autoPlay,
loop: this.props.loop,
width: this.props.width,
height: this.props.height,
className: classes.join(' ')
};
if (Array.isArray(this.props.derived) && this.props.derived.length) {
console.error('derived', this.props.derived);
return (
<video {...video}>
{
this.props.derived.map((derived, index) => {
let type = `video/${derived.format}`;
return (
<source src={derived.url} type={type} key={index} />
);
})
}
</video>
);
}
return (
<video {...video}>
{
this.props.formats.map((format, index) => {
let src = `${baseUrl}.${format}`;
let type = `video/${format}`.toLowerCase();
return (
<source src={src} type={type} key={index} />
);
})
}
</video>
);
}
return `Not yet implemented '${this.props.mode}' with src '${this.props.src}'`;
}
renderWidget() {
this.resolveAspectRatio();
if (!this.props.src) {
console.error('No `src` defined for video, cannot continue', this.props);
return null;
}
let classes = ['widget', 'video'];
if (this.props.className) {
classes.push(this.props.className);
}
let video = this.getVideo();
// Skip the wrappers, serve only the pure video
if (this.props.standalone) {
return video;
}
return (
<div className={classes.join(' ')}>
<div className='video-wrapper' ref='container'>
{video}
</div>
</div>
);
}
}
<file_sep>import React from 'react';
import ContentBlock from '../../../common/components/Widgets/ContentBlock';
import AuthStore from '../../../common/stores/AuthStore';
let debug = require('debug')('Logout');
export default class Logout extends React.Component {
static propTypes = {
context: React.PropTypes.object
}
static contextTypes = {
router: React.PropTypes.func
}
constructor() {
super();
this.storeListener = this.onStoreChange.bind(this);
}
state = {
user: AuthStore.getState().user,
loggedIn: AuthStore.getState().loggedIn,
error: AuthStore.getState().error
}
onStoreChange(state) {
this.setState(state);
}
logout() {
return new Promise((resolve, reject) => {
let req = new XMLHttpRequest();
req.addEventListener('load', function logoutSuccess() {
resolve();
});
req.addEventListener('error', function logoutError() {
resolve();
});
req.open('GET', '/auth/logout');
req.send();
});
}
componentDidMount() {
this.timer = null;
AuthStore.listen(this.storeListener);
this.logout()
.then(() => {
try {
AuthStore.fetchUser();
} catch (error) {
debug('AuthStore.fetchUser failed as expected', error);
}
this.setState({
user: null,
error: null,
loggedIn: false
});
if (window) {
this.timer = window.setTimeout(() => {
window.location.href = this.context.router.makeHref('app');
}, 2000);
}
});
}
componentWillUnmount() {
AuthStore.unlisten(this.storeListener);
if (this.timer) {
window.clearTimeout(this.timer);
}
}
render() {
if (this.state.loggedIn) {
return (
<ContentBlock>
<div id='loginForm' className='centered'>
<h1>Logging out...</h1>
<p>Please wait</p>
</div>
</ContentBlock>
);
}
return (
<ContentBlock className='centered'>
<div className='centered'>
<h1>Logged out</h1>
<p>You have been successfully logged out</p>
</div>
</ContentBlock>
);
}
}
<file_sep>import React from 'react';
import { Link } from 'react-router';
import HomeListStore from '../../stores/HomeListStore';
import HomeStore from '../../stores/HomeStore';
import Loading from '../../../common/components/Widgets/Loading';
import Table from 'react-bootstrap/lib/Table';
import Button from 'react-bootstrap/lib/Button';
import Row from 'react-bootstrap/lib/Row';
import Nav from 'react-bootstrap/lib/Nav';
import SubNavigationWrapper from '../Navigation/SubNavigationWrapper';
import { setPageTitle } from '../../../common/Helpers';
import DOMManipulator from '../../../common/DOMManipulator';
// import NavItemLink from 'react-router-bootstrap/lib/NavItemLink';
let debug = require('debug')('HomesIndex');
class HomesIndex extends React.Component {
static propTypes = {
params: React.PropTypes.object
}
constructor(props) {
super(props);
this.homes = null;
this.iterator = 0;
this.storeListener = this.onChange.bind(this);
}
state = {
homes: HomeListStore.fetchHomes(),
error: null
}
componentDidMount() {
setPageTitle('Homes');
HomeListStore.listen(this.storeListener);
HomeListStore.fetchHomes();
this.container = new DOMManipulator(this.refs.container);
}
componentWillUnmount() {
HomeListStore.unlisten(this.storeListener);
}
onChange(state) {
debug('onChange', state);
debug('StateChange');
for (let home of state.homes) {
debug('Home', home.homeTitle, home.metadata.score);
}
this.setState({
homes: state.homes,
error: state.error
});
}
sortHomes() {
this.homes.sort((a, b) => {
if (a.metadata.score > b.metadata.score) {
return -1;
}
if (a.metadata.score < b.metadata.score) {
return 1;
}
if (a.metadata.createdAt > b.metadata.createdAt) {
return -1;
}
if (a.metadata.createdAt < b.metadata.createdAt) {
return 1;
}
return 0;
});
}
movePosition(index, dir) {
if (typeof this.homes[index - dir] !== 'undefined') {
let tmp = this.homes[index];
this.homes[index] = this.homes[index - dir];
this.homes[index - dir] = tmp;
this.homes.map((home, index) => {
home.metadata.score = this.homes.length - index;
});
this.forceUpdate();
setTimeout(() => {
debug('timeout phase 1');
let node = React.findDOMNode(this.refs.container);
if (!node) {
return null;
}
let rows = node.getElementsByClassName('sortable');
rows[index].setAttribute('data-flash', 'data-flash');
rows[index - dir].setAttribute('data-flash', 'data-flash');
setTimeout(() => {
debug('timeout phase 2');
rows[index].removeAttribute('data-flash');
rows[index - dir].removeAttribute('data-flash');
}, 2000);
}, 100);
}
}
onSave() {
let scores = {};
for (let home of this.homes) {
// Do a minimal update
let homeProps = {
id: home.id,
metadata: home.metadata
};
HomeStore.updateItem(homeProps);
scores[home.metadata.score] = home.homeTitle;
}
debug(scores);
}
handleErrorState() {
return (
<div className='error'>
{this.state.error.message}
</div>
);
}
handleLoadingState() {
return (
<Loading>
Loading homes...
</Loading>
);
}
render() {
if (this.state.error) {
return this.handleErrorState();
}
if (HomeListStore.isLoading() || !this.state.homes) {
return this.handleLoadingState();
}
debug(this.state.homes);
this.homes = this.homes || this.state.homes;
this.sortHomes();
this.iterator++;
return (
<SubNavigationWrapper>
<Nav sidebar>
<h2 className='navigation-title'>
Homes
</h2>
<p>There are {this.homes.length} homes in the system currently.</p>
<ul>
<li><Link to='homeCreate'><i className='fa fa-home'></i> Create a new home</Link></li>
</ul>
</Nav>
<Row>
<h1><i className='fa fa-home'></i> {this.homes.length} homes</h1>
<Table className='flashable' ref='container'>
<thead>
<tr>
<th>Title</th>
<th>Published</th>
<th>Neighborhood</th>
<th>Story blocks</th>
<th>Enabled</th>
<th></th>
</tr>
</thead>
<tbody>
{this.homes.map((home, i) => {
debug('Home', home.homeTitle, home.metadata.score);
let neighborhood = null;
if (home.location.neighborhood) {
neighborhood = (
<Link
to='neighborhoodEdit'
params={{id: home.location.neighborhood.id}}>
{home.location.neighborhood.title}
</Link>
);
}
let upClass = ['fa', 'fa-chevron-circle-up'];
let downClass = ['fa', 'fa-chevron-circle-down'];
if (!i) {
upClass.push('disabled');
}
if (i === this.homes.length - 1) {
downClass.push('disabled');
}
let enabled = null;
let published = null;
if (home.story.enabled) {
enabled = (
<span>yes</span>
);
}
if (home.enabled) {
published = (
<span>yes</span>
);
}
return (
<tr key={`home-${i}-${this.iterator}`} className='sortable'>
<td>
<Link
to='homeEdit'
params={{id: home.id}}>
{home.homeTitle}
</Link>
</td>
<td>{published}</td>
<td>
{neighborhood}
</td>
<td>{home.story.blocks.length}</td>
<td>{enabled}</td>
<td className='sort-actions'>
<i className={upClass.join(' ')} onClick={() => {
this.movePosition(i, 1);
}}></i>
<i className={downClass.join(' ')} onClick={() => {
this.movePosition(i, -1);
}}></i>
</td>
</tr>
);
})}
</tbody>
<tfoot>
<tr>
<th></th>
<th></th>
<th><Button bsStyle='primary' onClick={this.onSave.bind(this)}>Save order</Button></th>
</tr>
</tfoot>
</Table>
</Row>
</SubNavigationWrapper>
);
}
}
export default HomesIndex;
<file_sep>import request from '../../common/request';
import ContactActions from '../actions/ContactActions';
let debug = require('../../common/debugger')('ContactSource');
let ContactSource = {
createItem: function () {
return {
remote(storeState, data) {
debug('createItem:remote', arguments, data);
let postData = {
contact: data
};
return request.post(`/api/contacts`, postData)
.then((response) => {
debug('got response', response);
if (!response.data || response.data.status !== 'ok') {
let err = new Error(response.data.error || 'Invalid response');
return Promise.reject(err);
}
return Promise.resolve(response.data.contact);
})
.catch((response) => {
if (response instanceof Error) {
return Promise.reject(response);
} else {
let msg = 'unexpected error';
if (response.data && response.data.error) {
msg = response.data.error;
}
return Promise.reject(new Error(msg));
}
return Promise.reject(response);
});
},
local(storeState, data) {
debug('createItem:local', arguments, data);
return null;
},
shouldFetch(state) {
debug('createItem:shouldFetch', arguments, state);
return true;
},
success: ContactActions.createSuccess,
error: ContactActions.requestFailed,
loading: ContactActions.createItem
};
}
};
export default ContactSource;
<file_sep>var BaseError = exports.BaseError = class BaseError extends Error {
constructor(message, data = null) {
super(message);
this.message = message;
this.data = data;
}
};
exports.Forbidden = class Forbidden extends BaseError {
constructor(message, data) {
message = message || 'Forbidden';
super(message, data);
this.statusCode = 403;
}
};
exports.BadRequest = class BadRequest extends BaseError {
constructor(message, data) {
message = message || 'Bad Request';
super(message, data);
this.statusCode = 400;
}
};
exports.NotFound = class NotFound extends BaseError {
constructor(message, data) {
message = message || 'Not Found';
super(message, data);
this.statusCode = 404;
}
};
exports.UnprocessableEntity = class UnprocessableEntity extends BaseError {
constructor(message, data) {
message = message || 'Unprocessable Entity';
super(message, data);
this.statusCode = 422;
}
};
exports.InternalServerError = class InternalServerError extends BaseError {
constructor(message, data) {
message = message || 'Internal Server Error';
super(message, data);
this.statusCode = 500;
}
};
exports.NotImplemented = class NotImplemented extends BaseError {
constructor(message, data) {
message = message || 'Not Implemented';
super(message, data);
this.statusCode = 501;
}
};
<file_sep>import alt from '../alt';
let debug = require('../debugger')('ApplicationStore');
class ApplicationStore {
constructor() {
this.on('bootstrap', () => {
// debug('bootstrapping', this.csrf, this.config);
debug('bootstrapping', this.csrf);
});
this.csrf = null;
this.config = {
siteHost: 'http://localhost:3001',
revisionedStaticPath: 'https://res.cloudinary.com/homehapp/raw/upload/site/',
cloudinary: {
baseUrl: 'https://res.cloudinary.com/homehapp/image/upload/',
apiUrl: 'https://api.cloudinary.com/v1_1/homehapp',
transformations: {
// Pinterest styled card
card: {
mode: 'fill',
width: 300
},
// Property list
propList: {
mode: 'fill',
width: 300,
height: 300
},
thumbnail: {
mode: 'thumb',
width: 100,
height: 100
},
pinkynail: {
mode: 'thumb',
width: 50,
height: 50
},
// Full-sized preview
preview: {
mode: 'fill',
height: 960
},
// Big image variants
large: {
mode: 'scale',
width: 1920
},
medium: {
mode: 'scale',
width: 1000
},
small: {
mode: 'fill',
height: 600
},
// Hexagon mask
masked: {
mode: 'fill',
width: 271,
height: 320,
mask: 'hexagon-white'
}
}
}
};
}
}
module.exports = alt.createStore(ApplicationStore);
<file_sep>import alt from '../../common/alt';
import UserActions from '../actions/UserActions';
import UserSource from '../sources/UserSource';
// import Cache from '../../common/Cache';
// let debug = require('../../common/debugger')('UserStore');
@alt.createStore
class UserStore {
constructor() {
this.bindListeners({
handleCreateItem: UserActions.CREATE_ITEM,
handleUpdateItem: UserActions.UPDATE_ITEM,
handleDeleteItem: UserActions.DELETE_ITEM,
handleRequestFailed: UserActions.REQUEST_FAILED,
handleCreateSuccess: UserActions.CREATE_SUCCESS,
handleUpdateSuccess: UserActions.UPDATE_SUCCESS,
handleDeleteSuccess: UserActions.DELETE_SUCCESS
});
this.error = null;
this.user = null;
this.deleted = false;
this.exportAsync(UserSource);
}
handleCreateItem(item) {
this.error = null;
this.user = null;
if (!this.getInstance().isLoading()) {
setTimeout(() => {
this.getInstance().createItem(item);
});
}
}
handleCreateSuccess(user) {
this.error = null;
this.user = user;
this.emitChange();
}
handleUpdateItem(item) {
this.error = null;
if (!this.getInstance().isLoading()) {
setTimeout(() => {
this.getInstance().updateItem(item);
});
}
}
handleUpdateSuccess(user) {
this.error = null;
this.user = user;
this.emitChange();
}
handleDeleteItem(item) {
this.error = null;
this.deleted = false;
if (!this.getInstance().isLoading()) {
setTimeout(() => {
this.getInstance().deleteItem(item);
});
}
}
handleDeleteSuccess() {
this.error = null;
this.user = null;
this.deleted = true;
this.emitChange();
}
handleRequestFailed(error) {
this.error = error;
}
}
module.exports = UserStore;
<file_sep>import React from 'react';
// import { Link } from 'react-router';
import ContentBlock from '../../../common/components/Widgets/ContentBlock';
import { setPageTitle } from '../../../common/Helpers';
export default class Content extends React.Component {
static propTypes = {
params: React.PropTypes.object
};
componentDidMount() {
setPageTitle(this.props.params.slug.substr(0, 1).toUpperCase() + this.props.params.slug.substr(1));
}
componentWillUnmount() {
setPageTitle();
}
render() {
return (
<ContentBlock className='padded'>
Content lorem ipsum for {this.props.params.slug}
</ContentBlock>
);
}
}
<file_sep>import QueryBuilder from '../../lib/QueryBuilder';
import {BadRequest} from '../../lib/Errors';
import fs from 'fs';
exports.registerRoutes = (app) => {
const QB = new QueryBuilder(app);
if (app.firstRun) {
app.firstRun.isDone = () => {
return new Promise((resolve, reject) => {
if (fs.existsSync(app.firstRun.firstRunFlagPath)) {
return resolve(true);
}
QB
.forModel('User')
.query({
_accessLevel: 'admin'
})
.findAll()
.count()
.then((count) => {
if (count) {
app.firstRun.markAsDone();
return resolve(true);
}
resolve(false);
})
.catch(reject);
});
};
}
app.post(app.firstRun.routePath, (req, res, next) => {
if (!req.body.username || !req.body.password) {
return next(new BadRequest('invalid request params'));
}
let data = {
givenName: req.body.givenName,
familyName: req.body.familyName,
username: req.body.username,
password: <PASSWORD>,
_accessLevel: 'admin',
active: true
};
QB
.forModel('User')
.createNoMultiset(data)
.then((result) => {
if (!result.model) {
return res.redirect(app.firstRun.routePath);
}
app.firstRun.markAsDone();
let redirectTo = '/';
if (req.body.redirectTo) {
redirectTo = req.body.redirectTo;
}
res.redirect(redirectTo);
})
.catch(next);
});
};
<file_sep># Homehapp Web
TBD
## Development
Happens in "development" -branch.
All features must be done in their own separated branches and when ready a merge request needs to be created for
getting them to the development branch.
Make sure you follow the Coding Standard as defined in here: https://github.com/airbnb/javascript
### Loading fixture data to database
To load fixtures to database run:
```sh
npm run migrate init applyFixtures
```
# Private and Public Keys for token Authentication
```sh
openssl genrsa -out auth-private.pem 2048
openssl rsa -in auth-private.pem -outform PEM -pubout -out auth-public.pem
```
# Docker
If you are using Kitematic, open it first and click the "Docker CLI" -button. Then navigate to the project checkout folder.
To build the Docker image
```sh
docker build -t homehapp/web:homehappweb .
```
Run the container locally with linked mongo database container (start the mongo docker before, read below how)
```sh
docker run --name homehappweb1 -d -p 3001:3001 --link mongodb:db -e DATABASE_URI="mongodb://db/homehappweb" homehapp/web:homehappweb
```
To see that everything worked (it takes a while to start as it will run in the development mode for now)
```sh
docker logs homehappweb1
```
Open your browser to your http://[DockerIP]:3001
The IP you can find either from the Kitematic UI or with "boot2docker ip" -command.
To remove the old docker image before running it again do:
```sh
docker rm homehappweb1
```
## Running Mongodb docker
### From project folder
```sh
cd support/dockers/mongodb
(docker build -t qvik/dockermongo .)
docker run --name mongodb -d qvik/dockermongo --noprealloc --smallfiles
```
### From Kitematic
Search and create MongoDB image (ie. tutum/mongodb)
Once installed, Go to the settings and find the name of the container (usually: mongodb). This will be used when connecting the containers together.
Change the environment variable "AUTH" to be "no" and restart the instance.
# Google Cloud notes
Remember to run Kitematic before trying to create the containers
Always run the following commands before executing
any of the deployment related methods!
```sh
export PROJECT_ID=homehappweb
gcloud config set project $PROJECT_ID
```
You need to have the gcloud crendentials also set. To list the available
clusters
gcloud container clusters list
gcloud container clusters get-credentials homehapp-prod
gcloud container clusters get-credentials homehapp-stg
## Initial steps before creating clusters
Following are only done if creating the clusters for first time.
Create and push the logger container
```sh
cd support/docker/fluentd-sidecar-gcp
make build push
cd ../../../
```
Create and push the nginx proxy container
```sh
cd support/dockers/nginx-proxy
make build push
cd ../../../
```
## Creating clusters
0. For staging do
export CLUSTER_ENV=stg
0. For production do
export CLUSTER_ENV=prod
1. Create and push the containers
```sh
./support/createContainers.sh $CLUSTER_ENV site
./support/createContainers.sh $CLUSTER_ENV admin
./support/createContainers.sh $CLUSTER_ENV api
```
2. Initialize the cluster
This will create the container cluster nodes
```sh
./support/initCluster $CLUSTER_ENV
```
3. Setup the containers to run inside the cluster
This will deploy and configure the controllers and services
for the project.
3.1 STAGING
```sh
./support/setupCluster.sh $CLUSTER_ENV site
./support/setupCluster.sh $CLUSTER_ENV admin
./support/setupCluster.sh $CLUSTER_ENV api
```
3.2 PRODUCTION
When setuping the production environment you need to add the
certificate path prefix as last argument.
```sh
./support/setupCluster.sh $CLUSTER_ENV site certs/homehapp_com/star_homehapp_com
./support/setupCluster.sh $CLUSTER_ENV admin certs/homehapp_com/star_homehapp_com
./support/setupCluster.sh $CLUSTER_ENV api certs/homehapp_com/star_homehapp_com
```
## Updating clusters
0. For staging do
export CLUSTER_ENV=stg
0. For production do
export CLUSTER_ENV=prod
1. Create and push the containers
```sh
./support/createContainers.sh $CLUSTER_ENV site
./support/createContainers.sh $CLUSTER_ENV admin
./support/createContainers.sh $CLUSTER_ENV api
```
2. Update the controllers
```sh
./support/updateCluster.sh $CLUSTER_ENV site
./support/updateCluster.sh $CLUSTER_ENV admin
./support/updateCluster.sh $CLUSTER_ENV api
```
3. Updating site assets
Build the site static files
```sh
npm run build-site
npm run build-admin
```
Run the distribution script to propagate files to CDN
```sh
npm run distribute-site
npm run distribute-admin
```
# Administration First-run
Credentials:
<EMAIL> / <PASSWORD>
# Run locally
1. Start Mongo with `mongod`
- check *Loading fixture data to database* on the first run or
to create local content
2. For running the site use `npm run dev`
3. For running the admin interface use `npm run dev-admin`
4. For running the mobile api use `npm run dev-api`
# Endpoints
- Production site: https://www.homehapp.com/
- Production admin: https://admin.homehapp.com/
- Production mobile API: https://mobile-api.homehapp.com/
- Production mobile API documentation: https://mobile-api.homehapp.com/api-docs/
- Staging site: http://alpha.homehapp.com:8080/
- Staging admin: http://staging-admin.homehapp.com:8080/
<file_sep>import HomeListActions from '../actions/HomeListActions';
import HomeListSource from '../sources/HomeListSource';
import ListStore from '../../common/stores/BaseListStore';
export default ListStore.generate('HomeListStore', {
actions: HomeListActions,
source: HomeListSource,
listeners: {}
});
<file_sep>import QueryBuilder from '../../../lib/QueryBuilder';
import {/*NotImplemented, */BadRequest} from '../../../lib/Errors';
let debug = require('debug')('/api/users');
exports.registerRoutes = (app) => {
const QB = new QueryBuilder(app);
let populate = {
createdBy: {},
updatedBy: {}
};
app.get('/api/users', app.authenticatedRoute, function(req, res, next) {
QB
.forModel('User')
.parseRequestArguments(req)
.populate(populate)
.findAll()
.fetch()
.then((result) => {
debug('/api/users');
debug(result.models);
res.json({
status: 'ok',
users: result.models.map((user) => {
return user.toJSON();
})
});
})
.catch(next);
});
app.post('/api/users', app.authenticatedRoute, function(req, res, next) {
debug('API update user with uuid', req.params.uuid);
//debug('req.body', req.body);
let data = req.body.user;
if (!data.username) {
return next(new BadRequest('invalid request body'));
}
if (req.user) {
data.createdBy = req.user.id;
data.updatedBy = req.user.id;
}
function createUser() {
return QB
.forModel('User')
.populate(populate)
.createNoMultiset(data)
.then((model) => {
res.json({
status: 'ok',
user: model
});
})
.catch(next);
}
createUser(data);
});
app.get('/api/users/:uuid', app.authenticatedRoute, function(req, res, next) {
debug('API fetch user with uuid', req.params.uuid);
debug('req.query', req.query);
QB
.forModel('User')
.populate(populate)
.findByUuid(req.params.uuid)
.fetch()
.then((result) => {
res.json({
status: 'ok',
user: result.user
});
})
.catch(next);
});
let updateUser = function updateUser(uuid, data) {
debug('Data', data);
return QB
.forModel('User')
.findByUuid(uuid)
.updateNoMultiset(data);
};
app.put('/api/users/:uuid', app.authenticatedRoute, function(req, res, next) {
debug('API update user with uuid', req.params.uuid);
//debug('req.body', req.body);
let data = req.body.user;
if (req.user) {
data.updatedBy = req.user.id;
}
updateUser(req.params.uuid, data)
.then((model) => {
res.json({
status: 'ok',
user: model
});
})
.catch(next);
});
// app.patch('/api/users/:uuid', function(req, res, next) {
// debug('API update user with uuid', req.params.uuid);
// //debug('req.body', req.body);
//
// let data = req.body.user;
//
// updateUser(req.params.uuid, data)
// .then((model) => {
// res.json({
// status: 'ok', user: model
// });
// })
// .catch(next);
// });
app.delete('/api/users/:uuid', app.authenticatedRoute, function(req, res, next) {
QB
.forModel('User')
.findByUuid(req.params.uuid)
.remove()
.then((result) => {
res.json({
status: 'deleted',
user: result.model
});
})
.catch(next);
});
};
<file_sep>import React from 'react';
import Image from './Image';
export default class Icon extends React.Component {
static propTypes = {
type: React.PropTypes.string.isRequired,
color: React.PropTypes.string,
size: React.PropTypes.string,
className: React.PropTypes.string
};
static defaultProps = {
color: 'black',
size: 'medium',
className: ''
};
render() {
let image = {
url: `images/icons/white/${this.props.type}.svg`,
alt: '',
type: 'asset'
};
let classes = ['widget', 'icon', this.props.color, this.props.size, this.props.type];
if (this.props.className) {
classes.push(this.props.className);
}
return (
<span className={classes.join(' ')}><Image {...image} /></span>
);
}
}
<file_sep>#! /bin/sh
# Do not change these
REV=`git rev-parse --short HEAD`
CWD=`pwd`
CONTAINER_REGISTRY_HOST=eu.gcr.io
ENV="prod"
PNAME="$1-$ENV"
PBNAME="$1"
CLUSTER_NAME="homehapp-$1-$ENV"
CLUSTER_GOOGLE_NAME=""
NODE_GOOGLE_NAME=""
function printUsage() {
echo "Required environment variables:"
echo " PROJECT_ID: Google Project ID"
echo ""
echo "Usage PROJECT_ID=id ./support/production/destroyCluster.sh [project_name]"
echo "Add -d for dry-run"
}
function printUsageAndExit() {
printUsage
exit
}
if [ "$PROJECT_ID" = "" ]; then
echo "No Google Project ID defined!"
printUsageAndExit
fi
if [ "$PNAME" = "" ]; then
echo "No project defined!"
printUsageAndExit
fi
if [ ! -d "$CWD/tmp" ]; then
mkdir "$CWD/tmp"
fi
if [ "$3" = "-d" ]; then
echo "In Dry-Run mode"
fi
function removeServices() {
if [ "$CLUSTER_GOOGLE_NAME" = "" ]; then
CLUSTER_GOOGLE_NAME=`kubectl config view | awk '{print $2}' | grep $CLUSTER_NAME | tail -n 1`
fi
if [ "$1" = "-d" ]; then
echo "Execute: 'kubectl delete services --context=$CLUSTER_GOOGLE_NAME $PNAME'"
echo "Execute: 'kubectl delete services --context=$CLUSTER_GOOGLE_NAME $PNAME-proxy'"
else
kubectl delete services --context=$CLUSTER_GOOGLE_NAME $PNAME
kubectl delete services --context=$CLUSTER_GOOGLE_NAME "$PNAME-proxy"
fi
}
function removeControllers() {
local CONTROLLER_NAME=`kubectl get rc | grep $PROJECT_ID | awk '{print $1}' | grep "$PNAME" | head -n 1`
local PROXY_CONTROLLER_NAME=`kubectl get rc | grep $PROJECT_ID | awk '{print $1}' | grep "$PNAME-proxy"`
if [ "$1" = "-d" ]; then
echo "Execute: 'kubectl stop rc $CONTROLLER_NAME'"
echo "Execute: 'kubectl stop rc $PROXY_CONTROLLER_NAME'"
else
kubectl stop rc $CONTROLLER_NAME
kubectl stop rc $PROXY_CONTROLLER_NAME
fi
}
function removeSecrets() {
if [ "$1" = "-d" ]; then
echo "Execute: 'kubectl delete secrets --context=$CLUSTER_GOOGLE_NAME proxy-secret'"
else
kubectl delete secrets --context=$CLUSTER_GOOGLE_NAME "proxy-secret"
fi
}
function removeCluster() {
if [ "$1" = "-d" ]; then
echo "Execute: 'gcloud beta container clusters delete $CLUSTER_NAME --project $PROJECT_ID'"
else
gcloud beta container clusters delete --quiet $CLUSTER_NAME --project $PROJECT_ID
fi
}
function unconfigureProxyFirewall() {
if [ "$1" = "-d" ]; then
echo "Execute: 'gcloud compute firewall-rules delete ${CLUSTER_NAME}-web-public --project $PROJECT_ID'"
else
gcloud compute firewall-rules delete --quiet ${CLUSTER_NAME}-web-public --project $PROJECT_ID
fi
}
if [ "$2" = "-d" ]; then
echo "In Dry-Run mode"
fi
echo ""
echo "Removing Services for $PNAME"
removeServices $2
echo ""
echo "Removing Replication Controllers for $PNAME"
removeControllers $2
echo ""
echo "Removing Secrets for $PNAME"
removeSecrets $2
echo ""
echo "Removing related firewall rules"
unconfigureProxyFirewall $2
echo "Removing Container Cluster $CLUSTER_NAME"
echo ""
removeCluster $2
echo ""
echo "Cluster removed!"
echo ""
<file_sep>import React from 'react';
import Row from 'react-bootstrap/lib/Row';
import Col from 'react-bootstrap/lib/Col';
import Well from 'react-bootstrap/lib/Well';
import Panel from 'react-bootstrap/lib/Panel';
import Button from 'react-bootstrap/lib/Button';
import InputWidget from '../Widgets/Input';
import AgentStore from '../../stores/AgentStore';
import AgentActions from '../../actions/AgentActions';
import UploadArea from '../../../common/components/UploadArea';
import UploadAreaUtils from '../../../common/components/UploadArea/utils';
import ImageList from '../Widgets/ImageList';
import { randomNumericId, merge, createNotification, scrollTop } from '../../../common/Helpers';
const countries = require('../../../common/lib/Countries').forSelect();
let debug = require('../../../common/debugger')('AgentsCreateEdit');
export default class AgentsCreateEdit extends React.Component {
static propTypes = {
model: React.PropTypes.object,
onSave: React.PropTypes.func,
onCancel: React.PropTypes.func
}
static defaultProps = {
model: null,
onSave: null,
onCancel: null
}
constructor(props) {
debug('constructor', props);
super(props);
if (props.model) {
this.state.model = props.model;
this.state.images = props.model.images;
}
this.storeListener = this.onChange.bind(this);
this.uploadListener = this.onUploadChange.bind(this);
this.imageUploaderInstanceId = randomNumericId();
}
state = {
error: null,
model: null,
images: [],
uploads: UploadAreaUtils.UploadStore.getState().uploads
}
componentDidMount() {
debug('componentDidMount');
AgentStore.listen(this.storeListener);
let editor = React.findDOMNode(this.refs.agentEdit);
if (editor && editor.parentNode) {
let offset = editor.getBoundingClientRect();
scrollTop(offset.top - 100, 500);
}
}
componentWillUnmount() {
debug('componentWillUnmount');
AgentStore.unlisten(this.storeListener);
}
onChange(state) {
debug('onChange', state);
if (state.created) {
return window.location.reload();
}
this.setState(state);
}
onUploadChange(state) {
debug('onUploadChange', state);
this.setState({
uploads: UploadAreaUtils.UploadStore.getState().uploads
});
}
onSave() {
debug('onSave');
let images = [];
// Clean broken images
this.state.images.forEach((image) => {
if (image.url) {
images.push(image);
}
});
// Prevalidate InputWidget contents
for (let key in this.refs) {
let ref = this.refs[key];
if (typeof ref.isValid !== 'function') {
continue;
}
if (!ref.isValid()) {
debug('Validation failed', ref);
let label = ref.props.label || 'Validation error';
let message = ref.message || 'Field failed the validation';
createNotification({
type: 'danger',
duration: 10,
label: label,
message: message
});
return false;
}
}
let data = {
firstname: this.refs.firstname.getValue(),
lastname: this.refs.lastname.getValue(),
title: this.refs.title.getValue() || null,
contactNumber: this.refs.contactNumber.getValue(),
_realPhoneNumber: this.refs.realPhoneNumber.getValue(),
_realPhoneNumberType: this.refs.realPhoneNumberType.getValue(),
email: this.refs.email.getValue(),
location: {
address: {
country: this.refs.addressCountry.getValue()
}
},
// @TODO: agency selector
images: images
};
if (this.state.model) {
data.id = this.state.model.id;
}
if (this.state.uploads) {
if (this.state.uploads[this.logoUploaderInstanceId]) {
let uploads = this.state.uploads[this.logoUploaderInstanceId];
let key = Object.keys(uploads)[0];
data.logo = {
url: uploads[key].url,
width: uploads[key].width,
height: uploads[key].height
};
}
}
if (data.id) {
AgentActions.updateItem(data);
} else {
AgentActions.createItem(data);
}
if (this.props.onSave) {
this.props.onSave();
}
}
onCancel() {
if (this.props.onCancel) {
this.props.onCancel();
}
}
onReleaseNumber() {
AgentActions.releaseNumber(this.props.model.id);
}
imageExists(url) {
debug('Check if image exists', this.state.images);
let found = false;
this.state.images.forEach((img) => {
if (img.url === url) {
debug('Image exists');
found = true;
}
});
debug('Image does not exist');
return found;
}
addImage(imageData) {
debug('Add image', imageData);
let isMaster = false;
let image = {
url: imageData.url,
width: imageData.width,
height: imageData.height,
isMaster: isMaster
};
if (!this.imageExists(image.url, this.state.images)) {
debug('Add', image);
this.state.images.push(image);
}
}
addImages() {
debug('addImages', this.state.uploads);
if (this.state.uploads) {
if (this.state.uploads[this.imageUploaderInstanceId]) {
let uploads = this.state.uploads[this.imageUploaderInstanceId];
debug('uploads str', uploads, typeof uploads);
for (let i in uploads) {
this.addImage(uploads[i]);
}
}
}
}
onImageUpload(data) {
debug('onImageUpload', data);
this.addImages();
this.setState({
images: this.state.images
});
}
onRemoveImageClicked(index) {
let newImages = [];
this.state.images.forEach((item, idx) => {
if (idx !== index) {
newImages.push(item);
}
});
this.setState({images: newImages});
}
handlePendingState() {
return (
<div className='model-saving'>
<h3>Saving model...</h3>
</div>
);
}
handleErrorState() {
return (
<div className='model-error'>
<h3>Error saving model!</h3>
<p>{this.state.error.message}</p>
</div>
);
}
getCountryOptions() {
return countries.map((country) => {
return (
<option
value={country.value}
key={'locCountry-' + country.value}>
{country.label}
</option>
);
});
}
render() {
let error = null;
let savingLoader = null;
let statusMessage = null;
//let saveButtonDisabled = null;
let formTitle = 'Create model';
if (this.state.model) {
formTitle = null;
}
if (this.state.error) {
error = this.handleErrorState();
}
if (AgentStore.isLoading()) {
savingLoader = this.handlePendingState();
//saveButtonDisabled = 'disabled';
}
if (this.state.saved) {
statusMessage = (
<p className='bg-success'>
Model saved successfully!
</p>
);
setTimeout(() => {
window.location.reload();
}, 800);
}
let agent = merge({
realPhoneNumberType: 'mobile'
}, this.props.model || {});
let location = merge({
address: {
country: 'GB'
}
}, agent.location || {});
let releaseNumberColumn = (
<Col xs={6}>
<Button
bsStyle='danger'
onClick={this.onReleaseNumber.bind(this)}
>
Release number
</Button>
</Col>
);
if (!agent.contactNumber) {
releaseNumberColumn = null;
}
let countrySelections = this.getCountryOptions();
return (
<Row className='center-block' ref='agentEdit'>
<h1>{formTitle}</h1>
<p>
{error}
{savingLoader}
{statusMessage}
</p>
<form name='agentDetails' ref='agentDetailsForm' method='POST'>
<Col md={10} sm={10}>
<Panel header='Common'>
<InputWidget
type='text'
ref='firstname'
label='<NAME>'
placeholder='<NAME>'
defaultValue={agent.firstname}
required
/>
<InputWidget
type='text'
ref='lastname'
label='<NAME>'
placeholder='<NAME>'
defaultValue={agent.lastname}
required
/>
<InputWidget
type='text'
ref='title'
label='Job title'
placeholder='Job title'
defaultValue={agent.title}
/>
<InputWidget
type='email'
ref='email'
label='Email'
placeholder='<EMAIL>'
defaultValue={agent.email}
required
/>
<InputWidget label='Real Contact Number' wrapperClassName='wrapper'>
<Row>
<Col xs={5}>
<InputWidget
type='select'
ref='addressCountry'
label='Country'
placeholder='Select Country'
defaultValue={location.address.country}>
<option value=''>Select country</option>
{countrySelections}
</InputWidget>
</Col>
<Col xs={3}>
<InputWidget
type='select'
ref='realPhoneNumberType'
label='Type'
placeholder='Type'
pattern='\+?[0-9 ]+'
defaultValue={agent.realPhoneNumberType}>
<option value='mobile'>Mobile</option>
<option value='local'>Landline</option>
</InputWidget>
</Col>
<Col xs={4}>
<InputWidget
type='tel'
ref='realPhoneNumber'
label='Number'
placeholder='+44 123 00 11 22'
defaultValue={agent.realPhoneNumber}
required
/>
</Col>
</Row>
</InputWidget>
<InputWidget label='Twilio Phone number (auto-generated if empty)' wrapperClassName='wrapper'>
<Row>
<Col xs={6}>
<InputWidget
type='tel'
ref='contactNumber'
placeholder='+44 123 00 11 22'
defaultValue={agent.contactNumber}
/>
</Col>
{releaseNumberColumn}
</Row>
</InputWidget>
</Panel>
<Panel header='Agency'>
<p>TODO: add a selector for agency</p>
</Panel>
<Panel header='Images'>
<Row>
<Col md={6}>
<h2>Image</h2>
<ImageList images={this.state.images} onRemove={this.onRemoveImageClicked.bind(this)} max={1} />
</Col>
<Col md={6}>
<UploadArea
className='uploadarea image-uploadarea'
signatureFolder='agentImage'
width='100%'
height='80px'
onUpload={this.onImageUpload.bind(this)}
acceptedMimes='image/*'
instanceId={this.imageUploaderInstanceId}>
<Well>
<p>Drag new image here, or click to select from filesystem.</p>
</Well>
</UploadArea>
</Col>
</Row>
</Panel>
<Well>
<Row>
<Col md={6}>
<Button
ref='saveButton'
bsStyle='success'
accessKey='s'
onClick={this.onSave.bind(this)}>Save</Button>
</Col>
<Col md={6} pullRight>
<Button
ref='cancelButton'
bsStyle='danger'
className='pull-right'
onClick={this.onCancel.bind(this)}>Cancel</Button>
</Col>
</Row>
</Well>
</Col>
</form>
</Row>
);
}
}
<file_sep>let debug = require('debug')('HomesAPI');
export default class HomesAPI {
constructor(app,qb) {
this.QB = qb;
}
listHomes(req, opts = {}) {
let query = {};
let type = null;
if (req.params && req.params.type) {
type = req.params.type.replace(/^stories$/, 'story');
}
if (req.query && req.query.type) {
type = req.query.type.replace(/^stories$/, 'story');
}
if (type) {
if (type === 'story') {
query['story.enabled'] = true;
} else {
query.announcementType = type;
}
}
if (req.params.story) {
query['story.enabled'] = true;
}
let populate = {
'location.neighborhood': {}
};
if (opts.populate) {
populate = opts.populate;
}
query.enabled = {
$in: [true, null]
};
return new Promise((resolve, reject) => {
this.QB
.forModel('Home')
.parseRequestArguments(req)
.query(query)
.populate(populate)
.sort({
'metadata.score': -1
})
.findAll()
.fetch()
.then((result) => {
resolve(result.models);
})
.catch((err) => {
reject(err);
});
});
}
getHome(req) {
return new Promise((resolve, reject) => {
this.QB
.forModel('Home')
.populate({
'location.neighborhood': {},
agents: {}
})
.findBySlug(req.params.slug)
.fetch()
.then((result) => {
resolve(result.model);
})
.catch((err) => {
reject(err);
});;
});
}
populateCityForHome(home) {
debug('populateCityForHome', home);
if (!home.location || !home.location.neighborhood || !home.location.neighborhood.location || !home.location.neighborhood.location.city) {
debug('No city defined');
return Promise.resolve(home);
}
debug('City defined');
return new Promise((resolve) => {
this.QB
.forModel('City')
.findById(home.location.neighborhood.location.city)
.fetch()
.then((result) => {
debug('City available', result.model);
home.location.neighborhood.location.city = result.model;
resolve(home);
})
.catch((err) => {
// Do not populate city if it was not found from the database
debug('City not available', err);
home.location.neighborhood.location.city = null;
resolve(home);
});
});
}
}
<file_sep>import React from 'react';
import { Link } from 'react-router';
import Row from 'react-bootstrap/lib/Row';
import Nav from 'react-bootstrap/lib/Nav';
import Table from 'react-bootstrap/lib/Table';
import SubNavigationWrapper from '../Navigation/SubNavigationWrapper';
// import NavItemLink from 'react-router-bootstrap/lib/NavItemLink';
import TimeAgo from '../../../common/components/TimeAgo';
import Loading from '../../../common/components/Widgets/Loading';
import ContactListStore from '../../stores/ContactListStore';
import { setPageTitle } from '../../../common/Helpers';
let debug = require('debug')('Contacts');
export default class Contacts extends React.Component {
static propTypes = {
contacts: React.PropTypes.array.isRequired
}
constructor(props) {
super(props);
this.storeListener = this.onChange.bind(this);
}
state = {
error: null,
contacts: ContactListStore.getState().contacts
}
componentDidMount() {
setPageTitle('Contact requests');
ContactListStore.listen(this.storeListener);
ContactListStore.fetchContacts();
}
componentWillUnmount() {
ContactListStore.unlisten(this.storeListener);
}
onChange(state) {
debug('onChange', state);
this.setState({
contacts: ContactListStore.getState().contacts
});
}
handlePendingState() {
return (
<Loading>
<h3>Loading contacts...</h3>
</Loading>
);
}
handleErrorState() {
return (
<div className='contacts-error'>
<h3>Error loading contacts!</h3>
<p>{this.state.error.message}</p>
</div>
);
}
render() {
if (this.state.error) {
return this.handleErrorState();
}
if (ContactListStore.isLoading() || !this.state.contacts) {
return this.handlePendingState();
}
return (
<SubNavigationWrapper>
<Nav sidebar>
<h2 className='navigation-title'>
Contacts
</h2>
<p>There are {this.state.contacts.length} contacts in the system currently.</p>
</Nav>
<Row>
<h1><i className='fa fa-contact'></i> {this.state.contacts.length} contacts</h1>
<Table>
<thead>
<tr>
<th>Timestamp</th>
<th>Home</th>
<th>Contact type</th>
<th>Contact subtype</th>
<th>Sender</th>
<th>Recipient</th>
</tr>
</thead>
<tbody>
{this.state.contacts.map((contact, i) => {
let sender = null;
let senderEmail = null;
let home = null;
let recipient = null;
let recipientEmail = null;
if (contact.sender.name) {
sender = contact.sender.name;
}
if (contact.sender.email) {
senderEmail = (
<a href={`mailto:${contact.sender.email}`}>
{`<${contact.sender.email}>`}
</a>
);
}
if (contact.recipient.name) {
recipient = contact.recipient.name;
}
if (contact.recipient.email) {
recipientEmail = (
<a href={`mailto:${contact.recipient.email}`}>
{`<${contact.recipient.email}>`}
</a>
);
}
if (contact.home) {
home = (
<Link to='homeEdit' params={{id: contact.home.id}}>
{contact.home.homeTitle}
</Link>
);
}
return (
<tr key={`contact${i}`}>
<td>
<Link to='contactView' params={{id: contact.id}}>
<TimeAgo date={contact.createdAt} />
</Link>
</td>
<td>{home}</td>
<td>{contact.type}</td>
<td>{contact.subType}</td>
<td>{sender} {senderEmail}</td>
<td>{recipient} {recipientEmail}</td>
</tr>
);
})}
</tbody>
</Table>
</Row>
</SubNavigationWrapper>
);
}
}
<file_sep>'use strict';
var semver = require('semver');
var fs = require('fs');
var glob = require("glob")
const SOURCE_PATH = 'server';
if (!process.argv[2] || !semver.valid(process.argv[2])) {
console.error('Usage: node revision.js version');
process.exit(1);
}
var version = process.argv[2];
// options is optional
glob(SOURCE_PATH + "/routes/api/*.js", function (err, files) {
var maxVersion = '0.0.1';
var blocks = files.map(function(filename) {
var code = fs.readFileSync(filename, 'utf8');
var regexp = /(\/\*(.|\n)+?\*\/)/g;
var tmp = [];
var match, v, blockVersion;
// Get all the @api documentation blocks
while (match = regexp.exec(code)) {
if (!match[1].match(/@apiVersion/)) {
if (match[1].match(/@api/)) {
console.error(filename, "found a documentation block without version information", match[1]);
throw new Error('Found an API documentation block without version information in "' + filename + '", aborting');
}
continue;
}
tmp.push(match[1]);
if (v = match[1].match(/@apiVersion\s+([0-9\.\-a-z]+)/g)) {
blockVersion = v[0].replace(/@apiVersion\s+/, '');
if (semver.gt(blockVersion, maxVersion)) {
maxVersion = blockVersion;
}
}
}
// Rewrite the new version to the code blocks
code = code.replace(/@apiVersion\s+(.+)/g, '@apiVersion ' + version);
fs.writeFileSync(filename, code);
return tmp.join("\n");
});
fs.writeFileSync(SOURCE_PATH + '/routes/api/documentation/v' + maxVersion + '.js', blocks.join("\n").replace(/[ ]+\*/g, ' *'));
});
<file_sep>import React from 'react';
import HomeContainer from './HomeContainer';
import HomeStore from '../../stores/HomeStore';
import HomeDetails from './HomeDetails';
let debug = require('debug')('HomeDetailsContainer');
export default class HomeDetailsContainer extends HomeContainer {
render() {
debug('Render', this.state.home, this.props);
if (this.state.error) {
return this.handleErrorState();
}
if (HomeStore.isLoading() || !this.state.home) {
return this.handlePendingState();
}
return (
<HomeDetails home={this.state.home} />
);
}
}
<file_sep>/*global window */
import React from 'react';
import { Link } from 'react-router';
import Row from 'react-bootstrap/lib/Row';
import Col from 'react-bootstrap/lib/Col';
import Panel from 'react-bootstrap/lib/Panel';
import Button from 'react-bootstrap/lib/Button';
import Well from 'react-bootstrap/lib/Well';
import Nav from 'react-bootstrap/lib/Nav';
import TabbedArea from 'react-bootstrap/lib/TabbedArea';
import TabPane from 'react-bootstrap/lib/TabPane';
import SubNavigationWrapper from '../Navigation/SubNavigationWrapper';
import NavItemLink from 'react-router-bootstrap/lib/NavItemLink';
import HomeStore from '../../stores/HomeStore';
import HomeActions from '../../actions/HomeActions';
import { createNotification, setPageTitle } from '../../../common/Helpers';
let debug = require('../../../common/debugger')('HomesDelete');
export default class HomesDelete extends React.Component {
static propTypes = {
home: React.PropTypes.object.isRequired,
context: React.PropTypes.object
}
static contextTypes = {
router: React.PropTypes.func
}
constructor(props) {
super(props);
this.storeListener = this.onHomeStoreChange.bind(this);
}
state = {
error: null
}
componentDidMount() {
HomeStore.listen(this.storeListener);
setPageTitle([`Delete ${this.props.home.homeTitle}`, 'Homes']);
}
componentWillUnmount() {
HomeStore.unlisten(this.storeListener);
}
onHomeStoreChange(state) {
debug('onHomeStoreChange', state);
if (!state.error && state.deleted) {
debug('Redirect to home listing');
let href = this.context.router.makeHref('homes');
window.location.href = href;
return;
}
this.setState(state);
}
onDelete() {
debug('Delete');
HomeActions.deleteItem(this.props.home);
}
handlePendingState() {
createNotification({
message: 'Deleting home...'
});
return null;
}
handleErrorState() {
createNotification({
label: 'Error deleting home',
message: this.state.error.message
});
}
render() {
if (this.state.error) {
this.handleErrorState();
}
if (HomeStore.isLoading()) {
this.handlePendingState();
}
debug('Home being prepared for deletion', this.props.home);
return (
<SubNavigationWrapper>
<Nav sidebar>
<h2 className='navigation-title'>Delete Home</h2>
<NavItemLink to='homes'>
< Back
</NavItemLink>
</Nav>
<Row>
<h1><i className='fa fa-home'></i> Delete {this.props.home.homeTitle}</h1>
<TabbedArea defaultActiveKey={1}>
<TabPane eventKey={1} tab='Delete'>
<Row>
<form name='homeDetails' ref='homeDetailsForm' method='POST'>
<Col md={10} sm={10}>
<Panel header='Common'>
Please confirm the deletion of this home
</Panel>
<Well>
<Row>
<Col md={12}>
<Button bsStyle='danger' accessKey='d' onClick={this.onDelete.bind(this)}>Delete</Button>
<Link to='homeEdit' params={{id: this.props.home.id}} className='btn btn-default'>Cancel</Link>
</Col>
</Row>
</Well>
</Col>
</form>
</Row>
</TabPane>
</TabbedArea>
</Row>
</SubNavigationWrapper>
);
}
}
<file_sep>'use strict';
import fs from 'fs';
import path from 'path';
import gulp from 'gulp';
import gutil from 'gulp-util';
import gulpLoadPlugins from 'gulp-load-plugins';
import del from 'del';
import livereload from 'gulp-livereload';
import nodemon from 'nodemon';
import webpack from 'webpack';
import minifyCss from 'gulp-minify-css';
import ProjectUploader from './support/cloudinaryUpload';
const g = gulpLoadPlugins();
let nodemonInstance = null;
let DEBUG = true;
if (process.env.NODE_ENV === 'production') {
DEBUG = false;
}
let PROJECT_NAME = 'site';
if (process.env.PROJECT_NAME && process.env.PROJECT_NAME !== 'undefined') {
PROJECT_NAME = process.env.PROJECT_NAME;
}
let extend = function extend(a, b) {
a = require('util')._extend({}, a);
return require('util')._extend(a, b);
};
const babelOptions = {
optional: ['runtime', 'es7.classProperties', 'es7.classProperties'],
stage: 0
};
/**
* path globs / expressions for targets below
*/
const paths = {
tests: 'test/**/*.js',
server: {
main: 'server/app.js',
sources: ['**/*.js', '!node_modules/**', '!client/vendor/**', '!build/**', '!gulpfile.babel.js'],
views: ['views/**/*.html'],
viewsBase: 'views/',
build: './build/server'
},
clients: {
site: {
root: './clients/site',
entry: './clients/site/client.js',
sources: ['clients/site/**/*.js', 'clients/common/**/*.js'],
styles: [
'assets/css/site/**/*.scss', 'assets/css/vendor/site/**/*.scss',
'assets/css/shared/**/*.scss'
],
images: ['assets/images/**/*'],
fonts: 'assets/fonts/**/*',
statics: './build/statics/site',
distBase: './dist/site'
},
admin: {
root: './clients/admin',
entry: './clients/admin/client.js',
sources: ['clients/admin/**/*.js', 'clients/common/**/*.js'],
styles: [
'assets/css/admin/**/*.scss', 'assets/css/vendor/admin/**/*.scss',
'assets/css/shared/**/*.scss'
],
images: ['assets/images/**/*'],
fonts: 'assets/fonts/**/*',
statics: './build/statics/admin',
migrators: 'assets/js/admin/migrators/**/*.js',
distBase: './dist/admin'
},
build: './build/clients'
}
};
let webpackCommonConfig = {
module: {
loaders: [
{ test: /\.(js)$/, exclude: /node_modules|bower_components|assets/, loader: 'babel', query: babelOptions }
// ,{ test: /\.(otf|eot|svg|ttf|woff)/, loader: 'url-loader?limit=8192' }
// ,{ test: /\.(js)$/, exclude: /node_modules/, loaders: ['eslint-loader'] }
]
},
watch: false,
keepalive: false
};
if (DEBUG) {
webpackCommonConfig.devtool = 'eval-source-map';
}
let getWebpackPlugins = (project_name) => {
let plugins = [
new webpack.DefinePlugin({
'process': {
env: {
'DEBUG': DEBUG,
'NODE_ENV': JSON.stringify(process.env.NODE_ENV || 'development')
}
}
}),
new webpack.ResolverPlugin(
new webpack.ResolverPlugin.DirectoryDescriptionFilePlugin('bower.json', ['main'])
),
new webpack.PrefetchPlugin('react'),
new webpack.PrefetchPlugin('react/lib/ReactComponentBrowserEnvironment'),
new webpack.optimize.CommonsChunkPlugin('vendor', DEBUG ? 'vendor.bundle.js' : 'vendor.bundle.min.js')
];
// if (!DEBUG) {
// plugins = plugins.concat([
// new webpack.optimize.UglifyJsPlugin({minimize: true})
// ]);
// }
return plugins;
};
const siteWebpackConfig = extend(webpackCommonConfig, {
resolve: {
root: paths.clients.site.root,
extensions: ['', '.js'],
modulesDirectories: ['node_modules', 'bower_components']
},
entry: {
client: paths.clients.site.entry,
vendor: [
'react', 'react-router', 'axios', 'alt', 'iso', 'jquery'
]
},
output: {
path: paths.clients.site.statics + '/js',
filename: DEBUG ? 'client.js' : 'client.min.js'
},
plugins: getWebpackPlugins('site')
});
const siteCompiler = webpack(siteWebpackConfig);
const adminWebpackConfig = extend(webpackCommonConfig, {
resolve: {
root: paths.clients.admin.root,
extensions: ['', '.js'],
modulesDirectories: ['node_modules', 'bower_components']
},
entry: {
client: paths.clients.admin.entry,
vendor: ['react', 'react-router', 'axios', 'alt', 'iso', 'react-bootstrap']
},
output: {
path: paths.clients.admin.statics + '/js',
filename: DEBUG ? 'client.js' : 'client.min.js'
},
plugins: getWebpackPlugins('admin')
});
const adminCompiler = webpack(adminWebpackConfig);
gulp.task('lint', () => {
return gulp.src(['server/**/*.js', 'clients/**/*.js'])
.pipe(g.eslint())
.pipe(g.eslint.format())
//.pipe(eslint.failOnError());
});
gulp.task('copy-server-views', () => {
var viewsPath = path.join(paths.server.viewsBase, PROJECT_NAME, '**');
return gulp.src(viewsPath)
.pipe(gulp.dest(path.join(paths.server.build, 'views')))
.pipe(g.size({title: 'Server views'}));
});
gulp.task('build-server', ['lint', 'copy-server-views'], function () {
return gulp.src(['./server/**/*.js', './config/**/*.js'], {base: 'server'})
.pipe(g.sourcemaps.init())
.pipe(g.babel(babelOptions))
.pipe(g.sourcemaps.write('.'))
.pipe(gulp.dest(paths.server.build))
.pipe(g.size({title: 'Server source'}));
});
gulp.task('compile-client-styles', () => {
return gulp.src(paths.clients[PROJECT_NAME].styles)
.pipe(g.sourcemaps.init())
.pipe(g.sass())
.pipe(g.sourcemaps.write())
.pipe(gulp.dest(path.join(paths.clients[PROJECT_NAME].statics, 'css')))
.pipe(g.size({title: 'Client styles'}));
});
gulp.task('minify-client-styles', () => {
let stylesBasePath = path.join(paths.clients[PROJECT_NAME].statics, 'css');
let styleSources = [
path.join(stylesBasePath, 'vendor.css'),
path.join(stylesBasePath, 'common.css'),
path.join(stylesBasePath, `${PROJECT_NAME}.css`)
];
return gulp.src(styleSources)
.pipe(g.concat('all.css'))
.pipe(minifyCss({
rebase: false,
noRebase: true, // Backwards compatibility of the previous switch
advanced: false
}))
.pipe(g.rename('all.min.css'))
.pipe(gulp.dest(path.join(paths.clients[PROJECT_NAME].distBase, 'css')))
.pipe(g.size({title: 'Minified Client styles'}));
});
gulp.task('copy-client-fonts', () => {
if (!DEBUG) {
return gulp.src(path.join(paths.clients[PROJECT_NAME].statics, 'fonts', '**/*'))
.pipe(gulp.dest(path.join(paths.clients[PROJECT_NAME].distBase, 'fonts')));
}
return gulp.src(paths.clients[PROJECT_NAME].fonts)
.pipe(gulp.dest(path.join(paths.clients[PROJECT_NAME].statics, 'fonts')))
.pipe(g.size({title: 'Client fonts'}));
});
gulp.task('copy-client-images', () => {
if (!DEBUG) {
return gulp.src(path.join(paths.clients[PROJECT_NAME].statics, 'images', '**/*'))
.pipe(gulp.dest(path.join(paths.clients[PROJECT_NAME].distBase, 'images')));
}
return gulp.src(paths.clients[PROJECT_NAME].images)
.pipe(gulp.dest(path.join(paths.clients[PROJECT_NAME].statics, 'images')))
.pipe(g.size({title: 'Client images'}));
});
gulp.task('copy-client-migrators', () => {
if (!paths.clients[PROJECT_NAME].migrators) {
return;
}
if (!DEBUG) {
return gulp.src(paths.clients[PROJECT_NAME].migrators)
.pipe(gulp.dest(path.join(paths.clients[PROJECT_NAME].distBase, 'js', 'migrators')));
}
return gulp.src(paths.clients[PROJECT_NAME].migrators)
.pipe(gulp.dest(path.join(paths.clients[PROJECT_NAME].statics, 'js', 'migrators')))
.pipe(g.size({title: 'Client migrator scripts'}));
});
gulp.task('copy-client-min-js', () => {
return gulp.src(path.join(paths.clients[PROJECT_NAME].statics, 'js', '*.min.js'))
.pipe(gulp.dest(path.join(paths.clients[PROJECT_NAME].distBase, 'js')));
});
gulp.task('webpack:build-site-client', function(callback) {
// run webpack
siteCompiler.run(function(err, stats) {
if(err) throw new gutil.PluginError('webpack:build-site-client', err);
// gutil.log('[webpack:build-site-client]', stats.toString({
// colors: true
// }));
callback();
});
});
gulp.task('webpack:build-admin-client', (callback) => {
// run webpack
adminCompiler.run((err, stats) => {
if (err) throw new gutil.PluginError('webpack:build-admin-client', err);
// gutil.log('[webpack:build-admin-client]', stats.toString({
// colors: true
// }));
callback();
});
});
gulp.task('compile-site', ['copy-client-migrators', 'compile-client-styles', 'copy-client-fonts', 'copy-client-images', 'webpack:build-site-client']);
gulp.task('compile-admin', ['copy-client-migrators', 'compile-client-styles', 'copy-client-fonts', 'copy-client-images', 'webpack:build-admin-client']);
gulp.task('copy-client-templates', () => {
return gulp.src('./clients/**/*.html')
.pipe(gulp.dest(path.join(paths.clients.build)))
.pipe(g.size({title: 'Client templates'}));
});
var clientBuildDependencies = ['copy-client-templates'];
clientBuildDependencies.push('compile-' + PROJECT_NAME);
gulp.task('build-clients', clientBuildDependencies, () => {
return gulp.src(['./clients/**/*.js'], {})
.pipe(g.sourcemaps.init())
.pipe(g.babel(babelOptions).on('error', gutil.log))
.pipe(g.sourcemaps.write('.'))
.pipe(gulp.dest(paths.clients.build))
.pipe(g.size({title: 'Clients'}));
});
gulp.task('minify-clients', ['minify-client-styles', 'copy-client-migrators', 'copy-client-fonts', 'copy-client-images', 'copy-client-min-js'], () => {
});
gulp.task('clean-dist', cb => del(['dist/*', '!dist/.git'], {dot: true}, cb));
gulp.task('dist-clients', ['minify-clients'], (callback) => {
let uploader = new ProjectUploader();
uploader.upload(paths.clients[PROJECT_NAME].distBase, (err, status) => {
if (err) {
throw new gutil.PluginError('dist-client:ProjectUploader', err);
}
callback();
});
});
gulp.task('apidoc', function(done) {
g.apidoc({
src: "server/routes",
dest: "docs/api"
}, done);
});
gulp.task('watch', function(){
// if (paths.clients[PROJECT_NAME]) {
// livereload.listen({
// quiet: true
// });
// }
// gulp.watch(paths.server.views, ['copy-server-views']);
// gulp.watch(paths.server.sources, ['lint']).on('error', function(err) {
// new gutil.PluginError('Watch', err, {showStack: true});
// this.emit('end');
// });
if (paths.clients[PROJECT_NAME]) {
// gulp.watch(paths.clients[PROJECT_NAME].sources, ['build-clients', 'restart-dev']).on('error', gutil.log);
gulp.watch(paths.clients[PROJECT_NAME].sources, ['build-clients', 'lint']).on('error', gutil.log);
gulp.watch(paths.clients[PROJECT_NAME].styles, ['build-clients']).on('error', gutil.log);
}
gulp.watch('./server/**', g.batch(function(events, done) {
//console.log('server changed', events);
gulp.start('lint');
gulp.start('restart-dev', done);
if (PROJECT_NAME === 'api') {
gulp.start('apidoc');
}
})).on('error', gutil.log);
gulp.watch('./configs/**', g.batch(function(events, done) {
//console.log('configs changed', events);
gulp.start('restart-dev', done);
})).on('error', gutil.log);
// if (paths.clients[PROJECT_NAME]) {
// gulp.watch('./build/**', function(changed) {
// livereload.changed(changed);
// }).on('error', gutil.log);
// }
});
gulp.task('restart-dev', () => {
if (nodemonInstance) {
// nodemonInstance.once('restart', () => {
// if (paths.clients[PROJECT_NAME]) {
// livereload.changed();
// }
// });
nodemonInstance.emit('restart');
}
});
let devSubTasks = ['lint', 'build-clients', 'watch'];
if (PROJECT_NAME === 'api') {
devSubTasks = ['lint', 'apidoc', 'watch'];
}
gulp.task('dev', devSubTasks, () => {
nodemonInstance = nodemon({
execMap: {
js: 'node'
},
script: path.join(__dirname, 'init.js'),
env: {PROJECT_NAME: process.env.PROJECT_NAME || 'site'},
//watch: ['./build/server'],
// ignore: ['gulpfile.js'],
// ext: 'js html'
//script: path.join(paths.server.build, 'app.js'),
ignore: ['*']
}).on('restart', function() {
console.log('Restarted!');
}).on('error', gutil.log);
});
<file_sep>import React from 'react';
import AgentListStore from '../../stores/AgentListStore';
import Index from './index';
import Loading from '../../../common/components/Widgets/Loading';
class AgentsIndexContainer extends React.Component {
static propTypes = {
params: React.PropTypes.object
}
constructor(props) {
super(props);
this.storeListener = this.onChange.bind(this);
}
state = {
error: null,
items: AgentListStore.getState().items
}
componentDidMount() {
AgentListStore.listen(this.storeListener);
AgentListStore.fetchItems();
}
componentWillUnmount() {
AgentListStore.unlisten(this.storeListener);
}
onChange(state) {
console.log('AgentsIndexContainer:onChange', state);
if (state.removed) {
window.location.reload();
}
this.setState(state);
}
handlePendingState() {
return (
<Loading>
<h3>Loading agents...</h3>
</Loading>
);
}
handleErrorState() {
return (
<div className='agents-error'>
<h3>Error loading agents!</h3>
<p>{this.state.error.message}</p>
</div>
);
}
render() {
if (this.state.error) {
return this.handleErrorState();
}
if (AgentListStore.isLoading() || !this.state.items) {
return this.handlePendingState();
}
return (
<Index items={this.state.items} />
);
}
}
export default AgentsIndexContainer;
<file_sep>#! /bin/sh
# Do not change these
REV=`git rev-parse --short HEAD`
CWD=`pwd`
CONTAINER_REGISTRY_HOST=eu.gcr.io
ENV=$1
CLUSTER_NAME="homehapp-$ENV"
CLUSTER_GOOGLE_NAME=""
NUM_NODES=2
MACHINE_TYPE="n1-standard-1"
function printUsage() {
echo "Required environment variables:"
echo " PROJECT_ID: Google Project ID"
echo ""
echo "Usage PROJECT_ID=id ./support/initCluster.sh [stg,prod]"
echo "Add -d for dry-run"
}
function printUsageAndExit() {
printUsage
exit
}
if [ "$PROJECT_ID" = "" ]; then
echo "No Google Project ID defined!"
printUsageAndExit
fi
if [ "$ENV" = "" ]; then
echo "No environment defined!"
printUsageAndExit
fi
if [ ! -d "$CWD/tmp" ]; then
mkdir "$CWD/tmp"
fi
if [ "$ENV" = "prod" ]; then
MACHINE_TYPE="n1-standard-2"
fi
function createCluster() {
if [ "$1" = "-d" ]; then
echo "Execute: 'gcloud beta container clusters create $CLUSTER_NAME --num-nodes $NUM_NODES --machine-type $MACHINE_TYPE --project $PROJECT_ID'"
else
gcloud beta container clusters create $CLUSTER_NAME --num-nodes $NUM_NODES --machine-type $MACHINE_TYPE --project $PROJECT_ID
echo "Execute: kubectl config view | grep $PROJECT_ID | awk '{print $2}' | grep $CLUSTER_NAME | tail -n 1"
CLUSTER_GOOGLE_NAME=`kubectl config view | grep $PROJECT_ID | awk '{print $2}' | grep $CLUSTER_NAME | tail -n 1`
echo "CLUSTER_GOOGLE_NAME: $CLUSTER_GOOGLE_NAME"
fi
}
if [ "$2" = "-d" ]; then
echo "In Dry-Run mode"
fi
echo "Creating Container Cluster $CLUSTER_NAME"
echo ""
createCluster $2
echo ""
echo "Cluster created!"
echo ""
<file_sep>import React from 'react';
import ContentBlock from './ContentBlock';
import Icon from './Icon';
let debug = require('debug')('Attachments');
export default class Attachments extends React.Component {
static propTypes = {
attachments: React.PropTypes.array,
className: React.PropTypes.string
}
static defaultProps = {
attachments: [],
className: null
}
render() {
if (!this.props.attachments.length) {
debug('No attachments provided for Attachments widget');
return null;
}
let classes = ['attachments', 'pattern'];
if (this.props.className) {
classes.push(this.props.className);
}
return (
<ContentBlock className={classes.join(' ')}>
{
this.props.attachments.map((attachment, index) => {
return (
<div className='attachment' key={`Attachments-attachment-${index}`}>
<a target='_blank' href={attachment.url}>
<Icon type={attachment.type} className='large' />
<span className='label'>{attachment.label}</span>
</a>
</div>
);
})
}
</ContentBlock>
);
}
}
<file_sep>import React from 'react';
import { Link } from 'react-router';
import DOMManipulator from '../../../common/DOMManipulator';
import SocialMedia from '../Navigation/SocialMedia';
import UserNavigation from '../User/Navigation';
import AuthStore from '../../../common/stores/AuthStore';
// let debug = require('debug')('Navigation');
export default class Navigation extends React.Component {
constructor() {
super();
this.click = this.click.bind(this);
this.hideNavigation = this.hideNavigation.bind(this);
this.body = null;
// Bind to self
this.hideNavigation = this.hideNavigation.bind(this);
this.showNavigation = this.showNavigation.bind(this);
this.onDocumentClick = this.onDocumentClick.bind(this);
this.onResize = this.onResize.bind(this);
this.storeListener = this.onStoreChange.bind(this);
}
state = {
user: AuthStore.getState().user,
loggedIn: AuthStore.getState().loggedIn,
error: AuthStore.getState().error
}
componentDidMount() {
this.container = new DOMManipulator(this.refs.container);
this.body = new DOMManipulator(document.getElementsByTagName('body')[0]);
// Icon actions
this.icon = new DOMManipulator(this.refs.icon);
if (this.icon && this.icon.node) {
this.icon.addEvent('touchstart', this.click, true);
this.icon.addEvent('mousedown', this.click, true);
}
// Navigation actions
this.navigation = new DOMManipulator(this.refs.navigation);
// this.navigation.addEvent('mouseover', this.showNavigation, true);
// this.navigation.addEvent('mouseout', this.hideNavigation, false);
// Navigation links
this.links = this.navigation.getByTagName('a');
for (let link of this.links) {
link.addEvent('click', this.hideNavigation.bind(this));
link.addEvent('touch', this.hideNavigation.bind(this));
}
this.body = new DOMManipulator(document.getElementsByTagName('body')[0]);
window.addEventListener('resize', this.onResize);
this.onResize();
AuthStore.listen(this.storeListener);
// Fetch the user only if the loggedIn status is null, i.e. implicit
if (this.state.loggedIn === null) {
AuthStore.fetchUser();
}
}
componentWillUnmount() {
// Remove events
if (this.icon && this.icon.node) {
this.icon.removeEvent('touch', this.click, true);
this.icon.removeEvent('click', this.click, true);
}
if (this.navigation && this.navigation.node) {
this.navigation.removeEvent('mouseover', this.showNavigation, true);
this.navigation.removeEvent('mouseout', this.hideNavigation, false);
}
window.removeEventListener('resize', this.onResize);
this.onResize();
AuthStore.unlisten(this.storeListener);
}
onStoreChange(state) {
this.setState(state);
}
onResize() {
if (!window || !this.container) {
return null;
}
if (window.innerWidth <= 900) {
this.container.css({
height: `${window.innerHeight}px`
});
} else {
this.container.css({
height: 'auto'
});
}
}
onDocumentClick(event) {
// debug('onDocumentClick', event);
let target = event.target;
// Check if inside navigation
while (target.parentNode) {
if (target.id === 'navigation') {
return true;
}
target = target.parentNode;
}
// Otherwise catch the event, hide navigation and remove the self
event.preventDefault();
event.stopPropagation();
this.hideNavigation();
}
hideNavigation() {
// debug('hideNavigation', event);
if (this.icon && this.icon.node) {
this.icon.removeClass('open');
}
if (this.navigation && this.navigation.node) {
this.navigation.removeClass('open');
}
this.body.removeClass('no-scroll-small').removeClass('away-for-small');
document.removeEventListener('mousedown', this.onDocumentClick, true);
document.removeEventListener('touchstart', this.onDocumentClick, true);
return true;
}
showNavigation() {
if (this.icon && this.icon.node) {
this.icon.addClass('open');
}
if (this.navigation && this.navigation.node) {
this.navigation.addClass('open');
}
this.body.addClass('no-scroll-small').addClass('away-for-small');
document.addEventListener('mousedown', this.onDocumentClick, true);
document.addEventListener('touchstart', this.onDocumentClick, true);
}
click(event) {
// debug('body hasclass', this.body.hasClass('no-scroll-small'));
if (this.body.hasClass('no-scroll-small')) {
this.hideNavigation(event);
} else {
this.showNavigation(event);
}
event.preventDefault();
event.stopPropagation();
return false;
}
getNavigation() {
if (!this.state.loggedIn) {
return (
<SocialMedia className='primary hide-for-small' />
);
}
let onClick = (event) => {
event.preventDefault();
};
return (
<div className='container full-height-small' ref='container'>
<ul>
<li><Link to='homeStories'>Home stories</Link></li>
<li>
<Link to='neighborhoodList' params={{city: 'london'}}>Neighbourhoods</Link>
</li>
<li><a href='#' onClick={onClick.bind(this)}>Your home</a></li>
<li><Link to='page' params={{slug: 'about'}}>About</Link></li>
</ul>
<SocialMedia className='secondary' />
</div>
);
}
getNavigationIcon() {
if (!this.state.loggedIn) {
return null;
}
return (
<div ref='icon' className='icon'>
<div className='bar top'></div>
<div className='bar middle'></div>
<div className='bar bottom'></div>
</div>
);
}
render() {
return (
<div id='navigation' ref='navigation'>
<UserNavigation />
{this.getNavigationIcon()}
{this.getNavigation()}
</div>
);
}
}
<file_sep>'use strict';
module.exports = (projectRoot) => {
let config = {
security: {
csrf: false,
xframe: false,
requiredHeaders: {
exists: [
'X-Homehapp-Client'
],
valueMatch: {
'X-Homehapp-Api-Key': '<KEY>'
},
allowRoutes: [
/^health/,
/^api\-docs/,
/^_ah\/[health]/
]
}
},
isomorphic: {
enabled: false
},
authentication: {
adapters: ['jwt']
},
docs: {
expose: true,
auth: {
enabled: true,
username: 'homehapp',
password: '<PASSWORD>'
}
},
versioning: {
enabled: true,
headerKey: 'X-Homehapp-Api-Version',
pathRegexp: /^\/api\/v([0-9])/
},
extensions: {
logDevices: {
clientHeader: 'X-Homehapp-Client'
}
}
};
return config;
};
<file_sep>import React from 'react';
import { Link } from 'react-router';
import ContentNavigation from '../Header/ContentNavigation';
import HomeContact from './HomeContact';
import Modal from '../../../common/components/Widgets/Modal';
import DOMManipulator from '../../../common/DOMManipulator';
import { scrollTop } from '../../../common/Helpers';
let debug = require('debug')('HomeNavigation');
export default class HomeNavigation extends React.Component {
static propTypes = {
home: React.PropTypes.object.isRequired,
router: React.PropTypes.object
};
static contextTypes = {
router: React.PropTypes.func
}
constructor() {
super();
this.displayForm = this.displayForm.bind(this);
}
componentDidMount() {
let fb = React.findDOMNode(this.refs.facebook);
let tw = React.findDOMNode(this.refs.twitter);
let em = React.findDOMNode(this.refs.contact);
fb.href = this.facebookShareUrl();
tw.href = this.twitterShareUrl();
em.addEventListener('click', this.displayForm, true);
let navi = new DOMManipulator(this.refs.navi);
let items = navi.getByTagName('li');
for (let i = 0; i < items.length; i++) {
items[i].attr('data-index', items.length - i - 1);
}
let links = navi.getByTagName('a');
for (let link of links) {
if (link.attr('href') === window.location.pathname) {
link.addClass('active');
} else {
link.removeClass('active');
}
}
this.bindPhoneToAgents();
}
componentWillUnmount() {
this.unbindPhoneToAgents();
}
onPhoneClick(event) {
let target = document.getElementById('agentsList');
if (!target) {
return true;
}
scrollTop(target.getBoundingClientRect().top, 500);
event.preventDefault();
event.stopPropagation();
return false;
}
bindPhoneToAgents() {
if (!this.refs.phone) {
return null;
}
this.onPhoneClick = this.onPhoneClick.bind(this);
let node = new DOMManipulator(this.refs.phone);
node.addEvent('click', this.onPhoneClick, true);
}
unbindPhoneToAgents() {
if (!this.refs.phone) {
return null;
}
let node = new DOMManipulator(this.refs.phone);
node.removeEvent('click', this.onPhoneClick, true);
}
modalClose() {
let modals = document.getElementById('modals').getElementsByClassName('contact-form');
for (let modal of modals) {
if (modal.parentNode) {
modal.parentNode.removeChild(modal);
}
}
let body = document.getElementsByTagName('body')[0];
body.className = body.className.replace(/ ?no-scroll/g, '');
}
createModal() {
return (
<Modal className='white with-overflow contact-form'>
<HomeContact home={this.props.home} context={this.context} onClose={this.modalClose.bind(this)} />
</Modal>
);
}
displayForm(e) {
e.preventDefault();
e.stopPropagation();
this.modal = this.createModal();
this.modalContainer = null;
// Create the modal
React.render(this.modal, document.getElementById('modals'));
return false;
}
facebookShareUrl() {
return `https://www.facebook.com/sharer.php?u=${window.location.href}`;
}
twitterShareUrl() {
return `https://www.twitter.com/share?url=${window.location.href}&via=homehapp`;
}
getDetailsLink() {
let href = this.context.router.makeHref('home', {slug: this.props.home.slug});
let className = '';
if (this.props.home.story.enabled) {
href = this.context.router.makeHref('homeDetails', {slug: this.props.home.slug});
}
return (
<li className='details'>
<a href={href} className={className}><i className='fa fa-info-circle'></i></a>
</li>
);
}
getStoryLink() {
if (!this.props.home.story.enabled) {
return null;
}
let href = this.context.router.makeHref('home', {slug: this.props.home.slug});
let className = '';
return (
<li className='story'>
<a href={href} className={className}><i className='fa fa-home'></i></a>
</li>
);
}
getPhoneLink() {
if (!this.props.home.agents || !this.props.home.agents.length) {
debug('No agents');
return null;
}
let phone = null;
for (let agent of this.props.home.agents) {
debug('Check agent', agent);
if (agent.contactNumber) {
phone = String(agent.contactNumber).replace(/[^\+0-9]+/g, '');
break;
}
}
if (!phone) {
debug('No phone number found on any agent');
return null;
}
debug('Got number', phone);
return (
<li className='phone'>
<a href={`callto:${phone}`} ref='phone'><i className='fa fa-phone'></i></a>
</li>
);
}
render() {
return (
<ContentNavigation>
<ul ref='navi'>
{this.getPhoneLink()}
<li className='contact'>
<Link ref='contact' to='homeForm' params={{slug: this.props.home.slug}} id='contactFormLink'><i className='fa fa-envelope-o'></i></Link>
</li>
<li className='facebook'>
<a ref='facebook' target='_blank'><i className='fa fa-facebook-square'></i></a>
</li>
<li className='twitter'>
<a ref='twitter' target='_blank'><i className='fa fa-twitter'></i></a>
</li>
</ul>
</ContentNavigation>
);
}
}
<file_sep>'use strict';
import should from 'should';
import expect from 'expect.js';
import testUtils from '../utils';
import MockupData from '../../MockupData';
let app = null;
let debug = require('debug')('Home API paths');
import { merge } from '../../../clients/common/Helpers';
describe('Home API paths', () => {
let body = null;
let home = null;
let id = null;
before((done) => {
testUtils.createApp((err, appInstance) => {
app = appInstance;
app.mockup.removeAll('Home')
.then(() => {
done(err);
})
.catch((err) => {
console.error('Failed to delete homes');
done(err);
});
});
});
it('Should deny basic HTTP request without added headers', (done) => {
app.basicRequest('get', '/api/homes')
.expect(403)
.end((err, res) => {
should.not.exist(err);
done();
});
});
it('Should accept the unauthenticated request', (done) => {
app.mobileRequest('get', '/api/homes')
.expect(200)
.end((err, res) => {
should.not.exist(err);
done();
});
});
it('Should accept the authenticated request', (done) => {
app.authRequest('get', '/api/homes')
.expect(200)
.end((err, res) => {
should.not.exist(err);
done();
});
});
it('Should not be possible to create a home without credentials', (done) => {
home = merge({}, app.mockup.home);
delete home.slug;
app.mobileRequest('post', '/api/homes')
.send(home)
.expect(403)
.end((err, res) => {
should.not.exist(err);
done();
});
});
it('Should be possible to create a home with credentials', (done) => {
home = merge({}, app.mockup.home);
delete home.slug;
app.authRequest('post', '/api/homes')
.send(home)
.expect(200)
.end((err, res) => {
home = res.body.home;
should.not.exist(err);
id = home.id;
done();
});
});
it('Should update the home instead of create a new for the authenticated users', (done) => {
home = merge({}, app.mockup.home);
delete home.slug;
app.authRequest('post', '/api/homes')
.send(home)
.expect(200)
.end((err, res) => {
should.not.exist(err);
expect(res.body.home.id).to.be(id);
home = res.body.home;
expect(res.body.home.createdBy.id).to.be(app.user.uuid);
done();
});
});
it('Should not have the newly created, but not enabled home in the home list', (done) => {
app.mobileRequest('get', '/api/homes')
.expect(200)
.end((err, res) => {
should.not.exist(err);
should(res.body).have.property('homes');
expect(res.body.homes.length).to.be(0);
done();
});
});
it('Should not be possible to update the home without authentication', (done) => {
app.mobileRequest('put', `/api/homes/${home.id}`)
.send({
home: {
enabled: true
}
})
.expect(403)
.end((err, res) => {
should.not.exist(err);
done();
});
});
it('Should be possible to update the home with authentication', (done) => {
app.authRequest('put', `/api/homes/${home.id}`)
.send({
home: {
enabled: true
}
})
.expect(200)
.end((err, res) => {
should.not.exist(err);
expect(res.body.home.enabled).to.be(true);
expect(res.body.home.createdBy.id).to.be(app.user.uuid);
done();
});
});
// Breaking changes in version 1.0.1
it('Should find the home from explicit home URL', (done) => {
app.mobileRequest('get', `/api/homes/${home.id}`)
.expect(200)
.end((err, res) => {
should.not.exist(err);
should(res.body).have.property('home');
should(res.body.home.createdBy).have.property('id');
expect(res.body.home.createdBy.id).to.be(app.user.uuid);
done();
});
});
// Pre-1.0.1 has a string for createdBy
it('Should have a string for createdBy', (done) => {
app.mobileRequest('get', `/api/homes/${home.id}`, '1.0.0')
.expect(200)
.end((err, res) => {
should.not.exist(err);
should(res.body).have.property('home');
expect(res.body.home.createdBy).to.be(app.user.uuid);
done();
});
});
it('Should have the newly created, enabled home in the home list', (done) => {
app.mobileRequest('get', '/api/homes')
.expect(200)
.end((err, res) => {
should.not.exist(err);
expect(res.body.homes.length).to.be(1);
// Verify that the newly created home is found
let found = false;
res.body.homes.map((item) => {
if (item.id === home.id) {
found = true;
}
});
expect(found).to.be(true);
done();
});
});
it('Should not be possible to delete a home without authentication', (done) => {
app.mobileRequest('del', `/api/homes/${home.id}`)
.expect(403)
.end((err, res) => {
should.not.exist(err);
done();
});
});
it('Should be possible to delete a home', (done) => {
app.authRequest('del', `/api/homes/${home.id}`)
.expect(200)
.end((err, res) => {
should.not.exist(err);
done();
});
});
it('Should not have the deleted home in the list anymore', (done) => {
app.mobileRequest('get', '/api/homes')
.expect(200)
.end((err, res) => {
should.not.exist(err);
should(res.body).have.property('homes');
expect(res.body.homes.length).to.be(0);
done();
});
});
});
<file_sep>import QueryBuilder from '../../../lib/QueryBuilder';
import {/*NotImplemented,*/ BadRequest} from '../../../lib/Errors';
let debug = require('debug')('/api/contacts');
exports.registerRoutes = (app) => {
const QB = new QueryBuilder(app);
let populate = {
home: {
select: {}
}
};
app.get('/api/contacts', app.authenticatedRoute, function(req, res, next) {
debug('API fetch contacts');
debug('req.query', req.query);
QB
.forModel('Contact')
.parseRequestArguments(req)
.populate(populate)
.sort({
createdAt: -1
})
.findAll()
.fetch()
.then((result) => {
res.json({
status: 'ok',
contacts: result.models
});
})
.catch(next);
});
let validateInput = function validateInput(data) {
if (!data.firstname) {
throw new Error('Missing firstname');
}
if (!data.lastname) {
throw new Error('Missing lastname');
}
if (!data.email) {
throw new Error('Missing email address');
}
if (!data.phone) {
throw new Error('Missing phone number');
}
};
app.post('/api/contacts', app.authenticatedRoute, function(req, res, next) {
debug('API update contact with uuid', req.params.uuid);
//debug('req.body', req.body);
let data = req.body.contact;
try {
validateInput(data);
} catch (error) {
debug('Validate failed', error);
return next(new BadRequest(error.message));
}
QB
.forModel('Contact')
.createNoMultiset(data)
.then((model) => {
res.json({
status: 'ok',
contact: model
});
})
.catch((error) => {
debug('Create failed', error);
return next(new BadRequest(error.message));
});
});
app.get('/api/contacts/:uuid', app.authenticatedRoute, function(req, res, next) {
debug('API fetch contact with uuid', req.params.uuid);
debug('req.query', req.query);
if (req.params.uuid === 'blank') {
debug('Create a blank contact');
let model = new (QB.forModel('Contact')).Model();
debug('created a blank', model);
res.json({
status: 'ok',
contact: model
});
return null;
}
QB
.forModel('Contact')
.findByUuid(req.params.uuid)
.populate(populate)
.fetch()
.then((result) => {
res.json({
status: 'ok', contact: result.contact
});
})
.catch(next);
});
let updateContact = function updateContact(uuid, data) {
debug('Data', data);
return QB
.forModel('Contact')
.findByUuid(uuid)
.updateNoMultiset(data);
};
app.put('/api/contacts/:uuid', app.authenticatedRoute, function(req, res, next) {
debug('API update contact with uuid', req.params.uuid);
//debug('req.body', req.body);
let data = req.body.contact;
try {
validateInput(data);
} catch (error) {
return next(new BadRequest(error.message));
}
updateContact(req.params.uuid, data)
.then((model) => {
res.json({
status: 'ok', contact: model
});
})
.catch(next);
});
// app.patch('/api/contacts/:uuid', app.authenticatedRoute, function(req, res, next) {
// debug('API update contact with uuid', req.params.uuid);
// //debug('req.body', req.body);
//
// let data = req.body.contact;
//
// updateContact(req.params.uuid, data)
// .then((model) => {
// res.json({
// status: 'ok', contact: model
// });
// })
// .catch(next);
// });
app.delete('/api/contacts/:uuid', app.authenticatedRoute, function(req, res, next) {
QB
.forModel('Contact')
.findByUuid(req.params.uuid)
.remove()
.then((result) => {
res.json({
status: 'deleted',
contact: result.model
});
})
.catch(next);
});
};
<file_sep>import alt from '../../common/alt';
let debug = require('../../common/debugger')('AuthActions');
@alt.createActions
class AuthActions {
updateUser(user) {
this.dispatch(user);
}
fetchUser() {
debug('fetchUser');
this.dispatch();
}
fetchFailed(error) {
debug('fetchFailed', error);
this.dispatch(error);
}
}
module.exports = AuthActions;
<file_sep>import React from 'react';
import { Link } from 'react-router';
import DOMManipulator from '../../../common/DOMManipulator';
import { scrollTop } from '../../../common/Helpers';
import ApplicationStore from '../../../common/stores/ApplicationStore';
export default class Header extends React.Component {
constructor() {
super();
this.config = ApplicationStore.getState().config;
this.onScrollTop = this.onScrollTop.bind(this);
this.onMouseOver = this.onMouseOver.bind(this);
}
componentDidMount() {
window.addEventListener('scroll', this.onScrollTop);
window.addEventListener('mouseover', this.onMouseOver);
this.header = new DOMManipulator(this.refs.header);
this.prevTop = scrollTop();
this.onScrollTop();
}
componentWillUnmount() {
window.removeEventListener('scroll', this.onScrollTop);
window.removeEventListener('mouseover', this.onMouseOver);
}
onMouseOver() {
this.header.removeClass('away');
}
// Generic stuff that should happen on scrollTop
onScrollTop() {
let top = scrollTop();
if (top < this.prevTop || top < this.header.height()) {
this.header.removeClass('away');
} else {
this.header.addClass('away');
}
this.prevTop = top;
}
render() {
return (
<div id='header' ref='header'>
<Link to='app' className='logo'>
<img className='logo' src={this.config.revisionedStaticPath + '/images/homehapp-logo-horizontal-2.svg'} alt='Homehapp' />
</Link>
</div>
);
}
}
<file_sep>import passport from 'passport';
import http from 'http';
//import moment from 'moment';
import Helpers from '../../Helpers';
import QueryBuilder from '../../QueryBuilder';
class AuthenticationMiddleware {
constructor(app, config) {
this.app = app;
this.config = Helpers.merge({}, config);
this.authentication = passport;
this.sessionStore = null;
}
register() {
let self = this;
const QB = new QueryBuilder(this.app);
this.app.authenticatedRoute = [];
http.IncomingMessage.prototype.isUserActive = function () {
if (!this.isAuthenticated()) {
return false;
}
return this.user.active;
};
this.app.use(function autoSignedHelperMiddleware(req, res, next) {
if (self.authentication._autoSignedUser) {
req.user = self.authentication._autoSignedUser;
}
next();
});
this.authentication.serializeUser((user, done) => {
done(null, user.id);
});
this.authentication.deserializeUser((id, done) => {
QB
.forModel('User')
.findById(id)
.fetch()
.then((result) => {
if (!result.user) {
return done(new Error('user not found'));
}
done(null, result.user);
})
.catch(done);
});
// Registering each enabled adapter
this.config.adapters.forEach((adapterName) => {
let adapter = null;
let adapterPath = `${__dirname}/adapters/${adapterName}`;
try {
adapter = require(adapterPath);
} catch (err) {
this.app.log.error(
`Adapter ${adapterName} not found from path ${adapterPath}!`, err
);
}
if (adapter) {
adapter.register(this, this.app, this.config.adapterConfigs[adapterName] || {});
}
});
this.app.use(this.authentication.initialize());
if (this.sessionStore) {
this.app.use(this.authentication.session());
}
this.authentication.resolveLoginMethod = this.resolveLoginMethod.bind(this);
return this.authentication;
}
/**
* @param req Request
*/
resolveLoginMethod() {
let loginMethod = 'local';
if (this.config.adapters.indexOf(loginMethod) === -1) {
return null;
}
return loginMethod;
}
}
module.exports = AuthenticationMiddleware;
<file_sep>import moment from 'moment';
import bcrypt from 'bcrypt';
import { loadCommonPlugins, getImageFields, getAddressFields, commonJsonTransform, populateMetadata } from './common';
let debug = require('debug')('UserSchema');
let getSalt = function () {
let salt = bcrypt.genSaltSync(10);
return salt;
};
let calculateHash = function (password, salt) {
let hash = bcrypt.hashSync(password, salt);
return hash;
};
exports.loadSchemas = function (mongoose, next) {
let Schema = mongoose.Schema;
//let ObjectId = Schema.Types.ObjectId;
let schemas = {};
schemas.User = new Schema(populateMetadata({
uuid: {
type: String,
index: true,
unique: true
},
firstname: {
type: String
},
lastname: {
type: String
},
_email: {
type: String
},
_lastValidEmail: {
type: String,
default: null
},
_emailValidated: {
type: Boolean,
default: false
},
// Authentication related
username: {
type: String,
index: true,
unique: true
},
_salt: {
type: String
},
_saltAlg: {
type: String,
default: 'default'
},
_password: {
type: String
},
_passwordSetAt: {
type: Date
},
_lastLogin: {
type: Date
},
_accessLevel: {
type: String,
default: 'user'
},
// JWT Authentication related
_checkId: {
type: String,
default: ''
},
// Service authentication related
_service: {
facebook: {
id: {
type: String,
index: true
},
token: String
},
google: {
id: {
type: String,
index: true
},
token: String
}
},
active: {
type: Boolean,
index: true,
default: true
},
// Client device related
deviceId: {
ios: String,
android: String
},
// Push notification related
pushToken: {
ios: String,
android: String
},
contactNumber: {
type: String,
default: null
},
_contactNumberSid: {
type: String
},
_realPhoneNumber: {
type: String
},
_realPhoneNumberType: {
type: String,
default: 'mobile',
enum: ['mobile', 'local']
},
profileImage: getImageFields(),
contact: {
address: getAddressFields(),
phone: {
type: String,
default: null
}
}
}));
schemas.User.virtual('displayName').get(function () {
let displayName = [];
if (this.firstname) {
displayName.push(this.firstname);
}
if (this.lastname) {
displayName.push(this.lastname);
}
if (!displayName.length) {
//debug('populate with email');
displayName.push(this._email);
}
if (!displayName.length) {
//debug('populate with username');
displayName.push(this.username);
}
let name = displayName.join(' ');
if (name.match(/[^\s]/)) {
return name;
}
return '<unidentified johndoe>';
});
schemas.User.virtual('name').get(function () {
let firstname = this.firstname || this.givenName || '';
let lastname = this.lastname || this.familyName || '';
if (!firstname && !lastname) {
return this.username;
}
return [firstname, lastname].join(' ');
});
schemas.User.virtual('rname').get(function () {
let firstname = this.firstname || this.givenName || '';
let lastname = this.lastname || this.familyName || '';
if (!firstname && !lastname) {
return this.username;
}
return [lastname, firstname].join(', ').replace(/^, /, '');
});
schemas.User.virtual('password').set(function (password) {
debug('Set password', password);
this._salt = getSalt();
this._password = calculateHash(password, this._salt);
this._passwordSetAt = moment().utc().toDate();
});
schemas.User.virtual('email').get(function() {
return this._email;
});
schemas.User.virtual('email').set(function (email) {
email = email.toLowerCase();
if (!schemas.User.methods.isValidEmail(email)) {
throw new Error('Invalid email given');
}
this._email = email;
});
schemas.User.methods.isValidPassword = function (password) {
if (!this._password) {
return false;
}
if (this._password === calculateHash(password, this._salt)) {
return true;
}
return false;
};
schemas.User.methods.isValidEmail = function (email) {
var re = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
return re.test(email);
};
schemas.User.statics.editableFields = function () {
return [
'firstname', 'lastname', 'email', 'profileImage', 'contact'
];
};
schemas.User.virtual('publicData').get(function() {
let values = {
id: this.uuid || this.id,
firstname: this.firstname || this.givenName || '',
lastname: this.lastname || this.familyName || '',
email: this.email,
phone: this.phone,
name: this.name,
rname: this.rname,
profileImage: this.profileImage,
contact: this.contact || {
address: null
},
createdAt: this.createdAt,
createdAtTS: this.createdAtTS,
updatedAt: this.updatedAt,
updatedAtTS: this.updatedAtTS
};
});
Object.keys(schemas).forEach((name) => {
loadCommonPlugins(schemas[name], name, mongoose);
schemas[name].options.toJSON.transform = (doc, ret) => {
ret = commonJsonTransform(ret);
delete ret.password;
return ret;
};
});
next(schemas);
};
<file_sep>import React from 'react';
import { Link } from 'react-router';
import AuthStore from '../../../common/stores/AuthStore';
let debug = require('debug')('UserNavigation');
export default class UserNavigation extends React.Component {
constructor() {
super();
this.storeListener = this.onStoreChange.bind(this);
}
state = {
user: AuthStore.getState().user,
loggedIn: AuthStore.getState().loggedIn,
error: AuthStore.getState().error
}
onStoreChange(state) {
debug('got state', state);
this.setState(state);
}
componentDidMount() {
AuthStore.listen(this.storeListener);
debug('AuthStore', AuthStore.getState());
if (this.state.loggedIn === null) {
AuthStore.fetchUser();
}
}
componentWillUnmount() {
AuthStore.unlisten(this.storeListener);
}
render() {
if (this.state.user) {
return (
<div className='user-profile logged-in'>
<Link to='logout'>Log out</Link>
</div>
);
}
return (
<div className='user-profile login'>
<Link to='login'>Log in</Link>
</div>
);
}
}
<file_sep>/*eslint-env es6 */
import React from 'react';
import Router from 'react-router';
let {Route, DefaultRoute, NotFoundRoute} = Router;
import Application from './Application';
import Homepage from './Homepage';
import RouteNotFound from './ErrorPages/RouteNotFound';
// Homes
import HomesIndex from './Homes';
import HomesCreateContainer from './Homes/CreateContainer';
import HomesEditContainer from './Homes/EditContainer';
import HomesDeleteContainer from './Homes/DeleteContainer';
// Agents
import AgentsIndexContainer from './Agents/IndexContainer';
// Neighborhoods
import Neighborhoods from './Neighborhoods';
import NeighborhoodsEditContainer from './Neighborhoods/EditContainer';
// Contact requests
import Contacts from './Contacts';
import ContactsViewContainer from './Contacts/ViewContainer';
// Homes
import UsersIndexContainer from './Users/IndexContainer';
import UsersCreateContainer from './Users/CreateContainer';
import UsersEditContainer from './Users/EditContainer';
import UsersDeleteContainer from './Users/DeleteContainer';
// Pages
import PagesIndex from './Pages';
import PagesCreate from './Pages/Create';
import PagesEdit from './Pages/Edit';
import PagesDelete from './Pages/Delete';
let routes = (
<Route name='app' path='/' handler={Application}>
<DefaultRoute handler={Homepage}/>
<Route name='homes' path='/homes'>
<DefaultRoute handler={HomesIndex}/>
<Route name='homeCreate' path='create' handler={HomesCreateContainer} />
<Route name='homeDelete' path=':id/delete' handler={HomesDeleteContainer} />
<Route name='homeEdit' path=':id' handler={HomesEditContainer}>
<Route name='homeEditTab' path=':tab' handler={HomesEditContainer} />
</Route>
</Route>
<Route name='agents' path='/agents'>
<DefaultRoute handler={AgentsIndexContainer}/>
</Route>
<Route name='neighborhoods' path='/neighborhoods'>
<DefaultRoute handler={Neighborhoods}/>
<Route name='neighborhoodsAll' path='all' handler={Neighborhoods} />
<Route name='neighborhoodDelete' path=':id/delete' handler={NeighborhoodsEditContainer} />
<Route name='neighborhoodEdit' path=':id' handler={NeighborhoodsEditContainer}>
<Route name='neighborhoodEditTab' path=':tab' handler={NeighborhoodsEditContainer} />
</Route>
</Route>
<Route name='pages' path='/pages'>
<DefaultRoute handler={PagesIndex} />
<Route name='pageCreate' path='create' handler={PagesCreate} />
<Route name='pageDelete' path=':id/delete' handler={PagesDelete} />
<Route name='pageEdit' path=':id' handler={PagesEdit}>
<Route name='pageEditTab' path=':tab' handler={PagesEdit} />
</Route>
</Route>
<Route name='contacts' path='/contacts'>
<DefaultRoute handler={Contacts}/>
<Route name='contactView' path=':id' handler={ContactsViewContainer} />
<Route name='contactDelete' path=':id/delete' handler={ContactsViewContainer} />
</Route>
<Route name='users' path='/users'>
<DefaultRoute handler={UsersIndexContainer}/>
<Route name='userCreate' path='create' handler={UsersCreateContainer} />
<Route name='userDelete' path=':id/delete' handler={UsersDeleteContainer} />
<Route name='userEdit' path=':id' handler={UsersEditContainer}>
<Route name='userEditTab' path=':tab' handler={UsersEditContainer} />
</Route>
</Route>
<NotFoundRoute handler={RouteNotFound} />
</Route>
);
module.exports = routes;
<file_sep>import CityActions from '../actions/CityActions';
import CitySource from '../sources/CitySource';
import ModelStore from '../../common/stores/BaseModelStore';
export default ModelStore.generate('CityStore', {
actions: CityActions,
source: CitySource,
listeners: {}
});
<file_sep>import QueryBuilder from '../../../lib/QueryBuilder';
//import {/*NotImplemented, */BadRequest} from '../../../lib/Errors';
let debug = require('debug')('/api/cities');
exports.registerRoutes = (app) => {
const QB = new QueryBuilder(app);
let populate = {
createdBy: {},
updatedBy: {}
};
app.get('/api/cities', app.authenticatedRoute, function(req, res, next) {
QB
.forModel('City')
.parseRequestArguments(req)
.populate(populate)
.findAll()
.fetch()
.then((result) => {
res.json({
status: 'ok',
cities: result.models.map((city) => {
return city.toJSON();
})
});
})
.catch(next);
});
app.post('/api/cities', app.authenticatedRoute, function(req, res, next) {
debug('API update city with uuid', req.params.uuid);
//debug('req.body', req.body);
let data = req.body.city;
if (req.user) {
data.createdBy = req.user.id;
data.updatedBy = req.user.id;
}
QB
.forModel('City')
.populate(populate)
.createNoMultiset(data)
.then((model) => {
res.json({
status: 'ok',
city: model
});
})
.catch(next);
});
app.get('/api/cities/:uuid', app.authenticatedRoute, function(req, res, next) {
debug('API fetch city with uuid', req.params.uuid);
QB
.forModel('City')
.populate(populate)
.findByUuid(req.params.uuid)
.fetch()
.then((result) => {
res.json({
status: 'ok',
city: result.model
});
})
.catch(next);
});
let updateCity = function updateCity(uuid, data) {
debug('Update city with data', data);
return QB
.forModel('City')
.findByUuid(uuid)
.updateNoMultiset(data);
};
app.put('/api/cities/:uuid', app.authenticatedRoute, function(req, res, next) {
debug('API update city with uuid', req.params.uuid);
//debug('req.body', req.body);
let data = req.body.city;
if (req.user) {
data.updatedBy = req.user.id;
}
updateCity(req.params.uuid, data)
.then((model) => {
res.json({
status: 'ok',
city: model
});
})
.catch(next);
});
app.delete('/api/cities/:uuid', app.authenticatedRoute, function(req, res, next) {
QB
.forModel('City')
.findByUuid(req.params.uuid)
.remove()
.then((result) => {
res.json({
status: 'deleted',
city: result.model
});
})
.catch(next);
});
};
<file_sep>import QueryBuilder from '../../lib/QueryBuilder';
let debug = require('debug')('routes/pages');
import { setLastMod, initMetadata } from '../../../clients/common/Helpers';
exports.registerRoutes = (app) => {
const QB = new QueryBuilder(app);
app.get('/:slug', function(req, res, next) {
debug(`/${req.params.slug}`);
// Restrict immediately some keywords out
if (['home', 'homes', 'search', 'neighborhoods', 'api', 'auth'].indexOf(req.params.slug) !== -1) {
debug('Reserved keyword, pass through');
return next();
}
QB
.forModel('Page')
.findBySlug(req.params.slug)
.fetch()
.then((result) => {
let page = result.model;
res.locals.data.title = [page.title];
res.locals.page = {
title: page.title
// description: description
};
res.locals.data.PageStore = {
model: page
};
initMetadata(res);
setLastMod([page], res);
next();
})
.catch(() => {
// Pass the 404 headers, but allow React to render an error page
debug('page not found');
res.status(404);
next();
});
});
};
<file_sep>cd support/docker/fluentd-sidecar-gcp
PROJECT_ID=homehappweb make build push
gcloud beta container clusters create homehapp-site \
--num-nodes 1 \
--machine-type g1-small
kubectl create -f infrastructure/configs/site-controller.json
kubectl get pods -l projectName=site -o wide
kubectl create -f infrastructure/configs/site-service.json
kubectl get services
kubectl get rc
gcloud compute firewall-rules create hh-site-8080 --allow tcp:8080 \
--target-tags gke-homehapp-site-7ad9580f-node
kubectl describe services site | grep "LoadBalancer Ingress"
PROJECT_ID=homehappweb ./support/createContainers.sh site
kubectl rolling-update site-controller --image=eu.gcr.io/homehappweb/site:$(git rev-parse --short HEAD)-stg
(kubectl rolling-update site-controller -f infrastructure/configs/site-controller.json)
kubectl delete services admin
kubectl stop rc admin-controller
gcloud beta container clusters delete homehapp-admin
gcloud compute firewall-rules delete hh-admin-8080
<file_sep># Google Container engine
## Update and install gcloud components
gcloud components update beta
gcloud components update kubectl
## Configure gcloud
gcloud config set project homehappweb
gcloud config set compute/zone europe-west1-c
gcloud auth login
## Deploy Docker to google
# Resources
https://cloud.google.com/container-engine/docs/tutorials/hello-node
https://cloud.google.com/container-engine/docs/tutorials/http-balancer
http://kubernetes.io/v1.0/docs/admin/namespaces/README.html
https://cloud.google.com/solutions/automated-build-images-with-jenkins-kubernetes
https://cloud.google.com/solutions/distributed-load-testing-using-kubernetes
http://stackoverflow.com/questions/31572467/running-many-docker-instances-on-google-cloud-with-different-command-line-parame
http://stackoverflow.com/questions/31571923/on-google-container-engine-how-do-i-use-expose-with-public-ip
https://circleci.com/docs/docker
https://labs.ctl.io/auto-loadbalancing-with-fig-haproxy-and-serf/
http://blog.tutum.co/2015/05/05/load-balancing-the-missing-piece-of-the-container-world/
http://fabric8.io/guide/getStarted/gke.html
https://cloud.google.com/compute/docs/metadata#custom
https://cloud.google.com/deployment-manager/overview
https://cloud.google.com/deployment-manager/create-advanced-http-load-balanced-deployment
https://cloud.google.com/appengine/docs/managed-vms/config
https://cloud.google.com/nodejs/getting-started/deploy-mongodb
https://cloud.google.com/compute/docs/containers/container_vms
https://github.com/GoogleCloudPlatform/container-vm-guestbook-redis-python
https://github.com/GoogleCloudPlatform/gcloud-node-todos
https://github.com/GoogleCloudPlatform/gcloud-node
https://github.com/GoogleCloudPlatform/nodejs-getting-started
http://12factor.net/
https://cloud.google.com/solutions/mongodb/intro#performance
https://cloud.google.com/docs/tutorials
https://cloud.google.com/solutions/articles
https://docs.docker.com/reference/builder/
http://stackoverflow.com/questions/20932357/docker-enter-running-container-with-new-tty/26496854#26496854
<file_sep>import React from 'react';
// import { Link } from 'react-router';
import Columns from '../../../common/components/Widgets/Columns';
import ContentBlock from '../../../common/components/Widgets/ContentBlock';
import Icon from '../../../common/components/Widgets/Icon';
import Video from '../../../common/components/Widgets/Video';
import { setPageTitle } from '../../../common/Helpers';
export default class ContentAbout extends React.Component {
componentDidMount() {
setPageTitle('About us');
}
componentWillUnmount() {
setPageTitle();
}
render() {
return (
<div id='aboutUs'>
<ContentBlock className='padded about' align='left' valign='top'>
<div className='centered homehapp'>
<Icon type='homehapp' color='turquoise' className='large' />
</div>
<h1>Homes that make people happy</h1>
<p>
Homehapp stands for dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum
</p>
<hr className='spacer' />
<Video src='https://res.cloudinary.com/homehapp/video/upload/v1439796972/contentMockup/IMG_0914.mov' mode='html5' aspectRatio='16:9' />
<hr className='spacer' />
<Columns cols={2} className='padded'>
<ContentBlock>
<div className='center'>
<Icon type='clipboard' className='large' />
</div>
<h2>Partner with us</h2>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum
</p>
<p className='right'>
<a href='#'>Read more ›</a>
</p>
</ContentBlock>
<ContentBlock>
<div className='center'>
<Icon type='clipboard' className='large' />
</div>
<h2>How it works?</h2>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum
</p>
</ContentBlock>
</Columns>
</ContentBlock>
</div>
);
}
}
<file_sep>/*global window */
import React from 'react';
import Row from 'react-bootstrap/lib/Row';
import Col from 'react-bootstrap/lib/Col';
import Panel from 'react-bootstrap/lib/Panel';
import InputWidget from '../Widgets/Input';
let debug = require('../../../common/debugger')('ContactsViewDetails');
export default class ContactsViewDetails extends React.Component {
propTypes = {
contact: React.PropTypes.object.isRequired,
context: React.PropTypes.object
}
render() {
debug('Render', this.props.contact);
return (
<Row>
<Col md={10} sm={10}>
<Panel header='Sender'>
<InputWidget
type='text'
label='Sender name'
readOnly
defaultValue={this.props.contact.sender.name}
/>
<InputWidget
type='email'
label='Sender email'
readOnly
defaultValue={this.props.contact.sender.email}
/>
</Panel>
<Panel header='Message'>
<InputWidget
type='textarea'
readOnly
defaultValue={this.props.contact.message}
/>
</Panel>
</Col>
</Row>
);
}
}
<file_sep>import React from 'react';
import classNames from 'classnames';
import Image from './Image';
import Video from './Video';
import BigBlock from './BigBlock';
import DOMManipulator from '../../DOMManipulator';
import { scrollTop } from '../../Helpers';
let debug = require('debug')('BigVideo');
export default class BigVideo extends BigBlock {
static propTypes = {
video: React.PropTypes.object.isRequired,
className: React.PropTypes.string,
poster: React.PropTypes.string,
fixed: React.PropTypes.bool,
gradient: React.PropTypes.string,
proportion: React.PropTypes.number,
children: React.PropTypes.oneOfType([
React.PropTypes.array,
React.PropTypes.object
]),
align: React.PropTypes.string,
valign: React.PropTypes.string,
author: React.PropTypes.string,
zIndex: React.PropTypes.number
};
static defaultProps = {
mode: 'html5',
author: null,
poster: null,
proportion: 1,
align: 'center',
valign: 'middle',
zIndex: -10
};
constructor() {
super();
this.togglePlay = this.togglePlay.bind(this);
this.playVideo = this.playVideo.bind(this);
this.pauseVideo = this.pauseVideo.bind(this);
this.muteVideo = this.muteVideo.bind(this);
this.unmuteVideo = this.unmuteVideo.bind(this);
this.onCanPlay = this.onCanPlay.bind(this);
this.containerTolerance = -150;
this.position = null;
this.inFullscreen = false;
this.muteChanged = false;
this.canPlay = false;
this.shouldPlay = true;
}
componentDidMount() {
debug('Video player mounted');
if (!this.refs.video) {
return null;
}
this.onMounted();
this.video = React.findDOMNode(this.refs.video);
// this.containerControls();
this.playbackControls();
this.loaderControls();
this.volumeControls();
this.positionControls();
this.fullscreenControls();
}
componentWillUnmount() {
if (!this.refs.video) {
return null;
}
this.onUnmount();
}
containerControls() {
debug('containerControls');
this.container = new DOMManipulator(this.refs.container);
let prev = null;
let ts = null;
// Start watching the touches
this.container.addEvent('touchstart', (event) => {
debug('Touch', event);
if (!event.target.className.match(/\bcontent\b/)) {
return null;
}
prev = event;
ts = (new Date()).getTime();
}, false);
// Reset the previous event so that moves do not count
this.container.addEvent('touchmove', () => {
prev = null;
}, false);
this.container.addEvent('touchend', (event) => {
if (!prev) {
debug('No previous found');
return null;
}
if (!event.target.className.match(/\bcontent\b/)) {
debug('Not in the content');
return null;
}
if (Math.abs(prev.pageX - event.pageX) > 10 || Math.abs(prev.pageY - event.pageY) > 10) {
debug('Touch moved');
return null;
}
if ((new Date()).getTime() - ts > 500) {
debug('Touch lasted too long');
}
this.video.play();
});
debug(this.container);
}
playbackControls() {
// Play button
this.play = new DOMManipulator(this.refs.play);
this.play.addEvent('click', this.playVideo, true);
this.play.addEvent('touch', this.playVideo, true);
// Pause button
this.pause = new DOMManipulator(this.refs.pause);
this.pause.addClass('hidden');
this.pause.addEvent('click', this.pauseVideo, true);
this.pause.addEvent('touch', this.pauseVideo, true);
// Mobile play button
this.mobilePlay = new DOMManipulator(this.refs.mobilePlay);
this.mobilePlay.addEvent('click', this.playVideo, true);
this.mobilePlay.addEvent('touch', this.playVideo, true);
// Mobile play button
this.mobilePause = new DOMManipulator(this.refs.mobilePause);
this.mobilePause.addEvent('click', this.pauseVideo, true);
this.mobilePause.addEvent('touch', this.pauseVideo, true);
this.mobilePause.addClass('hidden');
// General video events
this.video.addEventListener('play', () => {
this.play.addClass('hidden');
this.pause.removeClass('hidden');
this.mobilePlay.addClass('hidden');
this.mobilePause.removeClass('hidden');
});
this.video.addEventListener('pause', () => {
this.play.removeClass('hidden');
this.pause.addClass('hidden');
this.mobilePlay.removeClass('hidden');
this.mobilePause.addClass('hidden');
});
this.video.addEventListener('click', this.togglePlay.bind(this));
this.video.addEventListener('touch', this.togglePlay.bind(this));
this.video.addEventListener('ended', () => {
this.video.pause();
this.video.currentTime = 0;
if (this.bar) {
this.bar.addClass('no-transitions');
this.bar.width(0);
setTimeout(() => {
this.bar.removeClass('no-transitions');
});
}
});
this.video.addEventListener('canplay', this.onCanPlay);
this.video.addEventListener('playing', () => {
this.loader.addClass('hidden');
});
}
onCanPlay() {
this.canPlay = true;
debug('canplay');
if (this.container.attr('data-viewport') === 'visible') {
this.playVideo();
this.video.removeEventListener('canplay', this.onCanPlay);
}
}
loaderControls() {
this.loader = new DOMManipulator(this.refs.loader);
let bar = this.loader.getByClass('bar')[0];
this.video.addEventListener('progress', () => {
if (!this.video.paused) {
return null;
}
let range = 0;
let bf = this.video.buffered;
let time = this.video.currentTime;
try {
while(!(bf.start(range) <= time && time <= bf.end(range))) {
range += 1;
}
let loadStartPercentage = bf.start(range) / this.video.duration;
let loadEndPercentage = bf.end(range) / this.video.duration;
let loadPercentage = 100 * (loadEndPercentage - loadStartPercentage);
bar.css({
width: `${loadPercentage}%`
});
} catch (error) {
debug('Error', error);
bar.css({
width: 0
});
}
});
}
volumeControls() {
// Mute button
this.mute = new DOMManipulator(this.refs.mute);
this.mute.addEvent('mousedown', this.muteVideo, true);
this.mute.addEvent('touchstart', this.muteVideo, true);
// Unmute button
this.unmute = new DOMManipulator(this.refs.unmute);
this.unmute.addClass('hidden');
this.unmute.addEvent('mousedown', this.unmuteVideo, true);
this.unmute.addEvent('touchstart', this.unmuteVideo, true);
this.video.addEventListener('volumechange', () => {
if (this.video.muted) {
this.mute.addClass('hidden');
this.unmute.removeClass('hidden');
} else if (!this.video.paused) {
this.mute.removeClass('hidden');
this.unmute.addClass('hidden');
}
});
}
positionControls() {
this.positionController = new DOMManipulator(this.refs.position);
this.bar = this.positionController.getByClass('bar')[0];
this.bar.skipAnimation = () => {
this.bar.addClass('no-transitions');
setTimeout(() => {
this.bar.removeClass('no-transitions');
}, 1000);
};
// Set the progress indicator when the time is updated
this.video.addEventListener('timeupdate', () => {
if (this.video.paused) {
return null;
}
if (!this.bar) {
return null;
}
this.position = this.video.currentTime / this.video.duration;
this.bar.css('width', `${this.position * 100}%`);
});
this.positionController.addEvent('mousedown', this.onPositionChange.bind(this), true);
this.positionController.addEvent('touchstart', this.onPositionChange.bind(this), true);
}
onPositionChange(event) {
if (event) {
event.stopPropagation();
event.preventDefault();
}
let x = event.offsetX || event.layerX || 0;
let pos = x / this.positionController.width();
this.video.currentTime = pos * this.video.duration;
this.loader.addClass('hidden');
this.bar.skipAnimation();
}
fullscreenControls() {
this.fullscreen = new DOMManipulator(this.refs.fullscreen);
this.wrapper = new DOMManipulator(this.refs.wrapper);
let prevScroll = 0;
if (!this.fullscreen.fullscreenEnabled()) {
this.fullscreen.addClass('hidden');
}
let toggleFullscreen = (event) => {
this.inFullscreen = true;
// Store the scroll top
if (!prevScroll) {
prevScroll = scrollTop();
}
this.container.toggleFullscreen(
() => {
this.fullscreen.addClass('in-fullscreen');
this.wrapper.addClass('fullscreen');
this.unmuteVideo();
},
() => {
this.fullscreen.removeClass('in-fullscreen');
this.wrapper.removeClass('fullscreen');
this.inFullscreen = false;
setTimeout(() => {
// Use the previous scroll top to return to the original location
if (prevScroll) {
scrollTop(prevScroll, 10);
prevScroll = 0;
}
}, 200);
}
);
event.preventDefault();
event.stopPropagation();
};
this.fullscreen.addEvent('click', toggleFullscreen, true);
this.fullscreen.addEvent('touchstart', toggleFullscreen, true);
}
// Invoked when the container is visible on the screen (note: this.threshold)
onDisplayContainer() {
if (!this.video || this.inFullscreen) {
return null;
}
// debug('onDisplayContainer');
this.bar.skipAnimation();
let iPhone = false;
if (navigator && navigator.platform && /iPhone|iPod/.test(navigator.platform)) {
iPhone = true;
}
if (!this.muteChanged) {
this.video.muted = true;
}
if (this.canPlay && !iPhone && this.shouldPlay) {
this.video.currentTime = 0;
this.video.play();
}
}
// Invoked when the container is invisible on the screen (note: this.threshold)
onHideContainer() {
if (!this.video || this.inFullscreen) {
return null;
}
// debug('onHideContainer');
this.video.pause();
}
// Toggle the play state of the video
togglePlay(event) {
if (event) {
event.stopPropagation();
event.preventDefault();
}
if (!this.video) {
return null;
}
if (this.video.paused) {
this.video.play();
} else {
this.video.pause();
}
}
playVideo(event) {
debug('playVideo');
if (event) {
event.stopPropagation();
event.preventDefault();
this.shouldPlay = true;
}
if (!this.muteChanged) {
this.video.muted = false;
}
this.video.play();
this.wrapper.addClass('is-playing');
}
pauseVideo(event) {
if (event) {
event.stopPropagation();
event.preventDefault();
this.shouldPlay = false;
}
this.video.pause();
this.wrapper.removeClass('is-playing');
}
muteVideo(event) {
if (event) {
event.stopPropagation();
event.preventDefault();
}
this.muteChanged = true;
this.video.muted = true;
}
unmuteVideo(event) {
if (event) {
event.stopPropagation();
event.preventDefault();
}
this.muteChanged = true;
this.video.muted = false;
}
render() {
let classes = [
'widget',
'big-video',
'full-height'
];
let textProps = {
'data-align': 'center',
'data-valign': 'middle'
};
if (this.props.fixed) {
classes.push('fixed');
}
if (this.props.className) {
classes.push(this.props.className);
}
if (!this.props.video || !this.props.video.url) {
console.warn('Tried to create a BigVideo block without a video', this.props.video);
return null;
}
let video = {
src: this.props.video.url,
loop: false,
controls: false,
mode: 'html5',
standalone: true,
width: null,
height: null
};
if (Array.isArray(this.props.video.derived) && this.props.video.derived.length) {
video.derived = this.props.video.derived;
}
debug('video', video);
let image = {
src: video.src.replace(/\.[a-z0-9]{2,4}$/i, '.jpg'),
alt: '',
mode: 'fill',
gravity: 'center'
};
let props = {
className: classNames(classes),
'data-gradient': this.props.gradient,
'data-align': this.props.align,
'data-valign': this.props.valign
};
if (this.props.proportion) {
props['data-proportion'] = this.props.proportion;
textProps['data-proportion'] = this.props.proportion;
}
let author = null;
if (this.props.author) {
author = (<div className='image-author'>© {this.props.author}</div>);
}
return (
<div className='bigvideo-wrapper' ref='container'>
<div {...props} ref='wrapper'>
<div className='mobile-icons hidden'>
<i className='fa fa-play' ref='mobilePlay'></i>
<i className='fa fa-pause show-for-small' ref='mobilePause'></i>
</div>
<div className='image-content'>
<Image {...image} className='show-for-small' width={640} />
<Video {...video} className='big-video hide-for-small' ref='video' />
</div>
{author}
<div className='image-text full-height' {...textProps}>
{this.props.children}
</div>
<div className='loader hide-for-small' ref='loader'>
<div className='bar'></div>
</div>
<div className='controls'>
<div className='position' ref='position'>
<div className='bar'></div>
</div>
<i className='controller fa fa-play play' ref='play'></i>
<i className='controller fa fa-pause pause' ref='pause'></i>
<i className='controller fa fa-volume-up volume mute hide-for-small' ref='mute'></i>
<i className='controller fa fa-volume-off volume unmute hide-for-small' ref='unmute'></i>
<i className='controller fullscreen hide-for-small' ref='fullscreen'>
<i className='fa enter fa-arrows-alt'></i>
<i className='fa exit fa-compress'></i>
</i>
</div>
</div>
</div>
);
}
}
<file_sep>import React from 'react';
import AgentListStore from '../../stores/AgentListStore';
import Loading from '../../../common/components/Widgets/Loading';
// let debug = require('debug')('ChooseAgents');
import Row from 'react-bootstrap/lib/Row';
import Col from 'react-bootstrap/lib/Col';
import Panel from 'react-bootstrap/lib/Panel';
import Button from 'react-bootstrap/lib/Button';
import Well from 'react-bootstrap/lib/Well';
import HomeActions from '../../actions/HomeActions';
import Image from '../../../common/components/Widgets/Image';
export default class ChooseAgents extends React.Component {
static propTypes = {
home: React.PropTypes.object,
params: React.PropTypes.object
}
constructor(props) {
super(props);
this.storeListener = this.onChange.bind(this);
this.agents = {};
}
state = {
error: null,
agents: AgentListStore.getState().items
}
componentDidMount() {
AgentListStore.listen(this.storeListener);
// See that the dispatcher is called only when the previous
// dispatcher has had the time to finish
setTimeout(() => {
if (!AgentListStore.getState().items.length) {
try {
AgentListStore.fetchItems();
} catch (error) {
console.error('Failed to get the agents list', error.message);
}
}
});
}
componentWillUnmount() {
AgentListStore.unlisten(this.storeListener);
}
onChange() {
// debug('onChange', state);
this.setState({
error: AgentListStore.getState().error,
agents: AgentListStore.getState().items
});
}
onFormChange(event) {
// debug('Event', event, event.target, event.target.checked);
let id = event.target.value;
if (typeof this.agents[id] === 'undefined') {
return true;
}
let checked = event.target.checked;
let target = event.target;
setTimeout(() => {
target.checked = checked;
if (checked) {
// debug(target.parentNode.className);
target.parentNode.parentNode.className += ' selected';
} else {
target.parentNode.parentNode.className = target.parentNode.parentNode.className.replace(/ ?selected/g, '');
}
});
}
addAgent(agent) {
if (!this.isAgentSelected(agent)) {
this.props.home.agents.push(agent);
}
return true;
}
removeAgent(agent) {
let index = this.indexOfAgent(agent);
// debug('Remove agent', agent, index);
if (index !== -1) {
this.props.home.agents.splice(index, 1);
}
}
handlePendingState() {
return (
<Loading>
<h3>Loading agents...</h3>
</Loading>
);
}
handleErrorState() {
return (
<div className='homes-error'>
<h3>Error loading agents!</h3>
<p>{this.state.error.message}</p>
</div>
);
}
onSave() {
// debug('Saving agent list', this.refs);
let agents = [];
for (let key in this.refs) {
// debug('Ref', key);
let node = React.findDOMNode(this.refs[key]);
if (node.checked && typeof this.agents[node.value] !== 'undefined') {
agents.push(this.agents[node.value].id);
}
}
let homeProps = {
id: this.props.home.id,
agents: agents
};
// debug('Update props', homeProps);
return HomeActions.updateItem(homeProps);
}
indexOfAgent(agent) {
// debug('indexOfAgent', this.props.home, agent);
if (!this.props.home.agents || !this.props.home.agents.length) {
return -1;
}
for (let i in this.props.home.agents) {
let a = this.props.home.agents[i];
// debug('Check', agent, a);
if (agent.id === a.id) {
// debug('Agent is selected', agent, i);
return i;
}
}
return -1;
}
isAgentSelected(agent) {
return !(this.indexOfAgent(agent) === -1);
}
render() {
if (this.state.error) {
return this.handleErrorState();
}
if (AgentListStore.isLoading()) {
// debug('Pending...');
return this.handlePendingState();
}
let agents = [].concat(this.state.agents);
return (
<Row>
<form method='POST' id='agentSelector' className='clearfix'>
<Col md={10} sm={10}>
<Panel header='Choose the agents'>
<ul className='choose-agent'>
{
agents.map((agent, index) => {
this.agents[agent.id] = agent;
let image = agent.mainImage;
let agency = null;
let classes = ['agent'];
let selected = this.isAgentSelected(agent);
if (selected) {
classes.push('selected');
}
let inputProps = {
type: 'checkbox',
value: agent.id,
ref: `agent${index}`,
checked: selected,
onChange: this.onFormChange.bind(this)
};
return (
<li className={classes.join(' ')} key={`agent-${index}`}>
<label>
<Image {...image} width={100} height={100} mode='fill' applySize />
<p className='name'>{agent.rname}</p>
{agency}
<input {...inputProps} />
</label>
</li>
);
})
}
</ul>
</Panel>
<Well>
<Row>
<Col md={6}>
<Button bsStyle='success' accessKey='s' onClick={this.onSave.bind(this)}>Save</Button>
</Col>
</Row>
</Well>
</Col>
</form>
</Row>
);
}
}
<file_sep>import React from 'react';
import Row from 'react-bootstrap/lib/Row';
import Nav from 'react-bootstrap/lib/Nav';
import SubNavigationWrapper from '../Navigation/SubNavigationWrapper';
import NavItemLink from 'react-router-bootstrap/lib/NavItemLink';
class Homepage extends React.Component {
render() {
return (
<SubNavigationWrapper>
<Nav sidebar>
<h2>Frontpage</h2>
<NavItemLink to='homes'>Homes</NavItemLink>
<NavItemLink to='neighborhoods'>Neighborhoods</NavItemLink>
<NavItemLink to='pages'>Content pages</NavItemLink>
<NavItemLink to='agents'>Agents</NavItemLink>
<NavItemLink to='contacts'>Contact requests</NavItemLink>
<NavItemLink to='users'>Users</NavItemLink>
</Nav>
<Row>
<h1>Welcome to admin!</h1>
</Row>
</SubNavigationWrapper>
);
}
}
export default Homepage;
<file_sep>import BaseQueryBuilder from './BaseQueryBuilder';
import {NotFound} from '../../Errors';
let debug = require('debug')('CityQueryBuilder');
export default class CityQueryBuilder extends BaseQueryBuilder {
constructor(app) {
super(app, 'City');
}
findBySlug(slug) {
this._queries.push((callback) => {
let cursor = this.Model.findOne({
slug: slug,
deletedAt: null
});
this._configurePopulationForCursor(cursor);
cursor.exec((err, city) => {
if (err) {
debug('Got error', err);
return callback(err);
}
if (!city) {
debug('No city found');
return callback(new NotFound('City not found'));
}
this._loadedModel = city;
this.result.model = city;
this.result.models = [city];
this.result.city = city;
callback();
});
});
return this;
}
initialize() {
}
}
<file_sep>'use strict';
module.exports = function (projectRoot) {
var config = {
logging: {
Console: {
enabled: true,
level: 'debug'
},
File: {
level: 'debug'
}
},
database: {
adapter: 'mongoose',
adapterConfig: {
uri: [
'mongodb://homehapp:hSXDuC2VX850FjfQEV+5HFYYrPfw55F0@mongodb2-hhmdb-1/homehapp-staging',
'mongodb://homehapp:hSXDuC2VX850FjfQEV+5HFYYrPfw55F0@mongodb2-hhmdb-2'
],
options: {
replset: {
rs_name: 'rs0'
}
}
}
},
google: {
enabled: true
},
clientConfig: {
siteHost: 'http://alpha.homehapp.com:8080'
}
};
return config;
};
<file_sep>'use strict';
import fs from 'fs';
import path from 'path';
import {getEnvironmentValue} from '../server/lib/Helpers';
module.exports = (projectRoot) => {
let env = getEnvironmentValue('NODE_ENV', 'development');
let port = getEnvironmentValue('NODE_PORT', 3001);
let hostname = getEnvironmentValue('HOSTNAME', 'localhost');
let host = `http://${hostname}:${port}`;
let databaseOptions = {};
if (getEnvironmentValue('DATABASE_OPTIONS', null)) {
try {
databaseOptions = JSON.parse(getEnvironmentValue('DATABASE_OPTIONS', {}));
} catch (err) {
console.error(`Error while parsing database options: ${err.message}`);
}
}
let fileLoggingOptions = {
enabled: false,
level: 'info'
};
let fileLogPath = getEnvironmentValue('LOG_PATH', null);
if (fileLogPath) {
fileLoggingOptions.enabled = true;
fileLoggingOptions.filename = path.join(fileLogPath, 'general.log');
if (!fs.existsSync(fileLogPath)) {
try {
fs.mkdirSync(fileLogPath);
} catch (err) {
console.error('Error creating log path', err);
fileLoggingOptions.enabled = false;
}
}
}
let config = {
port: port,
host: host,
logging: {
Console: {
enabled: true,
json: false,
level: 'warn'
},
File: fileLoggingOptions
},
database: {
adapter: getEnvironmentValue('DATABASE_ADAPTER', 'mongoose'),
adapterConfig: {
uri: getEnvironmentValue('DATABASE_URI', `mongodb://localhost/homehapp-${env}`),
options: databaseOptions
}
},
security: {
csrf: true,
csrfSkipRoutes: [],
xframe: 'DENY'
},
authentication: {
adapters: [],
adapterConfigs: {
basic: {
username: 'homehapp',
password: '<PASSWORD>'
},
local: {
cookie: {
maxAge: 86000
},
session: {
name: 'qvik:common',
secret: 'really-secret-string-here'
},
routes: {
login: '/auth/login',
logout: '/auth/logout'
}
},
jwt: {
tokenField: 'X-Homehapp-Auth-Token',
secret: null,
checkIdField: '_checkId',
keys: {
public: path.join(projectRoot, 'auth-public.pem'),
private: path.join(projectRoot, 'auth-private.pem')
},
issuer: 'homehapp.com',
audience: 'homehapp.com',
lifetimeSeconds: 0 // 0 = Unexpiring
},
facebook: {
appId: null,
secret: null,
callbackUrl: null
},
google: {
clientID: null,
clientSecret: null,
callbackUrl: null
}
}
},
errors: {
includeData: false
},
cdn: {
adapter: 'cloudinary',
adapterConfig: {
projectName: 'homehapp',
uri: getEnvironmentValue('CLOUDINARY_URI', 'cloudinary://674338823352987:urOckACznNPsN58_1zewwJmasnI@homehapp'),
transformations: {}
}
},
isomorphic: {
enabled: true
},
google: {
enabled: false,
api: {
key: '<KEY>',
audience: '897870831901-fq0r8oi489tbvces0a6c7c9lcd4s1uq4.apps.googleusercontent.com'
}
},
versioning: {
enabled: false
},
docs: {
expose: false
},
extensions: {
twilio: {
sid: 'ACfe13687d3f1fc9f6217a3c5af02e1d76',
token: '184d32f9b009255e676cc15b87636331',
phoneNumbers: {
country: 'FI',
options: {
VoiceEnabled: true
}
}
}
},
mailchimp: {
apikey: '<KEY>',
newsletter: '914a5e94a5'
},
clientConfig: {
siteHost: 'http://localhost:3001',
google: {
apiKey: "<KEY>"
},
cloudinary: {
projectId: 'homehapp',
baseUrl: 'https://res.cloudinary.com/homehapp/image/upload/',
apiUrl: '//api.cloudinary.com/v1_1/homehapp',
transformations: {
// Pinterest styled card
card: {
mode: 'fill',
width: 280
},
// Property list
propList: {
mode: 'fill',
width: 300,
height: 300
},
thumbnail: {
mode: 'thumb',
width: 100,
height: 100
},
pinkynail: {
mode: 'thumb',
width: 50,
height: 50
},
// Full content
full: {
mode: 'fill',
width: 1200,
height: 800
},
half: {
mode: 'fill',
width: 800,
height: 600
},
// Full-sized preview
preview: {
mode: 'fill',
height: 960
},
// Big image variants
large: {
mode: 'scale',
width: 1920
},
medium: {
mode: 'scale',
width: 1000
},
small: {
mode: 'fill',
height: 600
},
gallery: {
mode: 'fit',
width: 600,
height: 600
},
fullscreen: {
width: 1920,
height: 1080,
mode: 'fit'
},
// Hexagon mask
masked: {
mode: 'fill',
width: 271,
height: 320,
mask: 'hexagon',
gravity: 'faces',
applyDimensions: true
}
}
}
}
};
return config;
};
<file_sep>import basicAuth from 'basic-auth-connect';
exports.register = function (parent, app, config) {
app.use(basicAuth(config.username, config.password));
};
<file_sep>import React from 'react';
import InputWidget from '../Widgets/Input';
import NeighborhoodListStore from '../../stores/NeighborhoodListStore';
let debug = require('debug')('NeighborhoodSelect');
export default class NeighborhoodSelect extends React.Component {
static propTypes = {
selected: React.PropTypes.oneOfType([
React.PropTypes.null,
React.PropTypes.object
]),
onChange: React.PropTypes.func
}
constructor(props) {
super(props);
this.storeListener = this.onChange.bind(this);
this.selected = null;
}
state = {
error: null,
neighborhoods: []
}
componentDidMount() {
NeighborhoodListStore.listen(this.storeListener);
setTimeout(() => {
NeighborhoodListStore.fetchItems();
}, 100);
}
componentWillUnmount() {
NeighborhoodListStore.unlisten(this.storeListener);
}
onChange(state) {
debug('onChange', state);
this.setState({
neighborhoods: NeighborhoodListStore.getState().items
});
}
isSelected(neighborhood) {
return !!(this.props.selected && String(this.props.selected.id) === String(neighborhood.id));
}
getValue() {
if (this.selected) {
return this.selected.id;
}
return null;
}
updateSelected() {
let selected = this.refs.neighborhoodSelect.getValue();
this.selected = null;
for (let neighborhood of this.state.neighborhoods) {
if (neighborhood.id === selected) {
this.selected = neighborhood;
if (typeof this.props.onChange === 'function') {
this.props.onChange(neighborhood);
}
break;
}
}
}
render() {
let neighborhoods = [
{
id: '',
title: 'Select one (optional)'
}
];
let selected = null;
if (this.props.selected) {
neighborhoods.push(this.props.selected);
selected = this.props.selected.id;
}
for (let neighborhood of this.state.neighborhoods) {
if (neighborhoods.indexOf(neighborhood) === -1) {
neighborhoods.push(neighborhood);
}
}
return (
<InputWidget
type='select'
ref='neighborhoodSelect'
label='Neighborhood'
defaultValue={selected}
onChange={this.updateSelected.bind(this)}>
{neighborhoods.map((neighborhood, index) => {
let opts = {
value: neighborhood.id
};
return (
<option {...opts} key={'nhs-' + index}>{neighborhood.title}</option>
);
})}
</InputWidget>
);
}
}
<file_sep>import {merge} from '../../lib/Helpers';
//let debug = require('debug')('Extension:commonLocals');
export function register(app) {
app.getLocals = function(req, res, ext = {}) {
ext = ext || {};
let user = req.user;
function cleanUser() {
if (!user) {
return null;
}
if (user.toJSON) {
return user.toJSON();
}
return null;
}
let appLocals = JSON.parse(JSON.stringify(app.locals)) || {};
let resLocals = JSON.parse(JSON.stringify(res.locals)) || {};
let jsIncludeHtml = '';
if (ext.includeJS && ext.includeJS.length) {
ext.includeJS.forEach((path) => {
let tag = `<script type="text/javascript" src="${path}"></script>`;
jsIncludeHtml += tag;
});
}
let opts = merge({
layout: 'layout',
staticPath: app.staticPath,
revisionedStaticPath: app.revisionedStaticPath,
revision: app.PROJECT_REVISION,
site: {
title: '',
host: app.config.host
},
user: cleanUser(),
env: app.config.env,
html: '',
cssIncludeHtml: '',
jsIncludeHtml: jsIncludeHtml,
bodyClass: '',
metadatas: [],
openGraph: {}
}, appLocals, resLocals, ext);
if (!opts.body) {
opts.body = '';
}
return Promise.resolve(opts);
};
return Promise.resolve();
}
<file_sep>import QueryBuilder from '../../lib/QueryBuilder';
import {NotFound, BadRequest, Forbidden} from '../../lib/Errors';
import {randomString, exposeHome, exposeUser} from '../../lib/Helpers';
import axios from 'axios';
exports.registerRoutes = (app) => {
const QB = new QueryBuilder(app);
let neighborhoodPopulation = {
select: 'uuid title description story images'
};
let populateAttributes = {
'location.neighborhood': neighborhoodPopulation,
'myNeighborhood': neighborhoodPopulation,
agents: {
select: 'uuid firstname lastname title contactNumber email images'
},
createdBy: {},
updatedBy: {}
};
// (new GoogleAuth).getApplicationDefault(function(err, authClient) {
// console.log('google err', err, authClient);
// });
// console.log('app.config.google.api.json', app.config.google.api.json);
// (new GoogleAuth).fromJSON(app.config.google.api.json, (err, authClient) => {
// console.log('glg', err, authClient);
// });
function generateTokenAndRespond(req, res, user, home) {
return new Promise((resolve, reject) => {
let tokenData = app.authentication.createTokenForUser(user);
let userJson = exposeUser(user, req.version, req.user);
if (!home) {
let createMyNeighborhood = (home) => {
return new Promise((createResolve, createReject) => {
QB
.forModel('Neighborhood')
.createNoMultiset({
createdBy: user,
slug: `nh-${user.uuid}-${(new Date()).getTime()}`, // create something for the slug
enabled: false
})
.then((neighborhood) => {
home.myNeighborhood = neighborhood;
home.save(() => {
createResolve(home);
});
}).catch(createReject);
});
};
// No home provided, get by user id or create if not available
app.log.debug(`No home provided, get by user id or create if not available`);
QB
.forModel('Home')
.populate(populateAttributes)
.query({
createdBy: user
})
.findOne()
.fetch()
.then((result) => {
if (!result.model.myNeighborhood) {
app.log.debug(`creating neighborhood for home ${result.model.uuid}`);
createMyNeighborhood(result.model)
.then((home) => {
app.log.debug(`created neighborhood for home ${result.model.uuid}`);
generateTokenAndRespond(req, res, user, home);
}).catch((err) => {
app.log.error(`Error creating my neighborhood: ${err.message}`, err);
generateTokenAndRespond(req, res, user, result.model);
});
} else {
generateTokenAndRespond(req, res, user, result.model);
}
})
.catch((err) => {
app.log.debug(`no home found for user, creating it now`);
if (!(err instanceof NotFound)) {
app.log.error(`Error occurred while finding users home: ${err.message}`, err);
}
QB
.forModel('Home')
.createNoMultiset({
createdBy: user,
enabled: false
})
.then((model) => {
app.log.debug(`creating neighborhood for home ${model.uuid}`);
createMyNeighborhood(model)
.then((home) => {
app.log.debug(`created neighborhood for home ${model.uuid}`);
generateTokenAndRespond(req, res, user, home);
}).catch((err) => {
app.log.error(`Error creating my neighborhood: ${err.message}`, err);
generateTokenAndRespond(req, res, user, model);
});
});
});
return null;
}
QB
.forModel('User')
.findById(user.id)
.setExtraData({
_checkId: tokenData.checkId
})
.update({})
.then(() => {
res.json({
status: 'ok',
session: {
token: tokenData.token,
expiresIn: tokenData.expiresIn,
expiresAt: tokenData.expiresAt || '',
user: userJson
},
home: exposeHome(home, req.version, req.user)
});
})
.catch(reject);
});
}
/**
* @apiDefine AuthSuccessResponse
* @apiVersion 1.0.1
*
* @apiSuccess {String} status Status message
* @apiSuccess {Object} session
* @apiSuccess {String} session.token Authentication token for the user
* @apiSuccess {Number} session.expiresIn Expiration time in seconds
* @apiSuccess {Datetime} session.expiresAt ISO-8601 Formatted Expiration Datetime
* @apiSuccess {Object} session.user <a href="#api-Users-UserData">User</a> object
* @apiSuccess {Object} home <a href="#api-Homes-GetHomeById">Home</a> object
*/
/**
* @apiDefine AuthSuccessResponseJSON
* @apiVersion 1.0.1
*
* @apiSuccessExample {json} Success-Response
* HTTP/1.1 200 OK
* {
* "status": "ok",
* "session": {
* "token": "...",
* "expiresIn": ...,
* "expiresAt": "...",
* "user": {...}
* },
* "home": {...}
* }
*/
/**
* @api {post} /api/auth/login Login the Mobile User
* @apiVersion 1.0.1
* @apiName UserLogin
* @apiGroup Authentication
*
* @apiUse MobileRequestHeadersUnauthenticated
* @apiParam {String} service Name of the external service. Enum[facebook, google]
* @apiParam {Object} user Details of the user
* @apiParam {String} user.id User's Id from the service
* @apiParam {String} user.email User's email from the service
* @apiParam {String} user.token User's token from the service
* @apiParam {String} [user.displayName] User's full name from the service
* @apiParam {String} [user.firstname] User's first name from the service
* @apiParam {String} [user.lastname] User's last name from the service
*
* @apiParamExample {json} Request-Example
* {
* "service": "facebook",
* "user": {
* "id": "12345678",
* "email": "<EMAIL>",
* "token": "<PASSWORD>",
* "displayName": "<NAME>",
* "firstname": "Testi",
* "lastname": "Testiikkeli"
* }
* }
*
* @apiUse AuthSuccessResponse
* @apiUse AuthSuccessResponseJSON
* @apiUse UserSuccessResponseJSON
* @apiUse HomeSuccessResponseJSON
*
* @apiError (400) BadRequest Invalid request body, missing parameters.
* @apiError (403) Forbidden User account has been disabled
* @apiErrorExample {json} Error-Response
* HTTP/1.1 403 Forbidden
* {
* "status": "failed",
* "error": "account disabled"
* }
*/
app.post('/api/auth/login', function(req, res, next) {
let data = req.body.user;
if (!req.clientInfo || !req.clientInfo.deviceID) {
return next(new BadRequest('invalid request, no device info found'));
}
if (!req.body.service || !data.email || !data.token) { // || !data.id
return next(new BadRequest('invalid request body'));
}
let verifyToken = () => {
if (app.config.env === 'test' && data.id === 'tester') {
return Promise.resolve(data.id);
}
return new Promise((resolve, reject) => {
switch (req.body.service) {
case 'google':
axios.get(`https://www.googleapis.com/oauth2/v3/tokeninfo?id_token=${data.token}`)
.then((response) => {
if (response.status !== 200) {
return reject(new Forbidden('error validating token: invalid response'));
}
if (response.data.aud !== app.config.google.api.audience) {
app.log.error('Error validating Google token: Audience mismatch');
return reject(new Forbidden('error validating token'));
}
resolve(response.data.sub);
})
.catch((err) => {
app.log.error(`Error validating Google token: ${err.message}`, err);
reject(new Forbidden('invalid token received'));
});
break;
case 'facebook':
axios.get('https://graph.facebook.com/me', {
headers: {
'Authorization': `Bearer ${data.token}`
}
})
.then((response) => {
if (response.status !== 200) {
return reject(new Forbidden('error validating token: invalid response'));
}
if (!response.data.id) {
app.log.error('Error validating Facebook token: Id missing');
return reject(new Forbidden('error validating token'));
}
resolve(response.data.id);
})
.catch((err) => {
app.log.error(`Error validating Facebook token: ${err.message}`, err);
reject(new Forbidden('invalid token received'));
});
break;
default:
reject(new BadRequest('unsupported service'));
}
});
};
verifyToken()
.then((verifiedUserId) => {
let deviceIdData = {};
let deviceType = 'ios';
if (req.clientInfo.platform) {
deviceType = req.clientInfo.platform.toLowerCase();
}
deviceIdData[deviceType] = req.clientInfo.deviceID;
let query = {};
let user = null;
// Add this query to bound the user to current device
//query[`deviceId.${deviceType}`] = req.clientInfo.deviceID;
QB
.forModel('User')
.query(query)
.findByServiceId(req.body.service, verifiedUserId)
.fetch()
.then((result) => {
if (!result.user.active) {
return next(new Forbidden('account disabled'));
}
generateTokenAndRespond(req, res, result.user);
})
.catch((err) => {
if (err instanceof NotFound) {
let serviceData = {};
serviceData[req.body.service] = {
id: data.id,
token: data.token
};
let userData = {
username: `${req.body.service}${data.id}`,
email: data.email,
//password: `${<PASSWORD>}${data.id}`,
deviceId: deviceIdData,
_service: serviceData
};
if (data.displayName) {
let firstname = '';
let lastname = '';
let parts = data.displayName.split(' ');
firstname = parts[0];
if (parts.length > 1) {
lastname = data.displayName.substr(firstname.length + 1);
}
userData.firstname = firstname;
userData.lastname = lastname;
}
if (data.firstname) {
userData.firstname = data.firstname;
}
if (data.lastname) {
userData.lastname = data.lastname;
}
QB
.forModel('User')
.createNoMultiset(userData)
.then((model) => {
generateTokenAndRespond(req, res, model);
})
.catch(next);
} else {
next(err);
}
});
})
.catch(next);
});
/**
* @api {post} /api/auth/register/push Register/Unregister Mobile Client for Push
* @apiVersion 1.0.1
* @apiName PushRegister
* @apiGroup Authentication
*
* @apiDescription When given a valid pushToken, registers the device to receive push notifications. Otherwise unregisters the device.
*
* @apiPermission authenticated
* @apiUse MobileRequestHeadersAuthenticated
* @apiParam {String} pushToken Push token for mobile client
*
* @apiSuccessExample {json} Success-Response:
* HTTP/1.1 200 OK
* {
* "status": "ok"
* }
*
* @apiError (400) BadRequest Invalid request body, missing parameters.
* @apiError (403) Forbidden User account has been disabled
* @apiErrorExample Error-Response:
* HTTP/1.1 403 Forbidden
* {
* "status": "failed",
* "error": "account disabled"
* }
*/
app.post('/api/auth/register/push', app.authenticatedRoute, function(req, res, next) {
if (!req.body.hasOwnProperty('pushToken')) {
return next(new BadRequest('invalid request body'));
}
let tokenData = {};
let deviceType = 'ios';
if (req.clientInfo.platform) {
deviceType = req.clientInfo.platform.toLowerCase();
}
tokenData[deviceType] = req.body.pushToken;
QB
.forModel('User')
.findById(req.user.id)
.fetch()
.then((result) => {
if (!result.user.active) {
return next(new Forbidden('account disabled'));
}
QB
.forModel('User')
.findById(result.user.id)
.setExtraData({
pushToken: tokenData
})
.update({})
.then(() => {
res.send({
status: 'ok'
});
})
.catch(next);
})
.catch(next);
});
/**
* @api {get} /api/auth/check Check session validity
* @apiVersion 1.0.1
* @apiName CheckSessionValidity
* @apiGroup Authentication
*
* @apiDescription Allows for checking if the session is valid
*
* @apiPermission authenticated
* @apiUse MobileRequestHeadersAuthenticated
*
* @apiSuccessExample {json} Success-Response:
* HTTP/1.1 200 OK
* {
* "status": "ok"
* }
*
* @apiError (403) Forbidden User account has been disabled
* @apiErrorExample Error-Response:
* HTTP/1.1 403 Forbidden
* {
* "status": "failed",
* "error": "account disabled"
* }
*/
app.get('/api/auth/check', app.authenticatedRoute, function(req, res, next) {
if (!req.user) {
return next(new Forbidden('invalid request'));
}
res.json({status: 'ok'});
});
};
<file_sep>import SourceBuilder from '../../common/sources/Builder';
import ContactActions from '../actions/ContactActions';
export default SourceBuilder.build({
name: 'ContactSource',
actions: {
base: ContactActions,
error: ContactActions.requestFailed
},
methods: {}
});
<file_sep>"use strict";
import should from "should";
import request from "supertest";
import testUtils from "../utils";
var app = null;
describe("Default routes without authentication", () => {
before((done) => {
testUtils.createApp((err, appInstance) => {
app = appInstance;
done(err);
});
});
it("Should find path /", (done) => {
request(app)
.get("/")
.expect(200)
.end((err, res) => {
should.not.exist(err);
done();
});
});
});
<file_sep>/* global window */
import React from 'react';
import DOMManipulator from '../../../common/DOMManipulator';
import Card from './Card';
export default class PropertyCards extends React.Component {
static propTypes = {
items: React.PropTypes.array.isRequired,
cols: React.PropTypes.number,
max: React.PropTypes.number,
className: React.PropTypes.string
}
static defaultProps = {
cols: 4,
max: Infinity,
className: null
};
constructor() {
super();
this.resize = this.resize.bind(this);
this.cols = 0;
}
componentDidMount() {
window.addEventListener('resize', this.resize);
// Trigger the events on load
this.resize();
}
componentDidUpdate() {
this.resize(true);
}
componentWillUnmount() {
window.removeEventListener('resize', this.resize);
}
resetMargins(cards) {
for (let i = 0; i < cards.length; i++) {
cards[i].css({
marginLeft: null,
marginTop: null
});
}
}
getMinHeight(arr) {
let min = Math.min.apply(Math, arr);
return arr.indexOf(min);
}
// Generic stuff that should happen when the window is resized
resize(forced = false) {
if (typeof this.refs.cards === 'undefined') {
return null;
}
let container = new DOMManipulator(this.refs.cards);
let cards = container.getByClass('card');
// No cards available
if (cards.length < 1) {
return null;
}
let width = cards[0].width();
let cols = Math.min(this.props.cols, Math.floor(container.width() / width), cards.length);
let heights = [];
if (cols === this.cols && !forced) {
return null;
}
// Store the changed column count
this.cols = cols;
if (cols === 1) {
this.resetMargins(cards);
container.addClass('single').removeClass('animate');
return null;
}
container.removeClass('single');
// Populate zero heights
for (let i = 0; i < cols; i++) {
heights.push(0);
}
// Set the positions
for (let i = 0; i < cards.length; i++) {
let c = this.getMinHeight(heights);
let offset = Math.round((c / cols - 0.5) * (cols * width));
cards[i].css({
marginLeft: `${offset}px`,
marginTop: `${heights[c]}px`
});
heights[c] += cards[i].height();
}
let max = Math.max.apply(Math, heights);
container.css('min-height', `${max}px`).addClass('animate');
}
render() {
let classes = ['widget', 'cards'];
if (this.props.className) {
classes.push(this.props.className);
}
return (
<div ref='cards' className={classes.join(' ')}>
{
this.props.items.map((item, index) => {
if (this.props.max <= index) {
return null;
}
return (
<Card item={item} key={index} />
);
})
}
</div>
);
}
}
<file_sep>import BaseQueryBuilder from './BaseQueryBuilder';
import {NotFound} from '../../Errors';
import {merge} from '../../Helpers';
let debug = require('debug')('HomeQueryBuilder');
export default class HomeQueryBuilder extends BaseQueryBuilder {
constructor(app) {
super(app, 'Home');
}
initialize() {
}
findBySlug(slug) {
this._queries.push((callback) => {
let cursor = this.Model.findOne({
slug: slug,
deletedAt: null
});
this._configurePopulationForCursor(cursor);
cursor.exec((err, model) => {
if (err) {
return callback(err);
}
if (!model) {
debug(`No homes found with slug '${slug}'`);
return callback(new NotFound('home not found'));
}
this.result.model = model;
this.result.models = [model];
this.result.home = model;
this.result.homeJson = model.toJSON();
this._loadedModel = model;
callback();
});
});
return this;
}
findByNeighborhood(neighborhood) {
let query = {
deletedAt: null,
'location.neighborhood': neighborhood
};
this._queries.push((callback) => {
let cursor = this.Model.find(query);
this._configurePopulationForCursor(cursor);
cursor.exec((err, homes) => {
if (err) {
debug('Got error', err);
return callback(err);
}
if (!homes) {
homes = [];
}
this.result.models = homes;
this.result.homes = homes;
callback();
});
});
return this;
}
findByUuid(uuid) {
this._queries.push((callback) => {
let findQuery = {
uuid: uuid,
deletedAt: null
};
if (this._opts.query) {
findQuery = merge(findQuery, this._opts.query);
}
let cursor = this.Model.findOne(findQuery);
this._configurePopulationForCursor(cursor);
cursor.exec((err, model) => {
if (err) {
return callback(err);
}
if (!model) {
return callback(new NotFound('home not found'));
}
this.result.model = model;
this.result.models = [model];
this.result.home = model;
this.result.homeJson = model.toJSON();
this._loadedModel = model;
callback();
});
});
return this;
}
}
<file_sep>#! /bin/sh
# Do not change these
REV=`git rev-parse --short HEAD`
CWD=`pwd`
CONTAINER_REGISTRY_HOST=eu.gcr.io
ENV=$1
PNAME=$2
NO_CLEAN=$3
BUILD_REVISION_FILE="$CWD/BUILD_REVISION";
function printUsage() {
echo "Required environment variables:"
echo " PROJECT_ID: Google Project ID"
echo ""
echo "Usage ./support/createContainers.sh [stg|prod] [project name]"
echo "Add -n as last argument, to not clean old containers"
}
function printUsageAndExit() {
printUsage
exit
}
function exitWithError() {
echo "$1" 1>&2
exit 1
}
if [ "$PROJECT_ID" = "" ]; then
echo "No Google Project ID defined!"
printUsageAndExit
fi
if [ "$ENV" = "" ]; then
echo "No environment defined!"
printUsageAndExit
fi
if [ "$PNAME" = "" ]; then
echo "No project defined!"
printUsageAndExit
fi
echo "Building Docker Containers for project '$PNAME' to revision $REV"
function checkAndUpdateBuildRevision() {
if [ -f $BUILD_REVISION_FILE ]; then
local CURR_REV=`cat $BUILD_REVISION_FILE`
local NEW_REV=`expr $CURR_REV + 1`
echo "Updating build revision to ${NEW_REV}"
echo $NEW_REV > $BUILD_REVISION_FILE
else
echo "Setting build revision to 1"
echo "1" > $BUILD_REVISION_FILE
fi
}
# Arguments:
# envName: Enum(prod, stg)
function buildContainer() {
local DOCKER_FILE="$CWD/Dockerfile.$PNAME.$1"
docker build -t $CONTAINER_REGISTRY_HOST/$PROJECT_ID/$PNAME -f $DOCKER_FILE $CWD || exitWithError "Error building container from $DOCKER_FILE"
}
# Arguments:
# envName: Enum(prod, stg)
function tagContainer() {
local REV_STRING="$REV-$1"
docker tag -f $CONTAINER_REGISTRY_HOST/$PROJECT_ID/$PNAME $CONTAINER_REGISTRY_HOST/$PROJECT_ID/$PNAME:$REV_STRING || exitWithError "Error tagging container"
}
function cleanOldImages() {
docker images | grep "$PROJECT_ID/$PNAME" | grep -v 'latest' | grep -v $REV-prod | grep -v $REV-stg | awk '{print $3}' | xargs docker rmi
}
function pushContainers() {
gcloud docker push $CONTAINER_REGISTRY_HOST/$PROJECT_ID/$PNAME || exitWithError "Error pushing container to google registry"
}
checkAndUpdateBuildRevision
if [ "$ENV" = "prod" ]; then
echo "Building and tagging production container"
echo ""
buildContainer "prod"
tagContainer "prod"
else
echo "Building and tagging staging container"
echo ""
buildContainer "stg"
tagContainer "stg"
fi
if [ "$NO_CLEAN" = "" ]; then
echo "Cleaning old Docker containers"
echo ""
cleanOldImages
echo ""
fi
echo ""
echo "Pushing containers to registry"
echo ""
pushContainers
echo "Finished!"
exit
<file_sep>#! /bin/sh
# Do not change these
REV=`git rev-parse --short HEAD`
CWD=`pwd`
CONTAINER_REGISTRY_HOST=eu.gcr.io
ENV="prod"
PNAME="$1-$ENV"
PBNAME="$1"
CERT_PATH_PREFIX=$2
CLUSTER_NAME="homehapp-$1-$ENV"
CLUSTER_GOOGLE_NAME=""
NODE_GOOGLE_NAME=""
function printUsage() {
echo "Required environment variables:"
echo " PROJECT_ID: Google Project ID"
echo ""
echo "Usage PROJECT_ID=id ./support/production/createCluster.sh [project_name] [path_to_cert(-extension)]"
echo "Add -d for dry-run"
}
function printUsageAndExit() {
printUsage
exit
}
if [ "$PROJECT_ID" = "" ]; then
echo "No Google Project ID defined!"
printUsageAndExit
fi
if [ "$PNAME" = "" ]; then
echo "No project defined!"
printUsageAndExit
fi
if [ ! -d "$CWD/tmp" ]; then
mkdir "$CWD/tmp"
fi
function createCluster() {
if [ "$1" = "-d" ]; then
echo "Execute: 'gcloud beta container clusters create $CLUSTER_NAME --num-nodes 1 --machine-type n1-standard-1 --project $PROJECT_ID'"
else
gcloud beta container clusters create $CLUSTER_NAME --num-nodes 1 --machine-type n1-standard-1 --project $PROJECT_ID
CLUSTER_GOOGLE_NAME=`kubectl config view | grep $PROJECT_ID | awk '{print $2}' | grep $CLUSTER_NAME | tail -n 1`
NODE_GOOGLE_NAME=`kubectl get nodes --context=$CLUSTER_GOOGLE_NAME | awk '{print $1}' | tail -n 1`
local len=${#NODE_GOOGLE_NAME}
NODE_GOOGLE_NAME=${NODE_GOOGLE_NAME:0:$((len-5))}
fi
}
function setContext() {
if [ "$CLUSTER_GOOGLE_NAME" = "" ]; then
CLUSTER_GOOGLE_NAME=`kubectl config view | awk '{print $2}' | grep $CLUSTER_NAME | tail -n 1`
fi
if [ "$1" = "-d" ]; then
echo "Execute: 'kubectl config use-context $CLUSTER_GOOGLE_NAME'"
else
kubectl config use-context $CLUSTER_GOOGLE_NAME
fi
}
function createController() {
local SOURCE_CONFIG="$CWD/infrastructure/configs/prod/project-controller-tpl.json"
local TARGET_CONFIG="$CWD/tmp/$PNAME-controller.json"
local TMP_FILE="/tmp/$PNAME-controller.json"
sed "s/:PROJECT_NAME/$PNAME/g" $SOURCE_CONFIG > $TARGET_CONFIG
sed "s/:PROJECT_BASE_NAME/$PBNAME/g" $TARGET_CONFIG > $TMP_FILE && mv $TMP_FILE $TARGET_CONFIG
sed "s/:PROJECT_ID/$PROJECT_ID/g" $TARGET_CONFIG > $TMP_FILE && mv $TMP_FILE $TARGET_CONFIG
sed "s/:CONTROLLER_NAME/$PNAME-controller-$REV/g" $TARGET_CONFIG > $TMP_FILE && mv $TMP_FILE $TARGET_CONFIG
sed "s/:REV/$REV/g" $TARGET_CONFIG > $TMP_FILE && mv $TMP_FILE $TARGET_CONFIG
sed "s/:ENV/$ENV/g" $TARGET_CONFIG > $TMP_FILE && mv $TMP_FILE $TARGET_CONFIG
if [ "$1" = "-d" ]; then
echo "Execute: 'kubectl create -f $CWD/tmp/$PNAME-controller.json'"
else
kubectl create -f "$CWD/tmp/$PNAME-controller.json"
rm $TARGET_CONFIG
fi
}
function createService() {
local SOURCE_CONFIG="$CWD/infrastructure/configs/prod/project-service-tpl.json"
local TARGET_CONFIG="$CWD/tmp/$PNAME-service.json"
local TMP_FILE="/tmp/$PNAME-service.json"
sed "s/:PROJECT_NAME/$PNAME/g" $SOURCE_CONFIG > $TARGET_CONFIG
sed "s/:PROJECT_ID/$PROJECT_ID/g" $TARGET_CONFIG > $TMP_FILE && mv $TMP_FILE $TARGET_CONFIG
if [ "$1" = "-d" ]; then
echo "Execute: 'kubectl create -f $CWD/tmp/$PNAME-service.json'"
else
kubectl create -f "$CWD/tmp/$PNAME-service.json"
rm $TARGET_CONFIG
fi
}
function createProxySecret() {
local SOURCE_CONFIG="$CWD/infrastructure/configs/prod/proxy-secret-tpl.json"
local TARGET_CONFIG="$CWD/tmp/$PNAME-proxy-secret.json"
local TMP_FILE="/tmp/$PNAME-proxy-secret.json"
local PROXY_CERT=`base64 -i $CERT_PATH_PREFIX.pem`
local PROXY_KEY=`base64 -i $CERT_PATH_PREFIX.key`
local PROXY_DHP=`base64 -i ${CERT_PATH_PREFIX}_dhp.pem`
sed "s/:PROXY_CERT/$PROXY_CERT/g" $SOURCE_CONFIG > $TARGET_CONFIG
sed "s/:PROXY_KEY/$PROXY_KEY/g" $TARGET_CONFIG > $TMP_FILE && mv $TMP_FILE $TARGET_CONFIG
sed "s/:PROXY_DHP/$PROXY_DHP/g" $TARGET_CONFIG > $TMP_FILE && mv $TMP_FILE $TARGET_CONFIG
if [ "$1" = "-d" ]; then
echo "Execute: 'kubectl create -f $CWD/tmp/$PNAME-proxy-secret.json'"
else
kubectl create -f "$CWD/tmp/$PNAME-proxy-secret.json"
rm $TARGET_CONFIG
fi
}
function createProxyController() {
local SOURCE_CONFIG="$CWD/infrastructure/configs/prod/proxy-controller-tpl.json"
local TARGET_CONFIG="$CWD/tmp/$PNAME-proxy-controller.json"
local TMP_FILE="/tmp/$PNAME-proxy-controller.json"
local UC_PNAME=`echo "${PBNAME}_${ENV}" | awk '{print toupper($0)}'`
local SERVICE_HOST="${UC_PNAME}_SERVICE_HOST"
local SERVICE_PORT="${UC_PNAME}_SERVICE_PORT_ENDPOINT"
sed "s/:PROJECT_NAME/$PNAME-proxy/g" $SOURCE_CONFIG > $TARGET_CONFIG
sed "s/:PROJECT_ID/$PROJECT_ID/g" $TARGET_CONFIG > $TMP_FILE && mv $TMP_FILE $TARGET_CONFIG
sed "s/:CONTROLLER_NAME/$PNAME-proxy-controller-$REV/g" $TARGET_CONFIG > $TMP_FILE && mv $TMP_FILE $TARGET_CONFIG
sed "s/:REV/$REV/g" $TARGET_CONFIG > $TMP_FILE && mv $TMP_FILE $TARGET_CONFIG
sed "s/:ENV/$ENV/g" $TARGET_CONFIG > $TMP_FILE && mv $TMP_FILE $TARGET_CONFIG
sed "s/:SERVICE_HOST/$SERVICE_HOST/g" $TARGET_CONFIG > $TMP_FILE && mv $TMP_FILE $TARGET_CONFIG
sed "s/:SERVICE_PORT/$SERVICE_PORT/g" $TARGET_CONFIG > $TMP_FILE && mv $TMP_FILE $TARGET_CONFIG
if [ "$1" = "-d" ]; then
echo "Execute: 'kubectl create -f $CWD/tmp/$PNAME-proxy-controller.json'"
else
kubectl create -f "$CWD/tmp/$PNAME-proxy-controller.json"
rm $TARGET_CONFIG
fi
}
function createProxyService() {
local SOURCE_CONFIG="$CWD/infrastructure/configs/prod/proxy-service-tpl.json"
local TARGET_CONFIG="$CWD/tmp/$PNAME-proxy-service.json"
local TMP_FILE="/tmp/$PNAME-proxy-service.json"
sed "s/:PROJECT_NAME/$PNAME-proxy/g" $SOURCE_CONFIG > $TARGET_CONFIG
sed "s/:PROJECT_ID/$PROJECT_ID/g" $TARGET_CONFIG > $TMP_FILE && mv $TMP_FILE $TARGET_CONFIG
if [ "$1" = "-d" ]; then
echo "Execute: 'kubectl create -f $CWD/tmp/$PNAME-proxy-service.json'"
else
kubectl create -f "$CWD/tmp/$PNAME-proxy-service.json"
rm $TARGET_CONFIG
fi
}
function configureProxyFirewall() {
if [ "$1" = "-d" ]; then
echo "Execute: 'gcloud compute firewall-rules create ${CLUSTER_NAME}-web-public --allow TCP:80,TCP:443 --source-ranges 0.0.0.0/0 --target-tags gke-${CLUSTER_NAME}-node'"
else
gcloud compute firewall-rules create ${CLUSTER_NAME}-web-public --project $PROJECT_ID --allow TCP:80,TCP:443 --source-ranges 0.0.0.0/0 --target-tags gke-${CLUSTER_NAME}-node
fi
}
function tagClusterNodes() {
if [ "$1" = "-d" ]; then
echo "Execute: 'gcloud compute instances add-tags {} --project $PROJECT_ID --tags gke-${CLUSTER_NAME}-node'"
else
gcloud compute instances list --project $PROJECT_ID -r "^gke-${CLUSTER_NAME}.*node.*$" | tail -n +2 | cut -f1 -d' ' | xargs -L 1 -I '{}' gcloud compute instances add-tags {} --project $PROJECT_ID --tags gke-${CLUSTER_NAME}-node
fi
}
if [ "$3" = "-d" ]; then
echo "In Dry-Run mode"
fi
echo "Creating Container Cluster $CLUSTER_NAME"
echo ""
createCluster $3
setContext $3
echo ""
echo "Creating Replication Controller $PNAME-controller"
createController $3
echo ""
echo "Creating Service $PNAME-service"
createService $3
echo ""
echo "Creating Proxy Secret $PNAME-proxy-secret"
createProxySecret $3
echo ""
echo "Creating Proxy Replication Controller $PNAME-proxy-controller"
createProxyController $3
echo ""
echo "Creating Proxy Service $PNAME-proxy-service"
createProxyService $3
echo ""
echo "Tagging Cluster nodes for $CLUSTER_NAME"
tagClusterNodes $3
echo ""
echo "Configuring Firewall for $PNAME-proxy"
configureProxyFirewall $3
echo ""
echo "Cluster created!"
echo ""
if [ "$3" = "" ]; then
echo "Execute following script after few minutes to find out the external IP."
echo "kubectl describe services $PNAME-proxy --context=$CLUSTER_GOOGLE_NAME | grep 'LoadBalancer Ingress'"
fi
<file_sep>/* global window */
import React from 'react';
import { Link } from 'react-router';
import { merge } from '../../../common/Helpers';
let debug = require('debug')('StoryBlocks');
export default class StoryBlocks extends React.Component {
static propTypes = {
context: React.PropTypes.object
}
static contextTypes = {
router: React.PropTypes.func
}
addViewControls(home) {
if (!home.story.enabled) {
return null;
}
let storyUrl = this.context.router.makeHref('home', {slug: home.slug});
let detailsUrl = this.context.router.makeHref('homeDetails', {slug: home.slug});
let neighborhood = null;
let city = 'london';
if (home.location && home.location.neighborhood) {
debug('home.location.neighborhood.city', home.location.neighborhood);
if (home.location.neighborhood && home.location.neighborhood.location && home.location.neighborhood.location.city && home.location.neighborhood.location.city.slug) {
city = home.location.neighborhood.location.city.slug;
}
neighborhood = (
<li>
<Link to='neighborhoodView' params={{
city: city,
neighborhood: home.location.neighborhood.slug}
}>
Neighborhood
</Link>
</li>
);
}
let currentPath = null;
try {
currentPath = window.location.pathname;
} catch (error) {
debug('window is not defined, most likely due to the server side rendering');
}
return (
<ul className='home-links'>
<li className={(storyUrl === currentPath) ? 'active' : ''}>
<a href={storyUrl}>
Story
</a>
</li>
<li className={(detailsUrl === currentPath) ? 'active' : ''}>
<a href={detailsUrl}>
Info
</a>
</li>
{neighborhood}
</ul>
);
}
prependBlocks(existingBlocks, home) {
let blocks = [];
if (!existingBlocks[0] || ['BigVideo', 'BigImage'].indexOf(existingBlocks[0].template) === -1) {
blocks.push({
template: 'BigImage',
properties: {
title: home.homeTitle,
image: merge({}, home.mainImage)
}
});
}
blocks = blocks.concat(existingBlocks);
blocks[0].properties.secondary = this.addViewControls(home);
return blocks;
}
appendBlocks(blocks) {
blocks = blocks || [];
// Add location
if (this.props.home.location.coordinates && this.props.home.location.coordinates[0] && this.props.home.location.coordinates[1]) {
let area = null;
if (this.props.home.location.neighborhood && this.props.home.location.neighborhood.area) {
area = this.props.home.location.neighborhood.area;
}
blocks.push({
template: 'Map',
properties: {
center: this.props.home.location.coordinates,
zoom: 12,
area: area,
markers: [{
location: this.props.home.location.coordinates,
title: this.props.home.homeTitle
}]
}
});
}
// Add agents block
blocks.push({
template: 'Separator',
properties: {
icon: 'marker'
}
});
blocks.push({
template: 'Agents',
properties: {
agents: this.props.home.agents,
home: this.props.home
}
});
// Add neighborhood block
if (this.props.home.location.neighborhood) {
blocks.push({
template: 'Separator',
properties: {}
});
blocks.push({
template: 'Neighborhood',
properties: this.props.home.location.neighborhood
});
}
return blocks;
}
}
<file_sep># Create NAT Gateway
Based on instructions from
https://developers.google.com/compute/docs/networking#natgateway
## Create instance
gcloud compute instances create "project-nat" \
--description="NATs outgoing internet for nodes" --zone "europe-west1-c" \
--no-boot-disk-auto-delete \
--machine-type "f1-micro" --can-ip-forward \
--image=debian-7-backports \
--tags "project-nat" --metadata-from-file "startup-script=startup-scripts/configure-nat-gw.sh"
## Create Network route
gcloud compute routes create "no-ip-internet-route" \
--destination-range "0.0.0.0/0" \
--next-hop-instance-zone europe-west1-c --next-hop-instance=project-nat --tags "project-noip" --priority 200
<file_sep>// let debug = require('debug')('/auth/login');
exports.registerRoutes = (app) => {
app.get('/auth/login', function(req, res) {
let redirectTo = '/';
if (req.query.redirectTo) {
redirectTo = req.query.redirectTo;
}
if (req.body.redirectTo) {
redirectTo = req.body.redirectTo;
}
app.getLocals(req, res, {
includeClient: false,
bodyClass: 'adminLogin',
csrfToken: req.csrfToken(),
redirectUrl: redirectTo
})
.then((locals) => {
//locals.layout = null;
res.render('login', locals);
});
});
};
<file_sep>import {Forbidden} from '../../lib/Errors';
exports.registerRoutes = (app) => {
if (!app.authentication) {
return;
}
let authError = (req, res) => {
let redirectTo = '/';
if (req.query.redirectTo) {
redirectTo = req.query.redirectTo;
}
if (req.body.redirectTo) {
redirectTo = req.body.redirectTo;
}
res.status(403);
app.getLocals(req, res, {
includeClient: false,
bodyClass: 'adminLogin',
csrfToken: req.csrfToken(),
redirectUrl: redirectTo
})
.then((locals) => {
//locals.layout = null;
res.render('login', locals);
});
};
app.post('/auth/login', function(req, res, next) {
let loginMethod = app.authentication.resolveLoginMethod(req);
let redirectTo = '/';
if (req.query.redirectTo) {
redirectTo = req.query.redirectTo;
}
if (req.body.redirectTo) {
redirectTo = req.body.redirectTo;
}
app.authentication.authenticate(loginMethod, function(err, user, info) {
if (err) {
return authError(req, res, next);
}
if (!user) {
if (info.message === 'user not active') {
authError(req, res, next);
return next(new Forbidden('Account not active'));
}
return authError(req, res, next);
// return next(new Forbidden('Invalid credentials'));
}
req.logIn(user, function(loginErr) {
if (loginErr) {
return authError(req, res, next);
}
if (req.xhr) {
return res.send({status: 'ok', user: user});
}
res.redirect(redirectTo);
});
})(req, res, next);
});
app.get('/auth/logout', function(req, res) {
req.logOut();
let redirectTo = '/';
if (req.query.redirectTo) {
redirectTo = req.query.redirectTo;
}
if (req.body.redirectTo) {
redirectTo = req.body.redirectTo;
}
res.redirect(redirectTo);
});
app.post('/auth/logout', function(req, res) {
return res.send({status: 'ok'});
});
app.get('/auth/check', app.authenticatedRoute, function(req, res, next) {
if (!req.user) {
return next(new Error('no user found from request!'));
}
res.send({
status: 'ok',
user: req.user.publicData
});
});
};
<file_sep>export default require('../../common/actions/BaseListActions')
.generate('HomeListActions', {});
<file_sep>import ContactActions from '../actions/ContactActions';
import ContactSource from '../sources/ContactSource';
import ModelStore from '../../common/stores/BaseModelStore';
export default ModelStore.generate('ContactStore', {
actions: ContactActions,
source: ContactSource,
listeners: {}
});
<file_sep>import cloudinary from 'cloudinary';
import {merge} from '../../../Helpers';
let debug = require('debug')('CloudinaryAdapter');
class CloudinaryAdapter {
constructor(app, config) {
this.app = app;
this.config = merge({}, config);
let uri = require('url').parse(this.config.uri, true);
let uriConfig = {
'cloud_name': uri.host,
'api_key': uri.auth && uri.auth.split(':')[0],
'api_secret': uri.auth && uri.auth.split(':')[1],
'private_cdn': uri.pathname != null,
'secure_distribution': uri.pathname && uri.pathname.substring(1)
};
this.config = merge(this.config, uriConfig);
cloudinary.config(this.config);
this.cloudinary = cloudinary;
this.registerRoutes();
}
getStaticPath() {
return `//res.cloudinary.com/${this.config.projectName}/raw/upload`;
}
sendResponse(body, res) {
debug('sendResponse', body);
let transformation = this.config.transformations.default;
if (this.config.transformations[body.folder]) {
transformation = this.config.transformations[body.folder];
}
let signData = {
folder: body.folder || '',
timestamp: Math.floor(new Date().getTime() / 1000)
};
// Allowed optional extra params
let opts = ['eager', 'eager_async', 'eager_notification_url'];
for (let k of opts) {
if (typeof body[k] !== 'undefined') {
signData[k] = body[k];
}
}
if (transformation) {
signData.transformation = transformation;
}
res.send({
status: 'ok',
signed: this.cloudinary.utils.sign_request(signData)
});
}
registerRoutes() {
debug('Registering POST route: /api/cdn/signature');
this.app.post('/api/cdn/signature', (req, res) => {
debug('Request', req);
if (!req.body) {
debug('No body found');
let rawBody = '';
req.setEncoding('utf8');
req.on('data', function(chunk) {
rawBody += chunk;
debug('Chunk', rawBody);
// "1k should be enough for anybody"
if (rawBody.length > 1024) {
res.status(413).json({
status: 'error',
message: 'Request entity too large, allowed JSON request maximum size is 1k'
});
}
});
req.on('end', () => {
let body = JSON.parse(rawBody);
if (!body) {
throw new Error('Failed to parse JSON request');
}
this.sendResponse(body, res);
});
return null;
}
debug('Got JSON');
this.sendResponse(req.body, res);
});
}
}
module.exports = CloudinaryAdapter;
<file_sep>// let debug = require('debug')('NeighborhoodActions');
export default require('../../common/actions/BaseModelActions')
.generate('NeighborhoodActions', {});
<file_sep>.PHONY: build push
build:
docker build -t eu.gcr.io/$(PROJECT_ID)/fluentd-sidecar-gcp .
push:
gcloud docker push eu.gcr.io/$(PROJECT_ID)/fluentd-sidecar-gcp
<file_sep>import moment from 'moment';
import Errors from '../../lib/Errors';
import {generateUUID} from '../../lib/Helpers';
// Update models createdAt value on save
// if model has the field and it is not set yet
exports.createdAt = (schema, options) => {
if (!schema.path('createdAt')) {
return;
}
schema.pre('save', function (next) {
if (!this.createdAt) {
this.createdAt = moment().millisecond(0).utc().toDate();
}
next();
});
if (options && options.index) {
schema.path('createdAt').index(options.index);
}
};
// Update models updatedAt value on save if model has the field
exports.lastModified = (schema, options) => {
if (!schema.path('updatedAt')) {
return;
}
schema.pre('save', function (next) {
this.updatedAt = moment().millisecond(0).utc().toDate();
next();
});
if (options && options.index) {
schema.path('updatedAt').index(options.index);
}
};
// Generate and set UUID for model has the field and it is not set yet
exports.uuid = (schema, options) => {
if (!schema.path('uuid')) {
return;
}
schema.pre('save', function (next) {
if (!this.uuid) {
this.uuid = generateUUID();
}
next();
});
if (options && options.index) {
schema.path('uuid').index(options.index);
}
};
exports.multiSet = schema => {
schema.methods.multiSet = function (obj, allowedFields, ignoreMissing = true) {
if (!allowedFields) {
return;
}
if (!Array.isArray(allowedFields)) {
return;
}
let i = allowedFields.indexOf('id');
if (i !== -1) {
allowedFields.splice(i, 1);
}
i = allowedFields.indexOf('_id');
if (i !== -1) {
allowedFields.splice(i, 1);
}
allowedFields.forEach(field => {
if ((typeof obj[field] !== 'undefined' && ignoreMissing) || !ignoreMissing) {
this.set(field, obj[field]);
}
});
};
};
exports.aclEnableIS = (schema, options) => {
if (!options) {
return;
}
if (!options.requestModelName) {
return;
}
schema.statics.reqUserIs = function(requirements) {
return function(req, res, next) {
if (!req.user) {
return next(new Errors.Forbidden('not enough permissions'));
}
if (!requirements) {
return next();
}
if (!Array.isArray(requirements)) {
requirements = [requirements];
}
let reqModel = req[options.requestModelName];
if (!reqModel) {
console.warn(`no request model ${options.requestModelName} found`);
return next();
}
if (typeof reqModel.is !== 'function') {
console.warn(`ACL: No is(user, requirements, done) -method defined for request model ${options.requestModelName}`);
return next();
}
reqModel.is(req.user, requirements, (err, status) => {
if (err) {
return next(err);
}
if (!status) {
return next(new Errors.Forbidden('not enough permissions'));
}
next();
});
};
};
};
exports.aclEnableCAN = (schema, options) => {
if (!options) {
return;
}
if (!options.requestModelName) {
return;
}
schema.statics.reqUserCan = function(requirement, withRequest = false) {
return function(req, res, next) {
if (!req.user) {
return next(new Errors.Forbidden('not enough permissions'));
}
if (!requirement) {
return next();
}
let reqModel = req[options.requestModelName];
if (!reqModel) {
console.warn(`no request model ${options.requestModelName} found`);
return next();
}
let method = 'can';
if (withRequest) {
method = 'canRequest';
}
if (typeof reqModel[method] !== 'function') {
console.warn(`ACL: No ${method}(user, requirement, done) -method defined for request model ${options.requestModelName}`);
return next();
}
let args = [req.user, requirement];
if (withRequest) {
args = [req, req.user, requirement];
}
args.push((err, status) => {
if (err) {
return next(err);
}
if (!status) {
return next(new Errors.Forbidden('not enough permissions'));
}
next();
});
reqModel[method].apply(reqModel, args);
};
};
};
exports.enableACL = (schema, options) => {
if (!options) {
return;
}
if (!options.requestModelName) {
return;
}
exports.aclEnableIS(schema, options);
exports.aclEnableCAN(schema, options);
};
<file_sep>import React from 'react';
let debug = require('debug')('DOMManipulator');
class DOMManipulator {
constructor(node) {
try {
let dom = React.findDOMNode(node);
if (!dom) {
throw new Error('Not a React node');
}
this.node = dom;
} catch (error) {
this.node = node;
}
}
hasClass(className) {
let regexp = new RegExp(`(^| )${className}($| )`);
if (this.node.className.match(regexp)) {
return true;
}
return false;
}
addClass(className) {
if (this.hasClass(className)) {
return this;
}
if (this.node.className) {
this.node.className += ` ${className}`;
} else {
this.node.className = className;
}
return this;
}
removeClass(className) {
if (!this.hasClass(className)) {
return this;
}
let regexp = new RegExp(`(^| )${className}($| )`);
this.node.className = this.node.className.replace(regexp, ' ').replace(/[ ]{2,}/, ' ').replace(/^ /, '').replace(/ $/, '');
return this;
}
addEvent(eventName, fn, capture = false) {
this.node.addEventListener(eventName, fn, capture);
}
removeEvent(eventName, fn, capture = false) {
this.node.removeEventListener(eventName, fn, capture);
}
css(args, value = null) {
if (typeof args === 'string') {
if (value) {
this.node.style[args] = value;
return this;
}
return (this.node.currentStyle) ? this.node.currentStyle[args] : getComputedStyle(this.node, null)[args];
}
if (!this.node) {
return null;
}
if (!this.node.style) {
this.node.style = {};
}
for (let i in args) {
this.node.style[i] = args[i];
}
return this;
}
/**
* Get or set an attribute of the current node
*
* @params key string Attribute key
* @params value mixed When undefined, act as a getter, otherwise set the attribute
* @return self
*/
attr(key, value = undefined) {
if (value === undefined) {
if (this.node.hasAttribute(key)) {
return this.node.getAttribute(key);
}
return undefined;
}
if (value === null) {
this.node.removeAttribute(key);
} else {
this.node.setAttribute(key, value);
}
return this;
}
/**
* Get or set the node width
*
* @params number width Either the width to be set or null to return the current width
* @return mixed Current width when getting, self when setting
*/
width(width = null) {
if (width === null) {
return this.node.offsetWidth;
}
return this.css('width', `${width}px`);
}
/**
* Get or set the node height
*
* @params number height Either the height to be set or null to return the current height
* @return mixed Current height when getting, self when setting
*/
height(height = null) {
if (height === null) {
return this.node.offsetHeight;
}
return this.css('height', `${height}px`);
}
getByClass(className) {
let tmp = [];
let objects = this.node.getElementsByClassName(className);
for (let i = 0; i < objects.length; i++) {
tmp.push(new DOMManipulator(objects[i]));
}
return tmp;
}
getByTagName(tag) {
let tmp = [];
let objects = this.node.getElementsByTagName(tag);
for (let i = 0; i < objects.length; i++) {
tmp.push(new DOMManipulator(objects[i]));
}
return tmp;
}
getNode() {
return this.node;
}
parent(skipLevels = 0) {
let node = this.node;
do {
if (!node.parentNode) {
throw new Exception('This node has no parents', this.node);
}
node = node.parentNode;
skipLevels--;
} while (skipLevels >= 0);
return new DOMManipulator(node);
}
children() {
let children = this.node.children;
let tmp = [];
for (let i = 0; i < children.length; i++) {
tmp.push(new DOMManipulator(children[i]));
}
return tmp;
}
visible(tolerance = 0) {
let el = this.node;
var top = el.offsetTop;
var height = el.offsetHeight;
while(el.offsetParent) {
el = el.offsetParent;
top += el.offsetTop;
}
return (
top - tolerance < (window.pageYOffset + window.innerHeight) &&
(top + height + tolerance) > window.pageYOffset
);
}
offset() {
let el = this.node;
var top = el.offsetTop;
var left = el.offsetLeft;
while(el.offsetParent) {
el = el.offsetParent;
top += el.offsetTop;
left += el.offsetLeft;
}
return {
top: top,
left: left
};
}
scrollTo(speed = 400, offset = 0) {
let f = 5;
let init = document.documentElement.scrollTop + document.body.scrollTop;
let c = Math.ceil(speed / f);
let i = 0;
// Invalid count
if (c <= 0) {
return null;
}
if (speed < 10) {
window.scrollTo(0, init + dy * i);
return null;
}
let target = Math.max(this.offset().top + offset, 0);
let dy = (target - init) / c;
let nextHop = function() {
i++;
window.scrollTo(0, init + dy * i);
if (i < c) {
setTimeout(nextHop, f);
}
};
nextHop();
}
isFullscreen() {
return !(!document.fullscreenElement && !document.mozFullScreenElement && !document.webkitFullscreenElement && !document.msFullscreenElement);
}
fullscreenEnabled() {
return (document.fullscreenEnabled || document.webkitFullscreenEnabled || document.mozFullScreenEnabled || document.msFullscreenEnabled);
}
enterFullscreen() {
debug('Enter fullscreen');
if (this.node.requestFullscreen) {
return this.node.requestFullscreen();
} else if (this.node.msRequestFullscreen) {
return this.node.msRequestFullscreen();
} else if (this.node.mozRequestFullScreen) {
return this.node.mozRequestFullScreen();
} else if (this.node.webkitRequestFullscreen) {
return this.node.webkitRequestFullscreen();
}
return false;
}
exitFullscreen() {
debug('Exit fullscreen');
if (document.exitFullscreen) {
return document.exitFullscreen();
} else if (document.msExitFullscreen) {
return document.msExitFullscreen();
} else if (document.mozCancelFullScreen) {
return document.mozCancelFullScreen();
} else if (document.webkitExitFullscreen) {
return document.webkitExitFullscreen();
}
return false;
}
toggleFullscreen(onEnter = null, onExit = null) {
if (!this.fullscreenEnabled()) {
debug('Fullscreen not enabled');
}
let events = ['webkitfullscreenchange', 'mozfullscreenchange', 'fullscreenchange', 'MSFullscreenChange'];
let fsChange = function() {
debug('fsChange', this.isFullscreen());
if (this.isFullscreen()) {
if (typeof onEnter === 'function') {
onEnter();
}
} else {
if (typeof onExit === 'function') {
onExit();
}
for (let event of events) {
debug('removeEventListener', event);
document.removeEventListener(event, fsChange);
}
}
};
fsChange = fsChange.bind(this);
for (let event of events) {
debug('addEventListener', event);
document.addEventListener(event, fsChange);
}
if (this.isFullscreen()) {
this.exitFullscreen();
} else {
this.enterFullscreen();
}
}
}
export default DOMManipulator;
<file_sep>import React from 'react';
import Icon from './Icon';
export default class Separator extends React.Component {
static propTypes = {
icon: React.PropTypes.string,
children: React.PropTypes.oneOfType([
React.PropTypes.array,
React.PropTypes.object
]),
type: React.PropTypes.string,
className: React.PropTypes.string
};
static defaultProps = {
icon: null,
type: 'pattern',
className: null
};
render() {
let icon = null;
if (this.props.icon) {
icon = (<Icon type={this.props.icon} />);
}
let classes = ['separator', 'widget', this.props.type];
if (this.props.className) {
classes.push(this.props.className);
}
return (
<div className={classes.join(' ')}>
{icon}
{this.props.children}
</div>
);
}
}
<file_sep>import React from 'react';
import HomeStore from '../../stores/HomeStore';
import HomeContainer from './HomeContainer';
import HomeContact from './HomeContact';
import Loading from '../../../common/components/Widgets/Loading';
import ErrorPage from '../../../common/components/Layout/ErrorPage';
export default class HomeContactContainer extends HomeContainer {
static propTypes = {
params: React.PropTypes.object
}
constructor(props) {
super(props);
this.homeStoreListener = this.homeStoreOnChange.bind(this);
}
state = {
error: null,
home: HomeStore.getState().home
}
componentDidMount() {
HomeStore.listen(this.homeStoreListener);
HomeStore.fetchHomeBySlug(this.props.params.slug, true);
}
componentWillUnmount() {
HomeStore.unlisten(this.homeStoreListener);
}
homeStoreOnChange(state) {
this.setState(state);
}
handlePendingState() {
return (
<Loading>
<p>Loading story data</p>
</Loading>
);
}
handleErrorState() {
let error = {
title: 'Error loading story!',
message: this.state.error.message
};
return (
<ErrorPage {...error} />
);
}
render() {
if (this.state.error) {
return this.handleErrorState();
}
if (HomeStore.isLoading() || !this.state.home) {
return this.handlePendingState();
}
return (
<HomeContact home={this.state.home} />
);
}
}
<file_sep>export default require('../../common/actions/BaseListActions')
.generate('CityListActions', {
updateItem(model) {
this.dispatch(model);
}
});
<file_sep>import React from 'react';
export default class RouteNotFound extends React.Component {
render() {
return (
<div className='errorPage'>
<h1>Route does not exist.</h1>
<p>The requested route was not found</p>
</div>
);
}
}
<file_sep>import async from 'async';
import moment from 'moment';
import {NotFound} from '../../Errors';
import {merge, enumerate} from '../../Helpers';
import CommonQueryBuilder from '../CommonQueryBuilder';
/**
* Base QueryBuilder for Mongoose
*/
export default class BaseQueryBuilder extends CommonQueryBuilder {
/**
* Initializes new QB for given Model
* @param {object} app Application instance
* @param {string} modelName Name of the Model to use
*/
constructor(app, modelName) {
super(app, modelName);
this.Schema = this._app.db.getSchema(modelName);
this._extraDatas = null;
this._populateOptions = {};
this.initialize();
}
/**
* Overridable initialization method
*/
initialize() {}
hasSchemaField(name) {
return !!this.Schema.pathType(name);
}
select(fields) {
this._opts.fields = fields;
return this;
}
populate(options) {
this._populateOptions = options;
return this;
}
count() {
this._opts = {count: true};
return this._executeTasks();
}
distinct(field) {
this._queries.push((callback) => {
let findQuery = {
deletedAt: null
};
if (this._opts.query) {
findQuery = merge(findQuery, this._opts.query);
}
let cursor = this.Model.distinct(field, findQuery);
this._configurePopulationForCursor(cursor);
cursor.exec((err, models) => {
if (err) {
return callback(err);
}
this.result.models = models;
this.result.modelsJson = JSON.stringify(models.map((id) => {
return String(id);
}));
callback();
});
});
return this;
}
query(query) {
if (!this._opts.query) {
this._opts.query = {};
}
this._opts.query = merge({}, this._opts.query, query);
return this;
}
setExtraData(data) {
if (!this._extraDatas) {
this._extraDatas = {};
}
this._extraDatas = merge({}, this._extraDatas, data);
return this;
}
create(data) {
this._loadedModel = new this.Model();
return this.update(data);
}
createNoMultiset(data) {
this._loadedModel = new this.Model(data);
this._queries.push((callback) => {
this._loadedModel.save((err, model) => {
this._loadedModel = model;
callback(err);
});
});
this._queries.push((callback) => {
this.afterSave(data, callback);
});
return this._save();
}
update(data) {
this._queries.push((callback) => {
this._loadedModel.multiSet(data, this.Model.editableFields());
if (this._extraDatas) {
for (let [key, value] of enumerate(this._extraDatas)) {
this._loadedModel.set(key, value);
}
}
this._loadedModel.save((err, model) => {
this._loadedModel = model;
callback(err);
});
});
this._queries.push((callback) => {
this.afterSave(data, callback);
});
return this._save();
}
updateNoMultiset(data) {
this._queries.push((callback) => {
for (let [key, value] of enumerate(data)) {
this._loadedModel.set(key, value);
}
if (this._extraDatas) {
for (let [key, value] of enumerate(this._extraDatas)) {
this._loadedModel.set(key, value);
}
}
this._loadedModel.save((err, model) => {
this._loadedModel = model;
callback(err);
});
});
this._queries.push((callback) => {
this.afterSave(data, callback);
});
return this._save();
}
remove() {
this._queries.push(this.beforeRemove.bind(this));
this._queries.push((callback) => {
this._loadedModel.deletedAt = moment().utc().toDate();
this._loadedModel.save((err, model) => {
this._loadedModel = model;
this.result.model = model;
callback(err);
});
});
return this._executeTasks();
}
removeAll() {
this.result.deletedCount = 0;
this._queries.push(this.beforeRemove.bind(this));
this._queries.push((callback) => {
let subQueries = [];
if (this.result.models && this.result.models.length) {
this.result.models.forEach((model) => {
subQueries.push((scb) => {
model.deletedAt = moment().utc().toDate();
model.save((err) => {
if (err) {
return scb(err);
}
this.result.deletedCount += 1;
scb();
});
});
});
}
async.series(subQueries, callback);
});
return this._executeTasks();
}
findAll() {
this._queries.push((callback) => {
let findQuery = {
deletedAt: null
};
if (this._opts.query) {
findQuery = merge(findQuery, this._opts.query);
}
let cursor = this.Model.find(findQuery);
if (this._opts.count) {
cursor = this.Model.count(findQuery);
}
if (this._opts.limit) {
cursor.limit(this._opts.limit);
}
if (this._opts.sort) {
cursor.sort(this._opts.sort);
}
if (this._opts.skip) {
cursor.skip(this._opts.skip);
}
if (this._opts.fields) {
cursor.select(this._opts.fields);
}
this._configurePopulationForCursor(cursor);
cursor.exec((err, models) => {
if (err) {
return callback(err);
}
if (this._opts.count) {
this.result.count = models;
return callback();
}
this.result.models = models;
this.result.modelsJson = models.map(model => {
return model.toJSON();
});
callback();
});
});
return this;
}
findOne() {
this._queries.push((callback) => {
let findQuery = {
deletedAt: null
};
if (this._opts.query) {
findQuery = merge(findQuery, this._opts.query);
}
let cursor = this.Model.findOne(findQuery);
if (this._opts.fields) {
cursor.select(this._opts.fields);
}
this._configurePopulationForCursor(cursor);
cursor.exec((err, model) => {
if (err) {
return callback(err);
}
if (!model) {
return callback(new NotFound('model not found'));
}
this.result.model = model;
this.result.modelJson = model.toJSON();
this._loadedModel = model;
callback();
});
});
return this;
}
findById(id) {
this._queries.push((callback) => {
let cursor = this.Model.findById(id);
this._configurePopulationForCursor(cursor);
cursor.exec((err, model) => {
if (err) {
return callback(err);
}
if (!model) {
return callback(new NotFound('model not found'));
}
this.result.model = model;
this.result.modelJson = model.toJSON();
this._loadedModel = model;
callback();
});
});
return this;
}
findByUuid(uuid) {
this._queries.push((callback) => {
let findQuery = {
uuid: uuid,
deletedAt: null
};
if (this._opts.query) {
findQuery = merge(findQuery, this._opts.query);
}
let cursor = this.Model.findOne(findQuery);
this._configurePopulationForCursor(cursor);
cursor.exec((err, model) => {
if (err) {
return callback(err);
}
if (!model) {
return callback(new NotFound('model not found'));
}
this.result.model = model;
this.result.modelJson = model.toJSON();
this._loadedModel = model;
callback();
});
});
return this;
}
_save() {
return new Promise((resolve, reject) => {
async.series(this._queries, (err) => {
this._queries = [];
if (err) {
return reject(err);
} else {
if (!Object.keys(this._populateOptions).length) {
return resolve(this._loadedModel);
}
this.findById(this._loadedModel._id)
.fetch()
.then((result) => {
resolve(result.model);
});
}
});
});
}
_configurePopulationForCursor(cursor) {
for (let [field, options] of enumerate(this._populateOptions)) {
if (options) {
if (typeof options === 'string') {
cursor.populate(field, options);
} else {
options.path = field;
cursor.populate(options);
}
} else {
cursor.populate(field, options);
}
}
}
}
<file_sep>/*global window */
import React from 'react';
// import { Link } from 'react-router';
import Panel from 'react-bootstrap/lib/Panel';
import Row from 'react-bootstrap/lib/Row';
import Col from 'react-bootstrap/lib/Col';
import Nav from 'react-bootstrap/lib/Nav';
import TabbedArea from 'react-bootstrap/lib/TabbedArea';
import TabPane from 'react-bootstrap/lib/TabPane';
import Well from 'react-bootstrap/lib/Well';
import Button from 'react-bootstrap/lib/Button';
import SubNavigationWrapper from '../Navigation/SubNavigationWrapper';
import NavItemLink from 'react-router-bootstrap/lib/NavItemLink';
import PageListStore from '../../stores/PageListStore';
import { setPageTitle, createNotification } from '../../../common/Helpers';
let debug = require('debug')('PagesEdit');
export default class PagesEdit extends React.Component {
static propTypes = {
params: React.PropTypes.object.isRequired,
context: React.PropTypes.object
}
static contextTypes = {
router: React.PropTypes.func
}
constructor(props) {
super(props);
this.storeListener = this.onStateChange.bind(this);
this.redirect = false;
}
state = {
page: PageListStore.getItem(this.props.params.id),
error: null
}
componentDidMount() {
setPageTitle(['Create', 'Pages']);
PageListStore.listen(this.storeListener);
if (!PageListStore.getItem(this.props.params.id)) {
PageListStore.fetchItems();
}
}
componentWillUnmount() {
PageListStore.unlisten(this.storeListener);
}
onStateChange(state) {
debug('onStateListChange', state);
this.setState({
error: state.error,
page: PageListStore.getItem(this.props.params.id) || null
});
if (!state.error && this.redirect) {
setTimeout(() => {
this.context.router.transitionTo('pages');
}, 100);
}
}
handleErrorState() {
if (!this.state.error) {
return null;
}
createNotification({
label: 'Error',
message: this.state.error.message,
type: 'danger'
});
}
onDelete() {
PageListStore.removeItem(this.state.page.id);
this.redirect = true;
}
handlePendingState() {
return (
<p>Loading...</p>
);
}
handleSavingState() {
createNotification({
message: 'Saving page'
});
}
render() {
if (this.state.error) {
return this.handleErrorState();
}
if (PageListStore.isLoading() || !this.state.page) {
return this.handlePendingState();
}
let title = (this.state.page) ? this.state.page.title : '';
debug('this.state', this.state);
return (
<SubNavigationWrapper>
<Nav sidebar>
<h2 className='navigation-title'>Delete {title}</h2>
<NavItemLink to='pages'>
< Back
</NavItemLink>
</Nav>
<Row>
<h1><i className='fa fa-page'></i> Delete {title}</h1>
<TabbedArea defaultActiveKey={1}>
<TabPane eventKey={1} tab='Details'>
<Row>
<form method='delete'>
<Col md={10} sm={10}>
<Panel header='Please confirm'>
<p>Please confirm the deletion of the page</p>
</Panel>
<Well>
<Row>
<Col md={6}>
<Button bsStyle='danger' accessKey='s' onClick={this.onDelete.bind(this)}>Delete</Button>
</Col>
</Row>
</Well>
</Col>
</form>
</Row>
</TabPane>
</TabbedArea>
</Row>
</SubNavigationWrapper>
);
}
}
<file_sep>import winston from 'winston';
import expressWinston from 'express-winston';
import {getEnvironmentValue} from '../../Helpers';
import path from 'path';
exports.configure = function(app/*, config = {}*/) {
app.googleCallbacks = app.googleCallbacks || {
onStop: null,
onStart: null
};
let fileLogPath = getEnvironmentValue('LOG_PATH', null);
if (fileLogPath) {
app.use(expressWinston.logger({
transports: [
new winston.transports.Console({
json: false
}),
new winston.transports.File({
filename: path.join(fileLogPath, 'request.log')
})
],
expressFormat: true
}));
}
// Respond to Google Health Checks
app.get('/_ah/health', function(req, res) {
res.status(200)
.set('Content-Type', 'text/plain')
.send('ok');
});
// app.get('/_ah/start', function(req, res) {
// if (app.googleCallbacks.onStart) {
// app.googleCallbacks.onStart(req);
// }
// res.status(200)
// .set('Content-Type', 'text/plain')
// .send('ok');
// });
//
// app.get('/_ah/stop', function(req, res) {
// app.log.info('Stopping as per instruction from google')
// if (app.googleCallbacks.onStop) {
// app.googleCallbacks.onStop(req);
// }
// res.status(200)
// .set('Content-Type', 'text/plain')
// .send('ok');
// });
return Promise.resolve();
};
<file_sep>import React from 'react';
import { Link } from 'react-router';
import Image from '../../../common/components/Widgets/Image';
import SocialMedia from '../Navigation/SocialMedia';
export default class Footer extends React.Component {
render() {
return (
<div id='footer' className='clearfix' ref='footer'>
<div className='width-wrapper'>
homehapp Limited. All rights reserved 2015. Contact, collaboration and inquiries: <a href='mailto:<EMAIL>'><EMAIL></a>
</div>
</div>
);
}
}
<file_sep>import {toTitleCase} from '../Helpers';
class QueryBuilder {
constructor(app) {
this.app = app;
}
forModel(modelName) {
let className = `${toTitleCase(modelName)}QueryBuilder`;
let Klass = null;
try {
Klass = require(`./${this.app.config.database.adapter}/${className}`);
} catch (err) {
console.log(err);
throw new Error(`No Query builder found for model ${modelName}!`);
}
return new Klass(this.app);
}
query(modelName) {
console.warn(`QueryBuilder.query(${modelName}) has been depracated. Use .forModel(${modelName})`);
return this.forModel(modelName);
}
}
module.exports = QueryBuilder;
<file_sep>#! /bin/sh
# Do not change these
REV=`git rev-parse --short HEAD`
CWD=`pwd`
CONTAINER_REGISTRY_HOST=eu.gcr.io
PNAME=$1
ENV=$2
CLUSTER_NAME="homehapp-$ENV"
CLUSTER_GOOGLE_NAME=""
NODE_GOOGLE_NAME=""
function printUsage() {
echo "Required environment variables:"
echo " PROJECT_ID: Google Project ID"
echo ""
echo "Usage PROJECT_ID=id ./support/destroyCluster.sh [project_name] [stg,prod]"
echo "Add -d for dry-run"
}
function printUsageAndExit() {
printUsage
exit
}
if [ "$PROJECT_ID" = "" ]; then
echo "No Google Project ID defined!"
printUsageAndExit
fi
if [ "$PNAME" = "" ]; then
echo "No project defined!"
printUsageAndExit
fi
if [ ! -d "$CWD/tmp" ]; then
mkdir "$CWD/tmp"
fi
if [ "$3" = "-d" ]; then
echo "In Dry-Run mode"
fi
function removeService() {
if [ "$CLUSTER_GOOGLE_NAME" = "" ]; then
echo "Execute: kubectl config view | awk '{print $2}' | grep $CLUSTER_NAME | tail -n 1"
CLUSTER_GOOGLE_NAME=`kubectl config view | awk '{print $2}' | grep $CLUSTER_NAME | tail -n 1`
fi
if [ "$1" = "-d" ]; then
echo "Execute: 'kubectl delete services --context=$CLUSTER_GOOGLE_NAME $PNAME'"
else
kubectl delete services --context=$CLUSTER_GOOGLE_NAME $PNAME
fi
}
function removeController() {
local CONTROLLER_NAME=`kubectl get rc | grep $PROJECT_ID | awk '{print $1}' | grep "$PNAME-$ENV-controller"`
if [ "$1" = "-d" ]; then
echo "Execute: kubectl get rc | grep $PROJECT_ID | awk '{print $1}' | grep '$PNAME-$ENV-controller'"
echo "Execute: 'kubectl stop rc $CONTROLLER_NAME'"
else
kubectl stop rc $CONTROLLER_NAME
fi
}
function removeCluster() {
if [ "$1" = "-d" ]; then
echo "Execute: 'gcloud beta container clusters delete $CLUSTER_NAME --project $PROJECT_ID'"
else
gcloud beta container clusters delete --quiet $CLUSTER_NAME --project $PROJECT_ID
fi
}
# function closeFirewall() {
# if [ "$1" = "-d" ]; then
# echo "Execute: 'gcloud compute firewall-rules delete $PNAME-80 --project $PROJECT_ID'"
# else
# gcloud compute firewall-rules delete $PNAME-80 --project $PROJECT_ID
# fi
# }
echo ""
echo "Removing Service $PNAME-service"
removeService $3
echo ""
echo "Removing Replication Controller $PNAME-controller"
removeController $3
echo "Removing Container Cluster $CLUSTER_NAME"
echo ""
removeCluster $3
# echo ""
# echo "Removing firewall rule for service"
#
# closeFirewall $3
echo ""
echo "Cluster removed!"
echo ""
<file_sep>exports.registerRoutes = (app) => {
/**
* @api {any} /api/* All story blocks
* @apiVersion 1.0.1
* @apiName All StoryBlocks
* @apiGroup StoryBlocks
* @apiUse StoryBlockSuccess
* @apiUse StoryBlockSuccessJSON
*
* @apiDescription Story block definitions for both setting and getting
*/
/**
* @apiDefine StoryBlockSuccess
* @apiVersion 1.0.1
*
* @apiSuccess {boolean} enabled Switch to enable story block
* @apiSuccess {Array} blocks Story blocks as defined here
*/
/**
* @apiDefine StoryBlockSuccessJSON
* @apiVersion 1.0.1
*
* @apiSuccessExample {json} Story block segment
* {
* "enabled": true,
* "blocks": [
* {
* "template": '...',
* "properties": {...}
* },
* ...,
* {
* "template": '...',
* "properties": {...}
* }
* ]
* }
*/
/**
* @api {any} /api/* BigImage
* @apiVersion 1.0.1
* @apiDescription BigImage widget is for displaying a fullscreen image with optional text on top of it
* @apiName BigImage
* @apiGroup StoryBlocks
*
* @apiParam {string='BigImage'} template Template name for big image widget
* @apiParam {object} properties Story block properties
* @apiParam {string} properties.title Story block title
* @apiParam {string} properties.description Story block description
* @apiParam {string='left', 'center', 'right'} [properties.align='center'] Horizontal position of the textual content
* @apiParam {string='top', 'middle', 'bottom'} [properties.valign='middle'] Vertical position of the textual content
* @apiParam {object} properties.image <a href="#api-Shared-Images">Image object</a>
*
* @apiSuccess {String} template Template name, always BigImage
* @apiSuccess {Object} properties Content control properties
* @apiSuccess {Object} properties.image <a href="#api-Shared-Images">Image</a> object
* @apiSuccess {String} properties.align Horizontal alignment of the text ('left', 'center', 'right')
* @apiSuccess {String} properties.valign Vertical alignment of the text ('top', 'middle', 'bottom')
* @apiSuccess {String} properties.title Block title
* @apiSuccess {String} properties.description Block content or description
*
* @apiSuccessExample {json} Example
* {
* "template": 'BigImage',
* "properties": {
* "image": {...},
* "title": "...",
* "description": "...",
* "align": "center",
* "valign": "middle",
* }
* }
* @apiUse ImageSuccessJSON
*/
/**
* @api {any} /api/* BigVideo
* @apiVersion 1.0.1
* @apiDescription BigVideo widget is for displaying a fullscreen video with optional text on top of it
* @apiName BigVideo
* @apiGroup StoryBlocks
*
* @apiParam {string='BigVideo'} template Template name for big video widget
* @apiParam {object} properties Story block properties
* @apiParam {string} properties.title Story block title
* @apiParam {string} properties.description Story block description
* @apiParam {string='left', 'center', 'right'} [properties.align='center'] Horizontal position of the textual content
* @apiParam {string='top', 'middle', 'bottom'} [properties.valign='middle'] Vertical position of the textual content
* @apiParam {object} properties.video <a href="#api-Shared-Videos">Video object</a>
*
* @apiSuccess {String} template Template name, always BigVideo
* @apiSuccess {Object} properties Content control properties
* @apiSuccess {Object} properties.video <a href="#api-Shared-Videos">Video</a> object
* @apiSuccess {String} properties.align Horizontal alignment of the text ('left', 'center', 'right')
* @apiSuccess {String} properties.valign Vertical alignment of the text ('top', 'middle', 'bottom')
* @apiSuccess {String} properties.title Block title
* @apiSuccess {String} properties.description Block content or description
*
* @apiSuccessExample {json} Example
* {
* "template": 'BigVideo',
* "properties": {
* "video": {...},
* "title": "...",
* "description": "...",
* "align": "center",
* "valign": "middle",
* }
* }
* @apiUse VideoSuccessJSON
*/
/**
* @api {any} /api/* ContentBlock
* @apiVersion 1.0.1
* @apiDescription ContentBlock is a basic text block in the content flow
* @apiName ContentBlock
* @apiGroup StoryBlocks
*
* @apiParam {string='ContentBlock'} template Template name for ContentBlock widget
* @apiParam {object} properties Story block properties
* @apiParam {string} properties.title Story block title
* @apiParam {string} properties.content Story block content
* @apiParam {string='left', 'center', 'right'} [properties.align='left'] Horizontal position of the content
*
* @apiSuccess {String} template Template name, always ContentBlock
* @apiSuccess {Object} properties Content control properties
* @apiSuccess {String} properties.title Block title
* @apiSuccess {String} properties.description Block content or description
*
* @apiSuccessExample {json} Example
* {
* "template": 'BigVideo',
* "properties": {
* "video": {...},
* "title": "...",
* "description": "...",
* "align": "center",
* "valign": "middle",
* }
* }
* @apiUse VideoSuccessJSON
*/
/**
* @api {any} /api/* ContentImage
* @apiVersion 1.0.1
* @apiDescription ContentImage displays an image in conjunction with text with a control parameter defining which comes first
* @apiName ContentBlock
* @apiGroup StoryBlocks
*
* @apiSuccess {String} template Template name, always ContentImage
* @apiParam {object} properties Story block properties
* @apiParam {string} properties.title Story block title
* @apiParam {string} properties.content Story block content
* @apiParam {object} properties.image <a href="#api-Shared-Images">Image object</a>
* @apiParam {string='left', 'right'} [properties.imageAlign='left'] Horizontal position of the content
*
* @apiSuccess {String} template Template name, always ContentImage
* @apiSuccess {Object} properties Content control properties
* @apiSuccess {Object} properties.image <a href="#api-Shared-Images">Image</a> object
* @apiSuccess {String} properties.title Block title
* @apiSuccess {String} properties.description Block content or description
* @apiSuccess {String} properties.imageAlign Position of the image related to the text: "left" or "right"
*
* @apiSuccessExample {json} Example
* {
* "template": 'BigVideo',
* "properties": {
* "video": {...},
* "title": "...",
* "description": "...",
* "align": "center",
* "valign": "middle",
* }
* }
* @apiUse VideoSuccessJSON
*/
/**
* @api {any} /api/* Gallery
* @apiVersion 1.0.1
* @apiDescription Gallery widget
* @apiName Gallery
* @apiGroup StoryBlocks
*
* @apiParam {string='Gallery'} template Template name for Gallery widget
* @apiParam {object} properties Story block properties
* @apiParam {Array} properties.images An array of <a href="#api-Shared-Images">Images</a>
*/
};
<file_sep>import React from 'react';
// import { Link } from 'react-router';
import Row from 'react-bootstrap/lib/Row';
import Col from 'react-bootstrap/lib/Col';
import Panel from 'react-bootstrap/lib/Panel';
// import Table from 'react-bootstrap/lib/Table';
import InputWidget from '../Widgets/Input';
import Button from 'react-bootstrap/lib/Button';
import Well from 'react-bootstrap/lib/Well';
import HomeStore from '../../stores/HomeStore';
import HomeActions from '../../actions/HomeActions';
import StoryEditBlocks from '../Shared/StoryEditBlocks';
import ApplicationStore from '../../../common/stores/ApplicationStore';
let debug = require('../../../common/debugger')('HomesEditStory');
export default class HomesEditStory extends React.Component {
static propTypes = {
home: React.PropTypes.object.isRequired
}
constructor(props) {
super(props);
this.storeListener = this.onHomeStoreChange.bind(this);
this.onSave = this.onSave.bind(this);
}
state = {
error: null
}
componentDidMount() {
HomeStore.listen(this.storeListener);
}
componentWillUnmount() {
HomeStore.unlisten(this.storeListener);
}
onHomeStoreChange(state) {
debug('onHomeStoreChange', state);
this.setState(state);
}
onChange(blocks) {
debug('onInput', blocks);
}
onSave() {
debug('onSave');
debug('blocks', this.refs.storyBlocks.getBlocks());
let homeProps = {
id: this.props.home.id,
story: {
blocks: this.refs.storyBlocks.getBlocks(),
enabled: this.props.home.story.enabled
}
};
this.saveHome(homeProps);
}
saveHome(homeProps) {
debug('Update homeProps', homeProps);
HomeActions.updateItem(homeProps);
}
toggleEnabled() {
// Invert the value and update the view
this.props.home.story.enabled = !(this.props.home.story.enabled);
this.forceUpdate();
}
render() {
let blocks = [];
if (this.props.home.story.blocks) {
blocks = this.props.home.story.blocks;
}
let enabledStatus = {};
if (this.props.home.story.enabled) {
enabledStatus = {checked: true};
}
debug('Home', this.props.home);
let previewLink = null;
if (this.props.home) {
previewLink = (
<a href={`${ApplicationStore.getState().config.siteHost}/homes/${this.props.home.slug}/story`}
target='_blank'
className='btn btn-primary'>
Preview
</a>
);
}
return (
<Row>
<form name='homeStory' ref='homeStoryForm' method='POST'>
<Col md={10} sm={10}>
<Panel header='Visibility settings'>
<InputWidget
type='checkbox'
ref='enabled'
label='Story visible'
{...enabledStatus}
addonBefore='Value'
onChange={this.toggleEnabled.bind(this)}
/>
</Panel>
<StoryEditBlocks parent={this.props.home} blocks={blocks} disabled={['HTMLContent']} ref='storyBlocks' onChange={this.onChange.bind(this)} />
<Well>
<Row>
<Col md={6}>
<Button bsStyle='success' accessKey='s' onClick={this.onSave.bind(this)}>Save</Button>
{previewLink}
</Col>
</Row>
</Well>
</Col>
</form>
</Row>
);
}
}
<file_sep>import React from 'react';
import { Link } from 'react-router';
import Table from 'react-bootstrap/lib/Table';
import Row from 'react-bootstrap/lib/Row';
import Nav from 'react-bootstrap/lib/Nav';
import SubNavigationWrapper from '../Navigation/SubNavigationWrapper';
import NeighborhoodListStore from '../../stores/NeighborhoodListStore';
import Loading from '../../../common/components/Widgets/Loading';
import { setPageTitle } from '../../../common/Helpers';
let debug = require('debug')('Neighborhoods');
export default class Neighborhoods extends React.Component {
constructor(props) {
super(props);
this.storeListener = this.onChange.bind(this);
}
state = {
error: null,
neighborhoods: null
}
componentDidMount() {
setPageTitle('Neighborhoods');
NeighborhoodListStore.listen(this.storeListener);
// This is a quick hack...
if (window && window.location.href.toString().match(/\/all/)) {
NeighborhoodListStore.fetchAllItems();
} else {
NeighborhoodListStore.fetchItems();
}
}
componentWillUnmount() {
NeighborhoodListStore.unlisten(this.storeListener);
}
onChange(state) {
debug('onChange', state);
this.setState({
error: state.error,
neighborhoods: state.items
});
}
handlePendingState() {
return (
<Loading>
<h3>Loading neighborhoods...</h3>
</Loading>
);
}
handleErrorState() {
return (
<div className='neighborhoods-error'>
<h3>Error loading neighborhoods!</h3>
<p>{this.state.error.message}</p>
</div>
);
}
render() {
if (this.state.error) {
return this.handleErrorState();
}
if (NeighborhoodListStore.isLoading() || !this.state.neighborhoods) {
return this.handlePendingState();
}
return (
<SubNavigationWrapper>
<Nav sidebar>
<h2 className='navigation-title'>
Neighborhoods
</h2>
</Nav>
<Row>
<h1>{this.state.neighborhoods.length} neighborhoods</h1>
<Table>
<thead>
<tr>
<th>Neighbourhood</th>
<th>City</th>
<th>Story blocks</th>
</tr>
</thead>
<tbody>
{this.state.neighborhoods.map((neighborhood, i) => {
let storyBlocks = neighborhood.story.blocks.length || null;
let city = null;
if (neighborhood.location && neighborhood.location.city && neighborhood.location.city.title) {
city = neighborhood.location.city.title;
}
return (
<tr key={i}>
<td>
<Link
to='neighborhoodEdit'
params={{id: neighborhood.id}}>
{neighborhood.title}
</Link>
</td>
<td>{city}</td>
<td>{storyBlocks}</td>
</tr>
);
})}
</tbody>
</Table>
</Row>
</SubNavigationWrapper>
);
}
}
<file_sep>import BaseQueryBuilder from './BaseQueryBuilder';
import {NotFound} from '../../Errors';
let debug = require('debug')('PageQueryBuilder');
export default class PageQueryBuilder extends BaseQueryBuilder {
constructor(app) {
super(app, 'Page');
}
findBySlug(slug) {
this._queries.push((callback) => {
let cursor = this.Model.findOne({
slug: slug,
deletedAt: null
});
this._configurePopulationForCursor(cursor);
cursor.exec((err, content) => {
if (err) {
debug('Got error', err);
return callback(err);
}
if (!content) {
debug('No content found');
return callback(new NotFound('Page not found'));
}
debug('findBySlug', content.title);
this._loadedModel = content;
this.result.model = content;
this.result.models = [content];
callback();
});
});
return this;
}
initialize() {
}
findByUuid(uuid) {
this._queries.push((callback) => {
let cursor = this.Model.findOne({
uuid: uuid,
deletedAt: null
});
this._configurePopulationForCursor(cursor);
cursor.exec((err, model) => {
if (err) {
return callback(err);
}
if (!model) {
return callback(new NotFound('Page page not found'));
}
this.result.model = model;
this.result.models = [model];
this._loadedModel = model;
callback();
});
});
return this;
}
}
<file_sep>import csrf from 'csurf';
import {Forbidden} from '../../Errors';
import {enumerate} from '../../Helpers';
exports.configure = function(app, config) {
return new Promise((resolve) => {
if (config.csrf) {
let csrfProtection = csrf({});
if (!app.authentication || !app.hasSessions) {
csrfProtection = csrf({
cookie: true
});
app.use(require('cookie-parser')());
}
if (config.csrfSkipRoutes && config.csrfSkipRoutes.length) {
app.use(function csrfSkipRoutes(req, res, next) {
let matched = false;
config.csrfSkipRoutes.forEach((skipPath) => {
if (req.path.match(skipPath)) {
matched = true;
}
});
if (matched) {
req.csrfToken = () => {
return '';
};
return next();
}
csrfProtection(req, res, next);
});
} else {
app.use(csrfProtection);
}
}
if (config.xframe && config.xframe.length) {
if (['DENY', 'SAMEORIGIN'].indexOf(config.xframe) === -1
&& !config.xframe.match(/ALLOW\-FROM /))
{
console.warn(`Configured X-Frame-Options value ${config.xframe} is not allowed. Skipping.`);
} else {
app.use(function xFrameProtection(req, res, next) {
res.header('X_FRAME_OPTIONS', config.xframe);
next();
});
}
}
if (config.requiredHeaders && Object.keys(config.requiredHeaders).length) {
app.use(function requiredHeaders(req, res, next) {
let reason = null;
// Skip favicon requests
if (req.path.substr(1).match(/^favicon/)) {
return next();
}
if (config.requiredHeaders.allowRoutes) {
let skipCheck = false;
let requestPath = req.path.substr(1);
config.requiredHeaders.allowRoutes.forEach((pathRegexp) => {
if (requestPath.match(pathRegexp)) {
skipCheck = true;
}
});
if (skipCheck) {
return next();
}
}
if (config.requiredHeaders.exists) {
config.requiredHeaders.exists.forEach((key) => {
if (!req.headers[key.toLowerCase()]) {
reason = `Missing required header: ${key}`;
}
});
}
if (config.requiredHeaders.valueMatch) {
for (let [key, value] of enumerate(config.requiredHeaders.valueMatch)) {
if (!req.headers[key.toLowerCase()]) {
reason = `Missing required header: ${key}`;
}
if (req.headers[key.toLowerCase()] !== value) {
reason = `Invalid value for header: ${key}`;
}
}
}
if (reason) {
app.log.info(`API client request denied. Reason: ${reason}`);
return next(new Forbidden('invalid request'));
} else {
app.log.info('API client request accepted');
}
next();
});
}
if (config.cors && config.cors.enabled) {
app.all('*', function(req, res, next) {
// CORS headers
res.header('Access-Control-Allow-Origin', config.cors.allowOrigin);
res.header(
'Access-Control-Allow-Methods',
'HEAD,GET,PUT,POST,DELETE,OPTIONS'
);
// Set custom headers for CORS
if (config.cors.allowHeaders && config.cors.allowHeaders.length) {
res.header(
'Access-Control-Allow-Headers',
config.cors.allowHeaders.join(',')
);
}
if (req.method === 'OPTIONS') {
return res.status(200).end();
}
next();
});
}
resolve();
});
};
<file_sep>import React from 'react';
import StoryBlocks from './StoryBlocks';
import StoryLayout from '../../../common/components/Layout/StoryLayout';
import HomeNavigation from './HomeNavigation';
import { setPageTitle } from '../../../common/Helpers';
// let debug = require('debug')('HomeDetails');
export default class HomeDetails extends StoryBlocks {
static propTypes = {
home: React.PropTypes.object.isRequired
}
componentDidMount() {
setPageTitle(this.props.home.homeTitle);
}
componentWillUnmount() {
setPageTitle();
}
getSecondaryTitle() {
let content = [];
// let content = this.props.home.attributes.map(function(c) {
// // Add the items that should be included in the secondary title
// let rval = null;
// switch (c.name) {
// case 'rooms':
// rval = (c.value === 1) ? (<span>1 room</span>) : (<span>{c.value} rooms</span>);
// break;
// }
// return rval;
// });
content.push((<span>{this.props.home.formattedPrice}</span>));
return content;
}
getTitleBlock() {
let image = null;
if (this.props.home.images && this.props.home.images.length) {
image = this.props.home.images[0];
} else {
image = {
url: 'images/content/content-placeholder.jpg',
alt: '',
type: 'asset'
};
}
return {
template: 'BigImage',
properties: {
image: image,
title: this.props.home.homeTitle,
align: 'center',
valign: 'middle',
isPageTitle: true,
secondary: this.addViewControls(this.props.home)
}
};
}
getAttachments() {
if (!this.props.home.brochures || !this.props.home.brochures.length) {
return [];
}
let attachments = this.props.home.brochures.map((attachment) => {
let type = attachment.tag || 'brochure';
let label = type;
if (attachment.alt) {
label = attachment.alt;
} else {
switch (type) {
case 'brochure':
label = 'Brochure';
break;
case 'epc':
label = 'EPC';
break;
case 'floorplan':
label = 'Floor plan';
break;
}
}
return {
url: attachment.url,
type: type,
label: label
};
});
let types = [
'floorplan',
'epc',
'brochure'
];
// Sort the attachments by type
attachments.sort((a, b) => {
let indexA = types.indexOf(a.type);
let indexB = types.indexOf(b.type);
if (indexA === -1) {
return 1;
}
if (indexB === -1) {
return -1;
}
if (indexA > indexB) {
return 1;
}
if (indexA < indexB) {
return -1;
}
return 0;
});
return attachments;
}
render() {
let blocks = [];
blocks.push(this.getTitleBlock());
blocks.push({
template: 'ContentBlock',
properties: {
content: this.props.home.description,
quote: true
}
});
if (this.props.home.images.length > 1) {
blocks.push({
template: 'Gallery',
properties: {
images: this.props.home.images,
imageWidth: 300,
className: 'pattern details-view'
}
});
}
let attachments = this.getAttachments();
if (attachments.length) {
blocks.push({
template: 'Attachments',
properties: {
attachments: attachments
}
});
}
blocks.push({
template: 'Details',
properties: {
home: this.props.home
}
});
blocks = this.appendBlocks(blocks, this.props.home);
return (
<div className='home-view'>
<HomeNavigation home={this.props.home} />
<StoryLayout blocks={blocks} />
</div>
);
}
}
<file_sep>#!/bin/sh
if [ "$1" != 'site' ] && [ "$1" != 'admin' ] && [ "$1" != 'api' ] ; then
echo "Usage: ./deploy.sh (site|api|admin) (stg|prod)";
exit 0;
fi
if [ "$2" != 'stg' ] && [ "$2" != 'prod' ] ; then
echo "Usage: ./deploy.sh $1 (stg|prod)";
exit 0;
fi
echo "# Run npm run test-$1";
if npm run "test-$1"; then
echo "# Tests passed";
else
echo "# Tests failed, refuse to deploy";
#exit 1;
fi
if [ "$3" == 'dry' ] ; then
echo "# Would run:";
echo "export PROJECT_ID=homehappweb";
export PROJECT_ID=homehappweb;
echo "export TARGET=$1";
export TARGET=$1;
echo "export CLUSTER_ENV=$2";
export CLUSTER_ENV=$2;
echo "gcloud config set project \$PROJECT_ID";
echo "./support/createContainers.sh \$CLUSTER_ENV \$TARGET";
if [ "$1" != "api" ]; then
echo "npm run \"build-\$TARGET\"";
echo "npm run \"distribute-\$TARGET\"";
fi
echo "./support/updateCluster.sh \$CLUSTER_ENV \$TARGET";
exit 1;
fi
export PROJECT_ID=homehappweb
export TARGET=$1
export CLUSTER_ENV=$2
gcloud config set project $PROJECT_ID
echo "EXEC: ./support/createContainers.sh $CLUSTER_ENV $TARGET";
./support/createContainers.sh $CLUSTER_ENV $TARGET
if [ "$1" != "api" ]; then
echo "------";
echo "EXEC: npm run build-$TARGET";
npm run "build-$TARGET"
echo "------";
echo "EXEC: npm run distribute-$TARGET";
npm run "distribute-$TARGET"
fi
echo "------";
echo "EXEC: ./support/updateCluster.sh $CLUSTER_ENV $TARGET";
./support/updateCluster.sh $CLUSTER_ENV $TARGET
<file_sep>import React from 'react';
import { Link } from 'react-router';
import BigImage from './BigImage';
import LargeText from './LargeText';
export default class Neighborhood extends React.Component {
static propTypes = {
title: React.PropTypes.string.isRequired,
slug: React.PropTypes.string.isRequired,
images: React.PropTypes.array.isRequired,
coordinates: React.PropTypes.array,
className: React.PropTypes.string
}
static defaultProps = {
className: null
}
render() {
let image = {
url: 'v1439564093/london-view.jpg',
alt: ''
};
if (Array.isArray(this.props.images) && this.props.images.length) {
image = this.props.images[0];
}
let classes = ['neighborhood'];
return (
<BigImage image={image} className={classes.join(' ')}>
<LargeText align='center' valign='middle' className='full-height'>
<p className='teaser'>...and about the neighbourhood</p>
<h1>
<Link to='neighborhoodView' params={{city: 'london', neighborhood: this.props.slug}}>
{this.props.title}
</Link>
</h1>
</LargeText>
</BigImage>
);
}
}
<file_sep>import SourceBuilder from '../../common/sources/Builder';
import PageActions from '../actions/PageActions';
export default SourceBuilder.build({
name: 'PageSource',
actions: {
base: PageActions,
error: PageActions.requestFailed
},
methods: {
createItem: {
remote: {
method: 'post',
uri: '/api/pages',
params: (state, args) => {
return {
page: args[0]
};
},
response: {
key: 'page'
}
},
local: null,
actions: {
success: PageActions.updateSuccess
}
},
updateItem: {
remote: {
method: 'put',
uri: (state, args) => {
let id = args[0].uuid || args[0].id;
return `/api/pages/${id}`;
},
params: (state, args) => {
return {
page: args[0]
};
},
response: {
key: 'page'
}
},
local: null,
actions: {
success: PageActions.updateSuccess
}
}
}
});
<file_sep>import React from 'react';
import NeighborhoodContainer from './NeighborhoodContainer';
import NeighborhoodStore from '../../stores/NeighborhoodStore';
import NeighborhoodStory from './NeighborhoodStory';
// let debug = require('../../../common/debugger')('NeighborhoodStoryContainer');
export default class NeighborhoodStoryContainer extends NeighborhoodContainer {
render() {
if (this.state.error) {
return this.handleErrorState();
}
if (NeighborhoodStore.isLoading() || !this.state.neighborhood) {
return this.handlePendingState();
}
return (
<NeighborhoodStory neighborhood={this.state.neighborhood} />
);
}
}
<file_sep>import QueryBuilder from '../../../lib/QueryBuilder';
// let debug = require('debug')('/api/pages');
exports.registerRoutes = (app) => {
const QB = new QueryBuilder(app);
app.get('/api/pages/:slug', function(req, res, next) {
QB
.forModel('Page')
.findBySlug(req.params.slug)
.fetch()
.then((result) => {
res.json({
status: 'ok',
page: result.model
});
})
.catch(next);
});
};
<file_sep>/*global window */
import React from 'react';
// import { Link } from 'react-router';
import Row from 'react-bootstrap/lib/Row';
import Nav from 'react-bootstrap/lib/Nav';
import TabbedArea from 'react-bootstrap/lib/TabbedArea';
import TabPane from 'react-bootstrap/lib/TabPane';
import SubNavigationWrapper from '../Navigation/SubNavigationWrapper';
import NavItemLink from 'react-router-bootstrap/lib/NavItemLink';
import EditDetails from './EditDetails';
import EditArea from './EditArea';
import EditStory from './EditStory';
import EditModel from '../Shared/EditModel';
import ViewMetadata from '../Shared/ViewMetadata';
import NeighborhoodStore from '../../stores/NeighborhoodStore';
import NeighborhoodActions from '../../actions/NeighborhoodActions';
import { setPageTitle } from '../../../common/Helpers';
let debug = require('debug')('NeighborhoodsEdit');
export default class NeighborhoodsEdit extends EditModel {
static propTypes = {
neighborhood: React.PropTypes.object.isRequired,
tab: React.PropTypes.oneOfType([
React.PropTypes.number,
React.PropTypes.string
])
}
constructor(props) {
super(props);
}
componentDidMount() {
setPageTitle([`Edit ${this.props.neighborhood.title}`, 'Neighborhoods']);
}
refreshTab(tab) {
debug('refreshTab', arguments);
this.setState({tab: tab});
if (tab === 4 && this.refs.areaSelector && typeof this.refs.areaSelector.updateMap === 'function') {
this.refs.areaSelector.updateMap();
}
}
render() {
let openTab = this.resolveOpenTab();
debug('openTab', openTab);
return (
<SubNavigationWrapper>
<Nav sidebar>
<h2 className='navigation-title'>Edit Neighborhood</h2>
<NavItemLink to='neighborhoods'>
< Back
</NavItemLink>
</Nav>
<Row>
<h1>Edit {this.props.neighborhood.title}</h1>
<TabbedArea defaultActiveKey={openTab} onSelect={this.refreshTab.bind(this)} activeKey={openTab}>
<TabPane eventKey={1} tab='Details'>
<EditDetails neighborhood={this.props.neighborhood} />
</TabPane>
<TabPane eventKey={2} tab='Story'>
<EditStory neighborhood={this.props.neighborhood} />
</TabPane>
<TabPane eventKey={4} tab='Area'>
<EditArea neighborhood={this.props.neighborhood} ref='areaSelector' />
</TabPane>
<TabPane eventKey={3} tab='Metadata'>
<ViewMetadata object={this.props.neighborhood} store={NeighborhoodStore} actions={NeighborhoodActions} />
</TabPane>
</TabbedArea>
</Row>
</SubNavigationWrapper>
);
}
}
<file_sep>import QueryBuilder from '../../lib/QueryBuilder';
import NeighborhoodsAPI from '../../api/NeighborhoodsAPI';
import { setLastMod, initMetadata } from '../../../clients/common/Helpers';
let debug = require('debug')('neighborhoods API');
exports.registerRoutes = (app) => {
const QB = new QueryBuilder(app);
let api = new NeighborhoodsAPI(app, QB);
app.get('/neighborhoods', function(req, res, next) {
QB
.forModel('City')
.findAll()
.fetch()
.then((result) => {
if (result.models.length === 1) {
debug('Found only one city', result.models[0]);
return res.redirect(301, `/neighborhoods/${result.models[0].slug}`);
}
res.locals.data.CityListStore = {
cities: result.models
};
})
.catch(() => {
res.status(404);
next();
});
});
app.get('/neighborhoods/:city', function(req, res, next) {
debug(`/neighborhoods/${req.params.city}`);
api.listNeighborhoodsByCity(req, res, next)
.then((neighborhoods) => {
let images = [];
let city = null;
for (let neighborhood of neighborhoods) {
let image = neighborhood.mainImage.url;
if (images.indexOf(image) === -1) {
images.push(image);
}
if (neighborhood.location && neighborhood.location.city) {
city = neighborhood.location.city;
}
}
initMetadata(res);
res.locals.openGraph['og:image'] = images.concat(res.locals.openGraph['og:image']);
res.locals.page = {
title: `Neighborhoods of ${city.title}`,
description: `Neighborhoods of ${city.title}`
};
setLastMod(neighborhoods, res);
res.locals.data.NeighborhoodListStore = {
neighborhoods: neighborhoods
};
next();
})
.catch(() => {
res.status(404);
next();
});
});
app.get('/neighborhoods/:city/:neighborhood', function(req, res, next) {
debug(`/neighborhoods/${req.params.city}/${req.params.neighborhood}`);
api.getNeighborhoodBySlug(req, res, next)
.then((neighborhood) => {
debug('Got neighborhood', neighborhood);
res.locals.data.title = neighborhood.pageTitle;
let description = neighborhood.description || `View the neighborhood of ${neighborhood.title}, ${neighborhood.location.city.title}`;
if (description.length > 200) {
description = description.substr(0, 200) + '…';
}
res.locals.page = {
title: neighborhood.pageTitle,
description: description
};
res.locals.data.NeighborhoodStore = {
neighborhood: neighborhood
};
next();
})
.catch(() => {
res.status(404);
next();
});
});
app.get('/neighborhoods/:city/:neighborhood/homes', function(req, res, next) {
api.getNeighborhoodBySlug(req, res, next)
.then((neighborhood) => {
debug('Got neighborhood', neighborhood);
res.locals.data.NeighborhoodStore = {
neighborhood: neighborhood
};
// Common metadata for all the single neighborhood views
let images = [];
if (neighborhood && neighborhood.images) {
for (let image of neighborhood.images) {
let src = image.url || image.src;
if (src) {
images.push(src.replace(/upload\//, 'upload/c_fill,h_526,w_1000/g_south_west,l_homehapp-logo-horizontal-with-shadow,x_20,y_20/v1441911573/'));
}
}
}
let city = neighborhood.location.city;
initMetadata(res);
res.locals.openGraph['og:image'] = images.concat(res.locals.openGraph['og:image']);
setLastMod([neighborhood, city].concat(neighborhood.homes), res);
res.locals.data.title = [`Homes in ${neighborhood.title}`];
let description = `View our exclusive homes in ${neighborhood.title}, ${city.title}`;
res.locals.page = {
title: res.locals.data.title.join(' | '),
description: description
};
debug('callback finished');
next();
})
.catch(next);
});
};
<file_sep>import React from 'react';
import { Link } from 'react-router';
// Widgets
import BigImage from '../../../common/components/Widgets/BigImage';
import ContentBlock from '../../../common/components/Widgets/ContentBlock';
import Hoverable from '../../../common/components/Widgets/Hoverable';
import LargeText from '../../../common/components/Widgets/LargeText';
import Loading from '../../../common/components/Widgets/Loading';
import NeighborhoodListStore from '../../stores/NeighborhoodListStore';
import ErrorPage from '../../../common/components/Layout/ErrorPage';
import { setPageTitle, merge } from '../../../common/Helpers';
// let debug = require('debug')('NeighborhoodList');
export default class NeighborhoodList extends React.Component {
static propTypes = {
params: React.PropTypes.object.isRequired
}
constructor(props) {
super(props);
this.city = props.params.city;
this.storeListener = this.onChange.bind(this);
}
state = {
error: null,
neighborhoods: NeighborhoodListStore.getState().items || NeighborhoodListStore.getState().neighborhoods
}
componentDidMount() {
setPageTitle(`Neighbourhoods of ${this.city.substr(0, 1).toUpperCase()}${this.city.substr(1)}`);
NeighborhoodListStore.listen(this.storeListener);
NeighborhoodListStore.fetchItems({city: this.city});
}
componentWillUnmount() {
setPageTitle();
NeighborhoodListStore.unlisten(this.storeListener);
}
onChange(state) {
this.setState({
error: state.error,
neighborhoods: state.items
});
}
handlePendingState() {
return (
<Loading>
<p>Loading neighborhoods...</p>
</Loading>
);
}
handleErrorState() {
let error = {
title: 'Error loading neighborhoods!',
message: this.state.error.message
};
return (
<ErrorPage {...error} />
);
}
render() {
let image = {
src: 'images/content/london-view.jpg',
alt: 'London Cityscape',
author: '<NAME>',
type: 'asset'
};
if (this.state.error) {
return this.handleErrorState();
}
let neighborhoods = this.state.neighborhoods || [];
return (
<div className='neighborhood-list-container'>
<BigImage image={image}>
<LargeText align='center' valign='middle'>
<h1>Neighbourhoods of London</h1>
</LargeText>
</BigImage>
<ContentBlock className='neighborhoods-list'>
{
neighborhoods.map((neighborhood, index) => {
let image = merge({}, neighborhood.mainImage);
let city = 'london';
if (neighborhood.location.city && neighborhood.location.city.slug) {
city = neighborhood.location.city.slug;
}
return (
<div className='neighborhood' key={index}>
<Link className='image-wrapper' to='neighborhoodView' params={{city: city, neighborhood: neighborhood.slug}}>
<Hoverable className='with-shadow' {...image} width={1200} height={680} mode='fill' />
</Link>
<ContentBlock valign='center'>
<h2 className='block-title'>
<Link to='neighborhoodView' params={{city: city, neighborhood: neighborhood.slug}}>
{neighborhood.title}
</Link>
</h2>
<ul className='buttons'>
<li>
<Link to='neighborhoodView' params={{city: city, neighborhood: neighborhood.slug}}>
Read about
</Link>
</li>
<li>
<Link to='neighborhoodViewHomes' params={{city: city, neighborhood: neighborhood.slug}}>
Show homes
</Link>
</li>
</ul>
</ContentBlock>
</div>
);
})
}
</ContentBlock>
</div>
);
}
}
<file_sep>import {randomString} from '../../lib/Helpers';
var generateUniqueSlug = function (home, cb, iteration) {
if (iteration > 10) {
return cb(new Error('iteration overflow'));
}
home.slug = randomString(8);
home.constructor.count({slug: home.slug, deletedAt: null}, function (err, count) {
if (err) {
return cb(err);
}
// slug is unique
if (count === 0) {
return cb();
}
// slug is not unique
generateUniqueSlug(home, cb, (iteration || 0) + 1);
});
};
exports.extendSchema = function (schema) {
// Generate slug
schema.pre('validate', function (next) {
if (!this.slug && this.isNew) {
generateUniqueSlug(this, next, 0);
} else {
next();
}
});
require('util')._extend((schema.methods || {}), {
/**
* Request ACL implementations
**/
is(user, requirements, done) {
var status = false;
done(null, status);
},
can(user, requirement, done) {
done(null, false);
},
updateActionState(type, user) {
return new Promise((resolve, reject) => {
let HomeAction = this.db.model('HomeAction');
switch (type) {
case 'like':
if (this.likes.users.indexOf(user.uuid) !== -1) {
// User has already liked this home
HomeAction.remove({
type: type,
home: this.id,
user: user.id
}).exec((err) => {
if (err) {
return reject(err);
}
this.likes.users = this.likes.users.filter((uuid) => {
return uuid !== user.uuid;
});
this.likes.total = this.likes.total - 1;
this.saveAsync().then(() => {
resolve({
status: false,
data: {
likes: this.likes
}
});
}).catch(reject);
});
} else {
// New like from User
let action = new HomeAction({
type: type,
home: this.id,
user: user.id
});
action.save((err) => {
if (err) {
return reject(err);
}
this.likes.users.push(user.uuid);
this.likes.total = this.likes.total + 1;
this.saveAsync().then(() => {
resolve({
status: true,
data: {
likes: this.likes
}
});
}).catch(reject);
});
}
break;
default:
return reject(new Error(`unknown action type '${type}'`));
}
});
}
});
};
<file_sep>'use strict';
import path from 'path';
import cloudinary from 'cloudinary';
import Configuration from '../server/lib/Configuration';
import {merge, walkDirSync} from '../server/lib/Helpers';
let debug = require('debug')('ProjectUploader');
const PROJECT_ROOT = path.join(__dirname, '..');
const PROJECT_NAME = process.env.PROJECT_NAME || 'site';
class ProjectUploader {
constructor() {
}
upload(sourceFolder, callback) {
this.sourceFolder = path.resolve(sourceFolder);
let status = null;
this._configure()
.then(() => {
console.log('Configured, proceed to upload resources');
return this._uploadResources('images')
})
.then(() => {
console.log('Images uploaded');
return this._uploadResources('fonts')
})
.then(() => {
console.log('Fonts uploaded');
return this._uploadResources('css');
})
.then(() => {
return this._uploadResources('js');
})
.then(() => {
console.log('Finished Uploading all assets');
callback(null, status);
})
.catch((err) => {
callback(err);
});
}
_uploadResources(resourceName) {
console.log(`Uploading ${resourceName} resources`);
let tasks = [];
let filesPath = path.join(this.sourceFolder, resourceName);
let files = walkDirSync(filesPath);
files.forEach((filePath) => {
let baseName = path.basename(filePath);
tasks.push(new Promise((resolve, reject) => {
let publicId = `${PROJECT_NAME}/${resourceName}/${baseName}`;
console.log(`Removing old ${baseName}`);
this.cloudinary.uploader.destroy(publicId, () => {
console.log(`Uploading ${baseName}`);
let timeout = 30;
let t = (new Date()).getTime();
let timer = setInterval(() => {
let dt = Math.round(((new Date()).getTime() - t) / 1000) / 60;
console.log(`Warning! Uploading '${baseName}' has lasted already for ${dt}min...`);
}, timeout * 1000);
this.cloudinary.uploader.upload(filePath, (result) => {
let dt = Math.round(((new Date()).getTime() - t) / 100) / 10;
console.log(`Upload finished for ${baseName} in ${dt}s`);
clearInterval(timer);
resolve();
}, {
public_id: publicId,
resource_type: 'raw',
invalidate: true
});
}, {
resource_type: 'raw'
});
}));
});
return Promise.all(tasks);
}
_configure() {
return new Promise((resolve, reject) => {
Configuration.load(PROJECT_ROOT, PROJECT_NAME, path.join(PROJECT_ROOT, 'config'), {}, (configError, projectConfig) => {
if (configError) {
return reject(configError);
}
let config = projectConfig.cdn.adapterConfig;
let uri = require('url').parse(config.uri, true);
let uriConfig = {
'cloud_name': uri.host,
'api_key': uri.auth && uri.auth.split(':')[0],
'api_secret': uri.auth && uri.auth.split(':')[1],
'private_cdn': uri.pathname != null,
'secure_distribution': uri.pathname && uri.pathname.substring(1)
};
config = merge(config, uriConfig);
cloudinary.config(uriConfig);
this.cloudinary = cloudinary;
resolve(config);
});
});
}
}
export default ProjectUploader;
<file_sep>/*eslint-env es6 */
import React from 'react';
// Internal components
import HomeListStore from '../../stores/HomeListStore';
import ErrorPage from '../../../common/components/Layout/ErrorPage';
// Home List
import HomeList from './HomeList';
// Story widgets
import BigImage from '../../../common/components/Widgets/BigImage';
import LargeText from '../../../common/components/Widgets/LargeText';
import Loading from '../../../common/components/Widgets/Loading';
import { setPageTitle } from '../../../common/Helpers';
let debug = require('debug')('HomeSearch');
export default class HomeSearch extends React.Component {
static propTypes = {
params: React.PropTypes.object
}
constructor(props) {
super(props);
this.storeListener = this.onChange.bind(this);
this.state.type = props.params.mode || 'buy';
}
state = {
error: null,
type: 'buy',
homes: HomeListStore.getState().items
}
componentDidMount() {
HomeListStore.listen(this.storeListener);
let filters = {type: this.props.params.mode || this.state.type};
this.updateFilters(filters);
}
componentWillReceiveProps(props) {
let type = props.params.mode || this.state.type || 'buy';
this.setState({
type: type
});
let filters = {type: type};
this.updateFilters(filters);
}
componentWillUnmount() {
HomeListStore.unlisten(this.storeListener);
}
onChange(state) {
this.setState({
error: state.error,
homes: state.items
});
}
updateFilters(filters = {}) {
debug('Filters', filters);
HomeListStore.fetchItems(filters);
}
handlePendingState() {
return (
<Loading>
<p>Loading homes...</p>
</Loading>
);
}
handleErrorState() {
let error = {
title: 'Error loading homes!',
message: this.state.error.message
};
return (
<ErrorPage {...error} />
);
}
render() {
if (this.state.error) {
return this.handleErrorState();
}
if (HomeListStore.isLoading()) {
return this.handlePendingState();
}
let homes = this.state.homes || [];
let label = (this.state.type === 'buy') ? 'sale' : 'rent';
setPageTitle(`Select homes for ${label} in London’s finest neighourhoods`);
let placeholder = {
url: 'https://res.cloudinary.com/homehapp/image/upload/v1439564093/london-view.jpg',
alt: ''
};
return (
<div id='propertyFilter'>
<BigImage gradient='green' fixed image={placeholder} proportion={0.8}>
<LargeText align='center' valign='middle' proportion={0.8}>
<div className='splash'>
<h1>Select homes for {label} in London’s finest neighourhoods</h1>
</div>
</LargeText>
</BigImage>
<HomeList items={homes} />
</div>
);
}
}
<file_sep>/* global window */
import React from 'react';
import { Link } from 'react-router';
import Hoverable from '../../../common/components/Widgets/Hoverable';
import DOMManipulator from '../../../common/DOMManipulator';
let debug = require('../../../common/debugger')('HomeList');
export default class HomeList extends React.Component {
static propTypes = {
items: React.PropTypes.array.isRequired,
max: React.PropTypes.number,
className: React.PropTypes.string,
children: React.PropTypes.oneOfType([
React.PropTypes.object,
React.PropTypes.array
]),
page: React.PropTypes.number,
maxCols: React.PropTypes.number,
filter: React.PropTypes.func
};
static defaultProps = {
max: Infinity,
className: null,
page: 1,
maxCols: 5,
filter: (home) => {
return null;
}
};
constructor() {
super();
this.onClick = this.onClick.bind(this);
this.updateView = this.updateView.bind(this);
this.container = null;
this.list = null;
this.lastWidth = 0;
}
componentDidMount() {
this.container = new DOMManipulator(this.refs.container);
this.list = new DOMManipulator(this.refs.list);
this.updateEvents();
if (window) {
window.addEventListener('resize', this.updateView);
this.updateView();
this.container.addClass('init');
}
}
componentDidUpdate() {
this.updateEvents();
}
componentWillUnmount() {
if (window) {
window.removeEventListener('resize', this.updateView);
}
}
componentWillReceiveProps(props) {
setTimeout(() => {
this.updateView();
}, 100);
}
updateView() {
if (!this.container) {
return null;
}
let cards = this.list.children();
if (!cards.length) {
return null;
}
if (cards.length === 1 || window.innerWidth < 320) {
debug('trap');
cards.map((card) => {
card.css({
marginLeft: '',
marginTop: ''
});
});
this.list.addClass('single');
return null;
}
this.list.removeClass('single');
let d = cards[0].width() || 424;
let w = this.list.width();
let cols = Math.max(2, Math.min(Math.floor(w / d), this.props.maxCols, cards.length) || 1);
debug('Cols', cols);
let heights = [];
for (let i = 0; i < cols; i++) {
heights.push(0);
}
cards.map((card) => {
if (cols < 2) {
card.css({
marginLeft: 0,
marginTop: 0
});
return card;
}
for (let img of card.getByTagName('img')) {
let ar = Number(img.attr('data-aspect-ratio'));
if (!ar) {
continue;
}
let height = Math.round(img.width() / ar);
img.height(height);
}
if (card.hasClass('invisible')) {
return card;
}
// Get the shortest column
let col = Math.max(0, heights.indexOf(Math.min(...heights)));
let h = card.height();
card.css({
marginLeft: `${(col - cols / 2) * d}px`,
marginTop: `${heights[col]}px`
});
heights[col] += h;
return card;
});
let height = Math.max(...heights);
this.list.css('min-height', `${height}px`);
}
updateEvents() {
if (!this.container) {
return false;
}
let cards = this.container.getByClass('card');
for (let card of cards) {
card.removeEvent('click', this.onClick, true);
card.addEvent('click', this.onClick, true);
card.removeEvent('touch', this.onClick, true);
card.addEvent('touch', this.onClick, true);
}
}
onClick(event) {
let target = event.target;
do {
if (target.tagName.toLowerCase() === 'a') {
return true;
}
if (target === this.container) {
break;
}
target = target.parentNode;
} while (target.parentNode);
let links = this.container.getByTagName('a');
for (let link of links) {
let e = new Event('click', {
target: link
});
link.node.dispatchEvent(e);
break;
}
}
getStreet(home) {
if (home.location.address.street) {
return (<span className='street'>{home.location.address.street}</span>);
}
return null;
}
getNeighborhood(home) {
if (home.location.neighborhood && typeof home.location.neighborhood === 'object') {
return (<span className='neighborhood'>{home.location.neighborhood.title}</span>);
}
return null;
}
getCity(home) {
if (home.location.neighborhood && home.location.neighborhood.city && home.location.neighborhood.city.title) {
return (<span className='neighborhood'>{home.location.neighborhood.city.title}</span>);
}
return null;
}
getCurrencySymbol(currency) {
if (currency.toLowerCase() === 'eur') {
return (<span className='currency eur'>€</span>);
}
return (<span className='currency gbp'>£</span>);
}
render() {
let containerClass = ['home-list', 'widget', 'pattern'];
if (this.props.className) {
containerClass.push(this.props.className);
}
let homes = this.props.items;
let limit = this.props.max;
let page = Number(this.props.page) - 1;
if (isNaN(page)) {
page = 0;
}
if (homes.length > limit) {
homes = homes.splice(page * limit, this.props.max);
}
return (
<div className={containerClass.join(' ')} ref='container'>
<hr className='spacer' />
{this.props.children}
<div className='clearfix list-container' ref='list'>
{
homes.map((home, index) => {
if (!home) {
return null;
}
let classes = ['card'];
let filterClass = (typeof this.props.filter === 'function') ? this.props.filter(home) : '';
if (filterClass) {
classes.push(filterClass);
}
if (index === this.props.max) {
classes.push('last');
}
if (!index) {
classes.push('first');
}
if (home.story.enabled && home.story.blocks.length) {
classes.push('story');
}
let link = {
to: 'home',
params: {
slug: home.slug
}
};
let mainImage = {
url: home.mainImage.url,
alt: home.mainImage.alt,
width: 424,
aspectRatio: home.mainImage.aspectRatio || 1,
applySize: true,
className: 'with-shadow',
mode: 'fit'
};
let neighborhood = null;
let city = (<span className='city default'>London</span>);
if (home.location && home.location.address && home.location.address.city) {
city = (<span className='city manual'>{home.location.address.city}</span>);
}
if (home.location.neighborhood && home.location.neighborhood.title) {
neighborhood = (<span className='neighborhood'>{home.location.neighborhood.title}</span>);
if (home.location.neighborhood.location && home.location.neighborhood.location.city && home.location.neighborhood.location.city.title) {
city = (<span className='city from-neighborhood'>{home.location.neighborhood.location.city.title}</span>);
}
}
let description = home.description;
let maxChars = 200;
if (description.length > maxChars) {
description = description.substr(0, maxChars).replace(/[\., \-]*$/, '...');
}
let price = null;
let badge = null;
switch (home.announcementType) {
case 'buy':
badge = (<span className='badge dark'><span>Buy now</span></span>);
if (home.formattedPrice) {
price = (
<p className='price'>
{this.getCurrencySymbol(home.costs.currency)}
{home.formattedPrice}
</p>
);
}
break;
case 'rent':
badge = (<span className='badge medium'><span>For rent</span></span>);
if (home.formattedPrice) {
price = (
<p className='price'>
{this.getCurrencySymbol(home.costs.currency)}
{home.formattedPrice}
<span className='per-month'>/ month</span>
</p>
);
}
break;
}
return (
<div className={classes.join(' ')} key={`containerItem${index}`}>
<Link {...link} className='thumbnail'>
<Hoverable {...mainImage}>
<span className='shares'>
<i className='fa fa-heart'>312</i>
<i className='fa fa-share-alt'>12</i>
</span>
</Hoverable>
</Link>
<Link {...link}>{badge}</Link>
<div className='details'>
<p className='location'>
{neighborhood}
{city}
</p>
<h3>
<Link {...link} className='thumbnail'>
{home.homeTitle}
</Link>
</h3>
<p className='description'>{description}</p>
{price}
</div>
</div>
);
})
}
</div>
<hr className='spacer' />
</div>
);
}
}
<file_sep>import Fixtures from './fixtures';
let debug = require('debug')('MongooseMigrator.Action.Init');
let initCollections = function initCollections(migrator, args) {
debug('initCollections');
let applyFixtures = false;
if (args.indexOf('applyFixtures') !== -1) {
applyFixtures = true;
}
if (!applyFixtures) {
return Promise.resolve();
}
return Fixtures.populate(migrator);
};
module.exports = function(migrator, args) {
debug('init action promise', args);
return initCollections(migrator, args);
};
<file_sep>import React from 'react';
export default class LargeText extends React.Component {
static propTypes = {
align: React.PropTypes.string,
valign: React.PropTypes.string,
children: React.PropTypes.oneOfType([
React.PropTypes.null,
React.PropTypes.object,
React.PropTypes.array
]),
proportion: React.PropTypes.number,
className: React.PropTypes.string,
aspectRatio: React.PropTypes.number,
id: React.PropTypes.string
};
static defaultProps = {
align: 'center',
valign: 'middle',
proportion: null,
aspectRatio: null,
className: null
};
render() {
let classes = [
'width-wrapper'
];
if (this.props.className) {
classes.push(this.props.className);
}
let props = {
'data-align': this.props.align,
'data-valign': this.props.valign
};
if (this.props.aspectRatio) {
classes.push('aspect-ratio');
props['data-aspect-ratio'] = this.props.aspectRatio;
} else {
classes.push('full-height');
}
let mainProps = {
className: 'widget large-text'
};
if (this.props.id) {
mainProps.id = this.props.id;
}
return (
<div {...mainProps}>
<div className={classes.join(' ')} {...props}>
<div className='content' {...props}>
{this.props.children}
</div>
</div>
</div>
);
}
}
<file_sep>import QueryBuilder from '../../lib/QueryBuilder';
import {NotFound, BadRequest, Forbidden} from '../../lib/Errors';
import {randomString, exposeHome, exposeUser} from '../../lib/Helpers';
let debug = require('debug')('API: /api/auth/user');
exports.registerRoutes = (app) => {
const QB = new QueryBuilder(app);
/**
* @apiDefine UserSuccessResponse
* @apiVersion 1.0.1
*
* @apiSuccess {Object} user User details
* @apiSuccess {String} user.id Internal Id of the user
* @apiSuccess {String} user.email User's email
* @apiSuccess {String} user.displayName User's fullname
* @apiSuccess {String} user.firstname User's firstname
* @apiSuccess {String} user.lastname User's lastname
* @apiSuccess {Object} user.profileImage User's profile image as an <a href="#api-Shared-Images">Image</a> object
* @apiSuccess {Object} user.contact User's contact information
* @apiSuccess {Object} user.contact.address Address information
* @apiSuccess {String} user.contact.address.street User's street address (only for the authenticated user)
* @apiSuccess {String} user.contact.address.city User's city
* @apiSuccess {String} user.contact.address.zipcode User's post office code
* @apiSuccess {String} user.contact.address.country User's country
* @apiSuccess {String} user.contact.phone User's phone number
*/
/**
* @apiDefine UserSuccessResponseJSON
* @apiVersion 1.0.1
*
* @apiSuccessExample {json} JSON serialization of the user
* "user": {
* "id": "...",
* "email": "...",
* "displayName": "...",
* "firstname": "...",
* "lastname": "...",
* "profileImage": {
* "url": "...",
* "alt": "...",
* "width": ...,
* "height": ...
* },
* "contact": {
* "address": {
* "street": "...",
* "city": "...",
* "zipcode": "...",
* "country": "..."
* },
* "phone": "..."
* }
* }
*/
/**
* @apiDefine UserBody
* @apiVersion 1.0.1
*
* @apiParam {String} [user.email] User's email address
* @apiParam {String} [user.firstname] User's firstname
* @apiParam {String} [user.lastname] User's lastname
* @apiParam {Object} [user.profileImage] User's profile <a href="#api-Shared-Images">Image</a>
* @apiParam {Object} [user.contact] User's contact information
* @apiParam {Object} [user.contact.address] User's address information
* @apiParam {String} [user.contact.address.street] User's street address
* @apiParam {String} [user.contact.address.city] User's street address
* @apiParam {String} [user.contact.address.zipcode] User's street address
* @apiParam {String} [user.contact.address.country] User's street address
* @apiParam {String} [user.contact.phone] User's phone number
*
* @apiParamExample {json} Request-example
* {
* "user": {
* "email": "<EMAIL>",
* "firstname": "Test",
* "lastname": "Tester",
* "profileImage": {
* "url": "https://lh3.googleusercontent.com/-1NSytNuggHM/VDp8UrP5dpI/AAAAAAAAAHk/Ds4khe_1Eoo/w214-h280-p/self-portrait.jpg",
* "alt": "Testi Testiikkeli",
* "width": 214,
* "height": 280
* },
* "contact": {
* "address": {
* "street": "Examplestreet",
* "city": "Exampleville",
* "zipcode": "01234",
* "country": "EX"
* },
* "phone": "+1 23 456 7890"
* }
* }
* }
*/
/**
* @api {any} /api/* User details
* @apiVersion 1.0.1
* @apiName UserData
* @apiGroup Users
*
* @apiDescription User details for each response that has the user object contains the same set of data
* @apiUse UserSuccessResponse
* @apiUse UserSuccessResponseJSON
*/
/**
* @api {get} /api/auth/user
* @apiVersion 1.0.1
* @apiName GetUser
* @apiGroup Users
*
* @apiDescription Get the details of the current user
* @apiPermission authenticated
* @apiUse MobileRequestHeadersAuthenticated
* @apiUse UserSuccessResponse
* @apiUse UserSuccessResponseJSON
*
* @apiError (403) Forbidden User account has been disabled or not logged in
* @apiErrorExample Error-Response:
* HTTP/1.1 403 Forbidden
* {
* "status": "failed",
* "error": "account disabled"
* }
*/
app.get('/api/auth/user', app.authenticatedRoute, function(req, res, next) {
debug('User ID', req.user.id);
let user = null;
QB
.forModel('User')
.findById(req.user.id)
.fetch()
.then((result) => {
user = result.model;
debug('foobar');
QB
.forModel('Home')
.query({
createdBy: user
})
.populate({
createdBy: {},
updatedBy: {}
})
.findOne()
.fetch()
.then((result) => {
res.json({
status: 'ok',
user: exposeUser(user, req.version, user),
home: exposeHome(result.model, req.version, user)
});
})
.catch((err) => {
res.json({
status: 'ok',
user: exposeUser(user, req.version, user),
home: null
});
});
})
.catch(next);
});
/**
* @api {put} /api/auth/user Update user details
* @apiVersion 1.0.1
* @apiName UpdateUser
* @apiGroup Users
*
* @apiDescription Update user details
*
* @apiPermission authenticated
* @apiUse MobileRequestHeadersAuthenticated
* @apiUse UserSuccessResponse
* @apiUse UserSuccessResponseJSON
* @apiUse UserBody
*
* @apiError (400) BadRequest Invalid request body, missing parameters.
* @apiError (403) Forbidden User account has been disabled
* @apiErrorExample Error-Response:
* HTTP/1.1 403 Forbidden
* {
* "status": "failed",
* "error": "account disabled"
* }
*/
app.put('/api/auth/user', app.authenticatedRoute, function(req, res, next) {
if (!req.body.user) {
return next(new BadRequest('invalid request body'));
}
let data = req.body.user;
delete data.id;
QB
.forModel('User')
.findById(req.user.id)
.update(data)
.then((user) => {
res.json({
status: 'ok',
user: exposeUser(user)
});
})
.catch(next);
});
};
<file_sep>import React from 'react';
import Row from 'react-bootstrap/lib/Row';
import Col from 'react-bootstrap/lib/Col';
import Panel from 'react-bootstrap/lib/Panel';
// let debug = require('../../../common/debugger')('HomesEditStory');
export default class HomesCreateStory extends React.Component {
render() {
return (
<Row>
<form name='homeStory' ref='homeStoryForm' method='POST'>
<Col md={10} sm={10}>
<Panel header='Common'>
<p>Please save the basic details first</p>
</Panel>
</Col>
</form>
</Row>
);
}
}
<file_sep>import AgentListActions from '../actions/AgentListActions';
import AgentListSource from '../sources/AgentListSource';
import ListStore from '../../common/stores/BaseListStore';
export default ListStore.generate('AgentListStore', {
actions: AgentListActions,
source: AgentListSource
});
<file_sep>#! /bin/sh
# Do not change these
REV=`git rev-parse --short HEAD`
CWD=`pwd`
CONTAINER_REGISTRY_HOST=eu.gcr.io
PNAME=$1
ENV=$2
CLUSTER_NAME="homehapp-$PNAME-$ENV"
CLUSTER_GOOGLE_NAME=""
NODE_GOOGLE_NAME=""
function printUsage() {
echo "Required environment variables:"
echo " PROJECT_ID: Google Project ID"
echo ""
echo "Usage PROJECT_ID=id ./support/createCluster.sh [project_name] [stg,prod]"
echo "Add -d for dry-run"
}
function printUsageAndExit() {
printUsage
exit
}
if [ "$PROJECT_ID" = "" ]; then
echo "No Google Project ID defined!"
printUsageAndExit
fi
if [ "$PNAME" = "" ]; then
echo "No project defined!"
printUsageAndExit
fi
if [ ! -d "$CWD/tmp" ]; then
mkdir "$CWD/tmp"
fi
function createCluster() {
if [ "$1" = "-d" ]; then
echo "Execute: 'gcloud beta container clusters create $CLUSTER_NAME --num-nodes 1 --machine-type n1-standard-1 --project $PROJECT_ID'"
else
gcloud beta container clusters create $CLUSTER_NAME --num-nodes 1 --machine-type n1-standard-1 --project $PROJECT_ID
CLUSTER_GOOGLE_NAME=`kubectl config view | grep $PROJECT_ID | awk '{print $2}' | grep $CLUSTER_NAME | tail -n 1`
NODE_GOOGLE_NAME=`kubectl get nodes --context=$CLUSTER_GOOGLE_NAME | awk '{print $1}' | tail -n 1`
local len=${#NODE_GOOGLE_NAME}
NODE_GOOGLE_NAME=${NODE_GOOGLE_NAME:0:$((len-5))}
fi
}
function setContext() {
if [ "$CLUSTER_GOOGLE_NAME" = "" ]; then
CLUSTER_GOOGLE_NAME=`kubectl config view | awk '{print $2}' | grep $CLUSTER_NAME | tail -n 1`
fi
if [ "$1" = "-d" ]; then
echo "Execute: 'kubectl config use-context $CLUSTER_GOOGLE_NAME'"
else
kubectl config use-context $CLUSTER_GOOGLE_NAME
fi
}
function createController() {
local SOURCE_CONFIG="$CWD/infrastructure/configs/project-controller-tpl.json"
local TARGET_CONFIG="$CWD/tmp/$PNAME-controller.json"
local TMP_FILE="/tmp/$PNAME-controller.json"
sed "s/:PROJECT_NAME/$PNAME/g" $SOURCE_CONFIG > $TARGET_CONFIG
sed "s/:PROJECT_ID/$PROJECT_ID/g" $TARGET_CONFIG > $TMP_FILE && mv $TMP_FILE $TARGET_CONFIG
sed "s/:CONTROLLER_NAME/$PNAME-controller-$REV/g" $TARGET_CONFIG > $TMP_FILE && mv $TMP_FILE $TARGET_CONFIG
sed "s/:REV/$REV/g" $TARGET_CONFIG > $TMP_FILE && mv $TMP_FILE $TARGET_CONFIG
sed "s/:ENV/$ENV/g" $TARGET_CONFIG > $TMP_FILE && mv $TMP_FILE $TARGET_CONFIG
if [ "$1" = "-d" ]; then
echo "Execute: 'kubectl create -f $CWD/tmp/$PNAME-controller.json'"
else
kubectl create -f "$CWD/tmp/$PNAME-controller.json"
rm $TARGET_CONFIG
fi
}
function createService() {
local SOURCE_CONFIG="$CWD/infrastructure/configs/project-service-tpl.json"
local TARGET_CONFIG="$CWD/tmp/$PNAME-service.json"
local TMP_FILE="/tmp/$PNAME-service.json"
sed "s/:PROJECT_NAME/$PNAME/g" $SOURCE_CONFIG > $TARGET_CONFIG
sed "s/:PROJECT_ID/$PROJECT_ID/g" $TARGET_CONFIG > $TMP_FILE && mv $TMP_FILE $TARGET_CONFIG
if [ "$1" = "-d" ]; then
echo "Execute: 'kubectl create -f $CWD/tmp/$PNAME-service.json'"
else
kubectl create -f "$CWD/tmp/$PNAME-service.json"
rm $TARGET_CONFIG
fi
}
# function openFirewall() {
# if [ "$CLUSTER_GOOGLE_NAME" = "" ]; then
# CLUSTER_GOOGLE_NAME=`kubectl config view | awk '{print $2}' | grep $CLUSTER_NAME | tail -n 1`
# fi
# if [ "$NODE_GOOGLE_NAME" = "" ]; then
# NODE_GOOGLE_NAME=`kubectl get nodes --context=$CLUSTER_GOOGLE_NAME | awk '{print $1}' | tail -n 1`
# local len=${#NODE_GOOGLE_NAME}
# NODE_GOOGLE_NAME=${NODE_GOOGLE_NAME:0:$((len-5))}
# fi
#
# if [ "$1" = "-d" ]; then
# echo "Execute: 'gcloud compute firewall-rules create $PNAME-8080 --allow tcp:8080 --target-tags $NODE_GOOGLE_NAME --project $PROJECT_ID"
# else
# gcloud compute firewall-rules create $PNAME-8080 --allow tcp:8080 --target-tags $NODE_GOOGLE_NAME --project $PROJECT_ID
# fi
# }
if [ "$3" = "-d" ]; then
echo "In Dry-Run mode"
fi
echo "Creating Container Cluster $CLUSTER_NAME"
echo ""
createCluster $3
setContext $3
echo ""
echo "Creating Replication Controller $PNAME-controller"
createController $3
echo ""
echo "Creating Service $PNAME-service"
createService $3
# echo ""
# echo "Opening firewall for service"
#
# openFirewall $3
echo ""
echo "Cluster created!"
echo ""
if [ "$3" = "" ]; then
echo "Execute following script after few minutes to find out the external IP."
echo "kubectl describe services $PNAME --context=$CLUSTER_GOOGLE_NAME | grep 'LoadBalancer Ingress'"
fi
<file_sep># Create instance
gcloud compute instances create hh-management \
--machine-type "f1-micro" --network "default" \
--image debian-7-backports \
--tags homehapp,management
# Connect to instance
gcloud compute ssh --project $PROJECT_ID --ssh-flag="-A" homehapp@hh-management
## Connecting to Docker containers
1. ssh to management
2. ssh to Container Cluster node
3. sudo su
4. docker ps
5. docker exec -it [container id] bash
<file_sep>.PHONY: build push
build:
docker build -t eu.gcr.io/$(PROJECT_ID)/nginx-proxy .
push:
gcloud docker push eu.gcr.io/$(PROJECT_ID)/nginx-proxy
<file_sep>import basicAuth from 'basic-auth-connect';
import fs from 'fs';
import path from 'path';
//let debug = require('debug')('FirstRunMiddleware');
exports.configure = function(app, config = {}) {
if (!config.enabled) {
return Promise.resolve();
}
let firstRunFlagPath = path.join(app.PROJECT_ROOT, '.firstrun');
app.firstRun = {
routePath: config.path,
firstRunFlagPath: firstRunFlagPath,
isDone: () => {
return new Promise((resolve) => {
if (fs.existsSync(firstRunFlagPath)) {
return resolve(true);
}
resolve(false);
});
},
markAsDone: () => {
fs.writeFileSync(firstRunFlagPath, '1');
}
};
app.use((req, res, next) => {
if (!req.path.match(new RegExp(`^${config.path}`))) {
app.firstRun.isDone()
.then((status) => {
if (!status) {
return res.redirect(config.path);
}
next();
}).catch(next);
} else {
next();
}
});
app.route(config.path)
.all(basicAuth(config.username, config.password))
.get((req, res, next) => {
app.firstRun.isDone()
.then((status) => {
if (status) {
return res.redirect('/');
}
app.getLocals(req, res, {
includeClient: false,
bodyClass: 'adminFirstRun',
csrfToken: req.csrfToken(),
firstRunPath: config.path
})
.then((locals) => {
res.render('firstrun', locals);
});
}).catch(next);
});
return Promise.resolve();
};
<file_sep>import alt from '../../common/alt';
let debug = require('../../common/debugger')('HomeActions');
@alt.createActions
class HomeActions {
updateHome(home) {
this.dispatch(home);
}
fetchHomeBySlug(slug, skipCache) {
debug('fetchHomeBySlug', slug, skipCache);
this.dispatch(slug, skipCache);
}
fetchFailed(error) {
debug('fetchFailed', error);
this.dispatch(error);
}
}
module.exports = HomeActions;
<file_sep>import React from 'react';
import ContentBlock from '../../../common/components/Widgets/ContentBlock';
import BigImage from '../../../common/components/Widgets/BigImage';
import LargeText from '../../../common/components/Widgets/LargeText';
import Image from '../../../common/components/Widgets/Image';
import Separator from '../../../common/components/Widgets/Separator';
import InputWidget from '../../../admin/components/Widgets/Input';
import Modal from '../../../common/components/Widgets/Modal';
import AuthStore from '../../../common/stores/AuthStore';
import SocialMedia from '../Navigation/SocialMedia';
import DOMManipulator from '../../../common/DOMManipulator';
import { countryMap } from '../../../common/lib/Countries';
import NewsletterStore from '../../stores/NewsletterStore';
import NewsletterActions from '../../actions/NewsletterActions';
import ContactStore from '../../stores/ContactStore';
import ContactActions from '../../actions/ContactActions';
let debug = require('debug')('Lander');
export default class Lander extends React.Component {
constructor() {
super();
this.contactStateChange = this.contactStateChange.bind(this);
this.newsletterStateChange = this.newsletterStateChange.bind(this);
this.authStoreListener = this.onAuthStoreChange.bind(this);
}
state = {
error: null,
newsletter: null,
contact: null,
user: AuthStore.getState().user,
loggedIn: AuthStore.getState().loggedIn
}
componentDidMount() {
let scroller = new DOMManipulator(this.refs.readmore);
debug('scroller', scroller);
if (jQuery) {
jQuery('a.pager').on('click touch', function() {
let i = Math.floor(jQuery(window).scrollTop() / jQuery(window).height()) + 1;
$('body, html').animate({
scrollTop: $(window).height() * i + 'px'
}, 1000);
});
$('#socialShare').on('click touchstart', (event) => {
event.stopPropagation();
event.preventDefault();
this.displaySocial();
});
} else {
debug('no jquery');
}
ContactStore.listen(this.contactStateChange);
NewsletterStore.listen(this.newsletterStateChange);
AuthStore.listen(this.authStoreListener);
}
componentWillUnmount() {
ContactStore.unlisten(this.contactStateChange);
NewsletterStore.unlisten(this.newsletterStateChange);
AuthStore.unlisten(this.authStoreListener);
}
onAuthStoreChange(state) {
debug('onAuthStoreChange', state);
this.setState(state);
}
newsletterStateChange(state) {
this.setState(state);
if (state.newsletter) {
this.displayThankYou();
}
}
contactStateChange(state) {
this.setState(state);
if (state.contact) {
this.displayThankYou();
}
}
displayThankYou() {
if (this.modal && this.modal.closeModal) {
this.modal.close();
}
let reject = () => {
this.modal.close();
};
let modal = (
<Modal className='white with-overflow confirmation' onClose={this.modalClose.bind(this)}>
<a className='close' onClick={reject}>✕</a>
<div className='content center centered'>
<h2>Thank you!</h2>
<p>
We will be in touch with you shortly. In the<br className='hide-for-small' /> meantime, you can check our social media<br className='hide-for-small' /> channels too.
</p>
<SocialMedia />
</div>
</Modal>
);
// Create the modal
this.modal = React.render(modal, document.getElementById('modals'));
this.initModal();
}
displaySocial() {
if (this.modal && this.modal.closeModal) {
this.modal.close();
}
let reject = () => {
this.modal.close();
};
let modal = (
<Modal className='white with-overflow confirmation confirmation-small' onClose={this.modalClose.bind(this)}>
<a className='close' onClick={reject}>✕</a>
<div className='content center centered'>
<h2>Follow us!</h2>
<p className='clearfix'></p>
<SocialMedia />
</div>
</Modal>
);
// Create the modal
this.modal = React.render(modal, document.getElementById('modals'));
this.initModal();
}
subscribeAsTester(event) {
event.preventDefault();
event.stopPropagation();
let data = {
subType: `Beta testing: ${this.refs.type.getValue()}`,
sender: {
name: this.refs.name.getValue(),
email: this.refs.email.getValue(),
country: this.refs.country.getValue(),
},
image: this.imageSeed,
type: 'email'
};
if (!data.sender.email || !data.sender.name) {
return null;
}
debug('Will send', data);
this.email = data.sender.email;
let submit = (e) => {
ContactActions.createItem(data);
};
this.displayConfirmation(submit);
}
subscribeToNewsletter(event) {
event.preventDefault();
event.stopPropagation();
this.email = (new DOMManipulator(this.refs.subscriberEmail)).node.value || (new DOMManipulator(this.refs.subscriberEmail2)).node.value || '';
if (!this.email) {
return null;
}
let submit = (e) => {
e.preventDefault();
e.stopPropagation();
let props = {
email: this.email,
image: this.imageSeed
};
NewsletterActions.createItem(props);
};
this.displayConfirmation(submit, null);
}
displayConfirmation(resolve, reject) {
if (!resolve) {
resolve = (event) => {
debug('Resolved');
};
}
if (!reject) {
reject = (event) => {
this.modal.close();
};
}
let modal = (
<Modal className='white with-overflow confirmation' onClose={this.modalClose.bind(this)}>
<a className='close' onClick={reject}>✕</a>
<div className='content center centered'>
<h2>Join with address:<br className='hide-for-small' /> {this.email}</h2>
<p>
Please confirm that your e-mail address is correct.
</p>
<p className='form-actions'>
<a className='button highlight' onClick={resolve}>Yes, that's right</a>
<a className='button' onClick={reject}>No, the address is wrong</a>
</p>
</div>
</Modal>
);
// Create the modal
this.modal = React.render(modal, document.getElementById('modals'));
this.initModal();
}
initModal() {
this.body = new DOMManipulator(document.getElementsByTagName('body')[0]);
this.body.addClass('blurred');
}
submitBetaForm(event) {
}
modalClose(event) {
if (event) {
event.preventDefault();
}
if (this.modal) {
React.unmountComponentAtNode(React.findDOMNode(this.modal));
this.modal = null;
}
let modals = document.getElementById('modals').getElementsByClassName('contact-form');
for (let modal of modals) {
if (modal.parentNode) {
modal.parentNode.removeChild(modal);
}
}
if (this.body) {
this.body.removeClass('blurred');
this.body.removeClass('no-scroll');
}
}
listCountries() {
let countries = [];
countries.push(
<option value='GB'>{countryMap['GB']}</option>
);
let tmp = [];
for (let code in countryMap) {
tmp.push([code, countryMap[code]]);
if (countryMap[code].match(/^The /)) {
tmp.push([code, countryMap[code].replace(/^The /, '')]);
}
}
tmp.sort((a, b) => {
if (a[1] < b[1]) {
return -1;
}
if (a[1] > b[1]) {
return 1;
}
return 0;
});
tmp.map((c) => {
let code = c[0];
let country = c[1];
countries.push(
<option value={code}>{country}</option>
);
});
return countries;
}
getSocialIcon() {
let classes = [
'fa',
'fa-share-alt',
'show-for-small'
];
if (this.state.loggedIn) {
classes.push('logged-in');
}
return (
<i className={classes.join(' ')} id='socialShare' ref='socialShare'></i>
);
}
render() {
let images = [
{
url: 'https://res.cloudinary.com/homehapp/image/upload/v1450887451/site/images/content/lander.jpg',
align: 'left',
width: 1920,
height: 1280
},
{
url: 'https://res.cloudinary.com/homehapp/image/upload/v1450887447/site/images/content/balcony.jpg',
align: 'center',
width: 1920,
height: 1280
},
{
url: 'https://res.cloudinary.com/homehapp/image/upload/v1450887437/site/images/content/moving-boxes.jpg',
align: 'right',
valign: 'top',
width: 1920,
height: 1280
}
];
this.imageSeed = Math.floor(Math.random() * images.length);
let image = images[this.imageSeed];
image.aspectRatio = image.width / image.height;
image.alt = '';
let appImage = {
url: 'http://res.cloudinary.com/homehapp/image/upload/v1450903388/site/images/content/responsive-homehapp.png',
alt: '',
width: 434,
height: 296,
applySize: true
};
let classes = [
'full-height-always',
`image-${this.imageSeed}`
];
return (
<div id='lander'>
{this.getSocialIcon()}
<BigImage image={image} className={classes.join(' ')} align='left'>
<LargeText align='center' valign='middle' className='full-height-always' id='mainContent'>
<h1>WE ARE<br className='show-for-small' /> TRANSFORMING<br /> HOW HOMES ARE<br className='show-for-small' /> PRESENTED</h1>
<p className='title-like hide-for-small'>
<span>Please join our mailing list.</span> We will keep you posted on our progress and notify you when we go live.
</p>
<form method='post' className='mailchimp hide-for-small' action='/api/contact/mailchimp' onSubmit={this.subscribeToNewsletter.bind(this)}>
<table className='wrapper'>
<tr>
<td width='60%' className='email'><input type='email' name='email' ref='subscriberEmail' placeholder='Fill in your email address' /></td>
<td width='40%' className='submit'><input type='submit' value='Notify me!' /></td>
</tr>
</table>
</form>
</LargeText>
<div className='secondary centered'>
<p className='title-like uppercase'>
<a href='#readmore' ref='readmore' className='pager'>
<i className='fa fa-angle-down icon'></i>
<span className='hide-for-small'>Want to know more?</span>
</a>
</p>
</div>
</BigImage>
<ContentBlock className='show-for-small pattern full-height-always mailing-list'>
<h2 className='page-title'>Please join<br /> our mailing list</h2>
<p className='title-like centered'>
We will keep you posted on our<br /> progress and notify you when<br /> we go live
</p>
<form method='post' className='mailchimp' action='/api/contact/mailchimp' onSubmit={this.subscribeToNewsletter.bind(this)}>
<table className='wrapper'>
<tr>
<td width='60%' className='email'><input type='email' name='email' ref='subscriberEmail2' placeholder='Fill in your email address' /></td>
<td width='40%' className='submit'><input type='submit' value='Join' /></td>
</tr>
</table>
</form>
<div className='secondary centered'>
<p className='title-like uppercase'>
<a href='#readmore' ref='readmore' className='pager'>
<i className='fa fa-angle-down icon'></i>
Want to know more?
</a>
</p>
</div>
</ContentBlock>
<ContentBlock className='centered center pattern' ref='target'>
<p>
<Image {...appImage} />
</p>
<h2>WE BELIEVE EVERY HOME HAS A STORY</h2>
<p className='mobile-padded'>
Homehapp is the place where you can create, store and share your<br className='hide-for-small' /> home
moments. And when the time comes for you to move on, and<br className='hide-for-small' /> you want
to sell or let your home, all you have to do is click a button<br className='hide-for-small' /> and
homehapp helps you find the right buyer or tenant.
</p>
<p className='title-like uppercase mobile-padded'>
WE’RE CURRENTLY IN BETA TESTING PHASE. PLEASE FILL IN YOUR DETAILS
<br className='hide-for-small' /> TO JOIN OUR TEST GROUP WITH EARLY ACCESS.
</p>
<form method='post' action='/api/contact/beta' onSubmit={this.subscribeAsTester.bind(this)} className='beta-testers'>
<div className='form'>
<InputWidget type='text' name='name' ref='name' placeholder='Your name' required />
<InputWidget type='email' name='email' ref='email' placeholder='Your email address' required />
<InputWidget type='select' name='country' ref='country'>
<option value=''>Pick your home country</option>
{this.listCountries()}
</InputWidget>
<InputWidget type='select' name='type' ref='type'>
<option value=''>Are you a home owner or a real estate professional?</option>
<option value='owner'>Home owner</option>
<option value='professional'>Real estate professional</option>
</InputWidget>
<InputWidget type='submit' value='Send info and become a beta tester' />
</div>
</form>
</ContentBlock>
</div>
);
}
}
<file_sep>import request from '../request';
import _debugger from '../debugger';
import {merge, enumerate} from '../Helpers';
function generateMethod(name, definition, sourceBase) {
let methodDefinition = {
local: function local() { return null; },
success: null,
error: sourceBase.actions.error,
loading: sourceBase.actions.base[name]
};
if (!definition.actions || !definition.actions.success) {
throw new Error(`no actions.success defined for ${name} -method`);
}
['success', 'loading', 'error'].forEach((key) => {
if (definition.actions[key]) {
methodDefinition[key] = definition.actions[key];
}
});
let remoteDefinition = merge({}, {
method: 'get',
response: {
key: 'items'
}
}, definition.remote || {});
remoteDefinition.method = String(remoteDefinition.method).toLowerCase();
remoteDefinition.response = definition.remote.response;
if (['put', 'post', 'patch', 'get', 'delete', 'trace', 'options', 'connect', 'head'].indexOf(remoteDefinition.method) === -1) {
throw new Error(`Invalid method "${remoteDefinition.method}"`);
}
if (typeof definition.remote.response === 'function') {
remoteDefinition.response = definition.remote.response;
}
if (!remoteDefinition.uri) {
throw new Error(`no uri defined for ${name} -method`);
}
methodDefinition.remote = function(state, ...args) {
let uri = remoteDefinition.uri;
if (typeof uri === 'function') {
uri = remoteDefinition.uri(state, args);
}
this.debug(`${name} uri: ${uri}`);
let params = {};
if (remoteDefinition.params) {
params = remoteDefinition.params;
if (typeof params === 'function') {
params = params(state, args);
}
}
console.log('remoteDefinition', remoteDefinition);
return request[remoteDefinition.method](uri, params)
.then((response) => {
this.debug(`${name} success response:`, response);
if (!response.data) {
return Promise.reject(new Error('invalid response'));
}
if (typeof remoteDefinition.response === 'function') {
return remoteDefinition.response(state, response, args);
}
let responseKey = remoteDefinition.response.key;
let resolveData = response.data;
if (responseKey) {
resolveData = response.data[responseKey];
}
if (!resolveData) {
this.debug('Invalid response, no data found for response key', responseKey);
this.debug('Received data', response.data);
return Promise.reject(new Error('invalid response'));
}
return Promise.resolve(resolveData);
})
.catch((response) => {
this.debug(`${name} error response:`, response);
if (response instanceof Error) {
return Promise.reject(response);
} else {
let msg = 'unexpected error';
if (response.data && response.data.error) {
msg = response.data.error;
}
return Promise.reject(new Error(msg));
}
return Promise.reject(response);
});
}.bind(sourceBase);
if (typeof definition.local === 'function') {
methodDefinition.local = definition.local;
}
return function() {
return methodDefinition;
};
}
export default {
build: function BuildSource(structure) {
if (!structure.name) {
throw new Error('no name defined for Source');
}
if (!structure.actions || !structure.actions.base) {
throw new Error('no actions.base defined for Source');
}
structure.methods = structure.methods || [];
let debug = _debugger(structure.name);
if (!structure.actions.error) {
structure.actions.error = structure.actions.base.requestFailed;
}
let base = {
debug: debug,
actions: structure.actions
};
let source = {};
for (let [name, definition] of enumerate(structure.methods)) {
source[name] = generateMethod(name, definition, base);
}
return source;
}
};
<file_sep>'use strict';
import should from 'should';
import expect from 'expect.js';
import request from 'supertest';
import testUtils from '../utils';
import MockupData from '../../MockupData';
let app = null;
let debug = require('debug')('Home API paths');
let mockup = null;
describe('Home API paths', () => {
before((done) => {
testUtils.createApp((err, appInstance) => {
app = appInstance;
mockup = new MockupData(app);
mockup.removeAll('Home')
.then(() => {
done(err);
})
.catch((err) => {
console.error('Failed to delete homes');
done(err);
});
});
});
let body = null;
let home = null;
it('Should respond to /api/homes with correct structure', (done) => {
request(app)
.get('/api/homes')
.expect(200)
.end((err, res) => {
should.not.exist(err);
body = res.body;
done();
});
});
it('Response of /api/homes should have the correct structure', (done) => {
should(body).have.property('status', 'ok');
should(body).have.property('homes');
should(body.homes).be.instanceof(Array);
should(body.homes).be.empty;
done();
});
it('Response of /api/homes should have the mockup home', (done) => {
mockup.createModel('Home')
.then((rval) => {
home = rval;
request(app)
.get('/api/homes')
.expect(200)
.end((err, res) => {
should.not.exist(err);
body = res.body;
should(body).have.property('status', 'ok');
should(body).have.property('homes');
should(body.homes).be.instanceof(Array);
should(body.homes).not.be.empty;
expect(body.homes.length).to.eql(1);
body.homes.map((item) => {
mockup.verify('Home', item);
});
done();
});
})
.catch((err) => {
done(err);
});
});
it('Response of /api/homes/:slug gives the correct object', (done) => {
request(app)
.get(`/api/homes/${home.slug}`)
.expect(200)
.end((err, res) => {
body = res.body;
should(body).have.property('status', 'ok');
should(body).have.property('home');
mockup.verifyHome(body.home);
done();
});
});
it('Check the URL space to verify that the newly created home is available', (done) => {
let urls = [
'/homes',
`/homes/${home.slug}`,
`/homes/${home.slug}/story`,
`/homes/${home.slug}/details`,
`/homes/${home.slug}/contact`,
'/search'
];
let promises = urls.map((url) => {
return new Promise((resolve, reject) => {
request(app)
.get(url)
.expect(200)
.end((err, res) => {
should.not.exist(err, `URL '${url}' should exist`);
body = res.text;
resolve();
});
});
});
Promise.all(promises)
.then(() => {
done();
})
.catch((err) => {
done(err);
});
});
it('Check that the home is found with the flag "buy"', (done) => {
mockup
.updateModel('Home', home, {
announcementType: 'buy'
})
.then((model) => {
return new Promise((resolve, reject) => {
request(app)
.get(`/api/homes?type=buy`)
.expect(200)
.end((err, res) => {
should.not.exist(err);
should(res.body).have.property('status', 'ok');
should(res.body).have.property('homes');
let ids = res.body.homes.map((h) => {
return h.id;
});
expect(ids.indexOf(home.uuid)).not.to.be(-1);
resolve();
})
});
})
.then(() => {
request(app)
.get(`/api/homes?type=rent`)
.expect(200)
.end((err, res) => {
should.not.exist(err);
should(res.body).have.property('status', 'ok');
should(res.body).have.property('homes');
let ids = res.body.homes.map((h) => {
return h.id;
});
expect(ids.indexOf(home.uuid)).to.be(-1);
done();
});
})
.catch((err) => {
done(err);
});
});
it('Check that the home is found with the flag "rent"', (done) => {
mockup
.updateModel('Home', home, {
announcementType: 'rent'
})
.then((model) => {
return new Promise((resolve, reject) => {
request(app)
.get(`/api/homes?type=rent`)
.expect(200)
.end((err, res) => {
should.not.exist(err);
should(res.body).have.property('status', 'ok');
should(res.body).have.property('homes');
let ids = res.body.homes.map((h) => {
return h.id;
});
expect(ids.indexOf(home.uuid)).not.to.be(-1);
resolve();
})
});
})
.then(() => {
request(app)
.get(`/api/homes?type=buy`)
.expect(200)
.end((err, res) => {
should.not.exist(err);
should(res.body).have.property('status', 'ok');
should(res.body).have.property('homes');
let ids = res.body.homes.map((h) => {
return h.id;
});
expect(ids.indexOf(home.uuid)).to.be(-1);
done();
});
})
.catch((err) => {
done(err);
});
});
it('Check that the storified home is displayed in the story API', (done) => {
mockup
.updateModel('Home', home, {
story: {
enabled: true
}
})
.then((model) => {
request(app)
.get('/api/homes?type=story')
.expect(200)
.end((err, res) => {
should.not.exist(err);
should(res.body).have.property('status', 'ok');
should(res.body).have.property('homes');
let ids = res.body.homes.map((h) => {
return h.id;
});
expect(ids.indexOf(home.uuid)).not.to.be(-1);
done();
});
})
.catch((err) => {
done(err);
});
});
it('Check that the storified home is displayed in the story API', (done) => {
mockup
.updateModel('Home', home, {
story: {
enabled: false
}
})
.then((model) => {
request(app)
.get('/api/homes?type=story')
.expect(200)
.end((err, res) => {
should.not.exist(err);
should(res.body).have.property('status', 'ok');
should(res.body).have.property('homes');
let ids = res.body.homes.map((h) => {
return h.id;
});
expect(ids.indexOf(home.uuid)).to.be(-1);
done();
});
})
.catch((err) => {
done(err);
});
});
it('Home should be hidden after enabled is set to false', (done) => {
mockup
.updateModel('Home', home, {
enabled: false
})
.then((model) => {
request(app)
.get('/api/homes')
.expect(200)
.end((err, res) => {
should.not.exist(err);
let found = false;
res.body.homes.map((h) => {
if (h.id === home.id) {
found = true;
}
});
expect(found).to.be(false);
done();
});
})
});
it('Home can be deleted', (done) => {
mockup
.remove(home)
.then(() => {
done();
})
.catch((err) => {
done(err);
});
});
it('Check the URL space to verify that the deleted home is no longer available', (done) => {
let urls = [
`/homes/${home.slug}`,
`/homes/${home.slug}/story`,
`/homes/${home.slug}/details`,
`/homes/${home.slug}/contact`
];
let promises = urls.map((url) => {
return new Promise((resolve, reject) => {
request(app)
.get(url)
.expect(404)
.end((err, res) => {
should.not.exist(err, `URL '${url}' should not exist anymore`);
body = res.text;
resolve();
});
});
});
Promise.all(promises)
.then(() => {
done();
})
.catch((err) => {
done(err);
});
});
});
<file_sep>import SourceBuilder from '../../common/sources/Builder';
import HomeListActions from '../actions/HomeListActions';
// let debug = require('debug')('HomeListSource');
export default SourceBuilder.build({
name: 'HomeListSource',
actions: {
base: HomeListActions,
error: HomeListActions.requestFailed
},
methods: {
fetchItems: {
remote: {
method: 'get',
uri: (model, args) => {
let url = '/api/homes';
let filters = [];
// Pass the allowed keys with quick validation
if (typeof args[0] === 'object') {
for (let i in args[0]) {
let v = args[0][i];
switch (i) {
case 'limit':
if (!isNaN(v)) {
filters.push(`limit=${v}`);
}
break;
case 'type':
if (['', 'story', 'buy', 'rent'].indexOf(v) !== -1) {
filters.push(`type=${v}`);
}
break;
case 'story':
filters.push('story=1');
break;
}
}
}
if (filters.length) {
url += `?${filters.join('&')}`;
}
return url;
},
params: null,
response: {
key: 'homes'
}
},
local: null,
actions: {
success: HomeListActions.updateItems
}
}
}
});
<file_sep>import SourceBuilder from '../../common/sources/Builder';
import PageListActions from '../actions/PageListActions';
export default SourceBuilder.build({
name: 'PageListSource',
actions: {
base: PageListActions,
error: PageListActions.requestFailed
},
methods: {
fetchItems: {
remote: {
method: 'get',
uri: '/api/pages',
params: null,
response: {
key: 'pages'
}
},
local: null,
actions: {
success: PageListActions.updateItems
}
},
updateItem: {
remote: {
method: 'put',
uri: (state, args) => {
return `/api/pages/${args[0].uuid}`;
},
params: (state, args) => {
return {
content: args[0]
};
},
response: {
key: 'pages'
}
},
local: null,
actions: {
success: PageListActions.updateItems
}
},
removeItem: {
remote: {
method: 'delete',
uri: (state, args) => {
return `/api/pages/${args[0]}`;
},
params: null,
response: (state, response, args) => {
return Promise.resolve(args[0]);
}
},
local: null,
actions: {
success: PageListActions.removeSuccess
}
}
}
});
<file_sep>import React from 'react';
import { Link } from 'react-router';
// Import widgets
import BigImage from '../../../common/components/Widgets/BigImage';
import ContentBlock from '../../../common/components/Widgets/ContentBlock';
import LargeText from '../../../common/components/Widgets/LargeText';
import Map from '../../../common/components/Widgets/Map';
import Separator from '../../../common/components/Widgets/Separator';
import StoryLayout from '../../../common/components/Layout/StoryLayout';
import { setPageTitle, merge } from '../../../common/Helpers';
let debug = require('../../../common/debugger')('NeighborhoodStory');
export default class NeighborhoodStory extends React.Component {
static propTypes = {
neighborhood: React.PropTypes.object.isRequired
}
componentDidMount() {
if (this.props.neighborhood) {
setPageTitle(this.props.neighborhood.pageTitle);
}
}
componentWillUnmount() {
setPageTitle();
}
getMarkers(homes) {
let markers = [];
for (let home of homes) {
debug('Add', home.title, home);
if (!home.location || !home.location.coordinates) {
continue;
}
markers.push({
location: home.location.coordinates,
title: home.homeTitle,
route: {
to: 'home',
params: {
slug: home.slug
}
}
});
}
return markers;
}
getMap() {
let homes = (this.props.neighborhood.homes.length) ? this.props.neighborhood.homes : [];
let markers = this.getMarkers(homes);
debug('Set markers', markers);
if (!this.props.neighborhood || !this.props.neighborhood.location || !this.props.neighborhood.location.coordinates || !Array.isArray(this.props.neighborhood.location.coordinates)) {
if (this.props.neighborhood.area) {
return (
<Map markers={markers} area={area} />
);
}
return null;
}
if (!homes.length) {
return (
<Map center={this.props.neighborhood.location.coordinates} markers={markers} />
);
}
let area = [];
if (this.props.neighborhood.area) {
area = this.props.neighborhood.area;
}
return (
<Map center={this.props.neighborhood.location.coordinates} markers={markers} area={area}>
{
homes.map((home, index) => {
if (index >= 3) {
return null;
}
return (
<div className='home' key={index}>
<h3>
<Link to='home' params={{slug: home.slug}} className='ellipsis-overflow'>
{home.homeTitle}
</Link>
</h3>
</div>
);
})
}
</Map>
);
}
getBlocks() {
let blocks = [];
let primaryImage = merge({}, this.props.neighborhood.mainImage);
if (this.props.neighborhood.story && this.props.neighborhood.story.blocks.length) {
debug('this.props.neighborhood.story.blocks', this.props.neighborhood.story.blocks);
blocks = [].concat(this.props.neighborhood.story.blocks);
} else {
blocks.push({
template: 'BigImage',
properties: {
image: primaryImage,
title: this.props.neighborhood.title,
marker: {
type: 'marker',
color: 'black',
size: 'large'
}
}
});
if (this.props.neighborhood.images && this.props.neighborhood.images.length > 1) {
blocks.push({
template: 'Gallery',
properties: {
images: this.props.neighborhood.images
}
});
}
if (this.props.neighborhood.description) {
blocks.push({
template: 'ContentBlock',
properties: {
content: this.props.neighborhood.description
}
});
}
}
debug('Use blocks', blocks);
return blocks;
}
renderHomeBlocks() {
if (!this.props.neighborhood.homes || !this.props.neighborhood.homes.length) {
return this.getMap();
}
let secondaryImage = merge({}, this.props.neighborhood.mainImage);
if (this.props.neighborhood.images && typeof this.props.neighborhood.images[1] !== 'undefined') {
secondaryImage = this.props.neighborhood.images[1];
}
let city = 'london';
if (this.props.neighborhood.location.city && this.props.neighborhood.location.city.slug) {
city = this.props.neighborhood.location.city.slug;
}
return (
<div className='neighborhood-home-blocks'>
<ContentBlock className='with-gradient padded'>
<p className='call-to-action'>
<Link className='button' to='neighborhoodViewHomes' params={{city: city, neighborhood: this.props.neighborhood.slug}}>Show homes</Link>
</p>
</ContentBlock>
<BigImage image={secondaryImage}>
<LargeText>
<h2>Homes of {this.props.neighborhood.title}</h2>
</LargeText>
</BigImage>
<Separator icon='apartment' />
{this.getMap()}
<ContentBlock align='center'>
<Link className='button' to='neighborhoodViewHomes' params={{city: city, neighborhood: this.props.neighborhood.slug}}>Show more homes</Link>
</ContentBlock>
</div>
);
}
render() {
debug('got neighborhood', this.props.neighborhood);
let blocks = this.getBlocks();
return (
<div className='neighborhood-story'>
<StoryLayout blocks={blocks} />
{this.renderHomeBlocks()}
</div>
);
}
}
<file_sep>import React from 'react';
import classNames from 'classnames';
import DOMManipulator from '../../DOMManipulator';
let debug = require('../../../common/debugger')('Map');
export default class Map extends React.Component {
static propTypes = {
center: React.PropTypes.array,
label: React.PropTypes.string,
zoom: React.PropTypes.number,
minZoom: React.PropTypes.number,
maxZoom: React.PropTypes.number,
markers: React.PropTypes.array,
children: React.PropTypes.oneOfType([
React.PropTypes.object,
React.PropTypes.array
]),
context: React.PropTypes.object,
lat: React.PropTypes.number,
lng: React.PropTypes.number,
className: React.PropTypes.string,
area: React.PropTypes.array
}
static contextTypes = {
router: React.PropTypes.func
};
static defaultProps = {
zoom: 10,
minZoom: 6,
maxZoom: 20,
markers: [],
className: null,
area: null
};
constructor() {
super();
this.resize = this.resize.bind(this);
this.initMaps = this.initMaps.bind(this);
}
componentDidMount() {
this.resize();
this.map = null;
this.area = null;
this.mapContainer = new DOMManipulator(this.refs.map);
this.loadGoogleMaps();
window.addEventListener('resize', this.resize);
}
componentWillUnmount() {
window.removeEventListener('resize', this.resize);
}
loadGoogleMaps() {
if (typeof google !== 'undefined' && typeof google.maps !== 'undefined') {
this.initMaps();
return;
}
let s = document.createElement('script');
// Homehapp Google API key
let key = '<KEY>';
s.src = `https://maps.googleapis.com/maps/api/js?key=${key}`;
s.addEventListener('load', this.initMaps);
document.getElementsByTagName('head')[0].appendChild(s);
}
initMaps() {
if (this.map) {
return null;
}
let center = this.getCenter();
let options = {
disableDefaultUI: true,
zoomControl: true,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.SMALL,
position: google.maps.ControlPosition.RIGHT_CENTER
},
center: {
lat: center[0],
lng: center[1]
},
zoom: this.props.zoom,
minZoom: this.props.minZoom,
maxZoom: this.props.maxZoom,
scrollWheel: false
};
this.map = new google.maps.Map(this.mapContainer.node, options);
this.setInitialMarkers();
this.setArea();
}
setArea() {
if (!this.props.area || !this.props.area.length) {
return null;
}
// Delete the old map
if (this.area) {
this.area.setMap(null);
}
this.area = new google.maps.Polygon({
paths: this.props.area,
strokeColor: '#9dc1fd',
fillColor: '#9dc1fd',
strokeOpacity: 0.8,
strokeWeight: 1,
fillOpacity: 0.2
});
this.area.setMap(this.map);
this.fitToBounds();
}
fitToBounds() {
if (!this.props.area || !this.props.area.length) {
return false;
}
let bounds = new google.maps.LatLngBounds();
for (let pos of this.props.area) {
bounds.extend(new google.maps.LatLng(pos.lat, pos.lng));
}
this.map.fitBounds(bounds);
return true;
}
setInitialMarkers() {
this.setMarkers(this.props.markers);
}
setMarkers(markers) {
if (!markers || !markers.length) {
return null;
}
let click = function() {
if (this.href) {
window.location.href = this.href;
}
};
markers.map((markerData) => {
if (!markerData.location || markerData.location.length < 2) {
return null;
}
// Type cast
let lat = Number(markerData.location[0]);
let lng = Number(markerData.location[1]);
debug('lat', lat, 'lng', lng);
if (isNaN(lat) || isNaN(lng) || !lat || !lng) {
debug('markerData.location failed type check, skip', markerData);
return null;
}
let marker = new google.maps.Marker({
position: {
lat: lat,
lng: lng
},
href: this.markerUrl(markerData),
title: markerData.title || '',
icon: this.getMarkerImage()
});
marker.setMap(this.map);
marker.addListener('click', click);
});
}
getMarkerImage() {
let width = 46;
let height = 63;
return {
url: 'https://res.cloudinary.com/homehapp/image/upload/v1443442957/site/images/icons/place-marker.svg',
size: new google.maps.Size(width, height),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(width / 2, height)
};
}
markerUrl(marker) {
if (typeof marker.href === 'string') {
return marker.href;
}
if (typeof marker.route === 'object') {
let params = marker.route.params || {};
return this.context.router.makeHref(marker.route.to, params);
}
return null;
}
resize() {
let map = new DOMManipulator(this.refs.map);
let content = (this.refs.content) ? new DOMManipulator(this.refs.content) : null;
let container = new DOMManipulator(this.refs.container);
let width = Math.floor(container.parent().width());
if (container.css('display') === 'table') {
width = Math.floor(width / 2) - 60;
}
// Maximum size for the map
let mapSize = 600;
map.width(Math.min(mapSize, width));
map.height(Math.min(mapSize, width));
if (content) {
content.width(width);
}
}
// Get a plain arithmetic average for the center position for a set of
// markers
getCenter() {
let defaultCenter = [51.5072, 0.1275];
if (this.props.center && this.props.center[0] && this.props.center[1]) {
debug('Use defined center', this.props.center);
return this.props.center;
}
if (this.props.lat && this.props.lng) {
return [this.props.lat, this.props.lng];
}
let lat = 0;
let lng = 0;
// Show London if nothing else is available
if (!this.props.markers || !this.props.markers.length) {
debug('Use default center', defaultCenter);
return defaultCenter;
}
let count = 0;
for (let marker of this.props.markers) {
debug('marker', marker);
if (typeof marker.location !== 'undefined' && marker.location[0] && marker.location[1]) {
lat += Number(marker.location[0]);
lng += Number(marker.location[1]);
} else if (typeof marker.position !== 'undefined' && marker.position.lat && marker.position.lng) {
lat += Number(marker.position.lat);
lng += Number(marker.position.lng);
} else {
continue;
}
count++;
}
if (!lat || !lng || !count) {
debug('Use defaultCenter', defaultCenter, lat, lng);
return defaultCenter;
}
debug('Use calculated center', lat / count, lng / count);
return [lat / count, lng / count];
}
render() {
if (this.props.context && !this.context) {
this.context = this.props.context;
}
let classes = [
'widget',
'map'
];
debug('Map children', this.props.children);
let auxContent = null;
if (this.props.children) {
auxContent = (
<div className='aux-content'>
<div className='content-wrapper' ref='content'>
{this.props.children}
</div>
</div>
);
} else {
classes.push('no-aux-content');
}
if (this.props.className) {
classes.push(this.props.className);
}
return (
<div className={classNames(classes)}>
<div className='width-wrapper' ref='container'>
<div className='map-content'>
<div className='map-wrapper' ref='map'></div>
</div>
{auxContent}
</div>
</div>
);
}
}
<file_sep>import React from 'react';
import DOMManipulator from '../../DOMManipulator';
export default class Columns extends React.Component {
static propTypes = {
max: React.PropTypes.number,
cols: React.PropTypes.number.isRequired,
children: React.PropTypes.oneOfType([
React.PropTypes.object,
React.PropTypes.array
]),
align: React.PropTypes.string,
valign: React.PropTypes.string,
className: React.PropTypes.string
}
static defaultProps = {
max: 1000,
align: 'left',
valign: 'top',
className: null
}
componentDidMount() {
let node = new DOMManipulator(this.refs.container);
let rows = node.getByClass('row');
for (let i = 0; i < rows.length; i++) {
let columns = rows[i].children();
for (let n = 0; n < columns.length; n++) {
let children = columns[n].children();
this.copyClass(children, columns[n]);
}
}
}
copyClass(children, column) {
if (!children.length) {
return null;
}
let cls = String(children[0].node.className).match(/(span[0-9+])/);
if (cls) {
column.addClass(cls[1]);
}
}
renderChildren() {
let cols = Math.max(1, Math.round(this.props.cols));
let last = Math.max(1, Math.min(this.props.children.length, this.props.max));
let rows = [];
let row = [];
// Create individual cells of each child found in the column wrapper
React.Children.map(this.props.children, function(child, index) {
if (index >= last) {
return null;
}
let classes = [];
classes.push(`cols-${cols}`);
if (index % cols === 0) {
classes.push('row-start');
} else if (index % cols === cols - 1) {
classes.push('row-end');
}
if (!index) {
classes.push('first');
}
// Store the child element, i.e. cell in the current row for later use
row.push((
<div className={classes.join(' ')} key={index}>
{child}
</div>
));
// When the row is full, store it for later use and initialize a new one
if (index % cols === cols - 1 || index === last - 1) {
rows.push(row);
row = [];
}
return null;
});
return (
<div className='columns-container'>
{
// Wrap cells into rows
rows.map((r, i) => {
return (
<div className='row' key={i}>
{
r.map((item) => {
return item;
})
}
</div>
);
})
}
</div>
);
}
render() {
let classes = ['columns', 'widget', 'clearfix'];
if (this.props.className) {
classes.push(this.props.className);
}
return (
<div className={classes.join(' ')} data-align={this.props.align} data-valign={this.props.valign} ref='container'>
{this.renderChildren()}
</div>
);
}
}
<file_sep>/**
* @apiDefine AuthSuccessResponse
* @apiVersion 1.0.0
*
* @apiSuccess {Object} session
* @apiSuccess {String} session.token Authentication token for the user
* @apiSuccess {Number} session.expiresIn Expiration time in seconds
* @apiSuccess {Datetime} session.expiresAt ISO-8601 Formatted Expiration Datetime
* @apiSuccess {Object} session.user <a href="#api-Users-UserData">User</a> object
*/
/**
* @api {post} /api/auth/login Login the Mobile User
* @apiVersion 1.0.0
* @apiName UserLogin
* @apiGroup Authentication
*
* @apiUse MobileRequestHeadersUnauthenticated
* @apiParam {String} service Name of the external service. Enum[facebook, google]
* @apiParam {Object} user Details of the user
* @apiParam {String} user.id User's Id from the service
* @apiParam {String} user.email User's email from the service
* @apiParam {String} user.token User's token from the service
* @apiParam {String} [user.displayName] User's full name from the service
* @apiParam {String} [user.firstname] User's first name from the service
* @apiParam {String} [user.lastname] User's last name from the service
* @apiUse AuthSuccessResponse
* @apiUse UserSuccessResponseJSON
* @apiUse HomeSuccessResponseJSON
*
* @apiSuccessExample Success-Response
* HTTP/1.1 200 OK
* {
* "status": "ok",
* "session": {
* "token": "...",
* "expiresIn": ...,
* "expiresAt": '...',
* "user": {...}
* }
* }
* }
*
* @apiError (400) BadRequest Invalid request body, missing parameters.
* @apiError (403) Forbidden User account has been disabled
* @apiErrorExample Error-Response:
* HTTP/1.1 403 Forbidden
* {
* 'status': 'failed',
* 'error': 'account disabled'
* }
*/
/**
* @api {post} /api/auth/register/push Register/Unregister Mobile Client for Push
* @apiVersion 1.0.0
* @apiName PushRegister
* @apiGroup Authentication
*
* @apiDescription When given a valid pushToken, registers the device to receive push notifications. Otherwise unregisters the device.
*
* @apiPermission authenticated
* @apiUse MobileRequestHeadersAuthenticated
* @apiParam {String} pushToken Push token for mobile client
*
* @apiSuccessExample {json} Success-Response:
* HTTP/1.1 200 OK
* {
* 'status': 'ok'
* }
*
* @apiError (400) BadRequest Invalid request body, missing parameters.
* @apiError (403) Forbidden User account has been disabled
* @apiErrorExample Error-Response:
* HTTP/1.1 403 Forbidden
* {
* 'status': 'failed',
* 'error': 'account disabled'
* }
*/
/**
* @api {get} /api/auth/check Check session validity
* @apiVersion 1.0.0
* @apiName CheckSessionValidity
* @apiGroup Authentication
*
* @apiDescription Allows for checking if the session is valid
*
* @apiPermission authenticated
* @apiUse MobileRequestHeadersAuthenticated
*
* @apiSuccessExample {json} Success-Response:
* HTTP/1.1 200 OK
* {
* 'status': 'ok'
* }
*
* @apiError (403) Forbidden User account has been disabled
* @apiErrorExample Error-Response:
* HTTP/1.1 403 Forbidden
* {
* 'status': 'failed',
* 'error': 'account disabled'
* }
*/
/**
* @apiDefine HomeSuccessResponse
* @apiVersion 1.0.0
*
* @apiSuccess {String} id Uuid of the home
* @apiSuccess {String} slug URL Slug of the Home
* @apiSuccess {Boolean} enabled Switch for enabling/disabling the public viewing of the home
* @apiSuccess {String} title Home title
* @apiSuccess {String} announcementType Home announcement type. Enum ['buy', 'rent', 'story']
* @apiSuccess {String} description Description of the Home
* @apiSuccess {Object} details Home details
* @apiSuccess {Number} details.area Area in square meters
* @apiSuccess {String} details.freeform Freeform description
* @apiSuccess {Object} location Location details
* @apiSuccess {Object} location.address Location address details
* @apiSuccess {String} location.address.street Street address
* @apiSuccess {String} location.address.apartment Apartment
* @apiSuccess {String} location.address.city City
* @apiSuccess {String} location.address.zipcode zipcode
* @apiSuccess {String} location.address.country Country
* @apiSuccess {Array} location.coordinates Map coordinates. [LAT, LON]
* @apiSuccess {Object} location.neighborhood Neighborhood object TODO: Define
* @apiSuccess {Object} mainImage Main <a href="#api-Shared-Images">Image</a> of the home
* @apiSuccess {Array} epc EPC <a href="#api-Shared-Images">Image</a> or PDF
* @apiSuccess {Array} images Home <a href="#api-Shared-Images">Images</a>
* @apiSuccess {Array} floorplans An array of <a href="#api-Shared-Images">Images</a>, dedicated to floorplans
* @apiSuccess {Array} brochures An array of <a href="#api-Shared-Images">Images</a>, dedicated to brochures
* @apiSuccess {Object} story Home story blocks
* @apiSuccess {Boolean} story.enabled Switch to determine if the story is public
* @apiSuccess {Array} story.blocks An array of <a href="#api-Shared-StoryBlock">StoryBlocks</a>
* @apiSuccess {Object} neighborhoodStory Neighborhood story blocks
* @apiSuccess {Boolean} neighborhoodStory.enabled Switch to determine if the story is public
* @apiSuccess {Array} neighborhoodStory.blocks An array of <a href="#api-Shared-StoryBlock">StoryBlocks</a>
* @apiSuccess {String} createdBy UUID of the <a href="#api-Users-UserData">User</a> that has created the home
* @apiSuccess {String} updatedBy UUID of the <a href="#api-Users-UserData">User</a> that has updated the home
* @apiSuccess {Datetime} createdAt ISO-8601 Formatted Creation Datetime
* @apiSuccess {Datetime} updatedAt ISO-8601 Formatted Updation Datetime
* @apiSuccess {Integer} createdAtTS EPOCH formatted timestamp of the creation time
* @apiSuccess {Integer} updatedAtTS EPOCH formatted timestamp of the updation time
*/
/**
* @apiDefine HomeSuccessResponseJSON
* @apiVersion 1.0.0
*
* @apiSuccessExample {json} JSON serialization of the home
* {
* "id": "00000000-0000-0000-0000-000000000000",
* "slug": "...",
* "enabled": true,
* "title": "Home sweet home",
* "announcementType": "story",
* "description": "I am an example",
* "details": {
* "area": ...,
* "freeform": "...",
* },
* "location": {
* "address": "221B Baker Street",
* "city": "Exampleby",
* "country": "Great Britain",
* "coordinates": [
* 51.4321,
* -0.1234
* ],
* "neighborhood": "00000000-0000-0000-0000-000000000000"
* },
* "mainImage": {
* "url": "https:*res.cloudinary.com/homehapp/.../example.jpg",
* "alt": "View towards the sunset",
* "width": 4200,
* "height": 2500
* },
* "images": [
* {
* "url": "https:*res.cloudinary.com/homehapp/.../example.jpg",
* "alt": "View towards the sunset",
* "width": 4200,
* "height": 2500
* },
* {
* ...
* }
* ],
* "epc": [
* {
* "url": "https:*res.cloudinary.com/homehapp/.../example.jpg",
* "alt": "View towards the sunset",
* "width": 4200,
* "height": 2500
* },
* {
* ...
* }
* ],
* "floorplans": [
* {
* "url": "https:*res.cloudinary.com/homehapp/.../example.jpg",
* "alt": "View towards the sunset",
* "width": 4200,
* "height": 2500
* },
* {
* ...
* }
* ],
* "brochures": [
* {
* "url": "https:*res.cloudinary.com/homehapp/.../example.jpg",
* "alt": "View towards the sunset",
* "width": 4200,
* "height": 2500
* },
* {
* ...
* }
* ],
* "story": {
* "enabled": true,
* "blocks": [
* {
* "template": "BigImage",
* "properties": {
* "image": {
* "url": "https:*res.cloudinary.com/homehapp/.../example.jpg",
* "alt": "View towards the sunset",
* "width": 4200,
* "height": 2500
* },
* "title": "A great spectacle",
* "description": "The evening routines of the Sun"
* }
* }
* ]
* },
* "neighborhoodStory": {
* "enabled": true,
* "blocks": [
* {
* "template": "BigImage",
* "properties": {
* "image": {
* "url": "https:*res.cloudinary.com/homehapp/.../example.jpg",
* "alt": "View towards the sunset",
* "width": 4200,
* "height": 2500
* },
* "title": "A great spectacle",
* "description": "The evening routines of the Sun"
* }
* }
* ]
* },
* "createdBy": "00000000-0000-0000-0000-000000000000",
* "updatedBy": "00000000-0000-0000-0000-000000000000",
* "createdAt": "2016-01-13T14:38:01.0000Z",
* "updatedAt": "2016-01-13T14:38:01.0000Z",
* "createdAtTS": 1452695955,
* "updatedAtTS": 1452695955
* }
*/
/**
* @apiDefine HomeBody
* @apiVersion 1.0.0
*
* @apiParam {Object} home Home object
* @apiParam {Boolean} [home.enabled] Switch for enabling/disabling the public viewing of the home
* @apiParam {String} [home.title] Title of the Home
* @apiParam {String} [home.announcementType] Home announcement type. Enum ['buy', 'rent', 'story']
* @apiParam {String} home.description Textual description of the Home
* @apiParam {Object} [home.details] Location details
* @apiParam {Number} [home.details.area] Numeric surface area
* @apiParam {Object} [home.location.address] Location address details
* @apiParam {String} [home.location.address.street] Street address
* @apiParam {String} [home.location.address.apartment] Apartment
* @apiParam {String} [home.location.address.city] City
* @apiParam {String} [home.location.address.zipcode] zipcode
* @apiParam {String} [home.location.address.country] Country
* @apiParam {Array} [home.location.coordinates] Map coordinates. [LAT, LON]
* @apiParam {String} [home.location.neighborhood] UUID of the Neighborhood
* @apiParam {Object} [home.costs] Costs details
* @apiParam {String} [home.properties] Home properties, i.e. list of
* @apiParam {String} [home.costs.currency='GBP'] Currency. Enum ['EUR', 'GBP', 'USD']
* @apiParam {Number} [home.costs.sellingPrice] Selling price
* @apiParam {Number} [home.costs.rentalPrice] Rental price
* @apiParam {Number} [home.costs.councilTax] Council tax
* @apiParam {Array} [home.images] An array of <a href="#api-Shared-Images">Images</a>
* @apiParam {Array} [home.epc] An array of <a href="#api-Shared-Images">Images</a>, dedicated to EPC
* @apiParam {Array} [home.floorplans] An array of <a href="#api-Shared-Images">Images</a>, dedicated to floorplans. Set the floorplan name as image.alt for each image.
* @apiParam {Array} [home.brochures] An array of <a href="#api-Shared-Images">Images</a>, dedicated to brochures. Set the printable brochure name as image.alt for each image.
* @apiParam {Object} [home.story] Story block container object
* @apiParam {Boolean} [home.story.enabled=false] Switch to determine if the story is public
* @apiParam {Array} [home.story.blocks] An array of <a href="#api-Shared-StoryBlock">StoryBlocks</a>
* @apiParam {Object} [home.neighborhoodStory] Story block container object
* @apiParam {Boolean} [home.neighborhoodStory.enabled=false] Switch to determine if the story is public
* @apiParam {Array} [home.neighborhoodStory.blocks] An array of <a href="#api-Shared-StoryBlock">StoryBlocks</a>
*/
/**
* @api {any} /api/* Home Details
* @apiVersion 1.0.0
* @apiName Home details
* @apiGroup Homes
*
* @apiDescription Data for each home object passed from the backend contains the same set of information
*
* @apiUse MobileRequestHeaders
* @apiUse HomeSuccessResponse
* @apiUse HomeSuccessResponseJSON
*/
/**
* @api {get} /api/homes Fetch All Homes
* @apiVersion 1.0.0
* @apiName GetHomes
* @apiGroup Homes
*
* @apiDescription Route for fetching Homes
*
* @apiUse MobileRequestHeaders
* @apiUse HomeSuccessResponse
* @apiUse HomeSuccessResponseJSON
*
* @apiParam (Query) {String} [sort=desc] Sort order. Enum: ['asc', 'desc']
* @apiParam (Query) {String} [sortBy=updatedAt] Which field to use for sorting
* @apiParam (Query) {Number} [limit=20] How many items to fetch
* @apiParam (Query) {Number} [skip] How many items to skip
*
* @apiSuccessExample {json} Success-Response:
* HTTP/1.1 200 OK
* {
* "status": "ok",
* "homes": [...]
* }
*
*/
/**
* @api {get} /api/homes/:uuid Get home by id
* @apiVersion 1.0.0
* @apiName GetHomeById
* @apiGroup Homes
* @apiDescription Fetch Single Home
*
* @apiParam {String} id Home's internal id
*
* @apiUse MobileRequestHeaders
* @apiUse HomeSuccessResponse
* @apiUse HomeSuccessResponseJSON
*
* @apiSuccessExample {json} Success-Response:
* HTTP/1.1 200 OK
* {
* "status": "ok",
* "home": {...}
* }
*
* @apiError (404) NotFound Home with given id was not found
* @apiErrorExample Error-Response:
* HTTP/1.1 404 Not Found
* {
* "status": "failed",
* "error": "model not found"
* }
*/
/**
* @api {put} /api/homes/:id Update home
* @apiVersion 1.0.0
* @apiName UpdateHome
* @apiGroup Homes
* @apiDescription Update home by uuid
*
* @apiUse MobileRequestHeaders
* @apiUse HomeBody
* @apiUse HomeSuccessResponse
* @apiUse HomeSuccessResponseJSON
*
* @apiSuccessExample {json} Success-Response:
* HTTP/1.1 200 OK
* {
* "status": "ok",
* "home": {...}
* }
*
*/
/**
* @api {post} /api/homes Create a home
* @apiVersion 1.0.0
* @apiName CreateHome
* @apiGroup Homes
*
* @apiUse MobileRequestHeaders
* @apiUse HomeBody
* @apiUse HomeSuccessResponse
* @apiUse HomeSuccessResponseJSON
*
* @apiSuccessExample {json} Success-Response:
* HTTP/1.1 200 OK
* {
* "status": "ok",
* "home": {...}
* }
*/
/**
* @api {delete} /api/homes/:id Delete home
* @apiVersion 1.0.0
* @apiName DeleteHome
* @apiGroup Homes
* @apiDescription Deletes the given home
*
* @apiParam {String} id Home's internal id
*
* @apiUse MobileRequestHeaders
* @apiUse HomeSuccessResponse
* @apiUse HomeSuccessResponseJSON
*
* @apiSuccessExample {json} Success-Response:
* HTTP/1.1 200 OK
* {
* "status": "deleted",
* "home": {...}
* }
*/
/**
* @apiDefine MobileRequestHeaders
* @apiVersion 1.0.0
*
* @apiHeader {String} X-Homehapp-Api-Key Api key for this project
* @apiHeader {String} X-Homehapp-Client Client identifier. In format: platform/manufacturer;deviceType;model;OS version/deviceID/deviceLanguageCode
* @apiHeader {String} [X-Homehapp-Auth-Token] Unique session token for logged in user
* @apiHeader {String} [X-Homehapp-Api-Version=0] Version of the API in use
*
* @apiHeaderExample {json} Required headers with authentication:
* {
* "X-Homehapp-Api-Key": "API KEY",
* "X-Homehapp-Client": "IOS/Apple;iPhone Simulator;x86_64;8.4.0/C9853654-3EBF-4BB5-9039-23DD0404A968/en",
* "X-Homehapp-Auth-Token": "USER TOKEN (IF APPLICAPLE)"
* }
*
* @apiHeaderExample {json} Required headers without authentication:
* {
* "X-Homehapp-Api-Key": "API KEY",
* "X-Homehapp-Client": "IOS/Apple;iPhone Simulator;x86_64;8.4.0/C9853654-3EBF-4BB5-9039-23DD0404A968/en"
* }
*/
/**
* @apiDefine MobileRequestHeadersUnauthenticated
* @apiVersion 1.0.0
*
* @apiHeader {String} X-Homehapp-Api-Key Api key for this project
* @apiHeader {String} X-Homehapp-Client Client identifier. In format: platform/manufacturer;deviceType;model;OS version/deviceID/deviceLanguageCode
* @apiHeader {String} [X-Homehapp-Api-Version=0] Version of the API in use
*
* @apiHeaderExample {json} Required headers:
* {
* "X-Homehapp-Api-Key": "API KEY",
* "X-Homehapp-Client": "IOS/Apple;iPhone Simulator;x86_64;8.4.0/C9853654-3EBF-4BB5-9039-23DD0404A968/en"
* }
*/
/**
* @apiDefine MobileRequestHeadersAuthenticated
* @apiVersion 1.0.0
*
* @apiHeader {String} X-Homehapp-Api-Key Api key for this project
* @apiHeader {String} X-Homehapp-Client Client identifier. In format: platform/manufacturer;deviceType;model;OS version/deviceID/deviceLanguageCode
* @apiHeader {String} X-Homehapp-Auth-Token Unique session token for logged in user
* @apiHeader {String} [X-Homehapp-Api-Version=0] Version of the API in use
*
* @apiHeaderExample {json} Required headers:
* {
* "X-Homehapp-Api-Key": "API KEY",
* "X-Homehapp-Client": "IOS/Apple;iPhone Simulator;x86_64;8.4.0/C9853654-3EBF-4BB5-9039-23DD0404A968/en",
* "X-Homehapp-Auth-Token": "USER TOKEN (IF APPLICAPLE)"
* }
*/
/**
* @apiDefine NeighborhoodSuccessResponse
* @apiVersion 1.0.0
*
* @apiSuccess {String} id Uuid of the Neighborhood
* @apiSuccess {String} title Title of the Neighborhood
* @apiSuccess {Datetime} createdAt ISO-8601 Formatted Creation Datetime
* @apiSuccess {Datetime} updatedAt ISO-8601 Formatted Updation Datetime
* @apiSuccess {Integer} createdAtTS EPOCH formatted timestamp of the creation time
* @apiSuccess {Integer} updatedAtTS EPOCH formatted timestamp of the updation time
*
*/
/**
* @apiDefine NeighborhoodBody
* @apiVersion 1.0.0
*
* @apiParam {Object} neighborhood Neighborhood object
* @apiParam {String} neighborhood.title Title of the Neighborhood
*
*/
/**
* @api {get} /api/neighborhoods/:city Fetch All Neighborhood from city
* @apiVersion 1.0.0
* @apiName GetNeighborhoods
* @apiGroup Neighborhoods
*
* @apiDescription Route for fetching Neighborhoods by city
*
* @apiUse MobileRequestHeaders
* @apiUse NeighborhoodSuccessResponse
*
* @apiSuccessExample {json} Success-Response:
* HTTP/1.1 200 OK
* {
* "status": "ok",
* "neighborhoods": [...]
* }
*
*/
/**
* @api {get} /api/neighborhoods/:city/:neighborhood Fetch City Neighborhood by slug
* @apiVersion 1.0.0
* @apiName GetNeighborhoodBySlug
* @apiGroup Neighborhoods
*
* @apiDescription Route for fetching Neighborhood by city and slug
*
* @apiUse MobileRequestHeaders
* @apiUse NeighborhoodSuccessResponse
*
* @apiSuccessExample {json} Success-Response:
* HTTP/1.1 200 OK
* {
* 'status': 'ok',
* 'neighborhood': {...}
* }
*
*/
/**
* @api {any} /api/* All story blocks
* @apiVersion 1.0.0
* @apiName All StoryBlocks
* @apiGroup StoryBlocks
*
* @apiDescription Story block definitions for both setting and getting
*
* @apiParam (BigImage) {string='BigImage'} template Template name for big image widget
* @apiParam (BigImage) {object} properties Story block properties
* @apiParam (BigImage) {string} properties.title Story block title
* @apiParam (BigImage) {string} properties.description Story block description
* @apiParam (BigImage) {string='left', 'center', 'right'} [properties.align='center'] Horizontal position of the textual content
* @apiParam (BigImage) {string='top', 'middle', 'bottom'} [properties.valign='middle'] Vertical position of the textual content
* @apiParam (BigImage) {object} properties.image <a href="#">Image object</a>
*
* @apiParam (BigVideo) {string='BigVideo'} template Template name for BigVideo widget
* @apiParam (BigVideo) {object} properties Story block properties
* @apiParam (BigVideo) {string} properties.title Story block title
* @apiParam (BigVideo) {string} properties.description Story block description
* @apiParam (BigVideo) {string='left', 'center', 'right'} [properties.align='center'] Horizontal position of the textual content
* @apiParam (BigVideo) {string='top', 'middle', 'bottom'} [properties.valign='middle'] Vertical position of the textual content
* @apiParam (BigVideo) {object} properties.video Video object
* @apiParam (BigVideo) {string} properties.video.url Video URL
* @apiParam (BigVideo) {string} properties.video.alt Alt text or brief description
* @apiParam (BigVideo) {number} [properties.video.width] Video width
* @apiParam (BigVideo) {number} [properties.video.height] Video height
* @apiParam (BigVideo) {boolean} [properties.video.fixed] Flag for fixing the video position for parallax scrolling
* @apiParam (BigVideo) {string='left', 'center', 'right'} [properties.video.align='center'] Horizontal position of the video
* @apiParam (BigVideo) {string='top', 'middle', 'bottom'} [properties.video.valign='middle'] Vertical position of the video
*
* @apiParam (ContentBlock) {string='ContentBlock'} template Template name for ContentBlock widget
* @apiParam (ContentBlock) {object} properties Story block properties
* @apiParam (ContentBlock) {string} properties.title Story block title
* @apiParam (ContentBlock) {string} properties.content Story block content
* @apiParam (ContentBlock) {string='left', 'center', 'right'} [properties.align='left'] Horizontal position of the content
*
* @apiParam (ContentImage) {string='ContentImage'} template Template name for big image widget
* @apiParam (ContentImage) {object} properties Story block properties
* @apiParam (ContentImage) {string} properties.title Story block title
* @apiParam (ContentImage) {string} properties.content Story block content
* @apiParam (ContentImage) {string='left', 'right'} [properties.imageAlign='left'] On which side the image should be related to the text
*
* @apiParam (Gallery) {string='Gallery'} template Template name for Gallery widget
* @apiParam (Gallery) {object} properties Story block properties
* @apiParam (Gallery) {Array} [properties.images] An array of <a href="#api-Shared-Images">Images</a>
*/
/**
* @api {any} /api/* Images
* @apiVersion 1.0.0
* @apiName Images
* @apiGroup Shared
*
* @apiDescription Every Image uses the following definition
*
* @apiParam {string} url Image URL
* @apiParam {string} alt Alt text or brief description
* @apiParam {number} [width] Image width
* @apiParam {number} [height] Image height
* @apiParam {number} [aspectRatio] Aspect ratio
* @apiParam {boolean} [fixed] Flag for fixing the image position for parallax scrolling
* @apiParam {string='left', 'center', 'right'} [align='center'] Horizontal position of the image
* @apiParam {string='top', 'middle', 'bottom'} [valign='middle'] Vertical position of the image
*/
/**
* @apiDefine UserSuccessResponse
* @apiVersion 1.0.0
*
* @apiSuccess {Object} user User details
* @apiSuccess {String} user.id Internal Id of the user
* @apiSuccess {String} user.email User's email
* @apiSuccess {String} user.displayName User's fullname
* @apiSuccess {String} user.firstname User's firstname
* @apiSuccess {String} user.lastname User's lastname
* @apiSuccess {Object} user.profileImage User's profile image as an <a href="#api-Shared-Images">Image</a> object
* @apiSuccess {Object} user.contact User's contact information
* @apiSuccess {Object} user.contact.address Address information
* @apiSuccess {String} user.contact.address.street User's street address (only for the authenticated user)
* @apiSuccess {String} user.contact.address.city User's city
* @apiSuccess {String} user.contact.address.zipcode User's post office code
* @apiSuccess {String} user.contact.address.country User's country
* @apiSuccess {String} user.contact.phone User's phone number
* @apiSuccess {Object} user.home User's <a href="#api-Homes-Home_details">Home</a>
*/
/**
* @apiDefine UserSuccessResponseJSON
* @apiVersion 1.0.0
*
* @apiSuccessExample {json} JSON serialization of the user
* "user": {
* "id": "...",
* "email": "...",
* "displayName": "...",
* "firstname": "...",
* "lastname": "...",
* "profileImage": {
* "url": "...",
* "alt": "...",
* "width": ...,
* "height": ...
* },
* "contact": {
* "address": {
* "street": "...",
* "city": "...",
* "zipcode": "...",
* "country": "..."
* },
* "phone": "..."
* },
* "home": {...}
* }
*/
/**
* @apiDefine UserBody
* @apiVersion 1.0.0
*
* @apiParam {String} [user.email] User's email address
* @apiParam {String} [user.firstname] User's firstname
* @apiParam {String} [user.lastname] User's lastname
* @apiParam {Object} [user.profileImage] User's profile <a href="#api-Shared-Images">Image</a>
* @apiParam {Object} [user.contact] User's contact information
* @apiParam {Object} [user.contact.address] User's address information
* @apiParam {String} [user.contact.address.street] User's street address
* @apiParam {String} [user.contact.address.city] User's street address
* @apiParam {String} [user.contact.address.zipcode] User's street address
* @apiParam {String} [user.contact.address.country] User's street address
* @apiParam {String} [user.contact.address] User's street address
*/
/**
* @api {any} /api/* User details
* @apiVersion 1.0.0
* @apiName UserData
* @apiGroup Users
*
* @apiDescription User details for each response that has the user object contains the same set of data
* @apiUse UserSuccessResponse
* @apiUse UserSuccessResponseJSON
*/
/**
* @api {put} /api/auth/user Update user details
* @apiVersion 1.0.0
* @apiName UpdateUser
* @apiGroup Users
*
* @apiDescription Update user details
*
* @apiPermission authenticated
* @apiUse MobileRequestHeadersAuthenticated
* @apiUse UserSuccessResponse
* @apiUse UserSuccessResponseJSON
* @apiUse UserBody
*
* @apiError (400) BadRequest Invalid request body, missing parameters.
* @apiError (403) Forbidden User account has been disabled
* @apiErrorExample Error-Response:
* HTTP/1.1 403 Forbidden
* {
* "status": "failed",
* "error": "account disabled"
* }
*/
<file_sep>import {loadCommonPlugins, commonJsonTransform, getImageSchema, getStoryBlockSchema, getMainImage, populateMetadata} from './common';
exports.loadSchemas = function (mongoose, next) {
let Schema = mongoose.Schema;
let schemas = {};
schemas.NeighborhoodStoryBlock = getStoryBlockSchema(Schema);
schemas.NeighborhoodImage = getImageSchema(Schema);
schemas.Neighborhood = new Schema(populateMetadata({
uuid: {
type: String,
index: true,
unique: true
},
slug: {
type: String,
index: true,
required: true,
unique: true
},
// Details
title: {
type: String,
default: ''
},
enabled: {
type: Boolean,
default: false
},
aliases: {
type: [String],
default: []
},
description: {
type: String,
default: ''
},
homes: {
type: [],
default: null
},
location: {
borough: {
type: String,
default: null
},
postCodes: {
type: [String],
default: []
},
postOffice: {
type: String,
default: null
},
city: {
type: mongoose.Schema.Types.ObjectId,
ref: 'City',
index: true
},
coordinates: {
type: [Number],
default: [],
index: '2dsphere'
}
},
area: {
type: [],
default: []
},
// Story
story: {
enabled: {
type: Boolean,
default: false
},
blocks: [schemas.NeighborhoodStoryBlock]
},
images: [schemas.NeighborhoodImage],
// Flags
visible: {
type: Boolean,
index: true,
default: true
}
}));
schemas.Neighborhood.virtual('pageTitle').get(function getPageTitle() {
let title = [this.title];
if (this.location.city) {
title.push(this.location.city.title);
}
return title.join(' | ');
});
schemas.Neighborhood.statics.editableFields = function editableFIelds() {
return [
'title', 'description', 'location', 'images', 'story', 'visible',
'metadata', 'enabled', 'area'
];
};
schemas.Neighborhood.virtual('mainImage').get(function mainImage() {
// Placeholder
let placeholder = {
url: 'https://res.cloudinary.com/homehapp/image/upload/v1439564093/london-view.jpg',
alt: 'A view over London',
width: 4828,
height: 3084,
aspectRatio: 4828 / 3084
};
return getMainImage(this, placeholder);
});
schemas.Neighborhood.virtual('allImages').get(function allImages() {
let images = this.images || [];
// @TODO: collect all images
return images;
});
Object.keys(schemas).forEach((name) => {
loadCommonPlugins(schemas[name], name, mongoose);
schemas[name].options.toJSON.transform = (doc, ret) => {
return commonJsonTransform(ret);
};
if (name === 'NeighborhoodStoryBlock') {
schemas[name].options.toJSON.transform = (doc, ret) => {
ret = commonJsonTransform(ret);
delete ret.id;
return ret;
};
}
});
next(schemas);
};
<file_sep># MongoDB (click-to-deploy installation)
Documentation variables used:
[user]: username of the user you use to login to the nodes
[project-name]: Name of the project (no spaces or special characters)
[primary-node]: name of the created mongodb node which currently acts as PRIMARY
[secondary-node]: name of the created mongodb node(s) which currently acts as SECONDARY
[arbiter-node]: name of the created mongodb node(s) which currently acts as ARBITER
[project-db]: name of the database used for project
[project-staging-db]: name of the database used for staging project
[project-db-password]: password for project production db user
[project-stg-db-password]: password for project staging db user
[site-user-admin-pwd]: password for mongo site admin
[cluster-admin-pwd]: password for mongo cluster admin
[stackdriver-user-pwd]: password for mongo stackdriver agent user
[stackdriver-api-key]: API key for Stackdriver
Project values:
[user]: homehapp
[project-name]: homehapp
[project-db]: homehapp
[project-staging-db]: homehapp-staging
[project-db-password]: <PASSWORD>
[project-stg-db-password]: <PASSWORD>
[site-user-admin-pwd]: <PASSWORD>
[cluster-admin-pwd]: <PASSWORD>
[stackdriver-user-pwd]: <PASSWORD>
[stackdriver-api-key]: N0XPSONDEIPQHLQDAV0WKDCPB6FTBXI8
We will do some after deployment optimizations to the Nodes following best practises from:
https://docs.mongodb.org/ecosystem/platforms/google-compute-engine/
## Execute the Deploy
After the deployment is done,
remove the public IPs form the nodes. (This ofcourse means you have to SSH to them through maintainance node)
Add the following tag to all the instances: "project-noip"
## Configure Nodes
After initial SSH connection to the node:
Add following to the end of ~/.bashrc -file
```
export LC_ALL=en_US.UTF-8
```
Logout and Login again
### Optimize Primary and Secondary nodes
Edit /etc/fstab and add the following after the "defaults" setting:
,auto,noatime,noexec
Ie.
/dev/disk/by-id/google-hhmongo-db-9kx9-data /mnt/mongodb ext4 defaults,auto,noatime,noexec 0 0
Edit /etc/mongod.conf (append to the end)
```
# Qvik config
auth = true
nohttpinterface = true
keyFile=/mnt/mongodb/.mongodb-key.pem
```
NOTE! Following command is only done in Primary node. Copy the contents to other nodes
sudo su
openssl rand -base64 741 > /mnt/mongodb/.mongodb-key.pem
exit
sudo chown mongodb:mongodb /mnt/mongodb/.mongodb-key.pem
sudo chmod 0600 /mnt/mongodb/.mongodb-key.pem
Edit /etc/security/limits.conf (append)
```
mongodb soft nofile 64000
mongodb hard nofile 64000
mongodb soft nproc 32000
mongodb hard nproc 32000
```
Edit /etc/security/limits.d/90-nproc.conf
```
mongodb soft nproc 32000
mongodb hard nproc 32000
```
sudo blockdev --setra 32 /dev/sdb
echo 'ACTION=="add", KERNEL=="sdb", ATTR{bdi/read_ahead_kb}="16"' | sudo tee -a /etc/udev/rules.d/85-mongod.rules
echo 300 | sudo tee /proc/sys/net/ipv4/tcp_keepalive_time
echo "net.ipv4.tcp_keepalive_time = 300" | sudo tee -a /etc/sysctl.conf
sudo service mongod stop
sudo service mongod start
### Configure Primary mongodb
mongo
```
use admin
db.createUser(
{
user: "siteUserAdmin",
pwd: "[<PASSWORD>]",
roles:
[
{
role: "userAdminAnyDatabase",
db: "admin"
}
]
}
)
exit
```
mongo -u siteUserAdmin -p '[site-user-admin-pwd]' --authenticationDatabase admin
```
use admin
db.createUser(
{
user: "clusterAdmin",
pwd: "[<PASSWORD>]",
roles:
[
{
role: "clusterAdmin",
db: "admin"
}
]
}
)
db.createUser(
{
user: "stackdriverUser",
pwd: "[<PASSWORD>]",
roles: [
{role: "dbAdminAnyDatabase", db: "admin"},
{role: "clusterAdmin", db: "admin"},
{role: "readAnyDatabase", db: "admin"}
]
}
)
use [project-db]
db.createUser(
{
user: "[project-name]",
pwd: "[<PASSWORD>]",
roles: [ "dbAdmin", "readWrite" ]
}
)
use [project-staging-db]
db.createUser(
{
user: "[project-name]",
pwd: "[<PASSWORD>]",
roles: [ "dbAdmin", "readWrite" ]
}
)
```
use homehapp-staging
db.createUser(
{
user: "homehapp",
pwd: "[<PASSWORD>]",
roles: [ "dbAdmin", "readWrite" ]
}
)
### Configure Arbiter node
Edit /etc/mongod.conf (append to the end)
```
# Qvik config
auth = true
keyFile=/home/[user]/.mongodb-key.pem
```
Copy .mongodb-key.pem from Primary to /home/[user]/.mongodb-key.pem
sudo chown mongodb:mongodb /home/[user]/.mongodb-key.pem
sudo chmod 0600 /home/[user]/.mongodb-key.pem
sudo service mongod stop
sudo service mongod start
# Configure Stackdriver agent on nodes (PRIMARY, SECONDARY)
Get your API key from https://app.google.stackdriver.com/settings/apikeys
Edit /etc/default/stackdriver-agent
```
STACKDRIVER_API_KEY="[stackdriver-api-key]"
```
Edit /opt/stackdriver/collectd/etc/collectd.d/mongodb.conf
```
User "stackdriverUser"
Password "[<PASSWORD>]"
```
sudo service stackdriver-agent restart
# Dump staging data to production
mongodump -u homehapp -p 'hSXDuC2VX850FjfQEV+5HFYYrPfw55F0' --db homehapp-staging
mongorestore -u homehapp -p 'NPUPZZD6Qocrh2o8diDhkXO4KtkXRRmp' --db homehapp dump/homehapp-staging
mongo -u homehapp -p 'NPUPZZD6Qocrh2o8diDhkXO4KtkXRRmp' homehapp
<file_sep>import SourceBuilder from '../../common/sources/Builder';
import CityActions from '../actions/CityActions';
// let debug = require('debug')('CitySource');
export default SourceBuilder.build({
name: 'CitySource',
actions: {
base: CityActions,
error: CityActions.requestFailed
},
methods: {}
});
<file_sep>import React from 'react';
import ContactListStore from '../../stores/ContactListStore';
import ContactsView from './View';
import Loading from '../../../common/components/Widgets/Loading';
let debug = require('debug')('EditContainer');
export default class ContactsEditContainer extends React.Component {
static propTypes = {
params: React.PropTypes.object
}
constructor(props) {
super(props);
this.storeListener = this.onChange.bind(this);
}
state = {
error: null,
contact: ContactListStore.getContact(this.props.params.id)
}
componentDidMount() {
ContactListStore.listen(this.storeListener);
if (!ContactListStore.getContact(this.props.params.id)) {
ContactListStore.fetchContacts();
}
}
componentWillUnmount() {
ContactListStore.unlisten(this.storeListener);
}
onChange(state) {
debug('state', state, ContactListStore.getState());
this.setState({
error: ContactListStore.getState().error,
contact: ContactListStore.getContact(this.props.params.id)
});
}
handlePendingState() {
return (
<Loading>
<h3>Loading contacts...</h3>
</Loading>
);
}
handleErrorState() {
return (
<div className='contacts-error'>
<h3>Error loading contacts!</h3>
<p>{this.state.error.message}</p>
</div>
);
}
render() {
if (this.state.error) {
return this.handleErrorState();
}
debug('Contact', this.state.contact);
if (ContactListStore.isLoading() || !this.state.contact) {
return this.handlePendingState();
}
let tab = this.props.params.tab || 1;
return (
<ContactsView contact={this.state.contact} tab={tab} />
);
}
}
<file_sep>import winston from 'winston';
import {merge} from './Helpers';
class Logger {
constructor(config) {
this.config = merge({
Console: {
enabled: true
}
}, config);
this.transports = winston.transports;
}
addTransport(name, implementation) {
if (this.transports[name]) {
return false;
}
if (!implementation) {
return false;
}
this.transports[name] = implementation;
}
configure(app) {
winston.exitOnError = false;
this.logger = new (winston.Logger)({
exitOnError: false
});
this.logger.handleExceptions(
new winston.transports.Console({prettyPrint: true})
);
Object.keys(this.config).forEach((loggerName) => {
let loggerConfig = this.config[loggerName];
loggerConfig.exitOnError = false;
loggerConfig.timestamp = true;
if (!loggerConfig.enabled) {
return;
}
if (!this.transports[loggerName]) {
console.warn(`Unable to load logger for transport ${loggerName}.`);
return;
}
this.logger.add(this.transports[loggerName], loggerConfig);
});
app.log = this.logger;
return Promise.resolve();
}
}
export default Logger;
<file_sep>#! /bin/sh
# Do not change these
REV=`git rev-parse --short HEAD`
CWD=`pwd`
CONTAINER_REGISTRY_HOST=eu.gcr.io
ENV="prod"
PNAME="$1-$ENV"
PBNAME="$1"
function printUsage() {
echo "Required environment variables:"
echo " PROJECT_ID: Google Project ID"
echo ""
echo "Usage PROJECT_ID=id ./support/production/updateCluster.sh [project_name]"
}
function printUsageAndExit() {
printUsage
exit
}
if [ "$PROJECT_ID" = "" ]; then
echo "No Google Project ID defined!"
printUsageAndExit
fi
if [ "$PNAME" = "" ]; then
echo "No project defined!"
printUsageAndExit
fi
if [ "$ENV" = "" ]; then
echo "No environment defined!"
printUsageAndExit
fi
function configGCloud() {
local CLUSTER_NAME=`gcloud beta container clusters list --project $PROJECT_ID | awk '{print $1}' | grep "$PNAME"`
echo "Executing: 'gcloud config set container/cluster $CLUSTER_NAME'"
gcloud config set container/cluster $CLUSTER_NAME
local CLUSTER_GOOGLE_NAME=`kubectl config view | awk '{print $2}' | grep $CLUSTER_NAME | tail -n 1`
echo "Executing: 'kubectl config use-context $CLUSTER_GOOGLE_NAME'"
kubectl config use-context $CLUSTER_GOOGLE_NAME
}
function updateCluster() {
local SOURCE_CONFIG="$CWD/infrastructure/configs/prod/project-controller-tpl.json"
local TARGET_CONFIG="$CWD/tmp/$PNAME-controller.json"
local TMP_FILE="/tmp/$PNAME-controller.json"
local CURRENT_CONTROLLER=`kubectl get rc | grep $PROJECT_ID | awk '{print $1}' | grep "$PNAME-controller"`
sed "s/:PROJECT_NAME/$PNAME/g" $SOURCE_CONFIG > $TARGET_CONFIG
sed "s/:PROJECT_BASE_NAME/$PBNAME/g" $TARGET_CONFIG > $TMP_FILE && mv $TMP_FILE $TARGET_CONFIG
sed "s/:PROJECT_ID/$PROJECT_ID/g" $TARGET_CONFIG > $TMP_FILE && mv $TMP_FILE $TARGET_CONFIG
sed "s/:CONTROLLER_NAME/$PNAME-controller-$REV/g" $TARGET_CONFIG > $TMP_FILE && mv $TMP_FILE $TARGET_CONFIG
sed "s/:REV/$REV/g" $TARGET_CONFIG > $TMP_FILE && mv $TMP_FILE $TARGET_CONFIG
sed "s/:ENV/$ENV/g" $TARGET_CONFIG > $TMP_FILE && mv $TMP_FILE $TARGET_CONFIG
echo "Executing: 'kubectl rolling-update $CURRENT_CONTROLLER -f $CWD/tmp/$PNAME-controller.json'"
kubectl rolling-update $CURRENT_CONTROLLER -f "$CWD/tmp/$PNAME-controller.json"
rm $TARGET_CONFIG
}
function updateProxyCluster() {
local SOURCE_CONFIG="$CWD/infrastructure/configs/prod/proxy-controller-tpl.json"
local TARGET_CONFIG="$CWD/tmp/$PNAME-proxy-controller.json"
local TMP_FILE="/tmp/$PNAME-proxy-controller.json"
local UC_PNAME=`echo "${PBNAME}_${ENV}" | awk '{print toupper($0)}'`
local CURRENT_CONTROLLER=`kubectl get rc | grep $PROJECT_ID | awk '{print $1}' | grep "$PNAME-proxy-controller"`
local SERVICE_HOST="${UC_PNAME}_SERVICE_HOST"
local SERVICE_PORT="${UC_PNAME}_SERVICE_PORT_ENDPOINT"
sed "s/:PROJECT_NAME/$PNAME-proxy/g" $SOURCE_CONFIG > $TARGET_CONFIG
sed "s/:PROJECT_ID/$PROJECT_ID/g" $TARGET_CONFIG > $TMP_FILE && mv $TMP_FILE $TARGET_CONFIG
sed "s/:CONTROLLER_NAME/$PNAME-proxy-controller-$REV/g" $TARGET_CONFIG > $TMP_FILE && mv $TMP_FILE $TARGET_CONFIG
sed "s/:REV/$REV/g" $TARGET_CONFIG > $TMP_FILE && mv $TMP_FILE $TARGET_CONFIG
sed "s/:ENV/$ENV/g" $TARGET_CONFIG > $TMP_FILE && mv $TMP_FILE $TARGET_CONFIG
sed "s/:SERVICE_HOST/$SERVICE_HOST/g" $TARGET_CONFIG > $TMP_FILE && mv $TMP_FILE $TARGET_CONFIG
sed "s/:SERVICE_PORT/$SERVICE_PORT/g" $TARGET_CONFIG > $TMP_FILE && mv $TMP_FILE $TARGET_CONFIG
echo "Executing: 'kubectl rolling-update $CURRENT_CONTROLLER -f $CWD/tmp/$PNAME-proxy-controller.json'"
kubectl rolling-update $CURRENT_CONTROLLER -f "$CWD/tmp/$PNAME-proxy-controller.json"
rm $TARGET_CONFIG
}
configGCloud
echo ""
echo "Updating Cluster Pods for project '$PNAME' to revision $REV for environment $ENV"
updateCluster
echo ""
echo "Updating Proxy Cluster"
updateProxyCluster
echo ""
echo "Finished"
<file_sep>import React from 'react';
import ProgressBar from 'react-bootstrap/lib/ProgressBar';
import ExecutionEnvironment from 'react/lib/ExecutionEnvironment';
import request from '../../request';
import UploadAreaUtils from './utils';
import Helpers from '../../Helpers';
import ApplicationStore from '../../stores/ApplicationStore';
import { toCloudinaryTransformation } from '../../../common/Helpers';
let debug = require('../../debugger')('UploadArea');
let Dropzone = null;
if (ExecutionEnvironment.canUseDOM) {
Dropzone = require('../../../../assets/js/admin/dropzone.js');
}
class UploadArea extends React.Component {
static propTypes = {
dropzoneConfig: React.PropTypes.object,
useCloudinary: React.PropTypes.bool,
signatureFolder: React.PropTypes.string,
signatureData: React.PropTypes.object,
isVideo: React.PropTypes.bool,
uploadUrl: React.PropTypes.string,
uploadParams: React.PropTypes.object,
width: React.PropTypes.string,
height: React.PropTypes.string,
className: React.PropTypes.string,
maxFiles: React.PropTypes.number,
maxSize: React.PropTypes.number,
onError: React.PropTypes.func,
onProgress: React.PropTypes.func,
onUpload: React.PropTypes.func,
acceptedMimes: React.PropTypes.string,
instanceId: React.PropTypes.number,
thumbnailWidth: React.PropTypes.number,
thumbnailHeight: React.PropTypes.number,
clickable: React.PropTypes.bool,
children: React.PropTypes.oneOfType([
React.PropTypes.array,
React.PropTypes.object
]),
transformations: React.PropTypes.string
}
static defaultProps = {
className: 'uploadArea',
instanceId: Helpers.randomNumericId(),
thumbnailWidth: 80,
thumbnailHeight: 80,
useCloudinary: true,
uploadUrl: null,
uploadParams: {},
clickable: true,
isVideo: false,
maxSize: Infinity,
transformations: null
}
constructor(props) {
let type = 'image';
if (props.isVideo) {
type = 'video';
}
let defaultUploadUrl = `${ApplicationStore.getState().config.cloudinary.apiUrl}/${type}/upload`;
props.uploadUrl = props.uploadUrl || defaultUploadUrl;
super(props);
this.uploads = {};
//this.state.signatureData = this.props.signatureData;
}
state = {
//signatureData: null,
uploading: false,
uploads: {}
}
componentDidMount() {
this._buildDropzone();
}
componentWillUnmount() {
if (this.dropzone) {
this.dropzone.destroy();
}
this.dropzone = null;
}
static fetchCloudinarySignature(folder, params = {}) {
let data = Helpers.merge({}, {
folder: folder
}, params);
debug('fetchCloudinarySignature', data);
let reqPath = ApplicationStore.getState().config.cloudinary.signatureRoute;
return request.post(reqPath, data);
}
_fetchCloudinarySignature() {
let params = {};
if (this.props.useCloudinary && this.props.isVideo && this.props.transformations) {
params = {
notification_type: 'eager',
eager_async: true,
eager: toCloudinaryTransformation(this.props.transformations)
};
}
return UploadArea.fetchCloudinarySignature(this.props.signatureFolder, params)
.then((result) => {
this.setState({
signatureData: result.data.signed
});
let params = Helpers.merge(this.dropzone.options.params, result.data.signed);
this.dropzone.options.params = params;
});
}
_buildDropzone() {
let params = this.props.uploadParams || {};
if (this.props.useCloudinary && this.props.isVideo) {
params[`resource_type`] = 'video';
}
let dropzoneConfig = {
url: this.props.uploadUrl,
previewsContainer: false,
addRemoveLinks: false,
maxFiles: this.props.maxFiles,
acceptedFiles: this.props.acceptedMimes,
params: params,
clickable: this.props.clickable,
accept: (file, done) => {
if (file.size > this.props.maxSize) {
let maxSize = `${this.props.maxSize} bytes`;
if (this.props.maxSize > 1024) {
maxSize = `${Math.round(this.props.maxSize / 1024)} kB`;
}
if (this.props.maxSize > 1024 * 1024) {
maxSize = `${Math.round(this.props.maxSize / (1024 * 1024))} MB`;
}
let error = `File size exceeded the maximum allowed, which is ${maxSize}`;
if (typeof this.props.onError === 'function') {
this.props.onError(error);
} else {
console.error(error);
}
return false;
}
file.id = Helpers.randomNumericId();
UploadAreaUtils.UploadActions.updateUpload({
instanceId: this.props.instanceId,
id: file.id,
data: file
});
this.uploads[file.id] = {
name: file.name,
progress: 0
};
this.setState({
uploading: true,
uploads: this.uploads
});
if (this.props.useCloudinary && !this.state.signatureData) {
this._fetchCloudinarySignature().then(() => {
done();
}).catch(done);
} else {
done();
}
}
};
if (this.props.dropzoneConfig) {
dropzoneConfig = Helpers.merge(dropzoneConfig, this.props.dropzoneConfig);
}
this.dropzone = new Dropzone(
this.refs.uploader.getDOMNode(), dropzoneConfig
);
this.dropzone.on('thumbnail', (file, dataUrl) => {
debug('dropzone.thumbnail', file, dataUrl);
UploadAreaUtils.UploadActions.updateUpload({
instanceId: this.props.instanceId,
id: file.id,
data: {
thumbnail: dataUrl
}
});
});
this.dropzone.on('uploadprogress', (file, progress) => {
debug('dropzone.uploadprogress', file, progress);
this.uploads[file.id].progress = progress;
this.setState({
uploading: true,
uploads: this.uploads
});
if (this.props.onProgress) {
this.props.onProgress(file, progress);
}
});
this.dropzone.on('success', (file, response) => {
debug('dropzone.success', file, response);
let fileData = response;
if (this.props.useCloudinary) {
fileData.url = response[`secure_url`];
if (this.props.isVideo) {
let projectId = ApplicationStore.getState().config.cloudinary.projectId;
let publicId = response[`public_id`];
let thumbnailUrl = `//res.cloudinary.com/${projectId}/video/upload/${publicId}.jpg`;
fileData.thumbnail = thumbnailUrl;
}
}
UploadAreaUtils.UploadActions.updateUpload({
instanceId: this.props.instanceId,
id: file.id,
data: fileData
});
this.props.onUpload(file, response);
this.setState({
uploading: false,
uploads: this.uploads
});
});
}
getLoader() {
let ids = Object.keys(this.state.uploads);
let files = [];
let progress = 0;
ids.map((id) => {
let file = this.state.uploads[id];
if (file.progress === 100) {
return null;
}
files.push(file.name);
progress += file.progress;
});
if (!files.length) {
return null;
}
// let percentage = `${Math.ceil(Math.round(10 * progress / (files.length))) / 10}%`;
let percentage = Math.ceil(Math.round(10 * progress / (files.length))) / 10;
return (
<ProgressBar striped active now={percentage} label={`${Math.round(percentage)}%`} />
);
}
render() {
let cls = [
this.props.className,
'clearfix'
];
return (
<div
className={cls.join(' ')}
ref='uploader'
style={{ width: this.props.width, height: this.props.height }}>
<div className='dz-message'>
{this.props.children}
{this.getLoader()}
</div>
</div>
);
}
}
export default UploadArea;
<file_sep>import Plugins from './Plugins';
import moment from 'moment';
import Mongoose from 'mongoose';
let Entities = require('html-entities').Html4Entities;
let entities = new Entities();
exports.getImageFields = function getImageFields() {
return {
url: {
type: String
},
width: {
type: Number,
required: true,
default: 0
},
height: {
type: Number,
required: true,
default: 0
},
alt: {
type: String,
default: ''
},
tag: {
type: String
},
isMaster: {
type: Boolean,
default: false
},
author: {
type: String,
default: ''
},
thumbnail: {
data: String,
dataVersion: Number,
url: String
}
};
};
exports.getAddressFields = function getAddressFields() {
return {
street: {
type: String,
default: ''
},
apartment: {
type: String,
default: ''
},
city: {
type: String,
default: ''
},
sublocality: {
type: String,
default: ''
},
zipcode: {
type: String,
default: ''
},
country: {
type: String,
default: ''
}
};
};
exports.getImageSchema = function getImageSchema(Schema) {
let image = new Schema(exports.getImageFields());
image.virtual('aspectRatio').get(function() {
return this.width / this.height;
});
return image;
};
exports.getStoryBlockSchema = function getStoryBlockSchema(Schema) {
return new Schema({
template: {
type: String,
default: 'default'
},
properties: {
type: Schema.Types.Mixed
}
});
};
exports.loadCommonPlugins = (schema, name, mongoose) => {
let extensionsFile = require('path').join(__dirname, name.toLowerCase() + '_extensions.js');
if (require('fs').existsSync(extensionsFile)) {
require(extensionsFile).extendSchema(schema, mongoose);
}
schema.plugin(Plugins.createdAt, {index: true});
schema.plugin(Plugins.lastModified, {index: true});
schema.plugin(Plugins.multiSet, {index: true});
schema.plugin(Plugins.uuid, {index: true});
schema.plugin(Plugins.enableACL, {
requestModelName: name.toLowerCase()
});
schema.set('toJSON', { virtuals: true });
};
exports.commonJsonTransform = (ret) => {
// remove the _id of every document before returning the result
delete ret._id;
delete ret.__v;
if (ret.uuid) {
ret.id = ret.uuid.toString();
delete ret.uuid;
}
// Delete private properties
let ownProps = Object.getOwnPropertyNames(ret);
ownProps.forEach((prop) => {
if (prop.substring(0, 1) === '_') {
delete ret[prop];
}
});
delete ret.deletedAt;
// Include EPOCH timestap for object
if (ret.createdAt) {
ret.createdAtTS = moment(ret.createdAt).unix();
}
if (ret.updatedAt) {
ret.updatedAtTS = moment(ret.updatedAt).unix();
}
return ret;
};
exports.getMainImage = function getMainImage(model, placeholder = null) {
if (!placeholder) {
placeholder = {
url: 'https://res.cloudinary.com/homehapp/image/upload/v1441913472/site/images/content/content-placeholder.jpg',
alt: 'Placeholder',
width: 1920,
height: 1280,
aspectRatio: 1920 / 1280
};
}
if (model.image && model.image.url) {
return model.image;
}
// This should include a check for the main image, but we go now with the
// simplest solution
if (model.images && model.images.length) {
return model.images[0];
}
if (model.story && model.story.blocks) {
let images = [];
for (let block of model.story.blocks) {
switch (block.template.type) {
case 'BigImage':
images.push(block.properties.image);
break;
case 'Gallery':
images.concat(block.properties.images);
break;
}
// Return the first available image from any story block
if (images.length) {
return images[0];
}
}
}
// Fallback placeholder
return placeholder;
};
exports.populateMetadata = function populateMetadata(schema) {
schema.createdBy = {
type: Mongoose.Schema.Types.ObjectId,
ref: 'User'
};
schema.createdAt = {
type: Date
};
schema.updatedBy = {
type: Mongoose.Schema.Types.ObjectId,
ref: 'User'
};
schema.updatedAt = {
type: Date
};
schema.deletedBy = {
type: Mongoose.Schema.Types.ObjectId,
ref: 'User'
};
schema.deletedAt = {
type: Date
};
schema.metadata = {
title: {
type: String,
default: null
},
description: {
type: String,
default: null
},
score: {
type: Number,
default: 0
}
};
return schema;
};
exports.urlName = function urlName(str) {
let patterns = [
['&', '_et_'],
['&([a-z])(cedil|elig|lpha|slash|tilde|acute|circ|grave|zlig|uml);', '$1'],
['[^0-9a-z\.\-]', '_'],
['^[\\-_\\.]+', ''],
['[\\-_\\.]+$', ''],
['_{2,}', '_'],
['_?\\-_?', '-'],
['\\.{2,}', '.'],
['\\s+', '_']
];
let tmp = entities.encode(String(str).toLowerCase());
let encoded = tmp;
for (let pattern of patterns) {
let regexp = new RegExp(pattern[0], 'ig');
encoded = encoded.replace(regexp, pattern[1]);
}
return encoded;
};
exports.generateUniqueSlug = function generateUniqueSlug(model, cb, iteration) {
if (iteration > 10) {
return cb(new Error('iteration overflow'));
}
model.slug = exports.urlName(model.title);
if (iteration) {
model.slug += `-${iteration}`;
}
model.constructor.count({slug: model.slug, deletedAt: null}, function (err, count) {
if (err) {
return cb(err);
}
// slug is unique
if (count === 0) {
return cb();
}
// slug is not unique
generateUniqueSlug(model, cb, (iteration || 0) + 1);
});
};
<file_sep>import {Strategy} from 'passport-strategy';
import jwt from 'jsonwebtoken';
import fs from 'fs';
class JWTStrategy extends Strategy {
constructor(options, verify) {
if (typeof options === 'function') {
verify = options;
options = {};
}
if (!verify) {
throw new TypeError('JWTStrategy requires a verify callback');
}
if (!options.secret && !(options.keys || options.keys.public)) {
throw new TypeError('JWTStrategy requires secret or key');
}
super(options, verify);
this.name = 'jwt';
this._verify = verify;
this._options = options;
this._passRequestToCallback = options.passRequestToCallback;
this._scheme = options.authScheme || 'JWT';
this._tokenField = options.tokenField || 'X-Qvik-Auth-Token';
this._secretOrKey = options.secret;
if (options.keys.public) {
this._secretOrKey = fs.readFileSync(options.keys.public);
}
this._verifyOpts = {};
if (options.issuer) {
this._verifyOpts.issuer = options.issuer;
}
if (options.audience) {
this._verifyOpts.audience = options.audience;
}
if (options.keys.public) {
this._verifyOpts.algorithm = 'RS256';
}
}
authenticate(req/*, opts*/) {
if (!req.headers || !req.headers[this._tokenField.toLowerCase()]) {
return this.fail(403);
}
let token = req.headers[this._tokenField.toLowerCase()];
let verified = (err, user, info) => {
if (err) {
return this.error(err);
}
if (!user) {
return this.fail(info);
}
req.user = user;
this.success(user, info);
};
jwt.verify(token, this._secretOrKey, this._verifyOpts, (err, payload) => {
if (err) {
return this.fail(403);
}
if (this._passRequestToCallback) {
this._verify(req, payload, verified);
} else {
this._verify(payload, verified);
}
});
}
}
export default JWTStrategy;
<file_sep>/* global window */
import React from 'react';
import { scrollTop, setFullHeight, itemViews } from '../../Helpers';
import ApplicationStore from '../../stores/ApplicationStore';
let debug = require('debug')('Layout');
export default class Layout extends React.Component {
static propTypes = {
children: React.PropTypes.oneOfType([
React.PropTypes.array,
React.PropTypes.object,
React.PropTypes.null
]).isRequired
}
static defaultProps = {
}
constructor() {
super();
this.pageScroller = this.pageScroller.bind(this);
this.stateListener = this.onStateChange.bind(this);
}
state = {
application: ApplicationStore.getState()
}
componentDidMount() {
debug('ApplicationStore', this.state.application, ApplicationStore);
window.addEventListener('resize', setFullHeight);
window.addEventListener('scroll', itemViews);
this.refs.scroller.getDOMNode().addEventListener('click', this.pageScroller, true);
this.refs.scroller.getDOMNode().addEventListener('touchstart', this.pageScroller, true);
ApplicationStore.listen(this.stateListener);
if (!this.state.application) {
ApplicationStore.getState();
}
// Trigger the events on load
setFullHeight();
itemViews();
}
componentWillUnmount() {
window.removeEventListener('resize', setFullHeight);
window.removeEventListener('scroll', itemViews);
this.refs.scroller.getDOMNode().removeEventListener('click', this.pageScroller);
this.refs.scroller.getDOMNode().removeEventListener('touchstart', this.pageScroller);
ApplicationStore.unlisten(this.stateListener);
}
onStateChange(state) {
debug('got state', state);
this.setState(state);
}
pageScroller() {
let top = scrollTop() + window.innerHeight;
scrollTop(top);
}
render() {
return (
<div id='layout'>
<div id='modals'></div>
{this.props.children}
<i className='fa fa-angle-down' id='scrollDown' ref='scroller'></i>
</div>
);
}
}
<file_sep>export function testDecorator() {
console.log('testDecorator', arguments);
return function(/*Component*/) {
console.log('testDecorator func', arguments);
};
}
<file_sep>import React from 'react';
import PageStore from '../../stores/PageStore';
import { setPageTitle } from '../../../common/Helpers';
import ErrorPage from '../../../common/components/Layout/ErrorPage';
import Loading from '../../../common/components/Widgets/Loading';
import StoryLayout from '../../../common/components/Layout/StoryLayout';
let debug = require('debug')('Page');
export default class Page extends React.Component {
static propTypes = {
params: React.PropTypes.object.isRequired
}
constructor() {
super();
this.storeListener = this.onStateChange.bind(this);
}
state = {
page: PageStore.getState().model,
error: null
}
componentDidMount() {
// setPageTitle();
PageStore.listen(this.storeListener);
PageStore.getItem(this.props.params.slug);
}
shouldComponentUpdate(nextProps) {
if (!this.state.page || nextProps.params.slug !== this.state.page.slug) {
PageStore.getItem(nextProps.params.slug);
return true;
}
return true;
}
componentWillUnmount() {
PageStore.unlisten(this.storeListener);
}
onStateChange(state) {
this.setState({
page: state.model,
error: state.error
});
if (state.model && state.model.title) {
setPageTitle(state.model.title);
}
}
handleErrorState() {
let error = {
title: 'Error loading page!',
message: this.state.error.message
};
return (
<ErrorPage {...error} />
);
}
handlePendingState() {
return (
<Loading>
<p>Loading page...</p>
</Loading>
);
}
render() {
debug('Render', this.state.page);
if (this.state.error) {
return this.handleErrorState();
}
if (PageStore.isLoading() || !this.state.page) {
return this.handlePendingState();
}
let blocks = [];
if (this.state.page.story && this.state.page.story.blocks && this.state.page.story.blocks.length) {
blocks = this.state.page.story.blocks;
} else {
blocks.push({
template: 'ContentBlock',
properties: {
title: this.state.page.title
}
});
}
return (
<div className='page' key={`page-${this.state.page.slug}`}>
<StoryLayout blocks={blocks} />
</div>
);
}
}
<file_sep>import BaseQueryBuilder from './BaseQueryBuilder';
import {NotFound} from '../../Errors';
// let debug = require('debug')('ContactQueryBuilder');
export default class ContactQueryBuilder extends BaseQueryBuilder {
constructor(app) {
super(app, 'Contact');
}
initialize() {
}
findByUuid(uuid) {
this._queries.push((callback) => {
let cursor = this.Model.findOne({
uuid: uuid,
deletedAt: null
});
this._configurePopulationForCursor(cursor);
cursor.exec((err, model) => {
if (err) {
return callback(err);
}
if (!model) {
return callback(new NotFound('Contact request not found'));
}
this.result.model = model;
this.result.models = [model];
this.result.contact = model;
this.result.contactJson = model.toJSON();
this._loadedModel = model;
callback();
});
});
return this;
}
}
<file_sep>import QueryBuilder from '../../lib/QueryBuilder';
let debug = require('debug')('/agents');
exports.registerRoutes = (app) => {
const QB = new QueryBuilder(app);
app.get('/agents', app.authenticatedRoute, function(req, res, next) {
debug('fetch agents');
debug('req.query', req.query);
QB
.forModel('Agent')
.parseRequestArguments(req)
.findAll()
.fetch()
.then((result) => {
res.locals.data.AgentListStore = {
agents: result.agentsJson
};
next();
})
.catch(next);
});
app.get('/agents/create', app.authenticatedRoute, function(req, res, next) {
debug('Create a blank agent');
let model = new (QB.forModel('Agent')).Model();
debug('Created a blank', model);
res.locals.data.AgentListStore = {
agents: [model]
};
next();
});
app.get('/agents/edit/:uuid', app.authenticatedRoute, function(req, res, next) {
debug('Fetch agent by uuid', req.params.uuid);
QB
.forModel('Agent')
.findByUuid(req.params.uuid)
.fetch()
.then((result) => {
res.locals.data.AgentListStore = {
agents: result.models
};
next();
})
.catch(next);
});
};
<file_sep>import alt from '../../common/alt';
import UserListActions from '../actions/UserListActions';
import UserListSource from '../sources/UserListSource';
// import Cache from '../../common/Cache';
// let debug = require('../../common/debugger')('UserListStore');
@alt.createStore
class UserListStore {
constructor() {
this.bindListeners({
handleUpdateUsers: UserListActions.UPDATE_USERS,
handleFetchUsers: UserListActions.FETCH_USERS,
handleFetchFailed: UserListActions.FETCH_FAILED
});
this.users = [];
this.error = null;
this.exportPublicMethods({
getUser: this.getUser
});
this.exportAsync(UserListSource);
}
getUser(id) {
let { users } = this.getState();
for (let user of users) {
if (!id) {
return user;
}
if (user.id === id) {
return user;
}
}
this.error = 'No matching id found in users';
}
handleUpdateUsers(users) {
this.users = users;
this.error = null;
}
handleFetchUsers() {
this.users = [];
this.error = null;
}
handleFetchFailed(error) {
this.error = error;
}
}
module.exports = UserListStore;
<file_sep>import React from 'react';
import BaseWidget from './BaseWidget';
import linearPartition from 'linear-partition';
import DOMManipulator from '../../DOMManipulator';
import Modal from './Modal';
import Pager from './Pager';
import Image from './Image';
let debug = require('../../../common/debugger')('Gallery');
export default class Gallery extends BaseWidget {
static propTypes = {
images: React.PropTypes.array.isRequired,
title: React.PropTypes.string,
columns: React.PropTypes.number,
imageWidth: React.PropTypes.number,
fullscreen: React.PropTypes.bool,
className: React.PropTypes.string
};
static defaultProps = {
images: [],
title: '',
columns: 8,
imageWidth: 200,
fullscreen: true,
className: null
};
static validate(props) {
if (!props.images) {
debug('No images provided for the gallery');
throw new Error('Attribute "images" is missing');
}
if (!Array.isArray(props.images)) {
debug('Attribute "images" is not an array');
throw new Error('Attribute "images" is not an array');
}
props.images.map((image) => {
Image.validate(image);
});
}
constructor() {
super();
this.aspectRatios = [];
this.galleryImages = [];
this.preloaded = {};
// Bind to this
this.onResize = this.onResize.bind(this);
this.onClick = this.onClick.bind(this);
this.changeImage = this.changeImage.bind(this);
this.closeModal = this.closeModal.bind(this);
this.moveStart = this.moveStart.bind(this);
this.moveEvent = this.moveEvent.bind(this);
this.moveEnd = this.moveEnd.bind(this);
this.imageContainer = null;
this.startT = null;
this.startX = null;
this.currentX = null;
this.currentX = null;
this.currentImage = null;
this.moveImages = [];
this.events = [
{
events: ['mousedown', 'touchstart'],
handler: this.moveStart,
target: 'image'
},
{
events: ['mousemove', 'touchmove'],
handler: this.moveEvent,
target: 'document'
},
{
events: ['mouseleave', 'mouseout', 'mouseup', 'touchend', 'touchcancel'],
handler: this.moveEnd,
target: 'document'
}
];
}
componentDidMount() {
if (!this.refs.gallery) {
return null;
}
this.gallery = new DOMManipulator(this.refs.gallery);
this.images = this.gallery.node.getElementsByTagName('img');
for (let i = 0; i < this.images.length; i++) {
this.galleryImages.push(this.images[i].parentNode.href);
}
this.updateGallery();
window.addEventListener('resize', this.onResize);
this.gallery.addEvent('click', this.onClick, true);
this.gallery.addEvent('touch', this.onClick, true);
}
componentWillUnmount() {
window.removeEventListener('resize', this.onResize);
this.endCapture();
this.gallery.removeEvent('click', this.onClick, true);
this.gallery.removeEvent('touch', this.onClick, true);
}
// Start moving, capture the event
startCapture() {
// Unbind all the old events in case of an unsuccessful unbinding
this.endCapture();
// Bind a whole lot of events here
for (let i = 0; i < this.events.length; i++) {
for (let n = 0; n < this.events[i].events.length; n++) {
let target = document;
let capturing = false;
if (this.events[i].target === 'image') {
target = this.imageContainer;
capturing = true;
}
if (!target) {
continue;
}
target.addEventListener(this.events[i].events[n], this.events[i].handler, capturing);
}
}
}
endCapture() {
// Unbind a whole lot of events here
for (let i = 0; i < this.events.length; i++) {
for (let n = 0; n < this.events[i].events.length; n++) {
let target = document;
let capturing = false;
if (this.events[i].target === 'image') {
target = this.imageContainer;
capturing = true;
}
if (!target) {
continue;
}
target.removeEventListener(this.events[i].events[n], this.events[i].handler, capturing);
}
}
}
getX(event) {
if (typeof event.clientX !== 'undefined') {
return event.clientX;
}
if (typeof event.touches !== 'undefined' && event.touches.length === 1) {
return event.touches[0].clientX;
}
return null;
}
moveStart(event) {
event.stopPropagation();
event.preventDefault();
this.startX = this.getX(event);
this.currentX = this.startX;
if (this.startX === null) {
return false;
}
this.startT = (new Date()).getTime();
this.moveImages = [];
let images = this.imageContainer.getElementsByTagName('img');
for (let i = 0; i < images.length; i++) {
if (Math.abs(Number(images[i].getAttribute('data-distance'))) <= 1) {
this.moveImages.push(images[i]);
images[i].setAttribute('data-move', '');
}
}
return false;
}
moveEvent(event) {
event.stopPropagation();
event.preventDefault();
if (this.startX === null) {
return true;
}
let dx = this.getX(event) - this.startX;
for (let i = 0; i < this.moveImages.length; i++) {
let d = Number(this.moveImages[i].getAttribute('data-distance'));
let margin = dx - d * window.innerWidth;
this.moveImages[i].style.marginLeft = `${margin}px`;
}
this.currentX = this.getX(event);
return false;
}
moveEnd(event) {
event.stopPropagation();
event.preventDefault();
if (this.startX === null) {
return true;
}
let currentT = (new Date()).getTime();
let dx = this.startX - this.currentX;
let absX = Math.abs(dx);
let dt = currentT - this.startT;
let speed = absX / dt;
// Reset for the next round
this.startX = null;
for (let i = 0; i < this.moveImages.length; i++) {
this.moveImages[i].removeAttribute('data-move');
this.moveImages[i].style.marginLeft = null;
}
if (absX < 10 && dt < 500) {
return true;
}
if ((absX > window.innerWidth * 0.1 && speed > 1) || absX > window.innerWidth * 0.25) {
if (dx < 0) {
this.changeImage(-1);
} else {
this.changeImage(1);
}
}
return false;
}
// Update the sizes and positions in the gallery
onResize() {
this.updateGallery();
}
onClick(e) {
let target = e.srcElement;
// Get the link if clicked on a child
while (target && target.tagName.toLowerCase() !== 'a') {
target = target.parentNode;
// No parent, no link, end gracefully
if (!target || target.tagName.toLowerCase() === 'body') {
return true;
}
}
this.modal = this.createModal();
this.modalContainer = null;
this.preloaded = {};
// Reference to self
let app = this;
React.render(this.modal, document.getElementById('modals'), function() {
try {
let src = target.getAttribute('href');
app.currentImage = src;
app.modalContainer = this.refs.modal.getDOMNode();
app.imageContainer = document.getElementById('galleryImages');
app.createImage(src);
app.preloadSurroundingImages(src);
app.startCapture();
} catch (err) {
console.error(err.message);
}
});
e.preventDefault();
return false;
}
// Create the modal view
createModal() {
return (
<Modal onclose={this.closeModal}>
<Pager onchange={this.changeImage} onclose={this.closeModal} />
<div id='galleryImages'></div>
</Modal>
);
}
closeModal() {
this.endCapture();
this.preloaded = {};
}
// Calculate the distance to the source element
getDistance(src) {
let current = this.galleryImages.indexOf(this.currentImage);
let target = this.galleryImages.indexOf(src);
let d = current - target;
let tolerance = Math.min(this.galleryImages.length - 2, 2);
let max = this.galleryImages.length - tolerance;
// Left overflow, start from the last one on right
if (d === max) {
d = -1 * tolerance;
}
// Right overflow, start from the first one on left
if (d === -1 * max) {
d = tolerance;
}
return d;
}
changeImage(dir) {
let next = this.galleryImages.indexOf(this.currentImage) + dir;
if (next < 0) {
next = 0;
// next = this.galleryImages.length - 1;
}
if (next >= this.galleryImages.length) {
next = this.galleryImages.length - 1;
// next = 0;
}
this.currentImage = this.galleryImages[next];
this.preloadSurroundingImages(this.currentImage);
this.updateDistances();
}
updateDistances() {
let images = this.imageContainer.getElementsByTagName('img');
for (let i = 0; i < images.length; i++) {
images[i].setAttribute('data-distance', this.getDistance(images[i].src));
}
}
preloadSurroundingImages() {
let current = this.galleryImages.indexOf(this.currentImage);
let next = current + 1;
let prev = current - 1;
if (prev < 0) {
prev = this.galleryImages.length - 1;
}
if (next >= this.galleryImages.length) {
next = 0;
}
this.createImage(this.galleryImages[prev]);
this.createImage(this.galleryImages[next]);
}
// Create the displayed Image
createImage(src) {
let distance = this.getDistance(src);
let image = document.createElement('img');
let app = this;
for (let img in this.imageContainer.getElementsByTagName('img')) {
if (img.src === src) {
image = img;
break;
}
}
if (typeof this.preloaded[src] === 'undefined') {
image.setAttribute('data-distance', distance);
image.onload = function() {
app.preloaded[this.src] = this;
};
image.src = src;
image.className = 'gallery-image';
if (!image.parentNode) {
this.imageContainer.appendChild(image);
}
}
}
// Update the gallery view by setting the width and height as linear
// partition suggests
updateGallery() {
let width = this.gallery.width();
let columns = 4;
if (width < 900) {
columns = 3;
}
let rows = Math.ceil(this.images.length / columns);
let aspectRatios = [];
for (let i = 0; i < this.images.length; i++) {
aspectRatios.push(Number(this.images[i].getAttribute('data-aspect-ratio')));
}
let partitioned = linearPartition(aspectRatios, rows);
let index = 0;
for (let i = 0; i < partitioned.length; i++) {
let row = partitioned[i];
let total = 0;
let h = 0;
for (let j = 0; j < row.length; j++) {
total += row[j];
}
for (let j = 0; j < row.length; j++) {
let col = row[j];
let w = col / total * 100;
let image = new DOMManipulator(this.images[index]);
image.addClass('visible');
if (!j) {
image.addClass('first');
// One height per row to prevent rounding corner cases
h = Math.round(col / total * width / aspectRatios[index]);
}
// Relative width to fill the space fully, absolute height
// to snap everything in place horizontally
image.css({
width: `${w}%`,
height: `${h}px`
});
index++;
}
}
}
renderWidget() {
let classes = ['gallery', 'widget', 'clearfix'];
let subclasses = ['gallery-images'];
if (this.props.className) {
classes.push(this.props.className);
}
// if (this.props.images.length < 4) {
// subclasses.push('width-wrapper');
// }
let title = null;
if (this.props.title) {
title = (
<div className='center'>
<h2>{this.props.title}</h2>
</div>
);
}
return (
<div className={classes.join(' ')}>
{title}
<div className={subclasses.join(' ')} ref='gallery'>
{
this.props.images.map((item, index) => {
let image = {
src: item.url,
alt: item.alt || '',
variant: 'gallery',
linked: (this.props.fullscreen) ? 'fullscreen' : null,
aspectRatio: item.aspectRatio || (item.width / item.height)
};
return (
<Image {...image} key={index} />
);
})
}
</div>
</div>
);
}
}
<file_sep>import React from 'react';
import Col from 'react-bootstrap/lib/Col';
class SubNavigation extends React.Component {
static propTypes = {
children: React.PropTypes.oneOfType([
React.PropTypes.array,
React.PropTypes.object,
React.PropTypes.null
])
};
render() {
return (
<Col sm={3} md={2} className='sidebar'>
{this.props.children}
</Col>
);
}
}
export default SubNavigation;
<file_sep>import React from 'react';
import { Link } from 'react-router';
import classNames from 'classnames';
import { primaryHomeTitle } from '../../../common/Helpers';
import Hoverable from './Hoverable';
export default class Card extends React.Component {
static propTypes = {
item: React.PropTypes.object.isRequired,
className: React.PropTypes.string
}
static defaultProps = {
className: null
}
mainImage() {
if (!this.props.item.images.length) {
return null;
}
let image = this.props.item.images[0];
return (
<span className='image-wrapper'>
<Hoverable {...image} variant='card' />
</span>
);
}
render() {
let classes = ['card'];
if (this.props.item.story.enabled) {
classes.push('storified');
}
if (this.props.className) {
classes.push(this.props.className);
}
let image = this.mainImage();
return (
<div className={classNames(classes)}>
<div className='card-content'>
<Link to='home' params={{slug: this.props.item.slug}} className='thumbnail'>
{image}
<span className='details'>
<span className='price'>{this.props.item.formattedPrice}</span>
<span className='street'>{this.props.item.location.address.street}, </span>
<span className='city'>{this.props.item.location.address.city}</span>
</span>
</Link>
<p className='title'>
<Link to='home' params={{slug: this.props.item.slug}}>{primaryHomeTitle(this.props.item)}</Link>
</p>
</div>
</div>
);
}
}
<file_sep>let debug = require('debug')('/api/newsletter');
let superagent = require('superagent');
exports.registerRoutes = (app) => {
let apikey = '<KEY>';
app.post('/api/newsletter', function(req, res, next) {
debug('/api/newsletter', req);
if (!req.body || !req.body.newsletter || !req.body.newsletter.email) {
debug('no body');
res.status(422);
return next();
}
superagent
.post('https://us12.api.mailchimp.com/3.0/lists/914a5e94a5/members')
.set('Authorization', 'apikey <KEY>')
.send({
email_address: req.body.newsletter.email,
status: 'subscribed'
})
.end((e, r) => {
let rval = {
status: 'ok',
message: 'subscribed',
newsletter: {}
};
let status = r.status || 100;
if (status === 400) {
status = 200;
rval.message = 'already subscribed';
}
res
.status(status)
.json(rval);
});
});
};
<file_sep>import request from '../../common/request';
import NewsletterActions from '../actions/NewsletterActions';
let debug = require('../../common/debugger')('NewsletterSource');
let NewsletterSource = {
createItem: function () {
return {
remote(storeState, data) {
debug('createItem:remote', arguments, data);
let postData = {
newsletter: data
};
return request.post(`/api/newsletter`, postData)
.then((response) => {
debug('got response', response);
if (!response.data || response.data.status !== 'ok') {
let err = new Error(response.data.error || 'Invalid response');
return Promise.reject(err);
}
return Promise.resolve(response.data.newsletter);
})
.catch((response) => {
if (response instanceof Error) {
return Promise.reject(response);
} else {
let msg = 'unexpected error';
if (response.data && response.data.error) {
msg = response.data.error;
}
return Promise.reject(new Error(msg));
}
return Promise.reject(response);
});
},
local(storeState, data) {
debug('createItem:local', arguments, data);
return null;
},
shouldFetch(state) {
debug('createItem:shouldFetch', arguments, state);
return true;
},
success: NewsletterActions.createSuccess,
error: NewsletterActions.requestFailed,
loading: NewsletterActions.createItem
};
}
};
export default NewsletterSource;
<file_sep>import React from 'react';
import InputWidget from '../Widgets/Input';
import { createNotification } from '../../../common/Helpers';
let debug = require('../../../common/debugger')('EditDetails');
const countries = require('../../../common/lib/Countries').forSelect();
export default class EditDetails extends React.Component {
constructor(props) {
super(props);
this.saving = null;
}
state = {
images: [],
coordinates: []
}
imageExists(url, key) {
debug('Check if image exists', this.state[key]);
let found = false;
this.state[key].forEach((img) => {
if (img.url === url) {
debug('Image exists');
found = true;
}
});
debug('Image does not exist');
return found;
}
addImage(imageData, key) {
debug('Add image', imageData, key);
let isMaster = false;
let image = {
url: imageData.url,
width: imageData.width,
height: imageData.height,
isMaster: isMaster
};
if (!this.imageExists(image.url, key)) {
debug('Add', image);
this.state[key].push(image);
}
}
addImages(key) {
debug('addImages', this.state.uploads, key);
if (this.state.uploads) {
if (this.state.uploads[key]) {
let uploads = this.state.uploads[key];
debug('uploads str', uploads, typeof uploads);
for (let i in uploads) {
this.addImage(uploads[i], key);
}
}
}
}
onImageUpload(data, object, key = 'images') {
debug('Arguments', arguments);
if (typeof this.state[key] === 'undefined') {
debug(`onImageUpload: There is no state "${key}"`, this.state);
return null;
}
debug('onImageUpload', data);
this.addImages(key);
let state = {};
state[key] = this.state[key];
this.setState(state);
}
onRemoveImageClicked(index, key = 'images') {
debug('onRemoveImageClicked args', arguments);
if (typeof this.state[key] === 'undefined') {
debug(`onRemoveImageClicked: There is no state "${key}"`, this.state);
return null;
}
let newImages = [];
this.state[key].forEach((item, idx) => {
if (idx !== index) {
newImages.push(item);
}
});
let state = {};
state[key] = newImages;
this.setState(state);
}
getCoordinates() {
if (this.state.lat && this.state.lng) {
return [Number(this.state.lat), Number(this.state.lng)];
}
if (!this.refs.locationLatitude || !this.refs.locationLongitude) {
return null;
}
let lat = this.refs.locationLatitude.getValue();
let lng = this.refs.locationLongitude.getValue();
if (!lat || !lng) {
return null;
}
return [
Number(lat),
Number(lng)
];
}
setCoordinates(lat, lng) {
debug('setCoordinates', lat, lng);
for (let prop of this.props) {
if (!prop || typeof prop.location === 'undefined' || typeof prop.location.coordinates === 'undefined') {
continue;
}
debug('set to', prop);
if (lat && lng) {
prop.location.coordinates = [lat, lng];
} else {
prop.location.coordinates = null;
}
}
}
getSlug(object) {
if (object.slug) {
return null;
}
return (
<InputWidget
type='text'
label='URL address'
placeholder='URL address (will be generated)'
readOnly
defaultValue={object.slug}
/>
);
}
getCountries() {
return countries;
}
getCountryOptions() {
return this.getCountries().map((country) => {
return (
<option
value={country.value}
key={'locCountry-' + country.value}>
{country.label}
</option>
);
});
}
setCoordinates(lat, lng) {
debug('Callback:setCoordinates', lat, lng);
this.setState({
lat: lat,
lng: lng
});
}
setInitialLocation(location) {
if (!location) {
return debug('No location provided for the model');
}
if (!location.coordinates) {
return debug('No coordinates were found from the location', location);
}
if (location.coordinates.length < 2) {
return debug('Coordinate system failed the sanity check for location', location);
}
this.state.lat = location.coordinates[0];
this.state.lng = location.coordinates[1];
}
handlePendingState() {
debug('handlePendingState');
this.saving = createNotification({
message: 'Saving the data...'
});
}
handleErrorState() {
debug('handleErrorState');
if (!typeof this.state.error === 'undefined' || !this.state.error) {
return null;
}
createNotification({
label: 'Error saving the object',
message: this.state.error.message,
type: 'danger'
});
}
handleRenderState() {
if (this.saving) {
this.saving.close();
this.saving = false;
}
}
}
<file_sep>import React from 'react';
import InputWidget from '../Widgets/Input';
import Panel from 'react-bootstrap/lib/Panel';
import Button from 'react-bootstrap/lib/Button';
import ButtonGroup from 'react-bootstrap/lib/ButtonGroup';
import AdminContentBlock from '../Widgets/ContentBlock';
import AdminBigImage from '../Widgets/BigImage';
import AdminContentImage from '../Widgets/ContentImage';
import AdminBigVideo from '../Widgets/BigVideo';
import AdminGallery from '../Widgets/Gallery';
import AdminLargeText from '../Widgets/LargeText';
import AdminHTMLContent from '../Widgets/HTMLContent';
import { moveToIndex } from '../../../common/Helpers';
import DOMManipulator from '../../../common/DOMManipulator';
let debug = require('debug')('StoryEditBlocks');
export default class StoryEditBlocks extends React.Component {
static propTypes = {
blocks: React.PropTypes.array.isRequired,
disabled: React.PropTypes.array,
enabled: React.PropTypes.array,
parent: React.PropTypes.object
};
static defaultProps = {
parent: null,
disabled: [],
enabled: []
}
constructor(props) {
super(props);
this.blocks = props.blocks;
this.iterator = 0;
//console.log('StoryEditBlocks', props);
}
getBlocks() {
let updatedBlocks = this.blocks;
this.blocks.map((item, index) => {
debug('Read block', index);
if (typeof this.refs[`block${index}`] === 'undefined') {
return null;
}
let newProps = this.refs[`block${index}`].getValues();
updatedBlocks[index].properties = newProps;
});
debug('getBlocks', updatedBlocks);
return updatedBlocks;
}
onAddBlock() {
let blockTemplate = this.refs.blockTemplate.getValue();
if (!blockTemplate) {
return;
}
this.blocks.push({
template: blockTemplate,
properties: {}
});
try {
this.refs.blockTemplate.getInputDOMNode().value = '';
} catch (error) {
debug('Failed to set the option to empty after the template was selected');
}
this.forceUpdate();
}
onReArrangeItem(index, dir) {
let newIndex = index;
if (dir === 'down') {
newIndex += 1;
} else {
newIndex -= 1;
}
this.blocks = moveToIndex(this.blocks, index, newIndex);
this.forceUpdate();
setTimeout(() => {
try {
let node = new DOMManipulator(this.refs[`block${newIndex}`]);
node.scrollTo(500, -150);
} catch (error) {
debug('Failed to scroll to the new location', error.toString());
}
}, 100);
}
onInput(index) {
return (key, value) => {
this.blocks = [].concat(this.blocks);
this.blocks[index].properties[key] = value;
};
}
onRemoveBlock(index) {
let newBlocks = [];
this.blocks.forEach((block, idx) => {
if (idx !== index) {
newBlocks.push(block);
}
});
this.blocks = newBlocks;
this.forceUpdate();
}
getSortingButtons(index) {
let upButton = null;
let downButton = null;
if (index > 0) {
upButton = (
<Button
bsSize='small'
onClick={() => {
this.onReArrangeItem(index, 'up');
}}
>
<i className='fa fa-arrow-up'></i>
</Button>
);
}
if (index < this.blocks.length - 1) {
downButton = (
<Button
bsSize='small'
onClick={() => {
this.onReArrangeItem(index, 'down');
}}
>
<i className='fa fa-arrow-down'></i>
</Button>
);
}
return (
<ButtonGroup>
{upButton}
{downButton}
</ButtonGroup>
);
}
getBlockHeader(item, index) {
let header = (
<div>
<span>{index + 1} {item.template}</span>
<div className='pull-right'>
{this.getSortingButtons(index)}
<Button
bsStyle='danger'
bsSize='small'
onClick={() => {
this.onRemoveBlock(index);
}}
>
Remove
</Button>
</div>
</div>
);
return header;
}
getBigImage(item, index) {
return (
<AdminBigImage {...item.properties} ref={'block' + index} onChange={this.onInput(index)} />
);
}
getContentImage(item, index) {
return (
<AdminContentImage {...item.properties} ref={'block' + index} onChange={this.onInput(index)} />
);
}
getContentBlock(item, index) {
return (
<AdminContentBlock {...item.properties} ref={'block' + index} onChange={this.onInput(index)} />
);
}
getGallery(item, index) {
return (
<AdminGallery {...item.properties} ref={'block' + index} parent={this.props.parent} onChange={this.onInput(index)}/>
);
}
getBigVideo(item, index) {
return (
<AdminBigVideo {...item.properties} ref={'block' + index} onChange={this.onInput(index)} />
);
}
getLargeText(item, index) {
return (
<AdminLargeText {...item.properties} ref={'block' + index} onChange={this.onInput(index)} />
);
}
getHTMLContent(item, index) {
return (
<AdminHTMLContent {...item.properties} ref={'block' + index} onChange={this.onInput(index)} />
);
}
render() {
this.iterator++;
let blockTypes = [
{
template: 'BigImage',
label: 'Big image'
},
{
template: 'BigVideo',
label: 'Video block'
},
{
template: 'ContentBlock',
label: 'Content block'
},
{
template: 'ContentImage',
label: 'Content Image'
},
{
template: 'Gallery',
label: 'Gallery'
},
{
template: 'HTMLContent',
label: 'HTML content'
}
];
return (
<div className='edit-story'>
{
this.blocks.map((item, index) => {
let method = `get${item.template}`;
if (typeof this[method] === 'function') {
let editor = this[method](item, index);
return (
<Panel
key={`b-${index}-${this.iterator}`}
header={this.getBlockHeader(item, index)}
>
{editor}
</Panel>
);
}
console.warn(`No method ${method} defined, cannot get story block with type ${item.template}`);
})
}
<hr />
<Panel header='Add a new block'>
<InputWidget
type='select'
name='blockTemplate'
ref='blockTemplate'
onChange={this.onAddBlock.bind(this)}
>
<option value=''>Choose the template to add</option>
{blockTypes.map((type, index) => {
if (this.props.disabled.indexOf(type.template) !== -1) {
return null;
}
if (this.props.enabled.length && this.props.disabled.indexOf(type.template) === -1) {
return null;
}
return (
<option value={type.template} key={`template-${type.template}-${index}`}>{type.label}</option>
);
})}
</InputWidget>
</Panel>
</div>
);
}
}
<file_sep>import React from 'react';
import BaseWidget from './BaseWidget';
export default class ContentBlock extends BaseWidget {
static propTypes = {
align: React.PropTypes.string,
children: React.PropTypes.oneOfType([
React.PropTypes.object,
React.PropTypes.array
]),
className: React.PropTypes.string,
fullheight: React.PropTypes.bool,
id: React.PropTypes.string
};
static defaultProps = {
align: 'left'
};
validate(props) {
if (['left', 'center', 'right'].indexOf(props.align) === -1) {
throw new Error('Allowed values for "align" are "left", "center" and "right"');
}
}
renderWidget() {
let classes = [
'widget',
'content-block',
this.props.align
];
if (this.props.className) {
classes.push(this.props.className);
}
if (this.props.fullheight) {
classes.push('full-height');
}
let props = {
className: classes.join(' ')
};
if (this.props.id) {
props.id = this.props.id;
}
return (
<div {...props}>
<div className='width-wrapper'>
{this.props.children}
</div>
</div>
);
}
}
<file_sep>exports.extendSchema = function (schema) {
require('util')._extend((schema.methods || {}), {
/**
* Request ACL implementations
**/
is(user, requirements, done) {
var status = false;
requirements.forEach((requirementKey) => {
if (requirementKey === 'creator' || requirementKey === 'self') {
requirementKey = '_id';
}
let compId = this[requirementKey];
if (requirementKey !== '_id') {
if (this[requirementKey]._id) {
compId = this[requirementKey]._id;
}
}
if (compId.toString() === user._id.toString()) {
status = true;
}
});
done(null, status);
},
can(user, requirement, done) {
if (requirement === 'edit' || requirement === 'modify') {
return this.is(user, ['self'], done);
}
done(null, false);
}
});
};
<file_sep>import React from 'react';
import { Link } from 'react-router';
// import Columns from '../../../common/components/Widgets/Columns';
import ContentBlock from '../../../common/components/Widgets/ContentBlock';
import Icon from '../../../common/components/Widgets/Icon';
import Image from '../../../common/components/Widgets/Image';
import PartnersForm from './Form';
import Modal from '../../../common/components/Widgets/Modal';
import DOMManipulator from '../../../common/DOMManipulator';
import { setPageTitle } from '../../../common/Helpers';
export default class ContentPartners extends React.Component {
static contextTypes = {
router: React.PropTypes.func
};
constructor() {
super();
this.displayForm = this.displayForm.bind(this);
}
componentDidMount() {
this.button = new DOMManipulator(this.refs.button);
this.button.addEvent('click', this.displayForm, true);
setPageTitle('Become our partner');
}
componentWillUnmount() {
this.button.removeEvent('click', this.displayForm, true);
}
createModal() {
return (
<Modal className='white with-overflow contact-form'>
<PartnersForm context={this.context} />
</Modal>
);
}
displayForm(e) {
e.preventDefault();
e.stopPropagation();
this.modal = this.createModal();
this.modalContainer = null;
this.preloaded = {};
// Create the modal
React.render(this.modal, document.getElementById('modals'));
return false;
}
render() {
let image = {
url: 'https://res.cloudinary.com/homehapp/image/upload/v1441014109/site/images/icons/icon_mobile_large.svg',
alt: ''
};
return (
<ContentBlock className='padded' align='left' valign='top'>
<div className='center'>
<Icon type='clipboard' className='large' />
</div>
<h1>Why Homehapp?</h1>
<p>
Homehapp is a platform for buyers and sellers, landlords and
tenants, Estate agents, legal conveyancers, chartered surveyors.
Expand your reach and increase your sales.
</p>
<div className='centered'>
<Image {...image} />
</div>
<p className='call-to-action'>
<Link className='button transparent' to='partnersContact' ref='button'>Get in contact & share us your details</Link>
</p>
</ContentBlock>
);
}
}
<file_sep>/*eslint-env es6 */
import React from 'react';
import Router from 'react-router';
let {Route, DefaultRoute, NotFoundRoute} = Router;
import Application from './Application';
import Lander from './Homepage/Lander';
import Homepage from './Homepage';
// Home handlers
import HomeContainer from './Home/HomeContainer';
import HomeContactContainer from './Home/HomeContactContainer';
import HomeDetailsContainer from './Home/HomeDetailsContainer';
import HomeStoryContainer from './Home/HomeStoryContainer';
import HomeSearch from './Home/HomeSearch';
import HomeStories from './Home/HomeStories';
import RouteNotFound from './ErrorPages/RouteNotFound';
// Forms
import HomeOwner from './Forms/HomeOwner';
// Neighborhoods handlers
import CityContainer from './City/CityContainer';
import NeighborhoodList from './Neighborhood/NeighborhoodList';
import NeighborhoodContainer from './Neighborhood/NeighborhoodContainer';
import NeighborhoodHomeFilterContainer from './Neighborhood/NeighborhoodHomeFilterContainer';
import Login from './User/Login';
import Logout from './User/Logout';
import Partners from './Partners';
import PartnersContact from './Partners/Contact';
// MIscellaneous other handlers
import Page from './Page';
module.exports = (
<Route name='app' path='/' handler={Application}>
<DefaultRoute handler={Lander}/>
<Route name='homepage' path='/mainpage' handler={Homepage} />
<Route name='user' path='/auth'>
<Route name='login' path='login' handler={Login} />
<Route name='logout' path='logout' handler={Logout} />
</Route>
<Route name='auth' path='/auth'>
<Route name='authLogin' path='login' handler={Login} />
</Route>
<Route name='homes' path='/homes'>
<Route name='contactLetting' path='letting' handler={HomeOwner} />
<Route name='contactSelling' path='selling' handler={HomeOwner} />
<Route name='home' path=':slug'>
<Route name='homeDetails' path='details' handler={HomeDetailsContainer} />
<Route name='homeStory' path='story' handler={HomeStoryContainer} />
<Route name='homeForm' path='contact' handler={HomeContactContainer} />
<DefaultRoute handler={HomeContainer}/>
<NotFoundRoute handler={RouteNotFound} />
</Route>
<DefaultRoute handler={HomeSearch} />
<NotFoundRoute handler={RouteNotFound} />
</Route>
<Route name='search' path='/search'>
<Route name='homeStories' path='stories' handler={HomeStories} />
<Route name='searchMode' path=':mode' handler={HomeSearch} />
<DefaultRoute handler={HomeSearch} />
<NotFoundRoute handler={RouteNotFound} />
</Route>
<Route name='neighborhoods' path='/neighborhoods'>
<Route name='cityList' path='' handler={CityContainer} />
<Route name='neighborhoodList' path=':city' handler={NeighborhoodList} />
<Route name='neighborhoodView' path=':city/:neighborhood' handler={NeighborhoodContainer} />
<Route name='neighborhoodViewHomes' path=':city/:neighborhood/homes' handler={NeighborhoodHomeFilterContainer} />
<DefaultRoute handler={CityContainer} />
<NotFoundRoute handler={RouteNotFound} />
</Route>
<Route name='partners' path='/partners' handler={Partners}>
<Route name='partnersContact' path='contact' handler={PartnersContact} />
<DefaultRoute handler={Partners} />
</Route>
<Route name='page' path=':slug' handler={Page} />
<NotFoundRoute handler={RouteNotFound} />
</Route>
);
<file_sep>'use strict';
import should from 'should';
import expect from 'expect.js';
import testUtils from '../utils';
import MockupData from '../../MockupData';
let app = null;
let debug = require('debug')('User/Authentication API paths');
describe('User/Authentication API paths', () => {
let body = null;
let home = null;
let user = null;
let userData = {
service: 'facebook',
user: {
id: 'tester',
email: '<EMAIL>',
token: '<PASSWORD>',
displayName: '<NAME>'
}
};
before((done) => {
testUtils.createApp((err, appInstance) => {
app = appInstance;
app.mockup.removeAll('Home', {
'_service.facebook.id': 'vapaaradikaali'
})
.then(() => {
done(err);
})
.catch((err) => {
console.error('Failed to delete homes');
done(err);
});
});
});
it('Should deny basic HTTP request without added headers', (done) => {
app.basicRequest('get', '/api/auth/check')
.expect(403)
.end((err, res) => {
should.not.exist(err);
done();
});
});
it('Should accept the unauthenticated request', (done) => {
app.mobileRequest('get', '/api/auth/check')
.expect(403)
.end((err, res) => {
should.not.exist(err);
done();
});
});
it('Should create a new user', (done) => {
app.mobileRequest('post', '/api/auth/login')
.send(userData)
.expect(200)
.end((err, res) => {
should.not.exist(err);
should(res.body).have.property('session');
should(res.body.session).have.property('user');
user = res.body.session.user;
should(user).have.property('id');
should(res.body).have.property('home');
home = res.body.home;
expect(home.createdBy.id).to.be(user.id);
done();
});
});
it('Should not recreate the same user again', (done) => {
app.mobileRequest('post', '/api/auth/login')
.send(userData)
.expect(200)
.end((err, res) => {
should.not.exist(err);
should(res.body).have.property('session');
should(res.body.session).have.property('user');
expect(res.body.session.user.id).to.be(user.id);
should(res.body.session.user).have.property('id');
should(res.body).have.property('home');
expect(res.body.home.createdBy.id).to.be(res.body.session.user.id);
expect(res.body.home.id).to.be(home.id);
done();
});
});
// Breaking changes in 1.0.1
it('Should return a string for 1.0.0', (done) => {
app.mobileRequest('post', '/api/auth/login', '1.0.0')
.send(userData)
.expect(200)
.end((err, res) => {
should.not.exist(err);
should(res.body).have.property('session');
should(res.body.session).have.property('user');
expect(res.body.session.user.id).to.be(user.id);
should(res.body.session.user).have.property('id');
should(res.body).have.property('home');
expect(res.body.home.createdBy).to.be(res.body.session.user.id);
expect(res.body.home.id).to.be(home.id);
done();
});
});
let updateValues = {
user: {
email: '<EMAIL>',
firstname: 'Lorem',
lastname: 'Ipsum',
profileImage: {
url: 'https://www.homehapp.com/',
alt: 'Test image',
width: 300,
height: 300
},
contact: {
phone: '+1 23 456 7890',
address: {
street: 'Lorem',
city: 'London',
zipcode: '01234',
country: 'GB'
}
}
}
};
it('Should be possible to update the user', (done) => {
app.authRequest('put', '/api/auth/user')
.send(updateValues)
.expect(200)
.end((err, res) => {
should.not.exist(err);
should(res.body).have.property('user');
MockupData.compare(updateValues.user, res.body.user);
done();
});
});
it('Should return the updated user on check', (done) => {
app.authRequest('get', '/api/auth/user')
.expect(200)
.end((err, res) => {
should.not.exist(err);
should(res.body).have.property('user');
MockupData.compare(updateValues.user, res.body.user);
done();
});
});
});
<file_sep>/*eslint-env es6 */
import React from 'react';
// Property List
import HomeList from '../Home/HomeList';
// Story widgets
import BigImage from '../../../common/components/Widgets/BigImage';
import Icon from '../../../common/components/Widgets/Icon';
import LargeText from '../../../common/components/Widgets/LargeText';
import { setPageTitle } from '../../../common/Helpers';
// let debug = require('../../../common/debugger')('NeighborhoodHomeFilter');
export default class NeighborhoodHomeFilter extends React.Component {
static propTypes = {
neighborhood: React.PropTypes.object.isRequired
};
componentDidMount() {
if (this.props.neighborhood && this.props.neighborhood.location && this.props.neighborhood.location.city && this.props.neighborhood.location.city.title) {
setPageTitle(`Homes in ${this.props.neighborhood.title} | Neighbourhoods of ${this.props.neighborhood.location.city.title}`);
}
}
componentWillUnmount() {
setPageTitle();
}
render() {
let neighborhood = this.props.neighborhood;
let image = neighborhood.mainImage;
for (let home of neighborhood.homes) {
home.location.neighborhood = neighborhood;
}
return (
<div className='neighborhoods-home-filter'>
<BigImage image={image} gradient='black' fixed={false} proportion={0.5}>
<LargeText align='center' valign='middle' proportion={0.5}>
<Icon type='marker' color='black' size='large' />
<h1>{neighborhood.title}</h1>
<p>Homes</p>
</LargeText>
</BigImage>
<HomeList items={neighborhood.homes} />
</div>
);
}
}
<file_sep>/*global window, process */
let debug = require('./debugger')('Cache');
let getTimestamp = () => {
return Math.round((new Date()).getTime() / 1000);
};
let hasLocalStorageSupport = () => {
try {
return 'localStorage' in window && window.localStorage !== null;
} catch (e) {
return false;
}
};
class CacheStorage {
constructor(config) {
this.config = config;
this.initialize();
}
initialize() {}
hasValue(/*group, key*/) {
return false;
}
getValue(/*group, key*/) {
return null;
}
setValue(/*group, key, value*/) {
return false;
}
_isValidItem(cachedItem) {
let tsNow = getTimestamp();
if ((tsNow - cachedItem.timestamp) < this.config.ttl) {
if (cachedItem.data !== null) {
return true;
}
}
return false;
}
}
class LocalStorage extends CacheStorage {
initialize() {
this._storage = window.localStorage;
}
hasValue(group, key) {
let groupKey = this._generateGroupKey(group, key);
let cachedValue = JSON.parse(this._storage.getItem(groupKey));
if (!cachedValue) {
return false;
}
return this._isValidItem(cachedValue);
}
getValue(group, key) {
if (!this.hasValue(group, key)) {
return null;
}
let groupKey = this._generateGroupKey(group, key);
let cachedValue = JSON.parse(this._storage.getItem(groupKey));
if (!cachedValue) {
return null;
}
return cachedValue.data;
}
setValue(group, key, value) {
let groupKey = this._generateGroupKey(group, key);
let cachedValue = {
timestamp: getTimestamp(),
data: value
};
try {
this._storage.setItem(groupKey, JSON.stringify(cachedValue));
} catch (err) {
if (err.code === 'QUOTA_EXCEEDED_ERR') {
this._storage.clear();
return false;
}
}
return true;
}
_generateGroupKey(group, key) {
return `${group}.${key}`;
}
}
class MemoryStorage extends CacheStorage {
initialize() {
this._storage = {};
}
hasValue(group, key) {
this._prepareGroup(group);
if (!this._storage[group].hasOwnProperty(key)) {
return false;
}
let cachedValue = this._storage[group][key];
return this._isValidItem(cachedValue);
}
getValue(group, key) {
this._prepareGroup(group);
if (!this.hasValue(group, key)) {
return null;
}
let cachedValue = this._storage[group][key];
return cachedValue.data;
}
setValue(group, key, value) {
this._prepareGroup(group);
let cachedValue = {
timestamp: getTimestamp(),
data: value
};
this._storage[group][key] = cachedValue;
return true;
}
_prepareGroup(group) {
if (!this._storage[group]) {
this._storage[group] = {};
}
}
}
class Cache {
constructor() {
this.ttl = 60 * 60; // 1 hour
this._enabled = true;
this._configureStorage();
}
disable() {
this._enabled = false;
}
enable() {
this._enabled = true;
}
has(group, key) {
debug('has', group, key);
if (!this._enabled) {
return false;
}
return this.storage.hasValue(group, key);
}
get(group, key) {
debug('get', group, key);
if (!this._enabled) {
return null;
}
return this.storage.getValue(group, key);
}
set(group, key, value) {
debug('set', group, key);
if (!this._enabled) {
return false;
}
return this.storage.setValue(group, key, value);
}
_configureStorage() {
if (hasLocalStorageSupport()) {
this.storage = new LocalStorage({
ttl: this.ttl
});
} else {
this.storage = new MemoryStorage({
ttl: this.ttl
});
}
}
}
let cacheInstance = new Cache();
if (process.env.DEBUG) {
cacheInstance.disable();
}
module.exports = cacheInstance;
<file_sep>import async from 'async';
/**
* Common QueryBuilder which different Database implementations
* base classes extend from.
*/
export default class CommonQueryBuilder {
constructor(app, modelName) {
this._app = app;
this._queries = [];
this._opts = {};
this._loadedModel = null;
this.Model = app.db.getModel(modelName);
this.result = {
queryBuilder: this
};
}
/**
* Limit query results by number
* @param {number} limit Limit results to number of items
*/
limit(limit) {
this._opts.limit = parseInt(limit);
return this;
}
/**
* Sort query result
* @param {{"sortBy": "order"}} sort Sort by rules
*/
sort(sort) {
this._opts.sort = sort;
return this;
}
/**
* Skip query results items by number
* @param {number} skipCount How many items to skip
*/
skip(skipCount) {
this._opts.skip = parseInt(skipCount);
return this;
}
/**
* Execute fetch
*/
fetch() {
return this._executeTasks();
}
/**
* Execute count
*/
count() {
this._opts.count = true;
return this._executeTasks();
}
/**
* Parse common request query arguments and translate them to
* search query arguments.
* req.query.sort String 'asc|desc' (defaults to desc)
* req.query.sortBy String (defaults to updatedAt)
* req.query.limit Number
* req.query.skip Number
* @param {object} req Express.js Request object
*/
parseRequestArguments(req) {
// Here we allow this convenience handling to sort ascendingly by the updatedAt value
if (req.query.sort || req.query.sortBy) {
let sortBy = req.query.sortBy || 'updatedAt';
let order = 'desc';
if (req.query.sort === 'asc') {
order = 'asc';
}
let sort = {};
sort[sortBy] = order;
this.sort(sort);
}
if (req.query.limit) {
this.limit(req.query.limit);
}
if (req.query.skip) {
this.skip(req.query.skip);
}
return this;
}
/**
* This is called after model is created and updated, right after saving model.
* override this to do extras after shaving the model.
* @param data that was used when creating/updating model
* @param callback
*/
afterSave(data, callback){
callback();
return this;
}
/**
* This is called before model is removed,
* override this to do extras before removing model.
* @param callback
*/
beforeRemove(callback){
callback();
return this;
}
/**
* @param data Object
*/
create() {
throw new Error('not implemented');
}
/**
* @param data Object
*/
update() {
throw new Error('not implemented');
}
remove() {
throw new Error('not implemented');
}
_executeTasks() {
return new Promise((resolve, reject) => {
async.series(this._queries, (err) => {
this._queries = [];
if (err) {
return reject(err);
} else {
resolve(this._opts.count ? this.result.count : this.result);
}
});
});
}
_save() {
return new Promise((resolve, reject) => {
async.series(this._queries, (err) => {
this._queries = [];
if (err) {
return reject(err);
} else {
resolve(this._loadedModel);
}
});
});
}
}
<file_sep>import QueryBuilder from '../../lib/QueryBuilder';
import { setLastMod, initMetadata } from '../../../clients/common/Helpers';
import HomesAPI from '../../api/HomesAPI';
let debug = require('debug')('/');
import {Forbidden} from '../../lib/Errors';
exports.registerRoutes = (app) => {
const QB = new QueryBuilder(app);
let api = new HomesAPI(app, QB);
// Remove the trailing slash as React
app.get('*/', function(req, res, next) {
debug('GET *', req.url);
if (!req.url.match(/^\/($|\?)/) && req.url.match(/\/($|\?)/)) {
let url = req.url.replace(/\/($|\?)/, '$1');
return res.redirect(301, url);
}
next();
});
app.get('*', function(req, res, next) {
if (req.url.toString() !== '/' && !req.url.toString().match(/^\/auth/) && !req.isAuthenticated()) {
debug('Authentication required');
return next(new Forbidden('Not authenticated'));
}
next();
});
app.get('/', function(req, res, next) {
debug('GET /');
api.listHomes(req, {
populate: {}
})
.then((homes) => {
debug(`Got ${homes.length} homes`);
initMetadata(res);
res.locals.data.HomeListStore = {
items: homes
};
res.locals.page = {
title: 'Discover y',
description: 'Homehapp - discover y'
};
setLastMod([].concat(homes).concat(res.locals.data.HomeListStore), res);
next();
//
// return QB
// .forModel('Neighborhood')
// .query({
// enabled: true
// })
// .findAll()
// .fetch();
// })
// .then((result) => {
// res.locals.data.NeighborhoodListStore = {
// items: result.models
// };
// setLastMod([].concat(result.models).concat(res.locals.data.HomeListStore), res);
//
// // return res.json(res.locals.data);
// next();
});
});
};
<file_sep>import React from 'react';
import { Link } from 'react-router';
import Row from 'react-bootstrap/lib/Row';
import Nav from 'react-bootstrap/lib/Nav';
import SubNavigationWrapper from '../Navigation/SubNavigationWrapper';
// import NavItemLink from 'react-router-bootstrap/lib/NavItemLink';
import { setPageTitle } from '../../../common/Helpers';
class UsersIndex extends React.Component {
static propTypes = {
users: React.PropTypes.array.isRequired
}
constructor(props) {
super(props);
}
componentDidMount() {
setPageTitle('User management');
}
render() {
return (
<SubNavigationWrapper>
<Nav sidebar>
<h2 className='navigation-title'>
Users
</h2>
<p>There are {this.props.users.length} users in the system currently.</p>
<ul>
<li><Link to='userCreate'><i className='fa fa-user'></i> Create a new user</Link></li>
</ul>
</Nav>
<Row>
<h1><i className='fa fa-user'></i> {this.props.users.length} users</h1>
<ul>
{this.props.users.map((user, i) => {
return (
<li key={i}>
<Link
to='userEdit'
params={{id: user.id}}>
{user.displayName}
</Link>
</li>
);
})}
</ul>
</Row>
</SubNavigationWrapper>
);
}
}
export default UsersIndex;
<file_sep>import path from 'path';
import fs from 'fs';
import http from 'http';
import express from 'express';
// For Isomorphic React
import React from 'react';
import Router from 'react-router';
import Iso from 'iso';
import Configuration from './lib/Configuration';
import Helpers from './lib/Helpers';
import Errors from './lib/Errors';
import Logger from './lib/Logger';
import bodyParser from 'body-parser';
let PROJECT_NAME = 'site';
let PROJECT_ROOT = path.resolve(__dirname, '..');
let COMMON_CLIENT_ROOT = path.resolve(PROJECT_ROOT, 'clients', 'common');
let STATICS_ROOT = path.resolve(PROJECT_ROOT, 'build', 'statics');
if (path.basename(PROJECT_ROOT) === 'build') {
STATICS_ROOT = path.resolve(PROJECT_ROOT, 'statics');
}
const SOURCE_PATH = __dirname;
let CLIENT_ROOT = null;
let PROJECT_REVISION = null;
let debug = require('debug')('app');
exports.run = function(projectName, afterRun) {
PROJECT_NAME = projectName || 'site';
CLIENT_ROOT = path.resolve(PROJECT_ROOT, 'clients', PROJECT_NAME);
if (typeof afterRun !== 'function') {
afterRun = () => {};
}
Configuration.load(PROJECT_ROOT, PROJECT_NAME, path.join(PROJECT_ROOT, 'config'), {}, function (configError, config) {
if (configError) {
throw configError;
}
process.env.DEBUG = process.env.DEBUG || true;
if (config.env === 'production') {
process.env.DEBUG = false;
}
let app = module.exports.app = express();
app.config = config;
app.server = http.createServer(app);
app.PROJECT_NAME = PROJECT_NAME;
app.PROJECT_ROOT = PROJECT_ROOT;
app.SOURCE_PATH = SOURCE_PATH;
app.set('trust proxy', 1);
/**
* Configure templating if views folder is present
*/
let viewsFolder = path.join(PROJECT_ROOT, 'views', PROJECT_NAME);
if (config.isomorphic.enabled) {
viewsFolder = path.join(CLIENT_ROOT, 'templates');
}
if (fs.existsSync(viewsFolder)) {
let ejs = require('ejs');
app.set('view engine', 'html');
app.set('views', viewsFolder);
app.engine('html', ejs.renderFile);
let partials = require('express-partials');
partials.register('.html', ejs.render);
app.use(partials());
if (!config.isomorphic.enabled) {
app.use(require('express-layout')());
}
}
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
function resolveCurrentRevision() {
return new Promise((resolve) => {
PROJECT_REVISION = require('moment')().format('YYYYMMDD');
app.PROJECT_REVISION = PROJECT_REVISION;
let revPath = path.join(PROJECT_ROOT, 'BUILD_REVISION');
fs.readFile(revPath, (err, content) => {
if (err) {
return resolve(PROJECT_REVISION);
}
if (content) {
PROJECT_REVISION = parseInt(content);
}
app.PROJECT_REVISION = PROJECT_REVISION;
return resolve(PROJECT_REVISION);
});
});
}
function configureLogger() {
return new Promise((resolve) => {
debug('configureLogger');
let logger = new Logger(config.logging);
// Add external logging transports here
// ie. logger.addTransport('Loggly', require('winston-loggly').Loggly);
logger.configure(app).then(() => resolve());
});
}
function connectToDatabase() {
return new Promise((resolve, reject) => {
debug('connectToDatabase');
if (!app.config.database.adapter) {
debug('no database adapter configured');
return resolve();
}
require(path.join(SOURCE_PATH, 'lib', 'Database')).configure(app, app.config.database)
.then(() => resolve() )
.catch((err) => {
app.log.error(`Unable to configure database!: ${err.message}`, err);
reject(err);
});
});
}
function setupStaticRoutes() {
return new Promise((resolve, reject) => {
debug('setupStaticRoutes');
let tasks = [];
if (app.config.cdn.adapter) {
tasks.push(
require(path.join(SOURCE_PATH, 'lib', 'Middleware', 'CDN')).configure(app, app.config.cdn)
);
}
Promise.all(tasks)
.then(() => {
let staticPath = '/public';
let revStaticPath = '/public';
if (app.config.env !== 'development') {
if (app.cdn && app.cdn.getStaticPath) {
staticPath = app.cdn.getStaticPath();
revStaticPath = `${staticPath}/v${app.PROJECT_REVISION}/${app.PROJECT_NAME}`;
}
}
app.staticPath = staticPath;
app.revisionedStaticPath = revStaticPath;
let staticDir = path.join(STATICS_ROOT, app.PROJECT_NAME);
if (app.config.env === 'development') {
app.use(staticPath, express.static(staticDir));
}
let faviconImage = path.join(staticDir, 'images', 'favicon.ico');
if (fs.existsSync(faviconImage)) {
let favicon = require('serve-favicon');
app.use(favicon(faviconImage));
}
resolve();
})
.catch(reject);
});
}
function configureMiddleware() {
return new Promise((resolve, reject) => {
debug('configureMiddleware');
if (config.isomorphic.enabled) {
app.use(function prepareResData(req, res, next) {
if (!res.locals.data) {
res.locals.data = {};
}
next();
});
}
if (app.config.authentication && app.config.authentication.adapters.length) {
let AuthenticationMiddleware = require(path.join(SOURCE_PATH, 'lib', 'Middleware', 'Authentication'));
let amInstance = new AuthenticationMiddleware(app, config.authentication);
app.authentication = amInstance.register();
}
let tasks = [];
tasks.push(
require(path.join(SOURCE_PATH, 'lib', 'Middleware', 'Security')).configure(app, app.config.security)
);
if (app.config.google.enabled) {
tasks.push(
require(path.join(SOURCE_PATH, 'lib', 'Middleware', 'Google')).configure(app, app.config.google)
);
}
if (app.config.versioning.enabled) {
tasks.push(
require(path.join(SOURCE_PATH, 'lib', 'Middleware', 'Versioning')).configure(app, app.config.versioning)
);
}
if (app.config.docs) {
tasks.push(
require(path.join(SOURCE_PATH, 'lib', 'Middleware', 'Documentation')).configure(app, app.config.docs)
);
}
if (app.config.firstRun && app.config.firstRun[PROJECT_NAME]) {
let firstRunConfig = app.config.firstRun[PROJECT_NAME];
tasks.push(
require(path.join(SOURCE_PATH, 'lib', 'Middleware', 'FirstRun')).configure(app, firstRunConfig)
);
}
return Promise.all(tasks)
.then(() => resolve())
.catch((err) => reject(err));
});
}
function setupExtensions() {
let tasks = [];
debug('setupExtensions');
let extensionsDir = path.join(SOURCE_PATH, 'extensions');
if (fs.existsSync(extensionsDir)) {
Helpers.listDirSync(extensionsDir)
.forEach((extensionName) => {
tasks.push(
new Promise((resolve, reject) => {
debug(`Loading extension ${extensionName}`);
let extConfig = {};
if (app.config.extensions && app.config.extensions[extensionName]) {
extConfig = app.config.extensions[extensionName];
}
return require(path.join(extensionsDir, extensionName)).register(app, extConfig)
.then( () => resolve() )
.catch( (err) => reject(err) );
})
);
});
}
return Promise.all(tasks);
}
function setupRoutes() {
return new Promise((resolve, reject) => {
debug('setupRoutes');
let routerFiles = Helpers.walkDirSync(path.join(SOURCE_PATH, '/routes/common'), {
ext: ['.js']
});
let projectRoutesPath = path.join(SOURCE_PATH, '/routes', app.PROJECT_NAME);
if (require('fs').existsSync(projectRoutesPath)) {
var projectRouterFiles = Helpers.walkDirSync(projectRoutesPath, {
ext: ['.js']
});
routerFiles = routerFiles.concat(projectRouterFiles);
}
routerFiles.forEach((rf) => {
let router;
try {
router = require(rf);
} catch(err) {
app.log.error('Unable to load router ' + rf + ': ' + err.message);
if (app.config.env === 'development') {
app.log.error(err.stack);
}
return reject(err);
}
if (!router || !router.registerRoutes || typeof router.registerRoutes !== 'function') {
return resolve();
}
try {
router.registerRoutes(app);
} catch (err) {
app.log.error('Unable to register routes from router ' + rf + ': ' + err.message);
if (app.config.env === 'development') {
app.log.error(err.stack);
}
return reject(err);
}
});
if (config.isomorphic.enabled) {
app.get('*', function populateCommonData(req, res, next) {
debug('populateCommonData');
if (!res.locals.metadatas) {
res.locals.metadatas = [];
}
let openGraph = {
'og:title': 'Homehapp',
'og:type': 'article',
'og:url': req.protocol + '://' + req.get('host') + req.originalUrl,
'og:site_name': 'Homehapp',
'og:locale': 'en_GB',
'og:image': [
'https://res.cloudinary.com/homehapp/image/upload/v1443094360/site/images/content/site-photo.jpg'
],
'fb:app_id': '151239851889238'
};
if (!res.locals.openGraph) {
res.locals.openGraph = {};
}
// Merge with OpenGraph defaults
for (let k in openGraph) {
if (Array.isArray(res.locals.openGraph[k])) {
res.locals.openGraph[k] = res.locals.openGraph[k].concat(openGraph[k]);
continue;
}
if (typeof res.locals.openGraph[k] !== 'undefined') {
continue;
}
res.locals.openGraph[k] = openGraph[k];
}
if (!res.locals.data) {
res.locals.data = {
title: []
};
}
if (!res.locals.styleSheets) {
res.locals.styleSheets = [];
}
if (app.authentication) {
if (!res.locals.data.AuthStore) {
res.locals.data.AuthStore = {};
}
res.locals.data.AuthStore.loggedIn = !!(req.user);
if (req.user) {
res.locals.data.AuthStore.user = req.user.publicData || {};
}
}
next();
});
}
if (config.isomorphic.enabled) {
app.use(function mainRoute(req, res, next) {
debug('mainRoute', req.skipMain);
if (req.skipMain) {
return next();
}
let alt = require(path.join(COMMON_CLIENT_ROOT, 'alt.js'));
alt.foo = 'bar';
var iso = new Iso();
if (!res.locals.data.ApplicationStore) {
res.locals.data.ApplicationStore = {};
}
if (app.config.security.csrf && req.csrfToken) {
res.locals.data.ApplicationStore.csrf = req.csrfToken();
}
if (req.query.redirectUrl) {
res.locals.data.ApplicationStore.redirectUrl = req.query.redirectUrl;
}
if (req.body && req.body.redirectUrl) {
res.locals.data.ApplicationStore.redirectUrl = req.body.redirectUrl;
}
debug('ApplicationStore', res.locals.data.ApplicationStore);
let clientConfig = app.config.clientConfig || {};
// Extra configs could be defined here
clientConfig = Helpers.merge(clientConfig, {
revisionedStaticPath: app.revisionedStaticPath
});
res.locals.data.ApplicationStore.config = clientConfig;
// debug('clientConfig', clientConfig);
// debug('res.locals.data', res.locals.data);
// debug('res.locals.metadatas', res.locals.metadatas);
let routes = require(path.join(CLIENT_ROOT, 'components/Routes'));
alt.bootstrap(JSON.stringify(res.locals.data));
// let snapshot = alt.takeSnapshot();
Router.run(routes, req.url, function (Handler) {
let content = React.renderToString(React.createElement(Handler));
iso.add(content, alt.flush());
let html = iso.render();
app.getLocals(req, res, {
html: html,
includeClient: true,
metadatas: res.locals.metadatas
})
.then((locals) => {
// debug('locals', locals);
res.render('index', locals);
});
});
});
}
app.use(function errorHandler(err, req, res, next) {
debug('errorHandler', err);
var code = err.statusCode || 422;
var msg = err.message || 'Unexpected error has occurred!';
var payload = msg;
var isJSONRequest = (req.xhr || req.headers['content-type'] === 'application/json');
app.log.error(
`Error handler received: ${err.message} (${err.code})`, err
);
if (err.code === 'EBADCSRFTOKEN') {
code = 403;
msg = 'Request was tampered!';
}
let handleUnauthenticatedGetRequest = function() {
if ([403].indexOf(code) !== -1) {
if (app.authenticationRoutes) {
let url = encodeURIComponent(req.url);
let redirectUrl = `${app.authenticationRoutes.login}?message=${msg}&redirectUrl=${url}`;
res.redirect(redirectUrl);
return true;
}
}
return false;
};
let prepareJSONError = function() {
payload = {
status: 'failed', error: msg, data: {
name: err.name
}
};
if (err.stack && app.config.env === 'development') {
payload.data.stack = err.stack;
}
if (err instanceof Errors.BaseError) {
var errors = err.data && err.data.errors;
if (errors) {
var fields = {};
Object.keys(errors).forEach(function (field) {
fields[field] = {
message: errors[field]
};
});
payload.data.fields = fields;
}
}
else if (err.message.match(/Duplicate primary key/)) {
payload.error = err.message.split('\n')[0];
payload.error = payload.error.substr(0, payload.error.length - 1);
}
else if (err.name === 'ValidationError') {
if (err.errors) {
payload.data.fields = {};
Object.keys(err.errors).forEach(function (field) {
payload.data.fields[field] = {
message: err.errors[field].message,
path: err.errors[field].path,
type: err.errors[field].type
};
});
}
}
return payload;
};
if (isJSONRequest) {
payload = prepareJSONError();
} else if (handleUnauthenticatedGetRequest()) {
return resolve();
}
if (err.stack && app.config.env !== 'production') {
app.log.error('Error stacktrace: ', err.stack);
}
if (!app.config.errors.includeData) {
delete payload.data;
}
res.status(code).send(payload);
});
resolve();
});
}
function additionalConfig() {
return new Promise((resolve) => {
debug('additionalConfig');
let pageTitle = 'Homehapp';
if (projectName === 'admin') {
pageTitle = 'Homehapp - Admin';
}
app.locals.site = {
title: pageTitle
};
resolve();
});
}
// Application initialization flow
resolveCurrentRevision()
.then( () => configureLogger() )
.then( () => connectToDatabase() )
.then( () => setupStaticRoutes() )
.then( () => configureMiddleware() )
.then( () => setupExtensions() )
.then( () => setupRoutes() )
.then( () => additionalConfig() )
.then( () => {
debug('Application initialization flow done!');
app.log.info(`Current project revision: ${PROJECT_REVISION}`);
//app.log.debug('Using configuration', app.config);
if (app.config.env !== 'test') {
app.server.listen(app.config.port, function() {
app.log.info(`Server listening on port: ${app.config.port}`);
afterRun(app);
});
} else {
afterRun(app);
}
})
.catch(err => {
app.log.error(`Error on initialization flow!: ${err.message}`, err, {stack: err.stack});
// console.error('Error on initialization flow', err);
// console.error(err.stack);
throw err;
});
});
};
if (require.main === module) {
exports.run();
}
<file_sep>import PageActions from '../actions/PageActions';
import PageSource from '../sources/PageSource';
import ModelStore from '../../common/stores/BaseModelStore';
export default ModelStore.generate('PageStore', {
actions: PageActions,
source: PageSource,
listeners: {}
});
<file_sep>import React from 'react';
import Row from 'react-bootstrap/lib/Row';
import Col from 'react-bootstrap/lib/Col';
import Panel from 'react-bootstrap/lib/Panel';
import InputWidget from '../Widgets/Input';
import Button from 'react-bootstrap/lib/Button';
import Well from 'react-bootstrap/lib/Well';
import CityListStore from '../../stores/CityListStore';
import NeighborhoodStore from '../../stores/NeighborhoodStore';
import NeighborhoodActions from '../../actions/NeighborhoodActions';
import ApplicationStore from '../../../common/stores/ApplicationStore';
import UploadArea from '../../../common/components/UploadArea';
import UploadAreaUtils from '../../../common/components/UploadArea/utils';
import { createNotification } from '../../../common/Helpers';
import ImageList from '../Widgets/ImageList';
import EditDetails from '../Shared/EditDetails';
import PlacePicker from '../../../common/components/Widgets/PlacePicker';
let debug = require('../../../common/debugger')('NeighborhoodsEditDetails');
// const countries = require('../../../common/lib/Countries').forSelect();
export default class NeighborhoodsEditDetails extends EditDetails {
static propTypes = {
neighborhood: React.PropTypes.object.isRequired
}
constructor(props) {
super(props);
this.storeListener = this.onNeighborhoodStoreChange.bind(this);
this.uploadListener = this.onUploadChange.bind(this);
this.cityListener = this.onCityStoreChange.bind(this);
this.state.images = props.neighborhood.images;
this.onRemoveImageClicked = this.onRemoveImageClicked.bind(this);
this.setCoordinates = this.setCoordinates.bind(this);
this.enabled = null;
}
state = {
model: null,
error: null,
cities: null,
uploads: UploadAreaUtils.UploadStore.getState().uploads,
currentAttributes: this.props.neighborhood.attributes,
images: []
}
componentDidMount() {
NeighborhoodStore.listen(this.storeListener);
CityListStore.listen(this.cityListener);
setTimeout(() => {
CityListStore.fetchItems();
}, 100);
}
componentWillUnmount() {
NeighborhoodStore.unlisten(this.storeListener);
CityListStore.unlisten(this.cityListener);
}
onNeighborhoodStoreChange(state) {
debug('onNeighborhoodStoreChange', state);
this.setState(state);
}
onCityStoreChange(state) {
debug('onCityStoreChange', state);
this.setState({
cities: state.items || state.cities
});
}
onUploadChange(state) {
debug('onUploadChange', state);
this.setState({
uploads: UploadAreaUtils.UploadStore.getState().uploads
});
}
onFormChange(/*event*/) {
// let {type, target} = event;
// TODO: Validation could be done here
//debug('onFormChange', event, type, target);
//this.props.neighborhood.facilities = this.refs.facilities.getValue().split("\n");
}
onSave() {
debug('save');
for (let key in this.refs) {
let ref = this.refs[key];
if (typeof ref.isValid !== 'function') {
continue;
}
if (!ref.isValid()) {
debug('Validation failed', ref);
let label = ref.props.label || 'Validation error';
let message = ref.message || 'Field failed the validation';
createNotification({
type: 'danger',
duration: 10,
label: label,
message: message
});
return false;
}
}
let images = [];
// Clean broken images
this.state.images.forEach((image) => {
if (image.url) {
images.push(image);
}
});
let neighborhoodProps = {
uuid: this.props.neighborhood.id,
slug: this.refs.slug.getValue(),
title: this.refs.title.getValue(),
enabled: this.enabled,
description: this.refs.description.getValue(),
location: {
coordinates: this.refs.coordinates.getValue(),
city: this.refs.locationCity.getValue() || null
},
images: images
};
console.log('neighborhoodProps', neighborhoodProps);
NeighborhoodActions.updateItem(neighborhoodProps);
}
onCancel() {
React.findDOMNode(this.refs.neighborhoodDetailsForm).reset();
}
getPreviewLink(neighborhood) {
if (!neighborhood || !neighborhood.location || !neighborhood.location.city || !neighborhood.location.city.slug) {
return null;
}
return (
<a href={`${ApplicationStore.getState().config.siteHost}/neighborhoods/${neighborhood.location.city.slug}/${this.props.neighborhood.slug}`}
target='_blank'
className='btn btn-primary'>
Preview
</a>
);
}
render() {
this.handleErrorState();
if (NeighborhoodStore.isLoading()) {
this.handlePendingState();
return null;
}
this.handleRenderState();
let neighborhood = this.state.model || this.props.neighborhood;
this.neighborhood = neighborhood;
let lat = null;
let lng = null;
if (this.state.lat && this.state.lng) {
lat = this.state.lat;
lng = this.state.lng;
} else if (neighborhood.location.coordinates.length) {
lat = neighborhood.location.coordinates[0];
lng = neighborhood.location.coordinates[1];
}
let updateCoords = (lat, lng) => {
this.setState({
lat: lat,
lng: lng
});
};
let selectedCity = null;
let cities = [];
if (neighborhood.location.city) {
cities.push(neighborhood.location.city);
selectedCity = neighborhood.location.city.id;
}
if (Array.isArray(this.state.cities)) {
this.state.cities.map((city) => {
cities.push(city);
});
}
let toggleEnabled = () => {
if (this.state.model) {
this.state.model.enabled = !(neighborhood.enabled);
this.enabled = this.state.model.enabled;
} else {
this.props.neighborhood.enabled = !(neighborhood.enabled);
this.enabled = this.props.neighborhood.enabled;
}
this.forceUpdate();
};
return (
<Row>
<form name='neighborhoodDetails' ref='neighborhoodDetailsForm' method='POST'>
<Col md={10} sm={10}>
<Panel header='Common'>
<InputWidget
type='text'
ref='title'
label='Title'
placeholder='Title (optional)'
defaultValue={neighborhood.title}
onChange={this.onFormChange.bind(this)}
/>
<InputWidget
type='checkbox'
ref='enabled'
label='Enabled'
checked={(neighborhood.enabled)}
onChange={toggleEnabled}
/>
<InputWidget
type='text'
ref='slug'
label='Slug'
placeholder='Slug'
readOnly
defaultValue={neighborhood.slug}
/>
<InputWidget
type='textarea'
ref='description'
label='Description'
placeholder='Write description'
defaultValue={neighborhood.description}
onChange={this.onFormChange.bind(this)}
/>
</Panel>
<Panel header='Location'>
<InputWidget
type='select'
ref='locationCity'
label='City'
onChange={this.onFormChange.bind(this)}
defaultValue={selectedCity}
>
{
cities.map((city, i) => {
return (
<option value={city.id} key={`city-${i}`}>{city.title}</option>
);
})
}
</InputWidget>
<PlacePicker lat={lat} lng={lng} ref='coordinates' onChange={updateCoords} />
<InputWidget
label='Coordinates'
help='Coordinates for the neighborhood' wrapperClassName='wrapper'>
<Row>
<Col xs={6}>
<InputWidget
type='text'
ref='locationLatitude'
readOnly
addonBefore='Latitude:'
value={lat}
/>
</Col>
<Col xs={6}>
<InputWidget
type='text'
ref='locationLongitude'
readOnly
addonBefore='Longitude:'
value={lng}
/>
</Col>
</Row>
</InputWidget>
</Panel>
<Panel header='Images'>
<Row>
<Col md={6}>
<h2>Images</h2>
<ImageList images={this.state.images} onRemove={this.onRemoveImageClicked} onChange={this.onFormChange} />
</Col>
<Col md={6}>
<UploadArea
className='uploadarea image-uploadarea'
signatureFolder='neighborhoodImage'
width='100%'
height='80px'
onUpload={this.onImageUpload.bind(this)}
acceptedMimes='image/*'
instanceId='images'>
<Well>
<p>Drag new image here, or click to select from filesystem.</p>
</Well>
</UploadArea>
</Col>
</Row>
</Panel>
<Well>
<Row>
<Col md={6}>
<Button bsStyle='success' accessKey='s' onClick={this.onSave.bind(this)}>Save</Button>
{this.getPreviewLink(neighborhood)}
</Col>
</Row>
</Well>
</Col>
</form>
</Row>
);
}
}
<file_sep>import React from 'react';
import Button from 'react-bootstrap/lib/Button';
import Row from 'react-bootstrap/lib/Row';
import Col from 'react-bootstrap/lib/Col';
import Panel from 'react-bootstrap/lib/Panel';
import Well from 'react-bootstrap/lib/Well';
import NeighborhoodStore from '../../stores/NeighborhoodStore';
import NeighborhoodActions from '../../actions/NeighborhoodActions';
import InputWidget from '../Widgets/Input';
import { createNotification } from '../../../common/Helpers';
let debug = require('../../../common/debugger')('NeighborhoodsEditArea');
// const countries = require('../../../common/lib/Countries').forSelect();
export default class NeighborhoodsEditArea extends React.Component {
static propTypes = {
neighborhood: React.PropTypes.object.isRequired,
zoom: React.PropTypes.number,
minZoom: React.PropTypes.number,
maxZoom: React.PropTypes.number
}
static defaultProps = {
zoom: 10,
minZoom: 6,
maxZoom: 20,
markers: [],
className: null
};
constructor(props) {
super(props);
this.storeListener = this.onNeighborhoodStoreChange.bind(this);
}
state = {
neighborhood: null
}
componentDidMount() {
NeighborhoodStore.listen(this.storeListener);
this.map = null;
this.mapContainer = React.findDOMNode(this.refs.map);
this.coords = this.props.neighborhood.area;
this.polygon = null;
this.initMap();
}
componentWillUnmount() {
NeighborhoodStore.unlisten(this.storeListener);
}
onNeighborhoodStoreChange(state) {
debug('onNeighborhoodStoreChange', state);
this.setState(state);
}
getCenter() {
let defaultCenter = [51.5072, 0.1275];
if (!this.neighborhood.location.coords || !this.neighborhood.location.coords[0] || !this.neighborhood.location.coords[1]) {
return defaultCenter;
}
return this.neighborhood.location.coords;
}
initMap() {
debug('initMap');
if (this.map) {
return null;
}
if (!this.mapContainer) {
console.error('No map container available');
return false;
}
debug('Map container', this.mapContainer);
let center = this.getCenter();
let options = {
disableDefaultUI: true,
zoomControl: true,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.SMALL,
position: google.maps.ControlPosition.RIGHT_CENTER
},
center: {
lat: center[0],
lng: center[1]
},
zoom: this.props.zoom,
minZoom: this.props.minZoom,
maxZoom: this.props.maxZoom,
scrollWheel: false
};
this.map = new google.maps.Map(this.mapContainer, options);
this.drawPolygon();
this.fitToBounds();
}
onChange() {
debug('onChange');
try {
let value = this.refs.coords.getValue();
if (!value) {
this.neighborhood.area = [];
createNotification({
duration: 5,
message: 'Warning: an empty area defined'
});
return null;
}
let json = JSON.parse(value);
if (!json) {
throw new Error('Failed to parse JSON');
}
// First type check to the JSON: it has to be an array
if (!Array.isArray(json)) {
throw new Error('Only array input is valid');
}
// Validate each item of the JSON
for (let pos of json) {
if (typeof pos.lat === 'undefined' || typeof pos.lng === 'undefined') {
throw new Error(`Position ${JSON.stringify(pos)} did not contain the required keys lat and lng`);
}
}
debug('Got neighborhood polygon', json);
this.neighborhood.area = json;
this.drawPolygon();
} catch (error) {
createNotification({
duration: 5,
message: error.toString(),
type: 'danger'
});
return false;
}
this.fitToBounds();
return true;
}
fitToBounds() {
if (!this.neighborhood.area || !this.neighborhood.area.length) {
return false;
}
let bounds = new google.maps.LatLngBounds();
for (let pos of this.neighborhood.area) {
bounds.extend(new google.maps.LatLng(pos.lat, pos.lng));
}
this.map.fitBounds(bounds);
return true;
}
onSave(event) {
event.preventDefault();
event.stopPropagation();
if (!this.onChange()) {
return false;
}
let props = {
id: this.neighborhood.id,
area: this.neighborhood.area
};
console.log('update with', props);
NeighborhoodActions.updateItem(props);
}
drawPolygon() {
// Destroy the old polygon if available
if (this.polygon) {
this.polygon.setMap(null);
}
if (!this.neighborhood.area || !this.neighborhood.area.length) {
return null;
}
this.polygon = new google.maps.Polygon({
paths: this.neighborhood.area,
strokeColor: '#ff0000',
fillColor: '#ff0000',
strokeOpacity: 0.8,
strokeWeight: 1,
fillOpacity: 0.4
});
this.polygon.setMap(this.map);
}
updateMap() {
debug('Update map');
if (this.map) {
setTimeout(() => {
google.maps.event.trigger(this.map, 'resize');
if (!this.fitToBounds()) {
let center = this.getCenter();
this.map.setCenter({lat: center[0], lng: center[1]});
}
}, 100);
}
}
render() {
this.neighborhood = this.state.neighborhood || this.props.neighborhood;
let coords = this.neighborhood.area || [];
debug('Use coords', coords);
return (
<Row>
<form name='neighborhoodDetails' ref='neighborhoodDetailsForm' method='POST'>
<Col md={10} sm={10}>
<Panel header='Area'>
<div className='map area-display' ref='map' style={{height: '500px'}} />
<InputWidget
type='textarea'
ref='coords'
onBlur={this.onChange.bind(this)}
defaultValue={JSON.stringify(coords)}
/>
</Panel>
<Well>
<Row>
<Col md={6}>
<Button bsStyle='success' accessKey='s' onClick={this.onSave.bind(this)}>Save</Button>
</Col>
</Row>
</Well>
</Col>
</form>
</Row>
);
}
}
<file_sep>import React from 'react';
import BaseWidget from './BaseWidget';
import Columns from './Columns';
import ContentBlock from './ContentBlock';
import Image from './Image';
export default class ContentImage extends BaseWidget {
static propTypes = {
image: React.PropTypes.object.isRequired,
imageAlign: React.PropTypes.string,
children: React.PropTypes.oneOfType([
React.PropTypes.null,
React.PropTypes.object,
React.PropTypes.array
]),
className: React.PropTypes.string
};
static defaultProps = {
imageAlign: 'left'
};
static validate(props) {
Image.validate(props.image);
if (['left', 'right'].indexOf(props.imageAlign) === -1) {
throw new Error('Attribute "imageAlign" has to be either "left" or "right"');
}
return true;
}
renderWidget() {
let left = null;
let right = null;
let classes = [
'content-image',
'with-gradient'
];
let variant = 'half';
let content = (<div className='description'>{this.props.children}</div>);
// Verify that there is any content
if (Array.isArray(this.props.children)) {
let hasContent = false;
for (let i = 0; i < this.props.children.length; i++) {
if (this.props.children[i]) {
hasContent = true;
break;
}
}
if (!hasContent) {
content = null;
variant = 'full';
}
}
let img = {
url: this.props.image.url,
alt: this.props.image.alt,
aspectRatio: this.props.image.aspectRatio
};
// Create the image block, all the data for its creation is now available
let image = (<Image {...img} variant={variant} />);
// If there is no content, display larger image in the center
if (!content) {
classes.push('no-content');
return (
<ContentBlock className={classes.join(' ')}>
{image}
</ContentBlock>
);
}
if (this.props.className) {
classes.push(this.props.className);
}
// Determine the content locations
if (this.props.imageAlign === 'left') {
left = image;
right = content;
classes.push('image-left content-right');
} else {
left = content;
right = image;
classes.push('image-right content-left');
}
return (
<ContentBlock className={classes.join(' ')}>
<Columns cols={2} className='table' valign='middle'>
{left}
{right}
</Columns>
</ContentBlock>
);
}
}
<file_sep>import BaseQueryBuilder from './BaseQueryBuilder';
import {NotFound} from '../../Errors';
let debug = require('debug')('NeighborhoodQueryBuilder');
export default class NeighborhoodQueryBuilder extends BaseQueryBuilder {
constructor(app) {
super(app, 'Neighborhood');
}
initialize() {
}
findByCity(city) {
this._queries.push((callback) => {
let query = {
'location.city': city,
deletedAt: null
};
if (typeof city === 'string') {
query = {
'location.city.slug': city,
deletedAt: null
};
}
let cursor = this.Model.find(query);
this._configurePopulationForCursor(cursor);
cursor.exec((err, neighborhoods) => {
debug(`findByCity found ${neighborhoods.length} neighborhoods`);
if (err) {
debug('Got error', err);
return callback(err);
}
if (!neighborhoods) {
debug('No neighborhoods were found');
neighborhoods = [];
}
this._loadedModel = neighborhoods;
this.result.models = neighborhoods;
this.result.modelsJson = JSON.stringify(neighborhoods.map((neighborhood) => {
return neighborhood.toJson();
}));
this.result.neighborhoods = neighborhoods;
callback();
});
});
return this;
}
findBySlug(slug) {
this._queries.push((callback) => {
let cursor = this.Model.findOne({
slug: slug,
deletedAt: null
});
this._configurePopulationForCursor(cursor);
cursor.exec((err, neighborhood) => {
debug('findBySlug');
if (err) {
debug('Got error', err);
return callback(err);
}
if (!neighborhood) {
debug(`No neighborhood found with slug '${slug}'`);
return callback(new NotFound('Neighborhood not found'));
}
debug(`Found Neighborhood ${neighborhood.title} (${neighborhood._id})`);
this._loadedModel = neighborhood;
this.result.model = neighborhood;
this.result.models = [neighborhood];
this.result.neighborhood = neighborhood;
callback();
});
});
return this;
}
findByUuid(uuid) {
this._queries.push((callback) => {
let cursor = this.Model.findOne({
uuid: uuid,
deletedAt: null
});
this._configurePopulationForCursor(cursor);
cursor.exec((err, model) => {
if (err) {
return callback(err);
}
if (!model) {
return callback(new NotFound('neighborhood not found'));
}
this.result.model = model;
this.result.models = [model];
this.result.neighborhood = model;
this.result.neighborhoodJson = model.toJSON();
this._loadedModel = model;
callback();
});
});
return this;
}
}
<file_sep>import React from 'react';
export default class Pager extends React.Component {
static propTypes = {
onchange: React.PropTypes.func.isRequired,
onclose: React.PropTypes.func
};
constructor() {
super();
this.onclick = this.onclick.bind(this);
this.onkeyb = this.onkeyb.bind(this);
}
componentDidMount() {
this.prev = this.refs.prev.getDOMNode();
this.next = this.refs.next.getDOMNode();
this.pager = this.refs.pager.getDOMNode();
this.prev.addEventListener('click', this.onclick, true);
this.prev.addEventListener('touchstart', this.onclick, true);
this.next.addEventListener('click', this.onclick, true);
this.next.addEventListener('touchstart', this.onclick, true);
this.pager.addEventListener('keydown', this.onkeyb, true);
this.pager.focus();
}
componentWillUnmount() {
this.prev.removeEventListener('click', this.onclick, true);
this.prev.removeEventListener('touchstart', this.onclick, true);
this.next.removeEventListener('click', this.onclick, true);
this.next.removeEventListener('touchstart', this.onclick, true);
this.pager.removeEventListener('keydown', this.onkeyb, true);
}
onclick(e) {
e.preventDefault();
let dir = (e.target.className.match(/\bnext\b/)) ? 1 : -1;
this.props.onchange(dir);
}
onkeyb(e) {
switch (e.keyCode) {
case 27:
// Handle closing somehow
if (typeof this.props.onclose === 'function') {
this.props.onclose();
}
break;
case 37:
this.props.onchange(-1);
break;
case 39:
this.props.onchange(1);
break;
}
}
render() {
return (
<div className='pager' ref='pager' tabIndex='-1'>
<a className='prev fa fa-angle-left' ref='prev'></a>
<a className='next fa fa-angle-right' ref='next'></a>
</div>
);
}
}
<file_sep>import { loadCommonPlugins, commonJsonTransform, getImageSchema, populateMetadata } from './common';
exports.loadSchemas = function (mongoose, next) {
let Schema = mongoose.Schema;
let schemas = {};
schemas.AgencyImage = getImageSchema(Schema);
schemas.Agency = new Schema(populateMetadata({
uuid: {
type: String,
index: true,
unique: true
},
slug: {
type: String,
index: true,
required: true
},
title: {
type: String,
required: true
},
logo: [schemas.AgencyImage],
// Flags
visible: {
type: Boolean,
index: true,
default: true
}
}));
schemas.Agency.statics.editableFields = function () {
return [
'title', 'logo', 'visible'
];
};
Object.keys(schemas).forEach((name) => {
loadCommonPlugins(schemas[name], name, mongoose);
schemas[name].options.toJSON.transform = (doc, ret) => {
return commonJsonTransform(ret);
};
});
next(schemas);
};
<file_sep>import BaseBlock from '../Widgets/BaseBlock';
export default class AdminContentImage extends BaseBlock {
blockProperties = {
title: {
label: 'Title (optional)',
type: 'text'
},
description: {
label: 'Content (optional)',
type: 'textarea'
},
imageAlign: {
label: 'On which side the image should be',
type: 'select',
options: [
['left', 'Left'], ['right', 'Right']
]
},
image: {
label: 'Image',
type: 'image'
}
}
}
| 84e1d3c65ed4a845a1b9d3ad0c06dfdb315e56b4 | [
"JavaScript",
"Markdown",
"Makefile",
"Dockerfile",
"Shell"
]
| 241 | JavaScript | homehapp1/homehapp-web-backend | a757d8ffefa2f2e43cd8200f1b4613f77372b05a | 323228222e2c562716a1332c49226e2634f552bc |
refs/heads/master | <repo_name>Zenkin/owen_pvt100_sensor<file_sep>/src/sensor/modbus_driver.py
#!/usr/bin/env python3
# coding=utf-8
"""
File name: thc_driver.py Author: <NAME>
A Python driver for the ModBus RTU protocols via serial port (via RS485).
"""
import minimalmodbus
import serial
import time
import os
debug = False
parity = 'N'
bytesize = 8
stopbits = 1
register = {
'temperature': 258,
'humidity': 259,
'network_address_of_the_device': 4,
'exchange_rate': 5,
'device_response_delay': 6,
'number_of_stopbits': 7,
'software_version': 16
}
function = {
'read': 3,
'write': 6
}
decimals_number = {
0: 0,
1: 1,
2: 2
}
class thc_driver:
sensors_count = 0
def __init__(self, port, slave_adress, baudrate_value, parity, bytesize, stopbits, timeout_value):
minimalmodbus.BAUDRATE = baudrate_value
minimalmodbus.PARITY = parity
minimalmodbus.BYTESIZE = bytesize
minimalmodbus.STOPBITS = stopbits
minimalmodbus.TIMEOUT = timeout_value
try:
self.instrument = minimalmodbus.Instrument(port, slave_adress, mode='rtu')
except:
print("No connection to " + str(port) + " or permission denied")
else:
self.instrument.mode = minimalmodbus.MODE_RTU # set rtu mode
self.instrument.serial.timeout = timeout_value
self.instrument.serial.baudrate = baudrate_value
thc_driver.sensors_count += 1
self.index = thc_driver.sensors_count
if debug:
print(" ---------------------------")
print(" | SENSOR " + str(thc_driver.sensors_count) + " INFO |")
print(" ---------------------------")
print(" ", "Port: ".ljust(20), str(port).ljust(40))
print(" ", "Slave adress: ".ljust(20), str(slave_adress).ljust(40))
print(" ", "Boudrate: ".ljust(20), str(baudrate_value).ljust(40))
print(" ", "Parity: ".ljust(20), str(parity).ljust(40))
print(" ", "Bytesize: ".ljust(20), str(bytesize).ljust(40))
print(" ", "Stopbits: ".ljust(20), str(stopbits).ljust(40))
print(" ", "Timeout: ".ljust(20), str(timeout_value).ljust(40))
print("")
def __del__(self):
if debug:
print('Сенсор {0} отключен'.format(self.index))
thc_driver.sensors_count -= 1
if debug:
if thc_driver.sensors_count == 0:
print('Все датчики отключены')
else:
print('Осталось {0:d} работающих датчиков'.format(thc_driver.sensors_count))
def get_temperature(self):
try:
self.temperature = self.instrument.read_register(register['temperature'], decimals_number[2],
function['read'], signed=True)
return self.temperature
except:
return -200
def get_humidity(self):
try:
self.humidity = self.instrument.read_register(register['humidity'], decimals_number[2], function['read'])
return self.humidity
except:
return -200
def get_network_address_of_the_device(self):
try:
self.network_address_of_the_device = self.instrument.read_register(
register['network_address_of_the_device'], decimals_number[0], function['read'])
return self.network_address_of_the_device
except:
return -200
def get_exchange_rate(self):
try:
self.exchange_rate = self.instrument.read_register(register['exchange_rate'], decimals_number[0],
function['read'])
return self.exchange_rate
except:
return -200
def get_device_response_delay(self):
try:
self.device_response_delay = self.instrument.read_register(register['device_response_delay'],
decimals_number[0], function['read'])
return self.device_response_delay
except:
return -200
def get_number_of_stopbits(self):
try:
self.number_of_stopbits = self.instrument.read_register(register['number_of_stopbits'], decimals_number[0],
function['read'])
return self.number_of_stopbits
except:
return -200
def get_software_version(self):
try:
self.software_version = self.instrument.read_register(register['software_version'], decimals_number[0],
function['read'])
return self.software_version
except:
return -200
def get_device_information(self):
try:
print(" network_address_of_the_device: " + str(self.get_network_address_of_the_device()) + "\n"
+ " exchange_rate: " + str(self.get_exchange_rate()) + "\n"
+ " device_response_delay: " + str(self.get_device_response_delay()) + "\n"
+ " number_of_stopbits: " + str(self.get_number_of_stopbits()) + "\n"
+ " software_version: " + str(self.get_software_version()) + "\n")
except:
print("no connection to " + str(port))
<file_sep>/scripts/start_node.py
#!/usr/bin/python2
import rospy
from std_msgs.msg import String
from sensor.msg import temperature as temperature_msg
from sensor.msg import humidity as humidity_msg
from sensor.srv import temperature_service, temperature_serviceResponse
from sensor.srv import humidity_service, humidity_serviceResponse
from sensor.srv import update_service, update_serviceResponse
from sensor.modbus_driver import *
import threading
debug = True
lock = threading.Lock()
class Node:
repeat = False
counter = 0
def publication_period_controll(self):
if self.publication_period == 0:
Node.repeat = False
else:
Node.repeat = True
def clear_parameters(self):
if debug:
rospy.loginfo("Clear all parameters [Used when parameters were not set]")
try:
rospy.delete_param("/thc_sensor")
except KeyError:
if debug:
rospy.loginfo("Nothing to clean [parameters were not set]")
def init(self):
rospy.init_node('sensor', anonymous=True)
try:
self.port = rospy.get_param("/thc_sensor/port")
error_get_param = False
except:
error_get_param = True
try:
self.slave_adress = rospy.get_param("/thc_sensor/slave_adress")
error_get_param = False
except:
error_get_param = True
try:
self.baudrate = rospy.get_param("/thc_sensor/baudrate")
error_get_param = False
except:
error_get_param = True
try:
self.capture_time = rospy.get_param("/thc_sensor/timeout")
error_get_param = False
except:
error_get_param = True
try:
self.publication_period = rospy.get_param("/thc_sensor/publication_period")
error_get_param = False
except:
error_get_param = True
if error_get_param:
self.clear_parameters()
if debug:
rospy.loginfo("Can't find parameters. Set default values ...")
self.set_default_parameters()
self.get_parameters()
if debug:
self.print_loginfo()
self.sensor = thc_driver(self.port, self.slave_adress, self.baudrate, parity, bytesize, stopbits,
self.capture_time)
def print_loginfo(self):
rospy.loginfo("port: " + self.port)
rospy.loginfo("slave adress: " + str(self.slave_adress))
rospy.loginfo("baudrate: " + str(self.baudrate))
rospy.loginfo("capture time: " + str(self.capture_time))
rospy.loginfo("publicationp period: " + str(self.publication_period))
def set_default_parameters(self):
rospy.set_param("/thc_sensor/port", "/dev/ttyUSB1")
rospy.set_param("/thc_sensor/slave_adress", 16)
rospy.set_param("/thc_sensor/baudrate", 9600)
rospy.set_param("/thc_sensor/timeout", 10)
rospy.set_param("/thc_sensor/publication_period", 30)
def get_parameters(self):
self.port = rospy.get_param("/thc_sensor/port")
self.slave_adress = rospy.get_param("/thc_sensor/slave_adress")
self.baudrate = rospy.get_param("/thc_sensor/baudrate")
self.capture_time = rospy.get_param("/thc_sensor/timeout")
self.publication_period = rospy.get_param("/thc_sensor/publication_period")
def start_publication(self):
temperature_message = temperature_msg()
humidity_message = humidity_msg()
temperature_publication = rospy.Publisher('thc_driver/temperature', temperature_msg, queue_size=10)
humidity_publication = rospy.Publisher('thc_driver/humidity', humidity_msg, queue_size=10)
while not rospy.is_shutdown():
self.publication_period_controll()
# form a message with temperature
temperature_message.port = self.port
temperature_message.header.stamp = rospy.Time.now()
temperature_message.header.frame_id = "temperure_sensor"
lock.acquire()
temperature_value = self.get_temperature()
lock.release()
if temperature_value == -200:
temperature_message.success = False
temperature_message.temperature = 0
else:
temperature_message.success = True
temperature_message.temperature = temperature_value
# form a message with humidity
humidity_message.port = self.port
humidity_message.header.stamp = rospy.Time.now()
humidity_message.header.frame_id = "humidity_sensor"
lock.acquire()
humidity_value = self.get_humidity
lock.release()
if humidity_value == -200:
humidity_message.success = False
humidity_message.humidity = 0
else:
humidity_message.success = True
humidity_message.humidity = humidity_value
# publish messages with temperature and humidity
if Node.repeat:
temperature_publication.publish(temperature_message)
humidity_publication.publish(humidity_message)
Node.counter = 0
time.sleep(self.publication_period)
else:
if Node.counter == 0:
temperature_publication.publish(temperature_message)
humidity_publication.publish(humidity_message)
Node.counter += 1
if debug:
rospy.loginfo("publication_period_controll:repeat: False")
def get_temperature(self):
return self.sensor.get_temperature()
def get_humidity(self):
return self.sensor.get_humidity
def temperature_service_callback(self, request):
temperature_message_response = temperature_serviceResponse()
lock.acquire()
temperature_value = self.get_temperature()
if temperature_value == -200:
temperature_message_response.success = False
temperature_message_response.temperature = 0
else:
temperature_message_response.success = True
temperature_message_response.temperature = temperature_value
temperature_message_response.port = self.port
temperature_message_response.header.stamp = rospy.Time.now()
temperature_message_response.header.frame_id = "temperure_sensor"
lock.release()
return temperature_message_response
def humidity_service_callback(self, request):
humidity_message_response = humidity_serviceResponse()
lock.acquire()
humidity_value = self.get_humidity
if humidity_value == -200:
humidity_message_response.success = False
humidity_message_response.humidity = 0
else:
humidity_message_response.success = True
humidity_message_response.humidity = humidity_value
humidity_message_response.port = self.port
humidity_message_response.header.stamp = rospy.Time.now()
humidity_message_response.header.frame_id = "temperure_sensor"
lock.release()
return humidity_message_response
def update_service_callback(self, request):
update_message_response = update_serviceResponse()
lock.acquire()
self.get_parameters()
lock.release()
update_message_response.header.stamp = rospy.Time.now()
update_message_response.header.frame_id = "update_service"
lock.acquire()
self.sensor = thc_driver(self.port, self.slave_adress, self.baudrate, parity, bytesize, stopbits,
self.capture_time)
lock.release()
update_message_response.log = "Parameters have been changed successfully"
return update_message_response
if __name__ == '__main__':
try:
node = Node()
except rospy.ROSInterruptException:
pass
try:
node.init()
except rospy.ROSInterruptException:
pass
try:
rospy.Service('get_temperature', temperature_service, node.temperature_service_callback)
except:
rospy.loginfo("Failed to start the temperature server")
try:
rospy.Service('get_humidity', humidity_service, node.humidity_service_callback)
except:
rospy.loginfo("Failed to start the humidity server")
try:
rospy.Service('update_parameters', update_service, node.update_service_callback)
except:
rospy.loginfo("Failed to start the humidity server")
try:
node.start_publication()
except rospy.ROSInterruptException:
pass
<file_sep>/README.md
# owen_pvt100_sensor
For Airalab, https://aira.life 06-2018
## Dependencies
It is the only two dependencies, you can download it from the links below:
* [MinimalModbus](http://minimalmodbus.readthedocs.io/en/master/installation.html)
* [PySerial](https://pypi.org/project/pyserial/)
## Installation
cd /home/<catkin_workspace>/srs
catkin_create_pkg sensor
git clone https://github.com/Zenkin/owen_pvt100_sensor.git
cp -r owen_pvt100_sensor/* sensor/
rm -rf owen_pvt100_sensor/
cd ..
catkin_make
catkin_make install
source devel/setup.bash
roslaunch sensor sensor.launch
## Description
### Parameters
Default parameters, which you can change in launch file:
/thc_sensor/baudrate: 9600
/thc_sensor/port: /dev/ttyUSB1
/thc_sensor/publication_period: 1
/thc_sensor/slave_adress: 16
/thc_sensor/timeout: 0.05
Note:
* timeout - maximum time to capture the bus interface. You can not set less than 0.05 seconds
* If the publication_period parameter is set to 0, a periodic poll will not be conducted
### Msg API
#### humidity
Header header
# port name
port string
# humidity sensor
float64 humidity
# Data checking. If the data is not reached it returns False otherwise True
bool success
#### temperature
Header header
# port name
string
# temperature sensor
float64 temperature
# Data checking. If the data is not reached it returns False otherwise True
bool success
### Services API
#### get_humidity
returns the humidity value (float64), and Header
*sensor/humidity_service*
---
Header header
string port
float64 humidity
bool success
#### get_temperature
returns the temperature value (float64), and Header
*sensor/temperature_service*
---
Header header
string port
float64 temperature
bool success
#### update_parameters
updates and applies parameters that have been changed through the rosparam set
*sensor/update_service*
---
Header header
string log
### Topics
/thc_driver/humidity
*Type:* sensor/humidity
*Description:* publishes humidity data (float64) and Header
/thc_driver/temperature
*Type:* sensor/temperature
*Description:* publishes temperature data (float64) and Header
<file_sep>/setup.py
## ! DO NOT MANUALLY INVOKE THIS setup.py, USE CATKIN INSTEAD
from distutils.core import setup
import catkin_pkg.python_setup
# fetch values from package.xml
setup_args = catkin_pkg.python_setup.generate_distutils_setup(
packages=['sensor'],
package_dir={'': 'src'})
setup(**setup_args)
<file_sep>/CMakeLists.txt
cmake_minimum_required(VERSION 2.8.3)
set(PROJECT sensor)
project(${PROJECT})
find_package(catkin REQUIRED COMPONENTS
rospy
std_msgs
message_generation
)
catkin_python_setup()
add_service_files(
FILES
temperature_service.srv
humidity_service.srv
update_service.srv
)
add_service_files(
FILES
temperature_service.srv
humidity_service.srv
update_service.srv
)
add_message_files(
FILES
temperature.msg
humidity.msg
)
generate_messages(
DEPENDENCIES
std_msgs
)
catkin_package(
CATKIN_DEPENDS message_runtime
)
include_directories(
# include
${catkin_INCLUDE_DIRS}
)
catkin_install_python(PROGRAMS scripts/start_node.py
DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION})
| 2040576edc0c8b1570f2bd0279b78d5d04d45551 | [
"Markdown",
"Python",
"CMake"
]
| 5 | Python | Zenkin/owen_pvt100_sensor | 249323c62df4fd5ed7574bef0030d740347412bf | 5e266a0478ce0014e4842b4fb7675263ea40047d |
refs/heads/master | <repo_name>skipter/Tech-Module<file_sep>/Software Technologies/PHP - Syntax and Basic Web/test.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Test Pieces of Code Here</title>
</head>
<body>
<?php
$str = "Hello Wolrd, how are you";
print_r(explode(" ",$str));
echo "<br />\n";
echo "<br />\n";
echo $str;
?>
</body>
</html><file_sep>/Programming Fundamentals/Programming-Fundamentals-Extended-May-2017/C- Basic Syntax - More Exercises/p.5 BPM Counter/Program.cs
using System;
namespace p._5_BPM_Counter
{
class Program
{
static void Main(string[] args)
{
double beatsPerMinute = double.Parse(Console.ReadLine());
double numberOfBeatsInSeconds = double.Parse(Console.ReadLine());
double bars = Math.Round(numberOfBeatsInSeconds * 0.25, 1);
double totalSeconds = ((int)numberOfBeatsInSeconds * 60 / (int)beatsPerMinute);
int minutes = (int) totalSeconds / 60;
double seconds = totalSeconds % 60;
Console.WriteLine("{0} bars - {1}m {2}s", Math.Round(bars, 1), minutes, Math.Floor(seconds));
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-Extended-May-2017/Lists - Exercises/5.Tear List in Half/Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
namespace _5.Tear_List_in_Half
{
class Program
{
static void Main(string[] args)
{
List<int> listForSeparation = Console.ReadLine()
.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
.Select(int.Parse)
.ToList();
TearListInHalf(listForSeparation);
}
private static void TearListInHalf (List<int> list)
{
var firstList = new List<int>();
var secondList = new List<int>();
for (int cnt = 0; cnt < list.Count; cnt++)
{
if (cnt < list.Count / 2)
{
firstList.Add(list[cnt]);
} else
{
secondList.Add(list[cnt]);
}
}
Output(firstList, secondList);
}
private static void Output(List<int> firstList, List<int> secondList)
{
var resultList = new List<int>();
for (int cnt = 0; cnt < firstList.Count; cnt++)
{
int firstDigit = secondList[cnt] / 10;
int secondDigit = secondList[cnt] % 10;
resultList.Add(firstDigit);
resultList.Add(firstList[cnt]);
resultList.Add(secondDigit);
}
Console.WriteLine(string.Join(" ", resultList));
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-September-2017/DictionariesLambdaAndLINQ/06.FoldAndSum/FoldAndSum.cs
namespace _06.FoldAndSum
{
using System;
using System.Collections.Generic;
using System.Linq;
public class FoldAndSum
{
public static void Main()
{
List<int> numbers = Console.ReadLine()
.Split(' ')
.Select(int.Parse)
.ToList();
int k = numbers.Count / 4;
var left = numbers.Take(k).Reverse().ToList();
numbers.Reverse();
var right = numbers.Take(k).ToList();
var newArr = left.Concat(right).ToList();
numbers.Reverse();
var middlePartOfK = numbers.Skip(k).Take(2 * k).ToList();
var result = newArr.Select((x, index) => x + middlePartOfK[index]);
Console.WriteLine(string.Join(" ", result));
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-September-2017/ConditionalStatementsAndLoops/07.DivisibleBy3/Program.cs
namespace DivisibleBy3
{
using System;
public class Program
{
static void Main()
{
for (int cnt = 1; cnt < 100; cnt++)
{
if (cnt % 3 == 0)
{
Console.WriteLine(cnt);
}
}
}
}
}
<file_sep>/Software Technologies/JavaScript Syntax and Basic Web - Exercises/10. RemoveElements.js
function elementGame(args) {
let emptyArr = [];
for (let obj of args) {
let input = obj.split(" ");
let command = input[0];
let value = input[1];
let indexToRemove = input[1];
if (command === "add") {
emptyArr.push(value);
}
if (command === "remove") {
if (emptyArr.length < indexToRemove) {
} else {
emptyArr.splice(indexToRemove, 1);
}
}
}
console.log(emptyArr.join('\n'));
}
// elementGame([
// 'add 3',
// 'add 5',
// 'add 7'
// ]);
elementGame([
'add 3',
'add 5',
'remove 2',
'remove 0',
'add 7'
]);
//elementGame([
// 'add 3',
// 'add 5',
// 'remove 1',
// 'add 2'
//]);<file_sep>/Programming Fundamentals/Programming-Fundamentals-September-2017/DataTypesAndVariables/04.Elevator/Program.cs
namespace _04.Elevator
{
using System;
public class Program
{
static void Main()
{
int numberOfPeople = int.Parse(Console.ReadLine());
int peopleCapacity = int.Parse(Console.ReadLine());
int courses = numberOfPeople / peopleCapacity;
int lastCours = numberOfPeople % peopleCapacity;
if (lastCours > 0)
{
courses += 1;
}
Console.WriteLine(courses);
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-September-2017/DataTypesAndVariables-Exercises/06.StringsAndObjects/Program.cs
namespace _06.StringsAndObjects
{
using System;
public class Program
{
static void Main()
{
string firstString = "Hello";
string secondString = "World";
object concatenation = firstString + " " + secondString;
// string thirdString = (string)concatenation;
Console.WriteLine(concatenation);
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-September-2017/DictionariesLambdaAndLINQ-Exercise/04.FixEmails/FixEmails.cs
namespace _04.FixEmails
{
using System;
using System.Collections.Generic;
using System.Linq;
public class FixEmails
{
public static void Main()
{
Dictionary<string, string> emailCordinats = new Dictionary<string, string>();
string input;
while (true)
{
input = Console.ReadLine();
if (input == "stop")
{
break;
}
string email = Console.ReadLine();
if (!emailCordinats.ContainsKey(input))
{
if (!email.Contains(".us") || email.Contains(".uk"))
{
emailCordinats.Add(input, email);
}
}
}
foreach (var name in emailCordinats)
{
Console.WriteLine("{0} -> {1}", name.Key, name.Value);
}
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-Extended-November-2017/Data Types, Variables and Methods - Lab/02. Real Number Types/RealNumbersTypes.cs
namespace _02.Real_Number_Types
{
using System;
public class RealNumbersTypes
{
public static void Main()
{
int num = int.Parse(Console.ReadLine());
decimal number = decimal.Parse(Console.ReadLine());
Console.WriteLine(Math.Round(number, num));
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-September-2017/MethodsDebuggingАndTroubleshootingCode-Exercises/12.MasterNumbers/Program.cs
namespace _12.MasterNumbers
{
using System;
public class Program
{
public static void Main()
{
int number = int.Parse(Console.ReadLine());
for (int i = 1; i <= number; i++)
{
if (ContainsEvenDigit(i) && SumOfDigitsDivineBySeven(i) && IsPalindrome(i))
{
Console.WriteLine(i);
}
}
}
static bool SumOfDigitsDivineBySeven(int number)
{
int sum = 0;
while (number > 0)
{
sum += number % 10;
number /= 10;
}
if (sum % 7 == 0)
{
return true;
}
return false;
}
static bool ContainsEvenDigit(int number)
{
while (number > 0)
{
if ((number % 10) % 2 == 0)
{
return true;
}
number /= 10;
}
return false;
}
static bool IsPalindrome(int number)
{
string text = number.ToString();
for (int i = 0; i <= text.Length / 2; i++)
{
if (text[i] == text[text.Length - 1 - i])
{
} else
{
return false;
}
}
return true;
}
}
}
<file_sep>/Software Technologies/JavaScript Syntax and Basic Web - Exercises/05. Print Numbers from 1 to N.js
function print(args) {
let stopNumber = Number(args[0]);
for (let i = 1; i <= stopNumber; i++) {
console.log(i);
}
}
print(['5']);
print(['2']);<file_sep>/Programming Fundamentals/Programming-Fundamentals-September-2017/MethodsDebuggingАndTroubleshootingCode-Exercises/08.CenterPoint/Program.cs
namespace _08.CenterPoint
{
using System;
public class Program
{
static void Main()
{
double x1 = double.Parse(Console.ReadLine());
double y1 = double.Parse(Console.ReadLine());
double x2 = double.Parse(Console.ReadLine());
double y2 = double.Parse(Console.ReadLine());
if (CloserPoint(x1, y1, x2, y2))
{
Console.WriteLine($"({x1}, {y1})");
} else
{
Console.WriteLine($"({x2}, {y2})");
}
}
public static double CalculateDistane(double x1, double y1, double x2, double y2)
{
var distance = Math.Sqrt(Math.Pow(x2 - x1, 2) + (Math.Pow(y2 - y1, 2)));
return distance;
}
private static bool CloserPoint (double x1, double y1, double x2, double y2)
{
var firstDistance = CalculateDistane(x1, y1, 0, 0);
var secondDistance = CalculateDistane(x2, y2, 0, 0);
if (firstDistance > secondDistance)
{
return false;
} else
{
return true;
}
}
}
}
<file_sep>/Programming Fundamentals/PF-Exams/PF-Exam-05November2017/01. Anonymous Downsite/AnonymouDowsite.cs
namespace _01.Anonymous_Downsite
{
using System;
using System.Collections.Generic;
using System.Numerics;
public class AnonymouDowsite
{
public static void Main()
{
int n = int.Parse(Console.ReadLine());
int key = int.Parse(Console.ReadLine());
var sites = new List<string>();
BigInteger totacClicks = 0;
decimal pricePerClick = 0m;
decimal totalSum = 0m;
for (BigInteger i = 0; i < n; i++)
{
var input = Console.ReadLine().Split(' ');
string siteName = input[0];
sites.Add(siteName);
long siteVisits = long.Parse(input[1]);
totacClicks += siteVisits;
pricePerClick = decimal.Parse(input[2]);
totalSum += siteVisits * pricePerClick;
}
Console.WriteLine(String.Join(Environment.NewLine, sites));
Console.WriteLine($"Total Loss: {totalSum:F20}");
Console.WriteLine($"Security Token: {BigInteger.Pow(key, n)}");
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-September-2017/DictionariesLambdaAndLINQ-Exercise/08.LogsAggregator/LogsAggregator.cs
namespace _08.LogsAggregator
{
using System;
using System.Collections.Generic;
using System.Linq;
public class LogsAggregator
{
public static void Main()
{
var loginDetails = new SortedDictionary<string, Dictionary<string, int>>();
int n = int.Parse(Console.ReadLine());
for (int i = 0; i < n; i++)
{
string input = Console.ReadLine();
var inputArgs = input
.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
.ToList();
string ipAdress = inputArgs[0];
string userName = inputArgs[1];
int duration = int.Parse(inputArgs[2]);
if (!loginDetails.ContainsKey(userName))
{
loginDetails.Add(userName, new Dictionary<string, int>());
}
if (!loginDetails[userName].ContainsKey(ipAdress))
{
loginDetails[userName].Add(ipAdress, 0);
}
loginDetails[userName][ipAdress] += duration;
}
foreach (var user in loginDetails)
{
HashSet<string> ip = new HashSet<string>();
var time = user.Value.Values.Sum();
foreach (var item in loginDetails[user.Key])
{
ip.Add($"{item.Key}");
}
Console.WriteLine($"{user.Key}: {time} [{String.Join(", ", ip.OrderBy(x => x))}]");
}
}
}
}
<file_sep>/Software Technologies/Java Basic Syntax/src/ThreeIntegersSum.java
import java.util.Scanner;
public class ThreeIntegersSum {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
String[] split = (input.split(" "));
int[] numbers = new int[split.length];
for (int i = 0; i < split.length; i++) {
numbers[i] = Integer.parseInt(split[i]);
}
int firstNum = numbers[0];
int secondNum = numbers[1];
int thirdNum = numbers[2];
//ToDo Print the elements, in such way, that num1 <= num2.
if (firstNum + secondNum == thirdNum) {
if (firstNum <= secondNum) {
System.out.println(firstNum + " + " + secondNum + " = " + thirdNum);
} else {
System.out.println(secondNum + " + " + firstNum + " = " + thirdNum);
}
} else if (secondNum + thirdNum == firstNum) {
if (secondNum <= thirdNum) {
System.out.println(secondNum + " + " + thirdNum + " = " + firstNum);
} else {
System.out.println(thirdNum + " + " + secondNum + " = " + firstNum);
}
} else if (firstNum + thirdNum == secondNum) {
if (firstNum <= thirdNum) {
System.out.println(firstNum + " + " + thirdNum + " = " + secondNum);
} else {
System.out.println(thirdNum + " + " + firstNum + " = " + secondNum);
}
} else {
System.out.println("No");
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-September-2017/Exam Preparation III/02.Command Intrepreter/CommandIntrepreter.cs
namespace _02.Command_Intrepreter
{
using System;
using System.Collections.Generic;
using System.Linq;
public class CommandIntrepreter
{
public static void Main()
{ // 90/100 Points
List<string> numbers = Console.ReadLine()
.Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)
.ToList();
while (true)
{
string[] command = Console.ReadLine().Split(' ').ToArray();
if (command[0] == "end")
{
break;
}
string input = command[0];
switch (input)
{
case "reverse":
Reverse(numbers, command);
break;
case "sort":
Sort(numbers, command);
break;
case "rollLeft":
RollLeft(numbers, command);
break;
case "rollRight":
RollRight(numbers, command);
break;
}
}
Console.WriteLine($"[{string.Join(", ", numbers)}]");
}
public static List<string> RollRight(List<string> numbers, string[] command)
{
int count = int.Parse(command[1]);
if (count < 0)
{
Console.WriteLine("Invalid input parameters.");
return numbers;
}
for (int i = 0; i < count % numbers.Count; i++)
{
if (i > numbers.Count)
{
return numbers;
}
string temp = numbers.Last();
numbers.RemoveAt(numbers.Count - 1);
numbers.Insert(0, temp);
}
return numbers;
}
public static List<string> RollLeft(List<string> numbers, string[] command)
{
int count = int.Parse(command[1]);
if (count < 0)
{
Console.WriteLine("Invalid input parameters.");
return numbers;
}
for (int i = 0; i < count; i++)
{
if (numbers.Count < i)
{
return numbers;
}
string temp = numbers[0];
numbers.RemoveAt(0);
numbers.Add(temp);
}
return numbers;
// int index = int.Parse(command[1]);
// if (index < 0)
// {
// Console.WriteLine("Invalid input parameters.");
// }
// index = index % numbers.Count;
// var remove = numbers.Take(index).ToList();
// numbers.RemoveRange(0, index);
// numbers.AddRange(remove);
// return numbers;
}
public static List<string> Sort(List<string> numbers, string[] command)
{
int start = int.Parse(command[2]);
int end = int.Parse(command[4]);
if (start < 0 || start >= numbers.Count || end < 0 || end > numbers.Count || start + end > numbers.Count)
{
Console.WriteLine("Invalid input parameters.");
return numbers;
}
else
{
numbers.Sort(start, end, null);
return numbers;
}
}
public static List<string> Reverse(List<string> numbers, string[] command)
{
int start = int.Parse(command[2]);
int count = int.Parse(command[4]);
if (start < 0 || start >= numbers.Count || count < 0 || count > numbers.Count || start + count > numbers.Count)
{
Console.WriteLine("Invalid input parameters.");
return numbers;
}
else
{
numbers.Reverse(start, count);
return numbers;
}
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-September-2017/Exam Preparation III/04.Files/Files.cs
namespace _04.Files
{
using System;
using System.Collections.Generic;
using System.Linq;
public class Files
{ //70/100 Points
public static void Main()
{
int n = int.Parse(Console.ReadLine());
List<string> adresses = new List<string>();
while (n > 0)
{
string adress = Console.ReadLine();
adresses.Add(adress);
n--;
}
string[] query = Console.ReadLine().Split(' ');
string mod = query[0];
string dir = query[2];
List<string> temp = new List<string>();
foreach (var adress in adresses)
{
if (adress.Contains(dir))
{
temp.Add(adress);
}
}
List<string> withModAndDir = new List<string>();
foreach (var tem in temp)
{
if (tem.Contains(mod))
{
withModAndDir.Add(tem);
}
}
if (withModAndDir.Count <= 0)
{
Console.WriteLine("No");
}
Dictionary<string, int> final = new Dictionary<string, int>();
foreach (var item in withModAndDir)
{
var getEndStr = item.Split(new char[] { ';', '\\' });
foreach (var words in item)
{
string modify = getEndStr[getEndStr.Length - 2];
int usage = int.Parse(getEndStr[getEndStr.Length - 1]);
if (!final.ContainsKey(modify))
{
final.Add(modify, usage);
}
final[modify] = usage;
}
}
foreach (var fi in final.OrderByDescending(x => x.Value).ThenBy(g => g.Key))
{
Console.WriteLine($"{fi.Key} - {fi.Value} KB");
}
}
}
}
<file_sep>/Programming Fundamentals/PF-Exams/PF-Exam-05November2017/03. Anonymous Vox/AnonymousVox.cs
namespace _03.Anonymous_Vox
{
using System;
using System.Linq;
using System.Text.RegularExpressions;
public class AnonymousThreat
{
public static void Main()
{
string encodedText = Console.ReadLine();
var placeHolders = Console.ReadLine()
.Split(new char[] { '{', '}', }, StringSplitOptions.RemoveEmptyEntries)
.ToList();
string pattern = @"([a-zA-Z]+)(.+)\1"; // \1 - Match the same text as first group.
Regex regex = new Regex(pattern);
MatchCollection matches = regex.Matches(encodedText);
int placeholderIndex = 0;
foreach (Match match in matches)
{
if (placeholderIndex >= placeHolders.Count)
{
break;
}
encodedText = ReplaceFirst(encodedText, match.Groups[2].Value, placeHolders[placeholderIndex++]);
}
Console.WriteLine(encodedText);
}
static string ReplaceFirst(string text, string oldValue, string newValue)
{
string substringWithOldValue = text.Substring(0, text.IndexOf(oldValue) + oldValue.Length);
string substringWithNewValue = substringWithOldValue.Replace(oldValue, newValue);
return substringWithNewValue + text.Substring(substringWithOldValue.Length);
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-September-2017/List-Exercises/03.SearchForANumber/SearchForANumber.cs
namespace _03.SearchForANumber
{
using System;
using System.Collections.Generic;
using System.Linq;
public class SearchForANumber
{
public static void Main()
{
List<int> numbers = Console.ReadLine()
.Split(new char[] { ' ', ',', ';', ':', '.', '!', '(', ')', '"', '/', '[', ']', '\'', '\\' }, StringSplitOptions.RemoveEmptyEntries)
.Select(int.Parse)
.ToList();
int[] modifiers = Console.ReadLine()
.Split(new char[] { ' ', ',', ';', ':', '.', '!', '(', ')', '"', '/', '[', ']', '\'', '\\' }, StringSplitOptions.RemoveEmptyEntries)
.Select(int.Parse)
.ToArray();
int num = modifiers[0];
int elementsToDelete = modifiers[1];
int numToFind = modifiers[2];
var result = numbers.Take(num).ToList();
result.RemoveRange(0, elementsToDelete);
if (result.Contains(numToFind) == true)
{
Console.WriteLine("YES!");
}
else
{
Console.WriteLine("NO!");
}
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-Extended-November-2017/Data Types, Variables and Methods - Lab/01. Integer Types/IntegersType.cs
namespace _01.Integer_Types
{
using System;
public class IntegersType
{
public static void Main()
{
long num1 = long.Parse(Console.ReadLine());
long num2 = long.Parse(Console.ReadLine());
long num3 = long.Parse(Console.ReadLine());
long num4 = long.Parse(Console.ReadLine());
Console.WriteLine(num1 + " " + num2 + " " + num3 + " " + num4);
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-September-2017/FilesDirectoriesАndExceptions-Exercise/09.BookLibrary/BookLibrary.cs
namespace _09.BookLibrary
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.IO;
public class Books
{
public string Title { get; set; }
public string Author { get; set; }
public string Publisher { get; set; }
public DateTime ReleaseDate { get; set; }
public long ISBNnumber { get; set; }
public double Price { get; set; }
}
public class Library
{
public string Book { get; set; }
public List<Books> listOfBooks { get; set; }
}
public class AuthorSale
{
public string Author { get; set; }
public double Sale { get; set; }
}
public class BookLibrary
{
public static void Main()
{
var dataFromFile = File.ReadAllLines("input.txt");
File.Delete("output.txt");
var books = new List<Books>();
var library = new Library()
{
Book = "Libra",
listOfBooks = new List<Books>()
};
foreach (var bookInsertion in dataFromFile)
{
var input = bookInsertion.Split(' ').ToList();
Books book = new Books();
book.Title = input[0];
book.Author = input[1];
book.Publisher = input[2];
book.ReleaseDate = DateTime.ParseExact(input[3], "dd.MM.yyyy", CultureInfo.InvariantCulture);
book.ISBNnumber = long.Parse(input[4]);
book.Price = double.Parse(input[5]);
library.listOfBooks.Add(book);
}
var autoSales = new List<AuthorSale>();
var authors = library.listOfBooks.Select(a => a.Author).Distinct().ToArray();
foreach (var author in authors)
{
var sales = library.listOfBooks.Where(a => a.Author == author).Sum(a => a.Price);
autoSales.Add(new AuthorSale()
{
Author = author,
Sale = sales
});
}
autoSales = autoSales.OrderByDescending(a => a.Sale).ThenBy(a => a.Author).ToList();
foreach (var sale in autoSales)
{
string output = $"{sale.Author} -> {sale.Sale:F2}" + Environment.NewLine;
File.AppendAllText("output.txt", output);
}
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-September-2017/DataTypesAndVariables-Exercises/04.VariableInHexadecimalFormat/Program.cs
namespace _04.VariableInHexadecimalFormat
{
using System;
public class Program
{
static void Main()
{
string hexValue = Console.ReadLine();
int number = Convert.ToInt32(hexValue, 16);
Console.WriteLine(number.ToString());
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-September-2017/DataTypesAndVariables-Exercises/17.PrintPartOfTheASCIITable/Program.cs
namespace _17.PrintPartOfTheASCIITable
{
using System;
public class Program
{
static void Main()
{
int charIndex = int.Parse(Console.ReadLine());
int secondCharIndex = int.Parse(Console.ReadLine());
char firstChar = Convert.ToChar(charIndex);
char secondChar = Convert.ToChar(secondCharIndex);
for (char i = firstChar; i <= secondChar; i++)
{
Console.Write($"{i} ");
}
Console.WriteLine();
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-September-2017/Arrays-Exercise/05.CompareCharArrays/CompareCharArray.cs
namespace _05.CompareCharArrays
{
using System;
using System.Linq;
public class CompareCharArray
{
public static void Main()
{
char[] firstArray = Console.ReadLine()
.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
.Select(char.Parse)
.ToArray();
char[] secondArray = Console.ReadLine()
.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
.Select(char.Parse)
.ToArray();
int lenght = Math.Min(firstArray.Length, secondArray.Length);
bool isFirst = false;
for (int i = 0; i < lenght; i++)
{
var index1 = (int)firstArray[i];
var index2 = (int)secondArray[i];
if (index1 <= index2)
{
isFirst = true;
}
else
{
break;
}
}
if (isFirst == true && lenght == firstArray.Length)
{
Console.WriteLine(string.Join("", firstArray));
Console.WriteLine(string.Join("", secondArray));
}
else
{
Console.WriteLine(string.Join("", secondArray));
Console.WriteLine(string.Join("", firstArray));
}
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-Extended-November-2017/Arrays, Lists, Array and List Algorithms - Exercise/04. Hornet Assault/HornetAssault.cs
namespace _04.Hornet_Assault
{
using System;
public class HornetAssault
{
public static void Main()
{
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-Extended-May-2017/Arrays and Methods - May 2017 Extended/8. String Encryption/Program.cs
namespace _08.String_Encryption
{
using System;
public class StringEncryption
{
public static void Main()
{
int numberOfChars = int.Parse(Console.ReadLine());
var output = string.Empty;
for (int i = 0; i < numberOfChars; i++)
{
char characters = char.Parse(Console.ReadLine());
var encryptChar = EncriptChar(characters, numberOfChars);
output += encryptChar;
}
Console.WriteLine(output);
}
static string EncriptChar(char characters, int n)
{
var result = string.Empty;
var charInNumbers = (int)characters;
var firstDigit = 0;
var lastDigit = charInNumbers % 10;
var firstEncryptedChar = (char)(characters + lastDigit);
var counter = 0;
if (charInNumbers > 9 && charInNumbers < 100)
{
counter = 2;
}
else
{
counter = 3;
}
while (counter > 1)
{
charInNumbers /= 10;
firstDigit = charInNumbers;
counter--;
}
var lastEncryptedChar = (char)(characters - firstDigit);
result = $"{firstEncryptedChar}{firstDigit}{lastDigit}{lastEncryptedChar}";
return result;
}
}
}<file_sep>/Programming Fundamentals/Programming-Fundamentals-September-2017/FilesDirectoriesАndExceptions-Exercise/04. MaxSequenceОfEqualElements/MaxSequanceOfEqualElements.cs
namespace _04.MaxSequenceOfEqualElements
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
public class MaxSequenceOfEqualElements
{
public static void Main()
{
string[] input = File.ReadAllLines("input.txt");
File.Delete("output.txt");
foreach (var line in input)
{
List<int> numbers = line
.Split(new char[] { ' ' })
.Select(int.Parse)
.ToList();
int counter = 1;
int maxCounter = 0;
int longestNumber = 0;
for (int i = 0; i < numbers.Count - 1; i++)
{
if (numbers[i] == numbers[i + 1])
{
counter++;
}
else
{
counter = 1;
}
if (counter > maxCounter)
{
maxCounter = counter;
longestNumber = numbers[i];
}
}
for (int i = 0; i < maxCounter; i++)
{
string output = longestNumber + " ";
File.AppendAllText("output.txt", output);
}
}
}
}
}<file_sep>/Programming Fundamentals/Programming-Fundamentals-September-2017/Arrays-Exercise/02.RotateAndSum/RotateAndSum.cs
namespace _02.RotateAndSum
{
using System;
using System.Linq;
public class RotateAndSum
{
public static void Main()
{
int[] array = Console.ReadLine()
.Split(' ')
.Select(int.Parse)
.ToArray();
int n = int.Parse(Console.ReadLine());
int[] result = new int[array.Length];
for (int i = 0; i < n; i++)
{
int reminder = array[array.Length - 1];
for (int j = array.Length - 1; j > 0; j--)
{
array[j] = array[j - 1];
result[j] += array[j];
}
array[0] = reminder;
result[0] += array[0];
}
Console.WriteLine(string.Join(" ", result));
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-September-2017/DataTypesAndVariables-Exercises/13.VowelOrDigit/Program.cs
namespace _13.VowelOrDigit
{
using System;
public class Program
{
static void Main()
{
char symbol;
symbol = Convert.ToChar(Console.ReadLine());
bool isVowel = (symbol == 'a') || (symbol == 'e') || (symbol == 'i' || (symbol == 'o') || (symbol == 'u'));
bool isDigit = (symbol >= '0') && (symbol <= '9');
if (isVowel)
{
Console.WriteLine("vowel");
} else if (isDigit)
{
Console.WriteLine("digit");
} else
{
Console.WriteLine("other");
}
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-Extended-May-2017/Arrays and Methods - May 2017 Extended/2.ElementEqualToIndex/Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _2.ElemntEqualIndex
{
class Program
{
static void Main(string[] args)
{
int[] findTheEqualIndex = Console.ReadLine().Split(' ').Select(int.Parse).ToArray();
string empryString = string.Empty;
for (int cnt = 0; cnt < findTheEqualIndex.Length; cnt++)
{
if (cnt == findTheEqualIndex[cnt])
{
empryString += cnt + " ";
}
}
Console.WriteLine(empryString);
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-September-2017/Arrays-Lab/03.LastKNumbersSumsSequence/Program.cs
namespace _03.LastKNumbersSumsSequence
{
using System;
using System.Linq;
public class Program
{
public static void Main()
{
int n = int.Parse(Console.ReadLine());
int k = int.Parse(Console.ReadLine());
long[] number = new long[n];
int sum = 0;
number[0] = 1;
for (int i = 1; i < number.Length; i++)
{
for (int j = 1; j <= k; j++)
{
if (i - j >= 0) //This if() is for "number[i-j] to be positive."
{
number[i] += number[i - j];
continue;
}
break;
}
}
Console.WriteLine(string.Join(" ", number));
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-September-2017/ConditionalStatementsAndLoops-Exercises/13.GameOfNumbers/Program.cs
namespace GameOfNumbers
{
using System;
public class Program
{
static void Main()
{
int a = int.Parse(Console.ReadLine());
int b = int.Parse(Console.ReadLine());
int magicNUmber = int.Parse(Console.ReadLine());
int combinationsCounter = 0;
bool isFOund = false;
int c = 0;
int d = 0;
for (int i = a; i <= b; i++)
{
for (int j = a; j <= b; j++)
{
if (i + j == magicNUmber)
{
isFOund = true;
c = i;
d = j;
}
combinationsCounter++;
}
}
if (isFOund)
{
Console.WriteLine("Number found! {0} + {1} = {2}", c, d, magicNUmber);
}
else
{
Console.WriteLine("{0} combinations - neither equals {1}", combinationsCounter, magicNUmber);
}
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-September-2017/ConditionalStatementsAndLoops-Exercises/04.Hotel/Program.cs
namespace Hotel
{
using System;
public class Program
{
static void Main()
{
string month = Console.ReadLine();
int nightToStay = int.Parse(Console.ReadLine());
double studioRoom = 0;
double doubleRoom = 0;
double suiteRoom = 0;
switch (month)
{
case "May":
case "October":
studioRoom = 50;
doubleRoom = 65;
suiteRoom = 75;
break;
case "June":
case "September":
studioRoom = 60;
doubleRoom = 72;
suiteRoom = 82;
break;
case "July":
case "August":
case "December":
studioRoom = 68;
doubleRoom = 77;
suiteRoom = 89;
break;
}
if (month.Equals("May") && nightToStay > 7 || month.Equals("October") && nightToStay > 7)
{
studioRoom = studioRoom - (studioRoom * 0.05);
}
if (nightToStay > 14 && month.Equals("June") || nightToStay > 14 && month.Equals("September"))
{
doubleRoom = doubleRoom - (doubleRoom * 0.10);
}
if (nightToStay > 14 && month.Equals("July") || nightToStay > 14 && month.Equals("August") || nightToStay > 14 && month.Equals("December")) {
suiteRoom = suiteRoom - (suiteRoom * 0.15);
}
double totalPriceStudio = studioRoom * nightToStay;
double totalPriceDouble = doubleRoom * nightToStay;
double totalPriceSuite = suiteRoom * nightToStay;
if (month.Equals("September") && nightToStay > 7 || nightToStay > 7 && month.Equals("October"))
{
totalPriceStudio = totalPriceStudio - studioRoom;
}
Console.WriteLine("Studio: {0:F2} lv.", totalPriceStudio);
Console.WriteLine("Double: {0:F2} lv.",totalPriceDouble);
Console.WriteLine("Suite: {0:F2} lv.",totalPriceSuite);
}
}
}
<file_sep>/Software Technologies/Java Basic Syntax Exercises/src/URLParser.java
import java.util.Scanner;
public class URLParser {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
String protocol = "";
String server = "";
String resource = "";
int protocolEndIndex = input.indexOf("://");
if (protocolEndIndex > 0) {
protocol = input.substring(0, input.indexOf("://"));
input = input.substring(protocolEndIndex + 3);
}
int serverEndIndex = input.indexOf('/');
if (serverEndIndex < 0) {
server = input;
}
else {
server = input.substring(0, serverEndIndex);
resource = input.substring(serverEndIndex + 1);
}
System.out.printf("[protocol] = \"%s\"", protocol);
System.out.println();
System.out.printf("[server] = \"%s\"", server);
System.out.println();
System.out.printf("[resource] = \"%s\"", resource);
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-September-2017/ConditionalStatementsAndLoops/09.MultiplicationTable/Program.cs
namespace MultiplicationTable
{
using System;
public class Program
{
static void Main()
{
int multiplaer = int.Parse(Console.ReadLine());
for (int i = 1; i <= 10; i++)
{
Console.WriteLine("{0} X {1} = {2}", multiplaer, i, multiplaer * i);
}
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-September-2017/Regular Expressions (RegEx) - Exercises/01.Extract Emails/ExtractEmails.cs
using System;
using System.Text.RegularExpressions;
namespace _01.Extract_Emails
{
public class ExtractEmails
{
public static void Main()
{
string input = Console.ReadLine();
string pattern = @"([\w.-]+\@[a-zA-Z-]+)(\.[a-zA-Z-]+)+";
Regex regex = new Regex(pattern);
MatchCollection emailCollect = regex.Matches(input);
foreach (Match email in emailCollect)
{
string emails = email.ToString();
if (!(emails.StartsWith(".") || emails.StartsWith("-") || emails.StartsWith("_") ||
emails.EndsWith("-") || emails.EndsWith(".") || emails.EndsWith("_")))
{
Console.WriteLine(email);
}
}
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-September-2017/Arrays-Lab/06.ReverseAnArrayOfStrings/ReverseAnArrayOfStrings.cs
namespace _06.ReverseAnArrayOfStrings
{
using System;
using System.Linq;
public class ReverseAnArrayOfStrings
{
public static void Main()
{
string[] array = Console.ReadLine()
.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
.ToArray();
Array.Reverse(array);
foreach (var word in array)
{
Console.Write(word + " ");
}
Console.WriteLine();
}
}
}
<file_sep>/Software Technologies/JavaScript Syntax and Basic Web - Lab/04. Three Integers Sum.js
function integersSum([nums]) {
nums = nums.split(' ').map(n => Number(n));
if (nums[0] + nums[1] == nums[2]) {
console.log(`${Math.min(nums[0], nums[1])} + ${Math.max(nums[0], nums[1])} = ${nums[2]}`);
} else if (nums[0] + nums[2] == nums[1]) {
console.log(`${Math.min(nums[0], nums[2])} + ${Math.max(nums[0], nums[2])} = ${nums[1]}`);
} else if (nums[1] + nums[2] == nums[0]) {
console.log(`${Math.min(nums[1], nums[2])} + ${Math.max(nums[1], nums[2])} = ${nums[0]}`);
} else {
console.log('No');
}
}
integersSum(['8 15 7']);
<file_sep>/Programming Fundamentals/Programming-Fundamentals-Extended-November-2017/Data Types, Variables and Methods - Exercise/02. Hornet Wings/HornetWings.cs
namespace _02.Hornet_Wings
{
using System;
public class HornetWings
{
public static void Main()
{
long wingFlaps = long.Parse(Console.ReadLine());
double distanceInMeters = double.Parse(Console.ReadLine()); //A hornet travels for 1000 wing flaps.
long endurance = long.Parse(Console.ReadLine()); //A hornet rests for 5 seconds.
//A hornet makes a 100 wingflaps per second.
double distance = (wingFlaps / 1000) * distanceInMeters;
long timeInSeconds = wingFlaps / 100;
long totalRest = (wingFlaps / endurance) * 5;
long totalTimeInSeconds = timeInSeconds + totalRest;
Console.WriteLine($"{distance:F2} m.");
Console.WriteLine($"{totalTimeInSeconds} s.");
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-September-2017/MethodsDebuggingАndTroubleshootingCode-Exercises/02.MaxMethod/Program.cs
namespace _02.MaxMethod
{
using System;
public class Program
{
static void Main()
{
int firstNumber = int.Parse(Console.ReadLine());
int secondNUmber = int.Parse(Console.ReadLine());
int thirdNumber = int.Parse(Console.ReadLine());
int biggerNum = GetMaxNumber(firstNumber, secondNUmber);
if (biggerNum > thirdNumber)
{
Console.WriteLine(biggerNum);
} else
{
Console.WriteLine(thirdNumber);
}
}
public static int GetMaxNumber(int a, int b)
{
int bigger = 0;
if (a > b)
{
bigger = a;
} else
{
bigger = b;
}
return bigger;
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-September-2017/StringsAndTextProcessing-Exercise/04.CharacterMultiplier/characterMultiplier.cs
namespace _04.CharacterMultiplier
{
using System;
using System.Linq;
using System.Numerics;
public class characterMultiplier
{
public static void Main()
{
string[] line = Console.ReadLine().Split(' ').ToArray();
string first = line[0];
string two = line[1];
char[] firstLine = first.ToCharArray();
char[] secondLine = two.ToCharArray();
int min = Math.Min(firstLine.Length, secondLine.Length);
int sum = 0;
int max = Math.Max(firstLine.Length, secondLine.Length);
for (int i = 0; i < min; i++)
{
sum += firstLine[i] * secondLine[i];
secondLine[i]--;
}
if (firstLine.Length != secondLine.Length)
{
string longerInput = first.Length > two.Length ? longerInput = first : longerInput = two;
for (int i = min; i < max; i++)
{
sum += longerInput[i];
}
}
string output = sum.ToString();
Console.WriteLine(output);
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-September-2017/DataTypesAndVariables-Exercises/11.ConvertSpeedUnits/Program.cs
namespace _11.ConvertSpeedUnits
{
using System;
public class Program
{
static void Main()
{
float distanceInMeters = Convert.ToSingle(Console.ReadLine());
float hours = Convert.ToSingle(Console.ReadLine());
float minutes= Convert.ToSingle(Console.ReadLine());
float seconds = Convert.ToSingle(Console.ReadLine());
float timeInSeconds = (hours * 3600) + (minutes * 60) + seconds;
float metersPerSecond = distanceInMeters / timeInSeconds;
float kilometersPerSecond = (distanceInMeters / 1000.0f) / (timeInSeconds / 3600.0f);
float milesPerSecond = kilometersPerSecond / 1.609f;
Console.WriteLine($"{metersPerSecond}");
Console.WriteLine($"{kilometersPerSecond}");
Console.WriteLine($"{milesPerSecond}");
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-September-2017/Arrays-Exercise/04.SieveOfEratosthenes/SieveOfEratoshenes.cs
namespace _04.SieveOfEratosthenes
{
using System;
using System.Collections.Generic;
using System.Linq;
public class SieveOfEratoshenes
{
public static void Main()
{
int number = int.Parse(Console.ReadLine());
bool[] boolArray = new bool[number + 1];
for (int i = 0; i < boolArray.Length; i++)
{
boolArray[i] = true;
}
for (int i = 2; i < Math.Sqrt(number); i++)
{
if (boolArray[i])
{
for (int j = i * i; j < number + 1; j += i)
{
boolArray[j] = false;
}
}
}
List<int> result = new List<int>();
for (int i = 2; i < boolArray.Length; i++)
{
if (boolArray[i])
{
result.Add(i);
}
}
Console.WriteLine(string.Join(" ", result));
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-Extended-May-2017/List Lab Exercises - May 2017 Extended/1.RemoveNegativeReverse/Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _1.RemoveNegativeRever
{
class Program
{
static void Main(string[] args)
{
List<int> removeNegatives = Console.ReadLine().Split(' ').Select(int.Parse).ToList();
bool IsEmpty = false;
for (int cnt = 0; cnt < removeNegatives.Count; cnt++)
{
if (removeNegatives[cnt] < 0)
{
removeNegatives.RemoveAt(cnt);
cnt--;
}
}
removeNegatives.Reverse();
if (removeNegatives.Count > 0)
{
Console.WriteLine(String.Join(" ", removeNegatives));
} else
{
Console.WriteLine("empty");
}
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-September-2017/FilesDirectoriesАndExceptions-Exercise/06.FixEmails/FixEmails.cs
namespace _06.FixEmails
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
public class FixEmails
{
public static void Main()
{
string[] lines = File.ReadAllLines("input.txt");
File.Delete("output.txt");
Dictionary<string, string> emailCordinats = new Dictionary<string, string>();
int nameIndex = 0;
int emailIndex = 1;
while (lines[nameIndex] != "stop")
{
Add(lines[nameIndex], lines[emailIndex]);
nameIndex += 2;
emailIndex += 2;
}
foreach (var name in emailCordinats)
{
string output = $"{name.Key} -> {name.Value}" + Environment.NewLine;
File.AppendAllText("output.txt", output);
}
void Add(string name, string email)
{
if (!emailCordinats.ContainsKey(name))
{
if (!email.Contains(".us") || email.Contains(".uk"))
{
emailCordinats.Add(name, email);
}
}
}
}
}
}<file_sep>/Programming Fundamentals/PF-Exams/PF-Exam-05November2017/04. Anonymous Cache/AnonymousCache.cs
namespace _04.Anonymous_Cache
{
using System;
using System.Collections.Generic;
using System.Linq;
public class AnonymousCache
{
public static void Main() // 90/100 Points - Missing Case
{
Dictionary<string, Dictionary<string, long>> data = new Dictionary<string, Dictionary<string, long>>();
string input = Console.ReadLine();
while (input != "thetinggoesskrra")
{
var commands = input.Split(new string[] { " -> ", " | ", "-", ">", "|", " ", }, StringSplitOptions.RemoveEmptyEntries).ToList();
if (commands.Count == 0)
{
input = Console.ReadLine();
}
if (commands.Count == 1)
{
if (data.ContainsKey(commands[0]))
{
}
else if (!data.ContainsKey(commands[0]))
{
data.Add(commands[0], new Dictionary<string, long>());
}
}
else if (commands.Count != 1)
{
string dataKey = commands[0];
long num = long.Parse(commands[1]);
string key = commands[2];
if (!data.ContainsKey(key))
{
data.Add(key, new Dictionary<string, long>());
data[key].Add(dataKey, num);
}
if (!data[key].ContainsKey(dataKey))
{
data[key].Add(dataKey, 0);
}
if (data[key].ContainsKey(dataKey))
{
data[key][dataKey] += num;
}
data[key][dataKey] = num;
}
input = Console.ReadLine();
}
if (data.Count == 0) return;
if (data.Count > 0)
{
foreach (var item in data.OrderByDescending(x => x.Value.Values.Sum()))
{
int count = 0;
if (count != 1)
{
Console.WriteLine($"Data Set: {item.Key}, Total Size: {item.Value.Values.Sum()}");
foreach (var items in item.Value)
{
var dataBaseInput = items.Key;
Console.WriteLine($"$.{dataBaseInput}");
}
count++;
break;
}
}
}
}
}
}
<file_sep>/Software Technologies/Java Basic Syntax Exercises/src/BombNumbers.java
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
import java.util.stream.Collectors;
public class BombNumbers {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
List<Integer> numbers = Arrays.stream(scanner.nextLine().split("\\s+"))
.map(Integer::parseInt)
.collect(Collectors.toList());
int[] tokens = Arrays.stream(scanner.nextLine()
.split("\\s+"))
.mapToInt(Integer::parseInt).toArray();
int specialNum = tokens[0];
int range = tokens[1];
while (numbers.contains(specialNum)) {
int index = numbers.indexOf(specialNum);
int leftIndex = index - range;
if (leftIndex < 0) {
leftIndex = 0;
}
int rightIndex = index + range;
if (rightIndex >= numbers.size()) {
rightIndex = numbers.size() - 1;
}
numbers.subList(leftIndex, rightIndex + 1).clear();
}
int sum = numbers.stream().mapToInt(Integer::intValue).sum();
System.out.println(sum);
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-September-2017/DictionariesLambdaAndLINQ-Exercise/09.LegendaryFarming/legendaryFarming.cs
namespace _09.LegendaryFarming
{
using System;
using System.Collections.Generic;
using System.Linq;
public class LegendaryFarming
{
public static void Main()
{
var keyMaterials = new Dictionary<string, int>() { ["motes"] = 0, ["fragments"] = 0, ["shards"] = 0 };
var junkMaterials = new SortedDictionary<string, int>();
var input = Console.ReadLine()
.ToLower().Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
.ToList();
while (true)
{
int quantity = 0;
var nameMaterial = String.Empty;
for (int i = 0; i < input.Count; i += 2)
{
quantity = int.Parse(input[i]);
nameMaterial = input[i + 1];
if (keyMaterials.ContainsKey(nameMaterial))
{
keyMaterials[nameMaterial] += quantity;
if (keyMaterials[nameMaterial] >= 250)
{
break;
}
}
else if (!junkMaterials.ContainsKey(nameMaterial))
{
junkMaterials.Add(nameMaterial, quantity);
}
else if (junkMaterials.ContainsKey(nameMaterial))
{
junkMaterials[nameMaterial] += quantity;
}
}
if (keyMaterials["shards"] >= 250 || keyMaterials["fragments"] >= 250 || keyMaterials["motes"] >= 250)
{
if (keyMaterials["shards"] >= 250)
{
Console.WriteLine("Shadowmourne obtained!");
}
else if (keyMaterials["fragments"] >= 250)
{
Console.WriteLine("Valanyr obtained!");
}
else
{
Console.WriteLine("Dragonwrath obtained!");
}
keyMaterials[nameMaterial] -= 250;
foreach (var material in keyMaterials.OrderByDescending(a => a.Value).ThenBy(a => a.Key))
{
Console.WriteLine($"{material.Key}: {material.Value}");
}
foreach (var material in junkMaterials)
{
Console.WriteLine($"{material.Key}: {material.Value}");
}
return;
}
input = Console.ReadLine()
.ToLower().Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
.ToList();
}
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-September-2017/StringsAndTextProcessing-Exercise/03.UnicodeCharacters/UnicodeCharacters.cs
namespace _03.UnicodeCharacters
{
using System;
public class UnicodeCharacters
{
public static void Main()
{
string input = Console.ReadLine();
char[] chars = input.ToCharArray();
string output = String.Empty;
foreach (var charr in chars)
{
output += "\\u" + ((int)charr).ToString("X4");
}
Console.WriteLine(output.ToLower());
}
}
}
<file_sep>/Software Technologies/Java Basic Syntax Exercises/src/ChangeToUppercase.java
import java.util.Scanner;
public class ChangeToUppercase {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
while (true) {
int tagOpenIndex = input.indexOf("<upcase>");
int tagCloseIndex = input.indexOf("</upcase>");
if (tagCloseIndex < 0 || tagOpenIndex < 0) {
break;
}
String replace = input.substring(tagOpenIndex, tagCloseIndex + 9);
input = input.replace(replace, replace.substring(8, replace.length() - 9).toUpperCase());
}
System.out.println(input);
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-Extended-May-2017/Arrays and Methods - May 2017 Extended/10.Negatives Elem/Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _10.Negatives_Elem
{
class Program
{
static void Main(string[] args)
{
int numberOfTokens = int.Parse(Console.ReadLine());
int[] arrayToCheck = new int[numberOfTokens];
int negativeCounter = 0;
for (int cnt = 0; cnt < numberOfTokens; cnt++)
{
arrayToCheck[cnt] = int.Parse(Console.ReadLine());
if (arrayToCheck[cnt] < 0)
{
negativeCounter++;
}
}
Console.WriteLine(negativeCounter);
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-September-2017/ConditionalStatementsAndLoops-Exercises/08.CaloriesCounter/Program.cs
namespace CaloriesCounter
{
using System;
public class Program
{
static void Main()
{
int numberOfProducts = int.Parse(Console.ReadLine());
int counter = 0;
int cheese = 500;
int tomatoSauce = 150;
int salami = 600;
int pepper = 50;
int totalCalories = 0;
while (counter != numberOfProducts)
{
string currentProduct = Console.ReadLine().ToLower();
counter++;
if (currentProduct == "cheese")
{
totalCalories += cheese;
}
else if (currentProduct == "tomato sauce")
{
totalCalories += tomatoSauce;
}
else if (currentProduct == "salami")
{
totalCalories += salami;
}
else if (currentProduct == "pepper")
{
totalCalories += pepper;
} else
{
// currentProduct = Console.ReadLine().ToLower();
}
}
Console.WriteLine("Total calories: {0}", totalCalories);
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-September-2017/FilesDirectoriesАndExceptions-Exercise/08.AverageGrades/AverageGrades.cs
namespace _08.AverageGrades
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
public class Student
{
public string Name { get; set; }
public List<double> Grades { get; set; }
public double AverageGrade
{
get
{
return Grades.Average();
}
}
}
public class AverageGrades
{
public static void Main()
{
// Number of students that will be entered in db.
var numberStudents = File.ReadAllLines("studentsCount.txt");
int enteredStudents = 0;
foreach (var num in numberStudents)
{
enteredStudents = int.Parse(num);
}
var studentsGrades = File.ReadAllLines("input.txt");
File.Delete("output.txt");
List<Student> student = new List<Student>();
foreach (var soldier in studentsGrades)
{
var inputData = soldier.Split(' ').ToList();
var currentStudent = new Student();
currentStudent.Name = inputData[0]; // Enter name from the List.
currentStudent.Grades = inputData.Skip(1).Select(double.Parse).ToList(); // Take all the grades to
student.Add(currentStudent); // add currentStud to List in Main() // List 'Grades' in Student Class
} // Skip(1) cuz this is the index with name
student.Where(g => g.AverageGrade >= 5.00).OrderBy(n => n.Name).ThenByDescending(n => n.AverageGrade).ToList()
.ForEach(f => File.AppendAllText("output.txt", $"{f.Name} -> {f.AverageGrade:F2}" + Environment.NewLine));
//First get studs with avergGrade big than 5.00, order by name, THEN by grade. If its ToList -> there is foreach method.
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-September-2017/RegularExpressions(RegEx)-Lab/02.MatchPhoneNumber/MatchPointNumber.cs
namespace _02.MatchPhoneNumber
{
using System;
using System.Linq;
using System.Text.RegularExpressions;
public class MatchPointNumber
{
public static void Main()
{
string regex = @"(\+359([ |-])2\2\d{3}\2\d{4})\b";
var phones = Console.ReadLine();
MatchCollection phoneMatches = Regex.Matches(phones, regex);
var matchedPhones = phoneMatches.Cast<Match>().Select(nameof => nameof.Value).ToArray();
Console.WriteLine(String.Join(", ", matchedPhones));
}
}
}
<file_sep>/Software Technologies/HTML5 and CSS - Blog Design/indexlogged.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>My First Test Blog</title>
<link type="text/css" rel="stylesheet" href="styles/style.css">
<script src="scripts/jquery-3.3.1.js"></script>
<script src="scripts/bootstrap.js"></script>
</head>
<body>
<header>
<div class="navbar navbar-default navbar-fixed-top text-uppercase">
<div class="container" >
<div class="navbar-header">
<a href="index.html" class="navbar-brand">My Test Blog for HTML</a>
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav navbar-right">
<li><a href="indexlogged.html">Welcome(User)</a> </li>
<li><a href="createnewpsot.html">New Post</a></li>
<li><a href="index.html">Logout</a></li>
</ul>
</div>
</div>
</div>
</header>
<main>
<div class="container body-content">
<div class="row">
<div class="col-md-6">
<article>
<h2>New rules for bats</h2>
</article>
<p>
WAUPACA, Wis. — <NAME> invested his life savings into a new baseball bat this spring. He paid $250 for a sleek DeMarini Voodoo bat, a model he hopes will help him live up to the nickname Big Country, which he earned for the long balls he hit deep into the outfield.
The investment was not entirely his own decision. Zeamer, 10, and millions of other youth baseball players were forced to dig deep into their (or their parents’) pockets for new bats this season, models stamped with the U.S.A. Baseball logo and mandated by new standards issued by the organization.
The changeover has angered parents who have been shocked by the bats’ high costs — $45 to $350 — and frustrated that the demand has seemingly outstripped the supply. Many sporting goods stores and online retailers struggled to stock the approved bats, especially the ones at the lower price points.
Adding to the anger, a popular model made by Easton was decertified by U.S.A. Baseball in May, leading the company to offer a $500 e-voucher to anyone who had purchased the bat — but only to spend on other Easton products.
<NAME>, John’s mother, said she was already in deep for this year’s baseball budget. John wears adult sizes, and everything needed to be replaced: a helmet ($50), two pairs of pants ($70), batting gloves ($20), cleats ($70) and catcher’s gear ($200).
“I wasn’t happy because he just got a new bat last year,” <NAME> said. “I really thought he was set for a while.”
</p>
<small class="author">
New York Times
</small>
<footer>
<div class="pull-right">
<a class="btn btn-default btn-xs" href="#">Read more »</a>
</div>
</footer>
</div>
<div class="col-md-6">
<article>
<h2>Robots open source ?</h2>
</article>
<p>
Open-source robotics (OSR) is where the physical artifacts of the subject are offered by the open design movement.
This branch of robotics makes use of open-source hardware and free and open source software providing blueprints,
schematics, and source code. The term usually means that information about the hardware is easily discerned so that
others can make it from standard commodity components and tools—coupling it closely to the maker
movement[1] and open science.
</p>
<small class="author">
Wikipedia
</small>
<footer>
<div class="pull-right">
<a class="btn btn-default btn-xs" href="#">Read more »</a>
</div>
</footer>
</div>
<div class="col-md-6">
<article>
<h2>Sofia, where are the parks ?</h2>
</article>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut a mollis felis.
Phasellus sollicitudin posuere mattis. Nulla euismod vehicula arcu, sed semper ex lacinia non.
Proin ante lacus, faucibus eu lobortis et, lacinia vel tortor. Fusce tincidunt, dui ut laoreet eleifend,
felis purus auctor nibh, at euismod orci tortor vitae felis. Suspendisse sed enim non turpis pulvinar fermentum.
Sed eget gravida eros. Quisque congue blandit arcu. Pellentesque commodo velit lacus, sit amet gravida nibh finibus ac.
Praesent rhoncus malesuada ligula ut scelerisque. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Integer vitae scelerisque eros, eget vulputate turpis. Nullam eros nulla, maximus vel leo vitae, dictum suscipit nisi.
Duis mollis lectus vel porta consectetur.
</p>
<small class="author">
Lorem Ipsum
</small>
<footer>
<div class="pull-right">
<a class="btn btn-default btn-xs" href="#">Read more »</a>
</div>
</footer>
</div>
<div class="col-md-6">
<article>
<h2>Lorem Ipsum</h2>
</article>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut a mollis felis.
Phasellus sollicitudin posuere mattis. Nulla euismod vehicula arcu, sed semper ex lacinia non.
Proin ante lacus, faucibus eu lobortis et, lacinia vel tortor. Fusce tincidunt, dui ut laoreet eleifend,
felis purus auctor nibh, at euismod orci tortor vitae felis. Suspendisse sed enim non turpis pulvinar fermentum.
Sed eget gravida eros. Quisque congue blandit arcu. Pellentesque commodo velit lacus, sit amet gravida nibh finibus ac.
Praesent rhoncus malesuada ligula ut scelerisque. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Integer vitae scelerisque eros, eget vulputate turpis. Nullam eros nulla, maximus vel leo vitae, dictum suscipit nisi.
Duis mollis lectus vel porta consectetur.
</p>
<small class="author">
Lorem Ipsum 2
</small>
<footer>
<div class="pull-right">
<a class="btn btn-default btn-xs" href="#">Read more »</a>
</div>
</footer>
</div>
<div class="col-md-6">
<article>
<h2>Test Article</h2>
</article>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut a mollis felis.
Phasellus sollicitudin posuere mattis. Nulla euismod vehicula arcu, sed semper ex lacinia non.
Proin ante lacus, faucibus eu lobortis et, lacinia vel tortor. Fusce tincidunt, dui ut laoreet eleifend,
felis purus auctor nibh, at euismod orci tortor vitae felis. Suspendisse sed enim non turpis pulvinar fermentum.
Sed eget gravida eros. Quisque congue blandit arcu. Pellentesque commodo velit lacus, sit amet gravida nibh finibus ac.
Praesent rhoncus malesuada ligula ut scelerisque. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Integer vitae scelerisque eros, eget vulputate turpis. Nullam eros nulla, maximus vel leo vitae, dictum suscipit nisi.
Duis mollis lectus vel porta consectetur.
</p>
<small class="author">
B.B.
</small>
<footer>
<div class="pull-right">
<a class="btn btn-default btn-xs" href="#">Read more »</a>
</div>
</footer>
</div>
</div>
</div>
</main>
<footer>
<div class="container modal-footer">
<p class="text-center">© 2018 - <NAME> Some Rights Reserved</p>
</div>
</footer>
</body>
</html><file_sep>/Programming Fundamentals/Programming-Fundamentals-September-2017/ConditionalStatementsAndLoops-Exercises/03.RestaurantDiscount/Program.cs
namespace Restaurant_Discount
{
using System;
public class Program
{
static void Main()
{
int groupSize = int.Parse(Console.ReadLine());
string restaurantPackage = Console.ReadLine();
string place = String.Empty;
int placePrice = 0;
int smallHall = 2500;
int terrace = 5000;
int greatHall = 7500;
if (groupSize > 0 && groupSize <= 50)
{
place = "Small Hall";
placePrice = smallHall;
} else if (groupSize > 50 && groupSize <= 100)
{
place = "Terrace";
placePrice = terrace;
} else if (groupSize > 100 && groupSize <= 120)
{
place = "Great Hall";
placePrice = greatHall;
} else if (groupSize > 120)
{
Console.WriteLine("We do not have an appropriate hall.");
}
int packagePrice = 0;
double discount = 0;
double totalPrice = 0;
switch (restaurantPackage)
{
case "Normal":
packagePrice = 500;
discount = 0.05;
totalPrice = (placePrice + packagePrice) - ((placePrice + packagePrice) * discount);
break;
case "Gold":
packagePrice = 750;
discount = 0.1;
totalPrice = (placePrice + packagePrice) - ((placePrice + packagePrice) * discount);
break;
case "Platinum":
packagePrice = 1000;
discount = 0.15;
totalPrice = (placePrice + packagePrice) - ((placePrice + packagePrice) * discount);
break;
}
if (groupSize > 0 && groupSize <= 129)
{
Console.WriteLine("We can offer you the {0}", place);
Console.WriteLine("The price per person is {0:F2}$", totalPrice / groupSize);
}
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-Extended-May-2017/Arrays and Methods - May 2017 Extended/3. Phonebook/Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
namespace _3.Phonebook
{
class Program
{
static void Main(string[] args)
{
string[] phoneNumbers = Console.ReadLine().Split(' ').ToArray();
string[] phoneNames = Console.ReadLine().Split(' ').ToArray();
string input = Console.ReadLine();
while (input != "done")
{
for (int cnt = 0; cnt < phoneNames.Length; cnt++)
{
if (input == phoneNames[cnt])
{
Console.WriteLine($"{phoneNames[cnt]} -> {phoneNumbers[cnt]}");
break;
}
}
input = Console.ReadLine();
}
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-Extended-November-2017/String, Regular Expressions and Text Processing - Exercise/02. Anonymous Vox/AnonymousVox.cs
namespace _02.Anonymous_Vox
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
public class AnonymousVox
{
public static void Main()
{
string input = Console.ReadLine();
List<string> placeHolders = Console.ReadLine()
.Split(new char[] { '{', '}' }, StringSplitOptions.RemoveEmptyEntries)
.ToList(); //Split("{}".ToCharArray()) - в кавичките може всичко и го разбира на чарове
//Second way to Split the input .
//string[] placeHolders = Regex.Split(Console.ReadLine(), "[{}]")
// .Where(x => x != String.Empty).ToArray();
string patternOne = @"([a-zA-Z]+)(.*)(\1)";
MatchCollection match = Regex.Matches(input, patternOne);
int counter = 0;
foreach (Match m in match)
{
string newString = m.Groups[1] + placeHolders[counter++] + m.Groups[3];
input = input.Replace(m.Value, newString);
}
Console.WriteLine(input);
}
}
}
<file_sep>/Software Technologies/Exam Preparation III - LogNoziroh & ShoppingList/ShoppingList/JavaScript Solution/controllers/product.js
const Product = require('../models').Product;
module.exports = {
index: (req, res) => {
//TODO
Product.findAll().then(entries => {
res.render("product/index",
{"entries": entries})}); //entries come from index view - for each entries !!!
},
createGet: (req, res) => {
//TODO
res.render("product/create");
},
createPost: (req, res) => {
//TODO
let args = req.body;
//console.log(args);
Product.create(args).then(()=>{res.redirect("/");
})
},
editGet: (req, res) => {
//TODO
let id = req.params.id;
Product.findById(id)
.then((product => {
res.render("product/edit",
product.dataValues);
}));
},
editPost: (req, res) => {
//TODO
let id = req.params.id;
let args = req.body;
Product.findById(id)
.then(product => product.updateAttributes(args))
.then(()=> {res.redirect('/')});
}
};<file_sep>/Programming Fundamentals/Programming-Fundamentals-Extended-May-2017/Lists - Exercises/3.Equal Sum After Extraction/Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
namespace EqualSumAfterExtraction
{
class Program
{
static void Main(string[] args)
{
List<int> firstList = Console.ReadLine().Split(' ').Select(int.Parse).ToList();
List<int> secondList = Console.ReadLine().Split(' ').Select(int.Parse).ToList();
List<int> secondResult = new List<int>();
for (int cnt = 0; cnt < firstList.Count; cnt++)
{
for (int i = 0; i < secondList.Count; i++)
{
if (firstList[cnt] == secondList[i])
{
secondList.RemoveAt(i);
i--;
}
}
}
long sumList1 = 0L;
long sumList2 = secondList.Sum();
foreach (int num in firstList)
{
sumList1 += num;
}
if (sumList1 == sumList2)
{
Console.WriteLine("Yes. Sum: " + sumList2);
} else
{
Console.WriteLine("No. Diff: " + Math.Abs(sumList2 - sumList1));
}
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-September-2017/DataTypesAndVariables-Exercises/01.PracticeIntegerNumbers/Program.cs
namespace _01.PracticeIntegerNumbers
{
using System;
public class Program
{
static void Main()
{
sbyte number1 = sbyte.Parse(Console.ReadLine());
byte number2 = byte.Parse(Console.ReadLine());
short number3 = short.Parse(Console.ReadLine());
ushort number4 = ushort.Parse(Console.ReadLine());
long number5 = long.Parse(Console.ReadLine());
long number6 = long.Parse(Console.ReadLine());
long number7 = long.Parse(Console.ReadLine());
Console.WriteLine(number1);
Console.WriteLine(number2);
Console.WriteLine(number3);
Console.WriteLine(number4);
Console.WriteLine(number5);
Console.WriteLine(number6);
Console.WriteLine(number7);
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-Extended-November-2017/Arrays, Lists, Array and List Algorithms - Lab/02. Odd Numbers at Odd Positions/OddNumberAtOddPosition.cs
namespace _02.Odd_Numbers_at_Odd_Positions
{
using System;
using System.Linq;
public class OddNumberAtOddPosition
{
public static void Main()
{
int[] numbers = Console.ReadLine().Split().Select(int.Parse).ToArray();
string prefix = "Index";
for (int i = 0; i < numbers.Length; i++)
{
int currentNumber = numbers[i];
if (i % 2 != 0 && currentNumber % 2 != 0)
{
Console.WriteLine($"{prefix} {i} -> {numbers[i]}");
}
}
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-Extended-May-2017/List - More Exercises Extended May 2017/3. Camel-s Back/Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _3.Camel_s_Back
{
class Program
{
static void Main(string[] args)
{
List<int> integersList = Console.ReadLine().Split(' ').Select(int.Parse).ToList();
string input = Console.ReadLine();
while (input != "end")
{
int currentNumber = (int)(input[0] - '0');
int element = int.Parse(input);
integersList.Insert(currentNumber, element);
input = Console.ReadLine();
}
Console.WriteLine(String.Join(" ", integersList));
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-September-2017/ConditionalStatementsAndLoops-Exercises/14.MagicLetter/Program.cs
namespace MagicLetter
{
using System;
public class Program
{
static void Main()
{
char firstChar = char.Parse(Console.ReadLine().ToLower());
char secondChar = char.Parse(Console.ReadLine().ToLower());
char thurdChar = char.Parse(Console.ReadLine().ToLower());
for (char i = firstChar; i <= secondChar; i++)
{
for (char j = firstChar; j <= secondChar; j++)
{
for (char k = firstChar; k <= secondChar; k++)
{
if (!(i == thurdChar || j == thurdChar || k == thurdChar))
{
Console.Write("{0}{1}{2} ", i, j, k);
}
}
}
}
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-Extended-November-2017/Dictionaries, Nested Collections, LINQ and Lambda Expressions - Lab/01. Odd Occurrences/OddOccurences.cs
namespace _01.Odd_Occurrences
{
using System;
using System.Collections.Generic;
public class OddOccurences
{
public static void Main()
{
Dictionary<string, int> words = new Dictionary<string, int>();
List<string> result = new List<string>();
string input = Console.ReadLine().ToLower();
var hhh = input.Split(new char[] { ' ', }, StringSplitOptions.RemoveEmptyEntries);
foreach (string item in hhh)
{
if (!words.ContainsKey(item))
{
words.Add(item, 1);
}
else
{
words[item]++;
}
}
foreach (var item in words)
{
if ((item.Value % 2 == 1))
{
result.Add(item.Key);
}
}
Console.WriteLine(string.Join(", ", result));
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-September-2017/MethodsDebuggingAndTroubleshootingCode/02.SignOfIntegerNumber/Program.cs
namespace _02.SignOfIntegerNumber
{
using System;
public class Program
{
static void Main()
{
int number = int.Parse(Console.ReadLine());
PrintNumberSign(number);
}
static private void PrintNumberSign(int num)
{
if (num >= 1)
{
Console.WriteLine("The number {0} is positive.", num);
} else if (num <= - 1)
{
Console.WriteLine("The number {0} is negative.", num);
} else
{
Console.WriteLine("The number 0 is zero.");
}
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-September-2017/Arrays-Exercise/10.PairsByDifference/PairsByDifference.cs
namespace _10.PairsByDifference
{
using System;
using System.Linq;
public class PairsByDifference
{
public static void Main()
{
int[] numbers = Console.ReadLine()
.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
.Select(int.Parse)
.ToArray();
int difference = int.Parse(Console.ReadLine());
int counter = 0;
for (int i = 0; i < numbers.Length; i++)
{
for (int k = i; k < numbers.Length; k++)
{
if (difference == Math.Abs(numbers[i] - numbers[k]))
{
counter++;
}
}
}
Console.WriteLine(counter);
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-September-2017/MethodsDebuggingAndTroubleshootingCode/01.BlankReceipt/Program.cs
namespace _01.BlankReceipt
{
using System;
public class Program
{
static void Main()
{
PrintReceipt();
}
public static void PrintHeader()
{
Console.WriteLine("CASH RECEIPT");
Console.WriteLine("------------------------------");
}
public static void PringMiddle()
{
Console.WriteLine("Charged to____________________");
Console.WriteLine("Received by___________________");
}
public static void PrintEnd()
{
Console.WriteLine("------------------------------");
Console.WriteLine("\u00A9 SoftUni");
}
public static void PrintReceipt()
{
PrintHeader();
PringMiddle();
PrintEnd();
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-Extended-May-2017/Arrays and Methods - May 2017 Extended/1.Last3EqualStrings/Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _1.Last3EqualStrings
{
class Program
{
static void Main(string[] args)
{
List<string> numberList = Console.ReadLine().Split(' ').ToList();
numberList.Reverse();
for (int cnt = 0; cnt < numberList.Count; cnt++)
{
string word = numberList[cnt];
string word2 = numberList[cnt + 1];
string word3 = numberList[cnt + 2];
if (word == word2 && word2 == word3)
{
Console.WriteLine($"{word} {word2} {word3}");
break;
}
}
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-September-2017/ObjectsАndClasses-Exercise/04.AverageGrades/AverageGrades.cs
namespace _04.AverageGrades
{
using System;
using System.Collections.Generic;
using System.Linq;
public class Student
{
public string Name { get; set; }
public List<double> Grades { get; set; }
public double AverageGrade
{
get
{
return Grades.Average();
}
}
}
public class AverageGrades
{
public static void Main()
{
List<Student> student = new List<Student>();
int enteredStudents = int.Parse(Console.ReadLine());
for (int i = 0; i < enteredStudents; i++)
{
var inputData = Console.ReadLine().Split(' ').ToList();
var currentStudent = new Student();
currentStudent.Name = inputData[0]; // Enter name from the List.
currentStudent.Grades = inputData.Skip(1).Select(double.Parse).ToList(); // Take all the grades to
student.Add(currentStudent); // add currentStud to List in Main() // List 'Grades' in Student Class
} // Skip(1) cuz this is the index with name
student.Where(g => g.AverageGrade >= 5.00).OrderBy(n => n.Name).ThenByDescending(n => n.AverageGrade).ToList()
.ForEach(f => Console.WriteLine($"{f.Name} -> {f.AverageGrade:F2}"));
} //First get studs with avergGrade big than 5.00, order by name, THEN by grade. If its ToList -> there is foreach method.
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-September-2017/DictionariesLambdaAndLINQ-Exercise/01.Phonebook/Disctionary.cs
namespace _01.Phonebook
{
internal class Disctionary<T1, T2>
{
public Disctionary()
{
}
}
}<file_sep>/Programming Fundamentals/Programming-Fundamentals-September-2017/Exam Preparation I/03. Endurance Rally/Endurance Rally.cs
namespace _03.Endurance_Rally
{
using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
public static void Main()
{
// 80/100 Point - Missing cases !!
List<string> drivers = Console.ReadLine().Split(' ').ToList();
double[] numbers = Console.ReadLine().Split(' ').Select(double.Parse).ToArray();
int[] index = Console.ReadLine().Split(' ').Select(int.Parse).ToArray();
//List<int> index = Console.ReadLine().Split(' ').Select(int.Parse).ToList();
int reachedIndex = 0;
for (int i = 0; i < drivers.Count; i++)
{
double fuel = drivers[i][0];
int temp = 0;
for (int k = 0; k < numbers.Length; k++)
{
temp++;
if (index.Contains(k))
{
fuel += numbers[k];
if (fuel <= 0)
{
break;
}
}
else if (numbers[k] > 0)
{
fuel -= numbers[k];
if (fuel <= 0)
{
//Console.WriteLine($"{drivers[i]} - reached 0");
break;
}
}
else if (numbers[k] < 0 && (!index.Contains(k)))
{
fuel += Math.Abs(numbers[k]);
if (fuel <= 0)
{
break;
}
}
}
reachedIndex = temp;
temp = 0;
if (fuel >= 0)
{
Console.WriteLine($"{drivers[i]} - fuel left {fuel:F2}");
}
else
{
Console.WriteLine($"{drivers[i]} - reached {reachedIndex - 1}");
}
}
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-September-2017/Exam Preparation II/03. Nether Realms/NetherRealms.cs
namespace _03.Nether_Realms
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
public class Program
{
public static void Main()
{
List<string> names = Console.ReadLine()
.Split(new char[] { ' ', ',', }, StringSplitOptions.RemoveEmptyEntries)
.ToList();
SortedDictionary<string, Dictionary<long, decimal>> sortedNames = new SortedDictionary<string, Dictionary<long, decimal>>();
foreach (var name in names)
{
long health = 0;
string healthPattern = @"([^0-9+\-\*/\.])";
foreach (Match lettersMatch in Regex.Matches(name, healthPattern))
{
health += Convert.ToChar(lettersMatch.Value);
}
decimal dmg = 0m;
string damagePattern = @"(-?\d+(?:\.?\d+)?)";
foreach (Match letter in Regex.Matches(name, damagePattern))//take num
{
dmg += Convert.ToDecimal(letter.Value);
}
foreach (var symbol in name)
{
if (symbol == '*')
{
dmg *= 2;
}
else if (symbol == '/')
{
dmg /= 2;
}
}
if (!sortedNames.ContainsKey(name))
{
sortedNames.Add(name, new Dictionary<long, decimal>());
}
if (!sortedNames[name].ContainsKey(health))
{
sortedNames[name].Add(health, 0);
}
sortedNames[name][health] = dmg;
}
foreach (var name in sortedNames)
{
foreach (var healthAndDmg in name.Value)
{
Console.WriteLine($"{name.Key} - {healthAndDmg.Key} health, {healthAndDmg.Value:F2} damage");
}
}
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-September-2017/FilesDirectoriesАndExceptions-Exercise/05.AMinerTask/AMinerTask.cs
namespace _05.AMinerTask
{
using System;
using System.Collections.Generic;
using System.IO;
public class AMinerTasker
{
public static void Main()
{
string[] inLines = File.ReadAllLines("input.txt");
File.Delete("output.txt");
var resources = new Dictionary<string, double>();
int materialIndex = 0;
int quantityIndex = 1;
while (inLines[materialIndex] != "stop")
{
Add(inLines[materialIndex], inLines[quantityIndex]);
materialIndex += 2;
quantityIndex += 2;
}
foreach (var pair in resources)
{
string output = $"{pair.Key} -> {pair.Value}" + Environment.NewLine;
File.AppendAllText("output.txt", output);
}
void Add(string res, string quaintity)
{
if (!resources.ContainsKey(res))
{
resources.Add(res, double.Parse(quaintity));
}
else
{
resources[res] += double.Parse(quaintity);
}
}
}
}
}<file_sep>/Programming Fundamentals/Programming-Fundamentals-Extended-May-2017/Arrays and Methods - May 2017 Extended/15.CapitalLettersInArray/Program.cs
using System;
using System.Linq;
namespace _15.CapitalLettersInAr
{
class Program
{
static void Main(string[] args)
{
string[] capitalArray = Console.ReadLine().Split(' ');
int counter = 0;
for (int cnt = 0; cnt < capitalArray.Length; cnt++)
{
string currentElement = capitalArray[cnt];
if (currentElement.Length == 1) // If you change currentElement with capitalArray, it will catch also Capital Letters in words.
{
if (currentElement[0] >= 'A' && currentElement[0] <= 'Z')
{
counter++;
}
}
}
Console.WriteLine(counter);
}
}
}
<file_sep>/Software Technologies/Exam Preparation II - Imbd & Kanban Board/IMDB/JavaScript Skeleton/models/film.js
const Sequelize = require('sequelize');
module.exports = function(sequelize){
// TODO
let Film = sequelize.define('Film', {
name:{type: Sequelize.TEXT, required: true, allowNull: false,
},
genre:{type: Sequelize.TEXT, required: true, allowNull: false,
},
director:{type: Sequelize.TEXT, required: true, allowNull: false,
},
year:{type: Sequelize.INTEGER, required: true, allowNull: false,
},
}, {
timestamps:false
});
return Film;
};<file_sep>/Programming Fundamentals/Programming-Fundamentals-September-2017/Arrays-Exercise/11.EqualSums/EqualSums.cs
namespace _11.EqualSums
{
using System;
using System.Linq;
public class EqualSums
{
public static void Main()
{
int[] number = Console.ReadLine()
.Split(' ')
.Select(int.Parse)
.ToArray();
bool isEqualSum = false;
for (int i = 0; i < number.Length; i++)
{
int[] left = number.Take(i).ToArray();
int[] right = number.Skip(i + 1).ToArray();
if (left.Sum() == right.Sum())
{
isEqualSum = true;
Console.WriteLine(i);
}
}
if (!isEqualSum)
{
Console.WriteLine("no");
}
}
}
}
<file_sep>/Software Technologies/JavaScript Syntax and Basic Web - Exercises/13. StoringObjects.js
function storingObjects(args) {
let personInfo = [];
for (let obj of args) {
let input = obj.split(" -> ");
let name = input[0];
let age = input[1];
let grade = input[2];
let userInfo = {};
userInfo['name'] = name;
userInfo['age'] = age;
userInfo['grade']= grade;
personInfo.push(userInfo);
}
for (let person of personInfo) {
console.log(`Name: ${person.name}`);
console.log(`Age: ${person.age}`);
console.log(`Grade: ${person.grade}`);
}
}
storingObjects([
'Pesho -> 13 -> 6.00',
'Ivan -> 12 -> 5.57',
'Toni -> 13 -> 4.90'
]);<file_sep>/Programming Fundamentals/Programming-Fundamentals-Extended-November-2017/Data Types, Variables and Methods - Exercise/04. Resurrection/Ressurection.cs
namespace _04.Resurrection
{
using System;
using System.Numerics;
public class Ressurection
{
public static void Main()
{
int amountOfPhoenix = int.Parse(Console.ReadLine());
decimal result = 0m;
for (int i = 0; i < amountOfPhoenix; i++)
{
long bodyLenght = long.Parse(Console.ReadLine());
decimal totalWidth = decimal.Parse(Console.ReadLine());
long lenghtOfOneWing = long.Parse(Console.ReadLine());
result = (decimal)Math.Pow(bodyLenght, 2) * (totalWidth + 2 * lenghtOfOneWing);
Console.WriteLine($"{result}");
}
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-Extended-November-2017/Arrays, Lists, Array and List Algorithms - Exercise/02. Icarus/Icarus.cs
namespace _02.Icarus
{
using System;
using System.Collections.Generic;
using System.Linq;
public class Icarus
{
public static void Main()
{
List<int> numbers = Console.ReadLine().Split().Select(int.Parse).ToList();
int startIndex = int.Parse(Console.ReadLine());
int icarusDamage = 1;
string command = Console.ReadLine();
while (command != "Supernova")
{
var commandArgs = command.Split();
string wayToMove = commandArgs[0];
int moves = int.Parse(commandArgs[1]);
if (wayToMove == "left")
{
}
if (wayToMove == "right")
{
}
command = Console.ReadLine();
}
Console.WriteLine(String.Join(" ", numbers));
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-Extended-May-2017/Arrays and Methods - May 2017 Extended/17. Altitude/Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
namespace _17.Altitude
{
class Program
{
static void Main(string[] args)
{
string[] altitudeArray = Console.ReadLine().Split(' ').ToArray();
long altitude = Convert.ToInt64(altitudeArray[0]);
for (int cnt = 0; cnt < altitudeArray.Length; cnt++)
{
if (altitudeArray[cnt] == "up")
{
altitude += Convert.ToInt64(altitudeArray[cnt + 1]);
}
if (altitudeArray[cnt] == "down")
{
altitude -= Convert.ToInt64(altitudeArray[cnt + 1]);
}
if (altitude <= 0)
{
Console.WriteLine("crashed");
return;
}
}
Console.WriteLine($"got through safely. current altitude: {altitude}m");
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-Extended-November-2017/String, Regular Expressions and Text Processing/06. Mathc Phone Number/MatchPhoneNumber.cs
namespace _06.Mathc_Phone_Number
{
using System;
using System.Linq;
using System.Text.RegularExpressions;
public class MatchPhoneNumber
{
public static void Main()
{
string input = Console.ReadLine();
string pattern = @"(\+359([ |-])2\2\d{3}\2\d{4})\b";
//string pattern2 = @"(\+[359]+)( )([0-9])( )([0-9]{3})( )([0-9]{4,4})\b";
var phoneMatches = Regex.Matches(input, pattern);
var matchedPhones = phoneMatches.Cast<Match>().Select(a => a.Value.Trim()).ToArray();
Console.WriteLine(string.Join(", ", matchedPhones));
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-September-2017/Arrays-Lab/05.TripleSum/TripleSum.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _04.TripleSum
{
public class TripleSum
{
public static void Main()
{
int[] numbers = Console.ReadLine()
.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
.Select(int.Parse)
.ToArray();
bool isSumAvaible = false;
for (int a = 0; a < numbers.Length; a++)
{
for (int b = a + 1; b < numbers.Length; b++)
{
int sum = numbers[a] + numbers[b]
; if (numbers.Contains(sum))
{
isSumAvaible = true;
Console.WriteLine($"{numbers[a]} + {numbers[b]} == {sum}");
}
}
}
if (!isSumAvaible)
{
Console.WriteLine("No");
}
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-September-2017/Arrays-Exercise/06.MaxSequenceOfEqualElements/MaxSequenceOfEqualElements.cs
namespace _06.MaxSequenceOfEqualElements
{
using System;
using System.Linq;
public class MaxSequenceOfEqualElements
{
public static void Main()
{
int[] array = Console.ReadLine()
.Split(' ')
.Select(int.Parse)
.ToArray();
int start = 0;
int len = 1;
int bestStart = 0;
int bestLen = 1;
for (int i = 1; i < array.Length; i++)
{
if (array[i] == array[i - 1])
{
start = array[i];
len++;
}
else
{
start = array[1];
len = 1;
}
if (len > bestLen)
{
bestLen = len;
bestStart = start;
}
}
for (int i = 0; i < bestLen; i++)
{
Console.Write(bestStart + " ");
}
Console.WriteLine();
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-Extended-May-2017/Lists - Exercises/4. Flip List Sides/Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
namespace _4.Flip_List_Sides
{
class Program
{
static void Main(string[] args)
{
List<int> list = Console.ReadLine()
.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
.Select(int.Parse)
.ToList();
ReverseList(list);
}
private static void ReverseList(List<int> list)
{
var newList = new List<int>();
var lastNum = list.Count - 1;
newList.Add(list[0]);
for (int i = list.Count - 2; i >= 1; i--)
{
newList.Add(list[i]);
}
newList.Add(list[lastNum]);
Console.WriteLine(string.Join(" ", newList));
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-September-2017/DictionariesLambdaAndLINQ/02.OddOccurrences/OddOccurences.cs
namespace _02.OddOccurrences
{
using System;
using System.Collections.Generic;
using System.Linq;
public class OddOccurences
{
public static void Main()
{
string[] arr = Console.ReadLine()
.ToLower()
.Split(' ')
.ToArray();
var words = new Dictionary<string, int>();
foreach (var word in arr)
{
if (words.ContainsKey(word))
{
words[word]++;
}
else
{
words[word] = 1;
}
}
var result = new List<string>();
foreach (var word in words)
{
if (word.Value % 2 != 0)
{
result.Add(word.Key);
}
}
Console.WriteLine(string.Join(", ", result));
}
}
}
<file_sep>/Software Technologies/JavaScript Syntax and Basic Web - Exercises/04. ProductOf3Numbers.js
function findProduct (args) {
let counter = 0;
let [x, y, z] = args.map(Number);
if (x === 0 || y === 0 || z === 0) {
console.log("Positive");
return;
}
[x, y, z,].forEach(n => {
if (n < 0) {
counter++;
}
});
if (counter % 2 === 0) {
console.log("Positive");
} else {
console.log("Negative");
}
}
findProduct([2, 3, -1]);
findProduct([5, 4, 3]);
findProduct([-3, -4, 5]);
findProduct([2, 1, -1]);<file_sep>/Programming Fundamentals/Programming-Fundamentals-September-2017/Regular Expressions (RegEx) - Exercises/02.Extract Sentences by Keyword/ExtractSentencesByKeyword.cs
using System;
using System.Text.RegularExpressions;
namespace _02.Extract_Sentences_by_Keyword
{
public class ExtractSentencesByKeyword
{
public static void Main() // 100/100
{
string word = Console.ReadLine();
var input = Console.ReadLine().Split(new char[] { '.', '?', '!', }, StringSplitOptions.RemoveEmptyEntries);
string pattern = "\\b" + word + "\\b";
Regex regex = new Regex(pattern);
foreach (var sentance in input)
{
if (regex.IsMatch(sentance))
{
Console.WriteLine(sentance.Trim());
}
}
}
}
}
// 80/100 ??
// using System;
// namespace _02.Extract_Sentences_by_Keyword
// {
// public class ExtractSentencesByKeyword
// {
// public static void Main()
// {
// string word = Console.ReadLine();
// var input = Console.ReadLine().Split(new char[] { '.', '?', '!', }, StringSplitOptions.RemoveEmptyEntries);
// string extraWord = " " + word + " ";
// foreach (var sentance in input)
// {
// if (sentance.Contains(extraWord))
// {
// Console.WriteLine(sentance.Trim('.', '!', '?', ' '));
// }
// }
// }
// }
// }
<file_sep>/Programming Fundamentals/Programming-Fundamentals-Extended-November-2017/Arrays, Lists, Array and List Algorithms - Lab/03. Array Contains Element/ArrayContainsElement.cs
namespace _03.Array_Contains_Element
{
using System;
using System.Linq;
public class ArrayContainsElement
{
public static void Main()
{
int[] numbers = Console.ReadLine().Split().Select(int.Parse).ToArray();
int containedNumber = int.Parse(Console.ReadLine());
if (numbers.Contains(containedNumber))
{
Console.WriteLine("yes");
}
else
{
Console.WriteLine("no");
}
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-September-2017/Regular Expressions (RegEx) - Exercises/05.Key Replacer/KeyReplacer.cs
namespace _05.Key_Replacer
{
using System;
using System.Text;
using System.Text.RegularExpressions;
public class KeyReplacer
{
public static void Main() //66/100 - Jugde.System --> Missing cases !!
{
string keys = Console.ReadLine();
Regex pattern = new Regex(@"^(?<start>[a-zA-Z]+)((?:[<|\\]).*?[<|\\])(?<end>[a-zA-Z]+)$");
if (pattern.IsMatch(keys))
{
string start = pattern.Match(keys).Groups["start"].Value;
string end = pattern.Match(keys).Groups["end"].Value;
string input = Console.ReadLine();
string newPattern = @"(?:" + string.Format("{0}", start) + ")" +
@"(?<take>.*?)" +
@"(?:" + string.Format("{0}", end) + ")";
Regex newRegex = new Regex(newPattern);
if (newRegex.IsMatch(input))
{
MatchCollection matches = newRegex.Matches(input);
StringBuilder output = new StringBuilder();
foreach (Match item in matches)
{
output.Append(item.Groups["take"].Value);
}
if (output.Length.Equals(0))
{
Console.WriteLine("Empty result");
}
else
{
Console.WriteLine(output);
}
}
}
else
{
Console.WriteLine("Empty result");
}
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-September-2017/Exam Preparation III/03.Rage Quit/Rage Quit.cs
namespace _03.Rage_Quit
{
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
public class Program
{
public static void Main()
{ //100/100 Point
string karakacil = Console.ReadLine().ToUpper();
HashSet<char> uniqueChars = new HashSet<char>();
MatchCollection match = Regex.Matches(karakacil, @"([^0-9]+)(\d+)");
//This regex catch everything except digits(firstGroup)(onlyDigits)
StringBuilder sb = new StringBuilder();
foreach (Match matchh in match)
{
string str = matchh.Groups[1].Value;
int count = int.Parse(matchh.Groups[2].Value);
while (count > 0)
{
sb.Append(str);
count--;
}
}
string gandalf = sb.ToString();
foreach (var letter in gandalf)
{
if (!Char.IsDigit(letter))
{
uniqueChars.Add(letter);
}
}
Console.WriteLine($"Unique symbols used: {uniqueChars.Count}");
Console.WriteLine(sb.ToString());
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-September-2017/MethodsDebuggingAndTroubleshootingCode/08.GreaterOfTwoValues/Program.cs
namespace _08.GreaterOfTwoValues
{
using System;
public class Program
{
static void Main()
{
string dataType = Console.ReadLine();
GetDataTypeAndResult(dataType);
}
private static void GetDataTypeAndResult(string input)
{
if (input == "string")
{
string firstWord = Console.ReadLine();
string secondWord = Console.ReadLine();
Console.WriteLine(GetMax(firstWord, secondWord));
}
else if (input == "int")
{
int firstNumber = int.Parse(Console.ReadLine());
int secondNumber = int.Parse(Console.ReadLine());
Console.WriteLine(GetMax(firstNumber, secondNumber));
}
else if (input == "char")
{
char firstChar = char.Parse(Console.ReadLine());
char secondChar = char.Parse(Console.ReadLine());
Console.WriteLine(GetMax(firstChar, secondChar));
}
}
public static int GetMax(int firstNumber, int secondNumber)
{
int bigger = 0;
if (firstNumber > secondNumber)
{
bigger = firstNumber;
} else
{
bigger = secondNumber;
}
return bigger;
}
public static string GetMax(string word, string secondWord)
{
string bigger = String.Empty;
if (word.CompareTo(secondWord) >= 0)
{
bigger = word;
} else
{
bigger = secondWord;
}
return bigger;
}
public static string GetMax(char firstChar, char secondChar)
{
string bigger = String.Empty;
if (firstChar.CompareTo(secondChar) >= 0)
{
bigger = firstChar.ToString();
} else
{
bigger = secondChar.ToString();
}
return bigger;
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-September-2017/FilesDirectoriesАndExceptions-Exercise/01.MostFrequentNumber/MostFrequentNumber.cs
namespace _01.MostFrequentNumber
{
using System;
using System.IO;
using System.Linq;
public class MostFrequentNumber
{
public static void Main()
{
string[] lines = File.ReadAllLines("input.txt");
File.Delete("output.txt");
foreach (var line in lines)
{
int[] array = line
.Split(' ')
.Select(int.Parse)
.ToArray();
int repeats = 0;
int freqNumber = 0;
for (int i = 0; i < array.Length; i++)
{
int currentNumber = array[i];
int counter = 0;
for (int k = i; k < array.Length; k++)
{
if (currentNumber == array[k])
{
counter++;
}
}
if (counter > repeats)
{
freqNumber = currentNumber;
repeats = counter;
}
}
var output = freqNumber.ToString();
File.AppendAllText("output.txt", output);
}
}
}
}<file_sep>/Programming Fundamentals/Programming-Fundamentals-September-2017/ConditionalStatementsAndLoops-Exercises/09.CounterTheIntegers/Program.cs
namespace CounterTheIntegers
{
using System;
public class Program
{
static void Main()
{
int integer = 0;
int counter = 0;
try
{
while ((int)integer == (int)integer)
{
integer = int.Parse(Console.ReadLine());
counter++;
}
} catch
{
}
Console.WriteLine(counter);
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-September-2017/List-Lab/07.CountNumbers/CountNumbers.cs
namespace _07.CountNumbers
{
using System;
using System.Collections.Generic;
using System.Linq;
public class CountNumbers
{
public static void Main()
{
List<int> numbers = Console.ReadLine()
.Split(new char[] {' ', }, StringSplitOptions.RemoveEmptyEntries)
.Select(int.Parse)
.ToList();
numbers.Sort();
numbers.Add(int.MaxValue);
int counter = 1;
for (int i = 0; i < numbers.Count - 1; i++)
{
if (numbers[i] == numbers[i + 1])
{
counter++;
} else
{
Console.WriteLine($"{numbers[i]} -> {counter}");
counter = 1;
}
}
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-September-2017/ConditionalStatementsAndLoops/03.BackIn30Minutes/Program.cs
namespace Back_in_30_Minutes
{
using System;
public class Program
{
static void Main()
{
int hour = int.Parse(Console.ReadLine());
int minutes = int.Parse(Console.ReadLine());
minutes += 30;
hour += minutes / 60;
minutes = minutes % 60;
if (hour >= 24)
{
hour = 0;
}
Console.WriteLine("{0:D1}:{1:D2}", hour, minutes);
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-September-2017/ConditionalStatementsAndLoops-Exercises/06.IntervalOfNumbers/Program.cs
namespace IntervalOfNumbers
{
using System;
public class Program
{
static void Main()
{
int startNumber = int.Parse(Console.ReadLine());
int stopNumber = int.Parse(Console.ReadLine());
if (startNumber < stopNumber)
{
for (int i = startNumber; i <= stopNumber; i++)
Console.WriteLine(i);
}
else if (startNumber > stopNumber)
{
for (int i = stopNumber; i <= startNumber; i++)
{
Console.WriteLine(i);
}
}
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-September-2017/DataTypesAndVariables/05.SpecialNumbers/Program.cs
namespace _05.specialNumberNumbers
{
using System;
public class Program
{
static void Main()
{
int stopNumber = int.Parse(Console.ReadLine());
int sum = 0;
int num = 0;
for (int i = 1; i <= stopNumber; i++)
{
sum = i % 10;
num = i / 10;
int specialNumber = sum + num;
bool isSpecial = i == 5 || i == 7 || specialNumber == 5 || specialNumber == 7 || specialNumber == 11;
if (isSpecial)
{
Console.WriteLine($"{i} -> True");
} else
{
Console.WriteLine($"{i} -> False");
}
}
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-Extended-May-2017/List Lab Exercises - May 2017 Extended/7. Count Numbers/Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _7.Count_Numbers
{
class Program
{
static void Main(string[] args)
{
var numbers = Console.ReadLine().Split(new char[] {' '},StringSplitOptions.RemoveEmptyEntries).Select(int.Parse).ToList();
numbers.Sort();
numbers.Add(0);
var counter = 1;
for (int cnt = 0; cnt < numbers.Count - 1; cnt++)
{
if (numbers[cnt] == numbers[cnt +1])
{
counter++;
} else
{
Console.WriteLine($"{numbers[cnt]} -> {counter}");
counter = 1;
}
}
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-Extended-November-2017/Dictionaries, Nested Collections, LINQ and Lambda Expressions - Lab/03. Cities by Continent and Country/CitiesByContinentAndCountry.cs
namespace _03.Cities_by_Continent_and_Country
{
using System;
using System.Collections.Generic;
public class CitiesByContinentAndCountry
{
public static void Main()
{
Dictionary<string, Dictionary<string, List<string>>> worldMap = new Dictionary<string, Dictionary<string, List<string>>>();
int counter = int.Parse(Console.ReadLine());
for (int i = 0; i < counter; i++)
{
var input = Console.ReadLine().Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
string continent = input[0];
string country = input[1];
string town = input[2];
if (!worldMap.ContainsKey(continent))
{
worldMap.Add(continent, new Dictionary<string, List<string>>());
}
if (!worldMap[continent].ContainsKey(country))
{
worldMap[continent][country] = new List<string>();
}
worldMap[continent][country].Add(town);
}
foreach (var continent in worldMap)
{
Console.WriteLine(continent.Key + ":");
foreach (var countries in continent.Value)
{
Console.Write($"{countries.Key} -> ");
Console.WriteLine(string.Join(", ", countries.Value));
}
}
}
}
}
<file_sep>/Software Technologies/Exam Preparation Cat Shop/js/models/cat.js
const Sequelize = require('sequelize');
module.exports = function (sequelize) {
//TODO
let Cat = sequelize.define("Cat",{
"name":{type:Sequelize.TEXT, required: true, allowNull: false,},
"nickname":{type:Sequelize.TEXT, required: true, allowNull: false,},
"price":{type:Sequelize.DOUBLE, required: true, allowNull: false,}
},{
timestamps:false
});
return Cat;
};<file_sep>/Programming Fundamentals/Programming-Fundamentals-September-2017/DictionariesLambdaAndLINQ-Exercise/ConsoleApp1/СръбскоUnleashed.cs
namespace ConsoleApp1
{
using System;
using System.Collections.Generic;
using System.Linq;
public class СръбскоUnleashed
{
public static void Main()
{
}
}
}
<file_sep>/Software Technologies/Java Basic Syntax Exercises/src/IndexOfLetters.java
import java.util.Scanner;
public class IndexOfLetters {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
char[] word = scanner.nextLine().toCharArray();
for (int i = 0; i < word.length; i++) {
char character = word[i];
int ascii = (int) character - 97;
System.out.println(word[i] + " -> " + ascii);
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-September-2017/Regular Expressions (RegEx) - Exercises/04. Weather/DIctionary.cs
using System;
namespace _04.Weather
{
internal class DIctionary<T1, T2>
{
internal object OrderBy(Func<object, object> p)
{
throw new NotImplementedException();
}
}
}<file_sep>/Programming Fundamentals/Programming-Fundamentals-Extended-November-2017/Arrays, Lists, Array and List Algorithms - Exercise/03. PokemonDon't Go/PokemonDontGo.cs
namespace _03.PokemonDon_t_Go
{
using System;
public class PokemonDontGo
{
public static void Main()
{
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-Extended-May-2017/List Lab Exercises - May 2017 Extended/6. Square Numbers/Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _6.Square_Numbers
{
class Program
{
static void Main(string[] args)
{
List<int> numbers = Console.ReadLine().Split(' ').Select(int.Parse).OrderByDescending(a => a).ToList();
foreach (var num in numbers)
{
if (Math.Sqrt(num) == Math.Floor(Math.Sqrt(num)))
{
Console.Write(num + " ");
}
}
Console.WriteLine();
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-September-2017/StringsAndTextProcessing-Lab/03.TextFilter/TextFilter.cs
namespace _03.TextFilter
{
using System;
using System.Linq;
public class TextFilter
{
public static void Main()
{
string[] bannedWords = Console.ReadLine()
.Split(new char[] { ' ', ',', }, StringSplitOptions.RemoveEmptyEntries)
.ToArray();
string textToCheck = Console.ReadLine();
foreach (var bannedWord in bannedWords)
{
if (textToCheck.Contains(bannedWord))
{
string format = new string('*', bannedWord.Length);
textToCheck = textToCheck.Replace(bannedWord, format);
}
}
Console.WriteLine(textToCheck);
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-September-2017/FilesDirectoriesАndExceptions-Exercise/03.EqualSums/EqualSums.cs
namespace _03.EqualSums
{
using System;
using System.Linq;
using System.IO;
public class EqualSums
{
public static void Main()
{
string[] input = File.ReadAllLines("input.txt");
File.Delete("output.txt");
foreach (var line in input)
{
int[] number = line.Split(' ')
.Select(int.Parse)
.ToArray();
bool isEqualSum = false;
for (int i = 0; i < number.Length; i++)
{
int[] left = number.Take(i).ToArray();
int[] right = number.Skip(i + 1).ToArray();
string output = i.ToString();
if (left.Sum() == right.Sum())
{
isEqualSum = true;
File.AppendAllText("output.txt", output);
}
}
if (!isEqualSum)
{
File.AppendAllText("output", "no");
}
}
}
}
}<file_sep>/Programming Fundamentals/Programming-Fundamentals-September-2017/Regular Expressions (RegEx) - Exercises/06.Valid Usernames/ValidUsernames.cs
namespace _06.Valid_Usernames
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
public class ValidUsernames
{
public static void Main()
{ //Not finished !
var inputUsers = Console.ReadLine()
.Split(new char[] { ' ', ',', '/', '\\', '(', ')', }
, StringSplitOptions.RemoveEmptyEntries)
.ToList();
var usernames = new List<string>();
foreach (var user in inputUsers)
{
char[] userChars = user.ToCharArray();
char firstChar = userChars[0];
string pattern = @"([a-zA-Z0-9_]{4,25}+)";
Regex regex = new Regex(pattern);
bool isCorrectUser = user.Length > 3 && user.Length < 25 && Char.IsLetter(firstChar) && regex.IsMatch(user);
; if (isCorrectUser)
{
usernames.Add(user);
}
}
Console.WriteLine(String.Join(", ", usernames));
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-September-2017/MethodsDebuggingAndTroubleshootingCode/05.TemperatureConversion/Program.cs
namespace _05.TemperatureConversion
{
using System;
public class Program
{
static void Main()
{
double fahrenheit = double.Parse(Console.ReadLine());
ConvertFahrenheitInCelsius(fahrenheit);
}
public static void ConvertFahrenheitInCelsius(double number)
{
double conversion = (number - 32) * 5 / 9;
Console.WriteLine($"{conversion:F2}");
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-September-2017/StringsAndTextProcessing-Exercise/05.MagicExchangeableWords/MagicExchangeableWords.cs
namespace _05.MagicExchangeableWords
{
using System;
using System.Linq;
public class MagicExchangeableWords
{
public static void Main()
{
var lines = Console.ReadLine().Split(' ').ToList();
string first = lines[0];
string second = lines[1];
char[] frst = first.ToCharArray();
char[] scnd = second.ToCharArray();
var newFirst = frst.Distinct().ToList();
var newSecond = scnd.Distinct().ToList();
bool areEquals = newFirst.Count == newSecond.Count;
if (areEquals)
{
Console.WriteLine("true");
}
else
{
Console.WriteLine("false");
}
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-Extended-May-2017/C- Basic Syntax - More Exercises/p. 4 Photo Gallery/Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace p._4_Photo_Gallery
{
class Program
{
static void Main(string[] args)
{
int pictureName = int.Parse(Console.ReadLine());
int day = int.Parse(Console.ReadLine());
int month = int.Parse(Console.ReadLine());
int year = int.Parse(Console.ReadLine());
int hours = int.Parse(Console.ReadLine());
int minutes = int.Parse(Console.ReadLine());
double bytes = double.Parse(Console.ReadLine());
int widthPic = int.Parse(Console.ReadLine());
int heightPic = int.Parse(Console.ReadLine());
double megabyte = bytes / 1000000;
double kylobytes = bytes / 1000;
string mb = "MB";
string b = "B";
string kb = "KB";
string pictureType = "";
if (widthPic > heightPic)
{
pictureType = "landscape";
}
else if (widthPic < heightPic)
{
pictureType = "portrait";
}
else if (widthPic == heightPic)
{
pictureType = "square";
}
Console.WriteLine("Name: DSC_{0:D4}.jpg", pictureName);
Console.WriteLine("Date Taken: {0}/{1:D2}/{2} {3:D2}:{4:D2}", day, month, year, hours, minutes);
if (bytes < 1000)
{
Console.WriteLine("Size: {0}{1}", bytes, b);
}
else if (bytes >= 1000 && bytes < 1000000)
{
Console.WriteLine("Size: {0}{1}", kylobytes, kb);
}
else if (bytes >= 1000000)
{
Console.WriteLine("Size: {0}{1}", Math.Round(megabyte, 1), mb);
}
Console.WriteLine("Resolution: {0}x{1} ({2})", widthPic, heightPic, pictureType);
}
}
}
<file_sep>/Software Technologies/JavaScript Syntax and Basic Web - Exercises/08. PrintNumbersInReverseOrder.js
function reverseOrder(args) {
args.reverse();
for (let i=0; i < args.length; i++) {
console.log(args[i]);
}
}
reverseOrder([
'10',
'15',
'20'
]);
reverseOrder([
'5',
'5.5',
'24',
'-3'
]);<file_sep>/Programming Fundamentals/Programming-Fundamentals-September-2017/DataTypesAndVariables-Exercises/14.IntegerToHexAndBinary/Program.cs
namespace _14.IntegerToHexAndBinary
{
using System;
public class Program
{
static void Main()
{
int decValue = int.Parse(Console.ReadLine());
string hexValue = decValue.ToString("X").ToUpper();
string binary = Convert.ToString(decValue, 2);
Console.WriteLine(hexValue);
Console.WriteLine(binary);
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-September-2017/ConditionalStatementsAndLoops-Exercises/02.ChooseADrink2/Program.cs
namespace Choose_a_Drink
{
using System;
public class Program
{
static void Main()
{
string profession = Console.ReadLine();
double productQuantity = double.Parse(Console.ReadLine());
double waterPrice = 0.70;
double coffeePrice = 1.00;
double beerPrice = 1.70;
double teaPrice = 1.20;
double totalPrice = 0;
switch (profession)
{
case "Athlete":
totalPrice = waterPrice * productQuantity;
Console.WriteLine("The {0} has to pay {1:F2}.", profession, totalPrice);
break;
case "Businessman":
case "Businesswoman":
totalPrice = coffeePrice * productQuantity;
Console.WriteLine("The {0} has to pay {1:F2}.", profession, totalPrice);
break;
case "SoftUni Student":
totalPrice = beerPrice * productQuantity;
Console.WriteLine("The {0} has to pay {1:F2}.", profession, totalPrice);
break;
default:
totalPrice = teaPrice * productQuantity;
Console.WriteLine("The {0} has to pay {1:F2}.", profession, totalPrice);
break;
}
}
}
}
<file_sep>/Software Technologies/Exam SoftUni Lab 10.Jan.2019/JavaScript/softunilabs/controllers/lab.js
const Lab = require('../models').Lab;
module.exports = {
index: (req, res) => {
//TODO: Implement me
Lab.findAll().then(labs =>{
res.render("lab/index", {"labs":labs})
});
},
createGet: (req, res) => {
//TODO: Implement me
res.render("lab/create")
},
createPost: (req, res) => {
//TODO: Implement me
let args = req.body.lab;
Lab.create(args).then(()=>{
res.redirect("/")
})
},
editGet: (req, res) => {
//TODO: Implement me
let id = req.params.id;
Lab.findById(id).then((lab => res.render("lab/edit", {"lab": lab})));
},
editPost: (req, res) => {
//TODO: Implement me
let id = req.params.id;
let args = req.body.lab;
Lab.findById(id)
.then(lab => lab.updateAttributes(args)
.then(() => {res.redirect('/')}));
},
deleteGet: (req, res) => {
//TODO: Implement me
let id = req.params.id;
Lab.findById(id).then((lab => res.render("lab/delete", {"lab": lab})));
},
deletePost: (req, res) => {
//TODO: Implement me
let id = req.params.id;
Lab.findById(id)
.then(lab => lab.destroy()
.then(() => {res.redirect('/')}));
}
};<file_sep>/Programming Fundamentals/Programming-Fundamentals-September-2017/FilesDirectoriesАndExceptions-Exercise/07.AdvertisementMessage/AdvertisementMessage.cs
namespace _07.AdvertisementMessage
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
public class AdvertisementMessage
{
public static void Main()
{
// Add info from files.
string[] phrases = File.ReadAllLines("input.txt");
string[] events = File.ReadAllLines("input_2.txt");
string[] authors = File.ReadAllLines("input_3.txt");
string[] cities = File.ReadAllLines("input_4.txt");
// Add to lists.
List<string> phrasesToList = new List<string>();
foreach (var phrase in phrases)
{
phrasesToList = phrase
.Split(new string[] { ", " }, StringSplitOptions.RemoveEmptyEntries)
.ToList();
}
List<string> eventsToList = new List<string>();
foreach (var eventt in events)
{
eventsToList = eventt
.Split(new string[] { ", " }, StringSplitOptions.RemoveEmptyEntries)
.ToList();
}
List<string> authorsToList = new List<string>();
foreach (var author in authors)
{
authorsToList = author
.Split(new string[] { ", " }, StringSplitOptions.RemoveEmptyEntries)
.ToList();
}
List<string> citiesToList = new List<string>();
foreach (var city in cities)
{
citiesToList = city
.Split(new string[] { ", " }, StringSplitOptions.RemoveEmptyEntries)
.ToList();
}
string[] numToAds = File.ReadAllLines("numberForAds.txt");
File.Delete("output.txt");
Random rnd = new Random();
string output = String.Empty;
foreach (var num in numToAds)
{
int numberPhrases = int.Parse(num);
for (int i = 0; i < numberPhrases; i++)
{
int eve = rnd.Next(eventsToList.Count);
string temp1 = eventsToList[eve];
int auth = rnd.Next(authorsToList.Count);
string temp2 = authorsToList[auth];
int citi = rnd.Next(citiesToList.Count);
string temp3 = citiesToList[citi];
int prh = rnd.Next(phrasesToList.Count);
string temp4 = phrasesToList[prh];
output = $"{temp4} {temp1} {temp2} - {temp3}" + Environment.NewLine;
File.AppendAllText("output.txt", output);
}
}
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-September-2017/List-Exercises/06.SumReversedNumbers/SumReversNumbers.cs
namespace _06.SumReversedNumbers
{
using System;
using System.Collections.Generic;
using System.Linq;
public class SumReversNumbers
{
public static void Main()
{
List<string> numbers = Console.ReadLine()
.Split(new char[] { ' ', ',', ';', ':', '.', '!', '(', ')', '"', '/', '[', ']', '\'', '\\' }, StringSplitOptions.RemoveEmptyEntries)
.ToList();
List<int> result = new List<int>();
foreach (string number in numbers)
{
int currentNumber = ReversNumber(number);
result.Add(currentNumber);
}
Console.WriteLine(result.Sum());
}
private static int ReversNumber(string number)
{
char[] array = number.ToCharArray();
string reverse = String.Empty;
for (int i = array.Length - 1; i >= 0; i--)
{
reverse += array[i];
}
return int.Parse(reverse);
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-September-2017/ObjectsAndClasses/02.RandomizeWords/RandomizeWords.cs
namespace _02.RandomizeWords
{
using System;
using System.Collections.Generic;
using System.Linq;
public class RandomizeWords
{
public static void Main()
{
List<string> text = Console.ReadLine().Split(' ').ToList();
Random rnd = new Random();
for (int i = 0; i < text.Count + 1; i++)
{
int index = rnd.Next(0, text.Count);
string rem = text[index];
int newIndex = rnd.Next(0, text.Count);
text[index] = text[newIndex];
text[newIndex] = rem;
}
for (int i = 0; i < text.Count; i++)
{
Console.WriteLine(text[i]);
}
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-Extended-May-2017/Lists - Exercises/6.Stuck Zipper/Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _6.Stuck_Zipper
{
class Program
{
static void Main(string[] args)
{
List<int> firstList = Console.ReadLine()
.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
.Select(int.Parse)
.ToList();
List<int> secondList = Console.ReadLine()
.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
.Select(int.Parse)
.ToList();
// var minNumberInList = FindMinDigits(firstList, secondList);
var result = ListUnited(firstList, secondList);
Console.WriteLine(string.Join(" ", result));
}
private static List<int> ListUnited (List<int> list1, List<int> list2)
{
var firstListResult = new List<int>();
var secondListResult = new List<int>();
var resultList = new List<int>();
foreach (var number in list1) // adding smallest nums in new list
{
var stringNumber = Math.Abs(number).ToString();
if (stringNumber.Length == FindMinDigits(list1, list2))
{
firstListResult.Add(number);
}
}
foreach (var number in list2) // adding smallest nums in new list
{
var stringNumber = Math.Abs(number).ToString();
if (stringNumber.Length == FindMinDigits(list1, list2))
{
secondListResult.Add(number);
}
}
var totalLength = firstListResult.Count + secondListResult.Count;
for (int cnt = 0; cnt < totalLength; cnt++)
{
var firstListNumber = 0;
var secondListNumber = 0;
if (secondListResult.Count > cnt)
{
secondListNumber = secondListResult[cnt];
resultList.Add(secondListNumber);
}
if (firstListResult.Count > cnt)
{
firstListNumber = firstListResult[cnt];
resultList.Add(firstListNumber);
}
}
return resultList;
}
private static int FindMinDigits (List<int> list1, List<int> list2)
{
var maxDigits = int.MaxValue;
foreach (var number in list1)
{
var stringLength = Math.Abs(number).ToString(); //Search for biggest digits in list1
if (stringLength.Length < maxDigits)
{
maxDigits = stringLength.Length;
}
}
foreach (var number in list2)
{
var stringLength = Math.Abs(number).ToString(); //Search for biggest digits in list2
if (stringLength.Length < maxDigits)
{
maxDigits = stringLength.Length;
}
}
return maxDigits;
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-September-2017/DataTypesAndVariables-Exercises/19.TheaThePhotographer/Program.cs
namespace _19.TheaThePhotographer
{
using System;
public class Program
{
static void Main()
{
long numberOfPictures = long.Parse(Console.ReadLine());
long filterTimeForPicture = long.Parse(Console.ReadLine());
long filterFactorPercent = long.Parse(Console.ReadLine());
long timeToUploadPicture = long.Parse(Console.ReadLine());
//Filtering good/bad pictures
double notGoodPictures = Math.Ceiling((double)numberOfPictures * filterFactorPercent / 100);
long uNusefulPicturesAfterFilterFactor = numberOfPictures - (int)notGoodPictures;
long usefulPicturesAfterFilterFactor = numberOfPictures - uNusefulPicturesAfterFilterFactor;
//Time for filtering
long totalTimeForFilterInSeconds = numberOfPictures * filterTimeForPicture;
long totalTimeForUploadInSeconds = usefulPicturesAfterFilterFactor * timeToUploadPicture;
long totalTimeForWork = totalTimeForFilterInSeconds + totalTimeForUploadInSeconds;
TimeSpan timeFormat = TimeSpan.FromSeconds(totalTimeForWork);
string printTimeFormat = string.Format("{0}:{1:D2}:{2:D2}:{3:D2}",
t.Days,
t.Hours,
t.Minutes,
t.Seconds);
Console.WriteLine(printTimeFormat);
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-Extended-November-2017/Data Types, Variables and Methods - Lab/03. Big Power/BigPower.cs
namespace _03.Big_Power
{
using System;
using System.Numerics;
public class BigPower
{
public static void Main()
{
int num = int.Parse(Console.ReadLine());
BigInteger result = 1;
for (int i = 0; i < num; i++)
{
result *= num;
}
Console.WriteLine(result);
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-September-2017/Exam Preparation III/01.SoftUni Coffee Orders/SoftUni Coffe Orders.cs
namespace _01.SoftUni_Coffee_Orders
{
using System;
using System.Globalization;
public class Program
{
public static void Main()
{ // 100/100 Points
long n = long.Parse(Console.ReadLine());
DateTime date = new DateTime();
decimal total = 0;
for (int i = 0; i < n; i++)
{
decimal price = decimal.Parse(Console.ReadLine());
date = DateTime.ParseExact(Console.ReadLine(), "d/M/yyyy", CultureInfo.InvariantCulture);
long capsules = long.Parse(Console.ReadLine());
int month = date.Month;
int year = date.Year;
int days = DateTime.DaysInMonth(year, month);
decimal sum = (decimal)((days * capsules) * price);
Console.WriteLine($"The price for the coffee is: ${sum:F2}");
total += sum;
}
Console.WriteLine($"Total: ${total:F2}");
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-September-2017/DataTypesAndVariables-Exercises/05.BooleanVariable/Program.cs
namespace _05.BooleanVariable
{
using System;
public class Program
{
static void Main()
{
string inputCommand = Console.ReadLine();
bool isItConvert = inputCommand == "True";
if (isItConvert)
{
Console.WriteLine("Yes");
} else
{
Console.WriteLine("No");
}
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-September-2017/ObjectsАndClasses-Exercise/02.AdvertisementMessage/AdvertisementMessage.cs
namespace _02.AdvertisementMessage
{
using System;
using System.Collections.Generic;
public class AdvertisementMessage
{
public static void Main()
{
List<string> phrases = new List<string>()
{
"Excellent product.",
"Such a great product.",
"I always use that product.",
"Best product of its category.",
"Exceptional product.",
"I can’t live without this product."
};
List<string> events = new List<string>()
{
"Now I feel good.",
"I have succeeded with this product.",
"Makes miracles. I am happy of the results!",
"I cannot believe but now I feel awesome.",
"Try it yourself, I am very satisfied.",
"I feel great!"
};
List<string> authors = new List<string>()
{
"Diana",
"Petya",
"Stella",
"Elena",
"Katya",
"Iva",
"Annie",
"Eva"
};
List<string> cities = new List<string>()
{
"Burgas",
"Sofia",
"Plovdiv",
"Varna",
"Ruse"
};
Random rnd = new Random();
int numberPhrases = int.Parse(Console.ReadLine());
for (int i = 0; i < numberPhrases; i++)
{
int eve = rnd.Next(events.Count);
string temp1 = events[eve];
int auth = rnd.Next(authors.Count);
string temp2 = authors[auth];
int citi = rnd.Next(cities.Count);
string temp3 = cities[citi];
int prh = rnd.Next(phrases.Count);
string temp4 = phrases[prh];
Console.WriteLine("{0}{1}{2} - {3}",temp4, temp1, temp2, temp3);
}
}
}
}
<file_sep>/Software Technologies/Java Basic Syntax Exercises/src/CensorEmailAdress.java
import java.util.Arrays;
import java.util.Scanner;
public class CensorEmailAdress {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String inputEmail = scanner.nextLine();
String username = inputEmail.split("@")[0];
String replacment = getReplacment(username.length(), '*', inputEmail);
String inputText = scanner.nextLine();
inputText = inputText.replaceAll(inputEmail, replacment);
System.out.println(inputText);
}
private static String getReplacment(int length, char s, String inputEmail) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < length; i++) {
sb.append(s);
}
String username = inputEmail.split("@")[0];
return inputEmail.replaceFirst(username, sb.toString());
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-September-2017/List-Lab/06.SquareNumbers/SquareNumbers.cs
namespace _06.SquareNumbers
{
using System;
using System.Collections.Generic;
using System.Linq;
public class SquareNumbers
{
public static void Main()
{
List<double> numbers = Console.ReadLine()
.Split(new char[] { ' ', ',', '|', ';', }, StringSplitOptions.RemoveEmptyEntries)
.Select(double.Parse)
.ToList();
List<double> result = new List<double>();
for (int i = 0; i < numbers.Count; i++)
{
if (Math.Sqrt(numbers[i]) == (int)Math.Sqrt(numbers[i]))
{
result.Add(numbers[i]);
}
}
var resultOrder = result.OrderByDescending(num => num); // 100/100 in judge
Console.WriteLine(string.Join(" ", resultOrder));
// result.Sort(); With this way 100/100
// result.Reverse(); Trying with OrderByDescending....
// Console.WriteLine(string.Join(" ", result));
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-Extended-November-2017/Arrays, Lists, Array and List Algorithms - Lab/01.Rotate Array of Strings/RotateArrayOfStrings.cs
namespace _01.Rotate_Array_of_Strings
{
using System;
using System.Collections.Generic;
using System.Linq;
public class RotateArrayOfStrings
{
public static void Main()
{
List<string> elements = Console.ReadLine().Split().ToList();
string temp = elements.Last();
elements.Insert(0, temp);
elements.RemoveAt(elements.Count - 1);
Console.WriteLine(String.Join(" ", elements));
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-Extended-May-2017/C- Basic Syntax - More Exercises/p.6 DNA Sequences/Program.cs
using System;
namespace p._6_DNA_Sequences
{
class Program
{
static void Main(string[] args)
{
int matchSum = int.Parse(Console.ReadLine());
for (int firstChar = 1; firstChar <= 4; firstChar++)
{
for (int secondChar = 1; secondChar <= 4; secondChar++)
{
for (int thirdChar = 1; thirdChar <= 4; thirdChar++)
{
string result = $"{firstChar}{secondChar}{thirdChar}";
result = result.Replace("1", "A").Replace("2", "C").Replace("3", "G").Replace("4", "T");
if (firstChar + secondChar + thirdChar >= matchSum)
{
Console.Write($"O{result}O ");
} else
{
Console.Write($"X{result}X ");
}
if (thirdChar % 4 == 0)
{
Console.WriteLine();
}
}
}
}
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-September-2017/MethodsDebuggingАndTroubleshootingCode-Exercises/01.Hello,Name!/Program.cs
namespace _01.Hello_Name_
{
using System;
public class Program
{
static void Main()
{
string input = Console.ReadLine();
GreetingMethod(input);
}
static void GreetingMethod(string input)
{
Console.WriteLine("Hello, {0}!", input);
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-September-2017/ObjectsАndClasses-Exercise/05.BookLibrary/BookLibrary.cs
namespace _05.BookLibrary
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
public class Books
{
public string Title { get; set; }
public string Author { get; set; }
public string Publisher { get; set; }
public DateTime ReleaseDate { get; set; }
public long ISBNnumber { get; set; }
public double Price { get; set; }
}
public class Library
{
public string Book { get; set; }
public List<Books> listOfBooks { get; set; }
}
public class AuthorSale
{
public string Author { get; set; }
public double Sale { get; set; }
}
public class BookLibrary
{
public static void Main()
{
int booksCount = int.Parse(Console.ReadLine());
var books = new List<Books>();
var library = new Library()
{
Book = "Libra",
listOfBooks = new List<Books>()
};
for (int i = 0; i < booksCount; i++)
{
var input = Console.ReadLine().Split(' ').ToList();
Books book = new Books();
book.Title = input[0];
book.Author = input[1];
book.Publisher = input[2];
book.ReleaseDate = DateTime.ParseExact(input[3], "dd.MM.yyyy", CultureInfo.InvariantCulture);
book.ISBNnumber = long.Parse(input[4]);
book.Price = double.Parse(input[5]);
library.listOfBooks.Add(book);
}
var autoSales = new List<AuthorSale>();
var authors = library.listOfBooks.Select(a => a.Author).Distinct().ToArray();
foreach (var author in authors)
{
var sales = library.listOfBooks.Where(a => a.Author == author).Sum(a => a.Price);
autoSales.Add(new AuthorSale()
{
Author = author,
Sale = sales
});
}
autoSales = autoSales.OrderByDescending(a => a.Sale).ThenBy(a => a.Author).ToList();
foreach (var sale in autoSales)
{
Console.WriteLine($"{sale.Author} -> {sale.Sale:F2}");
}
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-September-2017/Regular Expressions (RegEx) - Exercises/04. Weather/Weather.cs
namespace _04.Weather
{
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Linq;
public class Weather
{
public static void Main()
{
Dictionary<string, double> cityWithTemp = new Dictionary<string, double>();
Dictionary<string, string> cityWithWeather = new Dictionary<string, string>();
List<int> nlist = new List<int>();
string pattern = "([A-Z]{2})([0-9.]+)([a-zA-Z]+)\\|";
String input = Console.ReadLine();
Regex regex = new Regex(pattern);
while (input != "end")
{
if (Regex.IsMatch(input, pattern))
{
Match match = Regex.Match(input, pattern);
string city = match.Groups[1].Value;
double temp = double.Parse(match.Groups[2].Value);
string weather = match.Groups[3].Value;
cityWithTemp[city] = temp;
cityWithWeather[city] = weather;
}
input = Console.ReadLine();
}
Dictionary<string, double> sortedDictionryByTemp = cityWithTemp.OrderBy(c => c.Value).ToDictionary(x => x.Key, x => x.Value);
foreach (var cityy in sortedDictionryByTemp)
{
Console.WriteLine($"{cityy.Key} => {cityy.Value} => {cityWithWeather[cityy.Key]}");
}
}
}
}
<file_sep>/Programming Fundamentals/PF-Exams/PF-Exam-23October2016/01.Charity Marathon/CharityMarathon.cs
namespace _01.Charity_Marathon
{
using System;
public class CharityMarathon
{ // 80/100 - MissingCase
public static void Main()
{
try
{
long days = Math.Abs(long.Parse(Console.ReadLine()));
long runners = Math.Abs(long.Parse(Console.ReadLine()));
long laps = Math.Abs(long.Parse(Console.ReadLine()));
long trackMeters = Math.Abs(long.Parse(Console.ReadLine()));
long maxPeople = Math.Abs(long.Parse(Console.ReadLine()));
decimal moneyPerKm = Math.Abs(decimal.Parse(Console.ReadLine()));
var runnersPerDay = runners / days;
if (runnersPerDay < maxPeople)
{
}
else if (runnersPerDay > maxPeople)
{
runnersPerDay = maxPeople;
}
var totalRunners = runnersPerDay * days;
var totalMeters = totalRunners * laps * trackMeters;
var km = totalMeters / 1000;
decimal money = km * moneyPerKm;
Console.WriteLine($"Money raised: {money:F2}");
}
catch
{
Console.WriteLine("No");
}
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-September-2017/DictionariesLambdaAndLINQ-Exercise/06.UserLogs/UserLogs.cs
namespace _06.UserLogs
{
using System;
using System.Collections.Generic;
using System.Linq;
public class UserLogs
{
public static void Main()
{
var input = Console.ReadLine();
var dict = new SortedDictionary<string, Dictionary<string, int>>();
while (input != "end")
{
var loginStats = input.Split(' ').ToList();
var user = loginStats[2].Replace("user=", String.Empty);
var ip = loginStats[0].Replace("IP=", String.Empty);
var message = loginStats[1].Replace("message=", String.Empty); ;
var counter = 1;
if (!dict.ContainsKey(user))
{
dict.Add(user, new Dictionary<string, int>());
}
if (!dict[user].ContainsKey(ip))
{
dict[user].Add(ip, counter);
}
else
{
dict[user][ip]++;
}
input = Console.ReadLine();
}
foreach (var item in dict)
{
var user = item.Key;
Console.WriteLine("{0}: ", item.Key);
foreach (var userr in dict[user])
{
var ip = userr.Key;
var count = userr.Value;
if (userr.Key != item.Value.Keys.Last())
{
Console.Write($"{ip} => {count}, ");
}
else
{
Console.WriteLine($"{ip} => {count}.");
}
}
}
}
}
}
<file_sep>/Software Technologies/PHP - Syntax and Basic Web/07. From Celsius to Fahrenheit and Vice Versa.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Celsius to Fahrenheit</title>
</head>
<body>
<?php
function CelsiusToFahrenheit (float $celsius) : float
{
return $celsius * 1.8 + 32;
}
function FahrenheitToCelsius (float $fahrenheit) : float
{
return ($fahrenheit - 32) / 1.8;
}
$msgAfterCelsius = "";
if (isset($_GET['cel'])) {
$cel = floatval($_GET['cel']);
$fah = CelsiusToFahrenheit($cel);
$msgAfterCelsius = "$cel °C = $fah °F";
}
$msgAfterFahrenheit = "";
if (isset($_GET['fah'])) {
$fah = floatval($_GET['fah']);
$cel = FahrenheitToCelsius($fah);
$msgAfterCelsius = "$fah °F = $cel °C";
}
?>
<form>
Celsius: <input type = "text" name = "cel"/>
<input type = "submit" value = "Convert">
<?= $msgAfterCelsius ?>
</form>
<br>
<form>
Fahrenheit: <input type = "text" name = "fah" />
<input type = "submit" value = "Convert">
<?= $msgAfterFahrenheit ?>
</form>
</body>
</html><file_sep>/Programming Fundamentals/Programming-Fundamentals-Extended-May-2017/C- Basic Syntax - More Exercises/p.3 Megapixels/Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace p._3_Megapixels
{
class Program
{
static void Main(string[] args)
{
int width = int.Parse(Console.ReadLine());
int height = int.Parse(Console.ReadLine());
double pixels = (width * height);
double diversion = pixels / 1000000;
Console.WriteLine("{0}x{1} => {2}MP", width, height, Math.Round(diversion, 1));
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-September-2017/ConditionalStatementsAndLoops/08.SumOfOddNumbers/Program.cs
namespace SumOfOddNumbers
{
using System;
public class Program
{
static void Main()
{
int oddCOunter = int.Parse(Console.ReadLine());
int sum = 0;
int counter = 0;
for (int cnt = 1; ; cnt++)
{
if (cnt % 2 == 1)
{
Console.WriteLine(cnt);
sum += cnt;
counter++;
}
if (counter == oddCOunter)
{
break;
}
}
Console.WriteLine($"Sum: {sum}");
}
}
}
<file_sep>/Programming Fundamentals/PF-Exams/PF-Exam-26February2017/04. Hornet Armada/HornedArmada.cs
namespace _04.Hornet_Armada
{
using System;
using System.Collections.Generic;
public class HornedArmada
{
public static void Main()
{ //TODO
int n = int.Parse(Console.ReadLine());
Dictionary<string, Dictionary<string, long>> soldier = new Dictionary<string, Dictionary<string, long>>();
Dictionary<string, long> legionActivity = new Dictionary<string, long>();
for (int i = 0; i < n; i++)
{
var inputData = Console.ReadLine()
.Split(new string[] { " -> ", " ", "=", "-", ":", }, StringSplitOptions.RemoveEmptyEntries);
string lastActivity = inputData[0];
string legionName = inputData[1];
string soldierType = inputData[2];
string soldierCount = inputData[3]; //Input tested
}
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-September-2017/Arrays-Exercise/03.FoldAndSum/FoldAndSum.cs
namespace _03.FoldAndSum
{
using System;
using System.Linq;
public class FoldAndSum
{
public static void Main()
{
int[] array = Console.ReadLine()
.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
.Select(int.Parse)
.ToArray();
int lenght = array.Length / 4;
int[] middle = array.Skip(lenght).Take(lenght * 2).ToArray();
int[] left = array.Take(lenght).ToArray();
int[] right = array.Skip(lenght + (lenght * 2)).Take(lenght).ToArray();
Array.Reverse(left);
Array.Reverse(right);
int[] result = new int[lenght * 2];
for (int i = 0; i < lenght; i++)
{
result[i] = middle[i] + left[i];
result[i + lenght] = middle[i + lenght] + right[i];
}
Console.WriteLine(string.Join(" ", result));
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-September-2017/MethodsDebuggingАndTroubleshootingCode-Exercises/04.NumbersInReversedOrder/Program.cs
namespace _04.NumbersInReversedOrder
{
using System;
public class Program
{
static void Main()
{
string number = Console.ReadLine();
Console.WriteLine(ReverseNumber(number));
}
private static string ReverseNumber(string number)
{
char[] charArray = number.ToCharArray();
Array.Reverse(charArray);
return new string(charArray);
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-September-2017/List-Lab/02.AppendList/AppendList.cs
namespace _02.AppendList
{
using System;
using System.Collections.Generic;
using System.Linq;
public class AppendList
{
public static void Main()
{
List<string> input = Console.ReadLine()
.Split('|')
.ToList();
string result = String.Empty;
for (int i = input.Count - 1; i >= 0 ; i--)
{
string tokens = input[i];
List<string> resultList = tokens
.Split(new char[] {' '}, StringSplitOptions.RemoveEmptyEntries)
.ToList();
for (int k = 0; k < resultList.Count; k++)
{
result += resultList[k] + " ";
}
}
Console.WriteLine(result);
}
}
}
<file_sep>/Software Technologies/Java Basic Syntax Exercises/src/EqualSums.java
import java.util.Arrays;
import java.util.Scanner;
public class EqualSums {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int[] numbers = Arrays.stream(scanner.nextLine()
.split("\\s+"))
.mapToInt(Integer::parseInt).toArray();
for (int i = 0; i < numbers.length; i++) {
int leftSum = Arrays.stream(numbers).limit(i).sum();
int rightSum = Arrays.stream(numbers).skip(i + 1).sum();
if (leftSum == rightSum) {
System.out.println(i);
return;
}
}
System.out.println("no");
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-Extended-November-2017/String, Regular Expressions and Text Processing/02. Count Substring Occurrences/CountSubstringOccurrences.cs
namespace _02.Count_Substring_Occurrences
{
using System;
public class CountSubstringOccurrences
{
public static void Main()
{
string text = Console.ReadLine().ToLower();
string toMatch = Console.ReadLine().ToLower();
int lastIndex = text.IndexOf(toMatch);
int counter = 0;
while (lastIndex > -1)
{
counter++;
lastIndex = text.IndexOf(toMatch, lastIndex + 1);
}
Console.WriteLine(counter);
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-Extended-May-2017/List - More Exercises Extended May 2017/01. Distinct List/Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _1.Distinct_List
{
class Program
{
static void Main(string[] args)
{
int[] intputElements = Console.ReadLine()
.Split(' ')
.Select(int.Parse)
.ToArray();
List<int> distinctElements = new List<int>();
for (int index = 0; index < intputElements.Length; index++)
{
int currentElement = intputElements[index];
if (!distinctElements.Contains(currentElement))
{
distinctElements.Add(currentElement);
}
}
Console.WriteLine(String.Join(" ", distinctElements));
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-September-2017/List-Exercises/07.BombNumbers/BombNumbers.cs
namespace _07.BombNumbers
{
using System;
using System.Collections.Generic;
using System.Linq;
public class BombNumbers
{
public static void Main()
{
List<int> numbers = Console.ReadLine()
.Split(new char[] { ' ', ',', ';', ':', '.', '!', '(', ')', '"', '/', '[', ']', '\'', '\\' }, StringSplitOptions.RemoveEmptyEntries)
.Select(int.Parse)
.ToList();
int[] arr = Console.ReadLine()
.Split(new char[] { ' ', ',', ';', ':', '.', '!', '(', ')', '"', '/', '[', ']', '\'', '\\' }, StringSplitOptions.RemoveEmptyEntries)
.Select(int.Parse)
.ToArray();
int bomb = arr[0];
int rangeBomb = arr[1];
for (int i = 0; i < numbers.Count; i++)
{
if (numbers[i] == bomb)
{
int left = Math.Max(i - rangeBomb, 0);
int right = Math.Min(i + rangeBomb, numbers.Count - 1);
int lenght = right - left + 1;
numbers.RemoveRange(left, lenght);
i = 0;
}
}
Console.WriteLine(numbers.Sum());
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-Extended-May-2017/Arrays and Methods - May 2017 Extended/5.Char Rotation/Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _5.Char_Rotation
{
class Program
{
static void Main(string[] args)
{
var crypted = Console.ReadLine().ToCharArray();
int[] intForPosition = Console.ReadLine().Split(' ').Select(int.Parse).ToArray();
string output = string.Empty;
for (int cnt = 0; cnt < crypted.Length; cnt++)
{
if (intForPosition[cnt] % 2 == 0)
{
crypted[cnt] = (char)((int)crypted[cnt] - intForPosition[cnt]);
} else
{
crypted[cnt] = (char)((int)crypted[cnt] + intForPosition[cnt]);
}
}
Console.WriteLine(String.Join("", crypted));
}
}
}
<file_sep>/Software Technologies/Exam Preparation I - Project Rider/JavaScript/models/project.js
const Sequelize = require('sequelize');
module.exports = function (sequelize) {
//TODO
//rdy todo only for repository
let Project = sequelize.define('Project', {
title:{type: Sequelize.TEXT, allowNull: false,
},
description:{
type: Sequelize.TEXT, allowNull: false,
},
budget:{
type: Sequelize.INTEGER, allowNull: false,
}
}, {
timestamps:false
});
return Project;
};<file_sep>/Programming Fundamentals/Programming-Fundamentals-September-2017/ObjectsAndClasses/04.DistanceBetweenPoints/DistanceBetweenPoints.cs
namespace _04.DistanceBetweenPoints
{
using System;
using System.Linq;
public class DistanceBetweenPoints
{
public static void Main()
{
Point p1 = ReadPoint();
Point p2 = ReadPoint();
double output = CalculateDistance(p1, p2);
Console.WriteLine($"{output:F3}");
}
public static Point ReadPoint()
{
int[] numbers = Console.ReadLine().Split(' ').Select(int.Parse).ToArray();
Point point = new Point();
point.x = numbers[0];
point.y = numbers[1];
return point;
}
public static double CalculateDistance(Point p1, Point p2)
{
int deltaX = p2.x - p1.x;
int deltaY = p2.y - p1.y;
double result = Math.Sqrt(deltaX * deltaX + deltaY * deltaY);
return result;
}
}
public class Point
{
public int x { get; set; }
public int y { get; set; }
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-Extended-May-2017/Arrays and Methods - May 2017 Extended/9.Large Element In Array/Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _9.LargeElemnInArray
{
class Program
{
static void Main(string[] args)
{
int numberOfTokens = int.Parse(Console.ReadLine());
int[] arrayOfIntegers = new int[numberOfTokens];
int biggest = Int32.MinValue;
for (int cnt = 0; cnt < numberOfTokens; cnt++)
{
arrayOfIntegers[cnt] = int.Parse(Console.ReadLine());
if (arrayOfIntegers[cnt] > biggest)
{
biggest = arrayOfIntegers[cnt];
}
}
Console.WriteLine(biggest);
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-September-2017/ConditionalStatementsAndLoops/05.ForeignLanguages/Program.cs
namespace ForeignLanguages
{
using System;
public class Program
{
static void Main()
{
string country = Console.ReadLine();
if (country.Equals("USA") || country.Equals("England"))
{
Console.WriteLine("English");
} else if (country.Equals("Spain") || country.Equals("Argentina") || country == "Mexico")
{
Console.WriteLine("Spanish");
} else
{
Console.WriteLine("unknown");
}
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-September-2017/DataTypesAndVariables-Exercises/07. ExchangeVariableValues/Program.cs
namespace _07.ExchangeVariableValues
{
using System;
public class Program
{
static void Main()
{
int firstInteger = 5;
int secondInteger = 10;
int a = firstInteger;
int b = secondInteger;
int c = a;
int d = b;
a = b; b = c;
Console.WriteLine("Before:");
Console.WriteLine($"a = {firstInteger}");
Console.WriteLine($"b = {secondInteger}");
Console.WriteLine("After:");
Console.WriteLine($"a = {a}");
Console.WriteLine($"b = {b}");
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-Extended-November-2017/String, Regular Expressions and Text Processing/09. Match Numbers/MatchNuumbers.cs
namespace _09.Match_Numbers
{
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
public class MatchNuumbers
{
public static void Main()
{
string input = Console.ReadLine();
string pattern = @"(^|(?<=\s))-?\d+(\.\d+)?($|(?=\s))";
var result = new List<string>();
foreach (Match item in Regex.Matches(input, pattern))
{
result.Add(item.ToString());
}
Console.WriteLine(string.Join(" ", result));
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-September-2017/MethodsDebuggingАndTroubleshootingCode-Exercises/07.PrimesInGivenRange/Program.cs
namespace _07.PrimesInGivenRange
{
using System;
using System.Collections.Generic;
public class Program
{
static void Main()
{
int startNumber = Math.Abs(int.Parse(Console.ReadLine()));
int stopNumber = Math.Abs(int.Parse(Console.ReadLine()));
List<int> primes = GetPrimeNumber(startNumber, stopNumber);
Console.WriteLine(String.Join(", ", primes));
}
static List<int> GetPrimeNumber(int startNum, int stopNum)
{
List<int> primeList = new List<int>();
for (int i = startNum; i <= stopNum; i++)
{
if (IsPrime(i))
{
primeList.Add(i);
}
}
return primeList;
}
static bool IsPrime(int number)
{
if (number == 0 || number == 1)
{
return false;
}
if (number == 2)
{
return true;
}
for (int i = 2; i <= Math.Sqrt(number); i++)
{
if (number % i == 0)
{
return false;
}
}
return true;
}
}
}
<file_sep>/Software Technologies/Java Basic Syntax Exercises/src/CountWorkDays.java
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Scanner;
public class CountWorkDays {
public static void main(String[] args) throws ParseException {
Scanner scanner = new Scanner(System.in);
SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
Date date1 = format.parse(scanner.nextLine());
Date endDate = format.parse(scanner.nextLine());
int workDays = 0;
Calendar calendar = Calendar.getInstance();
while (date1.compareTo(endDate) != 1) {
calendar.setTime(date1);
boolean isHoliday = checkCurrentDay(date1);
if (!isHoliday) {
workDays++;
}
calendar.add(Calendar.DAY_OF_MONTH, 1);
date1 = calendar.getTime();
}
System.out.println(workDays);
}
private static boolean checkCurrentDay(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
int weekDays = calendar.get(Calendar.DAY_OF_WEEK);
if (weekDays == Calendar.SUNDAY || weekDays == Calendar.SATURDAY) {
return true;
}
int monthDay = calendar.get(Calendar.DAY_OF_MONTH);
switch (calendar.get(Calendar.MONTH)) {
case Calendar.JANUARY:
if(monthDay == 1) {
return true;
}
break;
case Calendar.MARCH:
if(monthDay == 3) {
return true;
}
break;
case Calendar.MAY:
if(monthDay == 1 || monthDay == 6 || monthDay == 24) {
return true;
}
break;
case Calendar.SEPTEMBER:
if(monthDay == 6 || monthDay == 22) {
return true;
}
break;
case Calendar.NOVEMBER:
if(monthDay == 1) {
return true;
}
break;
case Calendar.DECEMBER:
if(monthDay == 24 || monthDay == 25 || monthDay == 26) {
return true;
}
break;
}
return false;
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-Extended-November-2017/String, Regular Expressions and Text Processing/03. Text Filter/TextFilter.cs
namespace _03.Text_Filter
{
using System;
using System.Linq;
public class TextFilter
{
public static void Main()
{
string[] bannedWords = Console.ReadLine()
.Split(new char[] { ',', ' ', }, StringSplitOptions.RemoveEmptyEntries).ToArray();
string text = Console.ReadLine();
foreach (var w in bannedWords)
{
string str = new string('*', w.Length);
text = text.Replace(w, str);
}
Console.WriteLine(text);
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-Extended-November-2017/Data Types, Variables and Methods - Exercise/01. Anonymous Downsite/AnonymousDownsite.cs
namespace _01.Anonymous_Downsite
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
public class AnonymousDownsite
{
public static void Main()
{
List<string> webSiteNames = new List<string>();
int websitesDown = int.Parse(Console.ReadLine());
int securityKey = int.Parse(Console.ReadLine());
decimal totalLoss = 0;
for (int i = 0; i < websitesDown; i++)
{
var incomeData = Console.ReadLine().Split(' ').ToList();
string siteName = incomeData[0];
long siteVisits = long.Parse(incomeData[1]);
webSiteNames.Add(siteName);
decimal pricePerVisit = decimal.Parse(incomeData[2]);
totalLoss += siteVisits * pricePerVisit;
}
Console.WriteLine(String.Join(Environment.NewLine, webSiteNames));
Console.WriteLine($"Total Loss: { totalLoss:F20} ");
Console.WriteLine($"Security Token: {BigInteger.Pow(securityKey, websitesDown)}");
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-September-2017/DataTypesAndVariables/03.ExactSumOfRealNumbers/Program.cs
namespace _03.ExactSumOfRealNumbers
{
using System;
public class Program
{
static void Main()
{
int numbersCount = int.Parse(Console.ReadLine());
decimal exactSum = 0;
for (int i = 0; i < numbersCount; i++)
{
decimal currentNumber = decimal.Parse(Console.ReadLine());
exactSum += currentNumber;
}
Console.WriteLine(exactSum);
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-September-2017/StringsAndTextProcessing-Exercise/07.MultiplyBigNumber/MultiplyByNumber.cs
namespace _07.MultiplyBigNumber
{
using System;
using System.Collections.Generic;
using System.Linq;
public class MultiplyByNumber
{
public static void Main()
{
var first = Console.ReadLine().ToCharArray().Select(n => int.Parse(n.ToString())).ToList();
int secondNum = int.Parse(Console.ReadLine());
first.Reverse(); // За да не ги върти цикъла на обратно.
var result = new List<int>();
int sum = 0;
for (int i = 0; i < first.Count; i++)
{
int num = (first[i] * secondNum) + sum;
result.Add(num % 10);
sum = (int)num / 10;
}
if (sum != 0)
{
result.Add(sum);
}
result.Reverse();
bool cutZeros = true;
for (int i = 0; i < result.Count; i++)
{
if (cutZeros)
{
if (result[i] != 0)
{
Console.Write(result[i]);
cutZeros = false;
}
}
else
{
Console.Write(result[i]);
}
}
if (result.All(x => x == 0))
{
Console.WriteLine(0);
}
Console.WriteLine();
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-September-2017/Arrays-Exercise/08.MostFrequentNumber/MostFrequentNumber.cs
namespace _08.MostFrequentNumber
{
using System;
using System.Linq;
public class MostFrequentNumber
{
public static void Main()
{
int[] array = Console.ReadLine()
.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
.Select(int.Parse)
.ToArray();
int repeats = 0;
int freqNumber = 0;
for (int i = 0; i < array.Length; i++)
{
int currentNumber = array[i];
int counter = 0;
for (int k = i; k < array.Length; k++)
{
if (currentNumber == array[k])
{
counter++;
}
}
if (counter > repeats)
{
freqNumber = currentNumber;
repeats = counter;
}
}
Console.WriteLine("{0}", freqNumber);
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-September-2017/RegularExpressions(RegEx)-Lab/01.MatchFullName/MatchFullName.cs
namespace _01.MatchFullName
{
using System;
using System.Linq;
using System.Text.RegularExpressions;
public class MatchFullName
{
public static void Main()
{
//var input = Console.ReadLine().Split(new char[] { ' ', ',', }, StringSplitOptions.RemoveEmptyEntries).ToList();
string regex = @"\b([A-Z][a-z]+ [A-Z][a-z]+)\b";
string input = Console.ReadLine();
MatchCollection machNames = Regex.Matches(input, regex);
foreach (Match name in machNames)
{
Console.Write(name.Value + " ");
}
Console.WriteLine();
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-September-2017/StringsAndTextProcessing-Exercise/02.ConvertFromBaseNtoBase10/02.Convert.cs
namespace _01.ConvertFromBase_10toBase_N
{
using System;
using System.Linq;
using System.Numerics;
public class Convert
{
public static void Main()
{
string[] input = Console.ReadLine().Split(' ').ToArray();
int one = int.Parse(input[0]);
char[] two = input[1].ToCharArray();
BigInteger result = 0;
for (int i = two.Length - 1, n = 0; i >= 0; i--, n++)
{
BigInteger num = new BigInteger(char.GetNumericValue(two[n]));
BigInteger sum = BigInteger.Multiply(num, BigInteger.Pow(new BigInteger(one), i));
result += sum;
}
Console.WriteLine(result.ToString());
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-September-2017/MethodsDebuggingАndTroubleshootingCode-Exercises/05.FibonacciNumbers/Program.cs
namespace _05.FibonacciNumbers
{
using System;
public class Program
{
public static void Main()
{
int number = int.Parse(Console.ReadLine());
Console.WriteLine(GetFibonaciNthNumber(number));
}
private static int GetFibonaciNthNumber(int n)
{
int a = 1;
int b = 1;
for (int i = 0; i < n; i++)
{
int temp = a;
a = b;
b = temp + b;
}
return a;
}
}
}
<file_sep>/Programming Fundamentals/PF-Exams/PF-Exam-26February2017/01.HornetWings/HornetWings.cs
namespace _01.HornetWings
{
using System;
public class HornetWings
{
static void Main()
{ // 100/100 Points
int wingFlaps = int.Parse(Console.ReadLine());
double distancePer1000flaps = double.Parse(Console.ReadLine()); // for/per 1000 wing flaps
int endurance = int.Parse(Console.ReadLine());
//You can assume that a hornet makes 100 wing flaps per second.
double traveledDistance = distancePer1000flaps * (wingFlaps / 1000); //Distance
int timeHornetFlaps = wingFlaps / 100; // seconds that hornet is flap "wingFlap" times
int timesToRest = wingFlaps / endurance;
int allTimeToRest = timesToRest * 5;
int totalTimeInSeconds = allTimeToRest + timeHornetFlaps;
Console.WriteLine($"{traveledDistance:F2} m.");
Console.WriteLine($"{totalTimeInSeconds} s.");
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-September-2017/ConditionalStatementsAndLoops-Exercises/10.TriangleOfNumbers/Program.cs
namespace TriangleOfNumbers
{
using System;
public class Program
{
static void Main()
{
int number = int.Parse(Console.ReadLine());
for (int col = 1; col <= number; col++)
{
for (int row = 1; row <= col - 1; row++) // Starts from 1 to col - 1 !!!
{
Console.Write(col + " ");
}
Console.WriteLine(col);
}
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-September-2017/Arrays-Lab/02.ReverseAnArrayOfIntegers/Program.cs
namespace _02.ReverseAnArrayOfIntegers
{
using System;
using System.Linq;
public class Program
{
public static void Main()
{
int num = int.Parse(Console.ReadLine());
int[] numberArray = new int[num];
for (int i = 0; i < numberArray.Length; i++)
{
numberArray[i] += int.Parse(Console.ReadLine());
}
Array.Reverse(numberArray);
Console.WriteLine(string.Join(" ", numberArray));
}
}
}
<file_sep>/Software Technologies/Exam SoftUni Lab 10.Jan.2019/JavaScript/softunilabs/models/lab.js
const Sequelize = require('sequelize');
module.exports = function (sequelize) {
//TODO: Implement me
let Lab = sequelize.define('Lab', {
name:{type: Sequelize.TEXT,required: true, allowNull: false,
},
capacity:{
type: Sequelize.INTEGER,required: true, allowNull: false,
},
status:{
type: Sequelize.TEXT,required: true, allowNull: false,
}
}, {
timestamps:false
});
return Lab;
};<file_sep>/Programming Fundamentals/PF-Exams/PF-Exam-6January2017-Retake/01.SinoTheWalker/SinoTheWalker.cs
namespace _01.SinoTheWalker
{
using System;
using System.Globalization;
public class SinoTheWalker
{
static void Main()
{
CultureInfo provider = CultureInfo.InvariantCulture;
DateTime shinoLeaveTheBuilding = DateTime.ParseExact(Console.ReadLine(), "HH:mm:ss", provider);
double steps = double.Parse(Console.ReadLine());
double secondsForStep = double.Parse(Console.ReadLine());
// 86400 seconds in 1 day
steps = steps % 86400;
secondsForStep = secondsForStep % 86400;
double howLongIsHeWalk = steps * secondsForStep;
DateTime dtm = shinoLeaveTheBuilding.AddSeconds(howLongIsHeWalk);
string answer = string.Format("Time Arrival: {0}", dtm.ToString("HH:mm:ss"));
Console.WriteLine(answer);
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-Extended-May-2017/List Lab Exercises - May 2017 Extended/4. Split by Word Casing/Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _4.Split_by_Word_Casing
{
class Program
{
static void Main(string[] args)
{
List <string> lowerCase = new List<string>();
List <string> upperCase = new List<string>();
List <string> mixedCase = new List<string>();
List<string> totalWords = Console.ReadLine().Split(new char[] { ' ', '!', '(', ')', ',', '.', '\'',
'\"', ':', ';', '[', ']', '\\', '/' }, StringSplitOptions.RemoveEmptyEntries).ToList();
string currentWord = string.Empty;
for (int i = 0; i < totalWords.Count; i++)
{
if (totalWords[i].All(char.IsLower))
{
lowerCase.Add(totalWords[i]);
} else if (totalWords[i].All(char.IsUpper))
{
upperCase.Add(totalWords[i]);
} else
{
mixedCase.Add(totalWords[i]);
}
}
Console.WriteLine($"Lower-case: {string.Join(", ", lowerCase )}");
Console.WriteLine($"Mixed-case: {string.Join(", ", mixedCase)}");
Console.WriteLine($"Upper-case: {string.Join(", ", upperCase)}");
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-September-2017/StringsAndTextProcessing-Lab/04.Palindromes/Palindromes.cs
namespace ConsoleApp1
{
using System;
using System.Collections.Generic;
using System.Linq;
public class Palindromes
{
public static void Main()
{
string[] text = Console.ReadLine()
.Split(new char[] {' ', ',', '.', '!', '?', ':',}, StringSplitOptions.RemoveEmptyEntries)
.ToArray();
var result = new SortedSet<string>();
foreach (var word in text)
{
if (!IsPalindrome(word))
{
continue;
}
result.Add(word);
}
Console.WriteLine(string.Join(", ", result));
}
public static bool IsPalindrome(string value)
{
int min = 0;
int max = value.Length - 1;
while (true)
{
if (min > max)
{
return true;
}
char a = value[min];
char b = value[max];
if (a != b)
{
return false;
}
min++;
max--;
}
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-Extended-May-2017/List - More Exercises Extended May 2017/04. Ununion List/Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
namespace _4.Ununion_Lists
{
class Program
{
static void Main(string[] args)
{
List<int> primalList = Console.ReadLine()
.Split(' ')
.Select(int.Parse)
.ToList();
int n = int.Parse(Console.ReadLine());
for (int i = 0; i < n; i++)
{
List<int> currentList = Console.ReadLine()
.Split(' ')
.Select(int.Parse)
.ToList();
for (int cnt = 0; cnt < currentList.Count; cnt++)
{
int currentElement = currentList[cnt];
if (primalList.Contains(currentElement))
{
primalList.RemoveAll(e => e == currentElement);
} else
{
primalList.Add(currentElement);
}
}
}
primalList.Sort();
Console.WriteLine(string.Join(" ", primalList));
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-Extended-November-2017/Data Types, Variables and Methods - Exercise/05. Wormtest/wormtest.cs
namespace _05.Wormtest
{
using System;
using System.Numerics;
public class Wormtest
{
public static void Main()
{
int wormLength = int.Parse(Console.ReadLine());
double wormWidth = double.Parse(Console.ReadLine());
long lengthInSantimeters = wormLength * 100;
double remainder = lengthInSantimeters % wormWidth;
double totalsum = lengthInSantimeters * wormWidth;
double percents = (lengthInSantimeters / wormWidth) * 100;
if (remainder == 0 || wormWidth == 0)
{
Console.WriteLine($"{totalsum:F2}");
}
else
{
Console.WriteLine($"{percents:F2}%");
}
}
}
}
<file_sep>/Software Technologies/Java Basic Syntax Exercises/src/MostFrequentNumber.java
import java.util.Arrays;
import java.util.Scanner;
public class MostFrequentNumber {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int[] numbers = Arrays
.stream(scanner.nextLine()
.split("\\s+"))
.mapToInt(Integer::parseInt).toArray();
int maxCounter = 0;
int maxNnumber = numbers[0];
for (int i = 0; i < numbers.length; i++) {
int tempCounter = 1;
for (int j = i; j < numbers.length; j++) {
if (numbers[i] == numbers[j]) {
tempCounter++;
}
}
if (tempCounter > maxCounter) {
maxCounter = tempCounter;
maxNnumber = numbers[i];
}
}
System.out.println(maxNnumber);
}
}
<file_sep>/Software Technologies/JavaScript Syntax and Basic Web - Exercises/03. DivideNumber.js
function solve(args) {
let n = args[0];
let x = args[1];
if(x >= n) {
console.log(x * n);
} else {
console.log(n / x);
}
}
solve([2, 3]);
solve([13, 13]);
solve([3, 2]);
solve([144, 12]);
<file_sep>/Software Technologies/PHP - Syntax and Basic Web/05. Dump an HTTP GET Request.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>HTTP GET Request</title>
</head>
<body>
<form>
<div>Name:</div>
<input type = "text" name = "personName"/>
<div>Age:</div>
<input type = "number" name = "age"/>
<div>Town</div>
<select name = "townId">
<option value = "10">Sofia</option>
<option value = "20">Varna</option>
<option value = "30">Plovdiv</option>
</select>
<div><input type = "submit"/></div>
</form>
<?php var_dump($_GET); ?>
</body>
</html><file_sep>/Software Technologies/JavaScript Syntax and Basic Web - Lab/07. Largest3Numbers.js
function solve(numbers) {
let sortedNumbers = numbers.sort((a, b) => (a - b));
sortedNumbers.reverse();
if (sortedNumbers.length <= 2) {
console.log(sortedNumbers.shift());
console.log(sortedNumbers.shift());
} else {
console.log(sortedNumbers.shift());
console.log(sortedNumbers.shift());
console.log(sortedNumbers.shift());
}
}
solve(['10', '30', '15', '20', '50', '5']);<file_sep>/Programming Fundamentals/Programming-Fundamentals-September-2017/ObjectsАndClasses-Exercise/03.IntersectionOfCircles/IntersectionOfCircles.cs
namespace _03.Intersection_fCircles
{
using System;
using System.Collections.Generic;
using System.Linq;
public class IntersectionOfCircles
{
public static void Main()
{
List<int> list = Console.ReadLine().Split(' ').Select(int.Parse).ToList();
List<int> list2 = Console.ReadLine().Split(' ').Select(int.Parse).ToList();
Circle c1 = new Circle()
{
x = list[0],
y = list[1],
Radius = list[2],
};
Circle c2 = new Circle()
{
x = list2[0],
y = list2[1],
Radius = list2[2],
};
if (Intersect(c1, c2))
{
Console.WriteLine("Yes");
} else
{
Console.WriteLine("No");
}
}
public static bool Intersect(Circle c1, Circle c2)
{
var firstPoint = Math.Abs(c1.x - c2.y);
var secondPoint = Math.Abs(c1.y - c2.y);
var distance = Math.Sqrt(Math.Pow(firstPoint, 2) + Math.Pow(secondPoint, 2));
var sumRadiuses = c1.Radius + c2.Radius;
if (distance <= sumRadiuses)
{
return true;
}
else
{
return false;
}
}
public class Circle
{
public int Center { get; set; }
public int Radius { get; set; }
public int x { get; set; }
public int y { get; set; }
}
}
}
<file_sep>/Software Technologies/JavaScript Syntax and Basic Web - Exercises/01. MultiplyANumberBy2.js
function multipluyANumberBy2 (args) {
let number = Number(args[0]);
console.log(number * 2);
}
//multipluyANumberBy2(['13']);
//multipluyANumberBy2(['13']);
//multipluyANumberBy2(['5']);
//multipluyANumberBy2(['15']);<file_sep>/Programming Fundamentals/Programming-Fundamentals-Extended-November-2017/String, Regular Expressions and Text Processing - Exercise/03. Hornet Comm/HornetComm.cs
namespace _03.Hornet_Comm
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
public class HornetComm
{
public static void Main()
{
string input = Console.ReadLine();
List<string> message = new List<string>();
List<string> broadcast = new List<string>();
string privatePattern = @"^([0-9]+) <-> ([a-zA-Z0-9]+)$";
string broadcastPattern = @"^([^0-9]+) <-> ([a-zA-Z0-9]+)$";
while (input != "Hornet is Green")
{
var privatee = Regex.Match(input, privatePattern);
var broadcastMes = Regex.Match(input, broadcastPattern);
if (privatee.Success)
{
string temp = privatee.Groups[1].ToString();
temp = string.Join("", temp.ToCharArray().Reverse().ToArray());
message.Add(temp + " -> " + privatee.Groups[2].ToString());
}
if (broadcastMes.Success)
{
string temp = broadcastMes.Groups[2].ToString();
string tempResult = String.Empty;
for (int i = 0; i < temp.Length; i++)
{
if (char.IsLower(temp[i]))
{
tempResult += temp[i].ToString().ToUpper();
}
else if (char.IsUpper(temp[i]))
{
tempResult += temp[i].ToString().ToLower();
}
else
{
tempResult += temp[i].ToString();
}
}
broadcast.Add(tempResult + " -> " + broadcastMes.Groups[1]);
}
input = Console.ReadLine();
}
Console.WriteLine("Broadcasts:");
if (broadcast.Count == 0)
{
Console.WriteLine("None");
}
else
{
Console.WriteLine(String.Join(Environment.NewLine, broadcast));
}
Console.WriteLine("Messages:");
if (message.Count == 0)
{
Console.WriteLine("None");
}
else
{
Console.WriteLine(String.Join(Environment.NewLine, message));
}
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-September-2017/StringsAndTextProcessing-Exercise/01.ConvertFromBase-10toBase-N/Convert.cs
namespace _01.ConvertFromBase_10toBase_N
{
using System;
using System.Linq;
using System.Numerics;
public class Convert
{
public static void Main()
{
BigInteger[] input = Console.ReadLine().Split(' ').Select(BigInteger.Parse).ToArray();
BigInteger one = input[0];
BigInteger two = input[1];
BigInteger remainder = 0;
string str = String.Empty;
if (one >= 0 && one <= 10)
{
while (two > 0)
{
remainder = two % one;
two /= one;
str = remainder.ToString() + str;
}
Console.WriteLine(str);
}
else
{
}
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-Extended-November-2017/Data Types, Variables and Methods - Exercise/03. Poke Mon/PokeMon.cs
namespace _03.Poke_Mon
{
using System;
public class PokeMon
{
public static void Main()
{
int n = int.Parse(Console.ReadLine());
int m = int.Parse(Console.ReadLine());
int y = int.Parse(Console.ReadLine());
int counter = 0;
double divide = n / 2.0;
while (n >= m)
{
if (n == divide)
{
if (y != 0)
{
n = n / y;
}
if (n >= m)
{
n -= m;
counter++;
}
}
else
{
n -= m;
counter++;
}
}
Console.WriteLine(n);
Console.WriteLine(counter);
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-September-2017/DictionariesLambdaAndLINQ-Exercise/07.PopulationCounter/PopulationCounter.cs
namespace _07.PopulationCounter
{
using System;
using System.Collections.Generic;
using System.Linq;
public class PopulationCounter
{
public static void Main()
{
var data = new Dictionary<string, Dictionary<string, long>>();
string input = Console.ReadLine();
while (input != "report")
{
var inputArgs = input.Split('|');
var city = inputArgs[0];
var country = inputArgs[1];
long population = long.Parse(inputArgs[2]);
if (!data.ContainsKey(country))
{
data.Add(country, new Dictionary<string, long>());
data[country].Add(city, population);
}
if (!data[country].ContainsKey(city))
{
data[country].Add(city, 0);
}
data[country][city] = population;
input = Console.ReadLine();
}
foreach (var item in data.OrderByDescending(x => x.Value.Values.Sum()))
{
var country = item.Key;
Console.WriteLine("{0} (total population: {1})", country, item.Value.Values.Sum());
foreach (var items in item.Value.OrderByDescending(p => p.Value))
{
var city = items.Key;
long popUp = items.Value;
Console.WriteLine($"=>{city}: {popUp}");
}
}
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-September-2017/DataTypesAndVariables-Exercises/03.PracticeCharactersAndStrings/Program.cs
namespace _03.PracticeCharactersAndStrings
{
using System;
public class Program
{
static void Main()
{
string firstInput = Console.ReadLine();
char firstChar = char.Parse(Console.ReadLine());
char secondChar = char.Parse(Console.ReadLine());
char thirdChar = char.Parse(Console.ReadLine());
string secondInput = Console.ReadLine();
Console.WriteLine(firstInput);
Console.WriteLine(firstChar);
Console.WriteLine(secondChar);
Console.WriteLine(thirdChar);
Console.WriteLine(secondInput);
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-September-2017/ObjectsAndClasses/01.DayOfWeek/DayOfWeek.cs
namespace _01.DayOfWeek
{
using System;
using System.Globalization;
public class DayOfWeek
{
public static void Main()
{
DateTime input = DateTime.ParseExact(Console.ReadLine(), "d-M-yyyy", CultureInfo.InvariantCulture);
Console.WriteLine(input.DayOfWeek);
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-September-2017/Exam Preparation I/04. Winning Ticket/WinningTicket.cs
namespace _04.Winning_Ticket
{
using System;
using System.Linq;
using System.Text.RegularExpressions;
public class WinningTicket
{
public static void Main()
{ // 80/100 - Points - Missing cases
var tickets = Console.ReadLine()
.Split(new char[] { ',', ' ', }, StringSplitOptions.RemoveEmptyEntries)
.ToList();
string[] patterns = { "\\@{6,9}", "\\#{6,9}", "\\${6,9}", "\\^{6,9}", };
foreach (var ticket in tickets)
{
if (ticket.Length != 20)
{
Console.WriteLine("invalid ticket");
continue;
}
string left = ticket.Substring(0, 10);
string right = ticket.Substring(10, 10);
bool isMatch = false;
for (int i = 0; i < patterns.Length; i++)
{
if (Regex.IsMatch(left, patterns[i]) && Regex.IsMatch(right, patterns[i]))
{
string symbol = WinningSymbol(i);
int symbolMatch = SymbolCounter(left, Char.Parse(symbol));
if (symbolMatch == 10)
{
Console.WriteLine($"ticket \"{ticket}\" - {symbolMatch}{symbol} Jackpot!");
isMatch = true;
continue;
}
Console.WriteLine($"ticket \"{ticket}\" - {symbolMatch}{symbol}");
isMatch = true;
continue;
}
}
if (!isMatch)
{
Console.WriteLine($"ticket \"{ticket}\" - no match");
}
}
}
public static string WinningSymbol(int number)
{
switch (number)
{
case 0:
return "@";
case 1:
return "#";
case 2:
return "$";
case 3:
return "^";
default:
return "error";
}
}
public static int SymbolCounter(string str, char letter)
{
int counter = 0;
int maxCount = 0;
for (int i = 0; i < str.Length; i++)
{
if (str[i] == letter)
{
counter++;
if (maxCount < counter)
{
maxCount = counter;
}
}
else
{
counter = 0;
}
}
return maxCount;
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-September-2017/Arrays-Exercise/1. Largest Common End/LargestCommonEnd.cs
namespace _1.Largest_Common_End
{
using System;
using System.Linq;
public class LargestCommonEnd
{
public static void Main()
{
string[] firstArray = Console.ReadLine()
.Split(' ')
.ToArray();
string[] secondArray = Console.ReadLine()
.Split(' ')
.ToArray();
int arraysLenght = Math.Min(firstArray.Length, secondArray.Length);
int count = 0;
for (int i = 0; i < arraysLenght; i++)
{
if (firstArray[i] == secondArray[i])
{
count++;
} else
{
break;
}
}
Array.Reverse(firstArray);
Array.Reverse(secondArray);
int secondCount = 0;
for (int i = 0; i < arraysLenght; i++)
{
if (firstArray[i] == secondArray[i])
{
secondCount++;
}
}
if (count >= secondCount)
{
Console.WriteLine(count);
} else
{
Console.WriteLine(secondCount);
}
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-September-2017/Arrays-Lab/09.ExtractMiddle1-2or3Elements-Easyway/Program.cs
namespace _09.ExtractMiddle1_2or3Elements_Easyway
{
using System;
using System.Linq;
public class Program
{
public static void Main()
{
int[] array = Console.ReadLine()
.Split(' ')
.Select(int.Parse)
.ToArray();
int[] result;
int resultLenght = array.Length;
if (resultLenght == 1)
{
result = new int[1];
result[0] = array[0];
} else if (resultLenght % 2 == 0)
{
result = new int[2];
result[0] = array[array.Length / 2 - 1];
result[1] = array[array.Length / 2];
} else
{
result = new int[3];
result[0] = array[array.Length / 2 - 1];
result[1] = array[array.Length / 2];
result[2] = array[array.Length / 2 + 1];
}
Console.WriteLine("{0} {1} {2}", '{', string.Join(", ", result), '}');
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-September-2017/List-Lab/04.SplitByWordCasing/SplitByWordCasing.cs
namespace _04.SplitByWordCasing
{
using System;
using System.Collections.Generic;
using System.Linq;
public class SplitByWordCasing
{
public static void Main()
{
List<string> text = Console.ReadLine()
.Split(new char[] { ' ', ',', ';', ':', '.', '!', '(', ')', '"', '/', '[', ']', '\'', '\\' }, StringSplitOptions.RemoveEmptyEntries)
.ToList();
List<string> lowerCase = new List<string>();
List<string> upperCase = new List<string>();
List<string> mixedCase = new List<string>();
int lower = 0;
int upper = 0;
foreach (var word in text)
{
foreach (var letters in word)
{
if (letters >= 'a' && letters <= 'z')
{
lower++;
}
else if (letters >= 'A' && letters <= 'Z')
{
upper++;
}
else if (letters >= ' ' && letters <= '@')
{
lower++;
upper++;
}
}
if (lower > 0 && upper == 0)
{
lowerCase.Add(word);
}
else if (lower == 0 && upper > 0)
{
upperCase.Add(word);
}
else if (lower > 0 && upper > 0)
{
mixedCase.Add(word);
}
upper = 0;
lower = 0;
}
Console.WriteLine("Lower-case: {0}", string.Join(", ", lowerCase));
Console.WriteLine("Mixed-case: {0}", string.Join(", ", mixedCase));
Console.WriteLine("Upper-case: {0}", string.Join(", ", upperCase));
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-September-2017/MethodsDebuggingАndTroubleshootingCode-Exercises/14.FactorialTrailingZeroes/Program.cs
namespace _14.FactorialTrailingZeroes
{
using System;
using System.Numerics;
public class Program
{
public static void Main()
{
int number = int.Parse(Console.ReadLine());
Console.WriteLine(FindFactorial(number));
}
// Calculating factorial with n - number and find treiling zeros.
static int FindFactorial(int number)
{
BigInteger factorial = 1;
for (int i = 1; i <= number; i++)
{
factorial = factorial * i;
}
string text = factorial.ToString();
string[] zeros = text.Split('0');
int count = 0;
for (int i = zeros.Length - 1; i >= 0; i--)
{
if (zeros[i] == "")
{
count = count + 1;
}
else
{
break;
}
}
return count;
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-September-2017/MethodsDebuggingAndTroubleshootingCode/04.DrawAFilledSquare/Program.cs
namespace _04.DrawAFilledSquare
{
using System;
public class Program
{
static void Main()
{
int number = int.Parse(Console.ReadLine());
PrintHeaderRow(number);
for (int i = 0; i < number - 2; i++)
{
PrintMiddleRow(number);
}
PrintHeaderRow(number);
}
static void PrintHeaderRow(int num)
{
Console.WriteLine(new string('-', num * 2));
}
static void PrintMiddleRow(int num)
{
Console.Write('-');
for (int i = 1; i <= (2 * num-2)/2; i++)
{
Console.Write("\\/");
}
Console.WriteLine('-');
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-Extended-May-2017/Arrays and Methods - May 2017 Extended/14.EqualElemtsInArray/Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _14.EqualElemtsInArray
{
class Program
{
static void Main(string[] args)
{
int[] arrayElements = Console.ReadLine().Split(' ').Select(int.Parse).ToArray();
bool IsEqual = false;
for (int cnt = 0; cnt < arrayElements.Length - 1; cnt++)
{
if (arrayElements[cnt] == arrayElements[cnt + 1])
{
IsEqual = true;
} else
{
IsEqual = false;
break;
}
}
if (IsEqual)
{
Console.WriteLine("Yes");
} else
{
Console.WriteLine("No");
}
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-September-2017/DataTypesAndVariables/9.RefactorSpecialNumbers/Program.cs
namespace _9.RefactorSpecialNumbers
{
using System;
public class Program
{
static void Main()
{
int stopNumber = int.Parse(Console.ReadLine());
int sum = 0;
int num = 0;
bool isSpecial = false;
for (int ch = 1; ch <= stopNumber; ch++)
{
num = ch;
while (ch > 0)
{
sum += ch % 10;
ch = ch / 10;
}
isSpecial = (sum == 5) || (sum == 7) || (sum == 11);
Console.WriteLine($"{num} -> {isSpecial}");
sum = 0;
ch = num;
}
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-September-2017/FilesDirectoriesАndExceptions-Exercise/02.IndexOfLetters/IndexOfLetters.cs
namespace _02.IndexOfLetters
{
using System;
using System.IO;
public class IndexOfLetters
{
public static void Main()
{
string[] words = File.ReadAllLines("input.txt");
File.Delete("output.txt");
foreach (var charr in words)
{
char[] alphabet = new char[26]
{ 'a', 'b', 'c', 'd', 'e', 'f', 'g','h', 'i', 'j', 'k', 'l','m', 'n',
'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
for (int i = 0; i < charr.Length; i++)
{
char currentChar = charr[i];
string output = $"{currentChar} -> {Array.IndexOf(alphabet, currentChar)}\r\n";
File.AppendAllText("output.txt", output);
}
}
}
}
}<file_sep>/Software Technologies/Exam Preparation III - LogNoziroh & ShoppingList/LogNoziroh/JavaScript-Skeleton/models/Report.js
const Sequelize = require('sequelize');
module.exports = function (sequelize) {
//TODO
let Report = sequelize.define('Report', {
status:{type:Sequelize.TEXT, required: true, allowNull: false,},
message:{type:Sequelize.TEXT, required: true, allowNull: false,},
origin:{type:Sequelize.TEXT, required: true, allowNull: false,},
}, {
timestamps:false
})
return Report;
};<file_sep>/Programming Fundamentals/Programming-Fundamentals-Extended-May-2017/Arrays and Methods - May 2017 Extended/18.BallisticsTraining/Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _18.BallisticsTraining
{
class Program
{
static void Main(string[] args)
{
int[] cordinates = Console.ReadLine().Split(' ').Select(int.Parse).ToArray();
string[] commands = Console.ReadLine().Split(' ');
int x = 0;
int y = 0;
for (int cnt = 0; cnt < commands.Length; cnt++)
{
if (commands[cnt] == "up")
{
y += Convert.ToInt32(commands[cnt + 1]);
}
if (commands[cnt] == "down")
{
y -= Convert.ToInt32(commands[cnt + 1]);
}
if (commands[cnt] == "left")
{
x -= Convert.ToInt32(commands[cnt + 1]);
}
if (commands[cnt] == "right")
{
x += Convert.ToInt32(commands[cnt + 1]);
}
}
if (cordinates[0] == x && cordinates[1] == y)
{
Console.WriteLine("firing at [{0}, {1}]", cordinates[0], cordinates[1]);
Console.WriteLine("got 'em!");
} else
{
Console.WriteLine("firing at [{0}, {1}]", x, y);
Console.WriteLine("better luck next time...");
}
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-September-2017/DictionariesLambdaAndLINQ/03.SumMinMaxAverage/SumMinMaxAverage.cs
namespace _03.SumMinMaxAverage
{
using System;
using System.Collections.Generic;
using System.Linq;
public class SumMinMaxAverage
{
public static void Main()
{
int numbersCount = int.Parse(Console.ReadLine());
int currentNumber = 0;
List<int> numbers = new List<int>();
for (int i = 0; i < numbersCount; i++)
{
currentNumber = int.Parse(Console.ReadLine());
numbers.Add(currentNumber);
}
Console.WriteLine("Sum = " + numbers.Sum());
Console.WriteLine("Min = " + numbers.Min());
Console.WriteLine("Max = " + numbers.Max());
Console.WriteLine("Average = " + numbers.Average());
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-September-2017/Exam Preparation II/04. Roli The Coder/RoliTheCoder.cs
namespace _04.Roli_The_Coder
{
using System;
using System.Collections.Generic;
using System.Linq;
public class RoliTheCoder
{
public static void Main() // 60/100 Points - Missing cases
{
Dictionary<string, List<string>> eventsParticipants = new Dictionary<string, List<string>>();
Dictionary<string, string> eventsIDs = new Dictionary<string, string>();
while (true)
{
var input = Console.ReadLine();
if (input == "Time for Code")
{
break;
}
var inputArgs = input.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).ToArray();
if (!inputArgs[1].StartsWith("#"))
{
continue;
}
string id = inputArgs[0];
string eventName = inputArgs[1].Substring(1, inputArgs[1].Length - 1);
if (!eventsIDs.ContainsKey(id))
{
eventsIDs.Add(id, eventName);
eventsParticipants[eventName] = new List<string>();
for (int i = 2; i < inputArgs.Length; i++)
{
if (!inputArgs[i].Contains('@'))
{
continue;
}
if (!eventsParticipants[eventName].Contains(inputArgs[i]))
{
eventsParticipants[eventName].Add(inputArgs[i]);
}
}
}
else
{
if (eventsIDs[id] == eventName)
{
for (int i = 2; i < inputArgs.Length; i++)
{
if (!inputArgs[i].Contains('@'))
{
continue;
}
if (!eventsParticipants[eventName].Contains(inputArgs[i]))
{
eventsParticipants[eventName].Add(inputArgs[i]);
}
}
}
else
{
continue;
}
}
}
foreach (var pair in eventsParticipants.OrderByDescending(x => x.Value.Count).ThenBy(x => x.Key))
{
Console.WriteLine($"{pair.Key} - {pair.Value.Count}");
foreach (var item in pair.Value.OrderBy(x => x))
{
Console.WriteLine(item);
}
}
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-Extended-May-2017/Arrays and Methods - May 2017 Extended/6. Notifications/Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Arrays_and_Methods___Exercise
{
class Program
{
static void Main(string[] args)
{
int messageCount = int.Parse(Console.ReadLine());
string output = string.Empty;
for (int i = 0; i < messageCount; i++)
{
string message = Console.ReadLine();
if (message == "success")
{
string operation = Console.ReadLine();
string messageOne = Console.ReadLine();
output = SuccessMessage(operation, messageOne);
Console.WriteLine(output);
}
else if (message == "error")
{
string messageTwo = Console.ReadLine();
int code = int.Parse(Console.ReadLine());
output = ErrorMessage(messageTwo, code);
Console.WriteLine(output);
}
else
{
continue;
}
}
}
public static string ErrorMessage(string operation, int code)
{
string reason = "Invalid Client Data";
if (code < 0)
{
reason = "Internal System Failure";
}
string output = $@"Error: Failed to execute {operation}.
==============================
Error Code: {code}.
Reason: {reason}.";
return output;
}
public static string SuccessMessage(string operation, string messageOne)
{
string output = $@"Successfully executed {operation}.
==============================
Message: {messageOne}.";
return output;
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-September-2017/DictionariesLambdaAndLINQ/05.ShortWordsSorted/ShortWordsSorted.cs
namespace _05.ShortWordsSorted
{
using System;
using System.Collections.Generic;
using System.Linq;
public class ShortWordsSorted
{
public static void Main()
{
var text = Console.ReadLine()
.ToLower()
.Split(new char[] { ' ', ',', ';', ':', '.', '!', '(', ')', '"', '/', '[', ']', '\'', '\\' }
, StringSplitOptions.RemoveEmptyEntries)
.ToList();
text.Sort();
Console.WriteLine(string.Join(", ", text.Distinct().Where(x => x.Length < 5)));
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-September-2017/StringsAndTextProcessing-Lab/02.CountSubstringOccurrences/CountSubstringOccurences.cs
namespace _02.CountSubstringOccurrences
{
using System;
public class CountSubstringOccurences
{
public static void Main()
{
string text = Console.ReadLine().ToLower();
string lookFor = Console.ReadLine().ToLower();
int counter = 0;
int index = text.IndexOf(lookFor);
while (index != - 1)
{
counter++;
index = text.IndexOf(lookFor, index + 1);
}
Console.WriteLine(counter);
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-September-2017/ConditionalStatementsAndLoops-Exercises/07.CakeIngredients/Program.cs
namespace CakeIngredients
{
using System;
public class Program
{
static void Main()
{
string cakeProducts = Console.ReadLine();
int counter = 0;
while (cakeProducts != "Bake!")
{
Console.WriteLine("Adding ingredient {0}.", cakeProducts);
cakeProducts = Console.ReadLine();
counter++;
}
Console.WriteLine("Preparing cake with {0} ingredients.", counter);
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-September-2017/MethodsDebuggingAndTroubleshootingCode/11.PriceChangeAlert/Program.cs
using System;
public class PriceChangeAlert
{
public static void Main()
{
int numberOfPrices = int.Parse(Console.ReadLine());
double minorOrMajor = double.Parse(Console.ReadLine());
double prices = double.Parse(Console.ReadLine());
for (int i = 0; i < numberOfPrices - 1; i++)
{
double currentPrice = double.Parse(Console.ReadLine());
double diff = GetDifferenceProcents(prices, currentPrice);
bool isSignificantDifference = IsDifference(diff, minorOrMajor);
string priceAlert = GetDifference(currentPrice, prices, diff, isSignificantDifference);
Console.WriteLine(priceAlert);
prices = currentPrice;
}
}
private static string GetDifference(double currentPrice, double prices, double difference, bool etherTrueOrFalse)
{
string priceAlert = String.Empty;
if (difference == 0)
{
priceAlert = string.Format("NO CHANGE: {0}", currentPrice);
}
else if (!etherTrueOrFalse)
{
priceAlert = string.Format("MINOR CHANGE: {0} to {1} ({2:F2}%)", prices, currentPrice, difference * 100);
}
else if (etherTrueOrFalse && (difference > 0))
{
priceAlert = string.Format("PRICE UP: {0} to {1} ({2:F2}%)", prices, currentPrice, difference * 100);
}
else if (etherTrueOrFalse && (difference < 0))
{
priceAlert = string.Format("PRICE DOWN: {0} to {1} ({2:F2}%)", prices, currentPrice, difference * 100);
}
return priceAlert;
}
private static bool IsDifference(double minorOrMajor, double isDiff)
{
if (Math.Abs(minorOrMajor) >= isDiff)
{
return true;
}
return false;
}
//Procents
private static double GetDifferenceProcents(double price, double currentPrice)
{
double result = (currentPrice - price) / price;
return result;
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-September-2017/DataTypesAndVariables-Exercises/16.ComparingFloats/Program.cs
namespace _16.ComparingFloats
{
using System;
public class Program
{
static void Main()
{
double numberA = double.Parse(Console.ReadLine());
double numberB = double.Parse(Console.ReadLine());
double eps = 0.000001;
double difference = Math.Abs(numberA - numberB);
bool isEquals = false; ;
if (difference < eps)
{
isEquals = true;
} else if (difference == eps)
{
isEquals = false;
} else
{
isEquals = false;
}
Console.WriteLine(isEquals);
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-Extended-May-2017/Arrays and Methods - May 2017 Extended/12.LargerNumsInArray/Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _12.LergerNumsInArray
{
class Program
{
static void Main(string[] args)
{
double[] elements = Console.ReadLine().Split(' ').Select(double.Parse).ToArray();
// double[] elements = Console.ReadLine().Split(' ').Select(double.Parse).ToArray();
double specialNum = double.Parse(Console.ReadLine());
int counter = 0;
for (int cnt = 0; cnt < elements.Length; cnt++)
{
if (elements[cnt] > specialNum)
{
counter++;
}
}
Console.WriteLine(counter);
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-September-2017/List-Exercises/02.ChangeList/ChangeList.cs
namespace _02.ChangeList
{
using System;
using System.Linq;
using System.Collections.Generic;
public class ChangeList
{
public static void Main()
{
List<int> numbers = Console.ReadLine()
.Split(new char[] { ' ', ',', ';', ':', '.', '!', '(', ')', '"', '/', '[', ']', '\'', '\\' }, StringSplitOptions.RemoveEmptyEntries)
.Select(int.Parse)
.ToList();
string input = Console.ReadLine();
while (input != "Odd" || input != "Even")
{
var inputList = input
.Split(new char[] { ' ', ',', ';', ':', '.', '!', '(', ')', '"', '/', '[', ']', '\'', '\\' }, StringSplitOptions.RemoveEmptyEntries)
.ToList();
int index = 0;
int number;
if (inputList[0] == "Delete")
{
number = int.Parse(inputList[1]);
for (int i = 0; i < numbers.Count ; i++)
{
if (numbers[i] == number)
{
numbers.Remove(number);
i--;
}
}
}
if (inputList[0] == "Insert")
{
index = int.Parse(inputList[1]);
number = int.Parse(inputList[2]);
numbers.Insert(number, index);
}
if (inputList[0] == "Odd")
{
for (int i = 0; i < numbers.Count; i++)
{
if (numbers[i] % 2 != 0)
{
Console.Write(numbers[i] + " ");
}
}
Console.WriteLine();
break;
}
else if (inputList[0] == "Even")
{
for (int i = 0; i < numbers.Count; i++)
{
if (numbers[i] % 2 == 0)
{
Console.Write(numbers[i] + " ");
}
}
Console.WriteLine();
break;
}
input = Console.ReadLine();
}
}
}
}
<file_sep>/Software Technologies/Java Basic Syntax Exercises/src/ReverseCharacters.java
import java.util.Scanner;
public class ReverseCharacters {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String word = "";
for (int i = 0; i <= 2; i++) {
String input = scanner.nextLine();
word += input;
}
String reversedWord = new StringBuilder(word).reverse().toString();
System.out.println(reversedWord);
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-September-2017/ObjectsAndClasses/07.SalesReport/SalesReport.cs
namespace _07.SalesReport
{
using System;
using System.Collections.Generic;
using System.Linq;
public class SalesReport
{
public static void Main()
{
int n = int.Parse(Console.ReadLine());
var salesByTown = new SortedDictionary<string, double>();
for (int i = 0; i < n; i++)
{
Sale currentSale = new Sale().ReadSale();
string town = currentSale.Town;
double totalSum = currentSale.Price * currentSale.Quantity;
if (!salesByTown.ContainsKey(town))
{
salesByTown[town] = 0d;
}
salesByTown[town] += totalSum;
}
foreach (var town in salesByTown)
{
Console.WriteLine($"{town.Key} -> {town.Value:F2}");
}
}
}
public class Sale
{
public string Town { get; set; }
public string Product { get; set; }
public double Price { get; set; }
public double Quantity { get; set; }
public Sale ReadSale()
{
string[] input = Console.ReadLine().Split(' ').ToArray();
Sale sale = new Sale() { Town = input[0], Product = input[1],
Price = double.Parse(input[2]), Quantity = double.Parse(input[3]) };
return sale;
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-September-2017/FilesDirectoriesАndExceptions-Exercise/10.BookLibraryModification/BookLibraryModification.cs
namespace _10.BookLibraryModification
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.IO;
public class Books
{
public string Name { get; set; }
public DateTime ReleaseDate { get; set; }
}
class BookLibraryModification
{
static void Main(string[] args)
{
var inputDataLibrary = File.ReadAllLines("input.txt");
File.Delete("output.txt");
var books = new List<Books>();
foreach (var bookData in inputDataLibrary)
{
var input = bookData.Split(' ').ToList();
if (input.Count <= 1)
{
continue;
}
var book = new Books();
book.Name = input[0];
book.ReleaseDate = DateTime.ParseExact(input[3], "dd.MM.yyyy", CultureInfo.InvariantCulture);
books.Add(book);
}
var date = DateTime.ParseExact(inputDataLibrary.Last(), "dd.MM.yyyy", CultureInfo.InvariantCulture); //Input the date to check
foreach (var book in books.OrderBy(d => d.ReleaseDate).ThenBy(a => a.Name))
{
if (book.ReleaseDate > date)
{
File.AppendAllText("output.txt", $"{book.Name} -> " +
$"{book.ReleaseDate.ToString("dd.MM.yyyy", CultureInfo.InvariantCulture)}" + Environment.NewLine);
}
}
}
}
}<file_sep>/Programming Fundamentals/Programming-Fundamentals-September-2017/List-Lab/03.SumAdjacentEqualNumbers/SumAdjacentEqualNumbers.cs
namespace _03.SumAdjacentEqualNumbers
{
using System;
using System.Collections.Generic;
using System.Linq;
public class SumAdjacentEqualNumbers
{
public static void Main()
{
List<decimal> numbers = Console.ReadLine()
.Split(' ')
.Select(decimal.Parse)
.ToList();
List<decimal> result = new List<decimal>();
int index = 0;
decimal sum = 0;
bool isSum = true;
while (isSum)
{
isSum = false;
for (int i = 1; i < numbers.Count; i++)
{
if (numbers[i] == numbers[i - 1])
{
index = i - 1; //Index of element to be removed.
sum = numbers[i] + numbers[i - 1];
isSum = true;
break;
}
}
//If there is sum, else it will remove elements and broke the code.
if (isSum)
{
numbers.RemoveRange(index, 2); //Use index element.
numbers.Insert(index, sum); //Insert sum after remove element
}
}
Console.WriteLine(string.Join(" ", numbers));
}
}
}
<file_sep>/Programming Fundamentals/PF-Exams/PF-Exam-6January2017-Retake/02. SoftUni Karaoke/SoftUniKaraoke.cs
namespace _02.SoftUni_Karaoke
{
using System;
using System.Collections.Generic;
using System.Linq;
public class SoftUniKaraoke
{
public static void Main()
{
//Save karaoke names
var names = Console.ReadLine()
.Split(new string[] { ", ", }
, StringSplitOptions.RemoveEmptyEntries)
.ToList();
//Save songs for karaoke
var songs = Console.ReadLine()
.Split(new string[] { ", ", }
, StringSplitOptions.RemoveEmptyEntries)
.ToList();
string input = Console.ReadLine();
//Save for every single line, name, song/singer - name/ , int = number awards for name.
Dictionary<string, List<string>> awards = new Dictionary<string, List<string>>();
while (input != "dawn")
{
//Every new line - new Singer, song and award if have.
var onStage = input
.Split(new string[] { ", ", }
, StringSplitOptions.RemoveEmptyEntries);
var name = onStage[0];
var song = onStage[1];
var haveAward = onStage[2];
if (names.Contains(name) && songs.Contains(song))
{
if (!awards.ContainsKey(name))
{
awards.Add(name, new List<string>());
}
if (!awards[name].Contains(haveAward))
{
awards[name].Add(haveAward);
}
}
input = Console.ReadLine();
}
foreach (var item in awards.OrderByDescending(x => x.Value.Count).ThenBy(n => n.Key))
{
string singer = item.Key;
List<string> data = item.Value;
Console.WriteLine($"{singer}: {data.Count()} awards");
foreach (var award in data.OrderBy(n => n))
{
Console.WriteLine($"--{award}");
}
}
if (awards.Count == 0)
{
Console.WriteLine("No awards");
}
}
}
}<file_sep>/Programming Fundamentals/Programming-Fundamentals-September-2017/DictionariesLambdaAndLINQ-Exercise/05.HandsOfCards/HandsOfCards.cs
namespace _05.HandsOfCards
{
using System;
using System.Collections.Generic;
using System.Linq;
public class HandsOfCards
{
public static void Main()
{
var people = new Dictionary<string, Dictionary<string, int>>();
string input = Console.ReadLine();
while (input != "JOKER")
{
var inputLines = input
.Split(new char[] {':'}, StringSplitOptions.RemoveEmptyEntries)
.ToList();
var name = inputLines[0];
var cards = inputLines[1].Trim().Split(new string[] { ", "}, StringSplitOptions.RemoveEmptyEntries);
if(!people.ContainsKey(name))
{
people.Add(name, new Dictionary<string, int>());
AddPersonCards(people[name], cards);
}
else
{
AddPersonCards(people[name], cards);
}
input = Console.ReadLine();
}
foreach (var person in people)
{
Console.WriteLine("{0}: {1}", person.Key, person.Value.Values.Sum());
}
}
private static void AddPersonCards(Dictionary<string, int> person, string[] cards)
{
foreach (var card in cards)
{
if (!person.ContainsKey(card))
{
person.Add(card, GetCardValue(card));
}
}
}
private static int GetCardValue(string card)
{
int power = 0;
switch (card[0])
{
case '1':
power = 10;
break;
case '2':
power = 2;
break;
case '3':
power = 3;
break;
case '4':
power = 4;
break;
case '5':
power = 5;
break;
case '6':
power = 6;
break;
case '7':
power = 7;
break;
case '8':
power = 8;
break;
case '9':
power = 9;
break;
case 'J':
power = 11;
break;
case 'Q':
power = 12;
break;
case 'K':
power = 13;
break;
case 'A':
power = 14;
break;
}
switch (card[card.Length - 1])
{
case 'S':
power *= 4;
break;
case 'H':
power *= 3;
break;
case 'D':
power *= 2;
break;
case 'C':
power *= 1;
break;
}
return power;
}
}
}
<file_sep>/Software Technologies/Java Basic Syntax Exercises/src/FitStringIn20Chars.java
import java.util.Scanner;
public class FitStringIn20Chars {
public static String repeatString(String str, int counter) {
String text = "";
for (int i = 0; i < counter; i++) {
text += str;
}
return text;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
if (input.length() < 20) {
int astericsCounter = 20 - input.length();
System.out.print(input);
System.out.print(repeatString("*", astericsCounter));
} else if (input.length() > 20) {
System.out.println(input.substring(0, 20));
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-Extended-May-2017/Arrays and Methods - May 2017 Extended/16.ArraySymmetry/Program.cs
using System;
namespace _16.ArraySymmetry
{
class Program
{
static void Main(string[] args)
{
string[] firstArray = Console.ReadLine().Split(' ');
bool IsSymmetrical = false;
int n = firstArray.Length / 2;
for (int cnt = 0; cnt < n; cnt++)
{
if (firstArray[cnt] == firstArray[firstArray.Length - 1 - cnt])
{
IsSymmetrical = true;
} else
{
IsSymmetrical = false;
break;
}
}
if (IsSymmetrical)
{
Console.WriteLine("Yes");
} else
{
Console.WriteLine("No");
}
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-September-2017/MethodsDebuggingAndTroubleshootingCode/07.MathPower/Program.cs
namespace _07.MathPower
{
using System;
public class Program
{
static void Main()
{
double number = double.Parse(Console.ReadLine());
double powerNumber = double.Parse(Console.ReadLine());
double result = RaiseNumber(number, powerNumber);
Console.WriteLine($"{result}");
}
private static double RaiseNumber(double number, double power)
{
double resultNumber = Math.Pow(number, power);
return resultNumber;
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-September-2017/Arrays-Lab/09.ExtractMiddle1-2or3Elements/ExtractMiddle.cs
namespace _09.ExtractMiddle1_2or3Elements
{
using System;
using System.Collections.Generic;
using System.Linq;
public class ExtractMiddle
{
public static void Main()
{
int[] array = Console.ReadLine()
.Split(' ')
.Select(int.Parse)
.ToArray();
PrintExtractionResult(array);
}
public static void PrintExtractionResult (int[] array)
{
if (array.Length == 1)
{
SingleElementCase(array);
Console.WriteLine("{0} {1} {2}", '{', array[0], '}');
}
else if (array.Length > 1 && array.Length % 2 == 0)
{
Console.WriteLine("{0} {1} {2}", '{', string.Join(", ", EvenElementsInArray(array)), '}');
}
else if (array.Length > 1 && array.Length % 2 == 1)
{
Console.WriteLine("{0} {1} {2}", '{', string.Join(", ", OddElementsInArray(array)), '}');
}
}
public static int SingleElementCase(int[] array)
{
return array[0];
}
public static List<int> OddElementsInArray (int[] array)
{
List<int> results = new List<int>();
results.Add(array[array.Length / 2 - 1]);
results.Add(array[array.Length / 2]);
results.Add(array[array.Length / 2 + 1]);
return results;
}
public static List<int> EvenElementsInArray (int[] array)
{
List<int> results = new List<int>();
results.Add(array[array.Length / 2 - 1]);
results.Add(array[array.Length / 2]);
return results;
}
}
}
<file_sep>/Programming Fundamentals/PF-Exams/PF-Exam-26February2017/02.HornetComm/HornetComm.cs
namespace _02.HornetComm
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
public class HornetComm
{
public static void Main()
{ // 90/100 Points - Missing Case!
List<string> broadCasts = new List<string>();
List<string> messages = new List<string>();
string input = Console.ReadLine();
while (input != "Hornet is Green")
{
var tokens = input
.Split(new string[] { " <-> " }, StringSplitOptions.RemoveEmptyEntries)
.ToList();
string left = tokens[0];
string right = tokens[1];
if (left.All(char.IsDigit) && (right.All(char.IsLetterOrDigit)))
{
left = Reverse(left);
messages.Add(left + " -> " + right);
}
else if (!left.All(char.IsDigit) && (right.All(char.IsLetterOrDigit)))
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < right.Length; i++)
{
if (Char.IsUpper(right, i))
{
sb.Append(char.ToLower(right[i]));
}
else if (Char.IsLower(right, i))
{
sb.Append(char.ToUpper(right[i]));
}
else
{
sb.Append(right[i]);
}
}
broadCasts.Add(sb + " -> " + left);
}
input = Console.ReadLine();
}
Console.WriteLine("Broadcasts:");
if (broadCasts.Count > 0)
{
foreach (var broad in broadCasts)
{
Console.WriteLine(broad);
}
}
else
{
Console.WriteLine("None");
}
Console.WriteLine("Messages:");
if (messages.Count > 0)
{
foreach (var message in messages)
{
Console.WriteLine(message);
}
}
else
{
Console.WriteLine("None");
}
}
public static string Reverse(string str)
{
char[] reverse = str.ToCharArray();
Array.Reverse(reverse);
return new string(reverse);
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-Extended-May-2017/Arrays and Methods - May 2017 Extended/4. Phonebook/Program.cs
using System;
using System.Linq;
namespace _4.Phone
{
class Program
{
static void Main(string[] args)
{
string[] phoneNumbers = Console.ReadLine().Split();
string[] phoneNames = Console.ReadLine().Split();
string[] inputNames = Console.ReadLine().Split();
while (inputNames[0] != "done")
{
if (inputNames[0] == "call")
{
for (int cnt = 0; cnt < phoneNames.Length; cnt++)
{
if (inputNames[1] == phoneNames[cnt])
{
Console.WriteLine($"calling {phoneNumbers[cnt]}...");
string phoneNum = phoneNumbers[cnt];
int digitsSum = GetDigitsSum(phoneNum);
if (digitsSum % 2 == 1)
{
Console.WriteLine("no answer");
}
else
{
int minutes = digitsSum / 60;
int seconds = digitsSum % 60;
Console.WriteLine($"call ended. duration: {minutes:d2}:{seconds:d2}");
}
}
if (inputNames[1] == phoneNumbers[cnt])
{
Console.WriteLine($"calling {phoneNames[cnt]}...");
string phoneNum = phoneNumbers[cnt];
int digitsSum = GetDigitsSum(phoneNum);
if (digitsSum % 2 == 1)
{
Console.WriteLine("no answer");
}
else
{
int minutes = digitsSum / 60;
int seconds = digitsSum % 60;
Console.WriteLine($"call ended. duration: {minutes:d2}:{seconds:d2}");
}
}
}
}
if (inputNames[0] == "message")
{
for (int cnt = 0; cnt < phoneNames.Length; cnt++)
{
if (inputNames[1] == phoneNames[cnt])
{
Console.WriteLine($"sending sms to {phoneNumbers[cnt]}...");
string phoneNum = phoneNumbers[cnt];
int phoneNumSum = GetDigitsSum(phoneNum);
if (phoneNumSum % 2 == 0)
{
Console.WriteLine("meet me there");
}
else
{
Console.WriteLine("busy");
}
}
if (inputNames[1] == phoneNumbers[cnt])
{
Console.WriteLine($"sending sms to {phoneNames[cnt]}...");
string phoneNum = phoneNames[cnt];
int phoneNumSum = GetDigitsSum(phoneNum);
if (phoneNumSum % 2 == 0)
{
Console.WriteLine("meet me there");
}
else
{
Console.WriteLine("busy");
}
}
}
inputNames = Console.ReadLine().Split();
}
}
}
private static int GetDigitsSum(string phoneNumbera)
{
int getPhoneNumberSum = 0;
for (int indexCounter = 0; indexCounter < phoneNumbera.Length; indexCounter++)
{
if (phoneNumbera[indexCounter] >= 48 && phoneNumbera[indexCounter] <= 57)
{
getPhoneNumberSum += ((int)phoneNumbera[indexCounter] - 48);
}
}
return getPhoneNumberSum;
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-Extended-May-2017/List Lab Exercises - May 2017 Extended/2. Append List/Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
namespace _2.Append_List
{
class Program
{
static void Main(string[] args)
{
var values = Console.ReadLine().Split('|').ToList();
var result = new List<int>();
for (int cnt = 0; cnt < values.Count; cnt++)
{
var index = values[cnt].Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).Select(int.Parse).ToList();
index.Reverse();
foreach (var num in index)
{
result.Add(num);
}
}
result.Reverse();
Console.WriteLine(string.Join(" ", result));
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-September-2017/ConditionalStatementsAndLoops-Exercises/12.TestNumbers/Program.cs
namespace TestNumbers
{
using System;
public class Program
{
static void Main()
{
int n = Math.Abs(int.Parse(Console.ReadLine()));
int m = Math.Abs(int.Parse(Console.ReadLine()));
int stopNum = int.Parse(Console.ReadLine());
int counterCombinations = 0;
int sum = 0;
bool isStopNumber = false;
for (int i = n; i >= 1; i--)
{
for (int j = 1; j <= m; j++)
{
if (sum >= stopNum)
{
isStopNumber = true;
break;
}
else
{
counterCombinations++;
sum += 3 * (i * j);
}
}
if (sum >= stopNum)
{
isStopNumber = true;
break;
}
}
Console.WriteLine("{0} combinations", counterCombinations);
if (isStopNumber)
{
Console.WriteLine("Sum: {0} >= {1}", sum, stopNum);
} else
{
Console.WriteLine("Sum: {0}", sum);
}
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-September-2017/DataTypesAndVariables/02.CircleArea(12DigitsPrecision)/Program.cs
namespace _02.CircleArea_12DigitsPrecision_
{
using System;
public class Program
{
static void Main()
{
double radiusCircle = double.Parse(Console.ReadLine());
double areaCircle = radiusCircle * radiusCircle * Math.PI;
Console.WriteLine($"{areaCircle:F12}");
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-September-2017/MethodsDebuggingАndTroubleshootingCode-Exercises/11.GeometryCalculator/Program.cs
namespace _11.GeometryCalculator
{
using System;
public class Program
{
static void Main()
{
string figure = Console.ReadLine();
if (figure.Equals("triangle")) {
double side = double.Parse(Console.ReadLine());
double height = double.Parse(Console.ReadLine());
double output = GetTriangleArea(side, height);
Console.WriteLine($"{output:F2}");
}
else if (figure.Equals("square")) {
double side = double.Parse(Console.ReadLine());
double output = GetSquareArea(side);
Console.WriteLine($"{output:F2}");
}
else if (figure.Equals("rectangle")) {
double width = double.Parse(Console.ReadLine());
double height = double.Parse(Console.ReadLine());
double output = GetRectangleArea(width, height);
Console.WriteLine($"{output:F2}");
}
else if (figure.Equals("circle")) {
double radius = double.Parse(Console.ReadLine());
double output = GetCircleArea(radius);
Console.WriteLine($"{output:F2}");
}
}
static double GetTriangleArea (double side, double height)
{
double area = side * height / 2;
return area;
}
static double GetSquareArea (double side)
{
double area = side * side;
return area;
}
static double GetRectangleArea (double width, double height)
{
double area = width * height;
return area;
}
static double GetCircleArea (double radius)
{
double area = radius * radius * Math.PI;
return area;
}
}
}
<file_sep>/Programming Fundamentals/Programming-Fundamentals-September-2017/MethodsDebuggingAndTroubleshootingCode/03.PrintingTriangle/Program.cs
namespace _03.PrintingTriangle
{
using System;
public class Program
{
static void Main()
{
int number = int.Parse(Console.ReadLine());
for (int i = 0; i < number; i++)
{
PrintLine(1, i);
}
PrintLine(1, number);
for (int k = number - 1; k >= 0; k--)
{
PrintLine(1, k);
}
}
static private void PrintLine(int start, int stop)
{
for (int k = start; k <= stop; k++)
{
Console.Write(k + " ");
}
Console.WriteLine();
}
}
}
| eac54968d99302b9dd1a054a9ff7caa22423b51c | [
"HTML",
"JavaScript",
"C#",
"Java",
"PHP"
]
| 222 | PHP | skipter/Tech-Module | 4495ad89b566a54d0630fb841e6b07645017a16f | 24d071f9160704379761a34201cc6c69acf82000 |
refs/heads/master | <repo_name>ShobanaChakravarthy/netflix-build<file_sep>/src/components/Plans.js
import React, { useEffect, useState } from 'react'
import db from '../firebase'
import "./Plans.css"
function Plans() {
const[prods,setProds]=useState([])
useEffect(()=>{
db.collection('products')
.where('active','==',true)
.get().then(querySnapshot => {
const products = {};
querySnapshot.forEach(async productDoc => {
products[productDoc.id] = productDoc.data();
const priceSnap = await productDoc.ref.collection('prices').get();
priceSnap.docs.forEach(price=>{
products[productDoc.id].prices = {
priceId: price.id,
priceData : price.data()
}
})
})
setProds(products)
})
},[])
console.log(prods);
return (
<div className="plans">
{Object.entries(prods).map(([productId,productData])=>{
return(
<div className="plans__plan">
<div className="plans__info">
<h5>{productData.name}</h5>
<h6>{productData.description}</h6>
</div>
<button>Subscribe</button>
</div>
)
})}
</div>
)
}
export default Plans
<file_sep>/src/App.js
import React, { useEffect } from 'react';
import './App.css';
import HomeScreen from './components/HomeScreen';
import {BrowserRouter as Router, Route,Switch} from "react-router-dom"
import Login from './components/Login';
import {auth} from "./firebase"
import { useDispatch, useSelector } from 'react-redux';
import {login,logout, selectUser} from "./features/userSlice"
import Profile from './components/Profile';
function App() {
const user = useSelector(selectUser);
const dispatch=useDispatch()
useEffect(()=>{
const unsubscribe = auth.onAuthStateChanged(
(userAuth) => {
if(userAuth){
dispatch(login({
uid: userAuth.uid,
email: userAuth.email,
}))
}else{
dispatch(logout());
}
}
)
return unsubscribe;
},[dispatch])
return (
<div className="app">
<Router>
{!user ? (
<Login/>
) : (
<Switch>
<Route path="/profile">
<Profile/>
</Route>
<Route path="/">
<HomeScreen/>
</Route>
</Switch>
)}
</Router>
</div>
);
}
export default App;
<file_sep>/README.md
# Complete Netflix build with login,Movie Page,Payment using ReactJs, Firebase, Redux, Stripe
# Demo Link
https://netflix-build-67943.web.app
<file_sep>/src/firebase.js
import firebase from "firebase";
const firebaseApp = firebase.initializeApp({
apiKey: "<KEY>",
authDomain: "netflix-build-67943.firebaseapp.com",
projectId: "netflix-build-67943",
storageBucket: "netflix-build-67943.appspot.com",
messagingSenderId: "237758306117",
appId: "1:237758306117:web:7a65da98ead1538a59102c",
measurementId: "G-RKJQH3V04W"
});
// the firebaseApp which we initialized above, using that we can use it get firestore which will have all the data
// we are storing it in a variable called db and we are exporting it
const db=firebaseApp.firestore();
const auth=firebaseApp.auth();
export {auth};
export default db; | 8759c7d8aab195bf09922a1baf47d01008d42e30 | [
"JavaScript",
"Markdown"
]
| 4 | JavaScript | ShobanaChakravarthy/netflix-build | f6842bfae82cdfc1d40b2ea735d8513dca8b544c | d2146b5dfe3456d5b42699a55737c67d9e0da728 |
refs/heads/master | <repo_name>kenaszogara/umkm-webservice<file_sep>/routes/api.php
<?php
use Illuminate\Http\Request;
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
// CustomerAut endpoint
Route::post('/register', 'CustomerAuthController@register');
Route::post('/login', 'CustomerAuthController@login');
Route::get('/logout', 'CustomerAuthController@logout');
Route::get('/user', 'CustomerAuthController@getAuthUser');
// Customer endpoint
Route::get('/customers', 'CustomerController@index');
Route::post('/customers', 'CustomerController@store');
Route::get('/customers/{customer}', 'CustomerController@show');
Route::put('/customers/{customer}', 'CustomerController@update');
Route::delete('/customers/{customer}', 'CustomerController@destroy');
// Product endpoint
Route::get('/products', 'ProductController@index');
Route::post('/products', 'ProductController@store');
Route::get('/products/{product}', 'ProductController@show');
Route::put('/products/{product}', 'ProductController@update');
Route::delete('/products/{product}', 'ProductController@destory');
// Merchant endpoint
Route::get('/merchants', 'MerchantController@index');
Route::post('/merchants', 'MerchantController@store');
Route::get('/merchants/{merchant}', 'MerchantController@show');
Route::put('/merchants/{merchant}', 'MerchantController@update');
Route::delete('/merchants/{merchant}', 'MerchantController@destroy');
// Product Categories endpoint
Route::get('/categories', 'ProductCategoryController@index');
Route::get('/categories/{category}', 'ProductCategoryController@show');
// Bank endpoint
Route::get('/banks', 'BankController@index');
Route::get('/banks/{bank}', 'BankController@show');<file_sep>/database/seeds/ProductCategoryTableSeeder.php
<?php
use Illuminate\Database\Seeder;
class ProductCategoryTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
DB::table('product_categories')->insert([
[
'name' => 'BUKU',
],
[
'name' => 'ATK',
],
[
'name' => 'MAINAN',
],
[
'name' => 'CELANA',
],
[
'name' => 'BAJU',
],
]);
}
}
<file_sep>/database/migrations/2020_02_28_083345_create_merchant_bank_table.php
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
class CreateMerchantBankTable extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('merchant_bank', function(Blueprint $table)
{
$table->increments('id')->unsinged();
$table->string('name', 14);
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('merchant_bank');
}
}
<file_sep>/app/Http/Controllers/ProductController.php
<?php
namespace App\Http\Controllers;
use App\Product;
use App\Http\Resources\ProductResource;
use Illuminate\Http\Request;
use Ramsey\Uuid\Uuid;
class ProductController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$products = Product::with(['category' , 'merchant'])->paginate(10);
return ProductResource::collection($products);
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$uuid3 = Uuid::uuid4();
$product = Product::create([
'uuid' => $uuid3,
'name' => $request->name,
'price' => $request->price,
'description' => $request->description,
'merchant_id' => $request->merchant_id,
'category_code' => $request->category_code,
]);
return new ProductResource($product);
}
/**
* Display the specified resource.
*
* @param \App\Product $product
* @return \Illuminate\Http\Response
*/
public function show(Product $product)
{
return new ProductResource($product);
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param \App\Product $product
* @return \Illuminate\Http\Response
*/
public function update(Request $request, Product $product)
{
// check if product belong to category
if ($request->category()->id !== $product->category_id) {
return response()->json([
'error' => 'Product does not belong to ' . $request->category()->id . ' category.'],
403
);
}
// check if product belong to merchant
if ($request->merchant()->id !== $product->merchant_id) {
return response()->json([
'error' => 'Product does not belong to ' . $request->merchant()->id . ' merchant.'],
403
);
}
$product->edit($request->only([
'name',
'price',
'description',
'category'
]));
return new ProductResource($product);
}
/**
* Remove the specified resource from storage.
*
* @param \App\Product $product
* @return \Illuminate\Http\Response
*/
public function destroy(Product $product)
{
$product->delete();
return response()->json(null, 204);
}
}
<file_sep>/database/seeds/MerchantTableSeeder.php
<?php
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Faker\Factory;
use Carbon\Carbon;
class MerchantTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run(Factory $factory)
{
$faker = $factory->create();
DB::table('merchants')->insert([
[
'uuid' => $faker->uuid,
'name' => '<NAME>',
'phone_number' => '1234567890',
'email' => '<EMAIL>',
'address' => 'jalan merchant',
'bank_id' => 1,
'created_at' => Carbon::now()->format('Y-m-d H:i:s'),
'updated_at' => Carbon::now()->format('Y-m-d H:i:s')
],
[
'uuid' => $faker->uuid,
'name' => '<NAME>',
'phone_number' => '1234567890',
'email' => '<EMAIL>',
'address' => 'jalan merchant',
'bank_id' => 3,
'created_at' => Carbon::now()->format('Y-m-d H:i:s'),
'updated_at' => Carbon::now()->format('Y-m-d H:i:s')
],
[
'uuid' => $faker->uuid,
'name' => '<NAME>',
'phone_number' => '1234567890',
'email' => '<EMAIL>',
'address' => 'jalan merchant',
'bank_id' => 2,
'created_at' => Carbon::now()->format('Y-m-d H:i:s'),
'updated_at' => Carbon::now()->format('Y-m-d H:i:s')
],
]);
}
}
<file_sep>/app/Merchant.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Ramsey\Uuid\Uuid;
class Merchant extends Model
{
protected $primaryKey = 'uuid';
public $incrementing = false;
// description can be empty
protected $attributes = [
'description' => '',
'profile' => ''
];
protected $fillable = [
'uuid',
'name',
'phone',
'email',
'address',
'bank_id',
'description',
'profile'
];
public function products() {
return $this->hasMany('App\Product');
}
// ...->hasOne(
// model,
// column_name_in_bank_table_containing_the_reference_to_merchant,
// column_name_of_merchant_containing_identifier
// )
public function bank() {
return $this->hasOne('App\Bank', 'id', 'bank_id');
}
public static function boot()
{
parent::boot();
self::creating(function ($model) {
$model->uuid = (string) Uuid::uuid4();
});
}
}
<file_sep>/database/migrations/2020_02_28_083345_create_pending_merchants_table.php
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
class CreatePendingMerchantsTable extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('pending_merchants', function(Blueprint $table)
{
$table->uuid('uuid')->primary();
$table->string('name', 30);
$table->string('phone_number');
$table->string('email', 30);
$table->string('address', 50);
$table->uuid('user_uuid');
$table->string('description')->nullable();
$table->string('profile', 100)->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('pending_merchants');
}
}
<file_sep>/app/Customer.php
<?php
namespace App;
use Illuminate\Foundation\Auth\Customer as Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Tymon\JWTAuth\Contracts\JWTSubject;
use Ramsey\Uuid\Uuid;
class Customer extends Authenticatable implements JWTSubject
{
protected $primaryKey = 'uuid';
protected $guarded = ['uuid'];
public $incrementing = false;
// default value for table
protected $attributes = [
'profile' => '',
];
// which column can be filled from form
protected $fillable = [
'name',
'phone_number',
'password',
'email',
'address',
'gender',
'birth_date'
];
protected $hidden = [
'password'
];
public function getAuthPassword()
{
return $this->password;
}
public static function boot()
{
parent::boot();
self::creating(function ($model) {
$model->uuid = (string) Uuid::uuid4();
});
}
public function getJWTIdentifier()
{
return $this->getKey();
}
public function getJWTCustomClaims()
{
return [];
}
}
<file_sep>/database/seeds/BankTableSeeder.php
<?php
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
class BankTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
DB::table('merchant_bank')->insert([
[
'name' => 'BCA',
],
[
'name' => 'MANDIRI',
],
[
'name' => 'BNI',
],
[
'name' => 'BRI',
],
[
'name' => 'NIAGA',
],
[
'name' => 'HSBC',
],
]);
}
}
<file_sep>/app/Product.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Ramsey\Uuid\Uuid;
class Product extends Model
{
protected $primaryKey = 'uuid';
public $incrementing = false;
// description can be empty
protected $attributes = [
'description' => ''
];
protected $fillable = [
'uuid',
'name',
'price',
'description',
'merchant_uuid',
'category_id'
];
public function merchant() {
return $this->hasOne('App\Merchant', 'uuid', 'merchant_uuid');
}
public function category() {
return $this->hasOne('App\ProductCategory', 'id', 'category_id');
}
public static function boot()
{
parent::boot();
self::creating(function ($model) {
$model->uuid = (string) Uuid::uuid4();
});
}
}
<file_sep>/app/Http/Controllers/MerchantController.php
<?php
namespace App\Http\Controllers;
use App\Merchant;
use App\Http\Resources\MerchantResource;
use Illuminate\Http\Request;
use Ramsey\Uuid\Uuid;
class MerchantController extends Controller
{
public function __construct()
{
$this->middleware('auth:api')->except(['index', 'show']);
}
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$merchants = Merchant::with('bank')->paginate(10);
return MerchantResource::collection($merchants);
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$uuid3 = Uuid::uuid4();
$merchant = Merchant::create([
'uuid' => (string)$uuid3,
'name' => $request->name,
'phone' => $request->phone,
'email' => $request->email,
'address' => $request->address,
'bank_code' => $request->bank_code,
'description' => $request->description,
'profile' => $request->profile,
]);
return new MerchantResource($merchant);
}
/**
* Display the specified resource.
*
* @param \App\Merchant $merchant
* @return \Illuminate\Http\Response
*/
public function show(Merchant $merchant)
{
return new MerchantResource($merchant);
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param \App\Merchant $merchant
* @return \Illuminate\Http\Response
*/
public function update(Request $request, Merchant $merchant)
{
$merchant->edit($request->only([
'name',
'phone',
'email',
'address',
'bank',
'description',
'user',
'profile'
]));
return response()->json($merchant, 201);
}
/**
* Remove the specified resource from storage.
*
* @param \App\Merchant $merchant
* @return \Illuminate\Http\Response
*/
public function destroy(Merchant $merchant)
{
$merchant->delete();
return response()->json(null, 204);
}
}
<file_sep>/app/Http/Controllers/ProductCategoryController.php
<?php
namespace App\Http\Controllers;
use App\ProductCategory;
use App\Http\Resources\ProductCategoryResource;
use Illuminate\Http\Request;
class ProductCategoryController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$categories = ProductCategory::all();
return ProductCategoryResource::collection($categories);
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show(ProductCategory $category)
{
return ProductCategory::find($category);
}
}
| 58f4408ab33c1576203948de15af1c09be5dc478 | [
"PHP"
]
| 12 | PHP | kenaszogara/umkm-webservice | 29ec5bcc88964a29b5ac37904f5b453854e14dfe | 5706b1405accec477fb3cc0b83c768d7cfafa73d |
refs/heads/master | <repo_name>ncharlton02/mini<file_sep>/src/tui/mod.rs
extern crate cannon;
mod input;
use std::collections::VecDeque;
use self::input::*;
use self::cannon::*;
use self::cannon::input::Key;
///Includes the bar
const INPUT_BAR_HEIGHT: i16 = 4;
pub enum TuiEvent{
Quit,
SendMsg(String)
}
#[derive(Clone)]
struct ConsolePosition{
x: i16,
y: i16
}
pub struct Tui{
console: Console,
prev_size: ConsoleSize,
input: InputSystem,
output_line: i16,
output_lines: VecDeque<String>,
input_chars: Vec<char>,
cursor_pos: ConsolePosition
}
impl Tui{
pub fn draw_input_bar(&mut self){
let size = self.console.get_console_size();
let s: String = self.input_chars.clone().into_iter().collect();
let pos = self.cursor_pos.clone();
self.console.set_color(color::DARK_BLUE, color::DARK_BLUE);
rect(&mut self.console, 0, size.height - INPUT_BAR_HEIGHT,
size.width + 1, size.height - INPUT_BAR_HEIGHT);
self.calc_input_position();
self.console.set_color(color::BLACK, color::LIGHT_GRAY);
rect(&mut self.console, 0, size.height - INPUT_BAR_HEIGHT + 1,
size.width + 1, size.height);
self.calc_input_position();
self.reset_position();
//self.add_message(&s);
self.console.write(&s);
self.cursor_pos = pos;
self.reset_position();
}
fn calc_input_position(&mut self){
let size = self.console.get_console_size();
self.cursor_pos = ConsolePosition{x: 0, y: size.height - INPUT_BAR_HEIGHT + 1};
}
pub fn add_message(&mut self, string: &str){
self.output_lines.push_back(string.into());
let mut output_line = self.output_line + 1 + string_to_char_length(&string.to_string()) as i16 /
self.console.get_console_size().width;
while output_line > self.output_area_height(){
let s = self.output_lines.pop_front();
output_line -= 1 + string_to_char_length(&s.unwrap()) as i16 /
self.console.get_console_size().width;
}
self.output_line = output_line;
self.draw_output(true);
}
fn output_area_height(&self) -> i16 {
let size = self.console.get_console_size();
size.height - INPUT_BAR_HEIGHT
}
fn write_message(&mut self, string: &str){
self.console.set_cursor_position(0, self.output_line);
self.output_line += 1 + string_to_char_length(&string.to_string()) as i16 /
self.console.get_console_size().width;
self.console.set_color(color::BLACK, color::LIGHT_GRAY);
self.console.write(string);
self.reset_position();
}
pub fn draw_output(&mut self, redraw_background: bool){
self.console.set_color(color::BLACK, color::LIGHT_GRAY);
self.console.set_cursor_position(0, 0);
self.output_line = 0;
if redraw_background{
let size = self.console.get_console_size();
rect(&mut self.console, 0, 0, size.width + 1, size.height - INPUT_BAR_HEIGHT -1);
}
for line in &self.output_lines.clone() {
self.write_message(line);
}
}
pub fn redraw(&mut self){
self.console.set_color(color::BLACK, color::LIGHT_GRAY);
self.console.clear_screen();
self.console.set_cursor_position(0, 0);
self.draw_output(false);
self.draw_input_bar();
self.console.set_color(color::BLACK, color::LIGHT_GRAY);
self.reset_position();
}
pub fn reset_position(&self){
self.console.set_cursor_position(self.cursor_pos.x, self.cursor_pos.y);
}
fn check_cursor_pos(&mut self){
if self.cursor_pos.x < 0{
self.cursor_pos.x = 0;
}
if self.cursor_pos.x > self.input_chars.len() as i16{
self.cursor_pos.x = self.input_chars.len() as i16;
}
}
pub fn move_cursor(&mut self, x: i16, y: i16){
let pos = self.cursor_pos.clone();
self.cursor_pos = ConsolePosition{x: pos.x + x, y: pos.y + y}
}
pub fn update(&mut self) -> Option<TuiEvent>{
if self.prev_size != self.console.get_console_size(){
self.redraw();
self.prev_size = self.console.get_console_size();
}
if let Some(key) = self.input.poll(){
return match key {
Key::Escape => Some(TuiEvent::Quit),
Key::Char(c) => {
if self.input_chars.len() >= self.cursor_pos.x as usize
&& self.cursor_pos.x >= 0{
self.input_chars.insert(self.cursor_pos.x as usize, c);
self.move_cursor(1, 0);
}
self.draw_input_bar();
None
},
Key::Num(n) => {
self.input_chars.push((n + 48) as char);
self.draw_input_bar();
self.move_cursor(1, 0);
self.reset_position();
None
},
Key::Enter => {
let msg: String = self.input_chars.clone().into_iter().collect();
self.add_message(&format!("You: {}", &msg));
self.input_chars = Vec::new();
self.calc_input_position();
self.draw_input_bar();
Some(TuiEvent::SendMsg(msg))
},
Key::Backspace => {
if self.input_chars.len() > self.cursor_pos.x as usize - 1
&& self.cursor_pos.x - 1 >= 0{
self.move_cursor(-1, 0);
self.input_chars.remove(self.cursor_pos.x as usize);
}
self.draw_input_bar();
None
},
Key::Left => {
self.move_cursor(-1, 0);
self.check_cursor_pos();
self.reset_position();
None
}
Key::Right => {
self.move_cursor(1, 0);
self.check_cursor_pos();
self.reset_position();
None
}
_ => None
};
}
None
}
}
fn string_to_char_length(input: &String) -> usize{
input.chars().count()
}
pub fn init() -> Tui{
let mut console = Console::new();
let size = console.get_console_size();
console.set_should_cls(true);
let mut tui = Tui {
output_line: 0,
prev_size: size,
console: console,
input: input::init(),
input_chars: Vec::with_capacity(5),
output_lines: VecDeque::new(),
cursor_pos: ConsolePosition{x:0, y:0}
};
tui.calc_input_position();
tui.redraw();
tui
}
fn rect(console: &mut Console, x1: i16, y1: i16, x2: i16, y2: i16){
let width = x2 - x1;
let height = y2 - y1;
for x in 0..width + 1 {
for y in 0..height + 1{
console.write_character(x +x1, y + y1, 32);
}
}
}
<file_sep>/README.md
# mini
A Version of tiny for windows
<file_sep>/src/tui/input.rs
extern crate cannon;
use self::cannon::{Console};
use self::cannon::input::*;
use std::thread;
use std::sync::mpsc::{channel, Receiver};
pub struct InputSystem{
rx: Receiver<Key>
}
impl InputSystem{
pub fn poll(&self) -> Option<Key>{
match self.rx.try_recv() {
Err(_) => None,
Ok(k) => Some(k)
}
}
}
pub fn init() -> InputSystem{
let (tx, rx) = channel();
thread::spawn(move ||{
let mut console = Console::new();
console.set_should_cls(false);
loop{
let input = console.poll_input();
if let Some(i) = input{
let key_opt = match i.EventType{
1 => to_key(i.Event),
_ => None,
};
if let Some(key) = key_opt{
tx.send(key).unwrap_or_else(|err| {
panic!("Input System Channel Error: {}", err);
});
}
}
}
});
InputSystem {rx: rx}
}
fn to_key(event: [u32;4]) -> Option<Key>{
if event[0] == 0{
return None;
}
num_to_key(event[2])
}
<file_sep>/src/main.rs
extern crate irc;
mod tui;
use std::sync::Arc;
use std::sync::mpsc::channel;
use std::thread;
use std::default::Default;
use irc::client::prelude::*;
use self::tui::TuiEvent;
fn main() {
let config = create_config(
"program",
"irc.mozilla.org",
vec!["#mini, #rust".to_string()],
);
let data = Arc::new(IrcServer::from_config(config).unwrap());
let server = data.clone();
let (tx, rx) = channel();
let mut tui = tui::init();
server.identify().unwrap_or_else(|err| {
panic!("Error: {}", err);
});
thread::spawn(move || {
server.for_each_incoming(|message| {
tx.send(message).unwrap_or_else(|err| {
panic!("Error: {}", err);
});
})
.unwrap_or_else(|err| {
panic!("Error: {}", err);
});
});
let server = data.clone();
'main: loop {
if let Some(event) = tui.update(){
match event{
TuiEvent::Quit => break 'main,
TuiEvent::SendMsg(string) => {
server.send_privmsg("#mini", &string);
()
}
_ => ()
}
};
//Thread that draws and sends messages
let message = match rx.try_recv() {
Err(_) => None,
Ok(c) => Some(c),
};
if let Some(m) = message {
match m.command {
Command::PRIVMSG(ref target, ref msg) => {
tui.add_message(&format!("{}: {}", target, msg));
}
_ => (),
}
}
}
}
fn create_config(nickname: &str, server: &str, channels: Vec<String>) -> Config {
Config {
nickname: Some(nickname.to_owned()),
server: Some(server.to_owned()),
channels: Some(channels),
..Default::default()
}
}
<file_sep>/Cargo.toml
[package]
name = "mini"
version = "0.1.0"
authors = ["DevOrc <<EMAIL>>"]
[dependencies]
irc = "0.12.3"
cannon = {path = "tui"}
| 6070b0589f57fbf68e9cb063e9a85d49de5fc795 | [
"Markdown",
"Rust",
"TOML"
]
| 5 | Rust | ncharlton02/mini | 93b0a5b89aa32457c9f045d386fbefab1443f552 | 69c50f83d73cb2949eb138726b2f5aed4598f5b9 |
refs/heads/master | <file_sep>import rank
import re
class Search:
def __init__(self, list_of_files):
self.filenames = list_of_files
self.index = rank.rank(self.filenames)
self.invertedIndex = self.index.totalIndex
self.regularIndex = self.index.regdex
def make_vectors(self, documents):
vectors = {}
for doc in documents:
docVector = [0]*len(self.index.getUniques())
for ind, term in enumerate(self.index.getUniques()):
docVector[ind] = self.index.generateScore(term, doc)
vectors[doc] = docVector
return vectors
def queryFreq(self, term, query):
count = 0
for word in query.split():
if word == term:
count += 1
return count
def termfreq(self, terms, query):
temp = [0]*len(terms)
for i,term in enumerate(terms):
temp[i] = self.queryFreq(term, query)
return temp
def dotProduct(self, doc1, doc2):
if len(doc1) != len(doc2):
return 0
return sum([x*y for x,y in zip(doc1, doc2)])
def query_vec(self, query):
pattern = re.compile('[\W_]+')
query = pattern.sub(' ',query)
queryls = query.split()
queryVec = [0]*len(queryls)
index = 0
for ind, word in enumerate(queryls):
queryVec[index] = self.queryFreq(word, query)
index += 1
queryidf = [self.index.idf[word] for word in self.index.getUniques()]
magnitude = pow(sum(map(lambda x: x**2, queryVec)),.5)
freq = self.termfreq(self.index.getUniques(), query)
tf = [x/magnitude for x in freq]
final = [tf[i]*queryidf[i] for i in range(len(self.index.getUniques()))]
return final
def rankResults(self, resultDocs, query):
vectors = self.make_vectors(resultDocs)
queryVec = self.query_vec(query)
results = [[self.dotProduct(vectors[result], queryVec), result] for result in resultDocs]
results.sort(key=lambda x: x[0])
results = [x[1] for x in results]
return results
def one_word_search(self, word):
pattern = re.compile('[\W_]+')
word = pattern.sub(' ',word)
if word in self.invertedIndex.keys():
return self.rankResults([filename for filename in self.invertedIndex[word].keys()], word)
else:
return []
def free_text_search(self, string):
pattern = re.compile('[\W_]+')
string = pattern.sub(' ',string)
result = []
for word in string.split():
result += self.one_word_query(word)
return self.rankResults(list(set(result)), string)
def phrase_search(self, string):
pattern = re.compile('[\W_]+')
string = pattern.sub(' ',string)
listOfLists, result = [],[]
for word in string.split():
listOfLists.append(self.one_word_query(word))
setted = set(listOfLists[0]).intersection(*listOfLists)
for filename in setted:
temp = []
for word in string.split():
temp.append(self.invertedIndex[word][filename][:])
for i in range(len(temp)):
for ind in range(len(temp[i])):
temp[i][ind] -= i
if set(temp[0]).intersection(*temp):
result.append(filename)
return self.rankResults(result, string)
| f2f8904ef4c37aa835fc08d65407d65159942c13 | [
"Python"
]
| 1 | Python | ykl7/Top-Search | ab5f2230755f48e1b9aebe187c5ed4fd477bb234 | cfab8e713e1a5fe5a896e5f6f817e728d0263366 |
refs/heads/master | <file_sep>package com.tangge.newb.SeleniumImcoo;
import java.util.Date;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.Keys;
import org.openqa.selenium.support.ui.Select;
/**
*
承运商发布子运单
* */
public class Carrier_ChildrenBid {
public static void main(String[] args) throws Exception{
currency cy = new currency();
cy.Carrier_Login();
Carrier_ChildrenBid cb = new Carrier_ChildrenBid();
cb.ReleaseBid(cy);
}
public void ReleaseBid(currency cy) throws Exception {
cy.getDriver().findElement(By.className("nav-label")).click();
Thread.sleep(2000);
cy.getDriver().findElement(By.linkText("运单处理")).click();
cy.getDriver().switchTo().frame("iframe");
cy.getDriver().findElement(By.xpath("/html/body/div[2]/ul/li[2]/a")).click();
cy.getDriver().findElement(By.className("form-control")).sendKeys("测试物品脚本444");
cy.getDriver().findElement(By.id("search")).click();
Thread.sleep(2000);
cy.getDriver().findElement(By.linkText("发布子运单")).click();
cy.getDriver().switchTo().frame("layui-layer-iframe1");
Select sel = new Select(cy.getDriver().findElement(By.name("carLength")));
Thread.sleep(2000);
sel.selectByIndex(9);
Select sct = new Select(cy.getDriver().findElement(By.name("carType")));
Thread.sleep(2000);
sct.selectByVisibleText("高低板");
Thread.sleep(2000);
cy.getDriver().findElement(By.name("expectedLoadMoney")).sendKeys("6300");
Thread.sleep(2000);
cy.getDriver().findElement(By.name("customizeOrderNo")).sendKeys(DateFormatUtils.format(new Date(), "yyyyMMddHHmmss"));
Select sec = new Select(cy.getDriver().findElement(By.name("issueType")));
Thread.sleep(2000);
sec.selectByVisibleText("网上招标");
String js = "document.getElementsByName('bidValidTime')[0].removeAttribute('readonly')";
((JavascriptExecutor)cy.getDriver()).executeScript(js);
cy.getDriver().findElement(By.name("bidValidTime")).sendKeys("2019-12-31 16:16:16");
cy.getDriver().findElement(By.name("remarks")).sendKeys("这是测试脚本的备注模板,谢谢!!!");
Thread.sleep(2000);
cy.getDriver().findElement(By.cssSelector("#save")).click();
cy.getDriver().findElement(By.id("layui-layer1")).click();
//cy.getDriver().navigate().refresh();
cy.getAction().sendKeys(Keys.F5);
}
}
<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>
<groupId>com.tangge.newb</groupId>
<artifactId>SeleniumImcoo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>SeleniumImcoo</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-java -->
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>3.11.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/net.sourceforge.tess4j/用tess4j的方式来识别图像,得到验证码 -->
<dependency>
<groupId>net.sourceforge.tess4j</groupId>
<artifactId>tess4j</artifactId>
<version>3.2.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.2</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.8.1</version>
</dependency>
<!-- sikulix上传图片-->
<dependency>
<groupId>com.sikulix</groupId>
<artifactId>sikulixapi</artifactId>
<version>1.1.0</version>
</dependency>
</dependencies>
</project>
<file_sep>package com.tangge.newb.SeleniumImcoo;
import org.openqa.selenium.By;
/**
*货主选标
*/
public class Shipper_SelectBid {
public static void main(String[] args) throws Exception{
// TODO Auto-generated method stub
Jzt2_Shipper js = new Jzt2_Shipper();
js.Login();
Shipper_SelectBid ssb = new Shipper_SelectBid();
ssb.Select_Bid(js);
}
@SuppressWarnings("static-access")//告诉编译器忽略指定的警告,不用在编译完成后出现警告信息。
public void Select_Bid(Jzt2_Shipper js) {
//运单管理
js.driver.findElement(By.className("nav-label")).click();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//运单处理
js.driver.findElement(By.xpath("//*[@id=\"side-menu\"]/li[1]/ul/li[2]/a")).click();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
js.driver.switchTo().frame("iframe");
js.driver.findElement(By.name("search_like_projectName")).sendKeys("测试物品脚本444");//根据项目名称搜索
js.driver.findElement(By.id("search")).click();//搜索
js.driver.findElement(By.xpath("/html/body/div[4]/div/div[3]/div[3]/div/table/tbody/tr[2]/td[4]/a[2]")).click();
js.driver.switchTo().frame("layui-layer-iframe1");
js.driver.findElement(By.className("op-choose")).click();//选中
js.driver.findElement(By.className("layui-layer-btn0")).click();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
js.driver.switchTo().frame("J_Form");
js.driver.findElement(By.id("btnOK")).click();
}
}
<file_sep>package com.tangge.newb.SeleniumImcoo;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.datatransfer.StringSelection;
import java.awt.event.KeyEvent;
import java.util.Date;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.Select;
public class Jzt2_Shipper {
static WebDriver driver;
static Select select;
static WebElement element;
static Actions action;
/**
*货主发布运单
*/
public void Login() throws Exception {
System.setProperty("webdriver.chrome.driver", "D:\\chromedowlond\\chromedriver_win32\\chromedriver.exe");
driver = new ChromeDriver();
driver.get("http://172.16.58.3:8086/jzt2_web/login.jsp");
Thread.sleep(3000);
driver.manage().window().maximize();
select = new Select(driver.findElement(By.name("userType")));
select.selectByVisibleText("货主");
driver.findElement(By.name("username")).sendKeys("<PASSWORD>");
driver.findElement(By.name("password")).sendKeys("<PASSWORD>");
Thread.sleep(7000);//预留等待时间输入验证码
driver.findElement(By.className("btn")).click();//登录
}
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
Jzt2_Shipper jspe =new Jzt2_Shipper();
jspe.Login();
//运单管理
driver.findElement(By.className("nav-label")).click();
Thread.sleep(2000);
//发布货源
driver.findElement(By.xpath("//*[@id=\"side-menu\"]/li[1]/ul/li[1]/a")).click();
Thread.sleep(1000);
driver.switchTo().frame("iframe");//iframe切换
/*
* 基本信息
*
*/
//项目名称
driver.findElement(By.xpath("//*[@id=\"J_Form\"]/div[1]/div[1]/div[2]/table/tbody/tr[1]/td[2]/input")).sendKeys("测试物品脚本444");
Thread.sleep(1000);
//货主单号
driver.findElement(By.xpath("//*[@id=\"J_Form\"]/div[1]/div[1]/div[2]/table/tbody/tr[1]/td[4]/input")).sendKeys(DateFormatUtils.format(new Date(), "yyyyMMddHHmmss"));
//运输模式
select = new Select(driver.findElement(By.name("transportMode")));
select.selectByVisibleText("整车");
//预期运费
driver.findElement(By.name("expectedLoadMoney")).sendKeys("6300");
//发布类型
select = new Select(driver.findElement(By.name("issueType")));
select.selectByVisibleText("网上招标");
//投标截止日期【移除readonly的属性】
String js = "document.getElementById('bidValidTime').removeAttribute('readonly')";
((JavascriptExecutor)driver).executeScript(js);//将driver强制转换为JavascriptExecutor类型
driver.findElement(By.id("bidValidTime")).sendKeys("2018-12-29 15:32:00");
/*
* 发货人信息
*
*/
driver.findElement(By.xpath("//*[@id=\"chooseSenderAddress\"]/a/i")).click();//发货单位输入框的logo标签
driver.switchTo().frame("layui-layer-iframe1");//iframe切换
driver.findElement(By.xpath("//*[@id=\"b8e5fffa-f79c-11e8-bb03-00163e04a258\"]")).click();//选择发货单位信息
driver.findElement(By.id("btnOK")).click();
driver.switchTo().parentFrame();
//发货日期
String str = "document.getElementById('sendDate').removeAttribute('readonly')";
((JavascriptExecutor)driver).executeScript(str);//将driver强制转换为JavascriptExecutor类型
driver.findElement(By.xpath("//*[@id=\"sendDate\"]")).sendKeys("2018-12-31");
//发货时间
select = new Select(driver.findElement(By.id("sendTimeHour")));
select.selectByVisibleText("08:00-10:00");
/*
* 货物信息
*
*/
//货物名称
driver.findElement(By.name("loadName")).sendKeys("斜对面公司有个妹子不错");
driver.findElement(By.name("singleSize")).sendKeys("20*10*5");
select = new Select(driver.findElement(By.name("packageType")));
select.selectByVisibleText("木箱");//包装形式
//总吨量
driver.findElement(By.name("loadWeight")).sendKeys("50");
//总体积
driver.findElement(By.name("loadVolume")).sendKeys("200");
//件数
driver.findElement(By.name("loadCount")).sendKeys("2000");
//货物清单
StringSelection sel = new StringSelection("C:\\Users\\Administrator\\Desktop\\CIVIC.jpg");//指定图片的路径
driver.findElement(By.xpath("//*[@id=\"selectAttachment\"]")).click();//【点击上传附件】
//把图片文件路径复制到剪贴板
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(sel,null);
// 新建一个Robot类的对象
Robot robot = new Robot();
Thread.sleep(1000);
// 按下回车
robot.keyPress(KeyEvent.VK_ENTER);
// 释放回车
robot.keyRelease(KeyEvent.VK_ENTER);
// 按下 CTRL+V
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_V);
// 释放 CTRL+V
robot.keyRelease(KeyEvent.VK_CONTROL);
robot.keyRelease(KeyEvent.VK_V);
Thread.sleep(1000);
// 点击回车 Enter
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
//上传货物照片
driver.findElement(By.xpath("//*[@id=\"selectImage\"]")).click();
Thread.sleep(3000);
//Java 的Runtime 模块的getruntime.exec()方法可以调用exe 程序并执行
Runtime exe = Runtime.getRuntime();
String strup = "F:\\Image\\upFile.exe";
exe.exec(strup);
Thread.sleep(2000);
/*
* 收货人信息
*
*/
//发货单位
driver.findElement(By.xpath("//*[@id=\"receiverOrderAddress\"]/tbody/tr[1]/td[2]/div/input")).sendKeys("安徽稳石网络科技有限公司");
//联系人
driver.findElement(By.xpath("//*[@id=\"receiverOrderAddress\"]/tbody/tr[1]/td[4]/input")).sendKeys("汤老板");
//联系电话
driver.findElement(By.xpath("//*[@id=\"receiverOrderAddress\"]/tbody/tr[1]/td[6]/input")).sendKeys("15349873898");
//收货地
driver.findElement(By.xpath("//*[@id=\"receiverOrderAddress\"]/tbody/tr[2]/td[2]/div/span")).click();
//driver.switchTo().parentFrame();
action = new Actions(driver);
WebElement province = driver.findElement(By.xpath("//*[@id=\"receiverOrderAddress\"]/tbody/tr[2]/td[2]/div/div/div/div[2]/div[1]/dl[1]/dd/a[1]"));
action.click(province).perform();
action = new Actions(driver);
WebElement city = driver.findElement(By.xpath("//*[@id=\"receiverOrderAddress\"]/tbody/tr[2]/td[2]/div/div/div/div[2]/div[2]/dl/dd/a[13]"));
action.click(city).perform();
action = new Actions(driver);
WebElement district = driver.findElement(By.xpath("//*[@id=\"receiverOrderAddress\"]/tbody/tr[2]/td[2]/div/div/div/div[2]/div[3]/dl/dd/a[1]"));
action.click(district).perform();
//详细地址
driver.findElement(By.name("receiveDetailAddress")).sendKeys("东城花园1206");
//收货日期
String verTime = "document.getElementsByName('receiverTime')[0].removeAttribute('readonly')";//重点:name不唯一,需要加索引标注
((JavascriptExecutor)driver).executeScript(verTime);//将driver强制转换为JavascriptExecutor类型
driver.findElement(By.xpath("//*[@id=\"receiverOrderAddress\"]/tbody/tr[3]/td[2]/div/input")).sendKeys("2019-12-31");
/*
* 车辆信息
*
*/
select = new Select(driver.findElement(By.name("carLength")));
select.selectByVisibleText("12.5米");//车长
select = new Select(driver.findElement(By.name("carType")));
select.selectByVisibleText("高低板");//车型
/*
* 服务信息
*
*/
select = new Select(driver.findElement(By.name("signatureRequirements")));
select.selectByVisibleText("签字");//签收单要求
//是否需要发票
driver.findElement(By.xpath("//*[@id=\"J_Form\"]/div[1]/div[6]/div[2]/table/tbody/tr[2]/td[2]/label[1]/input")).click();//是
//发票类型
select = new Select(driver.findElement(By.name("invoiceType")));
select.selectByVisibleText("专用发票");
//发票抬头公司
driver.findElement(By.name("invoiceCompanyTitle")).sendKeys("锤子科技");
//税号
driver.findElement(By.name("invoiceCompanyTaxNo")).sendKeys(DateFormatUtils.format(new Date(), "yyyyMMddHHmm"));
//地址
driver.findElement(By.name("invoiceAddress")).sendKeys("北京市东城区大爷摆摊卖烧烤");
//电话
driver.findElement(By.name("invoicePhone")).sendKeys("13771716039");
//开户银行
driver.findElement(By.name("invoiceBank")).sendKeys("齐鲁银行");
//银行账户
driver.findElement(By.name("invoiceBankNo")).sendKeys("6223795315003442558");
//是否投保
driver.findElement(By.xpath("//*[@id=\"J_Form\"]/div[1]/div[6]/div[2]/table/tbody/tr[5]/td[2]/label[1]/input")).click();
//投保金额
driver.findElement(By.name("insuranceMoney")).sendKeys("666");
//备注
driver.findElement(By.name("remarks")).sendKeys("自动化测试备注信息");
//发布
driver.findElement(By.id("release")).click();
driver.navigate().refresh();//刷新页面
//action.sendKeys(Keys.F5);
}
}
<file_sep>package com.tangge.newb.SeleniumImcoo;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.Keys;
public class Shipper_Click_Event {
public static void main(String[] args) throws Exception {
currency cy = new currency();
cy.Shipper_Login();
Shipper_Click_Event sce = new Shipper_Click_Event();
sce.Click_Event(cy);
}
/**
* 随机事件的点击
* @throws Exception
* */
public void Click_Event(currency cy) throws Exception{
cy.getDriver().findElement(By.xpath("//*[@id=\"side-menu\"]/li[2]/a/span[1]")).click();//开票管理
Thread.sleep(2000);
cy.getDriver().findElement(By.xpath("//*[@id=\"side-menu\"]/li[2]/ul/li[1]/a")).click();//应付账单
cy.getDriver().switchTo().frame("iframe");
cy.getDriver().findElement(By.className("form-control")).sendKeys("9F55500000001421");
Thread.sleep(2000);
//选择一下日期
String js = "document.getElementsByName('search_gtedate_record.createDate').removeAttribute('readonly')";
((JavascriptExecutor)cy.getDriver()).executeScript(js);
cy.getDriver().findElement(By.id("bidValidTime")).sendKeys("2018-12-01");
cy.getDriver().findElement(By.id("search")).click();//搜索
Thread.sleep(2000);
cy.getDriver().findElement(By.linkText("9F55500000001421")).click();//运单详情
cy.getDriver().switchTo().frame("layui-layer-iframe1");
//下拉滚动条到底部
String str = "document.body.scrollTop=500";
((JavascriptExecutor)cy.getDriver()).executeScript(str);
cy.getDriver().findElement(By.xpath("/html/body/div[2]/div/div[3]/div[2]/table/tbody/tr[3]/td[2]/div[1]/ul/li[1]/img")).click();
cy.getDriver().switchTo().defaultContent();
Thread.sleep(2000);
//cy.getDriver().findElement(By.xpath("//*[@id=\"layui-layer1\"]/span[1]")).click();//关闭运单详情.
cy.getDriver().findElement(By.xpath("/html/body/div[3]/div[4]")).click();
cy.getDriver().findElement(By.className("layui-layer-setwin")).click();
cy.getAction().sendKeys(Keys.F5);
cy.getDriver().findElement(By.xpath("//*[@id=\"side-menu\"]/li[2]/ul/li[2]/a")).click();//开票列表
cy.getDriver().findElement(By.name("search_like_orderNo")).sendKeys("9F55500000001179");
cy.getDriver().findElement(By.id("search")).click();//搜索
cy.getDriver().findElement(By.xpath("/html/body/div[3]/div/div[3]/div[3]/div/table/tbody/tr[2]/td[4]/a")).click();
}
}
| 4db5646d3a1a3ada70b9b71069fc45ac49624863 | [
"Java",
"Maven POM"
]
| 5 | Java | KarasFighting/-SeleniumImcoo | 7ce236827e0f5a6f907a9c64ce3ae4e1aed5f5a3 | ef7d0ef5b48dad5086d44dbcef090b49109dec31 |
refs/heads/master | <file_sep>/**
* Created by balate on 26/2/17.
*/
angular.module("cookbook").component("nuevaReceta",{
//con bindings establecemos la interfaz de comunicacion del componente.Solicitamos el enlace de $router que
//lo hace automaticamente Angular en el ngOutlet
bindings:{
$router:"<"
},
templateUrl: "views/nueva-receta.html",
controller: function(ServicioRecetas){
//guardamos la referencia del componente
var self = this;
// Guardamos la receta.
self.guardarReceta = function(texto) {
var receta = { nombre: texto };
ServicioRecetas
.guardarReceta(receta)
.then(function(respuesta) {
//$router tiene los datos relacionados con la ruta que se esta navegando. puedo ejecutar su fucncion 'navigate()' para hacer redireción.
self.$router.navigate(["MisRecetas"]);
});
};
}
});
<file_sep>/**
* Created by balate on 21/2/17.
*/
//module setter
angular.module("cookbook", ["ngComponentRouter"]);
//configuramos el proveedor locationProvider
//establecemos el modo de navegación HTML5 para que funcione el single page application
angular.module("cookbook").config(function($locationProvider){
$locationProvider.html5Mode(true);
});
// En el value '$routerRootComponent' indicamos el componente raiz.
angular.module("cookbook").value("$routerRootComponent", "raiz");
<file_sep>/**
* Created by balate on 26/2/17.
*/
angular.module("cookbook").component("raiz", {
$routeConfig:[{
name: "MisRecetas",
path: "/mis-recetas",
component: "misRecetas"
},{
name: "NuevaReceta",
path: "/nueva-recetas",
component: "nuevaReceta",
}],
templateUrl: "views/raiz.html"
});
<file_sep>/**
* Created by balate on 22/2/17.
*/
angular.module("cookbook").service("ServicioRecetas", function($http){
//toda funcionalidad que quieras exponer hacia afuera, tiene que estar publicada en this (para llamarla desde fuera)
//obtenemos la collecion de recetas.
this.obtenerRecetas = function(){
return $http.get("http://localhost:8000/api/recetas");
};
//guardamos la receta
this.guardarReceta = function(receta){
return $http.post("http://localhost:8000/api/recetas", receta);
}
});<file_sep>/**
* Created by balate on 25/2/17.
*/
angular.module("cookbook").directive("formularioAlta", function () {
return {
//con restrict, indicamos como vamos a usar la directia con A como atributo y con E la usamos como el propio
// elemento
restrict: "EA",
//template o templateUrl indicamos la jerarquia de componentes que el navegador va a a renderizar como vista de la directiva
templateUrl: "views/formulario-alta.html",
//Con scope definimos la interfaz de comunicación entre la directiva y el scope padre (controlaador / componentes))
scope:{
alHacerClick: "&" //con & notificamos eventos al controlador padre
},
//con link establecemos la lógica de la directiva y ademas podemos hacer manipulación del DOM de a visata
link: function(scope){
//Manejador del botón 'Aceptar
scope.notificarTexto = function(){
//'notificar hacia fuera (hacia el controlador padre).
scope.alHacerClick({texto: scope.texto});
};
}
};
});<file_sep>/**
* Created by balate on 25/2/17.
*/
angular.module("cookbook").component("misRecetas", {
//establecemos la vista del componente
templateUrl:"views/mis-recetas.html",
// En controller establecemos la lógica del componente.
controller: function(ServicioRecetas){
var self = this;
//podemos engancharnos al hook '$onInit', que se dispara cuando el componente se inicia o se instancia.
self.$onInit = function(){
// Como 'obtenerRecetas()' retorna una promesa, tengo que
// pasar un manejador a su funcion 'then()'.
ServicioRecetas.obtenerRecetas().then(function(respuesta) {
// En la propiedad 'data' de la respuesta HTTP tenemos el cuerpo de la misma.
self.recetas = respuesta.data;
});
};
}
}); | 20c998237274beea0bd1a9d56f2867ead1b5c10a | [
"JavaScript"
]
| 6 | JavaScript | balate/cookbook | 9be436881b435aaabceb0556babe805f20123c7d | 84997e4866a82b9220ac718605cbe46f5196ab7d |
refs/heads/master | <file_sep>let socket
let color = '#FFF'
let bgColor = '#000'
let strokeWidth = 4
function setup() {
// Creating canvas
const cv = createCanvas(window.innerWidth, window.innerHeight)
cv.background(bgColor)
// Start the socket connection
socket = io.connect('http://localhost:3000')
// Callback function
socket.on('mouse', data => {
stroke(data.color)
strokeWeight(data.strokeWidth)
line(data.x, data.y, data.px, data.py)
})
// Getting our buttons and the holder through the p5.js dom
const color_picker = document.querySelector("#pickcolor");
const bg_picker = document.querySelector("#bg-pickcolor");
const stroke_width_picker = select('#stroke-width-picker')
const stroke_btn = select('#stroke-btn')
const clear_btn = select('#clear-btn')
const save_btn = select('#save')
color_picker.addEventListener("change", watchColorPicker, false);
bg_picker.addEventListener("change", watchBgPicker, false);
function watchColorPicker(event) {
color = event.target.value;
}
function watchBgPicker(event) {
bgColor = event.target.value;
cv.background(bgColor)
}
clear_btn.mousePressed(() => {
cv.background(bgColor)
})
save_btn.mousePressed(() => {
saveCanvas(cv, 'myArtwork', 'png');
})
// Adding a mousePressed listener to the button
stroke_btn.mousePressed(() => {
const width = parseInt(stroke_width_picker.value())
if (width > 0) strokeWidth = width
})
}
function mouseDragged() {
// Draw
stroke(color)
strokeWeight(strokeWidth)
line(mouseX, mouseY, pmouseX, pmouseY)
// Send the mouse coordinates
sendmouse(mouseX, mouseY, pmouseX, pmouseY)
}
// Sending data to the socket
function sendmouse(x, y, pX, pY) {
const data = {
x: x,
y: y,
px: pX,
py: pY,
color,
bgColor,
strokeWidth: strokeWidth,
}
socket.emit('mouse', data)
} | c366f364cc9b4e18bf1b4dd6638b2df7d3836121 | [
"JavaScript"
]
| 1 | JavaScript | kFs69/DrawingApp | dc59d954267881cd401bcb8ce672803d25361f01 | 8c3d2c450ad858190097c1f132de73934936053b |
refs/heads/master | <file_sep>import time as timer
import random
from env import read_env
from logger import Logger
from crawler import Crawler
from exception import AuthException
logger = Logger()
read_env()
# We run this continuously
while True:
try:
crawler = Crawler()
crawler.run()
rntime = random.randrange(30, 60, 5)
logger.log('Sleeping for %s seconds ... ' % rntime)
timer.sleep(rntime)
except AuthException as e:
logger.error('Authentication error: %s' % str(e))
except AttributeError as e:
logger.error('Attribute error: %s' % str(e))
except Exception as e:
logger.error('Unknown error: %s' % str(e))
<file_sep>import logging
import datetime
class Logger:
def __init__(self):
logging.basicConfig(
filename='%s.log' % (datetime.datetime.now().strftime("%Y-%m-%d")),
level=logging.DEBUG
)
def error(self, message):
logging.error(message)
def log(self, message):
logging.info(message)
<file_sep>from .RedisStorage import RedisStorage
from exception import StorageException
class Storage:
# Storage instance
__storage = None
# A list with valid storage engines
__valid_engine = [
'redis'
]
def __init__(self, name):
if name not in self.__valid_engine:
raise StorageException('Invalid storage engine: %s' % name)
if name == 'redis':
storage = RedisStorage()
self.__storage = storage.get_storage()
def get_storage(self):
return self.__storage
<file_sep>import mechanicalsoup
from exception import AuthException
class Auth:
def authenticate(self):
"""
Authenticate based on known credentials using the form
from the login page
:return browser:
"""
browser = mechanicalsoup.StatefulBrowser(raise_on_404=True)
browser.open(self.get_auth_url())
login_data = self.get_login_data()
form = browser.select_form('form')
form['username'] = login_data['username']
form['password'] = login_data['password']
response = browser.submit_selected()
if 'Logout' in response.text:
return browser
else:
raise AuthException
@staticmethod
def get_login_data():
"""
This can be retrieve from a storage engine or from a
configuration file
:return:
"""
return {
'username': 'admin',
'password': '<PASSWORD>',
'user_token': None
}
@staticmethod
def get_auth_url():
"""
This can be retrieve from a storage engine or from a
configuration file
:return:
"""
return 'http://localhost:11985/login.php'
<file_sep># Requirements
This software is build and optimized to run having the following requirements / dependency:
* Ubuntu (Ubuntu Server) >= 16.04 / Debian >= 7
* Python >= 3.6.4
* pip >= 19.0.3
# Installation
## Application
<pre>
$ git clone https://github.com/calinrada/appcheck.git
$ cd appcheck
$ pip install virtualenv
$ mkvirtualenv -p /usr/bin/python3.6 appcheck
$ workon appcheck
# cp .env.dist .env
</pre>
## Storage configuration
A storage (database) can be configured. By default only Redis storage is implemented (see storage/RedisStorage.py).
Update your local .env file before running the application.
## Docker containers
If you don't want to / can't use docker, you can install Redis and DVWA application locally
* Run DVWA Docker container:
<pre>
$ docker run --rm -it -p 11985:80 vulnerables/web-dvwa
</pre>
* Run Redis Docker Container:
<pre>
$ docker run --name some-redis -p 6380:6379 -d redis redis-server --appendonly yes
</pre>
# Run the application
<code>
$ python run.py
</code>
or in background
<code>
$ nohup python run.py >> debug.log &
</code>
# Todo
* Catch socket and storage connection errors
* Build a docker image containing this app
<file_sep>import redis
import os
from .AbstractStorage import AbstractStorage
class RedisStorage(AbstractStorage):
__storage = None
def __init__(self):
self.__storage = redis.Redis(
host=os.environ.get('STORAGE_ENGINE_HOST', 'localhost'),
port=os.environ.get('STORAGE_ENGINE_PORT', 6379),
db=os.environ.get('STORAGE_ENGINE_DB_NAME', 0)
)
def get_storage(self):
return self
def get(self, key):
return self.__storage.smembers(key)
def set(self, key, value):
return self.__storage.sadd(key, value)
def exists(self, **kwargs):
key = kwargs.pop('key')
value = kwargs.pop('value')
return self.__storage.sismember(key, value)
<file_sep>import os
import gevent
import gevent.monkey
gevent.monkey.patch_all()
from injections import INJECTION_TYPES
from storage.Storage import Storage
from auth import Auth
class Crawler:
browser = None
storage = None
def __init__(self):
storage = Storage(name=os.environ.get('STORAGE_ENGINE'))
self.storage = storage.get_storage()
def run(self):
auth = Auth()
self.browser = auth.authenticate()
jobs = [gevent.spawn(self.inject, url) for url in self.get_scrape_urls()]
gevent.wait(jobs)
def inject(self, url):
self.browser.open(url)
for key, value in INJECTION_TYPES.items():
form = self.browser.select_form('form')
form['id'] = value
self.browser.submit_selected()
# we assume that the presence of `pre` tag means we got some results
results = self.browser.get_current_page().select('pre')
for result in results:
self.storage.set(key, str(result))
@staticmethod
def get_scrape_urls():
"""
This can be retrieve from a storage engine or from a
configuration file
:return:
"""
return [
'http://localhost:11985/vulnerabilities/sqli/'
]
<file_sep># These values can be retrieved from an env or from a data store
INJECTION_TYPES = {
"DATABASE_USERNAME": "%' or 0=0 union select null, user() #",
"DATABASE_VERSION": "%' or 0=0 union select null, version() #"
}
<file_sep>class AuthException(Exception):
pass
class StorageException(Exception):
pass
class CrawlException(Exception):
pass
<file_sep>beautifulsoup4==4.7.1
certifi==2019.3.9
chardet==3.0.4
gevent==1.4.0
greenlet==0.4.15
idna==2.8
lxml==4.3.2
MechanicalSoup==0.11.0
redis==3.2.0
requests==2.21.0
six==1.12.0
soupsieve==1.8
urllib3==1.24.1
| f2d0aa7a850295d6107990e58cbde6eb6e0f83b6 | [
"Markdown",
"Python",
"Text"
]
| 10 | Python | calinrada/appcheck | 75d3b5b2caadc7e9eb8620d46211c7f5d427fef1 | 889fd32b87d1a147ecb1e403c95780828dbcae76 |
refs/heads/master | <repo_name>indrajitp/deletethis<file_sep>/apiproxies/tokenization/apiproxy/resources/jsc/retryMechanism.js
var mid = context.getVariable("mid");
var pan = context.getVariable("private.pan");
var modTenChk = context.getVariable("modTenCheck");
var path = context.getVariable("proxy.pathsuffix");
var token = context.getVariable("token");
var centralServer = "https://gptokenizationcentral-dev.globalpay.com";
var eastServer = "https://gptokenizationeast-dev.globalpay.com";
var healthMonitorURI = "/static/swaggerUI/dist/index.html";
var count = 0;
var flag = true;
var uri;
var myRequest;
var exchangeObj;
var eastHealthCheckURL = new Request();
var centralHealthCheckURL = new Request();
centralHealthCheckURL.url = centralServer + healthMonitorURI;
eastHealthCheckURL.url = centralServer + healthMonitorURI;
var header = {
'Content-Type' : 'application/x-www-form-urlencoded'
};
var detokenizeBasePath = "/api/detokenize";
var basepath = "/api/TokenizeData";
function toCheckFlow(serverName) {
if (path == "/merchant/number") {
url = serverName+basepath+"?format=json&PAN=" + pan + "&MID=" + mid
+ "&isGTRequired=false&isModTenRequired=" + modTenChk
+ "&token=" + token;
print("************url****************"+url);
//centralServer = centralServer + basepath + uri;
myRequest = new Request(url, 'POST', header);
exchangeObj = httpClient.send(myRequest);
//exchangeObj.waitForComplete(1);
if(!exchangeObj.isError()){
var op = exchangeObj.getResponse().content.asJSON;
print("Final" + JSON.stringify(op));
}
return exchangeObj.isError();
} else if (path == "/number") {
url = serverName + basepath+"?format=json&PAN=" + pan + "&MID=" + mid
+ "&isGTRequired=true&isModTenRequired=" + modTenChk
+ "&token=" + token;
myRequest = new Request(url, 'POST', header);
exchangeObj = httpClient.send(myRequest);
exchangeObj.waitForComplete(1);
print("TTTTTTT" + exchangeObj.isError());
var op1 = exchangeObj.getResponse().content.asJSON;
print("Final" + JSON.stringify(op1));
return exchangeObj.isError();
} else if (path == "/token") {
url = serverName + detokenizeBasePath+"?format=json&&token=" + token + "&TOKEN_NUM=" + tnumber;
myRequest = new Request(url, 'POST', header);
exchangeObj = httpClient.send(myRequest);
exchangeObj.waitForComplete(1);
print("TTTTTTT" + exchangeObj.isError());
var op2 = exchangeObj.getResponse().content.asJSON;
print("Final" + JSON.stringify(op2));
return exchangeObj.isError();
}
}
while (count < 5) {
print("*****************************************");
count++;
print("Count" + count);
if (flag) {
if (!httpClient.send(centralHealthCheckURL).isError()) {
print("*********Central*****true******");
if(!toCheckFlow(centralServer)){
break;
}
} else if (!httpClient.send(eastHealthCheckURL).isError()) {
print("*********East******true*****");
if(!toCheckFlow(eastServer)){
break;
}
}
flag = false;
}else {
if (!httpClient.send(eastHealthCheckURL).isError()) {
print("*********East******false*****");
if(!toCheckFlow(eastServer)){
break;
}
} else if (!httpClient.send(centralHealthCheckURL).isError()) {
print("*********Central******false*****");
if(!toCheckFlow(centralServer)){
break;
}
}
flag = true;
}
}<file_sep>/apiproxies/gnf-api/apiproxy/resources/jsc/targetPathSuffix.js
context.setVariable("target.copy.pathsuffix", false);
var reqUri = context.getVariable("proxy.pathsuffix");
var prefix = reqUri.substring(0, 7);
context.setVariable("uri", prefix);
if(prefix == "/images")
{
context.setVariable("target.copy.pathsuffix", false);
var backend = context.getVariable("target.url");
context.setVariable("Bkend", backend);
var path = context.getVariable("target.url") + "/gnf" + context.getVariable("proxy.pathsuffix");
context.setVariable("target.url", path);
print("path", path);
}
//setting uri for user-offboarding backend
/*var offboardingPrefix = reqUri.substring(0, 17);
if(offboardingPrefix == "/user/offboarding")
{
context.setVariable("target.copy.pathsuffix", false);*/
/*var targetUri = "serviceName="+context.getVariable("serviceName")+"&hash="+context.getVariable("hashValue"); */
/*var targetUri= context.getVariable("request.querystring")
print("***"+targetUri);
context.setVariable("uriPath", targetUri);
}*/
<file_sep>/apiproxies/gnf-api/apiproxy/resources/jsc/notifyRequestValidator.js
// jshint esversion: 6
//GNF:Validations on Notification request
//header details
var sourceId = context.getVariable("sid");
var sourceTransactionId = context.getVariable("sourceTxnId");
//notification details
var destinationType = context.getVariable("destinationType");
var message = context.getVariable("messageContent");
var messageCategory = context.getVariable("messageCategory");
var msgPriority = context.getVariable("messagePriority");
var smsNotiProvider = context.getVariable("smsNotificationProvider");
var emailNotiProvider = context.getVariable("emailNotificationProvider");
var notificationChannel = context.getVariable("notificationChannel");
//Scheduled Notification details
var isScheduled = context.getVariable("isScheduled");
var schedulingEta = context.getVariable("schedulingEta");
var timezone = context.getVariable("timezone");
//Recurring notification details
var isRecurring = context.getVariable("isRecurring");
var recurNum = context.getVariable("recurrenceNumber");
var recurUnit = context.getVariable("recurrenceUnit");
var maxRecurCnt = context.getVariable("maxRecurringCount");
var sendImmed = context.getVariable("sendImmediately");
//Multi message details
var multiMsgFlag = context.getVariable("multiMessageFlag");
var multiMsgNum = context.getVariable("multiMessageNumber");
var multiMsgTotal = context.getVariable("multiMessageTotal");
//template details
var useTemplate = context.getVariable("useTemplate");
var tempId = context.getVariable("templateId");
var tempType = context.getVariable("templateType");
//retry details
var retryMsgFlag = context.getVariable("retryMessageFlag");
var maxRetryCnt = context.getVariable("maxRetryCount");
// regex varaible
var alphaNumeric = /^[0-9a-zA-Z]+$/;
var alpahbets = /^[a-zA-Z]*$/;
var numbers = /^[0-9]*$/;
var templId = /^[a-zA-Z][a-zA-Z_0-9]+$/;
var timeZne = /^[A-Z][a-z]*[/]([A-Z][a-z]*)/;
var eta = /^([0]{0,1}[1-9]|1[012])\/([1-9]|([012][0-9])|(3[01]))\/\d\d\d\d (20|21|22|23|[0-1]?\d):[0-5]?\d:[0-5]?\d$/;
//regex methods
var reAlpNum = new RegExp(alphaNumeric);
var reAlphs = new RegExp(alpahbets);
var reNumbers = new RegExp(numbers);
var reTemplId = new RegExp(templId);
var reTimezne = new RegExp(timeZne);
var reEta = new RegExp(eta);
//applying regex on input data
var re_sid = reNumbers.test(sourceId);
var re_sTxnId = reAlpNum.test(sourceTransactionId);
var re_msgPriority = reNumbers.test(msgPriority);
var re_msgCategory = reAlphs.test(messageCategory);
var re_schedulingEta = reEta.test(schedulingEta);
var re_timezone = reTimezne.test(timezone);
var re_recurNum = reNumbers.test(recurNum);
var re_maxRetryCnt = reNumbers.test(maxRetryCnt);
var re_multiMsgNum = reNumbers.test(multiMsgNum);
var re_multiMsgTotal = reNumbers.test(multiMsgTotal);
var re_tempId = reTemplId.test(tempId);
var re_maxRecurCnt = reNumbers.test(maxRecurCnt);
var errorCode = '';
var errorMessage = '';
//error Handling
var errorHandling = [];
var isDestinationValidJson = true;
// extracting destinations with try-catch blocks
try {
var destinations = JSON.parse(context.getVariable("destinations"));
var destString = destinations.toString();
var destNumbers = destString.replace(/,/g, "");
var re_dest = reNumbers.test(destNumbers);
}catch (e) {
isDestinationValidJson = false ;
print("Error:"+e);
var errorCode = "40009";
var errorMessage = "destinations contains unexpected data";
context.setVariable("http.reasonPhrase", "BAD REQUEST");
context.setVariable("http.statusCode", "400");
context.setVariable("log.severity", "Error");
errorHandling.push({
errorCode : errorCode,
errorMessage : errorMessage
});
}
//declaring enum values
const notiChannelEnum = {
SMS: 1,
EMAIL: 2,
RCS: 3,
FAX: 4,
CALL: 5
};
const destTypeEnum = {
USER: 1,
GROUP: 2
};
const recurUnitEnum = {
MINUTES: 1,
HOURS: 2,
DAYS: 3,
WEEKS: 4
};
const tempTypeEnum = {
GNF: 1,
PROVIDER: 2
};
const smsNotiProviderEnum = {
TwilioSMS: 1,
OpenMarketSMS: 2
};
const emailNotiProviderEnum = {
SendGridEmail: 1,
JangoMailEmail: 2
};
const booleanEnum = {
true: 1,
false: 2
};
//manadtory fields list
var arrayMandatory = [];
var is_mandate = false;
var mandate_var_list = [];
var validPayload = "false";
var isError = "false";
arrayMandatory.push({
type: "sourceId",
value: sourceId
});
arrayMandatory.push({
type: "destinationType",
value: destinationType
});
if(isDestinationValidJson){
arrayMandatory.push({
type: "destinations",
value: destinations
});
}
arrayMandatory.push({
type: "message",
value: message
});
//manadtory fields check function
function mandatoryCheck(arrayMandatory) {
for (var i = 0; i < arrayMandatory.length; i++){
if (arrayMandatory[i].value === null || arrayMandatory[i].value === "" || arrayMandatory[i].value.length < 1) {
mandate_var_list.push(arrayMandatory[i].type);
}
}
}
//manadtory check execution
mandatoryCheck(arrayMandatory);
// mandatory check
if(mandate_var_list.length > 0){
errorCode = "40008";
errorMessage = "Request expects the following fields "+ mandate_var_list;
context.setVariable("http.reasonPhrase", "BAD REQUEST");
context.setVariable("http.statusCode", "400");
context.setVariable("log.severity", "Error");
errorHandling.unshift({
errorCode : errorCode,
errorMessage : errorMessage
});
}
//manual fields check
//Multi message fields
var multiMsg_fields = [multiMsgNum,multiMsgTotal,sourceTransactionId];
if (multiMsgFlag === "true") {
if (!isAnyObjectNull(multiMsg_fields)) {
errorCode = "40008";
errorMessage = "Request expects the following fields multiMessageNumber, multiMessageTotal, sourceTransactionId";
context.setVariable("http.reasonPhrase", "BAD REQUEST");
context.setVariable("http.statusCode", "400");
context.setVariable("log.severity", "Error");
errorHandling.push({
errorCode : errorCode,
errorMessage : errorMessage
});
}
}
//scheduling fields
var sched_fields = [schedulingEta, timezone];
if (isScheduled === "true") {
if (!isAnyObjectNull(sched_fields)) {
errorCode = "40008";
errorMessage = "Request expects the following fields schedulingEta,timezone";
context.setVariable("http.reasonPhrase", "BAD REQUEST");
context.setVariable("http.statusCode", "400");
context.setVariable("log.severity", "Error");
errorHandling.push({
errorCode : errorCode,
errorMessage : errorMessage
});
}
}
//Recurring fields
var recurring_fields = [recurNum,recurUnit];
if (isRecurring === "true") {
if (!isAnyObjectNull(recurring_fields)) {
errorCode = "40008";
errorMessage = "Request expects the following fields recurrenceNumber,recurrenceUnit";
context.setVariable("http.reasonPhrase", "BAD REQUEST");
context.setVariable("http.statusCode", "400");
context.setVariable("log.severity", "Error");
errorHandling.push({
errorCode : errorCode,
errorMessage : errorMessage
});
}
}
//template fields
var template_fields = [tempId,tempType];
if (useTemplate === "true") {
if (!isAnyObjectNull(template_fields)) {
errorCode = "40008";
errorMessage = "Request expects the following fields templateId,templateType";
context.setVariable("http.reasonPhrase", "BAD REQUEST");
context.setVariable("http.statusCode", "400");
context.setVariable("log.severity", "Error");
errorHandling.push({
errorCode : errorCode,
errorMessage : errorMessage
});
}
}
//function checks if any field is null for manual fields
function isAnyObjectNull(items) {
is_mandate = false;
if (items !== null) {
for (var j = 0; j < items.length; j++) {
if (items[j] === null || items[j] === "") {
is_mandate = false;
break;
} else {
is_mandate = true;
}
}
}
return is_mandate;
}
// enum check for input vars
if (destinationType !== null && destinationType !== "") {
if (!destTypeEnum[destinationType]) {
errorCode = "40009";
errorMessage = "destinationType contains unexpected data";
context.setVariable("http.reasonPhrase", "BAD REQUEST");
context.setVariable("http.statusCode", "400");
context.setVariable("log.severity", "Error");
errorHandling.push({
errorCode : errorCode,
errorMessage : errorMessage
});
}
}
(function() {
var errorCode = '';
var errorMessage = '';
//both check
if (smsNotiProvider !== null && smsNotiProvider !== "" && emailNotiProvider !== null && emailNotiProvider !== "") {
if ((!smsNotiProviderEnum[smsNotiProvider]) || (!emailNotiProviderEnum[emailNotiProvider])) {
errorCode = "40009";
errorMessage = "notificationProvider contains unexpected data";
context.setVariable("http.reasonPhrase", "BAD REQUEST");
context.setVariable("http.statusCode", "400");
context.setVariable("log.severity", "Error");
print("both");
errorHandling.push({
errorCode : errorCode,
errorMessage : errorMessage
});
return ;
}
}
//email check
if (emailNotiProvider !== null && emailNotiProvider !== "") {
if (!emailNotiProviderEnum[emailNotiProvider]) {
errorCode = "40009";
errorMessage = "notificationProvider contains unexpected data";
context.setVariable("http.reasonPhrase", "BAD REQUEST");
context.setVariable("http.statusCode", "400");
context.setVariable("log.severity", "Error");
print("email");
errorHandling.push({
errorCode : errorCode,
errorMessage : errorMessage
});
return ;
}
}
//sms check
if (smsNotiProvider !== null && smsNotiProvider !== "") {
if (!smsNotiProviderEnum[smsNotiProvider]) {
errorCode = "40009";
errorMessage = "notificationProvider contains unexpected data";
context.setVariable("http.reasonPhrase", "BAD REQUEST");
context.setVariable("http.statusCode", "400");
context.setVariable("log.severity", "Error");
print("sms");
errorHandling.push({
errorCode : errorCode,
errorMessage : errorMessage
});
return ;
}
}
})();
if (notificationChannel !== null && notificationChannel !== "") {
if (!notiChannelEnum[notificationChannel]) {
errorCode = "40009";
errorMessage = "notificationChannel contains unexpected data";
context.setVariable("http.reasonPhrase", "BAD REQUEST");
context.setVariable("http.statusCode", "400");
context.setVariable("log.severity", "Error");
errorHandling.push({
errorCode : errorCode,
errorMessage : errorMessage
});
}
}
if (recurUnit !== null && recurUnit !== "") {
if (!recurUnitEnum[recurUnit]) {
errorCode = "40009";
errorMessage = "recurrenceUnit contains unexpected data";
context.setVariable("http.reasonPhrase", "BAD REQUEST");
context.setVariable("http.statusCode", "400");
context.setVariable("log.severity", "Error");
errorHandling.push({
errorCode : errorCode,
errorMessage : errorMessage
});
}
}
if (tempType !== null && tempType !== "") {
if (!tempTypeEnum[tempType]) {
errorCode = "40009";
errorMessage = "templateType contains unexpected data";
context.setVariable("http.reasonPhrase", "BAD REQUEST");
context.setVariable("http.statusCode", "400");
context.setVariable("log.severity", "Error");
errorHandling.push({
errorCode : errorCode,
errorMessage : errorMessage
});
}
}
//Boolean values enum check for input variables
if (isScheduled !== null && isScheduled !== "") {
if (!booleanEnum[isScheduled]) {
errorCode = "40009";
errorMessage = "isScheduled contains unexpected data";
context.setVariable("http.reasonPhrase", "BAD REQUEST");
context.setVariable("http.statusCode", "400");
context.setVariable("log.severity", "Error");
errorHandling.push({
errorCode : errorCode,
errorMessage : errorMessage
});
}
}
if (isRecurring !== null && isRecurring !== "") {
if (!booleanEnum[isRecurring]) {
errorCode = "40009";
errorMessage = "isRecurring contains unexpected data";
context.setVariable("http.reasonPhrase", "BAD REQUEST");
context.setVariable("http.statusCode", "400");
context.setVariable("log.severity", "Error");
errorHandling.push({
errorCode : errorCode,
errorMessage : errorMessage
});
}
}
if (useTemplate !== null && useTemplate !== "") {
if (!booleanEnum[useTemplate]) {
errorCode = "40009";
errorMessage = "useTemplate contains unexpected data";
context.setVariable("http.reasonPhrase", "BAD REQUEST");
context.setVariable("http.statusCode", "400");
context.setVariable("log.severity", "Error");
errorHandling.push({
errorCode : errorCode,
errorMessage : errorMessage
});
}
}
if (multiMsgFlag !== null && multiMsgFlag !== "") {
if (!booleanEnum[multiMsgFlag]) {
errorCode = "40009";
errorMessage = "multiMessageFlag contains unexpected data";
context.setVariable("http.reasonPhrase", "BAD REQUEST");
context.setVariable("http.statusCode", "400");
context.setVariable("log.severity", "Error");
errorHandling.push({
errorCode : errorCode,
errorMessage : errorMessage
});
}
}
if (retryMsgFlag !== null && retryMsgFlag !== "") {
if (!booleanEnum[retryMsgFlag]) {
errorCode = "40009";
errorMessage = "retryMessageFlag contains unexpected data";
context.setVariable("http.reasonPhrase", "BAD REQUEST");
context.setVariable("http.statusCode", "400");
context.setVariable("log.severity", "Error");
errorHandling.push({
errorCode : errorCode,
errorMessage : errorMessage
});
}
}
if (sendImmed !== null && sendImmed !== "") {
if (!booleanEnum[sendImmed]) {
errorCode = "40009";
errorMessage = "sendImmediately contains unexpected data";
context.setVariable("http.reasonPhrase", "BAD REQUEST");
context.setVariable("http.statusCode", "400");
context.setVariable("log.severity", "Error");
errorHandling.push({
errorCode : errorCode,
errorMessage : errorMessage
});
}
}
//number check for input variables
if (sourceId !== null && sourceId !== "" && sourceId !== undefined) {
if (!(re_sid)) {
errorCode = "40009";
errorMessage = "SourceId contains unexpected data";
context.setVariable("http.reasonPhrase", "BAD REQUEST");
context.setVariable("http.statusCode", "400");
context.setVariable("log.severity", "Error");
errorHandling.push({
errorCode : errorCode,
errorMessage : errorMessage
});
}
}
if (destinations !== null && destinations !== "" && destinations !== undefined) {
if (!(re_dest)) {
errorCode = "40009";
errorMessage = "destinations contains unexpected data";
context.setVariable("http.reasonPhrase", "BAD REQUEST");
context.setVariable("http.statusCode", "400");
context.setVariable("log.severity", "Error");
errorHandling.push({
errorCode : errorCode,
errorMessage : errorMessage
});
}
}
if (msgPriority !== null && msgPriority !== "" && msgPriority !== undefined) {
if (!(re_msgPriority)) {
errorCode = "40009";
errorMessage = "messagePriority contains unexpected data";
context.setVariable("http.reasonPhrase", "BAD REQUEST");
context.setVariable("http.statusCode", "400");
context.setVariable("log.severity", "Error");
errorHandling.push({
errorCode : errorCode,
errorMessage : errorMessage
});
}
}
if (recurNum !== null && recurNum !== "" && recurNum !== undefined) {
if (!(re_recurNum)) {
errorCode = "40009";
errorMessage = "recurrenceNumber contains unexpected data";
context.setVariable("http.reasonPhrase", "BAD REQUEST");
context.setVariable("http.statusCode", "400");
context.setVariable("log.severity", "Error");
errorHandling.push({
errorCode : errorCode,
errorMessage : errorMessage
});
}
}
if (recurNum !== null && recurNum !== "" && recurNum !== undefined) {
if (!(re_recurNum)) {
errorCode = "40009";
errorMessage = "recurrenceNumber contains unexpected data";
context.setVariable("http.reasonPhrase", "BAD REQUEST");
context.setVariable("http.statusCode", "400");
context.setVariable("log.severity", "Error");
errorHandling.push({
errorCode : errorCode,
errorMessage : errorMessage
});
}
}
if (maxRecurCnt !== null && maxRecurCnt !== "" && maxRecurCnt !== undefined) {
if (!(re_maxRecurCnt)) {
errorCode = "40009";
errorMessage = "maxRecurringCount contains unexpected data";
context.setVariable("http.reasonPhrase", "BAD REQUEST");
context.setVariable("http.statusCode", "400");
context.setVariable("log.severity", "Error");
errorHandling.push({
errorCode : errorCode,
errorMessage : errorMessage
});
}
}
if (multiMsgNum !== null && multiMsgNum !== "" && multiMsgNum !== undefined) {
if (!(re_multiMsgNum)) {
errorCode = "40009";
errorMessage = "multiMessageNumber contains unexpected data";
context.setVariable("http.reasonPhrase", "BAD REQUEST");
context.setVariable("http.statusCode", "400");
context.setVariable("log.severity", "Error");
errorHandling.push({
errorCode : errorCode,
errorMessage : errorMessage
});
}
}
if (multiMsgTotal !== null && multiMsgTotal !== "" && multiMsgTotal !== undefined) {
if (!(re_multiMsgTotal)) {
errorCode = "40009";
errorMessage = "multiMessageTotal contains unexpected data";
context.setVariable("http.reasonPhrase", "BAD REQUEST");
context.setVariable("http.statusCode", "400");
context.setVariable("log.severity", "Error");
errorHandling.push({
errorCode : errorCode,
errorMessage : errorMessage
});
}
}
if (maxRetryCnt !== null && maxRetryCnt !== "" && maxRetryCnt !== undefined) {
if (!(re_maxRetryCnt)) {
errorCode = "40009";
errorMessage = "maxRetryCount contains unexpected data";
context.setVariable("http.reasonPhrase", "BAD REQUEST");
context.setVariable("http.statusCode", "400");
context.setVariable("log.severity", "Error");
errorHandling.push({
errorCode : errorCode,
errorMessage : errorMessage
});
}
}
//Alphabets check
if (messageCategory !== null && messageCategory !== "" && messageCategory !== undefined) {
if (!(re_msgCategory)) {
errorCode = "40009";
errorMessage = "messageCategory contains unexpected data";
context.setVariable("http.reasonPhrase", "BAD REQUEST");
context.setVariable("http.statusCode", "400");
context.setVariable("log.severity", "Error");
errorHandling.push({
errorCode : errorCode,
errorMessage : errorMessage
});
}
}
//Alphanumeric Check
if (sourceTransactionId !== null && sourceTransactionId !== "" && sourceTransactionId !== undefined) {
if (!(re_sTxnId)) {
errorCode = "40009";
errorMessage = "sourceTransactionId contains unexpected data";
context.setVariable("http.reasonPhrase", "BAD REQUEST");
context.setVariable("http.statusCode", "400");
context.setVariable("log.severity", "Error");
errorHandling.push({
errorCode : errorCode,
errorMessage : errorMessage
});
}
}
//patterns check for input variables
if (tempId !== null && tempId !== "" && tempId !== undefined) {
if (!(re_tempId)) {
errorCode = "40009";
errorMessage = "templateId contains unexpected data";
context.setVariable("http.reasonPhrase", "BAD REQUEST");
context.setVariable("http.statusCode", "400");
context.setVariable("log.severity", "Error");
errorHandling.push({
errorCode : errorCode,
errorMessage : errorMessage
});
}
}
if (schedulingEta !== null && schedulingEta !== "" && schedulingEta !== undefined) {
if (!(re_schedulingEta)) {
errorCode = "40010";
errorMessage = "schedulingEta is not in proper format";
context.setVariable("http.reasonPhrase", "BAD REQUEST");
context.setVariable("http.statusCode", "400");
context.setVariable("log.severity", "Error");
errorHandling.push({
errorCode : errorCode,
errorMessage : errorMessage
});
}
}
if (timezone !== null && timezone !== "" && timezone !== undefined) {
if (!(re_timezone)) {
var errorCode = "40010";
var errorMessage = "timezone is not in proper format";
context.setVariable("http.reasonPhrase", "BAD REQUEST");
context.setVariable("http.statusCode", "400");
context.setVariable("log.severity", "Error");
errorHandling.push({
errorCode : errorCode,
errorMessage : errorMessage
});
}
}
//setting the check to invoke raise fault
if(errorHandling.length>0)
{
print(errorHandling.length);
context.setVariable("isError", "true");
context.setVariable("flow.error.code",JSON.stringify(errorHandling));
}
<file_sep>/apiproxies/tokenization/apiproxy/resources/jsc/setSecurity.js
// initilizing variables to apply security policies of shared flow
context.setVariable("_SF_Default-Security-Policies.apikey","true");
context.setVariable("_SF_Default-Security-Policies.sqlProtection","true");
<file_sep>/apiproxies/gnf-api/apiproxy/resources/jsc/userManagementValidator.js
// jshint esversion: 6
//GNF:Validations on User management
var preferredChannel = context.getVariable("preferredChannel");
var userId = context.getVariable("uId");
var userIds = context.getVariable("uIds");
var groupIds = context.getVariable("gIds");
var appIds = context.getVariable("appIds");
var fromGroup = context.getVariable("fromGroup");
var toGroup = context.getVariable("toGroup");
var userEmail = context.getVariable("userEmail");
/*var modifiedBy = context.getVariable("modifiedBy"); */
var languageCode = context.getVariable("languageCode");
var userName = context.getVariable("userName");
var userStatus = context.getVariable("userStatus");
/*var createdBy = context.getVariable("createdBy");*/
var faxNumber = context.getVariable("faxNumber");
var mobileNumber = context.getVariable("mobileNumber");
var email = context.getVariable("email");
var preferredEndTime = context.getVariable("preferredEndTime");
var optIn = context.getVariable("optIn");
var preferredStartTime = context.getVariable("preferredStartTime");
var timezone = context.getVariable("timezone");
var isEmailValid = context.getVariable("isEmailValid");
var isMobileValid = context.getVariable("isMobileValid");
var isCustomAttrValidJson = true;
//mandatory check array declarations
var arrayMandatory = [];
var mandate_var_list = [];
var errorHandling = [];
//checking Custom Attribute has valid json
try {
var customAttribute = JSON.parse(context.getVariable("customAttribute"));
}
catch (e) {
isCustomAttrValidJson = false ;
print("Error:"+e);
var errorCode = "40009";
var errorMessage = "customAttribute contains unexpected data";
context.setVariable("http.reasonPhrase", "BAD REQUEST");
context.setVariable("http.statusCode", "400");
context.setVariable("log.severity", "Error");
errorHandling.push({
errorCode : errorCode,
errorMessage : errorMessage
});
}
//declaring enum values
const booleanEnum = {
true: 1,
false: 2
};
const notiChannelEnum = {
SMS: 1,
EMAIL: 2,
RCS: 3,
FAX: 4,
CALL: 5
};
//regex declarations
var mail = /^\w+([\.-]?\w+)+@\w+([\.:]?\w+)+(\.[a-zA-Z0-9]{2,3})+$/;
var mobileNum = /^([0+[0-9]{1,3})[- ]?([0-9]{10})$/;
var alpahbets = /^[a-zA-Z]*$/;
var numbers = /^[0-9]*$/;
var timeZne = /^[A-Z][a-z]*[/]([A-Z][a-z]*)/;
var reEmail = new RegExp(mail);
var reMobileNumber = new RegExp(mobileNum);
var reAlphs = new RegExp(alpahbets);
var reNumbers = new RegExp(numbers);
var reTimeZone = new RegExp(timeZne );
//applying regex on input params
var re_fromGroup = reNumbers.test(fromGroup);
var re_toGroup = reNumbers.test(toGroup);
/*var re_createdBy = reNumbers.test(createdBy);
var re_modifiedBy = reNumbers.test(modifiedBy);*/
var re_userId = reNumbers.test(userId);
var re_userName = reAlphs.test(userName );
var re_userEmail = reEmail.test(userEmail);
var re_email = reEmail.test(email);
var re_languageCode = reAlphs.test(languageCode);
var re_timezone = reTimeZone.test(timezone);
var re_mobileNumber = reMobileNumber.test(mobileNumber);
var re_userStatus = reAlphs.test(userStatus );
var re_appIds = reNumbers.test(appIds);
//getting incomming verb and request uri
var verb = context.getVariable("request.verb");
var reqUri = context.getVariable("request.uri");
//mandatory check for User Email field
if(verb !== "POST" || verb !== "PUT") {
//mandatory field check for input variables
if (userEmail === null || userEmail === "") {
var errorCode = "40008";
var errorMessage = "Request expects the following fields User Email";
context.setVariable("http.reasonPhrase", "BAD REQUEST");
context.setVariable("http.statusCode", "400");
context.setVariable("log.severity", "Error");
errorHandling.push({
errorCode : errorCode,
errorMessage : errorMessage
});
}
}
//number check for input variables
if (userIds !== null && userIds !== "" && userIds !== undefined) {
//removing comas if multiple group Ids are passed in the request
var userIdsString = userIds.toString();
print("after string"+userIdsString);
var userIdsNumbers = userIdsString.replace(/,/g, "");
print("after replace" +groupIdsNumbers);
var re_userIds = reNumbers.test(userIdsNumbers);
if (!(re_userIds)) {
var errorCode = "40009";
var errorMessage = "userIds contains unexpected data";
context.setVariable("http.reasonPhrase", "BAD REQUEST");
context.setVariable("http.statusCode", "400");
context.setVariable("log.severity", "Error");
errorHandling.push({
errorCode : errorCode,
errorMessage : errorMessage
});
}
}
if (appIds !== null && appIds !== "" && appIds !== undefined) {
//removing comas if multiple group Ids are passed in the request
var appIdsString = appIds.toString();
var appIdsNumbers = appIdsString.replace(/,/g, "");
var re_appIds = reNumbers.test(appIdsNumbers);
if (!(re_appIds)) {
var errorCode = "40009";
var errorMessage = "applicationIds contains unexpected data";
context.setVariable("http.reasonPhrase", "BAD REQUEST");
context.setVariable("http.statusCode", "400");
context.setVariable("log.severity", "Error");
errorHandling.push({
errorCode : errorCode,
errorMessage : errorMessage
});
}
}
if (groupIds !== null && groupIds !== "" && groupIds !== undefined) {
//removing comas if multiple group Ids are passed in the request
var groupIdsString = groupIds.toString();
var groupIdsNumbers = groupIdsString.replace(/,/g, "");
var re_groupIds = reNumbers.test(groupIdsNumbers);
if (!(re_groupIds)) {
var errorCode = "40009";
var errorMessage = "groupIds contains unexpected data";
context.setVariable("http.reasonPhrase", "BAD REQUEST");
context.setVariable("http.statusCode", "400");
context.setVariable("log.severity", "Error");
errorHandling.push({
errorCode : errorCode,
errorMessage : errorMessage
});
}
}
if (userId !== null && userId !== "" && userId !== undefined) {
if ((!(reqUri.includes("list"))) && (!(reqUri.includes("roles"))) && (!(reqUri.includes("details"))) && (!(reqUri.includes("upload")))) {
if ((!(re_userId)) || (userId <= 0)) {
var errorCode = "40009";
var errorMessage = "userId contains unexpected data";
context.setVariable("http.reasonPhrase", "BAD REQUEST");
context.setVariable("http.statusCode", "400");
context.setVariable("log.severity", "Error");
errorHandling.push({
errorCode : errorCode,
errorMessage : errorMessage
});
}
}
}
if (fromGroup !== null && fromGroup !== "" && fromGroup !== undefined) {
if ((!(re_fromGroup)) || (fromGroup <= 0)) {
var errorCode = "40009";
var errorMessage = "fromGroup contains unexpected data";
context.setVariable("http.reasonPhrase", "BAD REQUEST");
context.setVariable("http.statusCode", "400");
context.setVariable("log.severity", "Error");
errorHandling.push({
errorCode : errorCode,
errorMessage : errorMessage
});
}
}
if (toGroup !== null && toGroup !== "" && toGroup !== undefined) {
if ((!(re_toGroup)) || (toGroup <= 0)) {
var errorCode = "40009";
var errorMessage = "toGroup contains unexpected data";
context.setVariable("http.reasonPhrase", "BAD REQUEST");
context.setVariable("http.statusCode", "400");
context.setVariable("log.severity", "Error");
errorHandling.push({
errorCode : errorCode,
errorMessage : errorMessage
});
}
}
/*if (createdBy !== null && createdBy !== "" && createdBy !== undefined) {
if ((!(re_createdBy)) || (createdBy <= 0)) {
var errorCode = "40009";
var errorMessage = "createdBy contains unexpected data";
context.setVariable("http.reasonPhrase", "BAD REQUEST");
context.setVariable("http.statusCode", "400");
context.setVariable("log.severity", "Error");
errorHandling.push({
errorCode : errorCode,
errorMessage : errorMessage
});
}
}
if (modifiedBy !== null && modifiedBy !== "" && modifiedBy !== undefined) {
if ((!(re_modifiedBy)) || modifiedBy <= 0 ) {
var errorCode = "40009";
var errorMessage = "modifiedBy contains unexpected data";
context.setVariable("http.reasonPhrase", "BAD REQUEST");
context.setVariable("http.statusCode", "400");
context.setVariable("log.severity", "Error");
errorHandling.push({
errorCode : errorCode,
errorMessage : errorMessage
});
}
}*/
//Alphabets Check
if (languageCode !== null && languageCode !== "" && languageCode !== undefined) {
if (!(re_languageCode)) {
var errorCode = "40009";
var errorMessage = "languageCode contains unexpected data";
context.setVariable("http.reasonPhrase", "BAD REQUEST");
context.setVariable("http.statusCode", "400");
context.setVariable("log.severity", "Error");
errorHandling.push({
errorCode : errorCode,
errorMessage : errorMessage
});
}
}
if (userName !== null && userName !== "" && userName !== undefined) {
if (!(re_userName)) {
var errorCode = "40009";
var errorMessage = "userName contains unexpected data";
context.setVariable("http.reasonPhrase", "BAD REQUEST");
context.setVariable("http.statusCode", "400");
context.setVariable("log.severity", "Error");
errorHandling.push({
errorCode : errorCode,
errorMessage : errorMessage
});
}
}
if (userStatus !== null && userStatus !== "" && userStatus !== undefined) {
if (!(re_userStatus)) {
var errorCode = "40009";
var errorMessage = "userStatus contains unexpected data";
context.setVariable("http.reasonPhrase", "BAD REQUEST");
context.setVariable("http.statusCode", "400");
context.setVariable("log.severity", "Error");
errorHandling.push({
errorCode : errorCode,
errorMessage : errorMessage
});
}
}
//Email Check
if (email !== null && email !== "" && email !== undefined) {
if (!(re_email)) {
var errorCode = "40009";
var errorMessage = "email contains unexpected data";
context.setVariable("http.reasonPhrase", "BAD REQUEST");
context.setVariable("http.statusCode", "400");
context.setVariable("log.severity", "Error");
errorHandling.push({
errorCode : errorCode,
errorMessage : errorMessage
});
}
}
if (userEmail !== null && userEmail !== "" && userEmail !== undefined) {
if (!(re_userEmail)) {
var errorCode = "40009";
var errorMessage = "User Email contains unexpected data";
context.setVariable("http.reasonPhrase", "BAD REQUEST");
context.setVariable("http.statusCode", "400");
context.setVariable("log.severity", "Error");
errorHandling.push({
errorCode : errorCode,
errorMessage : errorMessage
});
}
}
//mobile number check
/*if (mobileNumber !== null && mobileNumber !== "" && mobileNumber !== undefined) {
if (!(re_mobileNumber)) {
var errorCode = "40009";
var errorMessage = "mobileNumber contains unexpected data";
context.setVariable("http.reasonPhrase", "BAD REQUEST");
context.setVariable("http.statusCode", "400");
context.setVariable("log.severity", "Error");
errorHandling.push({
errorCode : errorCode,
errorMessage : errorMessage
});
}
}*/
if (timezone !== null && timezone !== "" && timezone !== undefined) {
if (!(re_timezone)) {
var errorCode = "40009";
var errorMessage = "timezone contains unexpected data";
context.setVariable("http.reasonPhrase", "BAD REQUEST");
context.setVariable("http.statusCode", "400");
context.setVariable("log.severity", "Error");
errorHandling.push({
errorCode : errorCode,
errorMessage : errorMessage
});
}
}
//enum values check
if (preferredChannel !== null && preferredChannel !== "") {
if (!notiChannelEnum[preferredChannel]) {
var errorCode = "40009";
var errorMessage = "preferredChannel contains unexpected data";
context.setVariable("http.reasonPhrase", "BAD REQUEST");
context.setVariable("http.statusCode", "400");
context.setVariable("log.severity", "Error");
errorHandling.push({
errorCode : errorCode,
errorMessage : errorMessage
});
}
}
if (optIn !== null && optIn !== "") {
if (!booleanEnum[optIn]) {
var errorCode = "40009";
var errorMessage = "optIn contains unexpected data";
context.setVariable("http.reasonPhrase", "BAD REQUEST");
context.setVariable("http.statusCode", "400");
context.setVariable("log.severity", "Error");
errorHandling.push({
errorCode : errorCode,
errorMessage : errorMessage
});
}
}
if (isEmailValid !== null && isEmailValid !== "") {
if (!booleanEnum[isEmailValid]) {
var errorCode = "40009";
var errorMessage = "isEmailValid contains unexpected data";
context.setVariable("http.reasonPhrase", "BAD REQUEST");
context.setVariable("http.statusCode", "400");
context.setVariable("log.severity", "Error");
errorHandling.push({
errorCode : errorCode,
errorMessage : errorMessage
});
}
}
if (isMobileValid !== null && isMobileValid !== "") {
if (!booleanEnum[isMobileValid]) {
var errorCode = "40009";
var errorMessage = "isMobileValid contains unexpected data";
context.setVariable("http.reasonPhrase", "BAD REQUEST");
context.setVariable("http.statusCode", "400");
context.setVariable("log.severity", "Error");
errorHandling.push({
errorCode : errorCode,
errorMessage : errorMessage
});
}
}
// mandatory fields check for Add user details
if((reqUri == "/gnf/users/details") && (verb == "POST")) {
arrayMandatory.push({
type: "email",
value: email
});
arrayMandatory.push({
type: "userName",
value: userName
});
arrayMandatory.push({
type: "userStatus",
value: userStatus
});
/* arrayMandatory.push({
type: "createdBy",
value: createdBy
});*/
arrayMandatory.push({
type: "userEmail",
value: userEmail
});
//manadtory check function call
mandatoryCheck(arrayMandatory);
}
print("aaaa"+reqUri);
// mandatory fields check for update user details
if((reqUri == "/gnf/users/details") && (verb == "PUT")) {
arrayMandatory.push({
type: "email",
value: email
});
arrayMandatory.push({
type: "userId",
value: userId
});
arrayMandatory.push({
type: "userName",
value: userName
});
arrayMandatory.push({
type: "userStatus",
value: userStatus
});
/* arrayMandatory.push({
type: "modifiedBy",
value: modifiedBy
}); */
arrayMandatory.push({
type: "userEmail",
value: userEmail
});
//manadtory check function call
mandatoryCheck(arrayMandatory);
}
// mandatory fields check for Add user notification preferences
if((reqUri == "/gnf/users/notification/preference") && (verb == "POST")){
arrayMandatory.push({
type: "userId",
value: userId
});
/*arrayMandatory.push({
type: "createdBy",
value: createdBy
});*/
arrayMandatory.push({
type: "preferredChannel",
value: preferredChannel
});
arrayMandatory.push({
type: "userEmail",
value: userEmail
});
//manadtory check function call
mandatoryCheck(arrayMandatory);
}
// mandatory fields check for Update user notification preferences
if((reqUri == "/gnf/users/notification/preference") && (verb == "PUT")){
arrayMandatory.push({
type: "userId",
value: userId
});
/* arrayMandatory.push({
type: "modifiedBy",
value: modifiedBy
});*/
arrayMandatory.push({
type: "preferredChannel",
value: preferredChannel
});
arrayMandatory.push({
type: "userEmail",
value: userEmail
});
//manadtory check function call
mandatoryCheck(arrayMandatory);
}
// mandatory fields check for Add user preferences
if((reqUri == "/gnf/users/preferences") && (verb == "POST")){
arrayMandatory.push({
type: "userId",
value: userId
});
arrayMandatory.push({
type: "createdBy",
value: createdBy
});
arrayMandatory.push({
type: "userEmail",
value: userEmail
});
//manadtory check function call
mandatoryCheck(arrayMandatory);
}
// mandatory fields check for Update user preferences
if((reqUri == "/gnf/users/preferences") && (verb == "PUT")){
arrayMandatory.push({
type: "userId",
value: userId
});
/* arrayMandatory.push({
type: "modifiedBy",
value: modifiedBy
});*/
arrayMandatory.push({
type: "userEmail",
value: userEmail
});
//manadtory check function call
mandatoryCheck(arrayMandatory);
}
// mandatory check function
if(mandate_var_list.length > 0){
var errorCode = "40008";
var errorMessage = "Request expects the following fields "+ mandate_var_list;
context.setVariable("http.reasonPhrase", "BAD REQUEST");
context.setVariable("http.statusCode", "400");
context.setVariable("log.severity", "Error");
errorHandling.unshift({
errorCode : errorCode,
errorMessage : errorMessage
});
}
function mandatoryCheck(arrayMandatory) {
for (var i = 0; i < arrayMandatory.length; i++){
if (arrayMandatory[i].value === null || arrayMandatory[i].value === "" || arrayMandatory[i].value.length < 1) {
mandate_var_list.push(arrayMandatory[i].type);
}
}
}
//setting the check to invoke raise fault
if(errorHandling.length>0)
{
print(errorHandling.length);
context.setVariable("isError", "true");
context.setVariable("flow.error.code",JSON.stringify(errorHandling));
}<file_sep>/apiproxies/equifax/apiproxy/resources/jsc/setSecurity.js
context.setVariable("_SF_Default-Security-Policies.apikey","true");
//context.setVariable("_SF_Default_Security-Policies.all","true");
context.setVariable("_SF_Default-Security-Policies.sqlProtection","true");
context.setVariable("_SF_Default-Security-Policies.jsonValid","true");
<file_sep>/apiproxies/tokenization/apiproxy/resources/jsc/validateData.js
// get all input variables for validation
var mid = context.getVariable("mid");
var pan = context.getVariable("private.pan");
var tnumber = context.getVariable("private.tnumber");
var path = context.getVariable("proxy.pathsuffix");
// regex varaible
var letters = /^[0-9a-zA-Z]+$/;
var numbers = /^[0-9]*$/;
var year = /^(19[0-8][0-9]|199[0-9]|[2-9][0-9]{3})$/;
var month = /^(0[1-9]|1[0-2])$/;
var reLetter = new RegExp(letters);
var reNumber = new RegExp(numbers);
var re_mid = reLetter.exec(mid);
var re_pan = reNumber.exec(pan);
var re_tnumber = reLetter.exec(tnumber);
// intialize validate variables
var validPayload = "false";
// validate payload attributes as per pathsuffix
if (path == "/merchant/number") {
if ((mid !== null)
&& (mid !== "")
&& (re_mid)
&& (pan !== null)
&& (pan !== "")
&& (pan.length < 27)
&& (pan.length > 1)
&& (re_pan)
) {
validPayload = "true";
}
} else if (path == "/number") {
if ((mid !== null)
&& (mid !== "")
&& (re_mid)
&& (pan !== null)
&& (pan !== "")
&& (pan.length < 27)
&& (pan.length > 1)
&& (re_pan)) {
validPayload = "true";
}
}else if (path == "/global/number") {
if ((pan !== null)
&& (pan !== "")
&& (pan.length < 27)
&& (pan.length > 1)
&& (re_pan)) {
validPayload = "true";
}
}
else if (path == "/token") {
if ((tnumber !== null) && (tnumber !== "") && (re_tnumber)) {
validPayload = "true";
}
}
if(validPayload == "false"){
context.setVariable("validPayload", validPayload);
context.setVariable("errortype", "Bad Request");
context.setVariable("errorCode", "400");
}
<file_sep>/apiproxies/equifax/apiproxy/resources/jsc/setRequestForCreditReport.js
// Set Request for Credit Report
var xmlRequest= context.getVariable("xmlvar") + context.getVariable("request.content");
context.setVariable("request.content", xmlRequest);
<file_sep>/apiproxies/equifax/apiproxy/resources/jsc/createResponse.js
// Preparing response for Credit Report
var inputResponse = context.getVariable("response.content");
var creditReportResponse = JSON.parse(inputResponse);
<file_sep>/apiproxies/tokenization/apiproxy/resources/jsc/removePathsuffix.js
// Removing path suffix before sending it to backend system
context.setVariable('target.copy.pathsuffix', false);
<file_sep>/apiproxies/gnf-api/apiproxy/resources/jsc/skipVerifyOtpLogic.js
var reqUri = context.getVariable("proxy.pathsuffix");
if(reqUri.indexOf("/users/otp") > -1)
{
context.setVariable("skipOtpVerify", "true");
}<file_sep>/apiproxies/equifax/apiproxy/resources/jsc/verbValidation.js
var incomingVerb = context.getVariable("request.verb");
var validateMethod;
if (incomingVerb == "POST" || incomingVerb == "OPTIONS" )
{
validateMethod = "true" ;
}
else{
validateMethod = "false";
}
context.setVariable('validateMethod' , validateMethod);<file_sep>/apiproxies/gnf-api/apiproxy/resources/jsc/applicationManagementValidator.js
//GNF:Validations on Application management
var applicationId = context.getVariable("aId");
var groupId = context.getVariable("gId");
var userId = context.getVariable("uId");
var applicationName = context.getVariable("appName");
var userEmail = context.getVariable("userEmail");
var applicationStatus = context.getVariable("appStatus");
/*var createdBy = context.getVariable("createdBy");*/
var isDeleted = context.getVariable("isDeleted");
/*var modifiedBy = context.getVariable("modifiedBy");*/
var isAppPrefValidJson = true;
var errorHandling = [];
//checking applicationPreference has valid json
try {
var applicationPreference = JSON.parse(context.getVariable("appPref"));
}catch (e) {
isAppPrefValidJson = false ;
print("Error:"+e);
var errorCode = "40009";
var errorMessage = "applicationPreference contains unexpected data";
context.setVariable("http.reasonPhrase", "BAD REQUEST");
context.setVariable("http.statusCode", "400");
context.setVariable("log.severity", "Error");
errorHandling.push({
errorCode : errorCode,
errorMessage : errorMessage
});
}
//regex declarations
var mail = /^\w+([\.-]?\w+)+@\w+([\.:]?\w+)+(\.[a-zA-Z0-9]{2,3})+$/;
var alpahbets = /^[a-zA-Z]*$/;
var numbers = /^[0-9]*$/;
var reEmail = new RegExp(mail);
var reAlphs = new RegExp(alpahbets);
var reNumbers = new RegExp(numbers);
//applying regex on input params
var re_appId = reNumbers.test(applicationId);
var re_groupId = reNumbers.test(groupId);
var re_userId = reNumbers.test(userId);
/*var re_createdBy = reNumbers.test(createdBy);
var re_modifiedBy = reNumbers.test(modifiedBy);*/
var re_isDeleted = reNumbers.test(isDeleted);
var re_appName = reAlphs.test(applicationName);
var re_userEmail = reEmail.test(userEmail);
var re_appStatus = reAlphs.test(applicationStatus);
//getting incomming verb and request uri
var verb = context.getVariable("request.verb");
var reqUri = context.getVariable("request.uri");
//mandatory check for User Email field
if(verb !== "POST" || verb !== "PUT")
{
//mandatory field check for input variables
if (userEmail === null || userEmail === "") {
if (!(re_userEmail)) {
var errorCode = "40008";
var errorMessage = "Request expects the following fields User Email";
context.setVariable("http.reasonPhrase", "BAD REQUEST");
context.setVariable("http.statusCode", "400");
context.setVariable("log.severity", "Error");
errorHandling.push({
errorCode : errorCode,
errorMessage : errorMessage
});
}
}
}
//number check for input variables
if (applicationId !== null && applicationId !== "" && applicationId !== undefined) {
if ((!(re_appId)) || (applicationId <= 0)) {
var errorCode = "40009";
var errorMessage = "applicationId contains unexpected data";
context.setVariable("http.reasonPhrase", "BAD REQUEST");
context.setVariable("http.statusCode", "400");
context.setVariable("log.severity", "Error");
errorHandling.push({
errorCode : errorCode,
errorMessage : errorMessage
});
}
}
if (groupId !== null && groupId !== "" && groupId !== undefined) {
if (!(groupId.includes("users")))
{
if ((!(re_groupId)) || (groupId <= 0)) {
var errorCode = "40009";
var errorMessage = "groupId contains unexpected data";
context.setVariable("http.reasonPhrase", "BAD REQUEST");
context.setVariable("http.statusCode", "400");
context.setVariable("log.severity", "Error");
errorHandling.push({
errorCode : errorCode,
errorMessage : errorMessage
});
}
}
}
if (userId !== null && userId !== "" && userId !== undefined) {
if ((!(re_userId)) || (userId <= 0)) {
var errorCode = "40009";
var errorMessage = "userId contains unexpected data";
context.setVariable("http.reasonPhrase", "BAD REQUEST");
context.setVariable("http.statusCode", "400");
context.setVariable("log.severity", "Error");
errorHandling.push({
errorCode : errorCode,
errorMessage : errorMessage
});
}
}
/*if (createdBy !== null && createdBy !== "" && createdBy !== undefined) {
if ((!(re_createdBy)) || createdBy <= 0 ) {
var errorCode = "40009";
var errorMessage = "createdBy contains unexpected data";
context.setVariable("http.reasonPhrase", "BAD REQUEST");
context.setVariable("http.statusCode", "400");
context.setVariable("log.severity", "Error");
errorHandling.push({
errorCode : errorCode,
errorMessage : errorMessage
});
}
}
if (modifiedBy !== null && modifiedBy !== "" && modifiedBy !== undefined) {
if ((!(re_modifiedBy)) || modifiedBy <= 0 ) {
var errorCode = "40009";
var errorMessage = "modifiedBy contains unexpected data";
context.setVariable("http.reasonPhrase", "BAD REQUEST");
context.setVariable("http.statusCode", "400");
context.setVariable("log.severity", "Error");
errorHandling.push({
errorCode : errorCode,
errorMessage : errorMessage
});
}
}*/
if (isDeleted !== null && isDeleted !== "" && isDeleted !== undefined) {
if (!(re_isDeleted)) {
var errorCode = "40009";
var errorMessage = "isDeleted contains unexpected data";
context.setVariable("http.reasonPhrase", "BAD REQUEST");
context.setVariable("http.statusCode", "400");
context.setVariable("log.severity", "Error");
errorHandling.push({
errorCode : errorCode,
errorMessage : errorMessage
});
}
}
//Alphabets Check
if (applicationName !== null && applicationName !== "" && applicationName !== undefined) {
if (!(re_appName)) {
var errorCode = "40009";
var errorMessage = "applicationName contains unexpected data";
context.setVariable("http.reasonPhrase", "BAD REQUEST");
context.setVariable("http.statusCode", "400");
context.setVariable("log.severity", "Error");
errorHandling.push({
errorCode : errorCode,
errorMessage : errorMessage
});
}
}
if (applicationStatus !== null && applicationStatus !== "" && applicationStatus !== undefined) {
if (!(re_appStatus)) {
var errorCode = "40009";
var errorMessage = "applicationStatus contains unexpected data";
context.setVariable("http.reasonPhrase", "BAD REQUEST");
context.setVariable("http.statusCode", "400");
context.setVariable("log.severity", "Error");
errorHandling.push({
errorCode : errorCode,
errorMessage : errorMessage
});
}
}
//Email Check
if (userEmail !== null && userEmail !== "" && userEmail !== undefined) {
if (!(re_userEmail)) {
var errorCode = "40009";
var errorMessage = "User Email contains unexpected data";
context.setVariable("http.reasonPhrase", "BAD REQUEST");
context.setVariable("http.statusCode", "400");
context.setVariable("log.severity", "Error");
errorHandling.push({
errorCode : errorCode,
errorMessage : errorMessage
});
}
}
//mandatory check array declarations
var arrayMandatory = [];
var mandate_var_list = [];
// mandatory fields check for create application
if((reqUri == "/gnf/applications") && (verb == "POST"))
{
arrayMandatory.push({
type: "applicationName",
value: applicationName
});
arrayMandatory.push({
type: "userEmail",
value: userEmail
});
if(isAppPrefValidJson){
arrayMandatory.push({
type: "applicationPreference",
value: applicationPreference
});
}
//manadtory check function call
mandatoryCheck(arrayMandatory);
}
// mandatory fields check for update application
if((reqUri == "/gnf/applications") && (verb == "PUT"))
{
arrayMandatory.push({
type: "applicationId",
value: applicationId
});
arrayMandatory.push({
type: "applicationName",
value: applicationName
});
arrayMandatory.push({
type: "userEmail",
value: userEmail
});
if(isAppPrefValidJson){
arrayMandatory.push({
type: "applicationPreference",
value: applicationPreference
});
}
//manadtory check function call
mandatoryCheck(arrayMandatory);
}
// mandatory check function
if(mandate_var_list.length > 0){
var errorCode = "40008";
var errorMessage = "Request expects the following fields "+ mandate_var_list;
context.setVariable("http.reasonPhrase", "BAD REQUEST");
context.setVariable("http.statusCode", "400");
context.setVariable("log.severity", "Error");
errorHandling.unshift({
errorCode : errorCode,
errorMessage : errorMessage
});
}
function mandatoryCheck(arrayMandatory) {
for (var i = 0; i < arrayMandatory.length; i++){
if (arrayMandatory[i].value === null || arrayMandatory[i].value === "" || arrayMandatory[i].value.length < 1) {
mandate_var_list.push(arrayMandatory[i].type);
}
}
}
//setting the check to invoke raise fault
if(errorHandling.length>0)
{
print(errorHandling.length);
context.setVariable("isError", "true");
context.setVariable("flow.error.code",JSON.stringify(errorHandling));
}<file_sep>/apiproxies/gnf-api/apiproxy/resources/jsc/setStackdriverLogMessage.js
var gnf_ReqHeaders = JSON.parse( JSON.stringify(context.proxyRequest.headers) ) ;
//removing Authorization Header
if(gnf_ReqHeaders.hasOwnProperty("Authorization")){
delete gnf_ReqHeaders.Authorization;
}
if(gnf_ReqHeaders.hasOwnProperty("authorization")){
delete gnf_ReqHeaders.authorization;
}
//removing Apikey Header
if(gnf_ReqHeaders.hasOwnProperty("Apikey")){
delete gnf_ReqHeaders.Apikey;
}
if(gnf_ReqHeaders.hasOwnProperty("apikey")){
delete gnf_ReqHeaders.apikey;
}
if(gnf_ReqHeaders.hasOwnProperty("APIKEY")){
delete gnf_ReqHeaders.APIKEY;
}
if(gnf_ReqHeaders.hasOwnProperty("client_id")){
delete gnf_ReqHeaders.client_id;
}
if(gnf_ReqHeaders.hasOwnProperty("client_secret")){
delete gnf_ReqHeaders.client_secret;
}
// set Apikey to log to Stackdriver
var requestApikey = context.getVariable("apigee.client_id");
var gnf_ReqApikey = "";
gnf_ReqApikey = redactField(requestApikey) ;
context.setVariable("gnf_ReqApikey", gnf_ReqApikey);
// get all the Request headers and log it to Stackdriver
context.setVariable("gnf_ReqHeaders", gnf_ReqHeaders);
//redacting logic
function redactField(sensitiveField){
var first2 = "";
var last4 = "";
var remainingToMask = "";
var redacted_field_first2_last4 = "";
if(sensitiveField !== null && sensitiveField !== "" && sensitiveField !== undefined && sensitiveField.replace(/\s/g, '').length !== 0){
first2 = sensitiveField.substring(0,2);
last4 = sensitiveField.substring(sensitiveField.length - 4, sensitiveField.length);
remainingToMask = sensitiveField.substring(2,sensitiveField.length-4) ;
redacted_field_first2_last4 = first2 + Array(remainingToMask.length + 1).join("X") + last4 ;
return redacted_field_first2_last4;
}
else return "N/A";
}
/*
//redacting Apikey in headers
var apikeyIsPresent = gnf_ReqHeaders.hasOwnProperty("Apikey") || gnf_ReqHeaders.hasOwnProperty("apikey") || gnf_ReqHeaders.hasOwnProperty("APIKEY") ;
var apikeyValue = gnf_ReqHeaders["Apikey"] || gnf_ReqHeaders["apikey"] || gnf_ReqHeaders["APIKEY"] ;
if( apikeyIsPresent ){
// replace with redacted "Apikey"
gnf_ReqHeaders["Apikey"] = redactField(apikeyValue) ;
}*/<file_sep>/apiproxies/gnf-api/apiproxy/resources/jsc/setSecurity.js
/* Enabling the Oauth security for the incoming requests basing on the uri */
var reqUri = context.getVariable("proxy.pathsuffix");
var verb = context.getVariable("request.verb");
var enableSecurity = "false";
/* Enabling the required shared flow variables, oauth and source validation done in gnf proxy */
context.setVariable("_SF_Default-Security-Policies.sqlProtection","true");
context.setVariable("_SF_Default-Security-Policies.jsonValid","true");
if(reqUri != "/serviceproviders"){
context.setVariable("_SF_Default-Security-Policies.jsonProtection","true");
}
if (((reqUri == "/notify") || (reqUri == "/notify/publisher") || (reqUri == "/status") || (reqUri == "/notification/cancel") || (reqUri.startsWith("/applications"))|| (reqUri.startsWith("/groups")) || (reqUri == "/roles/user**") || (reqUri == "/configurations**") || (reqUri == "/logs**") || (reqUri == "/serviceproviders") ) && (verb != "OPTIONS")){
enableSecurity = "true";
context.setVariable("enableSecurity",enableSecurity);
}
//generating global transaction Id if it is not comming in the request
var gid = context.getVariable("gid");
if (gid !== "" && gid !== null && gid !== undefined && request.verb != "OPTIONS"){
context.setVariable("request.header.x_global_transaction_id",context.getVariable("gid") );
}
else if(request.verb != "OPTIONS"){
context.setVariable("request.header.x_global_transaction_id",context.getVariable("messageid") );
}
// extracting session_id if available in request header
var req_session_id = context.getVariable("request.header.session_id");
if( req_session_id !== null && req_session_id !== '' && req_session_id !== undefined )
context.setVariable("req_session_id", req_session_id);
<file_sep>/apiproxies/equifax/apiproxy/resources/jsc/setError.js
var fault = context.getVariable("fault.name");
if (fault!== null){
context.setVariable("flow.error.status", context.getVariable("message.status.code"));
context.setVariable("flow.error.reason", fault );
context.setVariable("flow.error.message", fault);
context.setVariable("flow.log.severity", "Error");
}<file_sep>/apiproxies/equifax/apiproxy/resources/jsc/requestValidation.js
//Preparing request based on the request content and flow(Credit Report)
var jsonRequest = JSON.parse(context.getVariable("request.content"));
var xmlvar = '<?xml version="1.0" encoding="utf-8"?>';
context.setVariable("xmlvar",xmlvar);
var contentType = context.getVariable("request.header.Content-Type");
context.setVariable("contentType",contentType);
var isCommercial = false;
try{
var cnRequests = jsonRequest.CNRequests;
if(cnRequests !== null && (!(cnRequests === undefined))){
var cnCustomerInfo = jsonRequest.CNCustomerInfo;
var customerCode = cnCustomerInfo.CustomerCode;
var customerNumber = cnCustomerInfo.CustomerInfo.CustomerNumber;
var securityCode = cnCustomerInfo.CustomerInfo.SecurityCode;
var customerId = cnCustomerInfo.CustomerId;
context.setVariable("customerCode",customerCode);
context.setVariable("customerNumber",customerNumber);
context.setVariable("securityCode",securityCode);
context.setVariable("customerId",customerId);
if(cnRequests.CNConsumerRequests)
{
var subjects = cnRequests.CNConsumerRequests.CNConsumerRequest.Subjects;
var subject = subjects.Subject;
var subjectType = subjects.Subject.subjectType;
var lastName = subject.SubjectName.LastName;
var firstName = subject.SubjectName.FirstName;
var socialInsuranceNumber = subject.SocialInsuranceNumber;
var dateOfBirth = subject.DateOfBirth;
var occupation = subject.Occupation;
var address = subjects.Addresses.Address;
var civicNumber = address.CivicNumber;
var streetName = address.StreetName;
var city = address.City;
var province = address.Province;
var code = province.code;
var description = province.description;
var postalCode = address.PostalCode;
context.setVariable("subjectType",subjectType);
context.setVariable("lastName",lastName);
context.setVariable("firstName",firstName);
context.setVariable("socialInsuranceNumber",socialInsuranceNumber);
context.setVariable("dateOfBirth",dateOfBirth);
context.setVariable("occupation",occupation);
context.setVariable("civicNumber",civicNumber);
context.setVariable("streetName",streetName);
context.setVariable("city",city);
context.setVariable("code",code);
context.setVariable("description",description);
context.setVariable("postalCode",postalCode);
var customerReferenceNumber = cnRequests.CNConsumerRequests.CNConsumerRequest.CustomerReferenceNumber;
var ecoaInquiryType = cnRequests.CNConsumerRequests.CNConsumerRequest.ECOAInquiryType;
var jointAccessIndicator = cnRequests.CNConsumerRequests.CNConsumerRequest.JointAccessIndicator;
var language = cnRequests.CNOutputParameters.Language;
var outputParameterType = cnRequests.CNOutputParameters.OutputParameter.outputParameterType;
var genericOutputCode = cnRequests.CNOutputParameters.OutputParameter.GenericOutputCode;
context.setVariable("customerReferenceNumber",customerReferenceNumber);
context.setVariable("ecoaInquiryType",ecoaInquiryType);
context.setVariable("jointAccessIndicator",jointAccessIndicator);
context.setVariable("language",language);
context.setVariable("outputParameterType",outputParameterType);
context.setVariable("genericOutputCode",genericOutputCode);
}else if(cnRequests.CNCommercialRequest){
var firmName = cnRequests.CNCommercialRequest.FirmName;
var fileNumber = cnRequests.CNCommercialRequest.FileNumber;
var address = cnRequests.CNCommercialRequest.Addresses.Address;
var civicNumber = address.CivicNumber;
var streetName = address.StreetName;
var city = address.City;
var province = address.Province;
var code = province.code;
var postalCode = address.PostalCode;
var parsedTelephone = cnRequests.CNCommercialRequest.ParsedTelephones.ParsedTelephone;
//var parsedTelephone = parsedTelephones.ParsedTelephone;
var areaCode = parsedTelephone.AreaCode;
var phnumber = parsedTelephone.Number;
var extension = parsedTelephone.Extension;
context.setVariable("firmName",firmName);
context.setVariable("fileNumber",fileNumber);
context.setVariable("civicNumber",civicNumber);
context.setVariable("streetName",streetName);
context.setVariable("city",city);
context.setVariable("code",code);
context.setVariable("postalCode",postalCode);
context.setVariable("parsedTelephone",parsedTelephone);
context.setVariable("areaCode",areaCode);
context.setVariable("phnumber",phnumber);
context.setVariable("extension",extension);
var cnOutputParameters = cnRequests.CNOutputParameters;
var language = cnOutputParameters.Language;
var outputParameterType = cnOutputParameters.OutputParameter.outputParameterType;
var genericOutputCode = cnOutputParameters.OutputParameter.GenericOutputCode;
var customizationCode = cnOutputParameters.OutputParameter.CustomizationCode;
context.setVariable("language",language);
context.setVariable("outputParameterType",outputParameterType);
context.setVariable("genericOutputCode",genericOutputCode);
context.setVariable("customizationCode",customizationCode);
isCommercial = true;
}
context.setVariable("isCommercial",isCommercial);
context.setVariable("CreditReport","CreditReport");
}
}catch(err)
{
throw err;
}
<file_sep>/apiproxies/gnf-api/apiproxy/resources/jsc/removeKeys.js
var b1 = JSON.parse(response.content),
propertiesToRemove = ['refresh_token_expires_in', 'api_product_list',
'api_product_list_json', 'application_name',
'refresh_count'];
propertiesToRemove.forEach(function(item){
delete b1[item];
});
// if there is no refresh token, don't keep properties related to it:
/*if( ! b1.refresh_token ) {
delete b1.refresh_token_expires_in;
delete b1.refresh_count;
}*/
context.setVariable('response.content', JSON.stringify(b1, null, 2));<file_sep>/apiproxies/gnf-api/apiproxy/resources/jsc/validateProvider.js
context.setVariable("provider", context.getVariable("request.header.provider_name"));<file_sep>/apiproxies/gnf-api/apiproxy/resources/jsc/inputValidator.js
//input validations
var sourceId = context.getVariable("sid");
var sourceTransactionId = context.getVariable("sourceTxnId");
var globalTransactionId = context.getVariable("gid");
var alphaNumeric = /^[0-9a-zA-Z]+$/;
var alpahbets = /^[a-zA-Z]*$/;
var numbers = /^[0-9]*$/;
var reAlpNum = new RegExp(alphaNumeric);
var reAlphs = new RegExp(alpahbets);
var reNumbers = new RegExp(numbers);
var re_sid = reNumbers.test(sourceId);
var re_sTxnId = reAlpNum.test(sourceTransactionId);
var errorHandling = [];
var source_fields = [sourceId, sourceTransactionId];
if (globalTransactionId === "" || globalTransactionId === null ) {
if (!isAnyObjectNull(source_fields)) {
var errorCode = "4008";
var errorMessage = "Request expects the following fields sourceTransactionId,sourceId";
context.setVariable("http.reasonPhrase", "BAD REQUEST");
context.setVariable("http.statusCode", "400");
errorHandling.push({
errorCode : errorCode,
errorMessage : errorMessage
});
}
}
//function checks if any field is null for manual fields
function isAnyObjectNull(items) {
is_mandate = false;
if (items !== null) {
for (var j = 0; j < items.length; j++) {
if (items[j] === null || items[j] === "") {
is_mandate = false;
break;
} else {
is_mandate = true;
}
}
}
return is_mandate;
}
//number check for input variables
if (sourceId !== null && sourceId !== "" && sourceId !== undefined) {
if (!(re_sid)) {
var errorCode = "4009";
var errorMessage = "SourceId contains unexpected data";
context.setVariable("http.reasonPhrase", "BAD REQUEST");
context.setVariable("http.statusCode", "400");
context.setVariable("log.severity", "Error");
errorHandling.push({
errorCode : errorCode,
errorMessage : errorMessage
});
}
}
//Alphanumeric Check
if (sourceTransactionId !== null && sourceTransactionId !== "" && sourceTransactionId !== undefined) {
if (!(re_sTxnId)) {
var errorCode = "4009";
var errorMessage = "sourceTransactionId contains unexpected data";
context.setVariable("http.reasonPhrase", "BAD REQUEST");
context.setVariable("http.statusCode", "400");
context.setVariable("log.severity", "Error");
errorHandling.push({
errorCode : errorCode,
errorMessage : errorMessage
});
}
}
//setting the check to invoke raise fault
if(errorHandling.length>0)
{
print(errorHandling.length);
context.setVariable("isError", "true");
context.setVariable("flow.error.code",JSON.stringify(errorHandling));
}
<file_sep>/apiproxies/tokenization/apiproxy/resources/jsc/logMidToStackDriver.js
//logging mid parameter to stackdriver
var mid = context.getVariable('mid');
context.setVariable('tokenization_mid',mid); | 80a1e011c5f21fb1a9196f609a8c0e1b7ca4dbe2 | [
"JavaScript"
]
| 21 | JavaScript | indrajitp/deletethis | 5b4a42cfe07600ec9245e5587c22332d0302e354 | f3ffb621ed70b20a6e09826d446636629e58c130 |
refs/heads/main | <repo_name>Chanchit1516/dotnet-101<file_sep>/DotNet-101.Api/Controllers/ProductController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using DotNet_101.Core.Entities;
using DotNet_101.Core.Interfaces.Service;
using DotNet_101.Infrastructure.Data;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
namespace DotNet_101.Api.Controllers
{
[Route("api/v1/[controller]/[action]")]
public class ProductController : Controller
{
private readonly ApplicationDbContext _context;
IProductService _productService;
public ProductController(IProductService productService, ApplicationDbContext context)
{
_productService = productService;
_context = context;
}
[HttpGet]
public async Task<IActionResult> GetAllProduct()
{
var productModel = await _productService.GetAllProduct();
return Ok(productModel);
}
[HttpGet]
public IActionResult InsertProduct()
{
var product = new Product();
product.ProductName = "Pencil";
product.UnitPrice = 10;
product.UnitsInStock = 100;
product.UpdatedBy = 1;
_context.Products.Add(product);
_context.SaveChanges();
return Ok();
}
}
}
<file_sep>/DotNet-101.Core/DTOs/BaseDTO.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace DotNet_101.Core.DTOs
{
public class BaseDTO
{
public DateTime CreatedDateTime { get; set; }
public int CreatedBy { get; set; }
public int? UpdatedBy { get; set; }
public DateTime? UpdatedDateTime { get; set; }
}
}
<file_sep>/DotNet-101.Core/Mapper/DTOMapper.cs
using AutoMapper;
using DotNet_101.Core.DTOs;
using DotNet_101.Core.Entities;
using System;
using System.Collections.Generic;
using System.Text;
namespace DotNet_101.Core.Mapper
{
public class DTOMapper : Profile
{
public DTOMapper()
{
CreateMap<Product, ProductViewModel>().ReverseMap();
}
}
}
<file_sep>/DotNet-101.Infrastructure/Data/ApplicationDbContext.cs
using DotNet_101.Core.Entities;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace DotNet_101.Infrastructure.Data
{
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext(DbContextOptions options) : base(options)
{
}
public DbSet<Product> Products { get; set; }
public DbSet<Order> Orders { get; set; }
public DbSet<Customer> Customers { get; set; }
public DbSet<OrderDetail> OrderDetails { get; set; }
}
}
<file_sep>/DotNet-101.Api/Startup.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AutoMapper;
using DotNet_101.Core.IoC;
using DotNet_101.Core.Mapper;
using DotNet_101.Infrastructure.Data;
using DotNet_101.Infrastructure.IoC;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace DotNet_101.Api
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(option =>
{
option.UseSqlServer(@"Data Source=DESKTOP-URTA846\SQLEXPRESS;Database=developmentDb;User ID=sa;Password=<PASSWORD>;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False");
});
services.AddControllers();
// Auto Mapper Configurations
var mapperConfig = new MapperConfiguration(mc =>
{
mc.AddProfile(new DTOMapper());
});
IMapper mapper = mapperConfig.CreateMapper();
services.RegisterCoreServices();
services.RegisterInfrastructureServices();
services.AddSingleton(mapper);
services.AddMvc();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}
<file_sep>/DotNet-101.Core/Entities/Order.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace DotNet_101.Core.Entities
{
public class Order
{
public Order()
{
OrderDetail = new List<OrderDetail>();
}
public int OrderId { get; set; }
public DateTime OrderDate { get; set; }
public DateTime ShippedDate { get; set; }
public int ShippedId { get; set; }
public Customer Customer { get; set; }
public int CustomerId { get; set; }
public virtual ICollection<OrderDetail> OrderDetail { get; }
}
}
<file_sep>/DotNet-101.Core/Entities/OrderDetail.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace DotNet_101.Core.Entities
{
public class OrderDetail
{
public int OrderDetailId { get; set; }
public Order Order { get; set; }
public int OrderId { get; set; }
public Product Product { get; set; }
public int ProductId { get; set; }
public decimal UnitPrice { get; set; }
public decimal Discount { get; set; }
public int Qty { get; set; }
}
}
<file_sep>/DotNet-101.Infrastructure/Data/Config/OrderDetailConfiguration.cs
using DotNet_101.Core.Entities;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using System;
using System.Collections.Generic;
using System.Text;
namespace DotNet_101.Infrastructure.Data.Config
{
public class OrderDetailConfiguration : IEntityTypeConfiguration<OrderDetail>
{
public void Configure(EntityTypeBuilder<OrderDetail> builder)
{
builder.HasKey(m => new { m.OrderId, m.ProductId });
builder.HasIndex(m => m.ProductId);
builder
.HasOne(m => m.Order)
.WithMany(m => m.OrderDetail)
.HasForeignKey(m => m.OrderId);
builder
.HasOne(m => m.Product)
.WithMany()
.HasForeignKey(m => m.ProductId);
}
}
}
<file_sep>/DotNet-101.Infrastructure/Data/Config/OrderConfiguration.cs
using DotNet_101.Core.Entities;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using System;
using System.Collections.Generic;
using System.Text;
namespace DotNet_101.Infrastructure.Data.Config
{
public class OrderConfiguration : IEntityTypeConfiguration<Order>
{
public void Configure(EntityTypeBuilder<Order> builder)
{
builder.HasKey(m => m.OrderId);
builder.HasOne(m => m.Customer)
.WithMany(m => m.Order)
.HasForeignKey(m => m.CustomerId);
}
}
}
<file_sep>/DotNet-101.Core/Interfaces/Repository/IProductRepository.cs
using DotNet_101.Core.Entities;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace DotNet_101.Core.Interfaces.Repository
{
public interface IProductRepository
{
Task<List<Product>> GetAllProduct();
}
}
<file_sep>/DotNet-101.Infrastructure/Data/Config/ProductConfiguration.cs
using DotNet_101.Core.Entities;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using System;
using System.Collections.Generic;
using System.Text;
namespace DotNet_101.Infrastructure.Data.Config
{
public class ProductConfiguration : IEntityTypeConfiguration<Product>
{
public void Configure(EntityTypeBuilder<Product> builder)
{
builder.HasKey(m => m.ProductId);
//builder.HasOne(m => m.Order).WithMany(m => m.Product).HasForeignKey(m => m.OrderId);
}
}
}
<file_sep>/DotNet-101.Infrastructure/Data/IApplicationDbContext.cs
//using DotNet_101.Core.Entities;
//using Microsoft.EntityFrameworkCore;
//using System.Threading.Tasks;
//namespace DotNet_101.Infrastructure.Data
//{
// public interface IApplicationDbContext
// {
// DbSet<Customer> Customers { get; set; }
// DbSet<Order> Orders { get; set; }
// DbSet<Product> Products { get; set; }
// }
//}<file_sep>/DotNet-101.Core/Entities/Customer.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace DotNet_101.Core.Entities
{
public class Customer : BaseEntity
{
public Customer()
{
Order = new List<Order>();
}
public int CustomerId { get; set; }
public string CompanyName { get; set; }
public string ContactTitle { get; set; }
public string Phone { get; set; }
public string Country { get; set; }
public virtual ICollection<Order> Order { get; }
}
}
<file_sep>/DotNet-101.Core/Services/ProductService.cs
using DotNet_101.Core.Entities;
using DotNet_101.Core.Interfaces;
using DotNet_101.Core.Interfaces.Repository;
using DotNet_101.Core.Interfaces.Service;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace DotNet_101.Core.Services
{
public class ProductService : IProductService
{
private IProductRepository _productRepository;
public ProductService(IProductRepository productRepository)
{
_productRepository = productRepository;
}
public async Task<List<Product>> GetAllProduct()
{
return await _productRepository.GetAllProduct();
}
}
}
<file_sep>/DotNet-101.Infrastructure/Data/ApplicationDbContextSeed.cs
//using DotNet_101.Core.Entities;
//using Microsoft.EntityFrameworkCore;
//using Microsoft.Extensions.Logging;
//using System;
//using System.Collections.Generic;
//using System.Linq;
//using System.Text;
//using System.Threading.Tasks;
//namespace DotNet_101.Infrastructure.Data
//{
// public class ApplicationDbContextSeed
// {
// public static async Task SeedAsync(ApplicationDbContext applicationContext, ILoggerFactory loggerFactory, int? retry = 0)
// {
// int retryForAvailability = retry.Value;
// try
// {
// // TODO: Only run this if using a real database
// applicationContext.Database.Migrate();
// applicationContext.Database.EnsureCreated();
// if (!applicationContext.Orders.Any())
// {
// applicationContext.Orders.AddRange(GetPreconfiguredCategories());
// await applicationContext.SaveChangesAsync();
// }
// if (!applicationContext.Products.Any())
// {
// applicationContext.Products.AddRange(GetPreconfiguredProducts());
// await applicationContext.SaveChangesAsync();
// }
// }
// catch (Exception exception)
// {
// if (retryForAvailability < 10)
// {
// retryForAvailability++;
// var log = loggerFactory.CreateLogger<ApplicationDbContextSeed>();
// log.LogError(exception.Message);
// await SeedAsync(applicationContext, loggerFactory, retryForAvailability);
// }
// throw;
// }
// }
// private static IEnumerable<Order> GetPreconfiguredCategories()
// {
// return new List<Order>()
// {
// new Order() { CustomerId = 1},
// new Order() { CustomerId = 2}
// };
// }
// private static IEnumerable<Product> GetPreconfiguredProducts()
// {
// return new List<Product>()
// {
// new Product() { ProductName = "IPhone" , UnitPrice = 19.5M , UnitsInStock = 10, UnitsOnOrder = 1 },
// new Product() { ProductName = "Samsung" , UnitPrice = 33.5M , UnitsInStock = 10, UnitsOnOrder = 1 },
// new Product() { ProductName = "LG TV" , UnitPrice = 33.5M , UnitsInStock = 10, UnitsOnOrder = 1}
// };
// }
// }
//}
<file_sep>/DotNet-101.Core/Entities/Product.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace DotNet_101.Core.Entities
{
public class Product : BaseEntity
{
public int ProductId { get; set; }
public string ProductName { get; set; }
public int UnitPrice { get; set; }
public int UnitsInStock { get; set; }
public int UnitsOnOrder { get; set; }
public string Barcode { get; set; }
public int OrderId { get; set; }
}
}
<file_sep>/DotNet-101.Core/Entities/BaseEntity.cs
using DotNet_101.SharedKernel.Helpers;
using System;
using System.Collections.Generic;
using System.Text;
namespace DotNet_101.Core.Entities
{
public class BaseEntity
{
public BaseEntity()
{
CreatedDateTime = DateTimeHelper.Now();
}
public DateTime CreatedDateTime { get; set; }
public int CreatedBy { get; set; }
public int? UpdatedBy { get; set; }
public DateTime? UpdatedDateTime { get; set; }
}
}
<file_sep>/DotNet-101.SharedKernel/Helpers/DateTimeHelper.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace DotNet_101.SharedKernel.Helpers
{
public static class DateTimeHelper
{
public static DateTime Now()
{
return DateTime.Now;
}
public static DateTime UtcNow()
{
return DateTime.UtcNow;
}
}
}
<file_sep>/DotNet-101.Infrastructure/IoC/ServiceModuleExtentions.cs
using DotNet_101.Core.Interfaces.Repository;
using DotNet_101.Infrastructure.SqlServer;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Text;
namespace DotNet_101.Infrastructure.IoC
{
public static class ServiceModuleExtentions
{
public static void RegisterInfrastructureServices(this IServiceCollection serviceCollection)
{
serviceCollection.AddTransient<IProductRepository, ProductRepository>();
}
}
}
<file_sep>/DotNet-101.Infrastructure/Data/Migrations/20210712151216_initial.cs
using System;
using Microsoft.EntityFrameworkCore.Migrations;
namespace DotNet_101.Infrastructure.Data.Migrations
{
public partial class initial : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Customers",
columns: table => new
{
CustomerId = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
CompanyName = table.Column<string>(type: "nvarchar(max)", nullable: true),
ContactTitle = table.Column<string>(type: "nvarchar(max)", nullable: true),
Phone = table.Column<string>(type: "nvarchar(max)", nullable: true),
Country = table.Column<string>(type: "nvarchar(max)", nullable: true),
CreatedDateTime = table.Column<DateTime>(type: "datetime2", nullable: false),
CreatedBy = table.Column<int>(type: "int", nullable: false),
UpdatedBy = table.Column<int>(type: "int", nullable: true),
UpdatedDateTime = table.Column<DateTime>(type: "datetime2", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Customers", x => x.CustomerId);
});
migrationBuilder.CreateTable(
name: "Orders",
columns: table => new
{
OrderId = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
CustomerId = table.Column<int>(type: "int", nullable: false),
ProductId = table.Column<int>(type: "int", nullable: false),
OrderDate = table.Column<DateTime>(type: "datetime2", nullable: false),
RequiredDate = table.Column<DateTime>(type: "datetime2", nullable: true),
ShippedDate = table.Column<DateTime>(type: "datetime2", nullable: false),
UnitPrice = table.Column<decimal>(type: "decimal(18,2)", nullable: false),
Quantity = table.Column<int>(type: "int", nullable: false),
Discount = table.Column<decimal>(type: "decimal(18,2)", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Orders", x => x.OrderId);
});
migrationBuilder.CreateTable(
name: "Products",
columns: table => new
{
ProductId = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
ProductName = table.Column<string>(type: "nvarchar(max)", nullable: true),
UnitPrice = table.Column<decimal>(type: "decimal(18,2)", nullable: false),
UnitsInStock = table.Column<int>(type: "int", nullable: false),
UnitsOnOrder = table.Column<int>(type: "int", nullable: false),
CreatedDateTime = table.Column<DateTime>(type: "datetime2", nullable: false),
CreatedBy = table.Column<int>(type: "int", nullable: false),
UpdatedBy = table.Column<int>(type: "int", nullable: true),
UpdatedDateTime = table.Column<DateTime>(type: "datetime2", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Products", x => x.ProductId);
});
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Customers");
migrationBuilder.DropTable(
name: "Orders");
migrationBuilder.DropTable(
name: "Products");
}
}
}
<file_sep>/DotNet-101.Infrastructure/Data/Config/CustomerConfiguration.cs
using DotNet_101.Core.Entities;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using System;
using System.Collections.Generic;
using System.Text;
namespace DotNet_101.Infrastructure.Data.Config
{
public class CustomerConfiguration : IEntityTypeConfiguration<Customer>
{
public void Configure(EntityTypeBuilder<Customer> builder)
{
builder.HasKey(m => m.CustomerId);
builder.HasMany(m => m.Order)
.WithOne(m => m.Customer)
.HasForeignKey(m => m.CustomerId);
}
}
}
<file_sep>/DotNet-101.Infrastructure/SqlServer/ProductRepository.cs
using DotNet_101.Core.Entities;
using DotNet_101.Core.Interfaces.Repository;
using DotNet_101.Infrastructure.Data;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DotNet_101.Infrastructure.SqlServer
{
public class ProductRepository : IProductRepository
{
private readonly ApplicationDbContext _dbContext;
public ProductRepository(ApplicationDbContext dbContext)
{
_dbContext = dbContext;
}
public async Task<List<Product>> GetAllProduct()
{
return await _dbContext.Products.ToListAsync();
}
}
}
<file_sep>/DotNet-101.Core/IoC/ServiceModuleExtentions.cs
using DotNet_101.Core.Interfaces.Service;
using DotNet_101.Core.Services;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Text;
namespace DotNet_101.Core.IoC
{
public static class ServiceModuleExtentions
{
public static void RegisterCoreServices(this IServiceCollection serviceCollection)
{
serviceCollection.AddScoped<IProductService, ProductService>();
}
}
}
<file_sep>/DotNet-101.Core/Interfaces/Service/IProductService.cs
using DotNet_101.Core.Entities;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace DotNet_101.Core.Interfaces.Service
{
public interface IProductService
{
Task<List<Product>> GetAllProduct();
}
}
| db94d88b470ba5cd8faf22feccd46a83d5671e7f | [
"C#"
]
| 24 | C# | Chanchit1516/dotnet-101 | a8b2909732969a295fae047869aed23f33f844cd | d35d79c2dcbbe4c86a1255a85489188da2fb5172 |
refs/heads/master | <file_sep>import pygame
import sys
import random
pygame.init()
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
GREY = (200, 200, 200)
RED = (255, 0, 0)
GOLD = (255, 255, 0)
clock = pygame.time.Clock()
screen = pygame.display.set_mode((750, 550))
pygame.display.set_caption("Testing")
x = 50
y = 50
yp = 50
xp = 50
vxp = 700
vyp = 450
playing = True
font = pygame.font.Font(None, 48)
player = "@"
tile = "."
enemy = "X"
gold = "G"
health = 10
health_max = 10
player_health = "Health: {}/{}".format(health, health_max)
player_font = pygame.font.Font(None, 72)
player_text = player_font.render(player, 1, WHITE)
health_text = font.render(player_health, 1, WHITE)
enemy_text = player_font.render(enemy, 1, RED)
gold_text = player_font.render(gold, 1, GOLD)
tile_text = player_font.render(tile, 1, GREEN)
action = ""
text = font.render(action, 1, WHITE)
action_pos = (50, 510)
sco = 0
score_pos = (400, 510)
score = "Score: {}".format(sco)
scoretext = font.render(score, 1, GREEN)
enemy_move = 0
gold_life = 0
gx = random.randint(1, 15)*50
gy = random.randint(1, 10)*50
while gx == xp and gy == yp:
gx = random.randint(1, 15)*50
gy = random.randint(1, 9)*50
while gx == vxp and gy == vyp:
gx = random.randint(1, 15)*50
gy = random.randint(1, 9)*50
hit = 0
hit_timer = 0
title = True
title_t = 0
while playing:
while title:
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
title = False
screen.fill(BLACK)
screen.blit(health_text, (10, 10))
title_t += 1
if title_t == 60:
title = False
clock.tick(60)
pygame.display.flip()
for event in pygame.event.get():
if event.type == pygame.QUIT:
playing = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_DOWN:
yp += 50
if yp >= 450:
yp = 450
else:
action = "You moved down."
text = font.render(action, 1, WHITE)
if event.key == pygame.K_UP:
yp += -50
if yp <= 50:
yp = 50
else:
action = "You moved up."
text = font.render(action, 1, WHITE)
if event.key == pygame.K_LEFT:
xp += -50
if xp <= 0:
xp = 0
else:
action = "You moved left."
text = font.render(action, 1, WHITE)
if event.key == pygame.K_RIGHT:
xp += 50
if xp >= 700:
xp = 700
else:
action = "You moved right."
text = font.render(action, 1, WHITE)
if random.randint(0, 150) <= 50:
i = random.randint(0, 3)
if i == 0:
vyp += 50
if vyp >= 450:
vyp = 450
if i == 1:
vyp += -50
if vyp <= 50:
vyp = 50
if i == 2:
vxp += -50
if vxp <= 0:
vxp = 0
if i == 3:
vxp += 50
if vxp >= 700:
vxp = 700
if vxp == xp and vyp == yp:
if hit == 0:
health += -5
hit = 1
player_health = "Health: {}/{}".format(health, health_max)
health_text = font.render(player_health, 1, WHITE)
if health == 0:
playing = False;
enemy_move += 1
gold_life += 1
if enemy_move >= 30:
enemy_move = 0
if random.randint(0, 150) <= 85:
i = random.randint(0, 3)
if i == 0:
vyp += 50
if vyp >= 450:
vyp = 450
if i == 1:
vyp += -50
if vyp <= 50:
vyp = 50
if i == 2:
vxp += -50
if vxp <= 0:
vxp = 0
if i == 3:
vxp += 50
if vxp >= 700:
vxp = 700
if vxp == xp and vyp == yp:
while gx == vxp and gy == vyp:
gx = random.randint(1, 15)*50
gy = random.randint(1, 9)*50
if hit == 0:
health += -5
hit = 1
player_health = "Health: {}/{}".format(health, health_max)
health_text = font.render(player_health, 1, WHITE)
if health == 0:
playing = False;
screen.fill(BLACK)
if hit == 1:
hit_timer += 1
if hit_timer >= 360:
hit = 0
hit_timer = 0
pygame.draw.rect(screen, GREY, [0, 505, 750, 5])
pygame.draw.rect(screen, GREY, [0, 45, 750, 5])
for i in range(25, 750, 50):
for j in range(50, 500, 50):
screen.blit(tile_text, (i, j))
if gold_life == 240:
gx = random.randint(1, 15)*50
gy = random.randint(1, 9)*50
while gx == xp and gy == yp:
gx = random.randint(1, 15)*50
gy = random.randint(1, 9)*50
while gx == vxp and gy == vyp:
gx = random.randint(1, 15)*50
gy = random.randint(1, 9)*50
gold_life = 0
if xp == gx and yp == gy:
sco += 100
score = "Score: {}".format(sco)
scoretext = font.render(score, 1, GREEN)
gx = random.randint(1, 15)*50
gy = random.randint(1, 9)*50
while gx == xp and gy == yp:
gx = random.randint(1, 15)*50
gy = random.randint(1, 9)*50
while gx == vxp and gy == vyp:
gx = random.randint(1, 15)*50
gy = random.randint(1, 9)*50
gold_life = 0
pygame.draw.rect(screen, BLACK, [xp, yp, x, y])
pygame.draw.rect(screen, BLACK, [vxp, vyp, x, y])
pygame.draw.rect(screen, BLACK, [gx, gy, x, y])
screen.blit(gold_text, (gx, gy))
screen.blit(player_text, (xp, yp))
screen.blit(health_text, (10, 10))
screen.blit(enemy_text, (vxp, vyp))
screen.blit(text, action_pos)
screen.blit(scoretext, score_pos)
clock.tick(60)
pygame.display.flip()
go = "GAME OVER"
go_text = font.render(go, 1, WHITE)
while not playing:
for event in pygame.event.get():
if event.type == pygame.QUIT:
playing = True
screen.fill(BLACK)
screen.blit(go_text, (250, 255))
screen.blit(scoretext, (270, 325))
clock.tick(60)
pygame.display.flip()
pygame.quit() | 2cccb0b10c2cbb2342f11bcaf3088d3af8f226d1 | [
"Python"
]
| 1 | Python | Blayze95/GameConcept1 | 45ce3ec6144b609bd7a6bbc3ecf10ad468312a3f | 341e4bf6e3dade2bba5801f5d8aa2510e3f773bb |
refs/heads/master | <repo_name>PlamenaMiteva/Diablo-JS-Application<file_sep>/js/controllers/heroesController.js
var app = app || {};
app.heroesController = (function () {
function HeroesController(viewBag, model) {
this.model = model;
this.viewBag = viewBag;
}
HeroesController.prototype.loadAllHeroes = function (selector) {
var _this = this;
this.model.getHeroes()
.then(function (data) {
var result = {
heroes: []
};
data.forEach(function (hero) {
var imageUrl;
if (hero.class.name == 'Amazon') {
imageUrl = 'imgs/amazon.png';
} else {
imageUrl = 'imgs/barbarian.png';
}
result.heroes.push({
name: hero.name,
imageUrl: imageUrl,
id: hero._id
})
});
_this.viewBag.showHeroes(selector, result);
})
};
HeroesController.prototype.loadHeroDetails = function (selector, heroId) {
var _this = this;
this.model.getHeroDetails(heroId)
.then(function (data) {
var imageUrl;
if (data.class.name == 'Amazon') {
imageUrl = 'imgs/amazon.png';
} else {
imageUrl = 'imgs/barbarian.png';
}
var result = {
imageUrl: imageUrl,
name: data.name,
attackPoints: data.class['attack-points'],
defensePoints: data.class['defense-points'],
lifePoints: data.class['life-points'],
items: [],
_id: data._id
};
if(data.items !=undefined) {
data.items.forEach(function (item) {
result.attackPoints += item['attack-points'];
result.defensePoints += item['defense-points'];
result.lifePoints += item['life-points'];
result.items.push({
name: item.name,
type: item.type.name,
attackPoints: item['attack-points'],
defensePoints: item['defense-points'],
lifePoints: item['life-points']
})
});
}
_this.viewBag.showHeroDetails(selector, result);
})
};
HeroesController.prototype.loadAddHero = function (selector) {
var _this = this;
this.model.listClasses()
.then(function (data) {
var result = {
classes: []
};
data.forEach(function (gameClass) {
result.classes.push({
name: gameClass.name,
attackPoints: gameClass['attack-points'],
defensePoints: gameClass['defense-points'],
lifePoints: gameClass['life-points'],
_id: gameClass._id
})
})
_this.viewBag.showAddHero(selector, result);
});
};
HeroesController.prototype.addHero = function (data) {
var result = {
name: data.name,
class: {
_type: "KinveyRef",
_id: data.classId,
_collection: "hero-classes"
}
};
this.model.addHero(result)
.then(function (success) {
var message = "You have successfully added a new hero";
var type = 'success';
Notify(message, type);
Sammy(function () {
this.trigger('redirectUrl', {url: '#/heroes/list/'});
});
}, function (error) {
var response = jQuery.parseJSON(error.responseText);
var message = response.description;
var type = 'error';
Notify(message, type);
}).done();
};
HeroesController.prototype.loadStoreItems = function (selector, heroId) {
var _this = this;
this.model.listStoreItems()
.then(function (data) {
var result = {
items: []
};
data.forEach(function (item) {
result.items.push({
name : item.name,
type : item.type,
attackPoints: item['attack-points'],
lifePoints: item['life-points'],
defensePoints: item['defense-points'],
_id: item._id,
heroId: heroId
})
});
_this.viewBag.showStoreItems(selector, result);
})
};
HeroesController.prototype.addItem = function (data) {
var _this = this;
var heroId = data.heroId;
this.model.getHeroDetails(heroId)
.then(function (heroData) {
var result = {
name: heroData.name,
class: {
_type: "KinveyRef",
_id: heroData.class._id,
_collection: "hero-classes"
},
items: []
};
if(heroData.items == undefined){
result.items.push({
_type: "KinveyRef",
_id: data.itemId,
_collection: "items"
})
}else {
var itemTypeExists = false;
heroData.items.forEach(function (item) {
if (item.type.name == data.itemType) {
var message = "You already have an item of this type, which will be thrown away in case you proceed with the purchase.";
var type = 'warning';
Notify(message, type);
result.items.push({
_type: "KinveyRef",
_id: data.itemId,
_collection: "items"
});
itemTypeExists = true;
} else {
result.items.push({
_type: "KinveyRef",
_id: item._id,
_collection: "items"
})
}
});
if(!itemTypeExists){
result.items.push({
_type: "KinveyRef",
_id: data.itemId,
_collection: "items"
});
}
}
var updatedItem ={
heroId : heroData._id,
result : result
};
console.log(updatedItem)
return updatedItem;
})
.then(function (updatedItem) {
_this.model.editHero(updatedItem.heroId, updatedItem.result)
.then(function (success) {
var message = "You have bought a new item";
var type = 'success';
Notify(message, type);
}, function (error) {
var response = jQuery.parseJSON(error.responseText);
var message = response.description;
var type = 'error';
Notify(message, type);
}).done();
});
};
function Notify(message, type) {
noty({
text: message,
layout: 'topRight',
closeWith: ['click', 'hover'],
type: type
});
};
return {
load: function (viewBag, model) {
return new HeroesController(viewBag, model);
}
};
}()); | a188f3153ffa1815192cdec8813fcc4e30b01a51 | [
"JavaScript"
]
| 1 | JavaScript | PlamenaMiteva/Diablo-JS-Application | 69c8e5a82462e9123b557d907c6a5fde4490fd7c | 1120f959b5e0a7aecaef19122e149c0a39529136 |
refs/heads/master | <file_sep>const primeFactor = (n) => {
//we know that 2 divides even numbers so we use 2 to deteroite n
//we show the number of time 2 divides n
//then pass the remainder to nex block
if (n % 2 == 0) {
var count = 0;
while (n % 2 == 0) {
count++;
n /= 2;
}
console.log(2, count);
}
//for i greater than square root of n we know we have a prime we pass it to next block
for (var i = 3; i * i <= n; i++) {
if (n % i == 0) {
var count = 0;
while (n % i == 0) {
count++;
n /= i;
}
console.log(i, count);
}
}
//the prime number id printed
if (n > 2) {
console.log(n);
}
}; //javascript function definition
primeFactor(66); //function call
//time complexity O(sqrt(n))
<file_sep>//closures
/*Closures are function that return another function*/
const add = (x) => {
//(1)
//
//
return function (y) {
//(2)
return x + y;
};
}; //javasctipt function definition
const add1 = add(1); //first function call 1
const add2 = add1(3); //second function call 2
console.log(add2); //answer:4
<file_sep>//Prime-> 1 and itself
//we iterate from 2->n-1 beacause we only need numbers that n is greater than and we only need numbers that can divide n
//we make sure that n is not <=1
const isPrime = (n) => {
//if n is <=1
if (n <= 1) return false;
//we loop from 2->n-1 to get the numbers that can divide it
for (var i = 2; i < n; i++) {
if (n % i == 0) return false; //factor
}
return true; //prime is found
}; //javascript function definition
console.log(isPrime(8));
//the time complexity is O(n)
<file_sep>//we use the for..in loop to loop through objects
var obj1={firstname:'Ken',lastname:'Austin',email:'<EMAIL>'};//javascript object definition
//we loop to get the keys and value
for(var key in obj1){//block
const data=obj1[key];//object slicing
console.log(data+'\n');
}
//we use for...of loop to loop through an array
var obj1=['apple','mango','pine','pear'];//javascript array definition
for(var elem of obj1){//block
console.log(elem);
} <file_sep>## Data structures and algorithm in javascript
## B01
--Classes B004
--Getters and setters
--closures B003
--loops
## Big o notation
<file_sep>## Array operators
```python
$elemMatch #this iterates through all the array elements if there exist an object
$all #if the array elements only consists of elements not objects
```
| 1a87f8ba49132e9e889aaeedd2ae91c62162e979 | [
"JavaScript",
"Markdown"
]
| 6 | JavaScript | Chidalu567/DS_ALGO | 48deb3247eaa8df1162909a98fdde7d105bc2274 | e636e9682d078c3b5e1b636945ee9d6c2995a9b1 |
refs/heads/master | <file_sep>################################### Zplug ####################################
if [[ ! -d ~/.zplug ]]; then
git clone https://github.com/zplug/zplug ~/.zplug
source ~/.zplug/init.zsh && zplug update --self
fi
source ~/.zplug/init.zsh
zplug "mafredri/zsh-async"
zplug "sindresorhus/pure", use:pure.zsh, from:github, as:theme
zplug "zsh-users/zsh-syntax-highlighting"
zplug "zsh-users/zsh-completions"
zplug "zsh-users/zsh-autosuggestions"
zplug "ael-code/zsh-colored-man-pages"
zplug "supercrabtree/k"
zplug "b4b4r07/enhancd", use:init.sh
if ! zplug check --verbose; then
printf "Install? [y/N]: "
if read -q; then
echo; zplug install
fi
fi
zplug load
################################### Settings #################################
username=`whoami`
set -o emacs
zstyle ':completion:*' matcher-list '' 'm:{a-zA-Z}={A-Za-z}' 'r:|[._-]=* r:|=*' 'l:|=* r:|=*'
# locale
export LC_ALL=en_US.UTF-8
export LANG=en_US.UTF-8
[ -z "$TMUX" ] && export TERM=screen-256color
# editor
export EDITOR='nvim'
# fzf
export FZF_DEFAULT_OPTS='--height 20% --layout=reverse --border'
# http_proxy
if [ $username = "yurunyu" ]; then
export http_proxy=10.110.216.52:3128 https_proxy=10.110.216.52:3128
export no_proxy='.byted.org,.cn,localhost,127.0.0.1,127.0.1.1'
else
export http_proxy='http://0.0.0.0:6152' https_proxy='http://0.0.0.0:6152'
export no_proxy='localhost,127.0.0.1,127.0.1.1'
fi
################################### PATH #####################################
BINPATH="/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin"
if [ $username = "yurunyu" ]; then
# linuxbrew
BINPATH+=":/home/linuxbrew/.linuxbrew/bin:/home/linuxbrew/.linuxbrew/sbin"
# go
export GOPATH="$HOME/repos/go"
BINPATH+=":$GOROOT/bin:$GOPATH/bin"
# other
BINPATH+=":$HOME/bin:/opt/tiger/ss_lib/bin:/opt/tiger/ss_bin"
else
# GNU tools
BINPATH+=":/usr/local/opt/coreutils/libexec/gnubin"
# go
export GO111MODULE=on
export GOROOT='/usr/local/opt/go/libexec'
export GOPATH="$HOME/Code/go"
BINPATH+=":$GOROOT/bin:$GOPATH/bin"
# python
BINPATH+=":$HOME/.conda/bin"
# flutter
BINPATH+=":$HOME/Code/flutter/bin"
# java
# export JAVA_HOME=`/usr/libexec/java_home -v 1.8`
fi
# n-install
export N_PREFIX="$HOME/.n";
BINPATH+=":$N_PREFIX/bin"
# rust
BINPATH+=":$HOME/.cargo/bin"
export PATH=$BINPATH
################################### Alias ####################################
alias g=git
alias v=nvim
alias vi=vim
alias pg='postgres -D /usr/local/var/postgres'
alias less='less --LONG-PROMPT --LINE-NUMBERS --ignore-case --QUIET'
alias gr='grep --color -n -E'
if [ $username = "yurunyu" ]; then
alias tmux=/home/linuxbrew/.linuxbrew/bin/tmux
alias tp=~/repos/toutiao/runtime/bin/python
alias onboard='ssh [email protected]'
else
alias en0="echo $(ifconfig en0 | grep netmask | awk '{print $2}')"
alias cleards="find ~ -name '*.DS_Store' -type f -delete && echo 'ALL .DS_STORE FILES RECURSIVELY REMOVED'"
fi
################################# Function ###################################
function t() {
tmux a -t $1
}
function rgg() {
rg $1 -g '!{vendor,thrift_gen,clients}' -tgo
}
function cheat() {
curl cheat.sh/$1
}
function md() {
mkdir -p "$@" && cd "$@"
}
function f() {
find . -name "$1" 2>&1 | grep -v 'Permission denied'
}
# build with os default path
function rawpath() {
path2=$PATH
export PATH="/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin"
command $@
export PATH=$path2
}
# iterm2
test -e "${HOME}/.iterm2_shell_integration.zsh" && source "${HOME}/.iterm2_shell_integration.zsh"
| 0c5d04a0bd325637d7dc28632564f6fba29ed7f6 | [
"Shell"
]
| 1 | Shell | P79N6A/dotfiles-3 | 5f01b80a4e21e596afe75e97afb503831e0fc5cb | 579ed388d44c91f4327d7ec76398e4ed141f7a0c |
refs/heads/master | <file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package edu.wpi.first.wpilibj.templates.commands;
import edu.wpi.first.wpilibj.Joystick;
import edu.wpi.first.wpilibj.Timer;
import edu.wpi.first.wpilibj.can.CANTimeoutException;
import edu.wpi.first.wpilibj.templates.RobotMap;
/**
*
* @author Owner
*/
public class ClawCommand extends CommandBase {
public static Joystick xbox;
public boolean initialized = false;
public double encoderValue = -1;
public double referenceTime = 0;
public ClawCommand() {
requires(upperClaw);
requires(lowerClaw);
}
protected void initialize() {
}
public void enableControl() {
upperClaw.enableControl();
lowerClaw.enableControl();
}
public void disableControl() {
upperClaw.disableControl();
lowerClaw.disableControl();
}
protected void execute() {
// initialize encoder
if (!initialized) {
lowerClaw.disable();
try {
RobotMap.lowerClaw.setX(-6);
if (referenceTime == 0 ) {
referenceTime = System.currentTimeMillis();
}
if (Math.abs(lowerClaw.lowerClaw.getPosition()-encoderValue) > 0.01) {
encoderValue = lowerClaw.lowerClaw.getPosition();
referenceTime = System.currentTimeMillis();
}
if (Math.abs(System.currentTimeMillis()-referenceTime) > 500) {
initialized = true;
RobotMap.encoderOffset = RobotMap.lowerClaw.getPosition();
RobotMap.lowerClaw.setX(0);
lowerClaw.enable();
}
} catch (CANTimeoutException ex) {
ex.printStackTrace();
}
} else {
boolean open, close, down, up;
if (RobotMap.auto) {
open = RobotMap.autoOpen;
close = RobotMap.autoClose;
up = RobotMap.autoUp;
down = RobotMap.autoDown;
}
else {
open = xbox.getRawButton(RobotMap.openButton);
RobotMap.closing = (xbox.getRawButton(RobotMap.closeButton)||RobotMap.closing)&&(!open);
close = RobotMap.closing;
up = xbox.getRawButton(RobotMap.upButton);
down = xbox.getRawButton(RobotMap.downButton);
}
if (open) {
upperClaw.setSetpoint(1.000);
} else if (close) {
upperClaw.setSetpoint(-1.000);
} else {
upperClaw.setSetpoint(0.000);
}
if (down) {
lowerClaw.setSetpoint(0);
} else if (up) {
lowerClaw.setSetpoint(RobotMap.upPosition);
}
/*double rightY = xbox.getRawAxis(5);
if (rightY > 0.5) {
try {
RobotMap.lowerClaw.setX(6);
} catch (CANTimeoutException ex) {
ex.printStackTrace();
}
} else if (rightY < -0.5) {
try {
RobotMap.lowerClaw.setX(-6);
} catch (CANTimeoutException ex) {
ex.printStackTrace();
}
} else {
try {
RobotMap.lowerClaw.setX(0);
} catch (CANTimeoutException ex) {
ex.printStackTrace();
}
}*/
}
}
protected boolean isFinished() {
return false;
}
protected void end() {
}
protected void interrupted() {
}
}
<file_sep>/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
package edu.wpi.first.wpilibj.templates;
import edu.wpi.first.wpilibj.CANJaguar;
import edu.wpi.first.wpilibj.CANJaguar.ControlMode;
import edu.wpi.first.wpilibj.IterativeRobot;
import edu.wpi.first.wpilibj.Joystick;
import edu.wpi.first.wpilibj.Relay;
import edu.wpi.first.wpilibj.Solenoid;
import edu.wpi.first.wpilibj.Timer;
import edu.wpi.first.wpilibj.can.CANTimeoutException;
import edu.wpi.first.wpilibj.command.Command;
import edu.wpi.first.wpilibj.command.Scheduler;
import edu.wpi.first.wpilibj.livewindow.LiveWindow;
import edu.wpi.first.wpilibj.templates.commands.ClawCommand;
import edu.wpi.first.wpilibj.templates.commands.CommandBase;
import edu.wpi.first.wpilibj.templates.commands.DriveCommand;
import edu.wpi.first.wpilibj.templates.commands.ShootCommand;
/**
* The VM is configured to automatically run this class, and to call the
* functions corresponding to each mode, as described in the IterativeRobot
* documentation. If you change the name of this class or the package after
* creating this project, you must also update the manifest file in the resource
* directory.
*/
public class RobotTemplate extends IterativeRobot {
DriveCommand driveCommand;
ClawCommand clawCommand;
ShootCommand shootCommand;
double shootTimer = -1;
/**
* This function is run when the robot is first started up and should be
* used for any initialization code.
*/
public void robotInit() {
try {
RobotMap.leftFront = new CANJaguar(RobotMap.leftForwardMotor, ControlMode.kVoltage);
RobotMap.leftBack = new CANJaguar(RobotMap.leftBackMotor, ControlMode.kVoltage);
RobotMap.rightFront = new CANJaguar(RobotMap.rightForwardMotor, ControlMode.kVoltage);
RobotMap.rightBack = new CANJaguar(RobotMap.rightBackMotor, ControlMode.kVoltage);
RobotMap.leftFront.configNeutralMode(CANJaguar.NeutralMode.kBrake);
RobotMap.leftBack.configNeutralMode(CANJaguar.NeutralMode.kBrake);
RobotMap.rightFront.configNeutralMode(CANJaguar.NeutralMode.kBrake);
RobotMap.rightBack.configNeutralMode(CANJaguar.NeutralMode.kBrake);
RobotMap.upperClaw = new CANJaguar(RobotMap.upperClawMotor, ControlMode.kVoltage);
RobotMap.upperClaw.configNeutralMode(CANJaguar.NeutralMode.kBrake);
RobotMap.upperClaw.setX(0);
RobotMap.lowerClaw = new CANJaguar(RobotMap.lowerClawMotor, ControlMode.kVoltage);
RobotMap.lowerClaw.configNeutralMode(CANJaguar.NeutralMode.kBrake);
RobotMap.lowerClaw.setPositionReference(CANJaguar.PositionReference.kQuadEncoder);
RobotMap.lowerClaw.configEncoderCodesPerRev(360);
RobotMap.lowerClaw.setX(0);
RobotMap.lowerClaw.enableControl();
RobotMap.leftFront.setSpeedReference(CANJaguar.SpeedReference.kQuadEncoder);
RobotMap.rightFront.setSpeedReference(CANJaguar.SpeedReference.kQuadEncoder);
RobotMap.leftFront.setPositionReference(CANJaguar.PositionReference.kQuadEncoder);
RobotMap.rightFront.setPositionReference(CANJaguar.PositionReference.kQuadEncoder);
RobotMap.leftFront.configEncoderCodesPerRev(360);
RobotMap.rightFront.configEncoderCodesPerRev(250);
RobotMap.compressorRelay = new Relay(1);
RobotMap.compressorRelay.setDirection(Relay.Direction.kForward);
// RobotMap.solenoidRelay = new Relay(2);
// RobotMap.solenoidRelay.setDirection(Relay.Direction.kForward);
RobotMap.shooterValveSolenoid = new Solenoid(1);
RobotMap.shooterValveSolenoid.set(false);
// Initialize all subsystems
CommandBase.init();
driveCommand = new DriveCommand();
clawCommand = new ClawCommand();
DriveCommand.xbox = new Joystick(1);
ClawCommand.xbox = DriveCommand.xbox;
shootCommand = new ShootCommand();
ShootCommand.xbox = DriveCommand.xbox;
clawCommand.disableControl();
driveCommand.disableControl();
} catch (CANTimeoutException ex) {
ex.printStackTrace();
}
}
public void autonomousInit() {
RobotMap.auto = true;
RobotMap.autoTimer = System.currentTimeMillis()+500;
driveCommand.enableControl();
driveCommand.start();
clawCommand.enableControl();
clawCommand.start();
shootCommand.start();
}
/**
* This function is called periodically during autonomous
*/
public void autonomousPeriodic() {
if (!RobotMap.auto) return;
// Start closing claw
if (System.currentTimeMillis()-RobotMap.autoTimer > 000) {
RobotMap.autoClose = true;
RobotMap.autoOpen = false;
}
// Start driving forward
if (System.currentTimeMillis()-RobotMap.autoTimer > 1500) {
RobotMap.autoY = 0.40;
}
// Raise bottom claw
if (System.currentTimeMillis()-RobotMap.autoTimer > 2000) {
RobotMap.autoUp = true;
RobotMap.autoDown = false;
}
// Open the claw
if (System.currentTimeMillis()-RobotMap.autoTimer > 3500) {
RobotMap.autoClose = false;
RobotMap.autoOpen = true;
}
// Stop opening
if (System.currentTimeMillis()-RobotMap.autoTimer > 4000) {
RobotMap.autoOpen = false;
}
/*try {
// Shoot
System.out.println(RobotMap.leftFront.getPosition()-RobotMap.leftOffset);
if (Math.abs(RobotMap.leftFront.getPosition()-RobotMap.leftOffset) >= 8.5 && shootTimer == -1) {
RobotMap.autoShoot = true;
shootTimer = System.currentTimeMillis();
RobotMap.autoY = 0;
}
} catch (CANTimeoutException ex) {
ex.printStackTrace();
}*/
if (System.currentTimeMillis()-RobotMap.autoTimer > 5000 && shootTimer ==-1) {
RobotMap.autoShoot = true;
shootTimer = System.currentTimeMillis();
RobotMap.autoY = 0;
}
if (shootTimer != -1 && System.currentTimeMillis()-shootTimer > 500) {
RobotMap.autoShoot = false;
RobotMap.auto = false;
RobotMap.autoTimer = -1;
}
Scheduler.getInstance().run();
}
public void teleopInit() {
RobotMap.auto = false;
System.out.println("TELEOP INIT");
driveCommand.enableControl();
driveCommand.start();
clawCommand.enableControl();
clawCommand.start();
shootCommand.start();
}
/**
* This function is called periodically during operator control
*/
public void teleopPeriodic() {
RobotMap.auto = false;
RobotMap.autoShoot = false;
Scheduler.getInstance().run();
}
/**
* This function is called periodically during test mode
*/
public void testPeriodic() {
LiveWindow.run();
}
}
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package edu.wpi.first.wpilibj.templates.commands;
import edu.wpi.first.wpilibj.Relay;
import edu.wpi.first.wpilibj.templates.RobotMap;
import edu.wpi.first.wpilibj.DigitalInput;
import edu.wpi.first.wpilibj.Joystick;
import edu.wpi.first.wpilibj.can.CANTimeoutException;
/**
*
* @author Owner
*/
public class ShootCommand extends CommandBase {
public static Joystick xbox;
long time = -1;
long clawTime = -1;
boolean shooting = false;
long buttonTime = -1;
DigitalInput pressureSwitch = null;
public ShootCommand() {
}
protected void initialize() {
if (pressureSwitch == null)
pressureSwitch = new DigitalInput(1);
}
protected void execute() {
if (pressureSwitch.get() == false && RobotMap.compressorEnabled) {
RobotMap.compressorRelay.set(Relay.Value.kForward);
} else {
RobotMap.compressorRelay.set(Relay.Value.kOff);
}
if (xbox.getRawButton(RobotMap.shootButton) || RobotMap.autoShoot) {
if (safeToShoot() || (RobotMap.auto&&RobotMap.autoShoot)) {
if (buttonTime == -1) {
buttonTime = System.currentTimeMillis();
}
shooting = true;
// if (System.currentTimeMillis()-buttonTime > 500) shooting = true;
} else {
System.out.println("not safe to shoot");
shooting = false;
time = -1;
}
} else {
buttonTime = -1;
}
if (shooting) {
if (time == -1) {
time = System.currentTimeMillis();
// RobotMap.solenoidRelay.set(Relay.Value.kForward);
RobotMap.shooterValveSolenoid.set(true);
System.out.println("turned shooter solenoid on");
} else if (System.currentTimeMillis() - time >= 500) {
// RobotMap.solenoidRelay.set(Relay.Value.kOff);
RobotMap.shooterValveSolenoid.set(false);
System.out.println("turned shooter solenoid off");
shooting = false;
time = -1;
}
}
}
public boolean safeToShoot() {
double lowerClawPos = RobotMap.shootingPosMin - 1;
try {
lowerClawPos = RobotMap.lowerClaw.getPosition() - RobotMap.encoderOffset;
} catch (CANTimeoutException ex) {
ex.printStackTrace();
}
System.out.println("safeToShoot lowerClawPos is "+ lowerClawPos);
return (RobotMap.shootingPosMin < lowerClawPos) && (lowerClawPos < RobotMap.shootingPosMax);
}
protected boolean isFinished() {
return false;
}
protected void end() {
}
protected void interrupted() {
}
}
<file_sep>package edu.wpi.first.wpilibj.templates;
import edu.wpi.first.wpilibj.CANJaguar;
import edu.wpi.first.wpilibj.Relay;
import edu.wpi.first.wpilibj.Solenoid;
/**
* The RobotMap is a mapping from the ports sensors and actuators are wired into
* to a variable name. This provides flexibility changing wiring, makes checking
* the wiring easier and significantly reduces the number of magic numbers
* floating around.
*/
public class RobotMap {
// For example to map the left and right motors, you could define the
// following variables to use with your drivetrain subsystem.
// public static final int leftMotor = 1;
// public static final int rightMotor = 2;
// If you are using multiple modules, make sure to define both the port
// number and the module. For example you with a rangefinder:
// public static final int rangefinderPort = 1;
// public static final int rangefinderModule = 1;
public static final int leftForwardMotor = 5;
public static final int leftBackMotor = 3;
public static final int rightForwardMotor = 2;
public static final int rightBackMotor = 12;
public static final int upperClawMotor = 7;
public static final int lowerClawMotor = 8;
public static CANJaguar leftFront;
public static CANJaguar leftBack;
public static CANJaguar rightFront;
public static CANJaguar rightBack;
public static CANJaguar upperClaw;
public static CANJaguar lowerClaw;
public static Relay compressorRelay;
public static Relay solenoidRelay;
public static Solenoid shooterValveSolenoid;
public static double encoderOffset;
public static int shootButton = 6;
public static int downButton = 4;
public static int upButton = 3;
public static int openButton = 2;
public static int closeButton = 1;
public static boolean closing = false;
public static final double upPosition = -0.23;
public static final double shootingPosMin = upPosition - 0.02;
public static final double shootingPosMax = upPosition + 0.02;
public static int valveSwitch = 1;
public static double lowerNormalP = 120;
public static double lowerNormalI = 0.15;
public static double lowerNormalD = 0;
public static double lowerCloseP = 120;
public static double lowerCloseI = 0.1;
public static double lowerCloseD = 0;
public static boolean compressorEnabled = true;
public static boolean auto = false;
public static double autoX = 0;
public static double autoY = 0;
public static boolean autoDown = true;
public static boolean autoUp = false;
public static boolean autoOpen = false;
public static boolean autoClose = false;
public static boolean autoShoot = false;
public static double autoTimer = -1;
public static double leftOffset = -1;
public static double rightOffset = -1;
}
| 06411d6f574ae7481f2c4aabeb890e900a374016 | [
"Java"
]
| 4 | Java | chrisdebrunner/TeamBlitzRobot2014 | 69e59aabc462dbcd765862021c8a6ae6bce628ac | 5765b5ed7eb8c064a78c76303c24c05efd6e6d2d |
refs/heads/master | <file_sep>/*
SA-MP Streamer Plugin v2.5.2
Copyright © 2010 Incognito
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <string>
#include "Invoke.h"
#include "plugin.h"
#include "utils.h"
Invoke * g_Invoke;
int Invoke::callNative(const PAWN::Native * native, ...)
{
if (amx_list.empty() || amx_map.find(native->name) == amx_map.end())
{
return 0;
}
unsigned int amx_addr = amx_map[native->name], count = strlen(native->data), variables = 0;
cell * params = new cell[count + 1], * physAddr[6];
params[0] = count * sizeof(cell);
va_list input;
va_start(input, native);
for (unsigned int i = 0; i < count; ++i)
{
switch (native->data[i])
{
case 'd':
case 'i':
{
params[i + 1] = va_arg(input, int);
}
break;
case 'b':
{
params[i + 1] = va_arg(input, bool);
}
break;
case 'f':
{
float value = (float)va_arg(input, double);
params[i + 1] = amx_ftoc(value);
}
break;
case 's':
{
char * string = va_arg(input, char *);
amx_Allot(amx_list.front(), strlen(string) + 1, ¶ms[i + 1], &physAddr[variables++]);
amx_SetString(physAddr[variables - 1], string, 0, 0, strlen(string) + 1);
}
break;
case 'v':
{
va_arg(input, void *);
amx_Allot(amx_list.front(), 1, ¶ms[i + 1], &physAddr[variables++]);
}
break;
case 'p':
{
va_arg(input, void *);
int size = va_arg(input, int);
amx_Allot(amx_list.front(), size, ¶ms[++i], &physAddr[variables++]);
params[i + 1] = amx_Allot(amx_list.front(), size, ¶ms[++i], &physAddr[variables++]);
}
break;
// Special refrence array/string where the destination is NOT followed by the size!
// However, the string passed to this method MUST be followed by size! (e.g. mysql_escape_string)
case 'r':
{
va_arg(input, void *);
int size = va_arg(input, int);
amx_Allot(amx_list.front(), size, ¶ms[i + 1], &physAddr[variables++]);
}
break;
/*
Since invoke does not nativley support this kind of behaviour I have implemented my own way to do this.
This parameter type is the format for calling a function with variable number of parameters.
*/
case 'l': // list of variables.
{
char * strList = va_arg(input, char *);
amx_Allot(amx_list.front(), strlen(strList) + 1, ¶ms[i + 1], &physAddr[variables++]);
amx_SetString(physAddr[variables - 1], strList, 0, 0, strlen(strList) + 1);
int len = strlen(strList);
cell* variableParams = va_arg(input, cell*);
AMX* amx = va_arg(input, AMX*);
count -= 2;
count += len;
i++;
// resize the params array
cell * tmpParams = new cell[count + 1], * physAddr[6];
memcpy(tmpParams, params, (count + 1) * sizeof(cell));
delete[] params;
params = tmpParams;
params[0] = count * sizeof(cell);
std::string destStr;
for (int j = 0; j < len; j++, i++)
{
switch (strList[j])
{
case 'i':
case 'd':
params[i + 1] = (cell) variableParams[j];
break;
case 'f':
params[i + 1] = amx_ftoc(variableParams[j]);
break;
case 'b':
params[i + 1] = (cell) variableParams[j];
break;
case 's':
Utilities::GetPawnString(amx, variableParams[j], destStr, 128);
amx_Allot(amx_list.front(), destStr.length() + 1, ¶ms[i + 1], &physAddr[variables++]);
amx_SetString(physAddr[variables - 1], destStr.c_str(), 0, 0, destStr.length() + 1);
break;
}
}
// stop the loop.
i = count;
}
break;
}
}
va_end(input);
amx_Function_t amx_Function = (amx_Function_t)amx_addr;
int value = amx_Function(amx_list.front(), params);
if (variables)
{
variables = 0;
va_start(input, native);
for (unsigned int i = 0; i < count; ++i)
{
switch (native->data[i])
{
case 's':
{
va_arg(input, void *);
amx_Release(amx_list.front(), params[i + 1]);
}
break;
case 'v':
{
unsigned int * value = va_arg(input, unsigned int *), * returnValue = (unsigned int *)physAddr[variables++];
* value = * returnValue;
amx_Release(amx_list.front(), params[i + 1]);
}
break;
case 'r':
// FALLTHROUGH
case 'p':
{
char * text = va_arg(input, char *);
int size = va_arg(input, int);
amx_GetString(text, physAddr[variables++], 0, size);
amx_Release(amx_list.front(), params[++i]);
}
break;
default:
{
va_arg(input, void *);
}
break;
case 'l':
{
char * strList = va_arg(input, char *);
int len = strlen(strList);
i++;
for (int j = 0; j < len; j++, i++)
{
switch (strList[j])
{
case 's':
amx_Release(amx_list.front(), params[i + 1]);
break;
}
}
i = count;
}
break;
}
}
va_end(input);
}
delete [] params;
return value;
}
int Invoke::getAddresses()
{
if (gotAddresses)
{
return 1;
}
AMX_HEADER * amx_hdr = (AMX_HEADER *)(amx_list.back())->base;
std::size_t size = sizeof(PAWN::names) / sizeof(const char *);
for (std::size_t i = 0; i < size; ++i)
{
amx_FindNative(amx_list.back(), PAWN::names[i], &amx_idx);
if (amx_idx != std::numeric_limits<int>::max())
{
unsigned int amx_addr = (unsigned int)((AMX_FUNCSTUB *)((char *)amx_hdr + amx_hdr->natives + amx_hdr->defsize * amx_idx))->address;
if (amx_addr)
{
if (amx_map.find(PAWN::names[i]) == amx_map.end())
{
amx_map.insert(std::make_pair(PAWN::names[i], amx_addr));
}
}
}
}
if (amx_map.size() == size)
{
gotAddresses = true;
return 1;
}
return 0;
}
<file_sep>#include <iostream>
#include "query.h"
#include "plugin.h"
#include "utils.h"
#include "Invoke.h"
extern std::vector<Query*> g_queryVec;
extern logprintf_t logprintf;
Query::Query(std::string strTable, std::string strCondition, cell connectionHandle, unsigned short type)
: m_strCondition(strCondition), m_nConnectionHandle(connectionHandle), m_nType(type)
{
InitQuery(type, strTable);
}
Query::Query(std::string table, cell connectionHandle) : m_nConnectionHandle(connectionHandle)
{
Query(table, NULL, connectionHandle, _QB_QUERY_TYPE_INSERT);
}
void Query::Insert(std::string field, std::string value)
{
static int
fieldPos = 0,
valuePos = 0;
if (!field.empty())
{
if (!fieldPos)
{
fieldPos = m_strQuery.length() - strlen(") VALUES ()");
valuePos = m_strQuery.length() - 1;
}
field.insert(0, "`");
field.insert(field.length(), "`");
value.insert(0, "'");
value.insert(value.length(), "'");
m_strQuery.insert(fieldPos, field);
m_strQuery.insert(fieldPos + field.length(), ",");
fieldPos += 1 + field.length();
valuePos += 1 + field.length();
m_strQuery.insert(valuePos, value);
m_strQuery.insert(valuePos + value.length(), ",");
valuePos += value.length() + 1;
}
else
{
// Remove commas.
m_strQuery.erase(valuePos-1, 1);
m_strQuery.erase(fieldPos-1, 1);
}
}
void Query::Print(void)
{
logprintf("%s", m_strQuery.c_str());
}
void Query::Append(const std::string& entry)
{
m_strQuery += entry;
}
void Query::Set(char* cStr)
{
m_strQuery.assign(cStr);
}
unsigned int Query::GetQueryLen(void)
{
return m_strQuery.length();
}
unsigned short Query::GetQueryType(void)
{
return m_nType;
}
void Query::Update(const std::string& field, const std::string& entry)
{
m_strQuery += '`' + field + "`='" + entry + "',";
}
void Query::AddSelect(const std::string& field)
{
static unsigned int length = 0;
if (field.empty())
{
int pos = m_strQuery.find_last_of(',');
if (pos != std::string::npos)
m_strQuery.erase(pos, 1);
}
else
{
m_strQuery.insert(strlen("SELECT ") + length, "`" + field + "`,");
length += field.length() + 3;
}
}
void Query::AddSelect(void)
{
m_strQuery.insert(strlen("SELECT "), "*");
}
void Query::AddCondition(void)
{
// Delete last comma on update queries.
if (GetQueryType() == _QB_QUERY_TYPE_UPDATE)
m_strQuery.pop_back();
if (!m_strCondition.empty())
m_strQuery.append(" WHERE " + m_strCondition);
}
cell Query::GetConnectionHandle(void)
{
return m_nConnectionHandle;
}
std::string Query::GetQuery(void)
{
return m_strQuery;
}
Query* Query::Create(cell connectionHandle, unsigned short type)
{
Query* p_cQuery = new Query("", "", connectionHandle, type);
if (p_cQuery != nullptr)
{
g_queryVec.push_back(p_cQuery);
return p_cQuery;
}
return nullptr;
}
Query* Query::Create(AMX* amx, const cell& table, const cell& condition, cell connectionHandle, unsigned short type)
{
std::string strTable;
Utilities::GetPawnString(amx, table, strTable, 32 + 1);
if (!strTable.empty())
{
std::string strCondition;
Utilities::GetPawnString(amx, condition, strCondition, 64 + 1);
Query* p_cQuery = new Query(strTable, strCondition, connectionHandle, type);
if (p_cQuery != nullptr)
{
g_queryVec.push_back(p_cQuery);
return p_cQuery;
}
}
return nullptr;
}
bool Query::IsValidQuery(Query* query)
{
if (query == nullptr)
return false;
// If it's in the vector it's valid.
for (auto it = g_queryVec.begin(); it != g_queryVec.end(); it++)
if (*it == query)
return true;
return false;
}
void Query::SetMaxLens(unsigned int fieldLen, unsigned int entryLen, unsigned int fieldsLen)
{
Query::fieldLen = fieldLen;
Query::entryLen = entryLen;
Query::fieldsLen = fieldsLen;
}
// Private Functions
void inline Query::InitQuery(int type, const std::string& table) {
switch (type)
{
case _QB_QUERY_TYPE_DELETE:
m_strQuery = "DELETE FROM `" + table + "`";
break;
case _QB_QUERY_TYPE_INSERT:
m_strQuery = "INSERT INTO `" + table + "` () VALUES ()";
break;
case _QB_QUERY_TYPE_UPDATE:
m_strQuery = "UPDATE `" + table + "` SET ";
break;
case _QB_QUERY_TYPE_SELECT:
m_strQuery = "SELECT FROM `" + table + "`";
break;
}
}<file_sep>#ifndef _H_PLUGIN
#define _H_PLUGIN
#include <vector>
#include "SDK\amx\amx.h"
#include "SDK\plugincommon.h"
#include "natives.h"
typedef void
(*logprintf_t)(char* format, ...);
extern void
*pAMXFunctions;
#endif<file_sep>/*
SA-MP Streamer Plugin v2.5.2
Copyright © 2010 Incognito
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include "SDK\amx\amx.h"
#include "SDK\plugincommon.h"
#include <bitset>
#include <list>
#include <map>
#include <stdarg.h>
namespace PAWN
{
struct Native
{
const char * name;
const char * data;
};
static const char * const names[] =
{
"mysql_query",
"mysql_tquery",
"mysql_pquery",
"mysql_escape_string",
};
// a_mysql.inc (BlueG)
static const Native mysql_query = { "mysql_query", "isb"};
static const Native mysql_tquery = { "mysql_tquery", "isslax"};
static const Native mysql_pquery = { "mysql_pquery", "isslax"};
static const Native mysql_escape_string = { "mysql_escape_string", "srii"};
};
class
Invoke
{
public:
Invoke()
{
gotAddresses = false;
}
int callNative(const PAWN::Native * native, ...);
int getAddresses();
int amx_idx;
std::list<AMX *> amx_list;
private:
bool gotAddresses;
std::map<std::string, unsigned int> amx_map;
};
typedef int (* amx_Function_t)(AMX * amx, cell * params);
extern Invoke *g_Invoke;
<file_sep>#include <vector>
#include <list>
#include "plugin.h"
#include "natives.h"
#include "query.h"
#include "utils.h"
#include "invoke.h"
extern std::vector<Query*> g_queryVec;
extern logprintf_t logprintf;
unsigned int Query::fieldLen = 0;
unsigned int Query::entryLen = 0;
unsigned int Query::fieldsLen = 0;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Select
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
cell AMX_NATIVE_CALL Natives::QueryBuilder_Select(AMX* amx, cell* params)
{
Query* p_cQuery = Query::Create(amx, params[1], params[3], params[4], _QB_QUERY_TYPE_SELECT);
if (!Query::IsValidQuery(p_cQuery))
{
logprintf("QueryBuilder: Empty table passed to QueryBuilder_Select.");
return 0;
}
std::string strFields;
Utilities::GetPawnString(amx, params[2], strFields, Query::fieldsLen);
if (strFields.empty())
{
p_cQuery->AddSelect();
}
else
{
Utilities::TrimWhitespace(strFields);
std::list<std::string> fieldsList = Utilities::Split(strFields, ',');
for (auto it = fieldsList.begin(); it != fieldsList.end(); it++)
{
if (!it->empty())
p_cQuery->AddSelect(*it);
}
p_cQuery->AddSelect("");
}
return (cell)p_cQuery;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Delete
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
cell AMX_NATIVE_CALL Natives::QueryBuilder_Delete(AMX* amx, cell* params)
{
Query* p_cQuery = Query::Create(amx, params[1], params[2], params[3], _QB_QUERY_TYPE_DELETE);
if (!Query::IsValidQuery(p_cQuery))
{
logprintf("QueryBuilder: Empty table passed to QueryBuilder_Delete.");
return 0;
}
return (cell) p_cQuery;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Insert
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
cell AMX_NATIVE_CALL Natives::QueryBuilder_Insert(AMX* amx, cell* params)
{
Query* p_cQuery = Query::Create(amx, params[2], NULL, params[1], _QB_QUERY_TYPE_INSERT);
if (!Query::IsValidQuery(p_cQuery))
{
logprintf("QueryBuilder: Empty table passed to QueryBuilder_Insert.");
return 0;
}
else
{
static const unsigned int static_args = 4;
std::string strFormat;
Utilities::GetPawnString(amx, params[3], strFormat, Query::fieldLen);
for (unsigned int i = 0, arg; i < strFormat.length(); i++)
{
arg = static_args + (i * 2);
std::string strField;
Utilities::GetPawnString(amx, params[arg], strField, Query::fieldLen);
cell* p_physAddr = nullptr;
amx_GetAddr(amx, params[arg + 1], &p_physAddr);
switch (strFormat[i])
{
case 'i':
//FALLTHROUGH
case 'd':
p_cQuery->Insert(strField, std::to_string(static_cast<int>(*p_physAddr)));
break;
case 'f':
p_cQuery->Insert(strField, std::to_string(amx_ctof(*p_physAddr)));
break;
case 's':
{
std::string strEntry;
Utilities::GetPawnString(amx, params[arg + 1], strEntry, Query::entryLen);
p_cQuery->Insert(strField, strEntry);
break;
}
}
}
// passing null field & entry to the insert method will finish the query building (but won't send it).
p_cQuery->Insert("", "");
return (cell) p_cQuery;
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Updating
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
cell AMX_NATIVE_CALL Natives::QueryBuilder_Update(AMX* amx, cell* params)
{
Query* p_cQuery = Query::Create(amx, params[1], params[2], params[3], _QB_QUERY_TYPE_UPDATE);
if (!Query::IsValidQuery(p_cQuery))
{
logprintf("QueryBuilder: Empty table passed to QueryBuilder_Update");
return 0;
}
return (cell)p_cQuery;
}
cell AMX_NATIVE_CALL Natives::QueryBuilder_UpdateString(AMX* amx, cell* params)
{
Query* p_cQuery = (Query*)params[1];
if (Query::IsValidQuery(p_cQuery))
{
std::string strField, strEntry;
Utilities::GetPawnString(amx, params[2], strField, Query::fieldLen);
Utilities::GetPawnString(amx, params[3], strEntry, Query::entryLen);
p_cQuery->Update(strField, strEntry);
}
else
logprintf("Query Builder: invalid query handle.");
return 0;
}
cell AMX_NATIVE_CALL Natives::QueryBuilder_UpdateInt(AMX* amx, cell* params)
{
Query* p_cQuery = (Query*)params[1];
if (Query::IsValidQuery(p_cQuery))
{
std::string strField;
Utilities::GetPawnString(amx, params[2], strField, Query::fieldLen);
p_cQuery->Update(strField, std::to_string((int)params[3]));
}
else
logprintf("Query Builder: invalid query handle.");
return 0;
}
cell AMX_NATIVE_CALL Natives::QueryBuilder_UpdateFloat(AMX* amx, cell* params)
{
Query* p_cQuery = (Query*)params[1];
if (Query::IsValidQuery(p_cQuery))
{
std::string strField;
Utilities::GetPawnString(amx, params[2], strField, Query::fieldLen);
p_cQuery->Update(strField, std::to_string(amx_ctof(params[3])));
}
else
logprintf("Query Builder: invalid query handle.");
return 0;
}
cell AMX_NATIVE_CALL Natives::QueryBuilder_MultiUpdate(AMX* amx, cell* params)
{
Query* p_cQuery = (Query*)params[1];
if (Query::IsValidQuery(p_cQuery))
{
static const unsigned int static_args = 3;
std::string strFormat;
Utilities::GetPawnString(amx, params[2], strFormat, Query::fieldLen);
for (unsigned int i = 0; i < strFormat.length(); i++)
{
std::string strField;
Utilities::GetPawnString(amx, params[static_args + (i * 2)], strField, Query::fieldLen);
cell *p_physAddr = nullptr;
amx_GetAddr(amx, params[static_args + (i * 2) + 1], &p_physAddr);
switch (strFormat[i])
{
case 'i':
// FALLTHROUGH
case 'd':
p_cQuery->Update(strField, std::to_string(static_cast<int>(*p_physAddr)));
break;
case 'f':
p_cQuery->Update(strField, std::to_string(amx_ctof(*p_physAddr)));
break;
case 's':
std::string strEntry;
Utilities::GetPawnString(amx, params[static_args + 1 + (i * 2)], strEntry, Query::entryLen);
p_cQuery->Update(strField, strEntry);
break;
}
}
}
else
logprintf("Query Builder: invalid query handle.");
return 0;
}
cell AMX_NATIVE_CALL Natives::QueryBuilder_Finish(AMX* amx, cell* params)
{
Query* p_cQuery = (Query*)params[1];
if (Query::IsValidQuery(p_cQuery))
{
switch (p_cQuery->GetQueryType())
{
case _QB_QUERY_TYPE_DELETE:
// FALLTHROUGH
case _QB_QUERY_TYPE_UPDATE:
p_cQuery->AddCondition();
break;
}
// Size should hold all variable parameters excluding the constant ones.
int size = params[0]/sizeof(cell) - 5;
if (p_cQuery != nullptr)
{
// Escape the query:
unsigned int queryLen = p_cQuery->GetQueryLen() + 1;
char* escapedQueryCStr = new char[queryLen];
g_Invoke->callNative
(&PAWN::mysql_escape_string,
p_cQuery->GetQuery().c_str(),
escapedQueryCStr,
queryLen,
p_cQuery->GetConnectionHandle(),
queryLen);
p_cQuery->Set(escapedQueryCStr);
delete[] escapedQueryCStr;
switch (params[2])
{
case 0:
// Regular unthreaded query (mysql_query)
return g_Invoke->callNative(&PAWN::mysql_query, p_cQuery->GetConnectionHandle(), p_cQuery->GetQuery().c_str(), !!params[3]);
break;
case 1:
// Threaded query (mysql_tquery)
// FALLTHROUGH
case 2:
// Threaded query, parallel (mysql_pquery)
if (size > 0)
{
cell* variableParams = new cell[size];
for (int i = 0; i < size; i++)
variableParams[i] = params[i + 6];
std::string strCallback, strFormat;
Utilities::GetPawnString(amx, params[4], strCallback, 33);
Utilities::GetPawnString(amx, params[5], strFormat, 17);
// Both natives have the EXACT same parameters.
g_Invoke->callNative(
(params[2] == 1) ? (&PAWN::mysql_tquery) : (&PAWN::mysql_pquery),
p_cQuery->GetConnectionHandle(),
p_cQuery->GetQuery().c_str(),
strCallback.c_str(),
strFormat.c_str(),
variableParams,
(cell) amx);
delete[] variableParams;
variableParams = nullptr;
}
break;
}
}
for (auto it = g_queryVec.begin(); it != g_queryVec.end(); it++)
{
if (*it == p_cQuery)
{
delete *it;
g_queryVec.erase(it);
break;
}
}
}
else
logprintf("Query Builder: invalid query handle.");
return 0;
}
cell AMX_NATIVE_CALL Natives::QueryBuilder_PrintQuery(AMX* amx, cell* params)
{
Query* p_cQuery = (Query*)params[1];
if (Query::IsValidQuery(p_cQuery))
p_cQuery->Print();
else
logprintf("Query Builder: invalid query handle.");
return 0;
}
cell AMX_NATIVE_CALL Natives::QueryBuilder_QueryLen(AMX* amx, cell* params)
{
Query* p_cQuery = (Query*)params[1];
if (Query::IsValidQuery(p_cQuery))
return (cell)p_cQuery->GetQueryLen();
else
logprintf("Query Builder: invalid query handle.");
return 0;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Free Query
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
cell AMX_NATIVE_CALL Natives::QueryBuilder_Build(AMX* amx, cell* params)
{
Query* p_cQuery = Query::Create(params[1], _QB_QUERY_TYPE_FREE);
if (!Query::IsValidQuery(p_cQuery))
{
logprintf("QueryBuilder: Empty table passed to QueryBuilder_Build.");
return 0;
}
return (cell)p_cQuery;
}
cell AMX_NATIVE_CALL Natives::QueryBuilder_Query(AMX* amx, cell* params)
{
Query* p_cQuery = (Query*)params[1];
if (Query::IsValidQuery(p_cQuery))
{
std::string strQuery;
Utilities::GetPawnString(amx, params[2], strQuery, 1024 + 1);
p_cQuery->Append(strQuery);
}
else
logprintf("Query Builder: invalid query handle passed to QueryBuilder_Query.");
return 0;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Other
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// QueryBuilder_GetQuery(Query:queryhandle, dest[], maxlength = sizeof(dest))
cell AMX_NATIVE_CALL Natives::QueryBuilder_GetQuery(AMX* amx, cell* params)
{
Query* p_cQuery = (Query*)params[1];
if (!Query::IsValidQuery(p_cQuery))
{
logprintf("QueryBuilder: invalid query handle passed to QueryBuilder_GetQuery");
return 0;
}
cell* amx_addr = nullptr;
amx_GetAddr(amx, params[2], &amx_addr);
amx_SetString(amx_addr, p_cQuery->GetQuery().c_str(), 0, 0, params[3]);
return 0;
}
cell AMX_NATIVE_CALL Natives::_QB_SetMaxLengths(AMX* amx, cell* params)
{
Query::SetMaxLens(params[1], params[2], params[3]);
return 0;
}
cell AMX_NATIVE_CALL Natives::_QB_Invoke_GetAddresses(AMX* amx, cell* params)
{
return g_Invoke->getAddresses();
}<file_sep>#ifndef _H_NATIVES
#define _H_NATIVES
#include "plugin.h"
namespace Natives
{
cell AMX_NATIVE_CALL QueryBuilder_Update (AMX* amx, cell* params);
cell AMX_NATIVE_CALL QueryBuilder_Finish (AMX* amx, cell* params);
cell AMX_NATIVE_CALL QueryBuilder_PrintQuery (AMX* amx, cell* params);
cell AMX_NATIVE_CALL QueryBuilder_QueryLen (AMX* amx, cell* params);
cell AMX_NATIVE_CALL QueryBuilder_UpdateString (AMX* amx, cell* params);
cell AMX_NATIVE_CALL QueryBuilder_UpdateInt (AMX* amx, cell* params);
cell AMX_NATIVE_CALL QueryBuilder_UpdateFloat (AMX* amx, cell* params);
cell AMX_NATIVE_CALL QueryBuilder_MultiUpdate (AMX* amx, cell* params);
cell AMX_NATIVE_CALL QueryBuilder_Insert (AMX* amx, cell* params);
cell AMX_NATIVE_CALL QueryBuilder_Delete (AMX* amx, cell* params);
cell AMX_NATIVE_CALL QueryBuilder_Build (AMX* amx, cell* params);
cell AMX_NATIVE_CALL QueryBuilder_Query (AMX* amx, cell* params);
cell AMX_NATIVE_CALL QueryBuilder_Select (AMX* amx, cell* params);
cell AMX_NATIVE_CALL QueryBuilder_GetQuery (AMX* amx, cell* params);
cell AMX_NATIVE_CALL _QB_Invoke_GetAddresses (AMX* amx, cell* params);
cell AMX_NATIVE_CALL _QB_SetMaxLengths (AMX* amx, cell* params);
}
#endif<file_sep>#pragma once
#define _QB_QUERY_TYPE_UPDATE (0)
#define _QB_QUERY_TYPE_INSERT (1)
#define _QB_QUERY_TYPE_DELETE (2)
#define _QB_QUERY_TYPE_SELECT (3)
#define _QB_QUERY_TYPE_FREE (4)
#include <string>
#include "plugin.h"
class Query
{
public:
/*
* constructors
*/
Query(std::string strTable, std::string strCondition, cell connectionHandle, unsigned short type);
/*
* Specific to insert queries.
*/
Query(std::string table, cell connectionHandle);
/*
* setters
*/
void Set(char* cStr);
void Update(const std::string& field, const std::string& entry);
void Insert(std::string field, std::string value);
void AddSelect(const std::string& field);
void AddSelect(void);
void AddCondition(void);
void Append(const std::string& entry);
/*
* getters
*/
cell GetConnectionHandle(void);
unsigned int GetQueryLen(void);
unsigned short GetQueryType(void);
std::string GetQuery(void);
/*
* other
*/
void Print(void);
/*
* static methods
*/
static Query* Create(AMX* amx, const cell& table, const cell& condition, cell connectionHandle, unsigned short type);
static Query* Create(cell connectionHandle, unsigned short type);
static void SetMaxLens(unsigned int fieldLen, unsigned int entryLen, unsigned int fieldsLen);
static bool IsValidQuery(Query* query);
/*
* static public members
*/
static unsigned int fieldLen;
static unsigned int entryLen;
static unsigned int fieldsLen;
private:
cell m_nConnectionHandle;
unsigned short m_nType;
std::string m_strQuery;
std::string m_strCondition;
/*
*private methods
*/
void inline InitQuery(int type, const std::string& table);
};
<file_sep>// LICENSES:
/*
* Copyright (C) 2014 Maxim "<NAME>.
*
* 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.
CREDITS:
Incognito - Original Invoke.cpp & Invoke.h
*/
#include <vector>
#include "plugin.h"
#include "query.h"
#include "natives.h"
#include "invoke.h"
void **ppPluginData;
logprintf_t logprintf;
std::vector<Query*> g_queryVec;
PLUGIN_EXPORT unsigned int PLUGIN_CALL Supports()
{
return SUPPORTS_VERSION | SUPPORTS_AMX_NATIVES;
}
PLUGIN_EXPORT bool PLUGIN_CALL Load(void **ppData)
{
pAMXFunctions = ppData[PLUGIN_DATA_AMX_EXPORTS];
logprintf = (logprintf_t) ppData[PLUGIN_DATA_LOGPRINTF];
g_Invoke = new Invoke;
logprintf("* Query Builder plugin by Maxi loaded successfuly.");
return true;
}
PLUGIN_EXPORT void PLUGIN_CALL Unload()
{
// Delete all queries.
for (auto it = g_queryVec.begin(); it != g_queryVec.end(); it++)
delete *it;
g_queryVec.clear();
logprintf("* Query Builder plugin by Maxi unloaded successfuly.");
}
AMX_NATIVE_INFO PluginNatives[] =
{
{"QueryBuilder_Update", Natives::QueryBuilder_Update},
{"QueryBuilder_Finish", Natives::QueryBuilder_Finish},
{"QueryBuilder_PrintQuery", Natives::QueryBuilder_PrintQuery},
{"QueryBuilder_UpdateString", Natives::QueryBuilder_UpdateString},
{"QueryBuilder_UpdateInt", Natives::QueryBuilder_UpdateInt},
{"QueryBuilder_UpdateFloat", Natives::QueryBuilder_UpdateFloat},
{"QueryBuilder_MultiUpdate", Natives::QueryBuilder_MultiUpdate},
{"QueryBuilder_QueryLen", Natives::QueryBuilder_QueryLen},
{"QueryBuilder_Insert", Natives::QueryBuilder_Insert},
{"QueryBuilder_Delete", Natives::QueryBuilder_Delete},
{"QueryBuilder_Query", Natives::QueryBuilder_Query},
{"QueryBuilder_Select", Natives::QueryBuilder_Select},
{"QueryBuilder_Build", Natives::QueryBuilder_Build},
{"QueryBuilder_GetQuery", Natives::QueryBuilder_GetQuery},
{"_QB_Invoke_GetAddresses", Natives::_QB_Invoke_GetAddresses},
{"_QB_SetMaxLengths", Natives::_QB_SetMaxLengths},
{NULL, NULL}
};
PLUGIN_EXPORT int PLUGIN_CALL AmxLoad( AMX *amx )
{
g_Invoke->amx_list.push_back(amx);
return amx_Register(amx, PluginNatives, -1);
}
PLUGIN_EXPORT int PLUGIN_CALL AmxUnload( AMX *amx )
{
for (std::list<AMX *>::iterator i = g_Invoke->amx_list.begin(); i != g_Invoke->amx_list.end(); ++i)
{
if (* i == amx)
{
g_Invoke->amx_list.erase(i);
break;
}
}
return AMX_ERR_NONE;
}<file_sep>#include "utils.h"
extern logprintf_t logprintf;
void Utilities::GetPawnString(AMX* amx, const cell& p_pawnString, std::string &strDest, int nLength)
{
if (p_pawnString == NULL)
{
strDest.clear();
}
else
{
cell *p_physAddr = nullptr;
amx_GetAddr(amx, p_pawnString, &p_physAddr);
if (p_physAddr != nullptr)
{
char
*p_szString = new char[nLength];
amx_GetString(p_szString, p_physAddr, 0, nLength);
strDest.assign(p_szString);
delete[] p_szString;
}
}
}
std::list<std::string> Utilities::Split(const std::string& src, char delimeter)
{
std::list<std::string> split_strings;
int lastIndex = 0;
for (unsigned int i = 0; i < src.length(); i++)
{
if (src.at(i) == delimeter)
{
split_strings.push_back(src.substr(lastIndex, i-lastIndex));
lastIndex = i + 1;
}
}
if (lastIndex != (src.length() - 1))
{
split_strings.push_back(src.substr(lastIndex, src.length()-lastIndex));
}
return split_strings;
}
void Utilities::TrimWhitespace(std::string& src)
{
for (auto it = src.begin(); it != src.end();)
{
if (*it == ' ')
it = src.erase(it);
else
it++;
}
}<file_sep>#ifndef _H_UTILS
#define _H_UTILS
#include <string>
#include <list>
#include "plugin.h"
namespace Utilities
{
void GetPawnString(AMX* amx, const cell& p_pawnString, std::string &strDest, int nLength);
void TrimWhitespace(std::string& src);
std::list<std::string> Split(const std::string& src, char delimeter);
}
#endif | d5fbba1cbe5004d34f3d7d969e0e80bc4e032d48 | [
"C++"
]
| 10 | C++ | MrMindyMind/Query_Builder | 6630394dec695e6fffc16550bb07c1ba36f8a5cb | eecfa630c329209f2efae72132459fcf62385afc |
refs/heads/master | <repo_name>bmanch/react-portfolio<file_sep>/app/components/children/Contact.js
import React from 'react';
const Contact = () => {
return (
<div className="container">
<div className="row">
<div className="col s12 m12 l8 offset-l2 center-align">
<h4>Get in touch</h4>
<div className="divider"></div>
<br />
<div className="col s10 offset-s1 m3 offset-m2 l4 offset-l1">
<h6 className="valign-wrapper"><i className="material-icons left">email</i><EMAIL></h6>
<h6 className="valign-wrapper"><img src="assets/img/twitter_icon.png" className="bird" />@bmanch7</h6>
</div>
<div className="col s10 offset-s1 m3 offset-m3 l4 offset-l3">
<h6><a className="valign-wrapper" href="https://www.linkedin.com/in/brian-l-manchester/" target="_blank"><img src="assets/img/linkedin_icon.png" className="bird" />LinkedIn</a></h6>
<h6><a className="valign-wrapper" href="https://github.com/bmanch" target="_blank"><img src="assets/img/github_icon.png" className="bird" />Github</a></h6>
<h6><a className="valign-wrapper" href="assets/files/Brian_Manchester_Resume.pdf" target="_blank"><i className="material-icons left">assignment</i>CV</a></h6>
</div>
</div>
</div>
</div>
);
};
export default Contact;
// <div className="col s12 m10 offset-m1 l8 offset-l2">
// <ul>
// <li><i className="material-icons left">email</i><EMAIL></li>
// <li><img src="assets/img/twitter_icon.png" className="bird left" />@bmanch7</li>
// </ul>
// </div><file_sep>/app/components/children/Home.js
import React, {Component} from 'react'
class Home extends Component {
constructor(props) {
super(props);
}
render() {
return (
<div className="container">
<div className="row" id="marquis">
<div className="col s4 offset-s4 m4 offset-m4 l3 offset-l1 center-align">
<img className="circle responsive-img" id="profpic" src="assets/img/profile_pic.jpg" />
<blockquote>
Graduate of The Coding Boot Camp at UNC, Chapel Hill
</blockquote>
</div>
<div className="col s12 m12 l6 offset-l1 center-align">
<h3><NAME></h3>
<h4>Full Stack Developer</h4>
<h4>Co-Founder of List Turtle™</h4>
<h5><a href="https://www.listturtle.com" target="_blank">www.listturlte.com</a></h5>
<br />
<div className="row" id="prof">
<h5>proficiencies</h5>
<br />
<div className="col s10 offset-s1">
<div className="chip">
Typescript
</div>
<div className="chip">
Javascript (es6+)
</div>
<div className="chip">
Node.js
</div>
<div className="chip">
Express
</div>
<div className="chip">
PostgresSQL
</div>
<div className="chip">
MySQL
</div>
<div className="chip">
REST APIs
</div>
<div className="chip">
GraphQL
</div>
<div className="chip">
React
</div>
<div className="chip">
Redux
</div>
<div className="chip">
Next.js
</div>
<div className="chip">
Material-UI
</div>
<div className="chip">
MongoDB
</div>
<div className="chip">
Angular
</div>
<div className="chip">
Socket.io
</div>
<div className="chip">
REST APIs
</div>
<div className="chip">
jQuery
</div>
<div className="chip">
Materialize CSS
</div>
<div className="chip">
Bootstrap
</div>
<div className="chip">
CSS3
</div>
<div className="chip">
HTML5
</div>
</div>
<div className="col s6 offset-s3 left-align">
<blockquote>
And more... Take a look at my apps for more details.
</blockquote>
</div>
</div>
</div>
</div>
<div className="divider"></div>
<div className="row">
<div className="col s12 center-align">
<h3>Featured Apps</h3>
</div>
<div className="col s10 offset-s1 m8 offset-m2 l6">
<div className="card medium hoverable sticky-action">
<div className="card-image waves-effect waves-block waves-light">
<img className="activator" src="assets/img/dopple.png" />
</div>
<div className="card-content">
<span className="card-title activator grey-text text-darken-4"><strong>Doppelgänger</strong><i className="material-icons right">keyboard_arrow_up</i></span>
<p>Expand your universe.</p>
</div>
<div className="card-action">
<a className="tooltipped" data-position="right" data-delay="50" data-tooltip="go to the app" href="https://doppelgaenger.herokuapp.com/" target="_blank"><i className="material-icons">desktop_mac</i></a>
<a className="tooltipped" data-position="right" data-delay="50" data-tooltip="see the code on github" href="https://github.com/Doppelganger-App/Doppelganger" target="_blank"><i className="material-icons">code</i></a>
</div>
<div className="card-reveal">
<span className="card-title grey-text text-darken-4"><strong>Doppelgänger</strong><i className="material-icons right">close</i></span>
<p><strong>Technologies...</strong></p>
<ul>
<li>MongoDB and Mongoose</li>
<li>Passport.js and Bcrypt (user authentication)</li>
<li>Socket.io</li>
<li>Node and Express</li>
<li>API Consumption</li>
<li>jQuery</li>
<li>Materialize CSS</li>
</ul>
<p><strong>Description...</strong></p>
<p>Doppelgänger asks for basic information. Are you a humanities or STEM person? Politically, are you left-leaning or right-leaning? Based on your response, Doppelgänger will
curate resources for you (news, videos, and podcasts) that are from the opposite perspective. What's more, you can learn how to speak with those of different allegiances by using
Doppelgänger's real-time chat app.</p>
</div>
</div>
</div>
<div className="col s10 offset-s1 m8 offset-m2 l6">
<div className="card medium hoverable sticky-action">
<div className="card-image waves-effect waves-block waves-light">
<img className="activator" src="assets/img/mern.png" />
</div>
<div className="card-content">
<span className="card-title activator grey-text text-darken-4"><strong>MERN News Search</strong><i className="material-icons right">keyboard_arrow_up</i></span>
<p>Search for and save news articles.</p>
</div>
<div className="card-action">
<a className="tooltipped" data-position="right" data-delay="50" data-tooltip="go to the app" href="https://intense-shelf-44096.herokuapp.com/" target="_blank"><i className="material-icons">desktop_mac</i></a>
<a className="tooltipped" data-position="right" data-delay="50" data-tooltip="see the code on github" href="https://github.com/bmanch/nytimes-search-react" target="_blank"><i className="material-icons">code</i></a>
</div>
<div className="card-reveal">
<span className="card-title grey-text text-darken-4"><strong>MERN News Search</strong><i className="material-icons right">close</i></span>
<p><strong>Technologies...</strong></p>
<ul>
<li>React and React Router pre-v4</li>
<li>ES6</li>
<li>MongoDB and Mongoose</li>
<li>Node and Express</li>
<li>API Consumption</li>
<li>Bootstrap</li>
</ul>
<p><strong>Description...</strong></p>
<p>This is a MERN SPA app that allows the you to search for articles and save articles.</p>
</div>
</div>
</div>
<div className="col s10 offset-s1 m8 offset-m2 l6">
<div className="card medium hoverable sticky-action">
<div className="card-image waves-effect waves-block waves-light">
<img className="activator" src="assets/img/truckin.png" />
</div>
<div className="card-content">
<span className="card-title activator grey-text text-darken-4"><strong>Truckin' Good</strong><i className="material-icons right">keyboard_arrow_up</i></span>
<p>Find and rate foodtrucks.</p>
</div>
<div className="card-action">
<a className="tooltipped" data-position="right" data-delay="50" data-tooltip="go to the app" href="https://still-sierra-11518.herokuapp.com/" target="_blank"><i className="material-icons">desktop_mac</i></a>
<a className="tooltipped" data-position="right" data-delay="50" data-tooltip="see the code on github" href="https://github.com/UNC-Otters/Food_Truck" target="_blank"><i className="material-icons">code</i></a>
</div>
<div className="card-reveal">
<span className="card-title grey-text text-darken-4"><strong>Truckin' Good</strong><i className="material-icons right">close</i></span>
<p><strong>Technologies...</strong></p>
<ul>
<li>MySQL and Sequelize</li>
<li>Multer-S3 and AWS S3 (file uploads and downloads)</li>
<li>Node and Express</li>
<li>API Consumption</li>
<li>jQuery</li>
<li>Bootstrap</li>
</ul>
<p><strong>Description...</strong></p>
<p>Truckin' Good enables you to find food trucks and rate them. We'll show you the average of each food truck's ratings along with their current tweets
so that you can see where they will be. Plus, you can download menus and write reviews. Do you have a food truck? You can enter your information into our
system (including uploading a menu), and we'll make your food truck available for users to find and rate.</p>
</div>
</div>
</div>
<div className="col s10 offset-s1 m8 offset-m2 l6">
<div className="card medium hoverable sticky-action">
<div className="card-image waves-effect waves-block waves-light">
<img className="activator" src="assets/img/aardy.png" />
</div>
<div className="card-content">
<span className="card-title activator grey-text text-darken-4"><strong>Aardvark</strong><i className="material-icons right">keyboard_arrow_up</i></span>
<p>Going to college? Let's talk expenses.</p>
</div>
<div className="card-action">
<a className="tooltipped" data-position="right" data-delay="50" data-tooltip="go to the app" href="https://bmanch.github.io/aardy-look/" target="_blank"><i className="material-icons">desktop_mac</i></a>
<a className="tooltipped" data-position="right" data-delay="50" data-tooltip="see the code on github" href="https://github.com/bmanch/aardy-look" target="_blank"><i className="material-icons">code</i></a>
</div>
<div className="card-reveal">
<span className="card-title grey-text text-darken-4"><strong>Aardvark</strong><i className="material-icons right">close</i></span>
<p><strong>Technologies...</strong></p>
<ul>
<li>Firebase</li>
<li>API Consumption</li>
<li>jQuery</li>
<li>Bootstrap</li>
<li>CSS3</li>
</ul>
<p><strong>Description...</strong></p>
<p>Aardvark is a college debt analysis tool. You give us some information about where you want to go to school, what you want to major in, and how much you think you will
contribute towards your education. Then, we'll let you know how much student loan debt you'll incur compared with your likely income level based on your choice of major. Plus,
we'll give you a forecast for what paying off your loans will look like in terms of monthly payments over a span of 5, 10, or 25 years.</p>
</div>
</div>
</div>
<div className="col s10 offset-s1 m8 offset-m2 l6 offset-l3">
<div className="card medium hoverable sticky-action">
<div className="card-image waves-effect waves-block waves-light">
<img className="activator" src="assets/img/newprof.png" />
</div>
<div className="card-content">
<span className="card-title activator grey-text text-darken-4"><strong>Portfolio</strong><i className="material-icons right">keyboard_arrow_up</i></span>
<p>My personal website.</p>
</div>
<div className="card-action">
<a className="tooltipped" data-position="right" data-delay="50" data-tooltip="go to the app" href="/" target="_blank"><i className="material-icons">desktop_mac</i></a>
<a className="tooltipped" data-position="right" data-delay="50" data-tooltip="see the code on github" href="https://github.com/bmanch/react-portfolio" target="_blank"><i className="material-icons">code</i></a>
</div>
<div className="card-reveal">
<span className="card-title grey-text text-darken-4"><strong>Portfolio</strong><i className="material-icons right">close</i></span>
<p><strong>Technologies...</strong></p>
<ul>
<li>React and React Router v4</li>
<li>Node and Express</li>
<li>ES6</li>
<li>Materialize CSS</li>
</ul>
<p><strong>Description...</strong></p>
<p>This is actually the SPA you are looking at right now. The entire site is built in React and routing is handled using React Router version 4. This app uses ES6 wherever possible!</p>
</div>
</div>
</div>
</div>
</div>
);
}
}
export default Home;<file_sep>/app/components/children/Nav.js
import React, { Component } from 'react';
import {Link} from 'react-router-dom';
class Nav extends Component {
constructor(props) {
super(props);
}
componentDidMount() {
$(".button-collapse").sideNav();
}
render() {
return (
<div>
<div className="navbar-fixed">
<nav className="cyan darken-4" id="top">
<div className="container">
<div className="nav-wrapper">
<a href="/" className="brand-logo center">blm</a>
<a data-activates="mobile" className="button-collapse"><i className="material-icons">menu</i></a>
<ul id="nav-mobile" className="hide-on-med-and-down">
<li><a className="valign-wrapper" href="assets/files/Brian_Manchester_Resume.pdf" target="_blank"><i className="material-icons left">assignment</i>CV</a></li>
<li><a className="valign-wrapper" href="https://www.linkedin.com/in/brian-l-manchester/" target="_blank"><img src="assets/img/linkedin_icon_white.png" className="icon left" />LinkedIn</a></li>
<li><a className="valign-wrapper" href="https://github.com/bmanch" target="_blank"><img src="assets/img/github_icon_white.png" className="icon left" />Github</a></li>
</ul>
<ul id="nav-mobile" className="right hide-on-med-and-down">
<li><Link to="/">Home</Link></li>
<li><Link to="/portfolio">Apps</Link></li>
<li><Link to="/contact">Contact</Link></li>
</ul>
</div>
</div>
</nav>
</div>
<ul className="side-nav" id="mobile">
<li><a className="valign-wrapper" href="assets/files/Brian_Manchester_Resume.pdf" target="_blank"><i className="material-icons left sidecon">assignment</i>CV</a></li>
<li><a className="valign-wrapper" href="https://www.linkedin.com/in/brian-l-manchester/" target="_blank"><img src="assets/img/linkedin_icon.png" className="icon left" />LinkedIn</a></li>
<li><a className="valign-wrapper" href="https://github.com/bmanch" target="_blank"><img src="assets/img/github_icon.png" className="icon left" />Github</a></li>
</ul>
<div className="navbar-fixed">
<nav className="hide-on-large-only" id="white">
<div className="container">
<ul>
<li><Link to="/">Home</Link></li>
<li><Link to="/portfolio">Apps</Link></li>
<li><Link to="/contact">Contact</Link></li>
</ul>
</div>
</nav>
</div>
</div>
);
}
};
export default Nav;<file_sep>/app/components/Main.js
import React from 'react';
import Nav from './children/Nav';
import Body from './children/Body';
const Main = () => {
return (
<div>
<Nav />
<Body />
</div>
);
};
export default Main; | d94a94685ae14c93651b713b99d80766eeead0c8 | [
"JavaScript"
]
| 4 | JavaScript | bmanch/react-portfolio | f3d59a10110300212021b5630132220890ed7c27 | ee1d4c7d0073ec343cbc1604902b600f68dbfdb3 |
refs/heads/master | <repo_name>stfalcon-studio/dng2jpg<file_sep>/README.md
dng2jpg
=======
Конвертер графических файлов из формата DNG в формат JPEG
=======
Требования при сборке:
-----------
Для сборки необходим CMake и mingw-4.8, и настроенная среда с наличием утилиты make (например, MSYS или Qt SDK).
Требования при запуске:
-----------
Должен быть установлен кодек от Adobe: DNGCodec.dll http://www.adobe.com/support/downloads/product.jsp?product=194&platform=Windows
Использование
-----------
```
dng2jpg <input_file> <output_file>
```
Где:
<input_file> - полный путь к входящему файлу DNG
<output_file> - полный путь, куда надо сохранить результат в JPG
<file_sep>/main.cpp
#include <windows.h>
#include <wincodec.h>
#include <assert.h>
#include <iostream>
#ifndef WINVER // Allow use of features specific to Windows XP or later.
#define WINVER 0x0501 // Change this to the appropriate value to target other versions of Windows.
#endif
#ifndef _WIN32_WINNT // Allow use of features specific to Windows XP or later.
#define _WIN32_WINNT 0x0501 // Change this to the appropriate value to target other versions of Windows.
#endif
#ifndef _WIN32_WINDOWS // Allow use of features specific to Windows 98 or later.
#define _WIN32_WINDOWS 0x0410 // Change this to the appropriate value to target Windows Me or later.
#endif
#ifndef _WIN32_IE // Allow use of features specific to IE 6.0 or later.
#define _WIN32_IE 0x0600 // Change this to the appropriate value to target other versions of IE.
#endif
#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers
#define HR(hr, errstr) \
if(FAILED(hr)) { \
std::cerr << errstr << std::endl; \
printHresultError(hr); \
return EXIT_FAILURE; \
} \
template <typename T>
inline void SafeRelease(T *&p)
{
if (NULL != p) {
p->Release();
p = NULL;
}
}
void printHresultError(const HRESULT hr)
{
LPTSTR errorText = NULL;
FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM|FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_IGNORE_INSERTS,
NULL, hr, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&errorText, 0, NULL);
if ( NULL != errorText ) {
std::cerr << errorText << std::endl;
LocalFree(errorText);
errorText = NULL;
}
}
unsigned GetStride(const unsigned width, const unsigned bitsPerPixel)
{
assert(0 == bitsPerPixel % 8);
const unsigned byteCount = bitsPerPixel / 8;
const unsigned stride = (width * byteCount + 3) & ~3;
assert(0 == stride % sizeof(DWORD));
return stride;
}
int main(int argc, char *argv[])
{
// check args
if(argc != 3) {
std::cerr << "Wrong args count. Usage:\n\ndng2jpeg <input_file> <output_file>" << std::endl;
return EXIT_FAILURE;
}
setlocale( LC_ALL, "" );
HRESULT hr = S_OK;
// initialize COM
hr = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);
HR(hr, "Can't init COM");
// Create WIC factory
IWICImagingFactory *factory = NULL;
hr = CoCreateInstance(CLSID_WICImagingFactory, NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&factory));
HR(hr, "Can't create IWICImagingFactory");
//Decode the source image to IWICBitmapSource
//Create a decoder
IWICBitmapDecoder *decoder = NULL;
std::wstring inFileName;
mbstowcs( &inFileName[0], argv[1], strlen(argv[1])+1);
hr = factory->CreateDecoderFromFilename(inFileName.data(), NULL, GENERIC_READ,
WICDecodeMetadataCacheOnDemand, &decoder);
HR(hr, "Can't create IWICBitmapDecoder");
//Retrieve the first frame of the image from the decoder
IWICBitmapFrameDecode *sourceFrame = NULL;
hr = decoder->GetFrame(0, &sourceFrame);
HR(hr, "Can't get frame");
// create JPEG encoder
IWICBitmapEncoder* encoder = NULL;
hr = factory->CreateEncoder(GUID_ContainerFormatJpeg, NULL, &encoder);
HR(hr, "Can't create encoder");
IWICStream *outStream = NULL;
hr = factory->CreateStream(&outStream);
HR(hr, "Can't create stream");
wchar_t* outFileName = new wchar_t[strlen(argv[2])+1];
mbstowcs(outFileName, argv[2], strlen(argv[2])+1);
hr = outStream->InitializeFromFilename(outFileName, GENERIC_WRITE);
delete outFileName;
HR(hr, std::string("Can't InitializeFromFilename ") + argv[2]);
hr = encoder->Initialize(outStream, WICBitmapEncoderNoCache);
HR(hr, "Can't initialize encoder");
UINT width = 0;
UINT height = 0;
hr = sourceFrame->GetSize(&width, &height);
HR(hr, "Can't get size from source frame");
GUID pixelFormat = { 0, 0, 0, 0 };
hr = sourceFrame->GetPixelFormat(&pixelFormat);
HR(hr, "Can't get pixel format from source frame");
// Prepare the target frame
IWICBitmapFrameEncode *targetFrame = NULL;
hr = encoder->CreateNewFrame(&targetFrame, 0);
HR(hr, "Can't create target frame");
hr = targetFrame->Initialize(0);
HR(hr, "Can't init target frame");
hr = targetFrame->SetSize(width, height);
HR(hr, "Can't setSize to target frame");
hr = targetFrame->SetPixelFormat(&pixelFormat);
HR(hr, "Can't setPixelFormat to target frame");
// Copy the pixels and commit frame
hr = targetFrame->WriteSource(sourceFrame, 0);
HR(hr, "Can't write source to target frame");
hr = targetFrame->Commit();
HR(hr, "Can't commit to target frame");
// Commit image to stream
hr = encoder->Commit();
HR(hr, "Can't commit to encoder");
SafeRelease(factory);
SafeRelease(decoder);
SafeRelease(encoder);
SafeRelease(sourceFrame);
SafeRelease(targetFrame);
SafeRelease(outStream);
return EXIT_SUCCESS;
}
<file_sep>/CMakeLists.txt
project(dng2jpg)
add_definitions(-Wall -O2 -Wextra -std=c++11 -pedantic)
set( SOURCES main.cpp )
add_executable(${PROJECT_NAME} ${SOURCES})
target_link_libraries(${PROJECT_NAME} WindowsCodecs Ole32)
| c3353c2b7b1d1ad78d4531ff39cbe0cccb2a8df0 | [
"Markdown",
"CMake",
"C++"
]
| 3 | Markdown | stfalcon-studio/dng2jpg | 9982c11e8a72ec7d805e99d8a8484c5a7a1afb3b | 0b4548833f30e929953fa774311d82ef065094c8 |
refs/heads/master | <repo_name>aski/packer-boxes<file_sep>/scripts/vagrant.sh
#!/usr/bin/env bash
set -x
set -e
date > /etc/vagrant_box_build_time
echo "==> Create vagrant user and groups"
groupadd vagrant
useradd vagrant -g vagrant -G wheel
echo "vagrant" | passwd --stdin vagrant
echo "==> Configure sudo permissions for vagrant"
echo "%vagrant ALL=(ALL) NOPASSWD: ALL" >> /etc/sudoers.d/vagrant
chmod 0440 /etc/sudoers.d/vagrant
echo "==> Add default vagrant public key to authorized_keys file"
mkdir -pm 700 /home/vagrant/.ssh
curl \
--output /home/vagrant/.ssh/authorized_keys \
--create-dirs \
--location https://raw.github.com/mitchellh/vagrant/master/keys/vagrant.pub
chmod 0600 /home/vagrant/.ssh/authorized_keys
chown -R vagrant /home/vagrant/.ssh
<file_sep>/scripts/virtualbox.sh
#! /usr/bin/env bash
set -x
set -e
echo "==> Compiling and installing virtualbox guest additions"
yum install -y bzip2 kernel-devel kernel-headers make gcc
mount -o loop /root/VBoxGuestAdditions.iso /mnt
sh /mnt/VBoxLinuxAdditions.run
yum history undo -y last
<file_sep>/scripts/cleanup.sh
DISK_USAGE_BEFORE_CLEANUP=$(df -h)
echo "==> Clear out machine id"
rm -f /etc/machine-id
touch /etc/machine-id
echo "==> Remove mac addresses from network config files"
rm -f /etc/udev/rules.d/70-persistent-net.rules
for ifcfg in $(ls /etc/sysconfig/network-scripts/ifcfg-*)
do
if [ "$(basename ${ifcfg})" != "ifcfg-lo" ]
then
sed -i '/^UUID/d' "${ifcfg}"
sed -i '/^HWADDR/d' "${ifcfg}"
fi
done
echo "==> Remove rescue kernel"
rm -f /boot/initramfs*rescue*
rm -r /boot/vmlinuz-0-rescue-*
grub2-mkconfig -o /boot/grub2/grub.cfg
echo "==> Remove old kernels"
yum install -y -q yum-utils
package-cleanup --oldkernels --count=1 -y -q
echo "==> Clear yum cache"
yum -y clean all
rm -rf /var/cache/yum
echo "==> Rebuild rpm deb and delete cache"
rm -rf /var/lib/rpm/__*
rpmdb --rebuilddb -v -v
echo "==> Remove all files from /root"
rm -rf /root/*
echo "==> Delete root's bash history"
unset HISTFILE
rm -f /root/.bash_history
echo "==> Clear tmp directory"
rm -rf /tmp/*
echo "==> Blank out all files in /var/log"
find /var/log -type f | while read f; do echo -ne '' > $f; done;
echo "==> Clear out swap space"
set +e
swapuuid=$(/sbin/blkid -o value -l -s UUID -t TYPE=swap)
case "$?" in
2|0) ;;
*) exit 1 ;;
esac
set -e
if [ "x${swapuuid}" != "x" ]; then
# Whiteout the swap partition to reduce box size
# Swap is disabled till reboot
swappart=$(readlink -f /dev/disk/by-uuid/$swapuuid)
/sbin/swapoff "${swappart}"
dd if=/dev/zero of="${swappart}" bs=1M || echo "dd exit code $? is suppressed"
/sbin/mkswap -U "${swapuuid}" "${swappart}"
fi
echo "==> Zero all blank space on /boot"
dd if=/dev/zero of=/boot/EMPTY bs=1M | true
rm -f /boot/EMPTY
echo "==> Zero all blank space on /"
dd if=/dev/zero of=/EMPTY bs=1M | true
rm -f /EMPTY
sync
sleep 30
echo "==> Disk usage before cleanup"
echo "${DISK_USAGE_BEFORE_CLEANUP}"
echo "==> Disk usage after cleanup"
df -h
| a852ec90f4a07c172316c69fcd3d5046c9da04a7 | [
"Shell"
]
| 3 | Shell | aski/packer-boxes | 28648bc9707d5839981a1de4acb7de179f584a6d | 81a1c8d92cb5b046ae7306c4bb117aa74614d02f |
refs/heads/master | <repo_name>harry-chiu/react-e-commerce<file_sep>/src/containers/CheckOut/components/Payment.js
import React, { useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import clsx from 'clsx';
import {
Grid,
TextField,
makeStyles,
Select,
MenuItem,
Typography,
IconButton,
Avatar,
} from '@material-ui/core';
import { formActions } from '../../../actions';
const { setForm } = formActions;
const months = ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12'];
const years = [...Array(100).keys()];
const icons = [
{
name: 'MasterCard',
src: 'https://image.flaticon.com/icons/svg/196/196561.svg',
},
{
name: 'VISA',
src: 'https://image.flaticon.com/icons/svg/196/196578.svg',
},
{
name: 'PayPal',
src: 'https://image.flaticon.com/icons/svg/174/174861.svg',
},
];
const useStyles = makeStyles(theme => ({
container: {
margin: 'auto',
maxWidth: 720,
[theme.breakpoints.down('sm')]: {
maxWidth: '100%',
},
},
content: {
marginBottom: theme.spacing(2),
},
textField: {
minWidth: 240,
},
cvv: {
width: 60,
},
iconContainer: {
margin: theme.spacing(1, 0),
},
icon: {
border: '2px solid #eeeeee',
boxSizing: 'border-box',
margin: theme.spacing(0, 1),
'&:hover': {
background: '#ffe8ef',
},
},
active: {
background: '#ffeff4',
borderColor: '#ffeff4',
},
}));
const Payment = ({confirmation}) => {
const classes = useStyles();
const dispatch = useDispatch();
const form = useSelector(state => state.form);
const [selected, setSelected] = useState(form.card || 'MasterCard');
const handleSelect = (name) => {
setSelected(name);
dispatch(setForm('card', name));
};
return (
<div className={classes.container}>
<Typography variant="h6">
Card
</Typography>
<div className={classes.iconContainer}>
{icons.map(({ name, src }) => (
<IconButton
key={name}
disabled={confirmation}
onClick={() => handleSelect(name)}
className={clsx(classes.icon, selected === name ? classes.active : null)}
>
<Avatar src={src} />
</IconButton>
))}
</div>
<Typography variant="h6">
Card Info
</Typography>
<Grid container spacing={2} className={classes.content}>
<Grid item>
<TextField
fullWidth
label="Cardholder Name"
disabled={confirmation}
className={classes.textField}
value={form.cardholderName || ''}
onChange={event => dispatch(setForm('cardholderName', event.target.value))}
/>
</Grid>
<Grid item>
<TextField
fullWidth
label="Card Number"
disabled={confirmation}
className={classes.textField}
value={form.cardNumber || ''}
onChange={event => dispatch(setForm('cardNumber', event.target.value))}
/>
</Grid>
</Grid>
<Grid container spacing={5}>
<Grid item>
<Typography variant="h6">
End Date
</Typography>
<Grid container spacing={2}>
<Grid item>
<Select
value={form.endMonth || 0}
disabled={confirmation}
onChange={event => dispatch(setForm('endMonth', event.target.value))}
>
<MenuItem value={0} disabled>MM</MenuItem>
{months.map(month => (
<MenuItem value={month} key={month}>{month}</MenuItem>
))}
</Select>
</Grid>
<Grid item>
<Select
value={form.endYear || 0}
disabled={confirmation}
onChange={event => dispatch(setForm('endYear', event.target.value))}
>
<MenuItem value={0} disabled>YYYY</MenuItem>
{years.map(year => (
<MenuItem value={1900 + year} key={year}>{1900 + year}</MenuItem>
))}
</Select>
</Grid>
</Grid>
</Grid>
<Grid item>
<Typography variant="h6">
CVV
</Typography>
<TextField
value={form.cvv || ''}
className={classes.cvv}
disabled={confirmation}
onChange={event => dispatch(setForm('cvv', event.target.value))}
/>
</Grid>
</Grid>
</div>
);
};
export default Payment;<file_sep>/src/components/NavigationBar/index.js
import React from 'react';
import {
Slide,
AppBar,
Toolbar,
Typography,
useScrollTrigger,
makeStyles,
IconButton,
} from '@material-ui/core';
import { Menu as MenuIcon } from '@material-ui/icons';
const HideOnScroll = props => {
const { children, window } = props;
const trigger = useScrollTrigger({ target: window ? window() : undefined });
return (
<Slide appear={false} direction="down" in={!trigger}>
{children}
</Slide>
);
};
const useStyles = makeStyles((theme) => ({
menuButton: {
marginRight: theme.spacing(2),
},
title: {
flexGrow: 1,
},
appBar: {
boxSizing: 'border-box',
color: '#333333',
background: '#ffffff',
boxShadow: 'none',
borderBottom: '1px solid rgba(0, 0, 0, 0.12)',
},
}));
const NavigationBar = props => {
const classes = useStyles();
const { setOpen } = props;
return (
<HideOnScroll {...props}>
<AppBar className={classes.appBar}>
<Toolbar>
<IconButton
edge="start"
color="inherit"
className={classes.menuButton}
onClick={() => setOpen(true)}
>
<MenuIcon />
</IconButton>
<Typography variant="h6" className={classes.title}>
E-Commerce
</Typography>
</Toolbar>
</AppBar>
</HideOnScroll>
);
};
export default NavigationBar;<file_sep>/src/containers/CheckOut/components/Delivery.js
import React from 'react';
import { useSelector, useDispatch } from 'react-redux';
import {
Grid,
TextField,
makeStyles,
Typography,
Select,
MenuItem,
FormControl,
InputLabel,
} from '@material-ui/core';
import { formActions } from '../../../actions';
const { setForm } = formActions;
const useStyles = makeStyles(theme => ({
container: {
margin: 'auto',
maxWidth: 720,
[theme.breakpoints.down('sm')]: {
maxWidth: '100%',
},
},
textField: {
minWidth: 240,
maxWidth: 496,
},
title: {
margin: theme.spacing(1, 0),
},
formControl: {
minWidth: 180,
maxWidth: 320,
},
content: {
marginBottom: theme.spacing(2),
},
}));
const Delivery = ({confirmation}) => {
const classes = useStyles();
const dispatch = useDispatch();
const form = useSelector(state => state.form);
return (
<div className={classes.container}>
<Typography variant="h6" className={classes.title}>
Info
</Typography>
<Grid container spacing={2} className={classes.content}>
<Grid item>
<TextField
fullWidth
label="<NAME>"
className={classes.textField}
disabled={confirmation}
value={form.firstName || ''}
onChange={event => dispatch(setForm('firstName', event.target.value))}
/>
</Grid>
<Grid item>
<TextField
fullWidth
label="<NAME>"
className={classes.textField}
disabled={confirmation}
value={form.lastName || ''}
onChange={event => dispatch(setForm('lastName', event.target.value))}
/>
</Grid>
</Grid>
<Typography variant="h6" className={classes.title}>
Contact
</Typography>
<Grid container spacing={2} className={classes.content}>
<Grid item>
<TextField
fullWidth
label="Phone"
className={classes.textField}
disabled={confirmation}
value={form.phone || ''}
onChange={event => dispatch(setForm('phone', event.target.value))}
/>
</Grid>
<Grid item>
<TextField
fullWidth
label="E-mail"
className={classes.textField}
disabled={confirmation}
value={form.email || ''}
onChange={event => dispatch(setForm('email', event.target.value))}
/>
</Grid>
</Grid>
<Typography variant="h6" className={classes.title}>
Shipping
</Typography>
<Grid container spacing={2} className={classes.content}>
<Grid item>
<FormControl fullWidth className={classes.formControl}>
<InputLabel>Country</InputLabel>
<Select
fullWidth
value={form.country || ''}
disabled={confirmation}
onChange={event => dispatch(setForm('country', event.target.value))}
>
<MenuItem value="Taiwan">Taiwan</MenuItem>
</Select>
</FormControl>
</Grid>
<Grid item>
<FormControl fullWidth className={classes.formControl}>
<InputLabel>City</InputLabel>
<Select
fullWidth
value={form.city || ''}
disabled={confirmation}
onChange={event => dispatch(setForm('city', event.target.value))}
>
<MenuItem value="Taipei">Taipei</MenuItem>
</Select>
</FormControl>
</Grid>
<Grid item>
<TextField
fullWidth
label="Address"
className={classes.textField}
disabled={confirmation}
value={form.address || ''}
onChange={event => dispatch(setForm('address', event.target.value))}
/>
</Grid>
</Grid>
</div>
);
};
export default Delivery;<file_sep>/src/components/ProductCard/index.js
import React from 'react';
import {
Grid,
Card,
Typography,
makeStyles,
} from '@material-ui/core';
const useStyles = makeStyles(theme => ({
card: {
transition: '0.2s ease-in-out',
'&:hover': {
transform: 'scale(1.1)',
},
},
fakeImage: {
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
width: '100%',
height: recommend => recommend ? 120 : 180,
color: theme.palette.text.secondary,
fontSize: theme.typography.h5.fontSize,
background: '#eeeeee',
[theme.breakpoints.down('sm')]: {
height: recommend => recommend ? 240 : 240,
},
},
price: {
color: '#e91e63',
},
horizentalPadding: {
padding: theme.spacing(1),
},
}));
const ProductCard = ({ title, price, recommend = false }) => {
const classes = useStyles(recommend);
return (
<Card variant="outlined" className={classes.card}>
<div className={classes.fakeImage}>
Image
</div>
<div className={classes.horizentalPadding}>
<Grid
container
alignItems="center"
className={classes.verticalMargin}
spacing={recommend ? null : 1}
>
<Grid item xs={recommend ? 12 : 'auto'}>
<Typography variant={recommend ? 'h6' : 'h5'} color="textSecondary" >
{title}
</Typography>
</Grid>
<Grid item>
<Typography variant="subtitle1" className={classes.price}>
$ {price}
</Typography>
</Grid>
</Grid>
{!recommend && (
<Typography variant="subtitle2" color="textSecondary">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce commodo quam vel aliquet sodales. Cras sit amet mollis turpis.
</Typography>
)}
</div>
</Card>
);
};
export default ProductCard;<file_sep>/src/components/Breadcrumbs/index.js
import React from 'react';
import {
NavLink,
useLocation,
} from 'react-router-dom';
import {
Breadcrumbs,
Typography,
makeStyles,
} from '@material-ui/core';
const pathnameMap = {
'/': 'Home',
'/products': 'Product',
'/checkout': 'Check Out',
};
const useStyles = makeStyles(theme => ({
container: {
margin: theme.spacing(2, 0),
},
navLink: {
color: '#737373',
textDecoration: 'none',
'&:hover': {
textDecoration: 'underline',
},
},
}));
const BreadcrumbsWrapper = () => {
const classes = useStyles();
const { pathname } = useLocation();
const pathnames = pathname.split('/');
return (
<div className={classes.container}>
<Breadcrumbs>
{pathname === '/' ? (
<Typography variant="h5" color="secondary">
{pathnameMap[pathname]}
</Typography>
) : (
pathnames.map((pathname, index) => {
const match = `/${pathname}`;
const title = pathnameMap[match] || pathname;
if (index === pathnames.length - 1) {
return (
<Typography key={index} variant="h5" color="secondary">
{title}
</Typography>
);
}
return (
<NavLink key={index} to={match} className={classes.navLink}>
<Typography variant="h5">
{title}
</Typography>
</NavLink>
);
})
)}
</Breadcrumbs>
</div>
);
};
export default BreadcrumbsWrapper;<file_sep>/src/constants/index.js
import cartConstants from './cartConstants';
import formConstants from './formConstants';
export {
cartConstants,
formConstants,
};<file_sep>/src/containers/Product/index.js
import React, { useState, useEffect } from 'react';
import { useLocation } from 'react-router-dom';
import { NavLink } from 'react-router-dom';
import {
Grid,
Select,
MenuItem,
makeStyles,
} from '@material-ui/core';
import products from '../../database/products';
import ProductCard from '../../components/ProductCard';
const useStyles = makeStyles(theme => ({
navLink: {
textDecoration: 'none',
},
toolbar: {
margin: theme.spacing(2, 0),
},
select: {
width: 120,
},
}));
const Product = () => {
const classes = useStyles();
const location = useLocation();
const categoryFromHome = location.category;
const [category, setCategory] = useState('All');
const [filteredProducts, setFilteredProducts] = useState([]);
useEffect(() => {
setCategory(categoryFromHome || 'All');
}, [categoryFromHome]);
useEffect(() => {
if (category === 'All') {
setFilteredProducts(products);
} else {
setFilteredProducts(products.filter(product => product.category === category));
}
}, [category]);
return (
<>
<div className={classes.toolbar}>
<Select
className={classes.select}
value={category}
onChange={event => setCategory(event.target.value)}
>
<MenuItem value="All">All</MenuItem>
<MenuItem value="Clothes">Clothes</MenuItem>
<MenuItem value="Pants">Pants</MenuItem>
<MenuItem value="Shoes">Shoes</MenuItem>
<MenuItem value="Decorations">Decorations</MenuItem>
</Select>
</div>
<Grid container spacing={3}>
{filteredProducts.map(({ id, title, price }) => (
<Grid item xs={12} sm={6} md={4} lg={3} key={id}>
<NavLink to={`/products/${id}`} className={classes.navLink}>
<ProductCard title={title} price={price} />
</NavLink>
</Grid>
))}
</Grid>
</>
);
};
export default Product;<file_sep>/src/containers/CheckOut/index.js
import React, { useState } from 'react';
import {
Grid,
Card,
CardHeader,
CardContent,
makeStyles,
} from '@material-ui/core';
import Stepper from './components/Stepper';
import ButtonGroup from './components/ButtonGroup';
import PriceTotal from '../../components/PriceTotal';
import Cart from './components/Cart';
import Delivery from './components/Delivery';
import Payment from './components/Payment';
import Confirmation from './components/Confirmation';
import Completed from './components/Completed';
const useStyles = makeStyles(theme => ({
card: {
padding: theme.spacing(2, 1),
},
content: {
display: 'flex',
flexDirection: 'column',
minHeight: 560,
},
footer: {
marginTop: 'auto',
},
}));
const CheckOut = () => {
const [step, setStep] = useState(0);
const classes = useStyles();
const renderContent = () => {
switch (step) {
case 0:
return <Cart />;
case 1:
return <Delivery />;
case 2:
return <Payment />;
case 3:
return <Confirmation />;
case 4:
return <Completed />;
default:
return '';
}
};
return (
<Card className={classes.card} variant="outlined">
<CardHeader title={<Stepper step={step} />} />
<CardContent className={classes.content}>
{renderContent()}
<Grid
container
alignItems="flex-end"
justify="flex-end"
spacing={1}
className={classes.footer}
>
<Grid item>
{step === 0 && (
<PriceTotal />
)}
</Grid>
<Grid item>
<ButtonGroup step={step} setStep={setStep} />
</Grid>
</Grid>
</CardContent>
</Card>
);
};
export default CheckOut;<file_sep>/src/actions/index.js
import cartActions from './cartActions';
import formActions from './formActions';
export {
cartActions,
formActions,
};<file_sep>/src/components/MenuDrawer/index.js
import React, { useState } from 'react';
import { NavLink } from 'react-router-dom';
import {
List,
ListItem,
ListItemIcon,
ListItemText,
Drawer,
makeStyles,
Collapse,
} from '@material-ui/core';
import {
Home as HomeIcon,
ShoppingBasket as ShoppingBasketIcon,
ExpandLess as ExpandLessIcon,
ExpandMore as ExpandMoreIcon
} from '@material-ui/icons';
const menuItems = [
{
id: 1,
title: 'Home',
pathname: '/',
icon: <HomeIcon />,
},
{
id: 2,
title: 'Category',
icon: <ShoppingBasketIcon />,
subMenuItems: [
{
id: 1,
title: 'Clothes',
pathname: '/products',
category: 'Clothes',
},
{
id: 2,
title: 'Pants',
pathname: '/products',
category: 'Pants',
},
{
id: 3,
title: 'Shoes',
pathname: '/products',
category: 'Shoes',
},
{
id: 4,
title: 'Decorations',
pathname: '/products',
category: 'Decorations',
},
],
},
];
const useStyles = makeStyles(theme => ({
list: {
width: 250,
},
navLink: {
textDecoration: 'none',
color: 'inherit',
},
nested: {
paddingLeft: theme.spacing(4),
},
}));
const MenuDrawer = ({ open, setOpen }) => {
const classes = useStyles();
const [collapse, setCollapse] = useState(true);
return (
<Drawer anchor="left" open={open} onClose={() => setOpen(false)}>
<div role="presentation" className={classes.list}>
<List>
{menuItems.map(({ id, icon, title, pathname, subMenuItems }) => {
if (subMenuItems) {
return (
<React.Fragment key={id}>
<ListItem button onClick={() => setCollapse(!collapse)}>
<ListItemIcon>{icon}</ListItemIcon>
<ListItemText primary={title} />
{collapse ? <ExpandLessIcon /> : <ExpandMoreIcon />}
</ListItem>
<Collapse in={collapse} timeout="auto" unmountOnExit>
<List disablePadding>
{subMenuItems.map(({ id, title, pathname, category }) => (
<NavLink
key={id}
to={{ pathname, category }}
className={classes.navLink}
onClick={() => setOpen(false)}
>
<ListItem button className={classes.nested}>
<ListItemText primary={title} />
</ListItem>
</NavLink>
))}
</List>
</Collapse>
</React.Fragment>
);
}
return (
<NavLink
key={id}
to={pathname}
className={classes.navLink}
onClick={() => setOpen(false)}
>
<ListItem button>
<ListItemIcon>{icon}</ListItemIcon>
<ListItemText primary={title} />
</ListItem>
</NavLink>
);
})}
</List>
</div>
</Drawer>
);
};
export default MenuDrawer;<file_sep>/src/containers/CheckOut/components/Stepper.js
import React from 'react';
import {
Step,
StepLabel,
Stepper,
Hidden,
makeStyles,
} from '@material-ui/core';
const useStyles = makeStyles(theme => ({
stepLabel: {
'& > .MuiStepLabel-iconContainer > .MuiStepIcon-root': {
color: theme.palette.secondary.light,
},
},
}));
const StepperWrapper = props => {
const classes = useStyles();
const { step } = props;
const renderMobileStepper = () => {
switch(step) {
case 0:
return 'Cart';
case 1:
return 'Delivery';
case 2:
return 'Payment';
case 3:
return 'Confirmation';
default:
return '';
}
};
const renderDesktopStepper = () => {
return (
<Stepper activeStep={step}>
<Step>
<StepLabel className={classes.stepLabel}>
Cart
</StepLabel>
</Step>
<Step>
<StepLabel className={classes.stepLabel}>
Delivery
</StepLabel>
</Step>
<Step>
<StepLabel className={classes.stepLabel}>
Payment
</StepLabel>
</Step>
<Step>
<StepLabel className={classes.stepLabel}>
Confirmation
</StepLabel>
</Step>
</Stepper>
);
};
return (
<>
<Hidden smUp>
{renderMobileStepper()}
</Hidden>
<Hidden smDown>
{renderDesktopStepper()}
</Hidden>
</>
);
};
export default StepperWrapper;<file_sep>/src/constants/formConstants.js
export default {
SET_FORM: 'SET_FORM',
};<file_sep>/src/actions/formActions.js
import { formConstants } from '../constants';
const { SET_FORM } = formConstants;
const setForm = (fieldName, value) => {
return {
type: SET_FORM,
payload: {
fieldName,
value,
},
};
};
export default {
setForm,
};<file_sep>/src/containers/Home/index.js
import React from 'react';
import { NavLink } from 'react-router-dom';
import clsx from 'clsx';
import {
Grid,
Card,
makeStyles,
Typography,
} from '@material-ui/core';
import CategoryCard from '../../components/CategoryCard';
import ProductCard from '../../components/ProductCard';
import categories from '../../database/categories';
import products from '../../database/products';
const useStyles = makeStyles(theme => ({
title: {
margin: theme.spacing(1, 0),
},
banner: {
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
width: '100%',
height: 360,
[theme.breakpoints.down('sm')]: {
height: 240,
},
},
bannerTitle: {
[theme.breakpoints.down('sm')]: {
fontSize: 48,
},
},
navLink: {
textDecoration: 'none',
},
}));
const Home = () => {
const classes = useStyles();
return (
<>
<NavLink to="/products/1" className={classes.navLink}>
<Card variant="outlined" className={clsx(classes.card, classes.banner)}>
<Typography variant="h1" color="textSecondary" className={classes.bannerTitle}>
Banner
</Typography>
</Card>
</NavLink>
<Typography variant="h4" className={classes.title}>
Product Categories
</Typography>
<Grid container spacing={3}>
{categories.map(({ id, category }) => (
<Grid item xs={12} sm={6} md={4} lg={3} key={id}>
<NavLink to={{ category, pathname: "/products" }} className={classes.navLink}>
<CategoryCard category={category} />
</NavLink>
</Grid>
))}
</Grid>
<Typography variant="h4" className={classes.title}>
Popular Products
</Typography>
<Grid container spacing={3}>
{products.map(({ id, title, price }) => (
<Grid item xs={12} sm={6} md={4} lg={3} key={id}>
<NavLink to={`/products/${id}`} className={classes.navLink}>
<ProductCard title={title} price={price} />
</NavLink>
</Grid>
))}
</Grid>
</>
);
};
export default Home;<file_sep>/src/reducers/cartReducer.js
import { cartConstants } from '../constants';
const {
ADD_PRODUCT,
REMOVE_PRODUCT,
} = cartConstants;
const initialState = {
productsInCart: JSON.parse(localStorage.getItem('cart')) || [],
};
export default (state = initialState, action) => {
switch (action.type) {
case ADD_PRODUCT:
return { ...state, productsInCart: [...action.payload] };
case REMOVE_PRODUCT:
return { ...state, productsInCart: [...action.payload] };
default:
return state;
}
};<file_sep>/src/containers/CheckOut/components/ButtonGroup.js
import React from 'react';
import clsx from 'clsx';
import { Button, makeStyles } from '@material-ui/core';
const useStyles = makeStyles(theme => ({
buttonGroup: {
float: 'right',
},
button: {
width: '80px',
margin: theme.spacing(0, 1),
},
hidden: {
display: 'none',
},
}));
const ButtonGroup = (props) => {
const { step, setStep } = props;
const classes = useStyles();
const previousStep = () => {
if (step > 0) {
setStep(step - 1);
}
};
const nextStep = () => {
if (step < 3) {
setStep(step + 1);
}
};
const handleSubmit = () => {
setStep(step + 1);
};
if (step > 3) {
return null;
}
return (
<div className={classes.buttonGroup}>
<Button
variant="outlined"
color="default"
onClick={previousStep}
className={clsx(classes.button, {
[classes.hidden]: step === 0,
})}
>
Prev
</Button>
<Button
variant="contained"
color="secondary"
onClick={nextStep}
className={clsx(classes.button, {
[classes.hidden]: step === 3,
})}
>
Next
</Button>
<Button
variant="contained"
color="secondary"
onClick={handleSubmit}
className={clsx(classes.button, {
[classes.hidden]: step !== 3,
})}
>
Submit
</Button>
</div>
);
};
export default ButtonGroup;<file_sep>/src/containers/CheckOut/components/Confirmation.js
import React from 'react';
import { makeStyles } from '@material-ui/core';
import Cart from './Cart';
import PriceTotal from '../../../components/PriceTotal';
import Delivery from './Delivery';
import Payment from './Payment';
const useStyles = makeStyles(theme => ({
container: {
maxWidth: 720,
margin: 'auto',
marginBottom: theme.spacing(2),
},
priceTotal: {
float: 'right',
},
content: {
paddingTop: theme.spacing(4),
},
textField: {
display: 'block',
},
}));
const Confirmation = () => {
const classes = useStyles();
return (
<div className={classes.container}>
<Cart />
<div className={classes.priceTotal}>
<PriceTotal />
</div>
<div className={classes.content}>
<Delivery confirmation />
<Payment confirmation />
</div>
</div>
);
};
export default Confirmation;<file_sep>/README.md
# React E-Commerce
An example to show the application of React-Router and LocalStorage.

## Demo
You can preview the live demo [here](https://harry-chiu.github.io/react-e-commerce).
## Technologies
- React
- React-Router
- LocalStorage
- Material-UI
<file_sep>/src/components/ShoppingCart/index.js
import React, { useState } from 'react';
import { NavLink, useLocation } from 'react-router-dom';
import { useSelector, useDispatch } from 'react-redux';
import {
Fab,
Grid,
Menu,
List,
ListItem,
ListItemIcon,
ListItemText,
ListItemSecondaryAction,
Divider,
makeStyles,
Avatar,
Button,
} from '@material-ui/core';
import {
ShoppingCartOutlined as ShoppingCartOutlinedIcon,
LocalMall as LocalMallIcon,
Close as CloseIcon,
DeleteOutline as DeleteOutlineIcon,
} from '@material-ui/icons';
import { cartActions } from '../../actions';
import PriceTotal from '../../components/PriceTotal';
const { removeProduct } = cartActions;
const useStyles = makeStyles(theme => ({
fab: {
position: 'fixed',
bottom: theme.spacing(2),
right: theme.spacing(2),
'&:hover': {
background: '#e40051',
},
},
list: {
minWidth: 320,
padding: 0,
},
pointer: {
cursor: 'pointer',
'&:hover': {
color: '#e91e63',
},
},
hint: {
height: 240,
textAlign: 'center',
color: theme.palette.text.secondary,
fontSize: theme.typography.subtitle2.fontSize,
},
hintIcon: {
width: 64,
height: 64,
},
menuBottom: {
padding: theme.spacing(1, 2),
},
navLink: {
textDecoration: 'none',
},
checkout: {
'&:hover': {
background: '#e40051',
},
},
}));
const ShoppingCart = () => {
const classes = useStyles();
const dispatch = useDispatch();
const { pathname } = useLocation();
const [anchorEl, setAnchorEl] = useState(null);
const { productsInCart } = useSelector(state => state.cart);
const handleClick = event => setAnchorEl(event.currentTarget);
const handleClose = () => setAnchorEl(null);
const handleRemoveProduct = index => dispatch(removeProduct(index));
if (pathname === '/checkout') {
return null;
}
return (
<>
<Fab color="secondary" className={classes.fab} onClick={handleClick}>
<ShoppingCartOutlinedIcon fontSize="large" />
</Fab>
<Menu
anchorEl={anchorEl}
open={Boolean(anchorEl)}
onClose={handleClose}
>
<List className={classes.list}>
<ListItem>
<ListItemText primary="Products in Cart" />
<ListItemSecondaryAction>
<CloseIcon onClick={handleClose} className={classes.pointer} />
</ListItemSecondaryAction>
</ListItem>
<Divider />
{productsInCart.length === 0 && (
<ListItem className={classes.hint}>
<Grid container direction="column">
<Grid item>
<ShoppingCartOutlinedIcon className={classes.hintIcon} />
</Grid>
<Grid item>
<ListItemText primary="You don't have any product in cart." />
</Grid>
</Grid>
</ListItem>
)}
{productsInCart.map(({ title, price, amount }, index) => (
<ListItem button key={index}>
<ListItemIcon>
<Avatar>
<LocalMallIcon />
</Avatar>
</ListItemIcon>
<ListItemText primary={`${title} * ${amount}`} secondary={`$ ${price * amount}`} />
<ListItemSecondaryAction>
<DeleteOutlineIcon onClick={() => handleRemoveProduct(index)} className={classes.pointer} />
</ListItemSecondaryAction>
</ListItem>
))}
<Divider />
<ListItem className={classes.menuBottom}>
<ListItemText primary={<PriceTotal />} />
<ListItemSecondaryAction>
<NavLink to="/checkout" className={classes.navLink}>
<Button
variant="contained"
color="secondary"
className={classes.checkout}
>
Check Out
</Button>
</NavLink>
</ListItemSecondaryAction>
</ListItem>
</List>
</Menu>
</>
);
};
export default ShoppingCart; | 5be1b5d9040c55fbae50d9e63e6c6b0e2b3413bd | [
"JavaScript",
"Markdown"
]
| 19 | JavaScript | harry-chiu/react-e-commerce | e7955e1f0cd7de2d2c916a7f260674cb248d539d | fd76d458bd014b227883fee7835a8188583eca8d |
refs/heads/master | <repo_name>WinGaming/weekly-game-jam-43<file_sep>/src/de/wingaming/present/entity/EntityBombSpawnerRight.java
package de.wingaming.present.entity;
import java.util.Random;
import de.wingaming.present.animation.AnimationManager;
import de.wingaming.present.utils.Location;
import de.wingaming.present.world.World;
public class EntityBombSpawnerRight extends Entity {
private long lastSpawn;
public EntityBombSpawnerRight(Location position, double width, double height) {
super(AnimationManager.getAnimation("bomb_spawner"), position, EntityType.BOMB_SPAWNER, width, height);
setGravity(false);
lastSpawn = System.currentTimeMillis();
}
@Override
public void update() {
super.update();
if (System.currentTimeMillis() - lastSpawn > 2500 + new Random().nextInt(100)) {
EntityPresentBomb bomb = new EntityPresentBomb(getPosition().clone().add(World.TILE_SIZE, 0), false);
getWorld().markEntityToSpawn(bomb);
lastSpawn = System.currentTimeMillis();
}
}
}<file_sep>/src/de/wingaming/present/world/TileType.java
package de.wingaming.present.world;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import de.wingaming.present.Main;
import de.wingaming.present.utils.ImageUtils;
import javafx.scene.image.Image;
public class TileType {
private static List<TileType> tiles = new ArrayList<>();
private static Map<String, TileType> types = new HashMap<>();
public static final TileType TILE_SHELF = new TileType(new Image(Main.class.getResourceAsStream("res/shelf.png")));
public static final TileType TILE_SHELF2 = new TileType(new Image(Main.class.getResourceAsStream("res/shelf2.png")));
public static final TileType TILE_BG = new TileType(new Image(Main.class.getResourceAsStream("res/background.png")));
public static final TileType TILE_GROUND_TOP = new TileType(new Image(Main.class.getResourceAsStream("res/ground_top.png"))).setSolid(true);
public static final TileType TILE_GROUND_TOP_LEFT = new TileType(new Image(Main.class.getResourceAsStream("res/ground_top_left.png"))).setSolid(true);
public static final TileType TILE_GROUND_TOP_RIGHT = new TileType(new Image(Main.class.getResourceAsStream("res/ground_top_right.png"))).setSolid(true);
public static final TileType ROCK = new TileType(new Image(Main.class.getResourceAsStream("res/rock.png"))).setSolid(true);
public static final TileType SNOW_TOP = new TileType(new Image(Main.class.getResourceAsStream("res/snow/snow_top.png"))).setSolid(true);
public static final TileType SNOW_BOTTOM = new TileType(new Image(Main.class.getResourceAsStream("res/snow/snow_bottom.png"))).setSolid(true);
public static final TileType SNOW_LEFT = new TileType(new Image(Main.class.getResourceAsStream("res/snow/snow_left.png"))).setSolid(true);
public static final TileType SNOW_RIGHT = new TileType(new Image(Main.class.getResourceAsStream("res/snow/snow_right.png"))).setSolid(true);
public static final TileType SNOW_TOP_LEFT = new TileType(new Image(Main.class.getResourceAsStream("res/snow/snow_top_left.png"))).setSolid(true);
public static final TileType SNOW_TOP_RIGHT = new TileType(new Image(Main.class.getResourceAsStream("res/snow/snow_top_right.png"))).setSolid(true);
public static final TileType SNOW_BOTTTOM_LEFT = new TileType(new Image(Main.class.getResourceAsStream("res/snow/snow_bottom_left.png"))).setSolid(true);
public static final TileType SNOW_BOTTTOM_RIGHT = new TileType(new Image(Main.class.getResourceAsStream("res/snow/snow_bottom_right.png"))).setSolid(true);
public static final TileType SNOW_NO_LEFT = new TileType(new Image(Main.class.getResourceAsStream("res/snow/snow_no_left.png"))).setSolid(true);
public static final TileType SNOW_TOPDOWN_RIGHT = new TileType(new Image(Main.class.getResourceAsStream("res/snow/snow_corner_topdown_right.png"))).setSolid(true);
public static final TileType SNOW_TOP_DOWN = new TileType(new Image(Main.class.getResourceAsStream("res/snow/snow_corner_top_down.png"))).setSolid(true);
public static final TileType SNOW_CORNER_TOP_LEFT = new TileType(new Image(Main.class.getResourceAsStream("res/snow/snow_corner_top_left.png"))).setSolid(true);
public static final TileType SNOW_CORNER_TOP_RIGHT = new TileType(new Image(Main.class.getResourceAsStream("res/snow/snow_corner_top_right.png"))).setSolid(true);
public static final TileType SNOW_CORNER_BOTTTOM_LEFT = new TileType(new Image(Main.class.getResourceAsStream("res/snow/snow_corner_bottom_left.png"))).setSolid(true);
public static final TileType SNOW_CORNER_BOTTTOM_RIGHT = new TileType(new Image(Main.class.getResourceAsStream("res/snow/snow_corner_bottom_right.png"))).setSolid(true);
public static final TileType UNDERGROUND = new TileType(new Image(Main.class.getResourceAsStream("res/underground.png")));
public static final TileType UNDERGROUND_TOP = new TileType(new Image(Main.class.getResourceAsStream("res/underground_top.png")));
public static final TileType LADDER = new TileType(new Image(Main.class.getResourceAsStream("res/ladder.png"))).setLadder(true);
public static final TileType CHEST = new TileType(new Image(Main.class.getResourceAsStream("res/chest.png"))).setLadder(true);
public static final TileType PLANKS = new TileType(new Image(Main.class.getResourceAsStream("res/planks.png"))).setSolid(true);
public static final TileType PLANKS_BROKEN = new TileType(new Image(Main.class.getResourceAsStream("res/planks_broken.png"))).setSolid(true);
public static final TileType PLANKS_DARK = new TileType(new Image(Main.class.getResourceAsStream("res/planks_dark.png")));
public static final TileType WATER = new TileType(new Image(Main.class.getResourceAsStream("res/water.png")));
static {
registerType("!", TILE_BG);
registerType("§", TILE_GROUND_TOP);
registerType("%", TILE_GROUND_TOP_LEFT);
registerType("&", TILE_GROUND_TOP_RIGHT);
registerType("/", TILE_SHELF);
registerType("(", TILE_SHELF2);
registerType(")", ROCK);
registerType("1", SNOW_TOP);
registerType("2", SNOW_BOTTOM);
registerType("3", SNOW_LEFT);
registerType("4", SNOW_RIGHT);
registerType("5", SNOW_TOP_LEFT);
registerType("6", SNOW_TOP_RIGHT);
registerType("7", SNOW_BOTTTOM_LEFT);
registerType("8", SNOW_BOTTTOM_RIGHT);
registerType("9", SNOW_CORNER_TOP_LEFT);
registerType("0", SNOW_CORNER_TOP_RIGHT);
registerType("z", SNOW_CORNER_BOTTTOM_LEFT);
registerType("?", SNOW_CORNER_BOTTTOM_RIGHT);
registerType("=", UNDERGROUND);
registerType("a", UNDERGROUND_TOP);
registerType("b", LADDER);
registerType("c", CHEST);
registerType("d", SNOW_NO_LEFT);
registerType("e", SNOW_TOPDOWN_RIGHT);
registerType("f", SNOW_TOP_DOWN);
registerType("g", PLANKS);
registerType("h", PLANKS_DARK);
registerType("i", PLANKS_BROKEN);
registerType("j", WATER);
}
private static int i;
public static void nextType() {
i++;
if (i >= tiles.size()) {
i = 0;
}
}
// public static TileType getCurrentType() {
// return tiles.get(i);
// }
public static void registerType(String symbol, TileType type) {
tiles.add(type);
types.put(symbol, type);
}
public static TileType getType(String symbol) {
return types.get(symbol);
}
public static String getSymbol(TileType type) {
for (String symbol : types.keySet()) {
if (types.get(symbol) == type)
return symbol;
}
return "*";
}
private boolean ladder;
private boolean solid;
private Image texture;
private TileType(Image texture) {
this.texture = ImageUtils.resample(texture, 2);
}
public TileType setSolid(boolean solid) {
this.solid = solid;
return this;
}
public TileType setLadder(boolean ladder) {
this.ladder = ladder;
return this;
}
public Image getTexture() {
return texture;
}
public boolean isSolid() {
return solid;
}
public boolean isLadder() {
return ladder;
}
}<file_sep>/src/de/wingaming/present/entity/EntityPresentBomb.java
package de.wingaming.present.entity;
import java.util.List;
import de.wingaming.present.animation.AnimationManager;
import de.wingaming.present.gui.GameOverlay;
import de.wingaming.present.utils.Location;
public class EntityPresentBomb extends Entity {
private boolean exploded = false;
private long spawnTime;
private boolean ignorePlayer = false;
public EntityPresentBomb(Location position, boolean ignorePlayer) {
super(AnimationManager.getAnimation("present_bomb"), position, EntityType.PRESENT_BOMB, 20, 20);
this.ignorePlayer = ignorePlayer;
spawnTime = System.currentTimeMillis();
setGravity(true);
}
@Override
public void update() {
super.update();
if (exploded) return;
if (System.currentTimeMillis() - spawnTime > 2000) {
getWorld().markEntityToRemove(this);
getWorld().markEntityToSpawn(new EntityExplosion(getPosition().clone()));
exploded = true;
return;
}
List<Entity> nearby = getWorld().getEntitiesInRadius(this.getPosition(), 1.5);
for (Entity entity : nearby) {
if (entity instanceof LivingEntity) {
getWorld().markEntityToRemove(this);
getWorld().markEntityToSpawn(new EntityExplosion(getPosition().clone()));
LivingEntity le = (LivingEntity) entity;
le.setHealth(le.getHealth()-2);
exploded = true;
break;
}
if (!ignorePlayer && entity.getType() == EntityType.PLAYER) {
getWorld().markEntityToRemove(this);
getWorld().markEntityToSpawn(new EntityExplosion(getPosition().clone()));
GameOverlay.showDamage();
exploded = true;
break;
}
}
}
}<file_sep>/src/de/wingaming/present/files/Loader.java
package de.wingaming.present.files;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import de.wingaming.present.animation.AnimationManager;
import de.wingaming.present.entity.Entity;
import de.wingaming.present.entity.EntityBalloon;
import de.wingaming.present.entity.EntityBombSpawnerRight;
import de.wingaming.present.entity.EntityChest;
import de.wingaming.present.entity.EntityChestBomb;
import de.wingaming.present.entity.EntityEvilBalloon;
import de.wingaming.present.entity.EntityExplosion;
import de.wingaming.present.entity.EntityPresent;
import de.wingaming.present.entity.EntityPresentBomb;
import de.wingaming.present.entity.EntityType;
import de.wingaming.present.entity.Friend;
import de.wingaming.present.entity.ParticleJumpHelper;
import de.wingaming.present.entity.ParticleLadderHelper;
import de.wingaming.present.entity.Player;
import de.wingaming.present.utils.Location;
import de.wingaming.present.world.TileType;
import de.wingaming.present.world.World;
public class Loader {
public static World loadWorld(String fileName) {
try {
// InputStream is = Main.class.getResourceAsStream("saves/"+fileName+".world");
File file = new File("saves/"+fileName+".world");
if (!file.exists()) {
World w = new World(fileName, null, null);
Location nLoc = new Location(w, 0, 0);
w.setPlayer(new Player(nLoc));
w.setFriend(new Friend(nLoc));
return w;
}
World world = new World(fileName, null, null);
Player player = new Player(new Location(world, 0, 0));
Friend friend = new Friend(new Location(world, 0, 0));
BufferedReader reader = new BufferedReader(new FileReader(file));
String line = null;
while((line = reader.readLine()) != null) {
if (line.contains(">>") && !line.contains(">>>")) {
//Blocks
String[] data = line.split(">>");
int dx = 0;
int y = Integer.parseInt(data[0]);
String blockString = data[1];
String[] blocksdata = blockString.split(";");
for (String blockdata : blocksdata) {
int count;
TileType type;
if (!blockdata.contains(",")) {
count = 1;
type = TileType.getType(blockdata);
} else {
String[] blockdataData = blockdata.split(",");
count = Integer.parseInt(blockdataData[0]);
type = TileType.getType(blockdataData[1]);
}
for (int i = 0; i < count; i++) {
world.setTile(i+dx, y, type);
}
dx += count;
}
} else if (line.startsWith("ent:")) {
String entityString = line.split(":")[1];
String[] data = entityString.split(",");
EntityType type = EntityType.UNKNOWN;
try { type = EntityType.valueOf(data[0]);
} catch (IllegalArgumentException ex) {}
double x = Double.parseDouble(data[1]);
double y = Double.parseDouble(data[2]);
Entity entity;
switch (type) {
case PRESENT:
entity = new EntityPresent(new Location(world, x, y));
break;
case LADDER_HELPER:
entity = new ParticleLadderHelper(new Location(world, x, y));
break;
case SPACE_HELPER:
entity = new ParticleJumpHelper(new Location(world, x, y));
break;
case CHEST_DOUBLEJUMP:
entity = new EntityChest(new Location(world, x, y));
break;
case CHEST_BOMB:
entity = new EntityChestBomb(new Location(world, x, y));
break;
case PRESENT_BOMB:
entity = new EntityPresentBomb(new Location(world, x, y), false);
break;
case BOMB_SPAWNER:
entity = new EntityBombSpawnerRight(new Location(world, x, y), 16, 16);
break;
case EXPLOSION:
entity = new EntityExplosion(new Location(world, x, y));
break;
case EVIL_BALLOON:
entity = new EntityEvilBalloon(new Location(world, x, y));
break;
case BALLOON:
entity = new EntityBalloon(new Location(world, x, y));
break;
default:
entity = new Entity(AnimationManager.getAnimation("unknown"), new Location(world, x, y), type, 32, 32);
break;
}
world.spawnEntity(entity);
} else if (line.contains(">>>")) {
//Blocks
String[] data = line.split(">>>");
int dx = 0;
int y = Integer.parseInt(data[0]);
String blockString = data[1];
String[] blocksdata = blockString.split(";");
for (String blockdata : blocksdata) {
int count;
TileType type;
if (!blockdata.contains(",")) {
count = 1;
type = TileType.getType(blockdata);
} else {
String[] blockdataData = blockdata.split(",");
count = Integer.parseInt(blockdataData[0]);
type = TileType.getType(blockdataData[1]);
}
for (int i = 0; i < count; i++) {
world.setDecoTile(i+dx, y, type);
}
dx += count;
}
} else if (line.startsWith("friend:")) {
String[] location = line.split(":")[1].split(",");
friend = new Friend(new Location(world, Double.parseDouble(location[0]), Double.parseDouble(location[1])));
} else if (line.startsWith("player:")) {
String[] location = line.split(":")[1].split(",");
player = new Player(new Location(world, Double.parseDouble(location[0]), Double.parseDouble(location[1])));
}
}
world.setFriend(friend);
world.setPlayer(player);
reader.close();
return world;
} catch (IOException ex) {
ex.printStackTrace();
World w = new World(fileName, null, null);
Location nLoc = new Location(w, 0, 0);
w.setPlayer(new Player(nLoc));
w.setFriend(new Friend(nLoc));
return w;
}
}
public static void saveWorld(String name, World world) {
File file = new File("saves/"+name+".world");
try {
if (!file.exists()) file.createNewFile();
TileType lastType = null;
int typeCount = 0;
StringBuilder builder = new StringBuilder();
for (int y = 0; y < world.getTiles().length; y++) {
builder.append(y+">>");
for (int x = 0; x < world.getTiles()[y].length; x++) {
TileType type = world.getTileTypeAt(x, y);
if (type != lastType) {
if (typeCount == 1)
builder.append(TileType.getSymbol(lastType)+";");
else
builder.append(typeCount+","+TileType.getSymbol(lastType)+";");
typeCount = 1;
lastType = type;
} else {
typeCount++;
}
}
typeCount = 0;
builder.append(typeCount+","+TileType.getSymbol(lastType)+"\n");
}
builder.append("\n");
for (int y = 0; y < world.getDecoTiles().length; y++) {
builder.append(y+">>>");
for (int x = 0; x < world.getDecoTiles()[y].length; x++) {
TileType type = world.getDecoTileTypeAt(x, y);
if (type != lastType) {
if (typeCount == 1)
builder.append(TileType.getSymbol(lastType)+";");
else
builder.append(typeCount+","+TileType.getSymbol(lastType)+";");
typeCount = 1;
lastType = type;
} else {
typeCount++;
}
}
typeCount = 0;
builder.append(typeCount+","+TileType.getSymbol(lastType)+"\n");
}
builder.append("\n");
for (Entity entity : world.getEntities()) {
if (entity.getType() == EntityType.PLAYER) {
builder.append("player:"+entity.getPosition().getX()+","+entity.getPosition().getY()+"\n");
} else if (entity.getType() == EntityType.FRIEND) {
builder.append("friend:"+entity.getPosition().getX()+","+entity.getPosition().getY()+"\n");
} else {
builder.append("ent:"+entity.getType().name()+","+entity.getPosition().getX()+","+entity.getPosition().getY()+"\n");
}
}
BufferedWriter writer = new BufferedWriter(new FileWriter(file));
writer.write(builder.toString());
writer.close();
System.out.println("Saved!");
} catch (IOException ex) {
ex.printStackTrace();
}
}
}<file_sep>/src/de/wingaming/present/entity/EntityType.java
package de.wingaming.present.entity;
public enum EntityType {
PLAYER, FRIEND, PRESENT, LADDER_HELPER, SPACE_HELPER, CHEST_DOUBLEJUMP, CHEST_BOMB, PRESENT_BOMB, UNKNOWN, EXPLOSION, BOMB_SPAWNER, EVIL_BALLOON, BALLOON
// public static final EntityType PLAYER = new EntityType("player", new Image("file:res/player.png"));
//
// private String name;
// private Image texture;
//
// private EntityType(String name, Image texture) {
// this.name = name;
// this.texture = ImageUtils.resample(texture, 2);
// }
//
// public Image getTexture() {
// return texture;
// }
//
// public String getName() {
// return name;
// }
}<file_sep>/src/de/wingaming/present/item/ItemBomb.java
package de.wingaming.present.item;
import de.wingaming.present.Main;
import de.wingaming.present.utils.ImageUtils;
import javafx.scene.image.Image;
public class ItemBomb extends Item {
public ItemBomb() {
super(ImageUtils.resample(new Image(Main.class.getResourceAsStream("res/items/bomb.png")), 2));
}
}<file_sep>/src/de/wingaming/present/gui/GameOverlay.java
package de.wingaming.present.gui;
import de.wingaming.present.Main;
import de.wingaming.present.gui.overlay.Inventory;
import de.wingaming.present.gui.overlay.Overlay;
import de.wingaming.present.gui.overlay.PresentBar;
import de.wingaming.present.render.RenderAble;
import de.wingaming.present.utils.ImageUtils;
import de.wingaming.present.world.World;
import javafx.scene.image.Image;
public class GameOverlay implements RenderAble {
private PresentBar presentBar;
private Inventory inventory;
private Image displayDamage = ImageUtils.resample(new Image(Main.class.getResourceAsStream("res/displayDamage.png")), 2);
private Image displayAu = ImageUtils.resample(new Image(Main.class.getResourceAsStream("res/displayAu.png")), 2);
private Image ad = ImageUtils.resample(new Image(Main.class.getResourceAsStream("res/AD.png")), 4);
private Image space = ImageUtils.resample(new Image(Main.class.getResourceAsStream("res/space.png")), 4);
private static long damageStart = System.currentTimeMillis();
private static boolean showDamage = false;
private static long AuStart = System.currentTimeMillis();
private static boolean showAu = false;
public GameOverlay() {
this.presentBar = Overlay.presentBar;
this.inventory = Overlay.inventory;
}
public static void showDamage() {
showDamage = true;
damageStart = System.currentTimeMillis();
}
public static void showAu() {
showAu = true;
AuStart = System.currentTimeMillis();
}
@Override
public void update() {
if (System.currentTimeMillis() - damageStart > 2600) {
showDamage = false;
}
if (System.currentTimeMillis() - AuStart > 2600) {
showAu = false;
}
}
@Override
public void render() {
presentBar.render();
inventory.render();
Overlay.itemInfo.render();
Overlay.presentInfo.render();
Overlay.presentInfo2.render();
Overlay.jumpTipInfo.render();
if (inventory.getItem(0) != null) Overlay.itemDoublejumpInfo.render();
Overlay.bombInfo.render();
if (inventory.getItem(1) != null) Overlay.dropInfo.render();
Overlay.bombDamage.render();
if (showDamage)
Main.gc.drawImage(displayDamage, 0, 0, Main.WIDTH, Main.HEIGHT);
if (showAu)
Main.gc.drawImage(displayAu, 0, 0, Main.WIDTH, Main.HEIGHT);
Main.gc.drawImage(ad, 400-Main.game.getCurrentWorld().getCamera().getX()*World.TILE_SIZE, 450-Main.game.getCurrentWorld().getCamera().getY()*World.TILE_SIZE, 29*3.5, 19*3.5);
Main.gc.drawImage(space, 740-Main.game.getCurrentWorld().getCamera().getX()*World.TILE_SIZE, 605-Main.game.getCurrentWorld().getCamera().getY()*World.TILE_SIZE, 23*3.5, 9*3.5);
Overlay.adMove.render();
Overlay.jumpMove.render();
Overlay.ladder.render();
Overlay.bombDelay.render();
Overlay.goal.render();
Overlay.e1.render();
Overlay.e2.render();
Overlay.e3.render();
Overlay.e4.render();
Overlay.e5.render();
}
}<file_sep>/src/de/wingaming/present/entity/EntityEvilBalloon.java
package de.wingaming.present.entity;
import java.util.List;
import de.wingaming.present.Main;
import de.wingaming.present.animation.AnimationManager;
import de.wingaming.present.gui.GameOverlay;
import de.wingaming.present.utils.Location;
public class EntityEvilBalloon extends LivingEntity {
public EntityEvilBalloon(Location position) {
super(20, AnimationManager.getAnimation("evil_balloon"), position, EntityType.EVIL_BALLOON, 9*2.5, 32*2.5);
getVelocity().setX(1);
}
@Override
public void update() {
super.update();
getVelocity().setY(Main.game.getCurrentWorld().getPlayer().getVelocity().getY());
// if (Main.game.getCurrentWorld().getPlayer().getPosition().getX()+Main.game.getCurrentWorld().getPlayer().getWidth() > getPosition().getX()) {
// Main.game.getCurrentWorld().getPlayer().getPosition().setX(getPosition().getX()-Main.game.getCurrentWorld().getPlayer().getWidth());
// Main.game.getCurrentWorld().getPlayer().getVelocity().setX(-2);
// }
List<Entity> entities = getWorld().getEntitiesInRadius(getPosition().clone().add(getWidth()/2, getHeight()/2), 2.75);
for (Entity entity : entities) {
if (entity.getType() == EntityType.PLAYER) {
GameOverlay.showAu();
}
}
}
@Override
public void collideX() {
getVelocity().setX(-getVelocity().getX());
}
}
<file_sep>/src/de/wingaming/present/camera/Camera.java
package de.wingaming.present.camera;
public class Camera {
private double x = 0;
private double y = 0;
public Camera() {}
public Camera(double x, double y) {this.x = x; this.y = y;}
public void update() {
// if (KeyboardManager.isDown(KeyCode.RIGHT)) {
// increasePosition(0.125, 0);
// }
//
// if (KeyboardManager.isDown(KeyCode.LEFT)) {
// increasePosition(-0.125, 0);
// }
//
// if (KeyboardManager.isDown(KeyCode.UP)) {
// increasePosition(0, -0.125);
// }
//
// if (KeyboardManager.isDown(KeyCode.DOWN)) {
// increasePosition(0, 0.125);
// }
}
public void increasePosition(double dx, double dy) {
this.x += dx;
this.y += dy;
}
public void setX(double x) {
this.x = x;
}
public void setY(double y) {
this.y = y;
}
public double getX() {
return x;
}
public double getY() {
return y;
}
}<file_sep>/src/de/wingaming/present/entity/LivingEntity.java
package de.wingaming.present.entity;
import de.wingaming.present.animation.Animation;
import de.wingaming.present.utils.Location;
public class LivingEntity extends Entity {
private double health, maxHealth;
private long damageAnimationStarted;
public LivingEntity(double maxHealth, Animation animation, Location position, EntityType type, double width, double height) {
super(animation, position, type, width, height);
this.health = this.maxHealth = maxHealth;
}
@Override
public void update() {
super.update();
if (this.health <= 0) {
getWorld().markEntityToRemove(this);
}
if (getAnimation().getCurrentAnimation().equals("damaged") && System.currentTimeMillis()-damageAnimationStarted > 250) {
getAnimation().setCurrentAnimation("default");
}
}
public void setHealth(double health) {
if (health <= this.health) {
getAnimation().setCurrentAnimation("damaged");
damageAnimationStarted = System.currentTimeMillis();
}
this.health = health;
}
public double getHealth() {
return health;
}
public double getMaxHealth() {
return maxHealth;
}
}<file_sep>/src/de/wingaming/present/world/World.java
package de.wingaming.present.world;
import java.util.ArrayList;
import java.util.List;
import de.wingaming.present.Main;
import de.wingaming.present.camera.Camera;
import de.wingaming.present.entity.Entity;
import de.wingaming.present.entity.Friend;
import de.wingaming.present.entity.Player;
import de.wingaming.present.math.Vector2d;
import de.wingaming.present.particle.Particle;
import de.wingaming.present.utils.Location;
public class World {
public static int TILE_SIZE = 16;
public static final int tilesInViewWidth = Main.WIDTH/TILE_SIZE+1, tilesInViewHeight = Main.HEIGHT/TILE_SIZE+1;
private TileType[][] tiles = new TileType[511][511];
private TileType[][] decoTiles = new TileType[511][511];
private Camera camera;
private Player player;
private Friend friend;
private final Vector2d gravity = new Vector2d(0, -0.15);
public static final double DEBUG_FACTOR = 0.00001;
private List<Entity> entities = new ArrayList<>();
private List<Particle> particles = new ArrayList<>();
private String name;
private boolean paused = false;
public World(String name, Player character, Friend friend) {
this.name = name;
this.camera = new Camera();
this.player = character;
this.friend = friend;
spawnEntity(friend);
spawnEntity(player);
}
public void setPaused(boolean paused) {
this.paused = paused;
}
public boolean isPaused() {
return paused;
}
public void setFriend(Friend friend) {
removeEntity(this.friend);
this.friend = friend;
spawnEntity(friend);
}
public void setPlayer(Player player) {
removeEntity(this.player);
this.player = player;
spawnEntity(player);
}
public String getName() {
return name;
}
public void update() {
//TODO: put in if
camera.update();
if (!paused) {
for (Entity entity : entityRemoveList) {
removeEntity(entity);
}
for (Entity entity : entitySpawnList) {
spawnEntity(entity);
}
entityRemoveList.clear();
entitySpawnList.clear();
for (Entity entity : entities) {
entity.update();
}
player.update();
friend.update();
}
}
public void render() {
int dx = (int) camera.getX();
int dy = (int) camera.getY();
double xDiff = (camera.getX() < 0 ? -1 : 1) * Math.abs(camera.getX()-dx)*TILE_SIZE;
double yDiff = (camera.getY() < 0 ? -1 : 1) * Math.abs(camera.getY()-dy)*TILE_SIZE;
for (int y = 0; y < tilesInViewHeight; y++) {
for (int x = 0; x < tilesInViewWidth; x++) {
int tileX = x+dx;
int tileY = y+dy;
if (!(tileX < 0 || tileY < 0) && !(tileX > tiles.length || tileY > tiles.length) && tiles[tileY][tileX] != null)
Main.gc.drawImage(tiles[tileY][tileX].getTexture(), x*TILE_SIZE-xDiff, y*TILE_SIZE-yDiff, TILE_SIZE, TILE_SIZE);
// else
// PresentGame.gc.drawImage(TileType.TILE_GROUND_TOP.getTexture(), x*TILE_SIZE-xDiff, y*TILE_SIZE-yDiff, TILE_SIZE, TILE_SIZE);
}
}
for (int y = 0; y < tilesInViewHeight; y++) {
for (int x = 0; x < tilesInViewWidth; x++) {
int tileX = x+dx;
int tileY = y+dy;
if (!(tileX < 0 || tileY < 0) && !(tileX > decoTiles.length || tileY > decoTiles.length) && decoTiles[tileY][tileX] != null)
Main.gc.drawImage(decoTiles[tileY][tileX].getTexture(), x*TILE_SIZE-xDiff, y*TILE_SIZE-yDiff, TILE_SIZE, TILE_SIZE);
}
}
for (Entity entity : entities) {
Main.gc.drawImage(entity.getCurrentTexture(), entity.getPosition().getX()-camera.getX()*TILE_SIZE, entity.getPosition().getY()-camera.getY()*TILE_SIZE, entity.getWidth(), entity.getHeight());
}
Main.gc.drawImage(friend.getCurrentTexture(), friend.getPosition().getX()-camera.getX()*TILE_SIZE, friend.getPosition().getY()-camera.getY()*TILE_SIZE, friend.getWidth(), friend.getHeight());
Main.gc.drawImage(player.getCurrentTexture(), player.getPosition().getX()-camera.getX()*TILE_SIZE, player.getPosition().getY()-camera.getY()*TILE_SIZE, player.getWidth(), player.getHeight());
for (Particle particle : particles) {
Main.gc.drawImage(particle.getTexture(), particle.getX(), particle.getY(), particle.getWidth(), particle.getHeight());
}
}
public void spawnEntity(Entity entity) {
if (!entities.contains(entity)) entities.add(entity);
}
public void removeEntity(Entity entity) {
if (entities.contains(entity)) entities.remove(entity);
}
public void addPartcle(Particle particle) {
if (!particles.contains(particle)) particles.add(particle);
}
public void removePartcle(Particle particle) {
if (particles.contains(particle)) particles.remove(particle);
}
public List<Entity> getEntitiesInRadius(Location loc, double radius) {
List<Entity> result = new ArrayList<>();
for (Entity entityEntry : entities) {
if (loc.toVector().distance(entityEntry.getPosition().clone().add(entityEntry.getWidth()/2, entityEntry.getHeight()).toVector())/TILE_SIZE <= radius) {
result.add(entityEntry);
}
}
return result;
}
public List<Entity> getEntities() {
return entities;
}
public void setTile(int x, int y, TileType type) {
tiles[y][x] = type;
}
public TileType getTileTypeAt(int x, int y) {
return y >= tiles.length || y < 0 || x >= tiles[y].length || x < 0 ? null : tiles[y][x];
}
public void setDecoTile(int x, int y, TileType type) {
decoTiles[y][x] = type;
}
public TileType getDecoTileTypeAt(int x, int y) {
return y >= decoTiles.length || y < 0 || x >= decoTiles[y].length || x < 0 ? null : decoTiles[y][x];
}
public Location collide(Entity entity, Location startLocation, double dx, double dy) {
Location targetLocation = startLocation.clone().add(dx, dy);
Location result = targetLocation.clone();
Location topLeft = result.clone();
Location bottomRight = result.clone().add(entity.getWidth(), entity.getHeight());
if (dy != 0) {
Location toLocation = startLocation.clone().add(0, dy);
Location newLocation = startLocation.clone();
int xCount = bottomRight.getTileX() - topLeft.getTileX() + 1;
List<Location> testLocations = new ArrayList<>();
if (dy > 0) {
for (int i = 0; i < xCount; i++) {
testLocations.add(new Location(entity.getWorld(), toLocation.getX()+i*TILE_SIZE, toLocation.getY()+entity.getHeight()));
}
if (collide(testLocations)) {
newLocation.setY(toLocation.clone().add(0, entity.getHeight()).getTileY()*TILE_SIZE-entity.getHeight()-DEBUG_FACTOR);
entity.collideY(true);
} else {
newLocation.add(0, dy);
}
} else if (dy < 0) {
for (int i = 0; i < xCount; i++) {
testLocations.add(new Location(entity.getWorld(), toLocation.getX()+i*TILE_SIZE, toLocation.getY()));
}
if (collide(testLocations)) {
newLocation.setY(toLocation.getTileY()*TILE_SIZE+TILE_SIZE+DEBUG_FACTOR);
entity.collideY(false);
} else {
newLocation.add(0, dy);
}
}
return collide(entity, newLocation, dx, 0);
} else if (dx != 0) {
Location toLocation = startLocation.clone().add(dx, 0);
Location newLocation = startLocation.clone();
int yCount = bottomRight.getTileY() - topLeft.getTileY() + 1;
List<Location> testLocations = new ArrayList<>();
if (dx > 0) {
for (int i = 0; i < yCount; i++) {
testLocations.add(new Location(entity.getWorld(), toLocation.getX()+entity.getWidth(), toLocation.getY()+i*TILE_SIZE));
}
if (collide(testLocations)) {
newLocation.setX(toLocation.clone().add(entity.getWidth(), 0).getTileX()*TILE_SIZE-entity.getWidth()-DEBUG_FACTOR);
entity.collideX();
} else {
newLocation.add(dx, 0);
}
} else if (dx < 0) {
for (int i = 0; i < yCount; i++) {
testLocations.add(new Location(entity.getWorld(), toLocation.getX(), toLocation.getY()+i*TILE_SIZE));
}
if (collide(testLocations)) {
newLocation.setX(toLocation.getTileX()*TILE_SIZE+TILE_SIZE+DEBUG_FACTOR);
entity.collideX();
} else {
newLocation.add(dx, 0);
}
}
return collide(entity, newLocation, 0, dy);
} else {
return targetLocation;
}
}
private boolean collide(List<Location> locations) {
for (Location location : locations) {
int x = location.getTileX();
int y = location.getTileY();
if (getTileTypeAt(x, y) != null) {
if (getTileTypeAt(x, y).isSolid()) {
return true;
}
}
}
return false;
}
public Camera getCamera() {
return camera;
}
public Vector2d getGravity() {
return gravity;
}
private List<Entity> entityRemoveList = new ArrayList<>();
public void markEntityToRemove(Entity entity) {
entityRemoveList.add(entity);
}
private List<Entity> entitySpawnList = new ArrayList<>();
public void markEntityToSpawn(Entity entity) {
entitySpawnList.add(entity);
}
public TileType[][] getTiles() {
return tiles;
}
public TileType[][] getDecoTiles() {
return decoTiles;
}
public Player getPlayer() {
return player;
}
}<file_sep>/src/de/wingaming/present/gui/overlay/InfoText.java
package de.wingaming.present.gui.overlay;
import de.wingaming.present.Main;
import de.wingaming.present.world.World;
import javafx.scene.paint.Color;
public class InfoText {
private String text;
private double x, y;
private Color color = Color.WHITE;
public InfoText(double x, double y, String text) {
this.x = x;
this.y = y;
this.text = text;
}
public void render() {
Main.gc.setFill(color);
Main.gc.setFont(Main.gc.getFont().font(20));
Main.gc.fillText(text, x-100 + 20 - Main.game.getCurrentWorld().getCamera().getX()*World.TILE_SIZE, y + 25 + 20/2 - Main.game.getCurrentWorld().getCamera().getY()*World.TILE_SIZE);
}
public double getX() {
return x;
}
public double getY() {
return y;
}
public InfoText setColor(Color color) {
this.color = color;
return this;
}
}<file_sep>/src/de/wingaming/present/entity/Friend.java
package de.wingaming.present.entity;
import java.util.List;
import de.wingaming.present.Main;
import de.wingaming.present.animation.AnimationManager;
import de.wingaming.present.input.KeyboardManager;
import de.wingaming.present.particle.Particle;
import de.wingaming.present.utils.ImageUtils;
import de.wingaming.present.utils.Location;
import de.wingaming.present.world.TileType;
import de.wingaming.present.world.World;
import javafx.scene.image.Image;
import javafx.scene.input.KeyCode;
public class Friend extends Entity {
private Particle particleKey;
public Friend(Location position) {
super(AnimationManager.getAnimation("friend"), position, EntityType.FRIEND, 22*0.75, 50*0.75);
this.particleKey = new Particle(getPosition().getX(), getPosition().getY(), 16, 16, ImageUtils.resample(new Image(Main.class.getResourceAsStream("res/keys/e.png")), 2));
}
@Override
public void update() {
super.update();
particleKey.setX(getPosition().getX() - Main.game.getCurrentWorld().getCamera().getX()*World.TILE_SIZE);
particleKey.setY(getPosition().getY() - getHeight()/2 - Main.game.getCurrentWorld().getCamera().getY()*World.TILE_SIZE);
boolean found = false;
List<Entity> nearby = getWorld().getEntitiesInRadius(this.getPosition().clone().add(-getWidth(), getHeight()), 0.75);
for (Entity entity : nearby) {
if (entity.getType() == EntityType.PLAYER) {
((Player) entity).setCanControll(false);
// Overlay.presentBar.setCollected(0);
Main.game.getCurrentWorld().addPartcle(particleKey);
if (KeyboardManager.isDown(KeyCode.E)) {
for (int y = -1; y < 2; y++) {
for (int x = -2; x < 3; x++) {
int rx = x+getPosition().getTileX();
int ry = (int) (y+((getPosition().getY()+getHeight())/World.TILE_SIZE));
if (getWorld().getTileTypeAt(rx, ry) != null)
getWorld().setTile(rx, ry, TileType.PLANKS_DARK);
}
}
}
found = true;
break;
}
}
if (!found) {
Main.game.getCurrentWorld().removePartcle(particleKey);
}
}
}<file_sep>/src/de/wingaming/present/gui/overlay/Inventory.java
package de.wingaming.present.gui.overlay;
import de.wingaming.present.Main;
import de.wingaming.present.item.Item;
import de.wingaming.present.utils.ImageUtils;
import javafx.scene.image.Image;
public class Inventory {
private static Image slot = ImageUtils.resample(new Image(Main.class.getResourceAsStream("res/overlay/slot.png")), 2);
private Item[] items = new Item[3];
private double slot_width = 32;
private double x, y;
public Inventory(double x, double y) {
this.x = x;
this.y = y;
}
public void render() {
double width = 3*slot_width+3*5;
double halfWidth = width/2;
Main.gc.drawImage(slot, x-halfWidth, y, slot_width, slot_width);
Main.gc.drawImage(slot, x-halfWidth+slot_width+5, y, slot_width, slot_width);
Main.gc.drawImage(slot, x-halfWidth+2*(slot_width+5), y, slot_width, slot_width);
if (items[0] != null) Main.gc.drawImage(items[0].getImage(), x-halfWidth, y, slot_width, slot_width);
if (items[1] != null) Main.gc.drawImage(items[1].getImage(), x-halfWidth+slot_width+5, y, slot_width, slot_width);
if (items[2] != null) Main.gc.drawImage(items[2].getImage(), x-halfWidth+2*(slot_width+5), y, slot_width, slot_width);
}
public void setItem(int slot, Item item) {
items[slot] = item;
}
public Item getItem(int slot) {
return items[slot];
}
public double getX() {
return x;
}
public double getY() {
return y;
}
}<file_sep>/src/de/wingaming/present/item/ItemGraplingHook.java
package de.wingaming.present.item;
import de.wingaming.present.Main;
import de.wingaming.present.utils.ImageUtils;
import javafx.scene.image.Image;
public class ItemGraplingHook extends Item {
public ItemGraplingHook() {
super(ImageUtils.resample(new Image(Main.class.getResourceAsStream("res/items/hook.png")), 2));
}
}<file_sep>/src/de/wingaming/present/entity/ParticleJumpHelper.java
package de.wingaming.present.entity;
import java.util.List;
import de.wingaming.present.Main;
import de.wingaming.present.animation.AnimationManager;
import de.wingaming.present.particle.Particle;
import de.wingaming.present.utils.ImageUtils;
import de.wingaming.present.utils.Location;
import de.wingaming.present.world.World;
import javafx.scene.image.Image;
public class ParticleJumpHelper extends Entity {
private Particle particle;
public ParticleJumpHelper(Location position) {
super(AnimationManager.getAnimation("empty"), position, EntityType.SPACE_HELPER, 16, 16);
setGravity(false);
this.particle = new Particle(getPosition().getX()-8, getPosition().getY()-8, 16, 16, ImageUtils.resample(new Image(Main.class.getResourceAsStream("res/keys/space.png")), 32));
}
@Override
public void update() {
super.update();
particle.setX(getPosition().getX()-8 - Main.game.getCurrentWorld().getCamera().getX()*World.TILE_SIZE);
particle.setY(getPosition().getY()-8 - Main.game.getCurrentWorld().getCamera().getY()*World.TILE_SIZE);
List<Entity> nearby = getWorld().getEntitiesInRadius(this.getPosition(), 3);
boolean found = false;
for (Entity entity : nearby) {
if (entity.getType() == EntityType.PLAYER) {
getWorld().addPartcle(particle);
found = true;
break;
}
}
if (!found)
getWorld().removePartcle(particle);
}
}
| dc7b051246ccfa38eaf13964427febd7f3e3117f | [
"Java"
]
| 16 | Java | WinGaming/weekly-game-jam-43 | 2d98c9b7807b6023bde617645930295e5bfbf57f | 77e6aa550fd0a9f14b9bbce56c2ed04a2def5b19 |
refs/heads/master | <file_sep>from capstone import *
from capstone.ppc import * # powerpc
from capstone.arm import * # ARM 32
from capstone.arm64 import * # ARM 64
import os, binascii
fp = open("codebreaker2.exe", "rb")
FP_CODE = fp.read()
code_base = (
"\x43\x20\x0c\x07\x41\x56\xff\x17\x80\x20\x00\x00\x80\x3f\x00\x00\x10\x43\x23\x0e\xd0\x44\x00\x80\x4c\x43\x22\x02\x2d\x03\x00\x80\x7c\x43\x20\x14\x7c\x43\x20\x93\x4f\x20\x00\x21\x4c\xc8\x00\x21\x40\x82\x00\x14",
"\x8d\x4c\x32\x08\x01\xd8\x81\xc6\x34\x12\x00\x00",
"\x8d\x4c\x32\x08\x01\xd8\x81\xc6\x34\x12\x00\x00",
"\x55\x48\x8b\x05\xb8\x13\x00\x00",
"\xED\xFF\xFF\xEB\x04\xe0\x2d\xe5\x00\x00\x00\x00\xe0\x83\x22\xe5\xf1\x02\x03\x0e\x00\x00\xa0\xe3\x02\x30\xc1\xe7\x00\x00\x53\xe3",
"\x10\xf1\x10\xe7\x11\xf2\x31\xe7\xdc\xa1\x2e\xf3\xe8\x4e\x62\xf3",
"\x70\x47\xeb\x46\x83\xb0\xc9\x68",
"\x4f\xf0\x00\x01\xbd\xe8\x00\x88",
"\xef\xf3\x02\x80",
"\xe0\x3b\xb2\xee\x42\x00\x01\xe1\x51\xf0\x7f\xf5",
"\x0C\x10\x00\x97\x00\x00\x00\x00\x24\x02\x00\x0c\x8f\xa2\x00\x00\x34\x21\x34\x56",
"\x56\x34\x21\x34\xc2\x17\x01\x00",
"\x00\x07\x00\x07\x00\x11\x93\x7c\x01\x8c\x8b\x7c\x00\xc7\x48\xd0",
"\xec\x80\x00\x19\x7c\x43\x22\xa0",
"\x09\x00\x38\xd5\xbf\x40\x00\xd5\x0c\x05\x13\xd5\x20\x50\x02\x0e\x20\xe4\x3d\x0f\x00\x18\xa0\x5f\xa2\x00\xae\x9e\x9f\x37\x03\xd5\xbf\x33\x03\xd5\xdf\x3f\x03\xd5\x21\x7c\x02\x9b\x21\x7c\x00\x53\x00\x40\x21\x4b\xe1\x0b\x40\xb9\x20\x04\x81\xda\x20\x08\x02\x8b\x10\x5b\xe8\x3c",
"\x80\x20\x00\x00\x80\x3f\x00\x00\x10\x43\x23\x0e\xd0\x44\x00\x80\x4c\x43\x22\x02\x2d\x03\x00\x80\x7c\x43\x20\x14\x7c\x43\x20\x93\x4f\x20\x00\x21\x4c\xc8\x00\x21",
"\x80\xa0\x40\x02\x85\xc2\x60\x08\x85\xe8\x20\x01\x81\xe8\x00\x00\x90\x10\x20\x01\xd5\xf6\x10\x16\x21\x00\x00\x0a\x86\x00\x40\x02\x01\x00\x00\x00\x12\xbf\xff\xff\x10\xbf\xff\xff\xa0\x02\x00\x09\x0d\xbf\xff\xff\xd4\x20\x60\x00\xd4\x4e\x00\x16\x2a\xc2\x80\x03",
"\x81\xa8\x0a\x24\x89\xa0\x10\x20\x89\xa0\x1a\x60\x89\xa0\x00\xe0",
"\xed\x00\x00\x00\x00\x1a\x5a\x0f\x1f\xff\xc2\x09\x80\x00\x00\x00\x07\xf7\xeb\x2a\xff\xff\x7f\x57\xe3\x01\xff\xff\x7f\x57\xeb\x00\xf0\x00\x00\x24\xb2\x4f\x00\x78",
"\xfe\x0f\xfe\x17\x13\x17\xc6\xfe\xec\x17\x97\xf8\xec\x4f\x1f\xfd\xec\x37\x07\xf2\x45\x5b\xf9\xfa\x02\x06\x1b\x10",
FP_CODE,
)
errors_for_type = dict()
all_tests = (
(CS_ARCH_X86, CS_MODE_16, "X86, 16 bit"),
(CS_ARCH_X86, CS_MODE_32, "X86, 32 bit"),
(CS_ARCH_X86, CS_MODE_64, "X86, 64 bit"),
(CS_ARCH_ARM, CS_MODE_ARM, "ARM"),
(CS_ARCH_ARM, CS_MODE_THUMB, "ARM THUMB"),
(CS_ARCH_ARM, CS_MODE_THUMB + CS_MODE_MCLASS, "ARM THUMB MCLASS"),
(CS_ARCH_ARM, CS_MODE_ARM + CS_MODE_V8, "ARM V8"),
(CS_ARCH_ARM64, CS_MODE_ARM, "ARM 64"),
(CS_ARCH_MIPS, CS_MODE_MIPS32 + CS_MODE_BIG_ENDIAN, "MIPS 32 BIG"),
(CS_ARCH_MIPS, CS_MODE_MIPS64 + CS_MODE_LITTLE_ENDIAN, "MIPS 32 LITTLE"),
(CS_ARCH_MIPS, CS_MODE_MIPS32R6 + CS_MODE_MICRO + CS_MODE_BIG_ENDIAN, "MIPS 32R6 MICRO BIG"),
(CS_ARCH_MIPS, CS_MODE_MIPS32R6 + CS_MODE_BIG_ENDIAN, "MIPS 32R6 BIG"),
(CS_ARCH_PPC, CS_MODE_BIG_ENDIAN, "PPC BIG ENDIAN"),
(CS_ARCH_SPARC, CS_MODE_BIG_ENDIAN, "SPARC BIG"),
(CS_ARCH_SPARC, CS_MODE_BIG_ENDIAN + CS_MODE_V9, "SPARC BIG V9"),
(CS_ARCH_SYSZ, 0, "SYSX"),
(CS_ARCH_XCORE, 0, "XCORE"),
)
for CODE in code_base:
for (arch, mode, platform) in all_tests:
md = Cs(arch, mode)
k = 0
error = 0
while k < len(CODE):
#As per x86 only need to look at first 15 bytes
gen = md.disasm(CODE[k:k+16], k)
try:
i = gen.next()
except StopIteration:
#print "BAD"
error +=1
k+=1
continue
#print "0x%x:\t%s\t%s\t" %(i.address, i.mnemonic, i.op_str),
m = 0
while m < len(i.bytes):
#print format(i.bytes[m], 'x').zfill(2),
m+=1
#print k
k += len(i.bytes)
#print "Platform: " + platform
#print "Size of Input File: "+str(len(CODE))
#print "Errors Decoding: "+str(error)
errors_for_type[platform] = str(error)
min = errors_for_type.itervalues().next()
for key in errors_for_type:
if errors_for_type[key] < min:
min = errors_for_type[key]
print "CLOSEST MATCH: "+ min
for key in errors_for_type:
if errors_for_type[key] == min:
print "Possible Match is: "+ key
| dafd782305988d4a1d31bf5737c61fb8a6e0212f | [
"Python"
]
| 1 | Python | RyanVrecenar/DiverseDissassembly | 7be5be8b8ed02b5b3d5b7559e75a3e9b6cb6e064 | 60907b011b5e290cdec83212a0bd95655c0cffab |
refs/heads/main | <file_sep>CREATE DATABASE blogpost;
USE blogpost;
CREATE TABLE blogs (title VARCHAR(200), body VARCHAR(400), created_at DATE);
<file_sep>import './BlogPost.css';
import { Link } from 'react-router-dom';
function BlogPost(props) {
return (
<div className='blogPostContainer'>
<div className='blogPostTitle'>
<h1>{props.title}</h1>
</div>
<div className='blogPostBody'>
<div className='blogPostBodyText'>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec nisi orci, accumsan ut blandit nec, fermentum non nulla. Proin dapibus mattis urna a efficitur. Aenean in venenatis leo, ut congue nibh. Ut sit amet ullamcorper nulla, sagittis accumsan ante. Donec mattis magna a nisl accumsan iaculis. Vivamus congue pellentesque fermentum. Aliquam justo tortor, aliquam a ultrices non, ornare lacinia urna. Proin vulputate varius enim, eu scelerisque ipsum. Praesent laoreet non mi sed pretium. Cras dictum sed ex ut venenatis. Curabitur eu felis nibh. Ut id aliquet dui. Nullam tellus erat, rhoncus id tellus et, vestibulum blandit ante. Ut dignissim a odio in venenatis. Vestibulum porta finibus maximus. Phasellus ultricies turpis sed nunc varius, iaculis suscipit elit sagittis.
Nulla facilisi. Aliquam tincidunt purus vitae vestibulum mollis. Pellentesque ornare laoreet felis, ac semper eros auctor vitae. Phasellus commodo ornare tincidunt. Aenean ultrices dolor lorem, eu scelerisque ex lobortis ac. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Phasellus eget ultrices risus, vel egestas elit. Pellentesque vestibulum sem eget turpis pretium scelerisque.
Praesent at sapien sapien. Nunc et est mauris. Ut eget augue nisi. Aenean quis eleifend tellus. In non vehicula eros, ut efficitur est. Praesent a elit sed ante elementum mattis id sit amet orci. Pellentesque sed tempus massa, nec tempus nulla. Morbi feugiat, arcu nec porttitor aliquet, risus justo sodales augue, nec rutrum neque odio scelerisque leo. Etiam lobortis pulvinar diam, vitae egestas quam tempus sit amet. Mauris lacus tellus, cursus vel sem vel, tincidunt tristique quam. Donec euismod pharetra scelerisque.
Cras a sollicitudin diam, consectetur malesuada est. Vivamus consectetur odio nunc, sed dictum lorem imperdiet non. Donec pellentesque, lacus dictum aliquet molestie, lectus ligula lacinia augue, quis porta justo quam eu justo. Aenean aliquam eget tortor non ultrices. Donec sed dui vitae velit blandit mollis. Nam ornare magna non mi ornare lobortis. Nulla lorem orci, lobortis a faucibus quis, laoreet eu purus. Nunc varius libero a sapien vulputate, et blandit sem faucibus. Integer porta pharetra convallis. Aliquam aliquet ipsum orci, nec convallis neque pharetra et. Curabitur dignissim, velit nec scelerisque suscipit, lectus quam viverra ipsum, et congue orci sem eu orci. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Suspendisse viverra turpis consectetur massa ultrices, ac sagittis urna cursus.
Aenean luctus augue id semper posuere. Quisque accumsan convallis nulla, nec posuere ligula malesuada ac. Fusce lobortis cursus ligula sed rhoncus.
</p>
</div>
</div>
<div className='buttonContainer'>
<Link to={`/post?id=${props.id}`}>Go To Post</Link>
</div>
</div>
)
}
export default BlogPost
// { props.body }<file_sep>import express from 'express';
import path from 'path';
import bodyParser from 'body-parser';
const blogRoutes = require('./src/controllers/BlogPostController');
const app = express();
const PORT = process.env.PORT | 35565;
app.use(express.static(path.join(__dirname,"../blog-app/build")));
app.use(bodyParser.json());
app.use('/blogpost', blogRoutes);
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, '../blog-app/build/index.html'));
});
app.listen(PORT, () => {
console.log(`listening on ${PORT}..`);
});<file_sep>import React from 'react';
import BlogPost from './BlogPost'
import './BlogPosts.css';
import * as axios from 'axios';
class BlogPosts extends React.Component {
constructor(props) {
super(props);
this.state = {
blogPosts: []
}
}
async componentDidMount() {
const apiData = await axios.get('http://localhost:35565/blogpost');
this.setState({ blogPosts: apiData.data });
}
goToPostOnClick(event) {
const postId = event.target.id;
}
render() {
const blogPosts = this.state.blogPosts.map(blog => {
return <BlogPost key={blog.id} id={blog.id} title={blog.title} body={blog.body}/>
});
return (
<div className='blogsContainer'>
{blogPosts}
</div>
)
}
}
export default BlogPosts<file_sep>always run a server terminal and npm start terminal in react folder<file_sep>const mysql = require('mysql');
export class BlogPostService {
constructor() {
this.connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '<PASSWORD>',
database: 'blogpost'
});
this.connection.connect((err) => {
if (err) {
throw err;
}
console.log('Connected to mysql')
})
}
async create(blogPost) {
this.validate(blogPost);
const data = await (() => {
return new Promise((resolve, reject) => {
this.connection.query('INSERT INTO blogs (title, body, created_at) VALUES (?, ?, NOW())', [blogPost.title, blogPost.body], (err, rows) => {
if (err) {
return reject(err);
}
resolve(rows);
});
});
})();
return new Promise((resolve, reject) => {
this.connection.query('SELECT * FROM blogs WHERE id = ?', [data.insertId], (err, rows) => {
if (err) {
return reject(err);
}
resolve(rows);
});
});
}
read(blogId) {
if (blogId) {
return new Promise((resolve, reject) => {
this.connection.query('SELECT * FROM blogs WHERE id = ?', [blogId], (err, rows) => {
if (err) {
return reject(err);
}
resolve(rows);
});
});
} else {
return new Promise((resolve, reject) => {
this.connection.query('SELECT * FROM blogs', (err, rows) => {
if (err) {
return reject(err);
}
resolve(rows);
});
});
}
}
async update(blogPost) {
if (typeof blogPost.id === 'number' && this.validate(blogPost) && await this.read(blogPost.id).length !== 0) {
await (() => {
return new Promise((resolve, reject) => {
this.connection.query('UPDATE blogs SET body = ?, modified_at = NOW() WHERE id = ?', [blogPost.body, blogPost.id], (err, rows) => {
if (err) {
return reject(err);
}
resolve(rows);
});
});
})();
return new Promise((resolve, reject) => {
this.connection.query('SELECT * FROM blogs WHERE id = ?', [blogPost.id], (err, rows) => {
if (err) {
return reject(err);
}
resolve(rows);
});
})
};
throw new Error('Id must be supplied on update');
}
delete(blogId) {
if (blogId) {
return new Promise((resolve, reject) => {
this.connection.query('UPDATE blogs SET deleted_at = NOW() WHERE id = ?', [blogId], (err, rows) => {
if (err) {
return reject(err);
}
resolve(rows);
});
})
};
};
validate(blogPost) {
const { title, body } = blogPost;
const errors = [];
if (title === null || title === undefined || title === '') {
errors.push({
field: 'title',
type: 'Validation Error',
message: 'title is null'
});
}
if (body === null || body === undefined || body === '') {
errors.push({
field: 'body',
type: 'Validation Error',
message: 'body is null'
});
}
if (title.length > 200) {
errors.push({
field: 'title',
type: 'Validation Error',
message: 'title is over 200 characters'
})
}
if (body.length > 400) {
errors.push({
field: 'body',
type: 'Validation Error',
message: 'body is over 400 characters'
});
}
if (errors.length !== 0) {
throw new Error(errors);
} else {
return true;
}
}
} | 5bf89fb2b9038b359ec90a242176b1dc8d58c0d2 | [
"JavaScript",
"SQL",
"Text"
]
| 6 | SQL | zachbarber/BlogApp | 1c66e7b5b48778ed884467149f5a86a526c3bf55 | a4e4a6c9c76204b5aec1d76b72f41c6e2bac0c3f |
refs/heads/main | <repo_name>K0STYAa/PracKernelJOS<file_sep>/oscourse-6/kern/pmap.c
/* See COPYRIGHT for copyright information. */
#include <inc/x86.h>
#include <inc/mmu.h>
#include <inc/error.h>
#include <inc/string.h>
#include <inc/assert.h>
#include <kern/pmap.h>
#include <kern/kclock.h>
#include <kern/env.h>
#include <inc/uefi.h>
#ifdef SANITIZE_SHADOW_BASE
// asan unpoison routine used for whitelisting regions.
void platform_asan_unpoison(void *addr, uint32_t size);
// not sanitized memset allows us to access "invalid" areas for extra poisoning.
void *__nosan_memset(void *, int, size_t);
#endif
extern uint64_t pml4phys;
// These variables are set by i386_detect_memory()
size_t npages; // Amount of physical memory (in pages)
static size_t npages_basemem; // Amount of base memory (in pages)
// These variables are set in mem_init()
pde_t *kern_pml4e; // Kernel's initial page directory
physaddr_t kern_cr3; // Physical address of boot time page directory
struct PageInfo *pages; // Physical page state array
static struct PageInfo *page_free_list = NULL; // Free list of physical pages
static struct PageInfo *page_free_list_top = NULL;
//Pointers to start and end of UEFI memory map
EFI_MEMORY_DESCRIPTOR *mmap_base = NULL;
EFI_MEMORY_DESCRIPTOR *mmap_end = NULL;
size_t mem_map_size = 0;
// --------------------------------------------------------------
// Detect machine's physical memory setup.
// --------------------------------------------------------------
//Count all available to the system pages (checks for avaiability
//should be done in page_init).
static void
load_params_read(LOADER_PARAMS *desc, size_t *npages_basemem, size_t *npages_extmem) {
EFI_MEMORY_DESCRIPTOR *mmap_curr;
size_t num_pages = 0;
mem_map_size = desc->MemoryMapDescriptorSize;
mmap_base = (EFI_MEMORY_DESCRIPTOR *)(uintptr_t)desc->MemoryMap;
mmap_end = (EFI_MEMORY_DESCRIPTOR *)((uintptr_t)desc->MemoryMap + desc->MemoryMapSize);
for (mmap_curr = mmap_base; mmap_curr < mmap_end; mmap_curr = (EFI_MEMORY_DESCRIPTOR *)((uintptr_t)mmap_curr + mem_map_size)) {
num_pages += mmap_curr->NumberOfPages;
}
*npages_basemem = num_pages > (IOPHYSMEM / PGSIZE) ? IOPHYSMEM / PGSIZE : num_pages;
*npages_extmem = num_pages - *npages_basemem;
}
static void
i386_detect_memory(void) {
size_t npages_extmem;
size_t pextmem;
if (uefi_lp && uefi_lp->MemoryMap) {
load_params_read(uefi_lp, &npages_basemem, &npages_extmem);
} else {
// Use CMOS calls to measure available base & extended memory.
// (CMOS calls return results in kilobytes.)
npages_basemem = (mc146818_read16(NVRAM_BASELO) * 1024) / PGSIZE;
npages_extmem = (mc146818_read16(NVRAM_EXTLO) * 1024) / PGSIZE;
pextmem = ((size_t)mc146818_read16(NVRAM_PEXTLO) * 1024 * 64);
if (pextmem)
npages_extmem = ((16 * 1024 * 1024) + pextmem - (1 * 1024 * 1024)) / PGSIZE;
}
// Calculate the number of physical pages available in both base
// and extended memory.
if (npages_extmem)
npages = (EXTPHYSMEM / PGSIZE) + npages_extmem;
else
npages = npages_basemem;
cprintf("Physical memory: %luM available, base = %luK, extended = %luK\n",
(unsigned long)(npages * PGSIZE / 1024 / 1024),
(unsigned long)(npages_basemem * PGSIZE / 1024),
(unsigned long)(npages_extmem * PGSIZE / 1024));
}
//
//Check if page is allocatable according to saved UEFI MemMap.
//
bool
is_page_allocatable(size_t pgnum) {
EFI_MEMORY_DESCRIPTOR *mmap_curr;
size_t pg_start, pg_end;
if (!mmap_base || !mmap_end)
return true; //Assume page is allocabale if no loading parameters were passed.
for (mmap_curr = mmap_base; mmap_curr < mmap_end; mmap_curr = (EFI_MEMORY_DESCRIPTOR *)((uintptr_t)mmap_curr + mem_map_size)) {
pg_start = ((uintptr_t)mmap_curr->PhysicalStart >> EFI_PAGE_SHIFT);
pg_end = pg_start + mmap_curr->NumberOfPages;
if (pgnum >= pg_start && pgnum < pg_end) {
switch (mmap_curr->Type) {
case EFI_LOADER_CODE:
case EFI_LOADER_DATA:
case EFI_BOOT_SERVICES_CODE:
case EFI_BOOT_SERVICES_DATA:
case EFI_CONVENTIONAL_MEMORY:
if (mmap_curr->Attribute & EFI_MEMORY_WB)
return true;
else
return false;
break;
default:
return false;
break;
}
}
}
//Assume page is allocatable if it's not found in MemMap.
return true;
}
// Fix loading params and memory map address to virtual ones.
static void
fix_lp_addresses(void) {
mmap_base = (EFI_MEMORY_DESCRIPTOR *)(uintptr_t)uefi_lp->MemoryMapVirt;
mmap_end = (EFI_MEMORY_DESCRIPTOR *)((uintptr_t)uefi_lp->MemoryMapVirt + uefi_lp->MemoryMapSize);
uefi_lp = (LOADER_PARAMS *)uefi_lp->SelfVirtual;
}
// --------------------------------------------------------------
// Set up memory mappings above UTOP.
// --------------------------------------------------------------
static void boot_map_region(pde_t *pgdir, uintptr_t va, size_t size, physaddr_t pa, int perm);
static void check_page_free_list(bool only_low_memory);
static void check_page_alloc(void);
static void check_kern_pml4e(void);
static physaddr_t check_va2pa(pde_t *pgdir, uintptr_t va);
static void check_page(void);
static void check_page_installed_pml4(void);
// This simple physical memory allocator is used only while JOS is setting
// up its virtual memory system. page_alloc() is the real allocator.
//
// If n>0, allocates enough pages of contiguous physical memory to hold 'n'
// bytes. Doesn't initialize the memory. Returns a kernel virtual address.
//
// If n==0, returns the address of the next free page without allocating
// anything.
//
// If we're out of memory, boot_alloc should panic.
// This function may ONLY be used during initialization,
// before the page_free_list list has been set up.
static void *
boot_alloc(uint32_t n) {
static char *nextfree; // virtual address of next byte of free memory
char *result;
// Initialize nextfree if this is the first time.
// 'end' is a magic symbol automatically generated by the linker,
// which points to the end of the kernel's bss segment:
// the first virtual address that the linker did *not* assign
// to any kernel code or global variables.
if (!nextfree) {
extern char end[];
nextfree = ROUNDUP((char *)end, PGSIZE);
}
// Allocate a chunk large enough to hold 'n' bytes, then update
// nextfree. Make sure nextfree is kept aligned
// to a multiple of PGSIZE.
//
// LAB 6: Your code here.
if (!n) {
return nextfree;
}
result = nextfree;
nextfree += ROUNDUP(n, PGSIZE);
if (PADDR(nextfree) > PGSIZE * npages) {
panic("Out of memory on boot, what? how?!");
}
// This is for sanitizers
#ifdef SANITIZE_SHADOW_BASE
// Unpoison the result since it is now allocated.
platform_asan_unpoison(result, n);
#endif
return result;
}
// Set up a two-level page table:
// kern_pml4e is its linear (virtual) address of the root
//
// This function only sets up the kernel part of the address space
// (ie. addresses >= UTOP). The user part of the address space
// will be setup later.
//
// From UTOP to ULIM, the user is allowed to read but not write.
// Above ULIM the user cannot read or write.
void
mem_init(void) {
pml4e_t *pml4e;
// Find out how much memory the machine has (npages & npages_basemem).
i386_detect_memory();
// Remove this line when you're ready to test this function.
// panic("mem_init: This function is not finished\n");
//////////////////////////////////////////////////////////////////////
// create initial page directory.
pml4e = boot_alloc(PGSIZE);
memset(pml4e, 0, PGSIZE);
kern_pml4e = pml4e;
kern_cr3 = PADDR(pml4e);
//////////////////////////////////////////////////////////////////////
// Recursively insert PD in itself as a page table, to form
// a virtual page table at virtual address UVPT.
// (For now, you don't have understand the greater purpose of the
// following line.)
// Permissions: kernel R, user R
kern_pml4e[PML4(UVPT)] = kern_cr3 | PTE_P | PTE_U;
//////////////////////////////////////////////////////////////////////
// Allocate an array of npages 'struct PageInfo's and store it in 'pages'.
// The kernel uses this array to keep track of physical pages: for
// each physical page, there is a corresponding struct PageInfo in this
// array. 'npages' is the number of physical pages in memory. Use memset
// to initialize all fields of each struct PageInfo to 0.
// LAB 6: Your code here.
pages = (struct PageInfo *)boot_alloc(sizeof(*pages) * npages);
memset(pages, 0, sizeof(*pages) * npages);
//////////////////////////////////////////////////////////////////////
// Now that we've allocated the initial kernel data structures, we set
// up the list of free physical pages. Once we've done so, all further
// memory management will go through the page_* functions. In
// particular, we can now map memory using boot_map_region
// or page_insert
page_init();
check_page_free_list(1);
check_page_alloc();
}
#ifdef SANITIZE_SHADOW_BASE
void
kasan_mem_init(void) {
// Unpoison memory in which kernel was loaded
platform_asan_unpoison((void *)KERNBASE, (uint32_t)(boot_alloc(0) - KERNBASE));
// Go through all pages and unpoison pages which have at least one ref.
for (int pgidx = 0; pgidx < npages; pgidx++) {
if (pages[pgidx].pp_ref > 0) {
platform_asan_unpoison(page2kva(&pages[pgidx]), PGSIZE);
}
}
// Additinally map all UEFI runtime services corresponding shadow memory.
EFI_MEMORY_DESCRIPTOR *mmap_curr;
struct PageInfo *pg;
uintptr_t virt_addr, virt_end;
for (mmap_curr = mmap_base; mmap_curr < mmap_end; mmap_curr = (EFI_MEMORY_DESCRIPTOR *)((uintptr_t)mmap_curr + mem_map_size)) {
virt_addr = ROUNDDOWN((uintptr_t)((mmap_curr->VirtualStart >> 3) +
SANITIZE_SHADOW_OFF),
PGSIZE);
virt_end = ROUNDUP((uintptr_t)(virt_addr + (mmap_curr->NumberOfPages * PGSIZE >> 3)), PGSIZE);
if (mmap_curr->Attribute & EFI_MEMORY_RUNTIME) {
for (; virt_addr < virt_end; virt_addr += PGSIZE) {
pg = page_alloc(ALLOC_ZERO);
if (!pg)
panic("region_alloc: page alloc failed!\n");
if (page_insert(kern_pml4e, pg, (void *)virt_addr,
PTE_P | PTE_W) < 0)
panic("Cannot allocate any memory for page directory allocation");
}
}
}
}
#endif
// --------------------------------------------------------------
// Tracking of physical pages.
// The 'pages' array has one 'struct PageInfo' entry per physical page.
// Pages are reference counted, and free pages are kept on a linked list.
// --------------------------------------------------------------
//
// Initialize page structure and memory free list.
// After this is done, NEVER use boot_alloc again. ONLY use the page
// allocator functions below to allocate and deallocate physical
// memory via the page_free_list.
//
void
page_init(void) {
// The example code here marks all physical pages as free.
// However this is not truly the case. What memory is free?
// 1) Mark physical page 0 as in use.
// This way we preserve the real-mode IDT and BIOS structures
// in case we ever need them. (Currently we don't, but...)
// 2) The rest of base memory, [PGSIZE, npages_basemem * PGSIZE)
// is free.
// 3) Then comes the IO hole [IOPHYSMEM, EXTPHYSMEM), which must
// never be allocated.
// 4) Then extended memory [EXTPHYSMEM, ...).
// Some of it is in use, some is free. Where is the kernel
// in physical memory? Which pages are already in use for
// page tables and other data structures?
//
// Change the code to reflect this.
// NB: DO NOT actually touch the physical memory corresponding to
// free pages!
size_t i;
uintptr_t first_free_page;
struct PageInfo *last = NULL;
//Mark physical page 0 as in use.
pages[0].pp_ref = 1;
pages[0].pp_link = NULL;
// 2) The rest of base memory, [PGSIZE, npages_basemem * PGSIZE)
// is free.
pages[1].pp_ref = 0;
page_free_list = &pages[1];
last = &pages[1];
for (i = 1; i < npages_basemem; i++) {
if (is_page_allocatable(i)) {
pages[i].pp_ref = 0;
last->pp_link = &pages[i];
last = &pages[i];
} else {
pages[i].pp_ref = 1;
pages[i].pp_link = NULL;
}
}
// 3) Then comes the IO hole [IOPHYSMEM, EXTPHYSMEM), which must
// never be allocated.
first_free_page = PADDR(boot_alloc(0)) / PGSIZE;
for (i = npages_basemem; i < first_free_page; i++) {
pages[i].pp_ref = 1;
pages[i].pp_link = NULL;
}
// Some of it is in use, some is free. Where is the kernel
// in physical memory? Which pages are already in use for
// page tables and other data structures?
for (i = first_free_page; i < npages; i++) {
if (is_page_allocatable(i)) {
pages[i].pp_ref = 0;
last->pp_link = &pages[i];
last = &pages[i];
} else {
pages[i].pp_ref = 1;
pages[i].pp_link = NULL;
}
}
}
//
// Allocates a physical page. If (alloc_flags & ALLOC_ZERO), fills the entire
// returned physical page with '\0' bytes. Does NOT increment the reference
// count of the page - the caller must do these if necessary (either explicitly
// or via page_insert).
//
// Be sure to set the pp_link field of the allocated page to NULL so
// page_free can check for double-free bugs.
//
// Returns NULL if out of free memory.
//
// Hint: use page2kva and memset
struct PageInfo *
page_alloc(int alloc_flags) {
// ne memory check
if (!page_free_list) {
return NULL;
}
struct PageInfo *return_page = page_free_list;
page_free_list = page_free_list->pp_link;
return_page->pp_link = NULL;
if (!page_free_list) {
page_free_list_top = NULL;
}
#ifdef SANITIZE_SHADOW_BASE
if ((uintptr_t)page2kva(return_page) >= SANITIZE_SHADOW_BASE) {
cprintf("page_alloc: returning shadow memory page! Increase base address?\n");
return NULL;
}
// Unpoison allocated memory before accessing it!
platform_asan_unpoison(page2kva(return_page), PGSIZE);
#endif
if (alloc_flags & ALLOC_ZERO) {
memset(page2kva(return_page), 0, PGSIZE);
}
return return_page;
}
int
page_is_allocated(const struct PageInfo *pp) {
return !pp->pp_link && pp != page_free_list_top;
}
//
// Return a page to the free list.
// (This function should only be called when pp->pp_ref reaches 0.)
//
void
page_free(struct PageInfo *pp) {
// LAB 6: Fill this function in
// Hint: You may want to panic if pp->pp_ref is nonzero or
// pp->pp_link is not NULL.
if (pp->pp_ref) {
panic("page_free: Page is still referenced!\n");
}
if (pp->pp_link) {
panic("page_free: Page is already freed!\n");
}
if (pp->pp_ref != 0 || pp->pp_link != NULL)
panic("page_free: Page cannot be freed!\n");
pp->pp_link = page_free_list;
page_free_list = pp;
if (!page_free_list_top) {
page_free_list_top = pp;
}
}
//
// Decrement the reference count on a page,
// freeing it if there are no more refs.
//
void
page_decref(struct PageInfo *pp) {
if (--pp->pp_ref == 0)
page_free(pp);
}
// Given 'pgdir', a pointer to a page directory, pgdir_walk returns
// a pointer to the page table entry (PTE) for linear address 'va'.
// This requires walking the two-level page table structure.
//
// The relevant page table page might not exist yet.
// If this is true, and create == false, then pgdir_walk returns NULL.
// Otherwise, pgdir_walk allocates a new page table page with page_alloc.
// - If the allocation fails, pgdir_walk returns NULL.
// - Otherwise, the new page's reference count is incremented,
// the page is cleared,
// and pgdir_walk returns a pointer into the new page table page.
//
// Hint 1: you can turn a Page * into the physical address of the
// page it refers to with page2pa() from kern/pmap.h.
//
// Hint 2: the x86 MMU checks permission bits in both the page directory
// and the page table, so it's safe to leave permissions in the page
// directory more permissive than strictly necessary.
//
// Hint 3: look at inc/mmu.h for useful macros that mainipulate page
// table and page directory entries.
//
pte_t *
pml4e_walk(pml4e_t *pml4e, const void *va, int create) {
// LAB 7: Fill this function in
return NULL;
}
pte_t *
pdpe_walk(pdpe_t *pdpe, const void *va, int create) {
// LAB 7: Fill this function in
return NULL;
}
pte_t *
pgdir_walk(pde_t *pgdir, const void *va, int create) {
// LAB 7: Fill this function in
return NULL;
}
//
// Map [va, va+size) of virtual address space to physical [pa, pa+size)
// in the page table rooted at pgdir. Size is a multiple of PGSIZE, and
// va and pa are both page-aligned.
// Use permission bits perm|PTE_P for the entries.
//
// This function is only intended to set up the ``static'' mappings
// above UTOP. As such, it should *not* change the pp_ref field on the
// mapped pages.
//
// Hint: the TA solution uses pgdir_walk
static void
boot_map_region(pml4e_t *pml4e, uintptr_t va, size_t size, physaddr_t pa, int perm) {
// static void
// boot_map_region(pde_t *pgdir, uintptr_t va, size_t size, physaddr_t pa, int perm){
// LAB 7: Fill this function in
}
//
// Map the physical page 'pp' at virtual address 'va'.
// The permissions (the low 12 bits) of the page table entry
// should be set to 'perm|PTE_P'.
//
// Requirements
// - If there is already a page mapped at 'va', it should be page_remove()d.
// - If necessary, on demand, a page table should be allocated and inserted
// into 'pgdir'.
// - pp->pp_ref should be incremented if the insertion succeeds.
// - The TLB must be invalidated if a page was formerly present at 'va'.
//
// Corner-case hint: Make sure to consider what happens when the same
// pp is re-inserted at the same virtual address in the same pgdir.
// However, try not to distinguish this case in your code, as this
// frequently leads to subtle bugs; there's an elegant way to handle
// everything in one code path.
//
// RETURNS:
// 0 on success
// -E_NO_MEM, if page table couldn't be allocated
//
// Hint: The TA solution is implemented using pgdir_walk, page_remove,
// and page2pa.
//
int
page_insert(pml4e_t *pml4e, struct PageInfo *pp, void *va, int perm) {
// LAB 7: Fill this function in
return 0;
}
//
// Return the page mapped at virtual address 'va'.
// If pte_store is not zero, then we store in it the address
// of the pte for this page. This is used by page_remove and
// can be used to verify page permissions for syscall arguments,
// but should not be used by most callers.
//
// Return NULL if there is no page mapped at va.
//
// Hint: the TA solution uses pgdir_walk and pa2page.
//
struct PageInfo *
page_lookup(pml4e_t *pml4e, void *va, pte_t **pte_store) {
// LAB 7: Fill this function in
return NULL;
}
//
// Unmaps the physical page at virtual address 'va'.
// If there is no physical page at that address, silently does nothing.
//
// Details:
// - The ref count on the physical page should decrement.
// - The physical page should be freed if the refcount reaches 0.
// - The pg table entry corresponding to 'va' should be set to 0.
// (if such a PTE exists)
// - The TLB must be invalidated if you remove an entry from
// the page table.
//
// Hint: The TA solution is implemented using page_lookup,
// tlb_invalidate, and page_decref.
//
void
page_remove(pml4e_t *pml4e, void *va) {
// LAB 7: Fill this function in
}
//
// Invalidate a TLB entry, but only if the page tables being
// edited are the ones currently in use by the processor.
//
void
tlb_invalidate(pml4e_t *pml4e, void *va) {
// Flush the entry only if we're modifying the current address space.
// For now, there is only one address space, so always invalidate.
invlpg(va);
}
//
// Reserve size bytes in the MMIO region and map [pa,pa+size) at this
// location. Return the base of the reserved region. size does *not*
// have to be multiple of PGSIZE.
//
void *
mmio_map_region(physaddr_t pa, size_t size) {
// Where to start the next region. Initially, this is the
// beginning of the MMIO region. Because this is static, its
// value will be preserved between calls to mmio_map_region
// (just like nextfree in boot_alloc).
static uintptr_t base = MMIOBASE;
// Reserve size bytes of virtual memory starting at base and
// map physical pages [pa,pa+size) to virtual addresses
// [base,base+size). Since this is device memory and not
// regular DRAM, you'll have to tell the CPU that it isn't
// safe to cache access to this memory. Luckily, the page
// tables provide bits for this purpose; simply create the
// mapping with PTE_PCD|PTE_PWT (cache-disable and
// write-through) in addition to PTE_W. (If you're interested
// in more details on this, see section 10.5 of IA32 volume
// 3A.)
//
// Be sure to round size up to a multiple of PGSIZE and to
// handle if this reservation would overflow MMIOLIM (it's
// okay to simply panic if this happens).
//
// Hint: The staff solution uses boot_map_region.
//
// LAB 6: Your code here:
(void)base;
return NULL;
}
// --------------------------------------------------------------
// Checking functions.
// --------------------------------------------------------------
//
// Check that the pages on the page_free_list are reasonable.
//
static void
check_page_free_list(bool only_low_memory) {
struct PageInfo *pp;
unsigned pdx_limit = only_low_memory ? 1 : NPDENTRIES;
int nfree_basemem = 0, nfree_extmem = 0;
char *first_free_page;
if (!page_free_list)
panic("'page_free_list' is a null pointer!");
if (only_low_memory) {
// Move pages with lower addresses first in the free
// list, since entry_pgdir does not map all pages.
struct PageInfo *pp1, *pp2;
struct PageInfo **tp[2] = {&pp1, &pp2};
for (pp = page_free_list; pp; pp = pp->pp_link) {
int pagetype = VPN(page2pa(pp)) >= pdx_limit;
*tp[pagetype] = pp;
tp[pagetype] = &pp->pp_link;
}
*tp[1] = 0;
*tp[0] = pp2;
page_free_list = pp1;
}
// if there's a page that shouldn't be on the free list,
// try to make sure it eventually causes trouble.
/*for (pp = page_free_list; pp; pp = pp->pp_link) {
if (VPN(page2pa(pp)) < pdx_limit) {
#ifdef SANITIZE_SHADOW_BASE
// This is technically invalid memory, access it via unsanitized routine.
__nosan_memset(page2kva(pp), 0x97, 128);
#else
memset(page2kva(pp), 0x97, 128);
#endif
}
}*/
first_free_page = (char *)boot_alloc(0);
for (pp = page_free_list; pp; pp = pp->pp_link) {
// check that we didn't corrupt the free list itself
assert(pp >= pages);
assert(pp < pages + npages);
assert(((char *)pp - (char *)pages) % sizeof(*pp) == 0);
// check a few pages that shouldn't be on the free list
assert(page2pa(pp) != 0);
assert(page2pa(pp) != IOPHYSMEM);
assert(page2pa(pp) != EXTPHYSMEM - PGSIZE);
assert(page2pa(pp) != EXTPHYSMEM);
assert(page2pa(pp) < EXTPHYSMEM || (char *)page2kva(pp) >= first_free_page);
if (page2pa(pp) < EXTPHYSMEM)
++nfree_basemem;
else
++nfree_extmem;
}
//assert(nfree_basemem > 0);
assert(nfree_extmem > 0);
}
//
// Check the physical page allocator (page_alloc(), page_free(),
// and page_init()).
//
static void
check_page_alloc(void) {
struct PageInfo *pp, *pp0, *pp1, *pp2;
int nfree;
struct PageInfo *fl;
char *c;
int i;
if (!pages)
panic("'pages' is a null pointer!");
// check number of free pages
for (pp = page_free_list, nfree = 0; pp; pp = pp->pp_link)
++nfree;
// should be able to allocate three pages
pp0 = pp1 = pp2 = 0;
assert((pp0 = page_alloc(0)));
assert((pp1 = page_alloc(0)));
assert((pp2 = page_alloc(0)));
assert(pp0);
assert(pp1 && pp1 != pp0);
assert(pp2 && pp2 != pp1 && pp2 != pp0);
assert(page2pa(pp0) < npages * PGSIZE);
assert(page2pa(pp1) < npages * PGSIZE);
assert(page2pa(pp2) < npages * PGSIZE);
// temporarily steal the rest of the free pages
fl = page_free_list;
page_free_list = 0;
// should be no free memory
assert(!page_alloc(0));
// free and re-allocate?
page_free(pp0);
page_free(pp1);
page_free(pp2);
pp0 = pp1 = pp2 = 0;
assert((pp0 = page_alloc(0)));
assert((pp1 = page_alloc(0)));
assert((pp2 = page_alloc(0)));
assert(pp0);
assert(pp1 && pp1 != pp0);
assert(pp2 && pp2 != pp1 && pp2 != pp0);
assert(!page_alloc(0));
// test flags
memset(page2kva(pp0), 1, PGSIZE);
page_free(pp0);
assert((pp = page_alloc(ALLOC_ZERO)));
assert(pp && pp0 == pp);
c = page2kva(pp);
for (i = 0; i < PGSIZE; i++)
assert(c[i] == 0);
// give free list back
page_free_list = fl;
// free the pages we took
page_free(pp0);
page_free(pp1);
page_free(pp2);
// number of free pages should be the same
for (pp = page_free_list; pp; pp = pp->pp_link)
--nfree;
assert(nfree == 0);
cprintf("check_page_alloc() succeeded!\n");
}
<file_sep>/oscourse-12/kern/kclock.c
/* See COPYRIGHT for copyright information. */
#include <inc/x86.h>
#include <inc/time.h>
#include <kern/kclock.h>
#include <kern/timer.h>
#include <kern/trap.h>
#include <kern/picirq.h>
static void
rtc_timer_init(void) {
// DELETED in LAB 5
// pic_init();
// DELETED in LAB 5 end
pic_init();
rtc_init();
}
static void
rtc_timer_pic_interrupt(void) {
irq_setmask_8259A(irq_mask_8259A & ~(1 << IRQ_CLOCK));
}
static void
rtc_timer_pic_handle(void) {
rtc_check_status();
pic_send_eoi(IRQ_CLOCK);
}
struct Timer timer_rtc = {
.timer_name = "rtc",
.timer_init = rtc_timer_init,
.enable_interrupts = rtc_timer_pic_interrupt,
.handle_interrupts = rtc_timer_pic_handle,
};
static int
get_time(void) {
struct tm time;
uint8_t s, m, h, d, M, y, Y, state;
s = mc146818_read(RTC_SEC);
m = mc146818_read(RTC_MIN);
h = mc146818_read(RTC_HOUR);
d = mc146818_read(RTC_DAY);
M = mc146818_read(RTC_MON);
y = mc146818_read(RTC_YEAR);
Y = mc146818_read(RTC_YEAR_HIGH);
state = mc146818_read(RTC_BREG);
if (state & RTC_12H) {
/* Fixup 12 hour mode */
h = (h & 0x7F) + 12 * !!(h & 0x80);
}
if (!(state & RTC_BINARY)) {
/* Fixup binary mode */
s = BCD2BIN(s);
m = BCD2BIN(m);
h = BCD2BIN(h);
d = BCD2BIN(d);
M = BCD2BIN(M);
y = BCD2BIN(y);
Y = BCD2BIN(Y);
}
time.tm_sec = s;
time.tm_min = m;
time.tm_hour = h;
time.tm_mday = d;
time.tm_mon = M - 1;
time.tm_year = y + Y * 100 - 1900;
return timestamp(&time);
}
int
gettime(void) {
nmi_disable();
// LAB 12: your code here
int t;
while (mc146818_read(RTC_AREG) & RTC_UPDATE_IN_PROGRESS) {} // wait while bit 7 in register A will be 0
if ((t = get_time()) != get_time()) {
t = get_time();
}
nmi_enable();
return t;
}
void
rtc_init(void) {
// запрет прерываний
nmi_disable();
// LAB 4 code
uint8_t reg_a = 0, reg_b = 0;
// меняем делитель частоты регистра часов А,
// чтобы прерывания приходили раз в полсекунды
outb(IO_RTC_CMND, RTC_AREG);
reg_a = inb(IO_RTC_DATA);
reg_a = reg_a | 0x0F; // биты 0-3 = 1 => 500 мс (2 Гц)
outb(IO_RTC_DATA, reg_a);
// устанавливаем бит RTC_PIE в регистре часов В
outb(IO_RTC_CMND, RTC_BREG);
reg_b = inb(IO_RTC_DATA);
reg_b = reg_b | RTC_PIE;
outb(IO_RTC_DATA, reg_b);
// разрешить прерывания
nmi_enable();
// LAB 4 code end
}
uint8_t
rtc_check_status(void) {
uint8_t status = 0;
// LAB 4 code
outb(IO_RTC_CMND, RTC_CREG);
status = inb(IO_RTC_DATA);
// LAB 4 code end
return status;
}
unsigned
mc146818_read(unsigned reg) {
outb(IO_RTC_CMND, reg);
return inb(IO_RTC_DATA);
}
void
mc146818_write(unsigned reg, unsigned datum) {
outb(IO_RTC_CMND, reg);
outb(IO_RTC_DATA, datum);
}
unsigned
mc146818_read16(unsigned reg) {
return mc146818_read(reg) | (mc146818_read(reg + 1) << 8);
}<file_sep>/oscourse-12/inc/mmu.h
#ifndef JOS_INC_MMU_H
#define JOS_INC_MMU_H
/*
* This file contains definitions for the x86 memory management unit (MMU),
* including paging- and segmentation-related data structures and constants,
* the %cr0, %cr4, and %rflags registers, and traps.
*/
/*
*
* Part 1. Paging data structures and constants.
*
*/
// A linear address 'la' has a three-part structure as follows:
//
// +-------9--------+-------9--------+--------9-------+--------9-------+----------12---------+
// |Page Map Level 4|Page Directory | Page Directory | Page Table | Offset within Page |
// | Index | Pointer Index | Index | Index | |
// +----------------+----------------+----------------+--------------------------------------+
// \----PML4(la)----/\--- PDPE(la)---/\--- PDX(la) --/ \--- PTX(la) --/ \---- PGOFF(la) ----/
// \------------------------------ VPN(la) -------------------------/
//
// The PML4, PDPE, PDX, PTX, PGOFF, and VPN macros decompose linear addresses as shown.
// To construct a linear address la from PML4(la), PDPE(la), PDX(la), PTX(la), and PGOFF(la),
// use PGADDR(PML4(la), PDPE(la), PDX(la), PTX(la), PGOFF(la)).
// page number field of address
#define PPN(pa) (((uintptr_t)(pa)) >> PTXSHIFT)
#define VPN(la) PPN(la) // used to index into vpt[]
#define PGNUM(la) PPN(la) // used to index into vpt[]
// page directory index
#define PDX(la) ((((uintptr_t)(la)) >> PDXSHIFT) & 0x1FF)
#define VPD(la) (((uintptr_t)(la)) >> PDXSHIFT) // used to index into vpd[]
#define VPDPE(la) (((uintptr_t)(la)) >> PDPESHIFT)
#define VPML4E(la) (((uintptr_t)(la)) >> PML4SHIFT)
#define PML4(la) ((((uintptr_t)(la)) >> PML4SHIFT) & 0x1FF)
// page table index
#define PTX(la) ((((uintptr_t)(la)) >> PTXSHIFT) & 0x1FF)
#define PDPE(la) ((((uintptr_t)(la)) >> PDPESHIFT) & 0x1FF)
// offset in page
#define PGOFF(la) (((uintptr_t)(la)) & 0xFFF)
// construct linear address from indexes and offset
#define PGADDR(m, p, d, t, o) ((void*)((m) << PML4SHIFT | (p) << PDPESHIFT | (d) << PDXSHIFT | (t) << PTXSHIFT | (o)))
// Page directory and page table constants.
#define NPDENTRIES 512 // page directory entries per page directory
#define NPTENTRIES 512 // page table entries per page table
#define NPMLENTRIES 4 // 1TB limit should have just two PML entries
#define NPDPENTRIES 512
#define PGSIZE 4096 // bytes mapped by a page
#define PGSHIFT 12 // log2(PGSIZE)
#define PTSIZE (PGSIZE * NPTENTRIES) // bytes mapped by a page directory entry
#define PTSHIFT 21 // log2(PTSIZE)
#define PTXSHIFT 12 // offset of PTX in a linear address
#define PDXSHIFT 21 // offset of PDX in a linear address
#define PDPESHIFT 30
#define PML4SHIFT 39
// Page table/directory entry flags.
#define PTE_P 0x001 // Present
#define PTE_W 0x002 // Writeable
#define PTE_U 0x004 // User
#define PTE_PWT 0x008 // Write-Through
#define PTE_PCD 0x010 // Cache-Disable
#define PTE_A 0x020 // Accessed
#define PTE_D 0x040 // Dirty
#define PTE_PS 0x080 // Page Size
#define PTE_G 0x100 // Global
#define PTE_MBZ 0x180 // Bits must be zero
// The PTE_AVAIL bits aren't used by the kernel or interpreted by the
// hardware, so user processes are allowed to set them arbitrarily.
#define PTE_AVAIL 0xE00 // Available for software use
// Flags in PTE_SYSCALL may be used in system calls. (Others may not.)
#define PTE_SYSCALL (PTE_AVAIL | PTE_P | PTE_W | PTE_U)
// Address in page table or page directory entry
#define PTE_ADDR(pte) ((physaddr_t)(pte) & ~0xFFF)
// Control Register flags
#define CR0_PE 0x00000001 // Protection Enable
#define CR0_MP 0x00000002 // Monitor coProcessor
#define CR0_EM 0x00000004 // Emulation
#define CR0_TS 0x00000008 // Task Switched
#define CR0_ET 0x00000010 // Extension Type
#define CR0_NE 0x00000020 // Numeric Errror
#define CR0_WP 0x00010000 // Write Protect
#define CR0_AM 0x00040000 // Alignment Mask
#define CR0_NW 0x20000000 // Not Writethrough
#define CR0_CD 0x40000000 // Cache Disable
#define CR0_PG 0x80000000 // Paging
#define CR4_PCE 0x00000100 // Performance counter enable
#define CR4_MCE 0x00000040 // Machine Check Enable
#define CR4_PSE 0x00000010 // Page Size Extensions
#define CR4_DE 0x00000008 // Debugging Extensions
#define CR4_TSD 0x00000004 // Time Stamp Disable
#define CR4_PVI 0x00000002 // Protected-Mode Virtual Interrupts
#define CR4_VME 0x00000001 // V86 Mode Extensions
//x86_64 related changes
#define CR4_PAE 0x00000020
#define EFER_MSR 0xC0000080
#define EFER_LME 8
// Eflags register
#define FL_CF 0x00000001 // Carry Flag
#define FL_PF 0x00000004 // Parity Flag
#define FL_AF 0x00000010 // Auxiliary carry Flag
#define FL_ZF 0x00000040 // Zero Flag
#define FL_SF 0x00000080 // Sign Flag
#define FL_TF 0x00000100 // Trap Flag
#define FL_IF 0x00000200 // Interrupt Flag
#define FL_DF 0x00000400 // Direction Flag
#define FL_OF 0x00000800 // Overflow Flag
#define FL_IOPL_MASK 0x00003000 // I/O Privilege Level bitmask
#define FL_IOPL_0 0x00000000 // IOPL == 0
#define FL_IOPL_1 0x00001000 // IOPL == 1
#define FL_IOPL_2 0x00002000 // IOPL == 2
#define FL_IOPL_3 0x00003000 // IOPL == 3
#define FL_NT 0x00004000 // Nested Task
#define FL_RF 0x00010000 // Resume Flag
#define FL_VM 0x00020000 // Virtual 8086 mode
#define FL_AC 0x00040000 // Alignment Check
#define FL_VIF 0x00080000 // Virtual Interrupt Flag
#define FL_VIP 0x00100000 // Virtual Interrupt Pending
#define FL_ID 0x00200000 // ID flag
// Page fault error codes
#define FEC_PR 0x1 // Page fault caused by protection violation
#define FEC_WR 0x2 // Page fault caused by a write
#define FEC_U 0x4 // Page fault occured while in user mode
/*
*
* Part 2. Segmentation data structures and constants.
*
*/
#ifdef __ASSEMBLER__
/*
* Macros to build GDT entries in assembly.
*/
#define SEG_NULL \
.word 0, 0; \
.byte 0, 0, 0, 0
#define SEG(type, base, lim) \
.word(((lim) >> 12) & 0xffff), ((base)&0xffff); \
.byte(((base) >> 16) & 0xff), (0x90 | (type)), \
(0xC0 | (((lim) >> 28) & 0xf)), (((base) >> 24) & 0xff)
#define SEG64(type, base, lim) \
.word(((lim) >> 12) & 0xffff), ((base)&0xffff); \
.byte(((base) >> 16) & 0xff), (0x90 | (type)), \
(0xA0 | (((lim) >> 28) & 0xF)), (((base) >> 24) & 0xff)
#define SEG64USER(type, base, lim) \
.word(((lim) >> 12) & 0xffff), ((base)&0xffff); \
.byte(((base) >> 16) & 0xff), (0xf0 | (type)), \
(0xA0 | (((lim) >> 28) & 0xF)), (((base) >> 24) & 0xff)
#else // not __ASSEMBLER__
#include <inc/types.h>
// Segment Descriptors
struct Segdesc {
unsigned sd_lim_15_0 : 16; // Low bits of segment limit
unsigned sd_base_15_0 : 16; // Low bits of segment base address
unsigned sd_base_23_16 : 8; // Middle bits of segment base address
unsigned sd_type : 4; // Segment type (see STS_ constants)
unsigned sd_s : 1; // 0 = system, 1 = application
unsigned sd_dpl : 2; // Descriptor Privilege Level
unsigned sd_p : 1; // Present
unsigned sd_lim_19_16 : 4; // High bits of segment limit
unsigned sd_avl : 1; // Unused (available for software use)
unsigned sd_l : 1; // Long mode
unsigned sd_db : 1; // 0 = 16-bit segment, 1 = 32-bit segment
// Has to be set to 0 in longmode.
unsigned sd_g : 1; // Granularity: limit scaled by 4K when set
unsigned sd_base_31_24 : 8; // High bits of segment base address
};
struct SystemSegdesc64 {
unsigned sd_lim_15_0 : 16;
unsigned sd_base_15_0 : 16;
unsigned sd_base_23_16 : 8;
unsigned sd_type : 4;
unsigned sd_s : 1; // 0 = system, 1 = application
unsigned sd_dpl : 2; // Descriptor Privilege Level
unsigned sd_p : 1; // Present
unsigned sd_lim_19_16 : 4; // High bits of segment limit
unsigned sd_avl : 1; // Unused (available for software use)
unsigned sd_rsv1 : 2; // Reserved
unsigned sd_g : 1; // Granularity: limit scaled by 4K when set
unsigned sd_base_31_24 : 8; // High bits of segment base address
uint32_t sd_base_63_32;
unsigned sd_res1 : 8;
unsigned sd_clear : 8;
unsigned sd_res2 : 16;
};
#define SETTSS(desc, type, base, lim, dpl) \
{ \
(desc)->sd_lim_15_0 = (uint64_t)(lim)&0xffff; \
(desc)->sd_base_15_0 = (uint64_t)(base)&0xffff; \
(desc)->sd_base_23_16 = ((uint64_t)(base) >> 16) & 0xff; \
(desc)->sd_type = type; \
(desc)->sd_s = 0; \
(desc)->sd_dpl = 0; \
(desc)->sd_p = 1; \
(desc)->sd_lim_19_16 = ((uint64_t)(lim) >> 16) & 0xf; \
(desc)->sd_avl = 0; \
(desc)->sd_rsv1 = 0; \
(desc)->sd_g = 0; \
(desc)->sd_base_31_24 = ((uint64_t)(base) >> 24) & 0xff; \
(desc)->sd_base_63_32 = ((uint64_t)(base) >> 32) & 0xffffffff; \
(desc)->sd_res1 = 0; \
(desc)->sd_clear = 0; \
(desc)->sd_res2 = 0; \
}
// Null segment
#define SEG_NULL \
(struct Segdesc) { \
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 \
}
// Segment that is loadable but faults when used
#define SEG_FAULT \
(struct Segdesc) { \
0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0 \
}
// Normal segment
#define SEG(type, base, lim, dpl) \
(struct Segdesc) { \
((lim) >> 12) & 0xffff, (base)&0xffff, ((base) >> 16) & 0xff, \
type, 1, dpl, 1, (unsigned)(lim) >> 28, 0, 0, 1, 1, \
(unsigned)(base) >> 24 \
}
#define SEG16(type, base, lim, dpl) \
(struct Segdesc) { \
(lim) & 0xffff, (base)&0xffff, ((base) >> 16) & 0xff, \
type, 1, dpl, 1, (unsigned)(lim) >> 16, 0, 0, 1, 0, \
(unsigned)(base) >> 24 \
}
#define SEG64(type, base, lim, dpl) \
(struct Segdesc) { \
((lim) >> 12) & 0xffff, (base)&0xffff, ((base) >> 16) & 0xff, \
type, 1, dpl, 1, (unsigned)(lim) >> 28, 0, 1, 0, 1, \
(unsigned)(base) >> 24 \
}
#endif /* !__ASSEMBLER__ */
// Application segment type bits
#define STA_X 0x8 // Executable segment
#define STA_E 0x4 // Expand down (non-executable segments)
#define STA_C 0x4 // Conforming code segment (executable only)
#define STA_W 0x2 // Writeable (non-executable segments)
#define STA_R 0x2 // Readable (executable segments)
#define STA_A 0x1 // Accessed
// System segment type bits
#define STS_T16A 0x1 // Available 16-bit TSS
#define STS_LDT 0x2 // Local Descriptor Table
#define STS_T16B 0x3 // Busy 16-bit TSS
#define STS_CG16 0x4 // 16-bit Call Gate
#define STS_TG 0x5 // Task Gate / Coum Transmitions
#define STS_IG16 0x6 // 16-bit Interrupt Gate
#define STS_TG16 0x7 // 16-bit Trap Gate
#define STS_T64A 0x9 // Available 64-bit TSS
#define STS_T64B 0xB // Busy 64-bit TSS
#define STS_CG64 0xC // 64-bit Call Gate
#define STS_IG64 0xE // 64-bit Interrupt Gate
#define STS_TG64 0xF // 64-bit Trap Gate
/*
*
* Part 3. Traps.
*
*/
#ifndef __ASSEMBLER__
// Task state segment format (as described by the Pentium architecture book)
struct Taskstate {
uint32_t ts_res1; // -- reserved in long mode
uintptr_t ts_esp0; // Stack pointers and segment selectors
uintptr_t ts_esp1;
uintptr_t ts_esp2;
uint64_t ts_res2; // reserved in long mode
uint64_t ts_ist1;
uint64_t ts_ist2;
uint64_t ts_ist3;
uint64_t ts_ist4;
uint64_t ts_ist5;
uint64_t ts_ist6;
uint64_t ts_ist7;
uint64_t ts_res3;
uint16_t ts_res4;
uint16_t ts_iomb; // I/O map base address
} __attribute__((packed));
// Gate descriptors for interrupts and traps
struct Gatedesc {
unsigned gd_off_15_0 : 16; // low 16 bits of offset in segment
unsigned gd_ss : 16; // segment selector
unsigned gd_ist : 3; // # args, 0 for interrupt/trap gates
unsigned gd_rsv1 : 5; // reserved(should be zero I guess)
unsigned gd_type : 4; // type(STS_{TG,IG32,TG32})
unsigned gd_s : 1; // must be 0 (system)
unsigned gd_dpl : 2; // descriptor(meaning new) privilege level
unsigned gd_p : 1; // Present
unsigned gd_off_31_16 : 16; // high bits of offset in segment
uint32_t gd_off_32_63;
uint32_t gd_rsv2;
};
// Set up a normal interrupt/trap gate descriptor.
// - istrap: 1 for a trap (= exception) gate, 0 for an interrupt gate.
// see section 9.6.1.3 of the i386 reference: "The difference between
// an interrupt gate and a trap gate is in the effect on IF (the
// interrupt-enable flag). An interrupt that vectors through an
// interrupt gate resets IF, thereby preventing other interrupts from
// interfering with the current interrupt handler. A subsequent IRET
// instruction restores IF to the value in the EFLAGS image on the
// stack. An interrupt through a trap gate does not change IF."
// - sel: Code segment selector for interrupt/trap handler
// - off: Offset in code segment for interrupt/trap handler
// - dpl: Descriptor Privilege Level -
// the privilege level required for software to invoke
// this interrupt/trap gate explicitly using an int instruction.
#define SETGATE(gate, istrap, sel, off, dpl) \
{ \
(gate).gd_off_15_0 = (uint64_t)(off)&0xffff; \
(gate).gd_ss = (sel); \
(gate).gd_ist = 0; \
(gate).gd_rsv1 = 0; \
(gate).gd_type = (istrap) ? STS_TG64 : STS_IG64; \
(gate).gd_s = 0; \
(gate).gd_dpl = (dpl); \
(gate).gd_p = 1; \
(gate).gd_off_31_16 = ((uint64_t)(off) >> 16) & 0xffff; \
(gate).gd_off_32_63 = ((uint64_t)(off) >> 32) & 0xffffffff; \
(gate).gd_rsv2 = 0; \
}
// Set up a call gate descriptor.
#define SETCALLGATE(gate, ss, off, dpl) \
{ \
(gate).gd_off_15_0 = (uint32_t)(off)&0xffff; \
(gate).gd_ss = (ss); \
(gate).gd_ist = 0; \
(gate).gd_rsv1 = 0; \
(gate).gd_type = STS_CG64; \
(gate).gd_s = 0; \
(gate).gd_dpl = (dpl); \
(gate).gd_p = 1; \
(gate).gd_off_31_16 = ((uint32_t)(off) >> 16) & 0xffff; \
(gate).gd_off_32_63 = ((uint64_t)(off) >> 32) & 0xffffffff; \
(gate).gd_rsv2 = 0; \
}
// Pseudo-descriptors used for LGDT, LLDT and LIDT instructions.
struct Pseudodesc {
uint16_t pd_lim; // Limit
uint64_t pd_base; // Base address
} __attribute__((packed));
#endif /* !__ASSEMBLER__ */
#endif /* !JOS_INC_MMU_H */
<file_sep>/oscourse-7/lib/random_data.c
unsigned char _dev_urandom[] = {
0xa1, 0x97, 0xdf, 0x11, 0x8d, 0x1e, 0xa5, 0x04, 0x25, 0xc1, 0x11, 0x5a,
0x65, 0xe6, 0xe4, 0x37, 0xf6, 0xd6, 0x75, 0x38, 0x9a, 0xcd, 0x72, 0x14,
0x60, 0xd3, 0xf7, 0x9f, 0x7c, 0x4a, 0x06, 0x9f, 0xd8, 0x05, 0x45, 0xfd,
0x68, 0x72, 0x7f, 0x4e, 0x3f, 0xaf, 0x11, 0x7d, 0x15, 0xc7, 0xb4, 0xf2,
0xb7, 0x0f, 0xbf, 0x31, 0xf9, 0xc0, 0x7d, 0x28, 0x98, 0xd3, 0x32, 0x7c,
0xf6, 0x46, 0x26, 0xd8, 0xe9, 0xcf, 0x14, 0xc0, 0xc8, 0xe4, 0x52, 0xf5,
0x06, 0xef, 0x51, 0x79, 0xdd, 0x57, 0xb1, 0x04, 0x1f, 0x0f, 0x47, 0xcf,
0x2a, 0x9a, 0xfa, 0x6f, 0x88, 0x55, 0x96, 0x54, 0xf0, 0x7f, 0x5f, 0xff,
0x4b, 0x3c, 0xb5, 0xef};
unsigned int _dev_urandom_len = 100;
<file_sep>/oscourse-10/conf/lab.mk
LAB=10
CONFIG_KSPACE=n
LABDEFS=-Ddebug=0
<file_sep>/oscourse-9/conf/lab.mk
LAB=9
CONFIG_KSPACE=n
LABDEFS=-Ddebug=0
<file_sep>/oscourse-6/conf/conf/lab.mk
LAB=6
CONFIG_KSPACE=n
LABDEFS=-Ddebug=0
<file_sep>/oscourse-8/kern/kclock.c
/* See COPYRIGHT for copyright information. */
#include <inc/x86.h>
#include <kern/kclock.h>
#include <kern/timer.h>
#include <kern/trap.h>
#include <kern/picirq.h>
static void
rtc_timer_init(void) {
// DELETED in LAB 5
// pic_init();
// DELETED in LAB 5 end
rtc_init();
}
static void
rtc_timer_pic_interrupt(void) {
irq_setmask_8259A(irq_mask_8259A & ~(1 << IRQ_CLOCK));
}
static void
rtc_timer_pic_handle(void) {
rtc_check_status();
pic_send_eoi(IRQ_CLOCK);
}
struct Timer timer_rtc = {
.timer_name = "rtc",
.timer_init = rtc_timer_init,
.enable_interrupts = rtc_timer_pic_interrupt,
.handle_interrupts = rtc_timer_pic_handle,
};
void
rtc_init(void) {
// запрет прерываний
nmi_disable();
// LAB 4 code
uint8_t reg_a = 0, reg_b = 0;
// меняем делитель частоты регистра часов А,
// чтобы прерывания приходили раз в полсекунды
outb(IO_RTC_CMND, RTC_AREG);
reg_a = inb(IO_RTC_DATA);
reg_a = reg_a | 0x0F; // биты 0-3 = 1 => 500 мс (2 Гц)
outb(IO_RTC_DATA, reg_a);
// устанавливаем бит RTC_PIE в регистре часов В
outb(IO_RTC_CMND, RTC_BREG);
reg_b = inb(IO_RTC_DATA);
reg_b = reg_b | RTC_PIE;
outb(IO_RTC_DATA, reg_b);
// разрешить прерывания
nmi_enable();
// LAB 4 code end
}
uint8_t
rtc_check_status(void) {
uint8_t status = 0;
// LAB 4 code
outb(IO_RTC_CMND, RTC_CREG);
status = inb(IO_RTC_DATA);
// LAB 4 code end
return status;
}
unsigned
mc146818_read(unsigned reg) {
outb(IO_RTC_CMND, reg);
return inb(IO_RTC_DATA);
}
void
mc146818_write(unsigned reg, unsigned datum) {
outb(IO_RTC_CMND, reg);
outb(IO_RTC_DATA, datum);
}
unsigned
mc146818_read16(unsigned reg) {
return mc146818_read(reg) | (mc146818_read(reg + 1) << 8);
}<file_sep>/oscourse-8/conf/lab.mk
LAB=8
CONFIG_KSPACE=n
LABDEFS=-Ddebug=1
<file_sep>/oscourse-5/lib/random_data.c
unsigned char _dev_urandom[] = {
0xb1, 0xe6, 0x67, 0xbe, 0xe1, 0x4f, 0x48, 0xe6, 0x2a, 0xe5, 0x40, 0xb3,
0x41, 0xae, 0x21, 0x55, 0xc2, 0xdd, 0x3a, 0xad, 0x1c, 0x3a, 0xbd, 0x41,
0x65, 0xea, 0xf4, 0xb6, 0x21, 0x14, 0x2f, 0x55, 0x44, 0x60, 0xd8, 0xa9,
0xd0, 0xb9, 0xa1, 0x4b, 0x91, 0x18, 0x60, 0x69, 0x71, 0xe6, 0x73, 0x48,
0x53, 0x56, 0xdf, 0x07, 0xfa, 0xc1, 0xb5, 0x14, 0x37, 0x5e, 0x53, 0x0a,
0x0f, 0x61, 0x37, 0x79, 0x33, 0x7d, 0xdb, 0x3f, 0x92, 0x96, 0xa9, 0xcd,
0x13, 0xc6, 0x3d, 0x4d, 0x11, 0x97, 0xc6, 0xdb, 0x14, 0xe7, 0xcc, 0x20,
0xc6, 0xaa, 0x82, 0x5f, 0x44, 0x03, 0x68, 0xf1, 0x06, 0x5e, 0xf3, 0x06,
0xf7, 0x9c, 0xda, 0x40
};
unsigned int _dev_urandom_len = 100;
<file_sep>/oscourse-8/lib/syscall.c
// System call stubs.
#include <inc/syscall.h>
#include <inc/lib.h>
static inline int64_t
syscall(int64_t num, int64_t check, int64_t a1, int64_t a2, int64_t a3, int64_t a4, int64_t a5) {
int64_t ret;
// Generic system call: pass system call number in AX,
// up to five parameters in DX, CX, BX, DI, SI.
// Interrupt kernel with T_SYSCALL.
//
// The "volatile" tells the assembler not to optimize
// this instruction away just because we don't use the
// return value.
//
// The last clause tells the assembler that this can
// potentially change the condition codes and arbitrary
// memory locations.
asm volatile("int %1\n"
: "=a"(ret)
: "i"(T_SYSCALL),
"a"(num),
"d"(a1),
"c"(a2),
"b"(a3),
"D"(a4),
"S"(a5)
: "cc", "memory");
if (check && ret > 0)
panic("syscall %ld returned %ld (> 0)", (long)num, (long)ret);
return ret;
}
void
sys_cputs(const char *s, size_t len) {
syscall(SYS_cputs, 0, (uint64_t)s, len, 0, 0, 0);
}
int
sys_cgetc(void) {
return syscall(SYS_cgetc, 0, 0, 0, 0, 0, 0);
}
int
sys_env_destroy(envid_t envid) {
return syscall(SYS_env_destroy, 1, envid, 0, 0, 0, 0);
}
envid_t
sys_getenvid(void) {
return syscall(SYS_getenvid, 0, 0, 0, 0, 0, 0);
}
<file_sep>/oscourse-7/conf/lab.mk
LAB=7
CONFIG_KSPACE=n
LABDEFS=-Ddebug=0
<file_sep>/oscourse-9/mykern/kclock.c
/* See COPYRIGHT for copyright information. */
#include <inc/x86.h>
#include <kern/kclock.h>
#include <kern/timer.h>
#include <kern/trap.h>
#include <kern/picirq.h>
static void
rtc_timer_init(void) {
pic_init();
rtc_init();
}
static void
rtc_timer_pic_interrupt(void) {
irq_setmask_8259A(irq_mask_8259A & ~(1 << IRQ_CLOCK));
}
static void
rtc_timer_pic_handle(void) {
rtc_check_status();
pic_send_eoi(IRQ_CLOCK);
}
struct Timer timer_rtc = {
.timer_name = "rtc",
.timer_init = rtc_timer_init,
.enable_interrupts = rtc_timer_pic_interrupt,
.handle_interrupts = rtc_timer_pic_handle,
};
void
rtc_init(void) {
nmi_disable();
// LAB 4: Your code here
outb(IO_RTC_CMND, RTC_AREG); // переключаемся на A
uint8_t value = inb(IO_RTC_DATA); // читаем
outb(IO_RTC_CMND, RTC_AREG);
outb(IO_RTC_DATA, SET_NEW_RATE(value, RTC_500MS_RATE)); // 500ms частота
outb(IO_RTC_CMND, RTC_BREG); // переключаемся на B
value = inb(IO_RTC_DATA); // читаем значение
outb(IO_RTC_CMND, RTC_BREG); // переключаемся на B
outb(IO_RTC_DATA, value | RTC_PIE); // установливаем PIE bit
}
uint8_t
rtc_check_status(void) {
uint8_t status = 0;
// LAB 4: Your code here
outb(IO_RTC_CMND, RTC_CREG); // переключаемся на C
status = inb(IO_RTC_DATA); // читаем значение
return status;
}
unsigned
mc146818_read(unsigned reg) {
outb(IO_RTC_CMND, reg);
return inb(IO_RTC_DATA);
}
void
mc146818_write(unsigned reg, unsigned datum) {
outb(IO_RTC_CMND, reg);
outb(IO_RTC_DATA, datum);
}
unsigned
mc146818_read16(unsigned reg) {
return mc146818_read(reg) | (mc146818_read(reg + 1) << 8);
}<file_sep>/oscourse-9/mykern/monitor.c
// Simple command-line kernel monitor useful for
// controlling the kernel and exploring the system interactively.
#include <inc/stdio.h>
#include <inc/string.h>
#include <inc/memlayout.h>
#include <inc/assert.h>
#include <inc/env.h>
#include <inc/x86.h>
#include <kern/console.h>
#include <kern/monitor.h>
#include <kern/kdebug.h>
#include <kern/tsc.h>
#include <kern/timer.h>
#include <kern/env.h>
#include <kern/pmap.h>
#include <kern/trap.h>
#define CMDBUF_SIZE 80 // enough for one VGA text line
struct Command {
const char *name;
const char *desc;
// return -1 to force monitor to exit
int (*func)(int argc, char **argv, struct Trapframe *tf);
};
// LAB 5: Your code here.
// Implement timer_start (mon_start), timer_stop (mon_stop), timer_freq (mon_frequency) commands.
// LAB 6: Your code here.
// Implement memory (mon_memory) command.
static struct Command commands[] = {
{"help", "Display this list of commands", mon_help},
{"hello", "Display greeting message", mon_hello},
{"kerninfo", "Display information about the kernel", mon_kerninfo},
{"backtrace", "Print stack backtrace", mon_backtrace},
{"name", "Print developer name", mon_name},
{"timer_start", "Start timer", mon_start},
{"timer_stop", "Stop timer", mon_stop},
{"timer_freq", "Count processor frequency", mon_frequency},
{"pplist", "Display physical pages states", mon_pplist}};
#define NCOMMANDS (sizeof(commands) / sizeof(commands[0]))
/***** Implementations of basic kernel monitor commands *****/
int
mon_help(int argc, char **argv, struct Trapframe *tf) {
int i;
for (i = 0; i < NCOMMANDS; i++)
cprintf("%s - %s\n", commands[i].name, commands[i].desc);
return 0;
}
int
mon_hello(int argc, char **argv, struct Trapframe *tf) {
cprintf("Hello!\n");
return 0;
}
int
mon_name(int argc, char **argv, struct Trapframe *tf) {
if (argc > 1) {
if (strcmp(argv[1], "-f") == 0) {
cprintf("Pavel\n");
} else if (strcmp(argv[1], "-l") == 0) {
cprintf("Seleznev\n");
} else {
cprintf("Unknown option %s\n", argv[1]);
}
} else {
cprintf("<NAME>.\n");
}
return 0;
}
int
mon_kerninfo(int argc, char **argv, struct Trapframe *tf) {
extern char _head64[], entry[], etext[], edata[], end[];
cprintf("Special kernel symbols:\n");
cprintf(" _head64 %08lx (phys)\n",
(unsigned long)_head64);
cprintf(" entry %08lx (virt) %08lx (phys)\n",
(unsigned long)entry, (unsigned long)entry - KERNBASE);
cprintf(" etext %08lx (virt) %08lx (phys)\n",
(unsigned long)etext, (unsigned long)etext - KERNBASE);
cprintf(" edata %08lx (virt) %08lx (phys)\n",
(unsigned long)edata, (unsigned long)edata - KERNBASE);
cprintf(" end %08lx (virt) %08lx (phys)\n",
(unsigned long)end, (unsigned long)end - KERNBASE);
cprintf("Kernel executable memory footprint: %luKB\n",
(unsigned long)ROUNDUP(end - entry, 1024) / 1024);
return 0;
}
int
mon_backtrace(int argc, char **argv, struct Trapframe *tf) {
// LAB 2: Your code here.
cprintf("Stack backtrace:\n");
uintptr_t cr3 = rcr3();
uint64_t *rbp = (uint64_t *)(tf ? tf->tf_regs.reg_rbp : read_rbp());
uint64_t rip;
struct Ripdebuginfo info;
while (rbp) {
pte_t *pte1 = pml4e_walk(KADDR(cr3), rbp, 0);
pte_t *pte2 = pml4e_walk(KADDR(cr3), rbp + 1, 0);
if (!pte1 || !pte2 || !(*pte1 & PTE_P) || !(*pte2 & PTE_P)) {
cprintf("<Unreadable memory>\n");
return 1;
}
rip = rbp[1];
debuginfo_rip(rip, &info);
cprintf(" rbp %016lx rip %016lx\n", (uint64_t)rbp, rip);
cprintf(" %.256s:%d: ", info.rip_file, info.rip_line);
cprintf("%.*s+%lu\n", info.rip_fn_namelen, info.rip_fn_name, rip - info.rip_fn_addr);
rbp = (uint64_t*)rbp[0];
}
return 0;
}
// LAB 5: Your code here.
// Implement timer_start (mon_start), timer_stop (mon_stop), timer_freq (mon_frequency) commands.
int mon_start(int argc, char **argv, struct Trapframe *tf) {
if (argc != 2) {
return 1;
}
timer_start(argv[1]);
return 0;
}
int mon_stop(int argc, char **argv, struct Trapframe *tf) {
timer_stop();
return 0;
}
int mon_frequency(int argc, char **argv, struct Trapframe *tf) {
if (argc != 2) {
return 1;
}
timer_cpu_frequency(argv[1]);
return 0;
}
int mon_pplist(int argc, char **argv, struct Trapframe *tf) {
unsigned char is_prev_allocated = page_is_allocated(&pages[0]) ? 1 : 0;
for (int i = 1; i <= npages; ++i) {
cprintf("%d", i);
if (i < npages && (page_is_allocated(&pages[i]) ? 1 : 0) == is_prev_allocated) {
while(i < npages && (page_is_allocated(&pages[i]) ? 1 : 0) == is_prev_allocated) {
is_prev_allocated = page_is_allocated(&pages[i]) ? 1 : 0;
++i;
}
cprintf("..%d", i);
}
cprintf(is_prev_allocated ? " ALLOCATED\n" : " FREE\n");
is_prev_allocated = (is_prev_allocated + 1) % 2;
}
return 0;
}
/***** Kernel monitor command interpreter *****/
#define WHITESPACE "\t\r\n "
#define MAXARGS 16
static int
runcmd(char *buf, struct Trapframe *tf) {
int argc;
char *argv[MAXARGS];
int i;
// Parse the command buffer into whitespace-separated arguments
argc = 0;
argv[argc] = 0;
while (1) {
// gobble whitespace
while (*buf && strchr(WHITESPACE, *buf))
*buf++ = 0;
if (*buf == 0)
break;
// save and scan past next arg
if (argc == MAXARGS - 1) {
cprintf("Too many arguments (max %d)\n", MAXARGS);
return 0;
}
argv[argc++] = buf;
while (*buf && !strchr(WHITESPACE, *buf))
buf++;
}
argv[argc] = 0;
// Lookup and invoke the command
if (argc == 0)
return 0;
for (i = 0; i < NCOMMANDS; i++) {
if (strcmp(argv[0], commands[i].name) == 0)
return commands[i].func(argc, argv, tf);
}
cprintf("Unknown command '%s'\n", argv[0]);
return 0;
}
void
monitor(struct Trapframe *tf) {
char *buf;
cprintf("Welcome to the JOS kernel monitor!\n");
cprintf("Type 'help' for a list of commands.\n");
if (tf != NULL)
print_trapframe(tf);
while (1) {
buf = readline("K> ");
if (buf != NULL)
if (runcmd(buf, tf) < 0)
break;
}
}
<file_sep>/oscourse-6/lib/random_data.c
unsigned char _dev_urandom[] = {
0x56, 0x8f, 0xfe, 0x5d, 0x87, 0x34, 0xd9, 0xef, 0xee, 0x4a, 0xd1, 0x89,
0x8b, 0x26, 0xbb, 0x62, 0x76, 0xa4, 0x8c, 0x9c, 0x68, 0xba, 0x98, 0x23,
0xa4, 0xcc, 0xb4, 0x42, 0xdb, 0x2b, 0xe9, 0x59, 0xd5, 0x43, 0x78, 0xa1,
0x90, 0xa6, 0x0b, 0xd3, 0x93, 0xcf, 0x74, 0xd6, 0x92, 0x67, 0x25, 0x4f,
0xab, 0xae, 0x12, 0xf4, 0x51, 0xaf, 0x08, 0x95, 0x4b, 0x7d, 0x65, 0xac,
0x0f, 0x50, 0xf8, 0x2e, 0xa7, 0xd9, 0xb0, 0xfe, 0x4d, 0x8c, 0xf9, 0xea,
0x26, 0x92, 0x06, 0x8e, 0x6c, 0x0f, 0x27, 0xb5, 0xec, 0xd4, 0x8e, 0xf6,
0x51, 0xcf, 0x08, 0x9b, 0xc1, 0x18, 0x59, 0x16, 0xa9, 0x59, 0x3b, 0x56,
0x33, 0x3f, 0x2d, 0x3a};
unsigned int _dev_urandom_len = 100;
| 96334248dd8b0fb061d54bb7eaf74d71268ea848 | [
"C",
"Makefile"
]
| 15 | C | K0STYAa/PracKernelJOS | cde67f681cdab44d48d9b0909e3b2000aaf07aa8 | b30b2a21fa16e96edff9990214ffcb5b14415db0 |
refs/heads/master | <file_sep>package com.wangli.accountlogin;
import java.text.SimpleDateFormat;
import java.util.Locale;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;
import com.wangli.accountlogin.utils.Constants;
import com.weibo.sdk.android.Oauth2AccessToken;
import com.weibo.sdk.android.Weibo;
import com.weibo.sdk.android.WeiboAuthListener;
import com.weibo.sdk.android.WeiboDialogError;
import com.weibo.sdk.android.WeiboException;
import com.weibo.sdk.android.sso.SsoHandler;
import com.weibo.sdk.android.util.AccessTokenKeeper;
public class MainActivity extends Activity implements OnClickListener {
private final String Tag = "MainActivity";
private TextView tvStatus;
private Button btQQ;
private Button btSinaWeibo;
private Button btTencentWeibo;
/** 腾讯API接口类 */
private Tencent tencent;
/** 微博API接口类,提供登陆等功能 */
private Weibo mWeibo;
/** (新浪)封装了 "access_token","expires_in","refresh_token",并提供了他们的管理功能 */
private Oauth2AccessToken mAccessToken;
/** (新浪)注意:SsoHandler 仅当sdk支持sso时有效 */
private SsoHandler mSsoHandler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
setListener();
}
private void initView() {
tvStatus = (TextView) findViewById(R.id.tv_status);
btQQ = (Button) findViewById(R.id.bt_qq);
btSinaWeibo = (Button) findViewById(R.id.bt_sinaweibo);
btTencentWeibo = (Button) findViewById(R.id.bt_tencentweibo);
}
private void setListener() {
btQQ.setOnClickListener(this);
btSinaWeibo.setOnClickListener(this);
btTencentWeibo.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.bt_qq:
qqLogin();
break;
case R.id.bt_sinaweibo:
sinaWeiboLogin();
break;
case R.id.bt_tencentweibo:
tencentWeiboLogin();
break;
default:
break;
}
}
private void tencentWeiboLogin() {
}
private void sinaWeiboLogin() {
mWeibo = Weibo.getInstance(Constants.SINA_APP_KEY,
Constants.SINA_REDIRECT_URL, Constants.SINA_SCOPE);
SsoHandler ssoHandler = new SsoHandler(this, mWeibo);
// 从 SharedPreferences 中读取上次已保存好 AccessToken 等信息,
// 第一次启动本应用,AccessToken 不可用
mAccessToken = AccessTokenKeeper.readAccessToken(this);
if (mAccessToken.isSessionValid()) {
String date = new java.text.SimpleDateFormat("yyyy/MM/dd hh:mm:ss",
Locale.CHINA).format(new java.util.Date(mAccessToken
.getExpiresTime()));
tvStatus.setText("access_token 仍在有效期内,无需再次登录: \naccess_token:"
+ mAccessToken.getToken() + "\n有效期:" + date);
} else {
tvStatus.setText("使用SSO登录前,请检查手机上是否已经安装新浪微博客户端,"
+ "目前仅3.0.0及以上微博客户端版本支持SSO;如果未安装,将自动转为Oauth2.0进行认证");
ssoHandler.authorize(new WeiboAuthListener() {
@Override
public void onWeiboException(WeiboException arg0) {
}
@Override
public void onError(WeiboDialogError arg0) {
}
@Override
public void onComplete(Bundle values) {
Log.i(Tag, values.toString());
String token = values.getString("access_token");
String expires_in = values.getString("expires_in");
mAccessToken = new Oauth2AccessToken(token, expires_in);
if (mAccessToken.isSessionValid()) {
String date = new SimpleDateFormat(
"yyyy/MM/dd HH:mm:ss", Locale.CHINA)
.format(new java.util.Date(mAccessToken
.getExpiresTime()));
tvStatus.setText("认证成功: \r\n access_token: " + token
+ "\r\n" + "expires_in: " + expires_in
+ "\r\n有效期:" + date);
AccessTokenKeeper.keepAccessToken(MainActivity.this,
mAccessToken);
Toast.makeText(MainActivity.this, "认证成功",
Toast.LENGTH_SHORT).show();
}
}
@Override
public void onCancel() {
}
});
}
}
private void qqLogin() {
tencent = Tencent.createInstance(Constants.QQ_APP_ID, this);
tencent.login(this, "get_simple_userinfo", new IUiListener() {
@Override
public void onError(UiError error) {
tvStatus.setText(error.errorDetail);
}
@Override
public void onComplete(JSONObject response) {
String info = response.toString();
Log.i(Tag, info);
try {
JSONObject object = new JSONObject(info);
String code = (String) object.get("ret");
if (code.trim().equals("0")) {
tvStatus.setText("QQ登录成功");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public void onCancel() {
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// 新浪SSO 授权回调
// 重要:发起 SSO 登陆的Activity必须重写onActivityResult
if (mSsoHandler != null) {
mSsoHandler.authorizeCallBack(requestCode, resultCode, data);
}
}
}
<file_sep>package com.wangli.accountlogin.utils;
public interface Constants {
// QQ
public final static String QQ_APP_ID = "100537521";
// 新浪
public final static String SINA_APP_KEY = "795243942";
public final static String SINA_SCOPE = "users/show";
public final static String SINA_REDIRECT_URL = "http://www.sina.com";
}
| 05284a8b5d694cb550651847643dc0aaeba52e6e | [
"Java"
]
| 2 | Java | wwangliw/AccountLogin | 329904d5f1a56931241f77abb0cf5204f2155a3b | 842c2a64bdc69a774e99ace947548fa43741a3d6 |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using NLog;
using AppFunc = System.Func<System.Collections.Generic.IDictionary<string, object>, System.Threading.Tasks.Task>;
namespace OwinIdentitySimpleInjector.Middleware
{
public class LogginMiddleware
{
private AppFunc _next;
private ILogger _logger;
public void Initialize(AppFunc next, ILogger logger)
{
this._next = next;
_logger = logger;
}
public async Task Invoke(IDictionary<string, object> environment)
{
_logger.Info("Owin instance demo, Begin Request");
await _next.Invoke(environment);
_logger.Info("Owin instance demo, End Request");
}
}
}<file_sep>using Microsoft.Owin;
using Owin;
using NLog;
using OwinIdentitySimpleInjector.Middleware;
[assembly: OwinStartupAttribute(typeof(OwinIdentitySimpleInjector.Startup))]
namespace OwinIdentitySimpleInjector
{
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
var container = IdentityConfig.RegisterInjections(app);
// OWIN logging addition
//Microsoft.Owin.Logging.ILogger logger = app.CreateLogger<Startup>();
//logger.WriteInformation("App is starting up");
ConfigureAuth(app, container);
Logger _logger;
//// example with an inline function
//app.Use(new Func<AppFunc, AppFunc>(next => (async env =>
//{
// _logger.Info("Begin Request");
// await next.Invoke(env);
// _logger.Info("End Request");
//})));
//// example with middleware type
//app.Use(typeof(OwinDemoMiddleware));
//// example with middleware instance
//var logginMiddleware = new LogginMiddleware();
//app.Use(logginMiddleware);
// example with redirect url
app.Use(typeof(RedirectMiddleware));
}
}
}
<file_sep>using OwinIdentitySimpleInjector.BO.Users;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace OwinIdentitySimpleInjector.Core.Users
{
public interface ICustomUserStore<TUser>
where TUser : ApplicationUser
{
}
}
<file_sep>using Microsoft.Owin.Testing;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Owin;
using System.Net.Http;
using System.Threading.Tasks;
namespace OwinIdentitySimpleInjector.Tests
{
[TestClass]
public class OwinTests
{
[TestMethod]
public async Task OwinAppTest()
{
using (var server = TestServer.Create(app =>
{
app.Run(async context =>
{
await context.Response.WriteAsync("Hello world using OWIN TestServer");
});
}))
{
HttpResponseMessage response = await server.CreateRequest("/").AddHeader("header1", "headervalue1").GetAsync();
//Execute necessary tests
Assert.AreEqual("Hello world using OWIN TestServer", await response.Content.ReadAsStringAsync());
}
}
}
}
<file_sep>using OwinIdentitySimpleInjector.Contracts;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace OwinIdentitySimpleInjector.BLL
{
public class UserBLL : IUserBLL
{
}
}
<file_sep>using Microsoft.AspNet.Identity.EntityFramework;
using OwinIdentitySimpleInjector.BO.Users;
using OwinIdentitySimpleInjector.DAL.Contracts;
using System.Data.Entity;
namespace OwinIdentitySimpleInjector.DAL
{
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>, IApplicationDbContext
{
public ApplicationDbContext()
: base("DefaultConnection")
{
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
// Database Authentication table override
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<ApplicationUser>().ToTable("User").Property(p => p.Id).HasColumnName("UserId");
modelBuilder.Entity<IdentityUserRole>().ToTable("UserRole");
modelBuilder.Entity<IdentityUserLogin>().ToTable("UserLogin");
modelBuilder.Entity<IdentityUserClaim>().ToTable("UserClaim").Property(p => p.Id).HasColumnName("UserClaimId");
modelBuilder.Entity<IdentityRole>().ToTable("Role").Property(p => p.Id).HasColumnName("RoleId");
}
}
}
<file_sep>using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin;
using OwinIdentitySimpleInjector.BO.Users;
using OwinIdentitySimpleInjector.Core.Users;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace OwinIdentitySimpleInjector.Core
{
public interface IApplicationUserManager
{
Task<IdentityResult> CreateAsync(ApplicationUser user);
Task<IdentityResult> ConfirmEmailAsync(string userId, string token);
Task<ApplicationUser> FindByEmailAsync(string email);
Task<bool> IsEmailConfirmedAsync(string userId);
Task<ApplicationUser> FindByNameAsync(string userName);
Task<IdentityResult> ResetPasswordAsync(string userId, string token, string newPassword);
Task<IList<string>> GetValidTwoFactorProvidersAsync(string userId);
Task<IdentityResult> AddLoginAsync(string userId, UserLoginInfo login);
Task<IdentityResult> CreateAsync(ApplicationUser user, string password);
Task<IdentityResult> AddPasswordAsync(string userId, string password);
Task<IdentityResult> SetPhoneNumberAsync(string userId, string phoneNumber);
Task<IdentityResult> ChangePasswordAsync(string userId, string currentPassword, string newPassword);
Task<IdentityResult> SetTwoFactorEnabledAsync(string userId, bool enabled);
Task<string> GenerateChangePhoneNumberTokenAsync(string userId, string phoneNumber);
Task<ApplicationUser> FindByIdAsync(string userId);
Task<IdentityResult> RemoveLoginAsync(string userId, UserLoginInfo login);
Task<IList<UserLoginInfo>> GetLoginsAsync(string userId);
Task<bool> GetTwoFactorEnabledAsync(string userId);
Task<string> GetPhoneNumberAsync(string userId);
Task<IdentityResult> ChangePhoneNumberAsync(string userId, string phoneNumber, string token);
IIdentityMessageService SmsServiceExtend();
}
}
<file_sep>using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin;
using OwinIdentitySimpleInjector.BO.Users;
using OwinIdentitySimpleInjector.Contracts;
using OwinIdentitySimpleInjector.Core.Users;
using OwinIdentitySimpleInjector.DAL;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace OwinIdentitySimpleInjector.Core.Users
{
// Configure the application user manager used in this application. UserManager is defined in ASP.NET Identity and is used by the application.
public class ApplicationUserManager : UserManager<ApplicationUser>, IApplicationUserManager
{
public ApplicationUserManager(IUserStore<ApplicationUser> store)
: base(store)
{
}
//public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context)
//{
// var manager = new ApplicationUserManager(new CustomUserStore(context.Get<IdentityDbContext>()));
// // Configure validation logic for usernames
// manager.UserValidator = new UserValidator<ApplicationUser>(manager)
// {
// AllowOnlyAlphanumericUserNames = false,
// RequireUniqueEmail = true
// };
// // Configure validation logic for passwords
// manager.PasswordValidator = new PasswordValidator
// {
// RequiredLength = 6,
// RequireNonLetterOrDigit = true,
// RequireDigit = true,
// RequireLowercase = true,
// RequireUppercase = true,
// };
// // Configure user lockout defaults
// manager.UserLockoutEnabledByDefault = true;
// manager.DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(5);
// manager.MaxFailedAccessAttemptsBeforeLockout = 5;
// // Register two factor authentication providers. This application uses Phone and Emails as a step of receiving a code for verifying the user
// // You can write your own provider and plug it in here.
// manager.RegisterTwoFactorProvider("Phone Code", new PhoneNumberTokenProvider<ApplicationUser>
// {
// MessageFormat = "Your security code is {0}"
// });
// manager.RegisterTwoFactorProvider("Email Code", new EmailTokenProvider<ApplicationUser>
// {
// Subject = "Security Code",
// BodyFormat = "Your security code is {0}"
// });
// // manager.EmailService = new EmailService();
// // manager.SmsService = new SmsService();
// var dataProtectionProvider = options.DataProtectionProvider;
// if (dataProtectionProvider != null)
// {
// manager.UserTokenProvider =
// new DataProtectorTokenProvider<ApplicationUser>(dataProtectionProvider.Create("ASP.NET Identity"));
// }
// return manager;
//}
public override Task<IdentityResult> CreateAsync(ApplicationUser user)
{
return base.CreateAsync(user);
}
public override Task<IdentityResult> ConfirmEmailAsync(string userId, string token)
{
return base.ConfirmEmailAsync(userId, token);
}
public override Task<ApplicationUser> FindByEmailAsync(string email)
{
return base.FindByEmailAsync(email);
}
public override Task<bool> IsEmailConfirmedAsync(string userId)
{
return base.IsEmailConfirmedAsync(userId);
}
public override Task<ApplicationUser> FindByNameAsync(string userName)
{
return base.FindByNameAsync(userName);
}
public override Task<IdentityResult> ResetPasswordAsync(string userId, string token, string newPassword)
{
return base.ResetPasswordAsync(userId, token, newPassword);
}
public override Task<IList<string>> GetValidTwoFactorProvidersAsync(string userId)
{
return base.GetValidTwoFactorProvidersAsync(userId);
}
public override Task<IdentityResult> AddLoginAsync(string userId, UserLoginInfo login)
{
return base.AddLoginAsync(userId, login);
}
public override Task<IdentityResult> CreateAsync(ApplicationUser user, string password)
{
return base.CreateAsync(user, password);
}
public override Task<string> GetPhoneNumberAsync(string userId)
{
return base.GetPhoneNumberAsync(userId);
}
public override Task<bool> GetTwoFactorEnabledAsync(string userId)
{
return base.GetTwoFactorEnabledAsync(userId);
}
public override Task<IList<UserLoginInfo>> GetLoginsAsync(string userId)
{
return base.GetLoginsAsync(userId);
}
public override Task<IdentityResult> RemoveLoginAsync(string userId, UserLoginInfo login)
{
return base.RemoveLoginAsync(userId, login);
}
public override Task<ApplicationUser> FindByIdAsync(string userId)
{
return base.FindByIdAsync(userId);
}
public override Task<string> GenerateChangePhoneNumberTokenAsync(string userId, string phoneNumber)
{
return base.GenerateChangePhoneNumberTokenAsync(userId, phoneNumber);
}
public override Task<IdentityResult> SetTwoFactorEnabledAsync(string userId, bool enabled)
{
return base.SetTwoFactorEnabledAsync(userId, enabled);
}
public override Task<IdentityResult> ChangePasswordAsync(string userId, string currentPassword, string newPassword)
{
return base.ChangePasswordAsync(userId, currentPassword, newPassword);
}
public override Task<IdentityResult> SetPhoneNumberAsync(string userId, string phoneNumber)
{
return base.SetPhoneNumberAsync(userId, phoneNumber);
}
public override Task<bool> CheckPasswordAsync(ApplicationUser user, string password)
{
return base.CheckPasswordAsync(user, password);
}
public override Task<IdentityResult> AddPasswordAsync(string userId, string password)
{
return base.AddPasswordAsync(userId, password);
}
public Task<IList<UserLoginInfo>> GetLoginsA(string userId)
{
return base.GetLoginsAsync(userId);
}
public override Task<IdentityResult> ChangePhoneNumberAsync(string userId, string phoneNumber, string token)
{
return base.ChangePhoneNumberAsync(userId, phoneNumber, token);
}
public IIdentityMessageService SmsServiceExtend()
{
return base.SmsService;
}
}
}
<file_sep>using NSubstitute;
using System.Collections.Generic;
using System.Security.Principal;
using System.Web;
namespace OwinIdentitySimpleInjector.Tests
{
public class HttpContextTest
{
protected static HttpRequestBase HttpRequestBase;
protected static HttpResponseBase HttpResponseBase;
protected static HttpSessionStateBase HttpSessionStateBase;
protected static HttpServerUtilityBase HttpServerUtilityBase;
public static HttpContextBase GetMockedHttpContext(IPrincipal userContext = null)
{
var context = Substitute.For<HttpContextBase>();
HttpRequestBase = Substitute.For<HttpRequestBase>();
HttpResponseBase = Substitute.For<HttpResponseBase>();
HttpSessionStateBase = Substitute.For<HttpSessionStateBase>();
HttpServerUtilityBase = Substitute.For<HttpServerUtilityBase>();
HttpCachePolicy = Substitute.For<HttpCachePolicyBase>();
context.Request.Returns(HttpRequestBase);
context.Response.Returns(HttpResponseBase);
context.Session.Returns(HttpSessionStateBase);
context.Server.Returns(HttpServerUtilityBase);
context.User = userContext;
HttpResponseBase.Cache.Returns(HttpCachePolicy);
Dictionary<string, object> owinEnvironment = new Dictionary<string, object>()
{
{"owin.RequestBody", null},
{"server.User", userContext}
};
Dictionary<object, object> itemDictionary = new Dictionary<object, object>();
itemDictionary.Add("owin.Environment", owinEnvironment);
context.Items.Returns(itemDictionary);
return context;
}
protected static HttpCachePolicyBase HttpCachePolicy;
}
}
<file_sep>using Microsoft.VisualStudio.TestTools.UnitTesting;
using OwinIdentitySimpleInjector.Controllers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace OwinIdentitySimpleInjector.Tests.Controllers
{
[TestClass]
public class HomeControllerTests : HttpContextTest
{
private HomeController _homeController;
[TestInitialize]
public void SetUp()
{
_homeController = new HomeController();
}
[TestMethod]
public void Authenticated_MockOwinContext_ReturnIfAuthneticatedCorrectView()
{
// Arrange
var context = GetMockedHttpContext();
// Act
// Assert
}
}
}
<file_sep>using Microsoft.Owin;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using NLog;
namespace OwinIdentitySimpleInjector.Middleware
{
public class RedirectMiddleware : OwinMiddleware
{
private OwinMiddleware _next;
private ILogger _logger = LogManager.GetLogger("RedirectMiddleware");
public RedirectMiddleware(OwinMiddleware next)
: base(next)
{
}
public async override Task Invoke(IOwinContext context)
{
var url = context.Request.Uri;
_logger.Info("Redirect demo, Begin Request");
if (url.AbsoluteUri == "http://localhost:52995/test")
{
if (context.Request.User != null && context.Request.User.Identity.IsAuthenticated)
{
//context.Response.StatusCode = 301;
//context.Response.Headers.Set("Location", "/home/authenticated");
await context.Response.WriteAsync("This feature is currently unavailable, even if the user is authenticated.");
}
else
{
string urlToRedirect = "http://localhost:52995/Redirect.html";
// for example you can redirect the page response in the middleware, 301 is the status code of permanent redirect
context.Response.StatusCode = 301;
context.Response.Headers.Set("Location", urlToRedirect);
}
}
else
{
await Next.Invoke(context);
}
_logger.Info("Redirect demo, End Request");
}
}
}<file_sep>using System.Collections.Generic;
using System.Threading.Tasks;
using NLog;
using AppFunc = System.Func<System.Collections.Generic.IDictionary<string, object>, System.Threading.Tasks.Task>;
namespace OwinIdentitySimpleInjector.Middleware
{
public class OwinDemoMiddleware
{
private AppFunc _next;
private ILogger _logger = LogManager.GetLogger("OwinDemoMiddleware");
public OwinDemoMiddleware(AppFunc next)
{
this._next = next;
}
public async Task Invoke(IDictionary<string, object> environment)
{
_logger.Info("Owin type demo, Begin Request");
await _next.Invoke(environment);
_logger.Info("Owin type demo, End Request");
}
}
}<file_sep>using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using OwinIdentitySimpleInjector.BO.Users;
using OwinIdentitySimpleInjector.DAL;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace OwinIdentitySimpleInjector.Core.Users
{
/// <summary>
/// Implements 'User Store' of ASP.NET Identity Framework.
/// </summary>
public class CustomUserStore : UserStore<ApplicationUser>, ICustomUserStore<ApplicationUser>
{
public CustomUserStore(ApplicationDbContext context)
: base(context)
{
}
}
}
<file_sep>using Microsoft.AspNet.Identity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace OwinIdentitySimpleInjector.Contracts
{
public interface ISmsService
{
Task SendAsync(IdentityMessage message);
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace OwinIdentitySimpleInjector.DAL.Contracts
{
public interface IApplicationDbContext
{
}
}
| bfc5a22513b67fe7b6a26d9c1e5b9f04a1311015 | [
"C#"
]
| 15 | C# | Filip3/OwinIdentitySimpleInjector | 856ea36491df9998391a75ea6e9629000ea6a841 | c16f47c9352c3d385ca1908b8f9e302802801d24 |
refs/heads/master | <repo_name>melnyknikolay/demo<file_sep>/src/main/java/com/example/demo/handler/HandlerException.java
package com.example.demo.handler;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
@ControllerAdvice
@Controller
public class HandlerException{
@ExceptionHandler(value = MaxUploadSizeExceededException.class)
public String uploadFileException(Model model){
model.addAttribute("msg", "MaxUploadSizeException");
return "error";
}
}
<file_sep>/src/main/java/com/example/demo/web/EventController.java
package com.example.demo.web;
import com.example.demo.model.Game;
import com.example.demo.service.EventService;
import com.example.demo.service.GamesService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.Collection;
@Controller
public class EventController {
private final EventService eventService;
private final GamesService gamesService;
public EventController(EventService eventService, GamesService gamesService) {
this.eventService = eventService;
this.gamesService = gamesService;
}
@GetMapping("/**")
public String welcome() {
return "redirect:/events";
}
@GetMapping("/events")
public String events(Model model) throws IOException {
model.addAttribute("events", eventService.getEvents());
return "eventPage";
}
@PostMapping("/events")
public String uploadEvents(@RequestParam("file") MultipartFile file, Model model) throws IOException {
String content = new String(file.getBytes(), "UTF-8");
eventService.uploadEvents(content);
model.addAttribute("events", eventService.getEvents());
return "eventPage";
}
@GetMapping("/games")
public String games(Model model) throws IOException {
Collection<Game> games = gamesService.getGames(eventService.getEvents());
model.addAttribute("games", games);
return "gamePage";
}
@PostMapping("/games")
public String uploadEventsRedirectToGames(@RequestParam("file") MultipartFile file, Model model) throws IOException {
String content = new String(file.getBytes(), "UTF-8");
eventService.uploadEvents(content);
Collection<Game> games = gamesService.getGames(eventService.getEvents());
model.addAttribute("games", games);
return "gamePage";
}
}
<file_sep>/src/main/java/com/example/demo/service/EventService.java
package com.example.demo.service;
import com.example.demo.model.Event;
import com.example.demo.repository.EventRepository;
import org.springframework.stereotype.Service;
import java.io.File;
import java.io.IOException;
import java.util.List;
@Service
public class EventService {
private final EventRepository repository;
private final ParseService parseService;
private final LoaderService loaderService;
public EventService(EventRepository repository, ParseService parseService, LoaderService loaderService) {
this.repository = repository;
this.parseService = parseService;
this.loaderService = loaderService;
}
public List<Event> getEvents() throws IOException {
if (repository.isEmpty()) {
repository.saveAll(getDefaultEvents());
}
return repository.getAllEvents().size() < 1500
?
repository.getAllEvents()
:
repository.getEventsLimited(1500L);
}
private List<Event> getDefaultEvents() throws IOException {
return parseService.parseJson(loaderService.loadEventsFromFile(new File("./2018-11-27B.json")));
}
public void uploadEvents(String content) throws IOException {
repository.saveAll(parseService.parseJson(content));
}
}
<file_sep>/src/main/java/com/example/demo/repository/EventRepository.java
package com.example.demo.repository;
import com.example.demo.model.Event;
import java.util.List;
public interface EventRepository {
void saveAll(List<Event> events);
List<Event> getAllEvents();
List<Event> getEventsLimited(Long limit);
boolean isEmpty();
}
<file_sep>/src/main/java/com/example/demo/service/ParseService.java
package com.example.demo.service;
import com.example.demo.model.Event;
import com.example.demo.model.SMEvent;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Service;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;
@Service
public class ParseService {
private final ObjectMapper mapper;
public ParseService(ObjectMapper mapper) {
this.mapper = mapper;
}
public List<Event> parseJson(String eventsJson) throws IOException {
List<Event> events = mapper.readValue(eventsJson, mapper.getTypeFactory().constructCollectionType(List.class, Event.class));
for (Event event : events) {
parseTextForSMEvents(event);
}
return events.stream().collect(Collectors.toList());
}
private void parseTextForSMEvents(Event event) throws IOException {
BufferedReader reader = new BufferedReader(new StringReader(event.getText()));
String text = "";
List<SMEvent> smEvents = new ArrayList<>();
while (reader.ready()) {
String line = reader.readLine();
if (line == null){
break;
}else if (!line.startsWith("SMEvent")){
if (line.startsWith("Late goal")){
text = line.substring(0, line.indexOf('['));
String[] smEvents1 = line.substring(line.indexOf('[') + 1, line.indexOf(']')).trim().split("SMEvent");
Arrays.stream(smEvents1)
.filter(str -> !str.equals(""))
.forEach(str -> addSMEvent(smEvents, str.trim()));
continue;
}
text = line;
continue;
}
addSMEvent(smEvents, line);
}
event.setText(text);
event.setSmEvents(smEvents);
}
private void addSMEvent(List<SMEvent> smEvents, String line) {
HashMap<String, String> pairParameters = new HashMap<>();
Arrays.stream(line.substring(line.indexOf('(') + 1, line.indexOf(')')).split(","))
.forEach(str -> pairParameters.put(str.substring(0, str.indexOf('=')).trim(), str.substring(str.indexOf('=') + 1).trim()));
SMEvent sm = SMEvent.builder()
.id(SMEvent.generateId())
.smEventId(parseLong(pairParameters.get("id")))
.teamId(parseLong(pairParameters.get("teamId")))
.type(validString(pairParameters.get("type")))
.fixtureId(parseLong(pairParameters.get("fixtureId")))
.playerId(parseLong(pairParameters.get("playerId")))
.playerName(validString(pairParameters.get("playerName")))
.relatedPlayerId(parseLong(pairParameters.get("relatedPlayerId")))
.relatedPlayerName(validString(pairParameters.get("relatedPlayerName")))
.minute(parseLong(pairParameters.get("minute")))
.extraMinute(validString(pairParameters.get("extraMinute")))
.reason(validString(pairParameters.get("reason")))
.injuried(validString(pairParameters.get("injuried")))
.result(validString(pairParameters.get("result")))
.build();
smEvents.add(sm);
}
private Long parseLong(String str){
return "null".equals(str) ? null : Long.parseLong(str);
}
private String validString(String str){
return "null".equals(str) ? null : str;
}
}
<file_sep>/src/main/java/com/example/demo/model/Event.java
package com.example.demo.model;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
@JsonInclude(JsonInclude.Include.NON_NULL)
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class Event {
private String text;
private String username;
@JsonProperty("bot_id")
private String botId;
@JsonProperty("is_auto_split")
private Boolean isAutoSplit;
private String type;
private String subtype;
private String ts;
private List<SMEvent> smEvents;
}<file_sep>/src/test/java/com/example/demo/service/LoaderServiceTest.java
package com.example.demo.service;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.core.io.ClassPathResource;
import org.springframework.test.context.junit4.SpringRunner;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import static org.junit.Assert.*;
@RunWith(SpringRunner.class)
public class LoaderServiceTest {
private LoaderService loaderService = new LoaderService();
@Test
public void loadEventsFromFile() throws IOException {
ClassPathResource classPathResource = new ClassPathResource("2018-11-27B.json", this.getClass().getClassLoader());
File testFile = classPathResource.getFile();
StringBuilder result = new StringBuilder();
BufferedReader reader = new BufferedReader(new FileReader(testFile));
while (reader.ready()){
result.append(reader.readLine());
}
String actual = loaderService.loadEventsFromFile(testFile);
assertEquals(result.toString(), actual);
}
}<file_sep>/src/main/resources/application.properties
server.port=8089
server.error.whitelabel.enabled=true | c7e307bbf889a057c365685df4140a8167cb5230 | [
"Java",
"INI"
]
| 8 | Java | melnyknikolay/demo | d328a13bb539824c0ffe257690f36cb6c6873b4c | 47bd8163cd4aa3e463a8684194cd604d62cd0374 |
refs/heads/master | <file_sep>■使い方
前提として、yarnがインストールされていることです。
格納されているreact.shを実行すればOKです。
引数ですが、
・第1引数:Reactプロジェクト名
・第2引数以降:各ページ用コード
になります。
例えば、
react.sh rpg aaa bbb ccc
と実行すると、
rpgというプロジェクトが作成され、
aaaとbbb、cccというページが作成されます。
App.jsには画面遷移用のパスが格納されております。
<file_sep>import React, { Component } from 'react'
import './battle.css'
export default class Battle extends Component {
constructor (props) {
super(props);
this.state = {
x:0,
};
}
componentDidMount(){
this.setState({x:0});
}
componentWillUnmount() {
}
render () {
return(
<div>
<p>Hello World</p>
</div>
)
}
}<file_sep>#!/bin/sh
#make React project.
create-react-app $1
#add new App.js
rm $1/src/App.js
cp App.js ./$1/src/
base=$((6+$#))
#make page file(add & make .js and .css)
for x in "$@"
do
if [ $x = $1 ]; then
echo "same var"
else
cp page1.js ./$1/src/$x.js
touch ./$1/src/$x.css
#delete and insert sentence in App.js.
sed -i -e "2d" ./$1/src/$x.js
sed -i -e "1a import './"$x".css'" ./$1/src/$x.js
sed -i -e "4d" ./$1/src/$x.js
sed -i -e "3a export default class "$x" extends Component {" ./$1/src/$x.js
sed -i -e "1a import "$x" from './"$x"'" ./$1/src/App.js
fi
done
for x in "$@"
do
if [ $x = $1 ]; then
echo "same var"
else
#delete and insert sentence in App.js.
sed -i -e $base"a <Route path='/"$x"' component={"$x"}/>" ./$1/src/App.js
fi
done
#install react-router-dom
yarn add install react-router-dom
cd $1
yarn start | ac231d83408f54ab169a451a481fdf1631144e11 | [
"Markdown",
"JavaScript",
"Shell"
]
| 3 | Markdown | Elsammit/React_SettingShell | 3834ec919c42260af883d0a5b26986a0fec727da | 7304aa99d0dce8a727c6e88273c748304bf2a453 |
refs/heads/master | <file_sep>from cProfile import label
from pyspark.mllib.linalg import SparseVector
import numpy as np
from pyspark import SparkConf,SparkContext
from pyspark.sql import SQLContext
from pyspark.ml.feature import PCA
from collections import defaultdict
import os
from pyspark.mllib.regression import LabeledPoint
from pyspark.mllib.classification import LogisticRegressionWithSGD,LogisticRegressionModel
from math import log,exp
import matplotlib.pyplot as plt
os.environ["PYSPARK_PYTHON"]="python3"
os.environ["PYSPARK_DRIVER_PYTHON"]="python3"
conf = SparkConf().setMaster("local")
sc = SparkContext(conf=conf)
sqlContext =SQLContext(sc)
######################################################
# one hot encoding function
def one_hot_encoding(rawFeats,OHEDict,numOHEFeats):
validFeatureTuples =[]
for (featID, value) in rawFeats:
try:
validFeatureTuples.append((OHEDict[(featID, value)], 1))
except KeyError:
pass
return SparseVector(numOHEFeats, validFeatureTuples)
# auto create ohe dictionary
def create_one_hot_dict(input_df):
retObj = (input_df.flatMap(lambda row:row)
.distinct()
.zipWithIndex()
.collectAsMap())
return retObj
raw_df = sc.textFile("/home/hadoop/PycharmProjects/data_ctr_criteo/test.txt").map(lambda x: x.replace('\t',','))
#raw_df.saveAsTextFile("subtrain_preprocess.txt")
weights =[.8,.1,.1]
seed =42
raw_train_df, raw_validation_df, raw_test_df = raw_df.randomSplit(weights, seed)
def parse_point(point):
feats = point.split(",")[1:]
return [(idx,value) for (idx,value) in enumerate(feats)]
parsedTrainFeat = raw_train_df.map(parse_point)
parsedValidFeat = raw_validation_df.map(parse_point)
####### PCA data ###############
pca = PCA(k=4, inputCol="features",outputCol="pcafeatures")
ctrOHEDict_train = create_one_hot_dict(parsedTrainFeat)
ctrOHEDict_valid = create_one_hot_dict(parsedValidFeat)
numCtrOHEFeats = len(ctrOHEDict_train.keys())
def pca_data(data,OHEDict):
df = sqlContext.createDataFrame(data,["features"])
model_pca= pca.fit(df)
data_pca = model_pca.transform(df).map(lambda x: parse_point(x))
numOHEFeats = len(data_pca.keys())
print(" THIS SHIT :",data_pca)
return one_hot_encoding(data_pca,OHEDict,numOHEFeats)
# df_train
# df_valid =sqlContext.createDataFrame(parsedTrainFeat,["features"])
# model_pca_train = pca.fit(df_train)
# data_pca_train = model_pca_train.transform(df_train).map(parse_point).select("pcafeatures")
# data_pca_train.show()
# model_pca_valid = pca.fit(df_valid)
# data_pca_valid = model_pca_valid.transform(df_valid)
#### tinh chieu dai OHEDict #################
def parseOHEPoint(point,OHEDict):
print("\n\n",parse_point(point),"\n\n")
pca_data(one_hot_encoding(parse_point(point), OHEDict))
# return LabeledPoint(point.split(',')[0],pca_data(one_hot_encoding(parse_point(point),OHEDict)),OHEDict)
OHETrainData = raw_train_df.map(lambda point:parseOHEPoint(point,ctrOHEDict_train))
# OHETrainData.cache()
# def bucketFeatByCount(featCount):
# """Bucket the counts by powers of two."""
# for i in range(11):
# size = 2 ** i
# if featCount <= size:
# return size
# return -1
#
# featCounts = (OHETrainData
# .flatMap(lambda lp: lp.features.indices)
# .map(lambda x: (x, 1))
# .reduceByKey(lambda x, y: x + y))
# featCountsBuckets = (featCounts
# .map(lambda x: (bucketFeatByCount(x[1]), 1))
# .filter(lambda x: x[0] != -1)
# .reduceByKey(lambda x, y: x + y)
# .collect())
# print (featCountsBuckets)
OHEValidationData = raw_validation_df.map(lambda point: parseOHEPoint(point, ctrOHEDict_valid, 4))
# OHEValidationData.cache()
############################
### hash data ##############
############################
# from collections import defaultdict
# import hashlib
#
# def hashFunction(numBuckets, rawFeats, printMapping = False):
# mapping = {}
# for ind, category in rawFeats:
# featureString = category + str(ind)
# featureString = featureString.encode('utf-8')
# mapping[featureString] = int(int(hashlib.md5(featureString).hexdigest(),16)%numBuckets)
# if(printMapping): print(mapping)
# sparseFeatures = defaultdict(float)
# for bucket in mapping.values():
# sparseFeatures[bucket] +=1.0
# return dict(sparseFeatures)
#
# def parseHashPoint(point,numBuckets):
# fields = point.split(",")
# label = fields[0]
# features = parse_point(point)
# return LabeledPoint(label,SparseVector(numBuckets,hashFunction(numBuckets,features)))
#
# numBucketCTR = 2**15
# hashTrainData = raw_train_df.map(lambda point: parseHashPoint(point,numBucketCTR))
# hashTrainData.cache()
# hashValidationData = raw_validation_df.map(lambda point:parseHashPoint(point,numBucketCTR))
# hashTrainData.cache()
# training CTR #############
numIters = 50
stepSize = 10.
regParam = 1e-10
regType = 'l2'
includeIntercept = True
model0 = LogisticRegressionWithSGD.train(OHETrainData,iterations=numIters,step=stepSize,regParam=regParam,regType=regType,intercept=includeIntercept)
sortedWeights = sorted(model0.weights)
#model0.save(sc,"/home/hadoop/PycharmProjects/ctr_predict/model0")
## train with hashdata#############
def getP(x, w, intercept):
rawPrediction = w.dot(x) + intercept
# Bound the raw prediction value
rawPrediction = min(rawPrediction, 20)
rawPrediction = max(rawPrediction, -20)
return 1 / (1 + exp(-rawPrediction))
def computeLogLoss(p, y):
epsilon = 10e-12
if p == 0:
p += epsilon
elif p == 1:
p -= epsilon
if y == 1:
return -log(p)
else:
return -log(1 - p)
def evaluateResults(model, data):
"""Calculates the log loss for the data given the model.
Args:
model (LogisticRegressionModel): A trained logistic regression model.
data (RDD of LabeledPoint): Labels and features for each observation.
Returns:
float: Log loss for the data.
"""
return (data
.map(lambda lp: (lp.label, getP(lp.pcafeatures, model.weights, model.intercept)))
.map(lambda x: computeLogLoss(x[1], x[0]))
.mean())
# for stepSize in stepSizes:
# for regParam in regParams:
# model0 = (LogisticRegressionWithSGD
# .train(hashTrainData, numIters, stepSize, regParam=regParam, regType=regType,
# intercept=includeIntercept))
# logLossVa = evaluateResults(model0, hashValidationData)
# print ('\tstepSize = {0:.1f}, regParam = {1:.0e}: logloss = {2:.3f}'
# .format(stepSize, regParam, logLossVa))
# if (logLossVa < bestLogLoss):
# bestModel = model0
# bestLogLoss = logLossVa
# model0 = LogisticRegressionModel.load(sc, "model0")
###log loss,predict function#################
# trainingPredictions = hashTrainData.map(lambda lp: getP(lp.features, model0.weights, model0.intercept))
# baseline log loss #################
classOneFracTrain = OHETrainData.map(lambda lp: lp.label).mean()
print (classOneFracTrain)
logLossTrBase = OHETrainData.map(lambda lp: computeLogLoss(classOneFracTrain, lp.label)).mean()
print('Baseline Train Logloss = {0:.3f}\n'.format(logLossTrBase))
# ## evaluate model ###################
#
# def evaluateResult(model,data):
# return (data.map(lambda x: (x.label,getP(x.features,model.weights,model.intercept))).
# map(lambda x:computeLogLoss(x[1],x[0])).mean())
# logLossTrLR0 = evaluateResult(model0,OHETrainData)
# print("OHE Features Train LogLoss :\n baseline ={0:.3f}\n loglossTrLR0 = {0:.3f} ".format(logLossTrBase,logLossTrLR0) )
#########################
### visualize data#######
#########################
def ROC(label,result):
from sklearn.utils import shuffle
from sklearn.metrics import roc_curve, auc
import pylab as pl
# Compute ROC curve and area the curve
Y = np.array(label)
fpr, tpr, thresholds = roc_curve(Y, result)
roc_auc = auc(fpr, tpr)
print ("Area under the ROC curve : %f" % roc_auc)
# Plot ROC curve
pl.clf()
pl.plot(fpr, tpr, label='ROC curve (area = %0.2f)' % roc_auc)
pl.plot([0, 1], [0, 1], 'k--')
pl.xlim([0.0, 1.0])
pl.ylim([0.0, 1.0])
pl.xlabel('False Positive Rate')
pl.ylabel('True Positive Rate')
pl.title('Receiver operating characteristic')
pl.legend(loc="lower right")
pl.show()
labelsAndScores = OHEValidationData.map(lambda lp:
(lp.label, getP(lp.pcafeatures, model0.weights, model0.intercept)))
labelsAndWeights = labelsAndScores.collect()
labelsAndWeights.sort(key=lambda x: x[0], reverse=True)
X_label = np.array([k for (k, v) in labelsAndWeights])
Y_result = np.array([v for (k, v) in labelsAndWeights])
ROC(X_label,Y_result)
<file_sep>import pandas as pd
import re
df = pd.read_csv("truyenkieu.txt",sep="/",names=["row"]).dropna()
print(df.head(10))
def transform_row(row):
row = re.sub(r"^[0-9\.]+","",row)
row = re.sub(r"[\.,\?]")<file_sep>import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.linear_model import LogisticRegression
from sklearn.cross_validation import train_test_split
import seaborn as sns
from sklearn.model_selection import train_test_split
sns.set(style= "white")
sns.set(style="whitegrid",color_codes=True)
plt.rc("font", size=14)
# load data and preprocess
data = pd.read_csv("/home/hadoop/PycharmProjects/train_subset.csv",header=0)
data = data.dropna()
df = pd.DataFrame(data,columns=(['id', 'click', 'hour', 'C1', 'banner_pos', 'site_id', 'site_domain', 'site_category',
'app_id', 'app_domain', 'app_category', 'device_id', 'device_ip', 'device_model',
'device_type', 'device_conn_type', 'C14', 'C15', 'C16', 'C17', 'C18', 'C19', 'C20', 'C21']))
df['C1'] =df['C1'].astype(str)
df['device_type'] = df['C1'].astype(str)
df = df.drop(['id', 'hour','banner_pos', 'site_id', 'site_domain', 'site_category', 'app_id', 'app_domain', 'app_category',
'device_id', 'device_ip', 'device_model','device_conn_type','C18','C20'],axis=1)
print(list(df))
data2 = pd.get_dummies(df,columns=['C1', 'device_type', 'C14', 'C15', 'C16', 'C17', 'C19', 'C21'])
X= data2.iloc[:,1:]
y = data2.iloc[:,0]
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0,test_size=0.2)
# training model
classifier = LogisticRegression(random_state=0)
classifier.fit(X_train,y_train)
y_predict = classifier.predict(X_test)
from sklearn.metrics import confusion_matrix
confusion_matrix = confusion_matrix(y_test,y_predict)
print(confusion_matrix)
print("accurancy :{:.2f}".format(classifier.score(X_test,y_test)))
| 7538e73b80f2ca379278f7a86208d12e329e2272 | [
"Python"
]
| 3 | Python | hieubz/ctr_prediction | 695b3362611a8962cd279486bd9a57da4f180aa2 | 79b840a59973ff9b425d50d4065f06214534dbe6 |
refs/heads/master | <repo_name>afecondo/my-resume<file_sep>/myclasses.py
from flask import Flask, render_template, request, flash
app = Flask(__name__)
app.secret_key = 'this should be a secret key'
@app.route('/')
def index():
# return HTML
# return "<h1>this is the index page!<h1>"
return render_template('index.html')
@app.route('/songs')
def show_all_classes():
classes = [
'MISY350',
'BUAD345',
'MISY261'
]
return render_template('song-all.html', classes=classes)
@app.route('/about')
def about():
return render_template('about.html')
@app.route('/users')
def show_all_users():
return render_template('user-all.html')
@app.route('/form-demo', methods=['GET', 'POST'])
def form_demo():
# how to get form data is different for GET vs. POST
if request.method == 'GET':
first_name = request.args.get('first_name')
return render_template('form-demo.html', first_name=first_name)
if request.method == 'POST':
first_name = request.form['first_name']
return render_template('form-demo.html', first_name=first_name)
@app.route('/user/<string:name>/')
def get_user_name(name):
# return "hello " + name
# return "Hello %s, this is %s" % (name, 'administrator')
return render_template('user.html', name=name)
@app.route('/classes/<int:id>/')
def get_song_id(id):
# return "This song's ID is " + str(id)
return "Hi, this is %s and the classes's id is %d" % ('administrator', id)
# https://goo.gl/Pc39w8 explains the following line
if __name__ == '__main__':
# activates the debugger and the reloader during development
# app.run(debug=True)
app.run()
# make the server publicly available on port 80
# note that Ports below 1024 can be opened only by root
# you need to use sudo for the following conmmand
# app.run(host='0.0.0.0', port=80)
<file_sep>/README.md
# my-resume
my-resume homework
| 37170882a5dc31262a6cf418baba71e6f76de12f | [
"Markdown",
"Python"
]
| 2 | Python | afecondo/my-resume | ae455e69726b3bf3d5261fc4dc2ba21265aa2a11 | b5a5b887208f0fe1229ab067440f7e5f3e8e72fb |
refs/heads/master | <file_sep>
var userAgent = window.navigator.userAgent.toLowerCase();
var appVersion = window.navigator.appVersion.toLowerCase();
if((userAgent.indexOf("msie") != -1 && (appVersion.indexOf("msie 8.") != -1 || appVersion.indexOf("msie 9.") != -1)) || navigator.userAgent.indexOf('Android') > 0 || navigator.userAgent.indexOf('iPad') > 0 || navigator.userAgent.indexOf('iPhone') > 0 || navigator.userAgent.indexOf('iPod') > 0){
$(function () {
$('#btn_play-m1-1 a').attr({href:'http://youtu.be/fem5RriWjeQ',target:'_blank'});
});
} else {
/**
* youtube
*/
var youtubeConfig = {
player : [
{
id : 'm0',
vId: 'fem5RriWjeQ'
},
{
id : 'm1-1',
vId: 'fem5RriWjeQ'
}
]
};
var youtubePlayer = {}
function onYouTubeIframeAPIReady() {
$.each(youtubeConfig.player, function(index) {
youtubePlayer[this.id] = new YT.Player(this.id, {
height: '480',
width: '853',
videoId: this.vId,
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
},
playerVars: {
"rel":0,
}
});
});
}
function onPlayerReady(event) {
}
var done = false;
function onPlayerStateChange(event) {
}
function stopVideo(id) {
youtubePlayer[id].stopVideo();
}
function playVideo(id) {
youtubePlayer[id].playVideo();
}
/**
* movie
*/
$(window).load(function () {
var target = $('.overlay'),
closeBtn = target.find('.overlay-close'),
trigger = $('#trigger-overlay');
trigger.click(function (e) {
$(target).addClass('open');
playVideo('m0');
e.preventDefault();
});
closeBtn.click(function () {
$(target).removeClass('open');
stopVideo('m0');
});
if(!$.cookie('movie')){
setTimeout(function() {
$.cookie('movie', 'true');
$(target).addClass('open');
setTimeout(function() {
playVideo('m0');
}, 500);
}, 2500);
}
});
$(function () {
$('.js-trigger-movie').each(function(index) {
var self = this,
target = $($(self).attr('href')),
closeBtn = target.find('.overlay-close');
$(self).click(function (e) {
var anc = $(this).attr('href');
$(anc).addClass('open');
setTimeout(function() {
playVideo($(self).data('controll-id'));
}, 500);
e.preventDefault();
});
closeBtn.click(function () {
$(target).removeClass('open');
stopVideo($(self).data('controll-id'));
});
});
});/*End Movie Player*/
}
<file_sep>/* youtube */
var youtubeConfig = {
player : [
{
id : 'movie_01',
vId: 'Cd3-Bz3y_Hs'
},
{
id : 'movie_02',
vId: 'cEIS4XWCK0g'
},
{
id : 'movie_03',
vId: 'R8ADBpBkWQU'
},
{
id : 'movie_04',
vId: '_utkkmN6C4M'
},
{
id : 'movie_05',
vId: '8gXd8UI9kHk'
},
{
id : 'movie_06',
vId: 'PUrHijnkGhM'
},
{
id : 'movie_07',
vId: 'cup6FQTqMoA'
},
{
id : 'movie_08',
vId: '6YwU9A-KL08'
},
{
id : 'movie_09',
vId: 'GBTKb4mYemI'
},
{
id : 'movie_10',
vId: 'Z31Kc94WjyI'
},
{
id : 'movie_11',
vId: 'R8Y2M1WqaT0'
}
]
};
var youtubePlayer = {}
function onYouTubeIframeAPIReady() {
$.each(youtubeConfig.player, function(index) {
youtubePlayer[this.id] = new YT.Player(this.id, {
height: '360',
width: '640',
videoId: this.vId,
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
},
playerVars: {
"rel":0,
}
});
});
}
function onPlayerReady(event) {
// event.target.mute();
}
var done = false;
function onPlayerStateChange(event) {
// if (event.data == YT.PlayerState.PLAYING && !done) {
// setTimeout(stopVideo, 6000);
// done = true;
// }
}
function stopVideo(id) {
youtubePlayer[id].stopVideo();
}
function playVideo(id) {
youtubePlayer[id].playVideo();
}
$(function(){
$('#modal_movie').on('show.bs.modal', function (event) {
var wH = $(window).height();
var button = $(event.relatedTarget);
var margin_left = button.data('margin_left');
var modal = $(this);
modal.find('#movie_portfolio').css('margin-left', margin_left);
});
$('#modal_web-print').on('show.bs.modal', function (event) {
var wH = $(window).height();
var button = $(event.relatedTarget);
var margin_left = button.data('margin_left');
var modal = $(this);
modal.find('#print_portfolio').css('margin-left', margin_left);
});
$('.js-trigger-movie').each(function(index) {
var self = this,
target = $($(self).attr('href')),
closeBtn = target.find('.close');
$(self).click(function (e) {
var anc = $(this).attr('href');
setTimeout(function() {
playVideo($(self).data('controll-id'));
}, 500);
e.preventDefault();
});
$('.close').click(function () {
stopVideo($(self).data('controll-id'));
});
// $('#modal_movie').on('show.bs.modal', function (event) {
// var wH = $(window).height();
// var button = $(event.relatedTarget)
// var margin_left = button.data('margin_left');
// var modal = $(this);
// modal.find('#portfolio').css('margin-left', margin_left);
// });
});
var controller = $.superscrollorama();
controller.addTween('#fade-it', TweenMax.from( $('#fade-it'), .5, {css:{opacity: 0}}));
controller.addTween('#fade-it-works', TweenMax.from( $('#fade-it-works'), .5, {css:{opacity: 0}}));
controller.addTween('#fade-it-elements', TweenMax.from( $('#fade-it-elements'), .5, {css:{opacity: 0}}));
controller.addTween('#fade-it-thought', TweenMax.from( $('#fade-it-thought'), .5, {css:{opacity: 0}}));
});
| 87dfd5a373a502786532db3a388449a7a2ac6b1d | [
"JavaScript"
]
| 2 | JavaScript | YoshiISHIGAMI/elemental.co.jp | ce8bf7c45f94595ed12bf5b7753b8b127d48e08e | eb52cc19b934d248e15efa8f592ebd5b9963baca |
refs/heads/master | <file_sep>import pykd
from os.path import expanduser
import timeit
start = timeit.default_timer()
home = expanduser("~")
return_reg = "rax"
stack_pointer = "rsp"
arch_bits = 64
log = None
def get_address(localAddr):
res = pykd.dbgCommand("x " + localAddr)
result_count = res.count("\n")
if result_count == 0:
print localAddr + " not found."
return None
if result_count > 1:
print "[-] Warning, more than one result for", localAddr
return res.split()[0]
class time(pykd.eventHandler):
def __init__(self):
addr = get_address("jscript9!StrToDbl")
if addr == None:
return
self.start = timeit.default_timer()
self.bp_init = pykd.setBp(int(addr, 16), self.enter_call_back)
def enter_call_back(self,bp):
end = timeit.default_timer()
print "Heap spray took: " + str(end - self.start)
return True
time()
pykd.go()<file_sep>import pykd
print pykd.dbgCommand("!teb")<file_sep>import pykd
return_reg = "rax"
stack_pointer = "rsp"
def get_address(localAddr):
res = pykd.dbgCommand("x " + localAddr)
result_count = res.count("\n")
if result_count == 0:
print localAddr + " not found."
return None
if result_count > 1:
print "[-] Warning, more than one result for", localAddr
return res.split()[0]
#RtlAllocateHeap(
# IN PVOID HeapHandle,
# IN ULONG Flags,
# IN ULONG Size );
class handle_allocate_heap(pykd.eventHandler):
def __init__(self):
addr = get_address("ntdll!RtlAllocateHeap")
if addr == None:
return
self.bp_init = pykd.setBp(int(addr, 16), self.enter_call_back)
self.bp_end = None
def enter_call_back(self,bp):
self.out = "RtlAllocateHeap("
esp = pykd.reg("esp")
self.out += hex(pykd.ptrPtr(esp + 4)) + " , "
self.out += hex(pykd.ptrMWord(esp + 0x8)) + " , "
self.out += hex(pykd.ptrMWord(esp + 0xC)) + ") = "
if self.bp_end == None:
disas = pykd.dbgCommand("uf ntdll!RtlAllocateHeap").split('\n')
for i in disas:
if 'ret' in i:
self.ret_addr = i.split()[0]
break
self.bp_end = pykd.setBp(int(self.ret_addr, 16), self.return_call_back)
return False
def return_call_back(self,bp):
self.out += hex(pykd.reg(return_reg))
print self.out
return False
try:
pykd.reg("rax")
except:
return_reg = "eax"
stack_pointer = "esp"
handle_allocate_heap()
pykd.go()<file_sep>/*
Uses windbg's JavaScript scripting support to trace user mode memory allocations in a format viewable with villoc
Heavily based off of https://doar-e.github.io/blog/2017/12/01/debugger-data-model/
*/
"use strict";
var archBits = 0;
var returnReg = null;
var stackPointer = null;
var allocateHeapOut = null;
var reallocateHeapOut = null;
var freeHeapOut = null;
function hex(val) {
return val.toString(16);
}
function print(msg) {
host.diagnostics.debugLog(msg);
}
function findRetAddrs(mod, name){
var addrs = [];
for(var line of host.namespace.Debugger.Utility.Control.ExecuteCommand("uf " + mod + ':' + name)){
if(line.includes('ret')){
var addr = host.parseInt64(line.split(" ")[0], 16);
addrs.push(addr);
}
}
return addrs;
}
/*#RtlAllocateHeap(
# IN PVOID HeapHandle,
# IN ULONG Flags,
# IN ULONG Size );*/
function handleAllocateHeap() {
var regs = host.currentThread.Registers.User;
var out = "RtlAllocateHeap(";
var args = null;
if(archBits == 32){
args = host.memory.readMemoryValues(regs[stackPointer] + 4, 3, 4);
} else {
args = [regs.rcx, regs.rdx, regs.r8];
}
out += hex(args[0]) + ", ";
out += hex(args[1]) + ", ";
out += hex(args[2]) + ") = ";
allocateHeapOut = out;
return false;
}
/* #RtlReAllocateHeap(
#IN PVOID HeapHandle,
#IN ULONG Flags,
# IN PVOID MemoryPointer,
# IN ULONG Size );
*/
function handleReAllocateHeap() {
var regs = host.currentThread.Registers.User;
var out = "RtlReAllocateHeap(";
var args = null;
if(archBits == 32){
args = host.memory.readMemoryValues(regs[stackPointer] + 4, 4, 4);
} else {
args = [regs.rcx, regs.rdx, regs.r8, regs.r9];
}
out += hex(args[0]) + ", ";
out += hex(args[1]) + ", ";
out += hex(args[2]) + ", ";
out += hex(args[3]) + ") = ";
reallocateHeapOut = out;
return false;
}
/*#RtlFreeHeap(
#IN PVOID HeapHandle,
#IN ULONG Flags OPTIONAL,
#IN PVOID MemoryPointer );*/
function handleFreeHeap() {
var regs = host.currentThread.Registers.User;
var out = "RtlFreeHeap(";
var args = null;
if(archBits == 32){
args = host.memory.readMemoryValues(regs[stackPointer] + 4, 3, 4);
} else {
args = [regs.rcx, regs.rdx, regs.r8];
}
out += hex(args[0]) + ", ";
out += hex(args[1]) + ", ";
out += hex(args[2]) + ") = ";
freeHeapOut = out;
return false;
}
function handleAllocateHeapRet() {
var regs = host.currentThread.Registers.User;
if(allocateHeapOut != null){
print(allocateHeapOut + hex(regs[returnReg]) + "\r\n");
allocateHeapOut = null;
}
return false;
}
function handleReAllocateHeapRet() {
var regs = host.currentThread.Registers.User;
if(reallocateHeapOut != null){
print(reallocateHeapOut + hex(regs[returnReg]) + "\r\n");
reallocateHeapOut = null;
}
return false;
}
function handleFreeHeapRet() {
var regs = host.currentThread.Registers.User;
if(freeHeapOut != null){
print(freeHeapOut + hex(regs[returnReg]) + "\r\n");
freeHeapOut = null;
}
return false;
}
function invokeScript() {
try {
host.currentThread.Registers.User.rax;
archBits = 64;
returnReg = "rax";
stackPointer = "rsp";
} catch (e) {
archBits = 32;
returnRed = "eax";
stackPointer = "esp";
}
print("Running on a " + archBits + "-bit process.\r\n");
var RtlAllocateHeap = host.getModuleSymbolAddress('ntdll', 'RtlAllocateHeap');
var RtlFreeHeap = host.getModuleSymbolAddress('ntdll', 'RtlFreeHeap');
var RtlReAllocateHeap = host.getModuleSymbolAddress('ntdll', 'RtlReAllocateHeap');
print('Hooking:\r\n\tRltAllocateHeap: ' + hex(RtlAllocateHeap) + "\r\n\tRtlFreeHeap: " + hex(RtlFreeHeap) + "\r\n\tRtlReAllocateHeap: " + hex(RtlReAllocateHeap) + "\r\n");
var breakpointsAlreadySet = host.currentProcess.Debug.Breakpoints.Any(
bp => bp.Address == RtlAllocateHeap || bp.Address == RtlFreeHeap || by.Address == RtlReAllocateHeap
);
if(breakpointsAlreadySet == false) {
host.namespace.Debugger.Utility.Control.ExecuteCommand('bp /w "@$scriptContents.handleAllocateHeap()" ' + RtlAllocateHeap.toString(16));
host.namespace.Debugger.Utility.Control.ExecuteCommand('bp /w "@$scriptContents.handleFreeHeap()" ' + RtlFreeHeap.toString(16));
host.namespace.Debugger.Utility.Control.ExecuteCommand('bp /w "@$scriptContents.handleReAllocateHeap()" ' + RtlReAllocateHeap.toString(16));
}
var RtlAllocateHeapRet = findRetAddrs("ntdll", "RtlAllocateHeap");
var RtlFreeHeapRet = findRetAddrs('ntdll', 'RtlFreeHeap');
var RtlReAllocateHeapRet = findRetAddrs('ntdll', 'RtlReAllocateHeap');
print('\tRltAllocateHeapRet: ' + hex(RtlAllocateHeapRet) + "\r\n\tRtlFreeHeapRet: " + hex(RtlFreeHeapRet) + "\r\n\tRtlReAllocateHeapRet: " + hex(RtlReAllocateHeapRet) + "\r\n");
var retBreakpointsAlreadySet = host.currentProcess.Debug.Breakpoints.Any(
bp => bp.Address in RtlAllocateHeapRet || bp.Address in RtlFreeHeapRet || bp.Address in RtlReAllocateHeapRet
);
if(retBreakpointsAlreadySet == false) {
for(var addr in RtlAllocateHeapRet){
host.namespace.Debugger.Utility.Control.ExecuteCommand('bp /w "@$scriptContents.handleAllocateHeapRet()" ' + RtlAllocateHeapRet[addr].toString(16));
}
for(var addr in RtlFreeHeapRet){
host.namespace.Debugger.Utility.Control.ExecuteCommand('bp /w "@$scriptContents.handleFreeHeapRet()" ' + RtlFreeHeapRet[addr].toString(16));
}
for(var addr in RtlReAllocateHeapRet){
host.namespace.Debugger.Utility.Control.ExecuteCommand('bp /w "@$scriptContents.handleReAllocateHeapRet()" ' + RtlReAllocateHeapRet[addr].toString(16));
}
}
}<file_sep>import pykd
def get_address(localAddr):
res = pykd.dbgCommand("x " + localAddr)
result_count = res.count("\n")
if result_count == 0:
print localAddr + " not found."
return None
if result_count > 1:
print "[-] Warning, more than one result for", localAddr
return res.split()[0]
class handle_allocate_heap(pykd.eventHandler):
def __init__(self):
addr = get_address("ntdll!RtlAllocateHeap")
if addr == None:
return
self.bp_init = pykd.setBp(int(addr, 16), self.enter_call_back)
self.bp_end = None
def enter_call_back(self,bp):
print "RtlAllocateHeap called."
if self.bp_end == None:
disas = pykd.dbgCommand("uf ntdll!RtlAllocateHeap").split('\n')
for i in disas:
if 'ret' in i:
self.ret_addr = i.split()[0]
break
self.bp_end = pykd.setBp(int(self.ret_addr, 16), self.return_call_back)
return False
def return_call_back(self,bp):
print "RtlAllocateHeap returned."
return False
handle_allocate_heap()
pykd.go()<file_sep># windbg-plugins
Repository for any useful windbg plugins I've written.
#heap_trace
Hooks heap operations and tracks their arguments and return values.
Run:
<pre>
.load pykd.pyd
!py "PATH_TO_REPO\heap_trace.py"
</pre>
This will log to your home directory as log.log. You can then create a villoc visualisation of this by running:
<pre>
python villoc.py log.log out.html
</pre>
Example villoc output:

#Requirements
All plugins use the [pykd](https://pykd.codeplex.com/) python interface for windbg. | 9fc886661ebb9672eb4889a06ba97f799a70f0a7 | [
"JavaScript",
"Python",
"Markdown"
]
| 6 | Python | chubbymaggie/windbg-plugins | 07cef89fc1fcdf3ba6471e04f61c2c05bbea51ef | cad5f54c3007de4e003c695ec547ac36611d861f |
refs/heads/master | <repo_name>jenniferpeterson/inventory<file_sep>/inventory/models.py
from django.contrib.auth.models import AbstractUser
from django.db import models
from django.utils.timezone import now
# Create your models here.
class User(AbstractUser):
household = models.ManyToManyField("User", blank=True)
def __str__(self):
return f"{self.username}"
class Household_request(models.Model):
from_user = models.ForeignKey(
User, related_name='from_user', on_delete=models.CASCADE)
to_user = models.ForeignKey(
User, related_name='to_user', on_delete=models.CASCADE)
def __str__(self):
return f"To: {self.to_user}, From: {self.from_user}"
class Category(models.Model):
category_name = models.CharField(max_length=64)
def __str__(self):
return f"{self.category_name}"
class Location(models.Model):
location = models.CharField(max_length=64)
created_by = models.ForeignKey(
User, on_delete=models.CASCADE, related_name="created_by_loc")
def __str__(self):
return f"{self.location}"
class StorageType(models.Model):
storage_type = models.CharField(max_length=64)
location = models.ForeignKey(
Location, on_delete=models.CASCADE, blank=True, related_name="storage_location")
notes = models.TextField(blank=True)
created_by = models.ForeignKey(
User, on_delete=models.CASCADE, related_name="created_by_stor")
def __str__(self):
return f"{self.storage_type} in {self.location} - Storage Owner: {self.created_by}"
class Item(models.Model):
item_name = models.CharField(max_length=64)
description = models.TextField(blank=True)
owner = models.ForeignKey(
User, related_name="owner", on_delete=models.CASCADE)
create_date = models.DateTimeField(default=now)
category = models.ForeignKey(
Category, on_delete=models.CASCADE, related_name="item_category")
img = models.URLField(blank=True)
stored_in = models.ForeignKey(
StorageType, on_delete=models.CASCADE, blank=True, related_name="stored_in")
def __str__(self):
return f"{self.item_name} in {self.stored_in}"
<file_sep>/inventory/views.py
from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect
from django.contrib.auth import authenticate, login, logout
from django.db import IntegrityError
from django.urls import reverse
from django.contrib.auth.decorators import login_required
from django.views.decorators.csrf import csrf_exempt
from .forms import NewItemForm, NewStorage, NewStorageLocation, SearchUsersForm
from .models import User, Category, Location, Item, StorageType, Household_request
from django.http.response import JsonResponse
import logging
import json
from django import forms
from django.db.models import Q
logger = logging.getLogger(__name__)
def index(request):
try:
current_user = User.objects.get(id=request.user.pk)
except User.DoesNotExist:
return render(request, "inventory/login.html")
user_household = current_user.household.all()
household_inventory = []
inventory = Item.objects.filter(owner=int(request.user.pk))
# Get household's locations and storage
location = Location.objects.filter(created_by=request.user.pk)
storage = StorageType.objects.filter(created_by=request.user.pk)
for x in user_household:
# logger.error(x)
user_inventory = Item.objects.filter(owner=int(x.pk))
household_inventory.extend(user_inventory)
household_locations = Location.objects.filter(created_by=int(x.pk))
location = location | household_locations
household_storage = StorageType.objects.filter(created_by=int(x.pk))
storage = storage | household_storage
household_inventory.extend(inventory)
location.order_by('location')
storage.order_by('storage_type')
categories = Category.objects.order_by('category_name')
numRequests = Household_request.objects.filter(to_user=request.user.pk)
return render(request, "inventory/index.html", {
"inventory": household_inventory,
"categories": categories,
"location": location,
"storage": storage,
"numRequests": numRequests
})
def user_inventory(request):
numRequests = Household_request.objects.filter(to_user=request.user.pk)
user = User.objects.get(pk=int(request.user.pk))
user_inventory = Item.objects.filter(owner=int(request.user.pk))
categories = Category.objects.order_by('category_name')
user_household = user.household.all()
# Get household's locations and storage
location = Location.objects.filter(created_by=request.user.pk)
storage = StorageType.objects.filter(created_by=request.user.pk)
for x in user_household:
household_locations = Location.objects.filter(created_by=int(x.pk))
location = location | household_locations
household_storage = StorageType.objects.filter(created_by=int(x.pk))
storage = storage | household_storage
location.order_by('location')
storage.order_by('storage_type')
return render(request, "inventory/user_inventory.html", {
"user": user,
"inventory": user_inventory,
"categories": categories,
"location": location,
"storage": storage,
"numRequests": numRequests
})
def create_item(request):
numRequests = Household_request.objects.filter(to_user=request.user.pk)
user_storage = StorageType.objects.filter(created_by=int(request.user.pk))
user = User.objects.get(pk=int(request.user.pk))
user_household = user.household.all()
for x in user_household:
temp = StorageType.objects.filter(created_by=int(x.pk))
user_storage = user_storage | temp
logger.error(user_storage.order_by('storage_type'))
NewItemForm.base_fields['stored_in'] = forms.ModelChoiceField(
queryset=user_storage.order_by('storage_type'), widget=forms.Select(attrs={'class': 'form-control'}))
if request.method == "POST":
form = NewItemForm(request.POST)
if form.is_valid():
item_name = form.cleaned_data['item_name']
description = form.cleaned_data['description']
category = form.cleaned_data['category']
img = form.cleaned_data['img']
owner = User.objects.get(pk=int(request.user.pk))
stored_in = form.cleaned_data['stored_in']
item = Item(item_name=item_name, description=description, category=category,
img=img, owner=owner, stored_in=stored_in)
item.save()
return render(request, "inventory/input_item.html", {
"form": NewItemForm(),
"numRequests": numRequests,
})
return render(request, "inventory/input_item.html", {
"form": NewItemForm(),
"numRequests": numRequests,
})
def create_storage(request):
numRequests = Household_request.objects.filter(to_user=request.user.pk)
user = User.objects.get(pk=int(request.user.pk))
user_locations = Location.objects.filter(created_by=int(request.user.pk))
NewStorage.base_fields['location'] = forms.ModelChoiceField(
queryset=user_locations.order_by('location'), widget=forms.Select(attrs={'class': 'form-control'}))
if request.method == "POST":
form = NewStorage(request.POST)
if form.is_valid():
storage_type = form.cleaned_data["storageType"]
location = form.cleaned_data["location"]
notes = form.cleaned_data["notes"]
created_by = User.objects.get(pk=int(request.user.pk))
s = StorageType(storage_type=storage_type,
location=location, notes=notes, created_by=created_by)
s.save()
return render(request, "inventory/create_storage.html", {
"form": NewStorage(),
"numRequests": numRequests
})
def create_location(request):
numRequests = Household_request.objects.filter(to_user=request.user.pk)
if request.method == "POST":
form = NewStorageLocation(request.POST)
if form.is_valid():
location = form.cleaned_data["location"]
created_by = User.objects.get(pk=int(request.user.pk))
l = Location(location=location, created_by=created_by)
l.save()
return render(request, "inventory/create_location.html", {
"form": NewStorageLocation(),
"numRequests": numRequests
})
def login_view(request):
if request.method == "POST":
# Attempt to sign user in
username = request.POST["username"]
password = request.POST["password"]
user = authenticate(request, username=username, password=<PASSWORD>)
# Check if authentication successful
if user is not None:
login(request, user)
return HttpResponseRedirect(reverse("index"))
else:
return render(request, "inventory/login.html", {
"message": "Invalid username and/or password."
})
else:
return render(request, "inventory/login.html")
def logout_view(request):
logout(request)
return render(request, "inventory/login.html")
def register(request):
if request.method == "POST":
username = request.POST["username"]
email = request.POST["email"]
# Ensure password matches confirmation
password = request.POST["password"]
confirmation = request.POST["confirmation"]
if password != confirmation:
return render(request, "inventory/register.html", {
"message": "Passwords must match."
})
# Attempt to create new user
try:
user = User.objects.create_user(username, email, password)
user.save()
except IntegrityError:
return render(request, "inventory/register.html", {
"message": "Username already taken."
})
login(request, user)
return HttpResponseRedirect(reverse("index"))
else:
return render(request, "inventory/register.html")
@csrf_exempt
@login_required
def update_location(request, item_id):
try:
item = Item.objects.get(pk=int(item_id))
except Item.DoesNotExist:
return JsonResponse({'message': 'The item does not exist'}, status=404)
if request.method == "PUT":
i = json.loads(request.body)
storage = StorageType.objects.get(pk=i['stored_in'])
item.stored_in = storage
item.save()
logger.error(storage)
valueOfLocation = storage.location.pk
logger.error(valueOfLocation)
return JsonResponse({'location': valueOfLocation}, status=200)
return HttpResponse(status=200)
def search_users(request):
numRequests = Household_request.objects.filter(to_user=request.user.pk)
pendingRequests = Household_request.objects.filter(
from_user=request.user.pk)
getToUsers = []
for x in pendingRequests:
getToUsers.append(x.to_user)
# logger.error(x.to_user)
logger.error(getToUsers)
if request.method == "POST":
form = SearchUsersForm(request.POST)
if form.is_valid():
user = form.cleaned_data['user']
logger.error(user)
try:
searching = User.objects.filter(username__icontains=user)
user = User.objects.get(id=request.user.pk)
user_household = user.household.all()
return render(request, "inventory/users.html", {
"form": SearchUsersForm(),
'users': searching,
"numRequests": numRequests,
"household": user_household,
"numRequests": numRequests,
"pendingRequests": getToUsers
})
except User.DoesNotExist:
return render(request, "inventory/users.html", {
"form": SearchUsersForm(),
'message': 'User does not exist',
"numRequests": numRequests
})
logger.error(searching)
return render(request, "inventory/users.html", {
"form": SearchUsersForm(),
"numRequests": numRequests
})
@login_required
def send_household_request(request, user_id):
from_user = request.user
to_user = User.objects.get(id=user_id)
household_request, created = Household_request.objects.get_or_create(from_user=from_user,
to_user=to_user)
if created:
return HttpResponse(status=200)
# return HttpResponse('household request send')
else:
return HttpResponseRedirect(reverse("users"))
@login_required
def accept_household_request(request, request_id):
household_request = Household_request.objects.get(id=request_id)
numRequests = Household_request.objects.filter(to_user=request.user.pk)
if household_request.to_user == request.user:
household_request.to_user.household.add(household_request.from_user)
household_request.from_user.household.add(household_request.to_user)
household_request.delete()
return render(request, "inventory/requests.html", {
"numRequests": numRequests
})
else:
return render(request, "inventory/requests.html", {
"numRequests": numRequests
})
@login_required
def reject_household_request(request, request_id):
household_request = Household_request.objects.get(id=request_id)
numRequests = Household_request.objects.filter(to_user=request.user.pk)
if household_request.to_user == request.user:
household_request.to_user.household.remove(household_request.from_user)
household_request.from_user.household.remove(household_request.to_user)
household_request.delete()
return render(request, "inventory/requests.html", {
"numRequests": numRequests
})
else:
return render(request, "inventory/requests.html", {
"numRequests": numRequests
})
@login_required
def remove_from_household(request, user_id):
user = User.objects.get(id=user_id)
current_user = User.objects.get(id=request.user.pk)
current_user.household.remove(user)
user.household.remove(current_user)
user_household = current_user.household.all()
return render(request, "inventory/household.html", {
"household": user_household
})
def requests(request):
numRequests = Household_request.objects.filter(to_user=request.user.pk)
return render(request, "inventory/requests.html", {
"numRequests": numRequests
})
def household(request):
user = User.objects.get(id=request.user.pk)
user_household = user.household.all()
return render(request, "inventory/household.html", {
"household": user_household
})
@login_required
def delete_item(request, item_id):
try:
item = Item.objects.get(pk=int(item_id))
except Item.DoesNotExist:
return JsonResponse({'message': 'The item does not exist.'}, status=404)
item.delete()
return HttpResponse(status=200)
<file_sep>/inventory/forms.py
from django import forms
from .models import User, Category, Location, Item, StorageType
class NewItemForm(forms.Form):
item_name = forms.CharField(label="Item Name", widget=forms.TextInput(
attrs={'class': 'form-control'}
))
description = forms.CharField(
label="Description", widget=forms.Textarea(attrs={'class': 'form-control'}), required=False)
category = forms.ModelChoiceField(queryset=Category.objects.all(
).order_by('category_name'), widget=forms.Select(attrs={'class': 'form-control'}))
img = forms.URLField(label="Image", widget=forms.TextInput(
attrs={'class': 'form-control'}), required=False)
stored_in = forms.ModelChoiceField(queryset=StorageType.objects.all(
), widget=forms.Select(attrs={'class': 'form-control'}))
class NewStorage(forms.Form):
storageType = forms.CharField(label="Storage Name", widget=forms.TextInput(
attrs={'class': 'form-control'}
))
location = forms.ModelChoiceField(queryset=Location.objects.all(
), widget=forms.Select(attrs={'class': 'form-control'}))
notes = forms.CharField(label="Notes", widget=forms.Textarea(
attrs={'class': 'form-control'}), required=False)
class NewStorageLocation(forms.Form):
location = forms.CharField(
label="Location Name", widget=forms.TextInput(attrs={'class': 'form-control'}))
class SearchUsersForm(forms.Form):
user = forms.CharField(label="Search Users", widget=forms.TextInput(
attrs={'class': 'form-control'}))
<file_sep>/inventory/urls.py
from django.urls import path
from . import views
urlpatterns = [
path("", views.index, name="index"),
path("login", views.login_view, name="login"),
path("logout", views.logout_view, name="logout"),
path("register", views.register, name="register"),
path("create_item", views.create_item, name="create_item"),
path("create_storage", views.create_storage, name="create_storage"),
path("create_location", views.create_location, name="create_location"),
path("user_inventory", views.user_inventory, name="user_inventory"),
path("requests", views.requests, name="requests"),
path("household", views.household, name="household"),
# API Routes
path("update_location/<int:item_id>",
views.update_location, name="update_location"),
path("search_users", views.search_users, name="search_users"),
path('send_household_request/<int:user_id>',
views.send_household_request, name="send_household_request"),
path('accept_household_request/<int:request_id>',
views.accept_household_request, name="accept_household_request"),
path('reject_household_request/<int:request_id>',
views.reject_household_request, name="reject_household_request"),
path('remove_from_household/<int:user_id>', views.remove_from_household,
name="remove_from_household"),
path('delete_item/<int:item_id>', views.delete_item, name="delete_item")
]
<file_sep>/README.md
# About the Project
I wanted to create a web app that provided a solution to disorganization and excess. I have accumulated a lifetime’s worth of possessions over the years and I wanted to create an app that would give me more order in my life. An advantage to knowing what you have is knowing what you do not need. So, I decided to create an inventory web app that keeps track of your household’s belongings. The ideal user for this app is someone who desires to keep track of the many possessions that they have acquired in their life.
This project is distinct from the past projects (CS50 Web) in that users can be joined together as a “household”. A django model stores the data for “household requests”. Once a user accepts a request, both users will be added to the household field in the User model. A user who has someone in their household will be able to view that user’s inventory, locations, and storage that the other user created.
This project is specifically distinct from the social network and commerce website because this web app’s core purpose is to showcase inventory among users of the same household rather than interacting between users. The app’s main purpose is to be able to view where items are located in locations within a household. The django models keep track of which users create “Locations” and “Storage Types” and these are shown to users of the same household to store items in.
# Built With
- Django
- Python
- Javascript
- Bootstrap
- HTML
# Getting Started
1. Access project directory from command line
2. Run django migrations to set up models:
⋅⋅⋅python manage.py makemigrations
⋅⋅⋅python manage.py migrate
3. Create a superuser
⋅⋅⋅python manage.py createsuperuser
4. Start local web server
⋅⋅⋅python manage.py runserver
5. Access at http://127.0.0.1:8000/
# Files
- Inventory folder - contains the inventory app for the final project (auto generated using ‘python manage.py startapp inventory’ command)
- Static files - contain inventory javascript file and inventory css file
- Templates - contain html files of the inventory app
- Admin.py - registers models with admin site
- Forms.py - contains forms for New Items, New Storage, New Storage Locations, and Searching users
- Urls.py - contains the url paths and api routes for app
- Views.py - contains inventory web responses
<file_sep>/inventory/templates/inventory/users.html
{% extends "inventory/layout.html" %}
{% block body %}
<div class="container">
<div class="row justify-content-md-center">
<div class="col-lg-7 text-center m-5">
<form method="POST" action="{% url 'search_users' %}">
{% csrf_token %}
{{form}}
</form>
</div>
</div>
<div class="row justify-content-md-center">
<div class="col-lg-7 text-center m-5">
<h3>Search Results:</h3>
<ul class="list-group list-group-flush">
{% for u in users%}
<li class="list-group-item user{{u.pk}}">{{u|title}}
{% if user != u %}
{% if u in household %}
<a class="ml-5">(Part Of Household)</a>
{% else %}
{% if u in pendingRequests %}
<button disabled class="ml-5 btn btn-outline-secondary">Request Sent</button>
{% else %}
<button onclick="sendHouseholdRequest(`{{u.pk}}`)" class="ml-5 btn btn-outline-primary">Add to Household</button>
{% endif %}
{% endif %}
{% else %}
(me)
{% endif %}
</li>
{% endfor %}
</ul>
</div>
</div>
</div>
{% endblock %}<file_sep>/inventory/admin.py
from django.contrib import admin
from .models import User, Category, Location, Item, StorageType, Household_request
# Register your models here.
admin.site.register(User)
admin.site.register(Category)
admin.site.register(Location)
admin.site.register(Item)
admin.site.register(StorageType)
admin.site.register(Household_request)
| b5ac184d796e9ed47050b1ab8b7cc059d1100d92 | [
"Markdown",
"Python",
"HTML"
]
| 7 | Python | jenniferpeterson/inventory | f33929f965fa5d8c022e17220e6a160bc57725af | bbe03a7f33e5ce4ea31eea1b19d9965b9ac8b04e |
refs/heads/master | <repo_name>gomson/pop-buffer<file_sep>/demo.js
var shell = require('gl-now')();
var bunny = require('bunny');
var normals = require('normals');
var createGeometry = require('gl-geometry');
var createShader = require('gl-shader');
var mat4 = require('gl-matrix').mat4;
var encode = require('./').encode;
var decode = require('./').decode;
var popBuffer = encode(bunny.cells, bunny.positions, 16);
var geom, shader, start, level = 0;
var vertexShader = ' \
attribute vec3 position; \
attribute vec3 normal ; \
uniform mat4 mv; \
uniform mat4 proj; \
varying vec3 v_normal; \
varying vec3 v_position; \
\
void main() { \
gl_Position = proj * mv * vec4(position, 1.0); \
v_normal = vec3(mv * vec4(normal, 0.0)); \
v_position = vec3(mv * vec4(position, 1.0)); \
} \
'
var fragmentShader = ' \
precision mediump float; \
uniform vec3 ambient; \
uniform vec3 diffuse; \
varying vec3 v_normal; \
varying vec3 v_position; \
\
void main() { \
vec3 N = normalize(v_normal); \
vec3 E = normalize(- v_position); \
float f = max(dot(N, E), 0.0); \
gl_FragColor = vec4(ambient + diffuse * f, 1.0); \
} \
';
shell.on('gl-init', function() {
shell.gl.enable(shell.gl.DEPTH_TEST);
shell.gl.enable(shell.gl.CULL_FACE)
bunny.normals = normals.vertexNormals(bunny.cells, bunny.positions);
geom = createGeometry(shell.gl);
shader = createShader(shell.gl, vertexShader, fragmentShader);
start = performance.now();
});
shell.on('gl-render', function() {
var t = performance.now() - start;
shader.bind();
var proj = mat4.create();
mat4.perspective(proj, Math.PI / 4, shell.width / shell.height, 0.1, 1000);
var mv = mat4.create();
mat4.lookAt(mv, [0, 0, 20], [0, 4, 0], [0, 1, 0]);
mat4.rotateX(mv, mv, Math.PI / 8);
mat4.rotateY(mv, mv, 2 * Math.PI * (t / 1000) / 10 * -1);
// cycle through levels every second / 2
var curLevel = parseInt(t / 1000 * 2) % 16 + 1;
if(curLevel !== level) {
level = curLevel;
console.log('rendering level', level);
// slice "level" levels from the pop buffer
var pb = {
bounds: popBuffer.bounds,
levels: popBuffer.levels.slice(0, level)
};
var mesh = decode(pb);
mesh.normals = normals.vertexNormals(mesh.cells, mesh.positions);
geom.dispose();
geom = createGeometry(shell.gl)
.attr('position', mesh.positions)
.attr('normal', mesh.normals)
.faces(mesh.cells);
}
geom.bind(shader);
shader.uniforms.proj = proj;
shader.uniforms.mv = mv;
shader.uniforms.ambient = [0.5, 0.5, 0.5];
shader.uniforms.diffuse = [0.5, 0.5, 0.5];
geom.draw();
});
<file_sep>/README.md
pop-buffer
==========
### Progressive encoding for 3D meshes
Implements POP Buffers, as described [here](http://x3dom.org/pop/files/popbuffer2013.pdf).
Install
-------
```bash
$ npm install pop-buffer
```
Example
-------
```javascript
var bunny = require('bunny');
var encode = require('pop-buffer').encode;
var decode = require('pop-buffer').decode;
var popBuffer = encode(bunny.cells, bunny.positions, 16);
var mesh = decode(popBuffer);
```
Demo
----
Check the [online demo](http://requirebin.com/?gist=538bb6f0da184e91c26a) or
```bash
$ git clone https://github.com/thibauts/pop-buffer.git
$ cd pop-buffer
$ npm install
$ npm run demo
```
| e07e9b5cb30c822da67987899d93d4b021f819fb | [
"JavaScript",
"Markdown"
]
| 2 | JavaScript | gomson/pop-buffer | 37674f6c14d9be571d3beaa66c3267d6e73aadd9 | 498b8b0026d84044232bec53eb5415b9286f2790 |
refs/heads/master | <file_sep><?php
namespace Akuma\Bundle\CoenFileBundle\Form\Type;
use Doctrine\Common\Persistence\ManagerRegistry;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\FileType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
class AttachmentType extends AbstractType
{
const NAME = 'coen_attachment';
/** @var ManagerRegistry */
protected $registry;
/** @var string */
protected $dataClass;
/**
* @inheritDoc
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('file', FileType::class);
}
/**
* @param ManagerRegistry $registry
*/
public function __construct(ManagerRegistry $registry)
{
$this->registry = $registry;
}
/**
* @param string $dataClass
*/
public function setDataClass($dataClass)
{
$this->dataClass = $dataClass;
}
/**
* {@inheritdoc}
*/
public function getName()
{
return $this->getBlockPrefix();
}
/**
* {@inheritdoc}
*/
public function getBlockPrefix()
{
return self::NAME;
}
/**
* @inheritDoc
*/
public function configureOptions(OptionsResolver $resolver)
{
parent::configureOptions($resolver);
$resolver->setDefaults([
'data_class' => $this->dataClass,
]);
}
}
<file_sep><?php
namespace Akuma\Bundle\CoenFileBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\HttpFoundation\File\File;
use Symfony\Component\HttpFoundation\File\UploadedFile;
/**
* @ORM\Table(name="files")
* @ORM\Entity()
* @ORM\HasLifecycleCallbacks()
*/
class Attachment
{
/**
* @var integer
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @var string
*
* @ORM\Column(name="filename", type="string", length=255, nullable=true)
*/
protected $filename;
/**
* @var string
*
* @ORM\Column(name="extension", type="string", length=10, nullable=true)
*/
protected $extension;
/**
* @var string
*
* @ORM\Column(name="mime_type", type="string", length=100, nullable=true)
*/
protected $mimeType;
/**
* @var string
*
* @ORM\Column(name="original_filename", type="string", length=255, nullable=true)
*/
protected $originalFilename;
/**
* @var \DateTime
*
* @ORM\Column(name="created_at", type="datetime")
*/
protected $createdAt;
/**
* @var \DateTime
*
* @ORM\Column(name="updated_at", type="datetime")
*/
protected $updatedAt;
/**
* @var File $file
*/
protected $file;
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* @return string
*/
public function getFilename()
{
return $this->filename;
}
/**
* @param string $filename
*
* @return $this
*/
public function setFilename($filename)
{
$this->filename = $filename;
return $this;
}
/**
* @return string
*/
public function getExtension()
{
return $this->extension;
}
/**
* @param string $extension
*
* @return $this
*/
public function setExtension($extension)
{
$this->extension = $extension;
return $this;
}
/**
* @return string
*/
public function getMimeType()
{
return $this->mimeType;
}
/**
* @param string $mimeType
*
* @return $this
*/
public function setMimeType($mimeType)
{
$this->mimeType = $mimeType;
return $this;
}
/**
* @return string
*/
public function getOriginalFilename()
{
return $this->originalFilename;
}
/**
* @param string $originalFilename
*
* @return $this
*/
public function setOriginalFilename($originalFilename)
{
$this->originalFilename = $originalFilename;
return $this;
}
/**
* @return \DateTime
*/
public function getCreatedAt()
{
return $this->createdAt;
}
/**
* @param \DateTime $createdAt
*
* @return $this
*/
public function setCreatedAt($createdAt)
{
$this->createdAt = $createdAt;
return $this;
}
/**
* @return \DateTime
*/
public function getUpdatedAt()
{
return $this->updatedAt;
}
/**
* @param \DateTime $updatedAt
*
* @return $this
*/
public function setUpdatedAt($updatedAt)
{
$this->updatedAt = $updatedAt;
return $this;
}
/**
* @return File
*/
public function getFile()
{
return $this->file;
}
/**
* @param File|UploadedFile $file
*
* @return $this
*/
public function setFile(File $file)
{
$this->file = $file;
if ($file instanceof UploadedFile) {
$this
->setExtension($file->guessClientExtension())
->setMimeType($file->getClientMimeType())
->setOriginalFilename($file->getClientOriginalName());
} else {
$this
->setExtension($file->guessExtension())
->setMimeType($file->getMimeType())
->setOriginalFilename($file->getFilename());
}
return $this;
}
/**
* Pre persist event handler
*
* @ORM\PrePersist
*/
public function prePersist()
{
$this->createdAt = new \DateTime('now', new \DateTimeZone('UTC'));
$this->updatedAt = clone $this->createdAt;
}
/**
* Pre update event handler
*
* @ORM\PreUpdate
*/
public function preUpdate()
{
$this->updatedAt = new \DateTime('now', new \DateTimeZone('UTC'));
}
}
<file_sep><?php
namespace Akuma\Bundle\CoenFileBundle\Manager;
use Symfony\Component\HttpFoundation\File\File;
class AttachmentManager
{
/** @var string */
protected $targetDir;
/** @var int */
protected $allowedCount = 3;
/**
* Returns moved file name
*
* @param File $file
*
* @return string
*/
public function upload(File $file)
{
$fileName = uniqid('file_', true);
$file->move($this->getTargetDir(), $fileName);
return $fileName;
}
/**
* @return int
*/
public function getAllowedCount()
{
return $this->allowedCount ?: 3;
}
/**
* @param int $allowedCount
*
* @return $this
*/
public function setAllowedCount($allowedCount)
{
$this->allowedCount = $allowedCount ?: 3;
return $this;
}
/**
* @return string
*/
public function getTargetDir()
{
return $this->targetDir;
}
/**
* @param string $targetDir
*
* @return $this
*/
public function setTargetDir($targetDir)
{
if (!is_dir($targetDir)) {
mkdir($targetDir);
}
if (!is_writable($targetDir)) {
throw new \Exception(sprintf('Target dir "%s" should be writable', $targetDir));
}
$this->targetDir = $targetDir;
return $this;
}
}
<file_sep><?php
namespace Akuma\Bundle\CoenFileBundle\Model;
use Akuma\Bundle\CoenFileBundle\Entity\Attachment;
class MultipleAttachment
{
protected $files = [];
/**
* @return array
*/
public function getFiles()
{
return $this->files;
}
/**
* @param array $files
*
* @return $this
*/
public function setFiles(array $files = [])
{
$this->files = $files;
return $this;
}
/**
* @return \Generator
*/
public function getAttachments()
{
foreach ($this->files as $file) {
yield (new Attachment())->setFile($file);
}
}
}
<file_sep><?php
namespace Akuma\Bundle\CoenFileBundle\DependencyInjection;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
/**
* This is the class that validates and merges configuration from your app/config files.
*
* To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/configuration.html}
*/
class Configuration implements ConfigurationInterface
{
const CONFIG_NODE = 'akuma_coen_file';
const TARGET_DIR_NODE = 'target_dir';
const MAX_UPLOADS_NODE = 'max_uploads';
/**
* {@inheritdoc}
*/
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder();
$treeBuilder->root(self::CONFIG_NODE)
->children()
->scalarNode(self::TARGET_DIR_NODE)
->defaultValue(sys_get_temp_dir())
->beforeNormalization()
->always()
->then(function($v) {
return is_dir($v)&&is_writable($v) ? $v: sys_get_temp_dir();
})
->end()
->end()
->integerNode(self::MAX_UPLOADS_NODE)
->defaultValue(3)
->beforeNormalization()
->always()
->then(function($v) {
return (int)$v ?: 3;
})
->end()
->end()
->end();
return $treeBuilder;
}
}
<file_sep><?php
namespace Akuma\Bundle\CoenFileBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\CollectionType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
class AttachmentCollectionType extends AbstractType
{
const NAME = 'coen_attachment_collection';
/** @var string */
protected $dataClass;
/**
* @inheritDoc
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('files', CollectionType::class, [
'entry_type' => AttachmentType::class,
'allow_add' => true,
'prototype' => true,
'attr' => [
'class' => "files-collection",
],
]);
}
/**
* {@inheritdoc}
*/
public function getName()
{
return $this->getBlockPrefix();
}
/**
* {@inheritdoc}
*/
public function getBlockPrefix()
{
return self::NAME;
}
/**
* @inheritDoc
*/
public function configureOptions(OptionsResolver $resolver)
{
parent::configureOptions($resolver);
}
}
<file_sep><?php
namespace Akuma\Bundle\CoenFileBundle\Listener;
use Akuma\Bundle\CoenFileBundle\Entity\Attachment;
use Akuma\Bundle\CoenFileBundle\Manager\AttachmentManager;
use Doctrine\ORM\Event\LifecycleEventArgs;
use Doctrine\ORM\Event\PreUpdateEventArgs;
use Symfony\Component\HttpFoundation\File\UploadedFile;
class AttachmentListener
{
/** @var AttachmentManager */
protected $attachmentManager;
/**
* @param AttachmentManager $attachmentManager
*/
public function __construct(AttachmentManager $attachmentManager)
{
$this->attachmentManager = $attachmentManager;
}
public function prePersist(LifecycleEventArgs $args)
{
/** @var Attachment $entity */
$entity = $args->getEntity();
$this->uploadFile($entity);
}
public function preUpdate(PreUpdateEventArgs $args)
{
/** @var Attachment $entity */
$entity = $args->getEntity();
$this->uploadFile($entity);
}
/**
* @param Attachment $entity
*/
private function uploadFile($entity)
{
// upload only works for Product entities
if (!$entity instanceof Attachment) {
return;
}
$file = $entity->getFile();
// only upload new files
if ($file instanceof UploadedFile) {
$fileName = $this->attachmentManager->upload($file);
$entity->setFilename($fileName);
}
}
}
<file_sep>AkumaCoenFileBundle
=================
Installation
------------
First you need to add `akuma/coen-uploader-bundle ` to `composer.json`:
```sh
composer require akuma/coen-uploader-bundle
```
You also have to add `AkumaCoenFileBundle` to your `AppKernel.php`:
```php
// app/AppKernel.php
//...
class AppKernel extends Kernel
{
//...
public function registerBundles()
{
$bundles = array(
...
new Akuma\Bundle\CoenFileBundle\AkumaCoenFileBundle()
);
//...
return $bundles;
}
//...
}
```
Configuration
-------------
You also may customize some config options:
```yml
akuma_coen_file:
target_dir: ~ #default sys_get_tmp_dir
max_uploads: ~ #default 3
```
Changelog
---------
### Version 1.0.0
- First release
License
-------
- The bundle is licensed under the [WTFPL License](http://www.wtfpl.net/)
<file_sep><?php
namespace Akuma\Bundle\CoenFileBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\FileType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
class AttachmentMultipleType extends AbstractType
{
const NAME = 'coen_attachment_multiple';
/** @var string */
protected $dataClass;
/**
* @inheritDoc
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
parent::buildForm($builder, $options);
$builder->add('files', FileType::class, ['multiple' => true]);
}
/**
* @param string $dataClass
*/
public function setDataClass($dataClass)
{
$this->dataClass = $dataClass;
}
/**
* @return string
*/
public function getDataClass()
{
return $this->dataClass;
}
/**
* {@inheritdoc}
*/
public function getName()
{
return $this->getBlockPrefix();
}
/**
* {@inheritdoc}
*/
public function getBlockPrefix()
{
return self::NAME;
}
/**
* @inheritDoc
*/
public function configureOptions(OptionsResolver $resolver)
{
parent::configureOptions($resolver);
$resolver->setDefaults([
'data_class' => $this->dataClass,
]);
}
}
<file_sep><?php
namespace Akuma\Bundle\CoenFileBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;
class AkumaCoenFileBundle extends Bundle
{
}
| 2fb6bcc8f625b6c89d3c7702d270d9017401579c | [
"Markdown",
"PHP"
]
| 10 | PHP | inri13666/coen-uploader-bundle | c8d9814ef3c6e0242c559001fd249b0fdae318f4 | 732803023e17bedf1fd2518234bd8b0893a39cb6 |
refs/heads/master | <repo_name>ASAMOTO/the-template<file_sep>/app/controllers/searches_controller.rb
class SearchesController < ApplicationController
def index
@search = Search.new
end
def create
@who = params[:search][:who]
#redirect_to root_path
render 'edit'
end
end
| 266289681c9d86d4395710db76755d2d6d6a68ae | [
"Ruby"
]
| 1 | Ruby | ASAMOTO/the-template | 9409cd205c45c2bc880a1789a94c11c197228cce | 432b8a2c82fa61534dc6ce0c11f041ef88d623a2 |
refs/heads/master | <repo_name>Nikitha-Anjan/Blog-UI<file_sep>/App.js
import React from 'react';
import {BrowserRouter as Router,Route,Link} from 'react-router-dom'
// connect allows us to dispatch or read values from store into component
import { connect } from 'react-redux'
import UsersList from './components/UsersList'
import UserShow from './components/UserShow'
import PostsList from './components/PostsList'
import PostShow from './components/PostShow'
function App(props) {
return (
<Router>
<div>
<h1>Redux Examples - Exercises</h1>
<Link to="/users">Users</Link>
<Link to="/posts">Posts</Link>
<Route path="/users" component ={UsersList} exact={true}/>
<Route path="/users/:id" component={UserShow} />
<Route path="/posts" component ={PostsList} exact={true}/>
<Route path="/posts/:id" component={PostShow} />
</div>
</Router>
)
}
const mapStateToProps = (state) => {
return {
count: state.count
}
}
export default connect(mapStateToProps)(App)
//export default App<file_sep>/selectors/postSelector.js
export const findPost =(posts,id) => {
return posts.find(post => post.id == id)
}<file_sep>/actions/postsAction.js
import axios from 'axios'
//set to store
export const setPosts = (posts) => {
return {type: 'SET_POSTS',payload: posts }
}
//get from api ( if name starts with 'start' it means its a thunk (network)call)
export const startGetPosts = () => {
return function(dispatch,getState){
axios.get('http://jsonplaceholder.typicode.com/posts')
.then((response) =>{
const posts = response.data
dispatch(setPosts(posts))
})
}
}
<file_sep>/selectors/postUserSelector.js
export const filterPostUser =(posts,id) => {
return posts.filter(post => post.userId == id)
}<file_sep>/actions/usersAction.js
import axios from 'axios'
//set to store
export const setUsers = (users) => {
return {type: 'SET_USERS',payload: users }
}
//get from api ( if name starts with 'start' it means its a thunk (network)call)
export const startGetUsers = () => {
return function(dispatch,getState){
axios.get('https://jsonplaceholder.typicode.com/users')
.then((response) =>{
const users = response.data
dispatch(setUsers(users))
})
}
}
<file_sep>/components/UserShow.js
import React from 'react'
import { connect, connectAdvanced } from 'react-redux'
import { findUser } from '../selectors/userSelector'
import { filterPostUser } from '../selectors/postUserSelector'
import { Link } from 'react-router-dom'
import{ makeAdmin,removeAdmin} from '../actions/adminAction'
class UserShow extends React.Component {
render(){
return (
<div>
{this.props.user && (
<div>
<h2>User Show - {this.props.user.id}
{this.props.admin === this.props.user.id ? " Admin": " NotAdmin"}
{(this.props.admin != this.props.user.id) &&
(<button onClick={()=>{this.props.dispatch(makeAdmin(this.props.user.id))}}>Make Admin </button>)}
{(this.props.admin === this.props.user.id) &&
(<button onClick={()=>{this.props.dispatch(removeAdmin())}}>Remove Admin </button>)}
</h2>
<p>UserName: { this.props.user.username } </p>
<p>Name: { this.props.user.name } </p>
<p>Email Id: { this.props.user.email } </p>
<h2>Posts by the {this.props.user.username}</h2>
<ul>
{this.props.posts.map((ele)=>{
return(
<li key={ele.id}> <Link to={`/posts/${ele.id}`}>{ele.title} </Link></li>
)
})}
</ul>
</div>
)}
</div>
)
}
}
const mapStateToProps =(state, props) => {
const user= findUser(state.users,props.match.params.id)
return {
user,
posts : filterPostUser(state.posts,user.id),
admin: state.admin
}
}
export default connect(mapStateToProps)(UserShow)<file_sep>/components/PostShow.js
import React from 'react'
import { connect } from 'react-redux'
import { findPost } from '../selectors/postSelector'
import { findUser } from '../selectors/userSelector'
import { Link } from 'react-router-dom'
class PostShow extends React.Component {
render(){
return (
<div>
{this.props.post && (
<div>
<h2>Post Show: {this.props.post.id}</h2>
<h2>Post Title:{ this.props.post.title } </h2>
<h3>Post Username: {this.props.user.username }</h3>
<h3>Post Body:</h3>
<p>{ this.props.post.body } </p>
<p><Link to ={`/users/${this.props.user.id}`}>More Posts of Author: {this.props.user.name}</Link></p>
</div>
)}
</div>
)
}
}
const mapStateToProps =(state, props) => {
const post = findPost(state.posts,props.match.params.id)
if (post) {
return {
post,
user: findUser(state.users,post.userId)
}
}
}
export default connect(mapStateToProps)(PostShow) | ad9814182c8ca3938e5447c97ce6a906071d0ea0 | [
"JavaScript"
]
| 7 | JavaScript | Nikitha-Anjan/Blog-UI | 6a4ba8b6b346a99a9509741c8f60e48156d4c8e1 | fe45a05cfe237c812aa28c53c869d86d1667cfa2 |
refs/heads/master | <file_sep>//Author:
#include<iostream>
int main()
{
int wholenumber1;
int wholenumber2;
std::cout<<"Please enter a whole number:\n";
std::cin>>wholenumber1;
std::cout<<"Please enter another whole number:\n";
std::cin>>wholenumber2;
int biggest;
if(wholenumber1 < wholenumber2)
{
biggest = wholenumber2;
}
else
{
biggest = wholenumber1;
}
std::cout<<"Of those two numbers, the biggest is: ";
std::cout<<biggest;
std::cout<<std::endl<<"Thank you for playing.\n";
return 0;
}
| a8de011f24ebdd87b3461bf7f33264fdcd10eb83 | [
"C++"
]
| 1 | C++ | lokeshkumaraguru/BiggestNumber | 6452b94e8a61ab6dd4ea892d033c73b9abac4b0d | 487fedc7b9c4c829edf57517e78240f4151d7037 |
refs/heads/master | <file_sep>var React = require('react')
import Svg_up from './svg_upload.jsx';
export class FacebookLink extends React.Component{
constructor(props){
super(props);
}
render(props) {
return (
<a href={this.props.src} className='facebook-link'>
<Svg_up svg="fblink" className="social-link fb-link"/>
</a>
)
}
}
export class TwitterLink extends React.Component{
constructor(props){
super(props);
}
render(props) {
return (
<a href={this.props.src} className='twitter-link'>
<Svg_up svg="twitterlink" className="social-link twitter-link"/>
</a>
)
}
}
// module.exports = Copyright<file_sep>var React = require('react/addons')
var Svg_up = require('../reusable-modules/svg_upload.jsx')
export class Leadership extends React.Component{
constructor() {
super()
document.title = "IndiaStories | Leadership"
}
render() {
return (
<section className="leadership">
<div className="leadership-splash-wrapper">
<div className="leadership-image"></div>
<h1> LEADERSHIP STYLE </h1>
<h2> Shared Vision. Self Directed Teams.</h2>
<hr/>
</div>
<article className="team-members">
<div className="member-1 member">
<h2> <NAME></h2>
<p>An industry veteran having spent over <em>28 years</em> in the industry in
over 35 films. These films have grossed over <em>2000</em> crs of revenues.
His experience spans the entire life cycle of film production
management, starting from validation of scripting, budgeting,
production, marketing and distribution of films. Has managed shoots in
various locations of India, and overseas.<br></br><br></br>In his association with <em>Boney Kapoor</em> he executed films of such scale
as <em>Roop Ki Rani Choron Ka Raja, Pukar, Prem and Sirf Tum.</em> He also set
up the initial production for <em>Rang De Basanti</em>.<br></br><br></br>Was until recently the Head of Production of <em>Fox Star Studios</em>,
specifically hired by Fox to lead their foray into Bollywood. He was
responsible for films including <em>My Name is Khan, <NAME>, Force, Dum
<NAME>, <NAME>, Raaz 3D and Murder 3.</em><br></br><br></br>He brings the right balance of creativity and business acumen which
is key for a business like the film business.
Above all, he enjoys <em>great goodwill</em> in the industry. This depth of
relationship gives him unparalleled access to all key talent in the
industry – be it top stars, directors, music directors and technical
crew.</p>
</div>
<div className="member-2 member">
<h2><NAME></h2>
<p>A start up specialist with experience of more than <em>20 years</em> in media industry spanning Satellite Television, Satellite Radio, Music Record Label and Motion Pictures.
Past assignments included Dy.CFO of <em>Star TV</em>, Managing Director and CFO <em>Asia Pacific World Space</em>, Group CFO Data Access, Managing Director Phat Phish India Pvt Limited and Producer at <em>Lightforms and Pictures</em> Pvt Ltd <br></br><br></br>
Produced <em>Quick Gun Murugun</em> (presented by Fox Star Studios) and
Frozen (which premiered in the Toronto film festival 2007) as Managing
Director <em>Phat Phish India</em> Private Limited and <em>What the Fish </em>
presented by Viacom18 Studios.<br></br><br></br>Harish has a professional background of being a Chartered Accountant
and Cost Accountant.
</p>
</div>
</article>
</section>
)
}
};
module.exports = Leadership
<file_sep># India-Stories
<file_sep>var React = require('react')
export class SplashBG extends React.Component{
render(props) {
var srcLink = "url("+this.props.src+")";
return (
<div className="splash-bg" style={{backgroundImage: srcLink}}>
</div>
)
}
}
module.exports = SplashBG<file_sep>
var React = require('react/addons')
import Svg_up from '../../reusable-modules/svg_upload.jsx';
import Copyright from '../../reusable-modules/copyright.jsx';
import {FacebookLink, TwitterLink} from '../../reusable-modules/social.jsx';
export class Footer extends React.Component{
render() {
return (
<footer id={this.props.id}>
<div className="back-to-top-icon">
</div>
<section className="social-icons">
<FacebookLink src="https://www.facebook.com/profile.php?id=100010226854696"/>
<TwitterLink src="https://twitter.com/India_stories"/>
</section>
<section className="contact-info-box">
<h3> INDIA STORIES MEDIA & ENTERTAINMENT PVT. LTD. </h3>
<h4>
<span> 706, Aston, Sundervan Complex </span>
<span> Lokhandwala Road, Andheri (W) </span>
<span> Mumbai - 400053 </span>
<span> India </span>
<span> +91 22 6166 8969 </span>
</h4>
<h3> Contact us:</h3>
<h5>
<EMAIL>
</h5>
</section>
<Copyright name="INDIA STORIES MEDIA & ENTERTAINMENT PVT. LTD."/>
</footer>
)
}
componentDidMount() {
$('.back-to-top-icon').on('click', function(){
this.backToTop()
}.bind(this))
}
backToTop() {
TweenMax.to(window, 1, {scrollTo:{y:0}, ease:Power2.easeOut});
}
}
module.exports = Footer
<file_sep>import React from 'react/addons';
var Link = require('react-router').Link
export class Menu extends React.Component {
render() {
return (
<div className="menu-wrapper">
<ul className="menu">
<Link to="home"><li className="menu-item selected home">INDIA STORIES</li></Link>
<Link to="leadership"><li className="menu-item leadership">Leadership</li></Link>
<Link to="projects"><li className="menu-item projects">Projects</li></Link>
</ul>
</div>
);
}
}
module.exports = Menu
<file_sep>module.exports = function(app) {
var mainController = require('../lib/controllers/main')
app.get('/', mainController.index);
app.post('/contact-submit' , mainController.contactSubmit);
app.get('/:page', mainController.index);
}<file_sep>var React = require('react/addons')
var Svg_up = require('../reusable-modules/svg_upload.jsx')
class Home extends React.Component{
constructor() {
super()
document.title = "IndiaStories"
}
render() {
return (
<div>
<section className="splash-wrapper">
<div className="splash-bg"></div>
</section>
<section className="about-us">
<h2> OUR STORY </h2>
<hr/>
<p>
India Stories Media & Entertainment Pvt. Ltd, is an integrated entertainment and communication company looking to encompass the <em>entire span of content</em> creation across Motion Pictures, Big Ticket Television content, Boutique Advertising Commercials , Public Service films and short form New Media Content.
It prides itself to be arguably the first true media house focused on Stories rooted and originating from India, for the rest of the world. Additionally, as its internal mandate, India Stories will only make content that the <em>entire</em> family can watch together.
</p>
<p>
India Stories also prides itself in launching <em>new talent</em> across acting, music and direction . This comes from a solid understanding of content and appreciating the entire spectrum from creative to production and from distribution to targeted marketing.
India Stories sees itself as an industry leader in operating in a strong corporate governance framework with best practices and <em>financial transparency</em> across the board.
</p>
<p>
India Stories is in the process of setting up the India Stories Foundation to lead and support initiatives that go above and <em>beyond profit motive</em> and use the resources of the organization, monetary and non-monetary initiatives across art, education and senior citizen care. India Stories believes that art has a great role in ensuring a <em>culturally rich and sensitive society</em>.
</p>
</section>
<section className="our-philosophy">
<h2> OUR PHILOSOPHY</h2>
<hr/>
<article className="mini-section">
<Svg_up svg="Brain" className="svg-icon"/>
<div className="text-wrapper" >
<h3>Systemic Thinking</h3>
<p>All learnings will be institutionalized.
Orientation towards long term value v/s short term profit.
Continuous Disruptive innovation.</p>
</div>
</article>
<article className="mini-section">
<Svg_up svg="Compass" className="svg-icon"/>
<div className="text-wrapper">
<h3>Core Values</h3>
<p>Entertainment using the power of imagination.
Undistorted transmission of culture and objective truths.
No compromise on ethics and morality.
Prudent transparency at all levels.</p>
</div>
</article>
<article className="mini-section">
<Svg_up svg="Personal-Mastery" className="svg-icon"/>
<div className="text-wrapper">
<h3>Personal Mastery</h3>
<p>Core Competence.
Openness and adaptability.</p>
</div>
</article>
<article className="mini-section">
<Svg_up svg="Leadership" className="svg-icon"/>
<div className="text-wrapper">
<h3>Leadership</h3>
<p>Shared Vision.
Self Directed Teams.
Leaders as merely custodians of creative tension.</p>
</div>
</article>
</section>
<section className="bg-image-grid">
<article className="vision">
<h2>VISION</h2>
<p>To be the leading producer of entertainment content from India for domestic and global audiences.</p>
</article>
<article className="mission">
<h2>MISSION</h2>
<p> To tell great stories and thereby humanise life.</p>
</article>
</section>
<section className="wide proposition">
<h2>VALUE PROPOSITION</h2>
<p>High credibility and access in the Industry.</p>
<br/>
<p>Perfect match between creative vision and business wisdom.</p>
<br/>
<p>Optimally designed product portfolio to balance risk and return.</p>
</section>
</div>
)
}
};
module.exports = Home
<file_sep>var React = require('react/addons')
var Svg_up = require('../reusable-modules/svg_upload.jsx')
import {Splash} from '../reusable-modules/splash.jsx'
export class Projects extends React.Component{
constructor() {
super()
document.title = "IndiaStories | Projects"
}
render() {
return (
<section className="page projects">
<h1> PROJECTS </h1>
<Splash src="/img/hindi.jpg">
<em>HINDI FILMS</em> UNDER DEVELOPMENT
<span className="sub-text">Projects underway with the following directors</span>
</Splash>
<section className="hindi info-section">
<ul className="film-list hindi-list">
<li className="film-item">
<span className="film-language">HINDI</span>
<h3><NAME></h3>
<p>
Shashanka has been associated with the media world for over 18 years. He was one of the key players to define and add character to the emerging face of the entertainment TV in India, having launched MTV India and then Channel [V], where he worked as Creative Director and then as Dy. General Manager. He has won many international awards for his distinctive work.
<br/>
<br/>
Shashanka became famous with his cult films like 'Waisa Bhi Hota Hai' and 'Quick Gun Murugun'. His last release 'Khoobsurat' starring Sonam Kapoor and Fawad Khan was a mainstream commercial success.
</p>
</li>
<li className="film-item">
<span className="film-language">HINDI</span>
<h3><NAME></h3>
<p>
An alumnus in Direction & Screenplay Writing from the Satyajit Ray Film and Television Institute. Sagar made 'Bheja Fry' which went on to be a cult success as well as a commercial blockbuster.
</p>
</li>
<li className="film-item">
<span className="film-language">HINDI</span>
<h3>Padmakumar</h3>
<p>
Former National Creative Director – Rediffussion. Prior to that he has also worked with McCann Worldgroup Sri Lanka as Executive Creative Director, South East Asia, and ventured into scripting and directing commercials for brands in Singapore and Sri Lanka.
</p>
</li>
<li className="film-item">
<span className="film-language">HINDI</span>
<h3><NAME></h3>
<p>
The Director duo Glen - Ankush began their film careers assisting Mansoor khan and went on to direct films on their own. They also have under their belts over ten thousand hours of Television content including the mega series ‘Everest’ for Star Plus.
</p>
</li>
<li className="film-item">
<span className="film-language">HINDI</span>
<h3><NAME></h3>
<p>
Associate to <NAME> in 'Khosla ka Ghosla'.
Over 2500 hrs of TV, Television commercials and Corporate films.
</p>
</li>
<li className="film-item">
<span className="film-language">HINDI</span>
<h3><NAME></h3>
<p>
Chinmay began his film career assisting the acclaimed Director <NAME>. He comes with a very strong theatre background and has directed many successful shows for leading Television networks across the country.
</p>
</li>
</ul>
</section>
<Splash src="/img/regional.jpg">
<em>REGIONAL FILMS</em> UNDER DEVELOPMENT
</Splash>
<section className="regional info-section">
<ul className="film-list hindi-list">
<li className="film-item">
<span className="film-language">BENGALI</span>
<h3><NAME> and <NAME></h3>
<p>
They are amongst the few director duos in the history of Bengali cinema to have achieved success both critically and commercially.
<br/>
<br/>
They have directed films like 'Icche', 'Muktodhara', 'Accident', '<NAME>' and 'Ramdhanu' . Their latest release 'Bela Seshe'(2015) about the institution of marriage is already a runaway success commercially.
</p>
</li>
<li className="film-item">
<span className="film-language">BENGALI</span>
<h3><NAME></h3>
<p>
Director of Bengali films like '<NAME>', '<NAME>' and '<NAME>'.
<br/>
<br/>
Recipient of many awards including three National Awards and a Filmfare award for Best Art Director / Production Designer for feature films.
</p>
</li>
<li className="film-item">
<span className="film-language">BENGALI</span>
<h3>Udayan Namboodiry</h3>
<p>
In a career spanning 28 years with major national and international media
houses, Udayan Namboodiry is also the author of ‘Bengal’s night without
end’. He is also the director of the acclaimed documentary ‘The Girl who lost her name’.
</p>
</li>
<li className="film-item">
<span className="film-language">MARATHI</span>
<h3><NAME></h3>
<p>
Jatin is from the new crop of Directors who are making waves in the Marathi film industry with their fresh subjects and treatment. Jatin’s films include 'Chakwa', and 'Ek Marathi Manoos'. He has won numerous awards and nominations including 2 state awards. His next Marathi film ‘Bandh Nylon Che’ with Mahesh Manjrekar is slated for release by December 2015.
</p>
</li>
<li className="film-item">
<span className="film-language">ASSAMESE</span>
<h3><NAME></h3>
<p>
Bidyut’s debut Asamese film 'Bhraimoman Theatre' won him the Special Jury Award in the 53rd National Awards.His next feature ‘Ekhon
Nedekha N<NAME>are’ won many international
awards including the Audience Choice Award at the North Carolina
International South Asian Film Festival (NCISAFF).
</p>
</li>
</ul>
</section>
<Splash src="/img/bigbudget.jpg">
<em>BIG TICKET TELEVISION</em>
</Splash>
<section className="tv info-section">
<article>
<p>
Two large projects are currently under development by the Company for global distribution.
</p>
<p>
One is in the genre of techno-mythology and fantasy and the other is a historical-spiritual odyssey based in the Buddhist times.
</p>
<p>
The Company is currently in the process of securing additional developmental funding from a group of international and domestic investors.
</p>
</article>
</section>
<Splash src="/img/tv.jpg">
<em>FILMS FOR TV</em>
</Splash>
<section className="tv-films info-section">
<article>
<p>
The Company has also finalized its plan for rolling out a series of films specifically for television audiences.
</p>
<p>
These films will be mentored by reputed and respected directors from Hindi Film Industry as well as from Regional cinema.
</p>
<p>
In addition to featuring known as well as fresh talent, these films will carry exceptional production values, and scale that are usually absent from films traditionally made for television and thereby raising the bar of films for TV.
</p>
</article>
</section>
<Splash src="/img/filmads.jpg">
<em>ADVERTISING FILMS</em>
</Splash>
<section className="advertising-films info-section">
<article>
<p>
A roster of Directors that span the entire range of specialization – from full length feature films to short duration commercials (and all in between!)
</p>
<p>
A very strong production infrastructure and skill sets that carry very high standards of execution skills and delivery timelines.
</p>
<p>
Over 200 years of combined experience across features, promos, ads etc.
</p>
</article>
</section>
<Splash src="/img/newmedia.jpg">
<em>NEW MEDIA</em>
</Splash>
<section className="new-media info-section">
<article>
<p>
With the expected roll out of 4G, increased broadband penetration, and personalized media consumption, short video on demand will take a huge leap in the coming years.
</p>
<p>
The New Media Content would be largely created for consumption on cell phones. These would be short format content and would initially focus on Comedy but with the strategy of creating “personalities” who would build a community of fan-base around them. This would then progress to drama, romance and reality genres as the audiences expand.
</p>
</article>
</section>
<Splash src="/img/psfilms.jpg">
<em>PUBLIC SERVICE FILMS</em>
</Splash>
<section className="public-service-films info-section">
<article>
<p>
Films are an extremely significant means to raise crucial social concerns and to stimulate dialogue, and an involved and passionate public discourse around them.
</p>
<p>
As part of our advocacy initiatives, these would be films made with no profit motive to empower filmmakers and provide them opportunities to articulate their ideas and visions on issues like human rights, gender and sexuality, environment, conflict, diversity, and cultural pluralism and identity, among others.
</p>
</article>
</section>
</section>
)
}
};
module.exports = Projects
<file_sep>$(document).ready(function(){
WebFontOptions = {
typekit: { id: 'yrp3zbi' },
timeout: 4000
}
WebFont.load(WebFontOptions)
})<file_sep>var React = require('react')
export class Copyright extends React.Component{
constructor(props){
super(props);
}
render(props) {
const time = new Date().getFullYear();
return (
<span className='copyright'>
© {time} <span className="bold">{this.props.name}</span> All Rights Reserved
</span>
)
}
}
module.exports = Copyright<file_sep>
var React = require('react/addons'),
Home = require('./pages/home.jsx'),
Leadership = require('./pages/leadership.jsx'),
Projects = require('./pages/projects.jsx'),
Footer = require('./components/global/footer.jsx'),
Menu = require('./components/global/menu.jsx'),
TransitionGroup = React.addons.CSSTransitionGroup;
import {
Router,
Route,
Link,
RouteHandler,
NotFoundRoute,
DefaultRoute,
Redirect,
HistoryLocation,
run
} from 'react-router';
export class App extends React.Component {
static contextTypes = {
router: React.PropTypes.func.isRequired
}
render(props) {
var name = this.context.router.getCurrentPath().split('/')[1];
return (
<div id="react-wrapper">
<Menu id="menu"/>
<TransitionGroup transitionName="page-transition" className="page-transition-wrapper" component="div">
<RouteHandler key={name}/>
</TransitionGroup>
<Footer id="footer"/>
</div>
);
}
}
var routes = (
<Route name="index" handler={App} path="/" ignoreScrollBehavior>
<DefaultRoute name="home" handler={Home}/>
<Route name="leadership" path="leadership" handler={Leadership}/>
<Route name="projects" path="projects" handler={Projects}/>
</Route>
)
run(routes, HistoryLocation, function(Root) {
React.render(<Root/>, document.getElementById('react-app'));
}); | df31b5cd3a401ea4bb27175a6cfcfaf0a8cfb62e | [
"JavaScript",
"Markdown"
]
| 12 | JavaScript | sim13/India-Stories | 6de1a1209ff5ec166cf6f73547b85fd9a44bb9c0 | 9ee61563662baf7e0679e607c9e5137c1c07832e |
refs/heads/master | <file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package cplx;
public interface ConnectorListener {
public void onConnected(Connector invoker);
public void onReceivedPacket(Connector invoker, Packet packet);
public void onClosed(Connector invoker);
}
| 4b0e97523cff5c7cfa8c0154adc125bc2eaf74d4 | [
"Java"
]
| 1 | Java | mcpexil/CplxConnector | b48530cd595518ffdfc705871956b52b2866e88f | 9db55183fdef687a889eefbe2ba8c4e87a0993a9 |
refs/heads/main | <repo_name>vcbartolome/user-auth-mern-passport-jwt<file_sep>/frontend/src/App.js
// import logo from './logo.svg';
import './App.css';
import { useState } from 'react';
import axios from 'axios';
import { Paper, Grid, TextField, Button } from '@material-ui/core';
import { makeStyles } from '@material-ui/core/styles';
import { Face, Fingerprint } from '@material-ui/icons';
const useStyles = makeStyles((theme) => ({
diiv: {
margin: theme.spacing.unit * 2,
},
paper: {
padding: theme.spacing.unit,
width: '620px',
margin: 'auto',
marginTop: '50px',
backgroundColor: '#e3f5f6',
},
}));
function App() {
const classes = useStyles();
const [signUp, setSignUp] = useState(false);
const [authForm, setAuthForm] = useState({
name: '',
email: '',
password: '',
});
const [dashboard, setDashboard] = useState('');
const handleSubmit = async () => {
if (signUp) {
// register
const { name, email, password } = authForm;
if (!name || !email || !password) {
alert('Please enter all required fields');
return false;
}
const config = {
headers: {
'Content-Type': 'application/json',
},
};
await axios.post(
'http://localhost:8000/users/register',
{ name, email, password },
config
);
setSignUp((value) => !value);
} else {
// login
const { email, password } = authForm;
if (!email || !password) {
alert('Please enter all required fields');
return false;
}
const config = {
headers: {
'Content-Type': 'application/json',
},
};
const { data } = await axios.post(
'http://localhost:8000/users/login',
{ email, password },
config
);
localStorage.setItem('userInfo', JSON.stringify(data));
var token = data.token;
if (data.token) {
const config = {
headers: {
'Content-Type': 'application/json',
Authorization: token.token,
},
};
const { data } = await axios.get(
'http://localhost:8000/users/dashboard',
config
);
setDashboard(data.msg);
}
}
};
return (
<Paper className={classes.paper}>
{!dashboard ? (
<div className={classes.diiv}>
{signUp && (
<Grid container spacing={8} alignItems='flex-end'>
<Grid item>
<Face />
</Grid>
<Grid item md={true} sm={true} xs={true}>
<TextField
id='name'
label='Name'
type='text'
fullWidth
autoFocus
onChange={(e) =>
setAuthForm({ ...authForm, name: e.target.value })
}
/>
</Grid>
</Grid>
)}
<Grid container spacing={8} alignItems='flex-end'>
<Grid item>
<Face />
</Grid>
<Grid item md={true} sm={true} xs={true}>
<TextField
id='email'
label='Email'
type='email'
fullWidth
autoFocus
onChange={(e) =>
setAuthForm({ ...authForm, email: e.target.value })
}
/>
</Grid>
</Grid>
<Grid container spacing={8} alignItems='flex-end'>
<Grid item>
<Fingerprint />
</Grid>
<Grid item md={true} sm={true} xs={true}>
<TextField
id='username'
label='<PASSWORD>'
type='password'
fullWidth
onChange={(e) =>
setAuthForm({ ...authForm, password: e.target.value })
}
/>
</Grid>
</Grid>
<Grid container alignItems='center' justify='space-between'>
<Grid item></Grid>
<Grid item>
<Button
disableFocusRipple
disableRipple
style={{ textTransform: 'none' }}
variant='text'
color='primary'
onClick={() => setSignUp((value) => !value)}
>
{signUp
? 'Already have an account ? '
: 'Dont have an account ?'}
</Button>
</Grid>
</Grid>
<Grid container justify='center' style={{ marginTop: '10px' }}>
<Button
variant='outlined'
color='primary'
style={{ textTransform: 'none' }}
onClick={handleSubmit}
>
{signUp ? 'Sign Up' : 'Sign in'}
</Button>
</Grid>
</div>
) : (
<div>{dashboard}</div>
)}
</Paper>
);
}
export default App;
| 3615d5640962f883315cf27c9a2477486f391ae8 | [
"JavaScript"
]
| 1 | JavaScript | vcbartolome/user-auth-mern-passport-jwt | cfa4f629a4ab68478246a2a853e1c6b5cdf640cb | e34d2f56554360b864bf815a95e84f5227f2e358 |
refs/heads/master | <repo_name>jimichailidis/big-data-lab-reports<file_sep>/lab5/athena_sql/customer_parquet.sql
CREATE EXTERNAL TABLE customer(
C_CustKey int ,
C_Name varchar(64) ,
C_Address varchar(64) ,
C_NationKey int ,
C_Phone varchar(64) ,
C_AcctBal decimal(13, 2) ,
C_MktSegment varchar(64) ,
C_Comment varchar(120) ,
skip varchar(64)
)
STORED AS PARQUET
LOCATION 's3://group10-lab5/customer/'
tblproperties ("parquet.compress"="SNAPPY");<file_sep>/lab5/athena_sql/partsup.sql
CREATE EXTERNAL TABLE partsupp(
PS_PartKey int ,
PS_SuppKey int ,
PS_AvailQty int ,
PS_SupplyCost decimal(13, 2) ,
PS_Comment varchar(200) ,
skip varchar(64)
)
STORED AS PARQUET
LOCATION 's3://group10-lab5/partsupp/'
tblproperties ("parquet.compress"="SNAPPY");
<file_sep>/lab5/athena_sql/region_parquet.sql
CREATE EXTERNAL TABLE region(
R_RegionKey int ,
R_Name varchar(64) ,
R_Comment varchar(160) ,
skip varchar(64)
)
STORED AS PARQUET
LOCATION 's3://group10-lab5/region/'
tblproperties ("parquet.compress"="SNAPPY");<file_sep>/lab2/enron-reduce.py
#!/usr/bin/env python
import sys
current_count = 0
current_word = ""
for line in sys.stdin:
line = line.strip().split('\t')
if len(line) != 1:
continue
key = line[0]
if (key != current_word):
if (current_count > 1):
print current_word + '\t' + str(current_count)
current_count = 0
current_word = key
current_count += 1
if (current_count > 1):
print current_word + '\t' + str(current_count)
<file_sep>/lab5/tpch_q5_ath.sql
select
n_name, sum(l_extendedprice * (1 - l_discount)) as revenue
from
customer c join
( select n_name, l_extendedprice, l_discount, s_nationkey, o_custkey from orders o join
( select n_name, l_extendedprice, l_discount, l_orderkey, s_nationkey from lineitem l join
( select n_name, s_suppkey, s_nationkey from supplier s join
( select n_name, n_nationkey
from nation n join region r
on n.n_regionkey = r.r_regionkey and r.r_name = 'MIDDLE EAST'
) n1 on s.s_nationkey = n1.n_nationkey
) s1 on l.l_suppkey = s1.s_suppkey
) l1 on l1.l_orderkey = o.o_orderkey
) o1
on c.c_nationkey = o1.s_nationkey and c.c_custkey = o1.o_custkey
group by n_name
order by revenue desc;
<file_sep>/lab2/enron-map.py
#!/usr/bin/env python
from datetime import datetime
import sys
def get_email_domain(email):
return email.split('@')[1]
for line in sys.stdin:
data = line.split('\t')
# Exclude emails not between the given date
date = datetime.strptime(data[0], '%Y-%m-%dT%H:%M:%S%fZ')
keep_date = datetime(2001, 11, 5).date() <= date.date() <= datetime(2001, 11, 8).date()
# Get the domain of the email addresses of the sender and the recipient
sndr = get_email_domain(data[1])
rcpt = get_email_domain(data[2])
# Exclude emails from enron not sent outside of enron
keep_sndr = 'enron' in sndr
keep_rcpt = 'enron' not in rcpt
if keep_date and keep_sndr and keep_rcpt:
# Emit the sender to the reducer.
print data[1].strip()
<file_sep>/lab5/athena_sql/part_parquet.sql
CREATE EXTERNAL TABLE part(
P_PartKey int ,
P_Name varchar(64) ,
P_Mfgr varchar(64) ,
P_Brand varchar(64) ,
P_Type varchar(64) ,
P_Size int ,
P_Container varchar(64) ,
P_RetailPrice decimal(13, 2) ,
P_Comment varchar(64) ,
skip varchar(64)
)
STORED AS PARQUET
LOCATION 's3://group10-lab5/part/'
tblproperties ("parquet.compress"="SNAPPY");
<file_sep>/README.md
big-data-lab-reports
<file_sep>/lab5/athena_sql/lineitem_parquet_partinioned.sql
CREATE EXTERNAL TABLE lineitem(
L_OrderKey int ,
L_PartKey int ,
L_SuppKey int ,
L_LineNumber int ,
L_Quantity int ,
L_ExtendedPrice decimal(13, 2) ,
L_Discount decimal(13, 2) ,
L_Tax decimal(13, 2) ,
L_ReturnFlag varchar(64) ,
L_LineStatus varchar(64) ,
L_CommitDate date ,
L_ReceiptDate date ,
L_ShipInstruct varchar(64) ,
L_ShipMode varchar(64) ,
L_Comment varchar(64) ,
skip varchar(64)
)
PARTITIONED BY (L_ShipDate date)
STORED AS PARQUET
LOCATION 's3://group10-lab5/partitioned/date-strategy/lineitem'
tblproperties ("parquet.compress"="SNAPPY");
<file_sep>/lab5/tpch_q1_ath.sql
SELECT
L_RETURNFLAG,
L_LINESTATUS,
SUM(L_QUANTITY),
SUM(L_EXTENDEDPRICE),
SUM(L_EXTENDEDPRICE*(1-L_DISCOUNT)),
SUM(L_EXTENDEDPRICE*(1-L_DISCOUNT)*(1+L_TAX)),
AVG(L_QUANTITY),
AVG(L_EXTENDEDPRICE),
AVG(L_DISCOUNT),
COUNT(1)
FROM
lineitem
WHERE
L_SHIPDATE<= CAST ('1998-09-02' AS DATE)
GROUP BY L_RETURNFLAG, L_LINESTATUS
ORDER BY L_RETURNFLAG, L_LINESTATUS;
<file_sep>/lab5/athena_sql/nation_parquet.sql
CREATE EXTERNAL TABLE nation(
N_NationKey int ,
N_Name varchar(64) ,
N_RegionKey int ,
N_Comment varchar(160) ,
skip varchar(64)
)
STORED AS PARQUET
LOCATION 's3://group10-lab5/nation/'
tblproperties ("parquet.compress"="SNAPPY");<file_sep>/lab2/enron-etl.py
#!/usr/bin/env python
# this turns enron email archive into tuples (date, from, to)
import sys
import zipfile
import tempfile
import email
import time
import datetime
import os
import urllib
# stdin is list of URLs to data files
for u in sys.stdin:
u = u.strip()
if not u:
continue
tmpf = tempfile.mkstemp()
urllib.urlretrieve(u, tmpf[1])
try:
zip = zipfile.ZipFile(tmpf[1], 'r')
except:
continue
txtf = [i for i in zip.infolist() if i.filename.endswith('.txt')]
for f in txtf:
msg = email.message_from_file(zip.open(f))
tostr = msg.get("To")
fromstr = msg.get("From")
datestr = msg.get("Date")
if (tostr is None or fromstr is None or datestr is None):
continue
toaddrs = [email.utils.parseaddr(a) for a in tostr.split(',')]
fromaddr = email.utils.parseaddr(fromstr)[1].replace('\'','').strip().lower()
try: # datetime hell, convert custom time zone stuff to UTC
dt = datetime.datetime.strptime(datestr[:25].strip(), '%a, %d %b %Y %H:%M:%S')
dt = dt + datetime.timedelta(hours = int(datestr[25:].strip()[:3]))
except ValueError:
continue
if not '@' in fromaddr or '/' in fromaddr:
continue
for a in toaddrs:
if (not '@' in a[1] or '/' in a[1]):
continue
ta = a[1].replace('\'','').strip().lower()
print dt.isoformat() + 'Z\t' + fromaddr + '\t' + ta
zip.close()
os.remove(tmpf[1])
<file_sep>/lab5/athena_sql/orders_parquet.sql
CREATE EXTERNAL TABLE orders(
O_OrderKey int ,
O_CustKey int ,
O_OrderStatus varchar(64) ,
O_TotalPrice decimal(13, 2) ,
O_OrderDate date ,
O_OrderPriority varchar(15) ,
O_Clerk varchar(64) ,
O_ShipPriority int ,
O_Comment varchar(80) ,
skip varchar(64)
)
STORED AS PARQUET
LOCATION 's3://group10-lab5/orders/'
tblproperties ("parquet.compress"="SNAPPY");
| f26796e7885251ec20c801a743b694a51676578e | [
"Markdown",
"SQL",
"Python"
]
| 13 | SQL | jimichailidis/big-data-lab-reports | a7ad354775ea953ff9b2faa9e53e41b896895bf7 | 2cbd30d0e1975a711f0de7ee0deff3e073babda6 |
refs/heads/master | <file_sep>package com.aboal3ta.breathe.Util;
import android.app.Activity;
import android.content.SharedPreferences;
import java.util.Calendar;
public class Prefs {
private SharedPreferences preferences;
public Prefs(Activity activity) {
this.preferences = activity.getPreferences(Activity.MODE_PRIVATE);
}
public void setDate( long milliseconds) {
preferences.edit().putLong("seconds", milliseconds).apply();
}
public String getDate() {
long milliDate = preferences.getLong("seconds", 0);
String amOrPm;
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(milliDate);
int a = calendar.get(Calendar.AM_PM);
if (a == Calendar.AM)
amOrPm = "AM";
else
amOrPm = "PM";
String time = "Last " + calendar.get(Calendar.HOUR_OF_DAY) + ":" + calendar.get(Calendar.MINUTE)
+ " " + amOrPm;
return time;
}
public void setSessions(int session) {
preferences.edit().putInt("sessions", session).apply();
}
public int getSessions() {
return preferences.getInt("sessions", 0);
}
public void setBreaths(int breaths) {
preferences.edit().putInt("breaths", breaths).apply(); //saving our breaths into system file
}
public int getBreaths() {
return preferences.getInt("breaths", 0);
}
}
<file_sep>package com.aboal3ta.breathe;
import androidx.appcompat.app.AppCompatActivity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.aboal3ta.breathe.Util.Prefs;
import com.github.florent37.viewanimator.AnimationListener;
import com.github.florent37.viewanimator.ViewAnimator;
import java.text.MessageFormat;
import java.util.Calendar;
public class MainActivity extends AppCompatActivity {
private ImageView imageView;
private TextView breathsTxt, timeTxt, sessionTxt, guideTxt,showconter;
private Button startButton;
private Prefs prefs;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = findViewById(R.id.lotusImage);
breathsTxt = findViewById(R.id.breathsTakenTxt);
timeTxt = findViewById(R.id.lastBreathTxt);
sessionTxt = findViewById(R.id.todayMinutesTxt);
guideTxt = findViewById(R.id.guideTxt);
showconter=findViewById(R.id.countershow);
prefs = new Prefs(this);
startIntroAnimation();
sessionTxt.setText(MessageFormat.format("{0} min today", prefs.getSessions()));
breathsTxt.setText(MessageFormat.format("{0} Breaths", prefs.getBreaths()));
timeTxt.setText(prefs.getDate());
startButton = findViewById(R.id.startButton);
startButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startAnimation();
setnotifaiction();
}
});
}
private void startIntroAnimation(){
ViewAnimator
.animate(guideTxt)
.scale(0, 1)
.duration(1500)
.onStart(new AnimationListener.Start() {
@Override
public void onStart() {
guideTxt.setText("Breathe");
}
})
.start();
}
private void startAnimation() {
ViewAnimator
.animate(imageView)
.alpha(0, 1)
.onStart(new AnimationListener.Start() {
@Override
public void onStart() {
guideTxt.setText("Inhale... Exhale");
startButton.setVisibility(View.INVISIBLE);
//refresh activity
new CountDownTimer(60000, 1000) {
@Override
public void onTick(long l) {
//put code to show ticking... 1, 2, 3...
showconter.setText("seconds remaining: "+ String.valueOf(l/1000));
}
@Override
public void onFinish() {
showconter.setText("0");
startActivity(new Intent(getApplicationContext(), MainActivity.class));
finish();
}
}.start();
}
})
.decelerate()
.duration(1000)
.thenAnimate(imageView)
.scale(0.02f, 1.5f, 0.02f)
.rotation(360)
.repeatCount(13)
.accelerate()
.duration(5000)
.onStop(new AnimationListener.Stop() {
@Override
public void onStop() {
guideTxt.setText("Good Job");
imageView.setScaleX(1.0f);
imageView.setScaleY(1.0f);
prefs.setSessions(prefs.getSessions() + 1);
prefs.setBreaths(prefs.getBreaths() + 1);
prefs.setDate(System.currentTimeMillis());
}
})
.start();
}
private void setnotifaiction()
{
AlarmManager alarmManager= (AlarmManager) getSystemService(ALARM_SERVICE);
Calendar calendar=Calendar.getInstance();
calendar.add(Calendar.HOUR,1);
calendar.add(Calendar.HOUR_OF_DAY,16);
Intent intent=new Intent(this, Alrammanger.class);
PendingIntent pendingIntent=PendingIntent.getBroadcast(this,100,intent,PendingIntent.FLAG_UPDATE_CURRENT);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
alarmManager.setExact(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis(),pendingIntent);
}
}
}
| 057d2b7fe439ae7a3a6dfa35146b9b9c7a823383 | [
"Java"
]
| 2 | Java | ahmedaboalata/Breathe | baeeaf53f1d778036cddbc64bfa166bc28cd98b8 | 07d49fee01f7fcd3384c0281199c18e8ed727de8 |
refs/heads/master | <file_sep># News Api
This is an open source api for educational purposes.
You can find the android app in this repository :
https://github.com/majedalmoqbeli/news-api
<file_sep>-- phpMyAdmin SQL Dump
-- version 4.8.4
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: Oct 21, 2020 at 10:54 PM
-- Server version: 10.1.37-MariaDB
-- PHP Version: 7.3.1
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `news_db`
--
DELIMITER $$
--
-- Procedures
--
CREATE DEFINER=`root`@`localhost` PROCEDURE `get_news` () NO SQL
BEGIN
SELECT news_id, news_title, news_info, news_lat, news_lng,news_date,news_image,
news.user_id , user.u_name , user.u_image
FROM news
INNER JOIN user ON news.user_id = user.u_id
WHERE news_active = 1 and user.u_active = 1
ORDER BY news_id DESC
LIMIT 5;
END$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `get_news_by_last_id` (IN `last_id` INT(11)) NO SQL
BEGIN
SELECT news_id, news_title, news_info, news_lat, news_lng,news_date, news_image,
news.user_id , user.u_name , user.u_image
FROM news
INNER JOIN user ON news.user_id = user.u_id
WHERE news_active = 1 and user.u_active = 1
and news_id < last_id
ORDER BY news_id DESC
LIMIT 5;
END$$
DELIMITER ;
-- --------------------------------------------------------
--
-- Table structure for table `news`
--
CREATE TABLE `news` (
`news_id` int(11) NOT NULL,
`news_title` varchar(255) NOT NULL,
`news_info` text NOT NULL,
`news_lat` double NOT NULL,
`news_lng` double NOT NULL,
`news_date` varchar(255) NOT NULL,
`news_image` varchar(255) DEFAULT NULL,
`user_id` int(11) NOT NULL,
`news_active` tinyint(1) NOT NULL DEFAULT '1'
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data for table `news`
--
INSERT INTO `news` (`news_id`, `news_title`, `news_info`, `news_lat`, `news_lng`, `news_date`, `news_image`, `user_id`, `news_active`) VALUES
(1, 'This is title well change ', 'This is title well change with the real news after publish This is title well change with the real news after publish This is title well change with the real news after publish This is title well change with the real news after publish This is title well change with the real news after publish This is title well change with the real news after publish This is title well change with the real news after publish This is title well change with the real news after publish This is title well change with the real news after publish This is title well change with the real news after publish This is title well change with the real news after publish This is title well change with the real news after publish ', 15.307469, 44.185884, '2020-03-29T22:58:29+00:00', '345434535443.jpg', 2, 1),
(2, 'This is title well change', 'This is title well change with the real news after publish This is title well change with the real news after publish This is title well change with the real news after publish This is title well change with the real news after publish This is title well change with the real news after publish This is title well change with the real news after publish This is title well change with the real news after publish This is title well change with the real news after publish This is title well change with the real news after publish This is title well change with the real news after publish This is title well change with the real news after publish This is title well change with the real news after publish ', 15.30766, 44.189774, '2020-03-29T22:58:29+00:00', '34545645534345.jpg', 1, 1),
(3, 'This is title well change', 'This is title well change with the real news after publish This is title well change with the real news after publish This is title well change with the real news after publish This is title well change with the real news after publish This is title well change with the real news after publish This is title well change with the real news after publish This is title well change with the real news after publish This is title well change with the real news after publish This is title well change with the real news after publish This is title well change with the real news after publish This is title well change with the real news after publish This is title well change with the real news after publish ', 15.306947, 44.189346, '2020-03-29T22:58:29+00:00', '23345354443543.jpg', 2, 1),
(4, 'This is title well change with tilte', 'This is title well change with the real news after publish This is title well change with the real news after publish This is title well change with the real news after publish This is title well change with the real news after publish This is title well change with the real news after publish This is title well change with the real news after publish This is title well change with the real news after publish This is title well change with the real news after publish This is title well change with the real news after publish This is title well change with the real news after publish This is title well change with the real news after publish This is title well change with the real news after publish ', 0, 0, '2020-03-29T22:58:29+00:00', '2324545434556656445.jpg', 1, 1),
(5, 'Any title for testing', 'This is title well change with the real news after publish This is title well change with the real news after publish This is title well change with the real news after publish This is title well change with the real news after publish This is title well change with the real news after publish This is title well change with the real news after publish This is title well change with the real news after publish This is title well change with the real news after publish This is title well change with the real news after publish This is title well change with the real news after publish This is title well change with the real news after publish This is title well change with the real news after publish', 15.305584, 44.186357, '2020-04-04T22:58:29+00:00', '34545645534345.jpg', 1, 1),
(6, 'Any title for testing', 'This is title well change with the real news after publish This is title well change with the real news after publish This is title well change with the real news after publish This is title well change with the real news after publish This is title well change with the real news after publish This is title well change with the real news after publish This is title well change with the real news after publish This is title well change with the real news after publish This is title well change with the real news after publish This is title well change with the real news after publish This is title well change with the real news after publish This is title well change with the real news after publish', 15.301123, 44.186432, '2020-05-05T22:58:29+00:00', NULL, 1, 1),
(7, 'Any title for testing', 'This is title well change with the real news after publish This is title well change with the real news after publish This is title well change with the real news after publish This is title well change with the real news after publish This is title well change with the real news after publish This is title well change with the real news after publish This is title well change with the real news after publish This is title well change with the real news after publish This is title well change with the real news after publish This is title well change with the real news after publish This is title well change with the real news after publish This is title well change with the real news after publish', 16.301123, 44.186432, '2020-05-05T22:58:29+00:00', '23345354443543.jpg', 2, 1),
(8, 'Any title for testing', 'This is title well change with the real news after publish This is title well change with the real news after publish This is title well change with the real news after publish This is title well change with the real news after publish This is title well change with the real news after publish This is title well change with the real news after publish This is title well change with the real news after publish This is title well change with the real news after publish This is title well change with the real news after publish This is title well change with the real news after publish This is title well change with the real news after publish This is title well change with the real news after publish', 17.301123, 44.186432, '2020-10-21T19:33:21+00:00', NULL, 1, 1);
-- --------------------------------------------------------
--
-- Table structure for table `user`
--
CREATE TABLE `user` (
`u_id` int(11) NOT NULL,
`u_name` varchar(255) NOT NULL,
`u_image` varchar(255) NOT NULL,
`u_active` tinyint(1) NOT NULL DEFAULT '1'
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data for table `user`
--
INSERT INTO `user` (`u_id`, `u_name`, `u_image`, `u_active`) VALUES
(1, '<NAME>', '8987538490938539.jpg', 1),
(2, '<NAME>', '23455667456456740.jpg', 1);
--
-- Indexes for dumped tables
--
--
-- Indexes for table `news`
--
ALTER TABLE `news`
ADD PRIMARY KEY (`news_id`),
ADD KEY `user_id` (`user_id`);
--
-- Indexes for table `user`
--
ALTER TABLE `user`
ADD PRIMARY KEY (`u_id`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `news`
--
ALTER TABLE `news`
MODIFY `news_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=9;
--
-- AUTO_INCREMENT for table `user`
--
ALTER TABLE `user`
MODIFY `u_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;
--
-- Constraints for dumped tables
--
--
-- Constraints for table `news`
--
ALTER TABLE `news`
ADD CONSTRAINT `news_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `user` (`u_id`);
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
<file_sep><?PHP
/**
* start config
*/
$con = mysqli_connect("localhost", "root", "", "news_db");
mysqli_set_charset($con, 'utf8mb4');
header("Content-Type:application/json;charset=utf-8");
/**
* end config
*/
if ($_POST != null) {
if (isset($_POST['last_id'])
&& is_numeric($_POST['last_id'])
) {
if ($_POST['last_id'] == '0') {
$sql = "Call get_news()";
} else {
$sql = "Call get_news_by_last_id('$_POST[last_id]')";
}
$data['news'] = array();
if ($news_data = mysqli_query($con, $sql)) {
while ($row = mysqli_fetch_assoc($news_data)) {
array_push($data['news'], $row);
}
$data['status_code'] = 200;
$data['status_message'] = 'Success';
echo json_encode($data);
} else {
$data['status_code'] = 204;
$data['status_message'] = 'Failed to get data.';
echo json_encode($data);
}
} else {
$data['status_code'] = 403;
$data['status_message'] = 'Forbidden. You don\'t have permission to access to the server !!';
echo json_encode($data);
}
} else {
$data['status_code'] = 406;
$data['status_message'] = 'Not Acceptable';
echo json_encode($data);
}
// closing connection
mysqli_close($con);
| 6c22b62e6c3658b4296f643137a378445f40cf20 | [
"Markdown",
"SQL",
"PHP"
]
| 3 | Markdown | WatheqAlshowaiter/news-api | 2152f3ccedf9e5bb94e44aeb97209f279c5e40a8 | c4792ae04c601efe626c1b432d3aa676daf48580 |
refs/heads/main | <repo_name>danteee999/sinav<file_sep>/src/calculator/dictionary.java
package calculator;
import java.lang.reflect.Array;
public class dictionary {
int activeIndex= 0;
word[] words = new word[100];
public void addWord1(String original, String translation) {
word wr = new word();
wr.set_original(original);
wr.set_translation(translation);
words[activeIndex] = wr;
activeIndex++;
}
public void addWord2(word wr) {
words[activeIndex] = wr;
activeIndex++;
}
public String translate(String original) {
for(int i = 0 ; i < activeIndex; i++) {
if (words[i].get_original() == original) {
return words[i].get_translation();
}
}
return "yok";
}
@Override
public String toString() {
for(int i = 0 ; i < activeIndex; i++) {
System.out.println(words[i].toString());
}
for(int i = 0 ; i < activeIndex; i++) {
System.out.println(String.format("Original => %s", words[i].get_original()));
System.out.println(String.format("Translation => %s", words[i].get_translation()));
}
return "";
}
}
<file_sep>/src/calculator/word.java
package calculator;
public class word {
private String _original;
private String _translation;
public String get_original() {
return _original;
}
public void set_original(String _original) {
this._original = _original;
}
public String get_translation() {
return _translation;
}
public void set_translation(String _translation) {
this._translation = _translation;
}
public word() {
}
@Override
public String toString() {
return String.format("(%s , %s)", _original,_translation);
}
}
| 0bec0b22cca03e61251f7cf8a400b46ca6815889 | [
"Java"
]
| 2 | Java | danteee999/sinav | caa120828b5161cfa2d432217c785d435eacc6a1 | 9103ddf2f5bb8f0f72fa4f8c43802b1a558f4c62 |
refs/heads/master | <repo_name>Ikaw/Website_Travel_SBD<file_sep>/Admin/home.php
<?php session_start();
if (ISSET($_SESSION['adminlogin']))
{
//Tidak ada event, dalam artian menghindari jump page
}
else
//header("location:index.php");
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Travel Online</title>
<script type="text/javascript">
function MM_swapImgRestore() { //v3.0
var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}
function MM_preloadImages() { //v3.0
var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}
function MM_findObj(n, d) { //v4.01
var p,i,x; if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
if(!x && d.getElementById) x=d.getElementById(n); return x;
}
function MM_swapImage() { //v3.0
var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}
</script>
</head>
<style type="text/css">
.Menu_Kiri {
width: 150px;
font-family: Tahoma, Geneva, sans-serif;
font-size: 14px;
margin-top: 10px;
margin-bottom: 10px;
}
.Menu_Tengah {
margin-top: 10px;
margin-bottom: 10px;
}
body {
background-color: #cdedf6;
}
</style>
<body onload="MM_preloadImages('../gambar/btnadmin2.jpg','../gambar/btnmember2.jpg','../gambar/btntrayek2.jpg','../gambar/btnjamberangkat2.jpg','../gambar/btnjadwal2.jpg','../gambar/btnpesanan2.jpg','../gambar/btnlogout2.jpg')">
<table width="900" border="0" align="center" cellpadding="0" cellspacing="0">
<tr>
<td colspan="2"><img src="../gambar/header1.jpg" width="900" height="169" /></td>
</tr>
<tr>
<td colspan="2"><img src="../gambar/header2.jpg" width="900" height="30" /></td>
</tr>
<tr>
<td width="200" valign="top"><table width="200" border="0" cellspacing="6" cellpadding="3">
<tr>
<td><a href="home.php" onmouseout="MM_swapImgRestore()" onmouseover="MM_swapImage('btnadmin','','../gambar/btnadmin2.jpg',1)"><img src="../gambar/btnadmin.jpg" width="200" height="30" id="btnadmin" /></a></td>
</tr>
<tr>
<td><a href="member.php" onmouseout="MM_swapImgRestore()" onmouseover="MM_swapImage('btnmember','','../gambar/btnmember2.jpg',1)"><img src="../gambar/btnmember.jpg" width="200" height="30" id="btnmember" /></a></td>
</tr>
<tr>
<td><a href="trayek.php" onmouseout="MM_swapImgRestore()" onmouseover="MM_swapImage('btntrayek','','../gambar/btntrayek2.jpg',1)"><img src="../gambar/btntrayek.jpg" width="200" height="30" id="btntrayek" /></a></td>
</tr>
<tr>
<td><a href="jamberangkat.php" onmouseout="MM_swapImgRestore()" onmouseover="MM_swapImage('btnjamberangkat','','../gambar/btnjamberangkat2.jpg',1)"><img src="../gambar/btnjamberangkat.jpg" width="200" height="30" id="btnjamberangkat" /></a></td>
</tr>
<tr>
<td><a href="jadwal.php" onmouseout="MM_swapImgRestore()" onmouseover="MM_swapImage('btnjadwal','','../gambar/btnjadwal2.jpg',1)"><img src="../gambar/btnjadwal.jpg" width="200" height="30" id="btnjadwal" /></a></td>
</tr>
<tr>
<td><a href="pesanan.php" onmouseout="MM_swapImgRestore()" onmouseover="MM_swapImage('btnpesanan','','../gambar/btnpesanan2.jpg',1)"><img src="../gambar/btnpesanan.jpg" width="200" height="30" id="btnpesanan" /></a></td>
</tr>
<tr>
<td><a href="logout.php" onmouseout="MM_swapImgRestore()" onmouseover="MM_swapImage('btnlogout','','../gambar/btnlogout2.jpg',1)"><img src="../gambar/btnlogout.jpg" width="200" height="30" id="btnlogout" /></a></td>
</tr>
</table></td>
<td width="650" valign="top">
<table width="650" border="0" cellspacing="0" cellpadding="0">
<tr>
<td colspan="2"><?php include "isi.php"; ?></td>
</tr>
<tr>
<td> </td>
<td> </td>
</tr>
</table>
</td>
</tr>
<tr>
<td colspan="2"><img src="../gambar/footeradmin.jpg" width="900" height="98" /></td>
</tr>
</table>
</body>
</html>
<file_sep>/Admin/pesanan_form.php
<link href="js/jquery-ui-1.10.4.custom.css" rel="stylesheet">
<script src="js/jquery-1.10.2.js"></script>
<script src="js/jquery-ui-1.10.4.custom.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#tgltxt").datepicker({
dateFormat : "yy-mm-dd",
});
});
</script>
<style type="text/css">
form {
font-family: "Segoe UI", "Segoe UI Light";
}
#form1 table {
font-size: 16px;
}
#form1 table tr td p {
font-size: 14px;
}
</style>
<form id="form1" name="form1" method="post" action="pesanan_tambah.php">
<table width="650" border="0" align="left">
<tr>
<td width="30%" align="left" valign="top">ID </td>
<td width="1%" align="left" valign="top">:</td>
<td width="69%" align="left" valign="top"><label>
<input name="idtxt" type="text" id="idtxt" size="40"/>
</label>
</span></td>
</tr>
<tr>
<td width="left" align="left" valign="top">Nomor Kursi </td>
<td width="left" align="left" valign="top">:</td>
<td width="left" align="left" valign="top"><label>
<input name="noktxt" type="text" id="noktxt" size="40"/>
</label>
</span></td>
</tr>
<tr>
<td width="left" align="left" valign="top">Tanggal Pesan </td>
<td width="left" align="left" valign="top">:</td>
<td width="left" align="left" valign="top"><label>
<input name="tgltxt" type="date" id="tgltxt" size="40"/>
</label>
</span></td>
</tr>
<tr>
<td width="left" align="left" valign="top">ID Member</td>
<td width="left" align="left" valign="top">:</td>
<td width="left" align="left" valign="top"><label for="memtxt"></label>
<label for="memlist"></label>
<select name="memlist" size="1" id="memlist">
<?php
require ("config.php");
$perintah="select * from member order by id_member asc";
$hasil=mysql_query($perintah);
while ($data = mysql_fetch_array($hasil))
{
?>
<option value="<?php echo "$data[id_member]"; ?>"><?php echo "$data[id_member]"; }?></option>
</select></td>
<td>
<?php
// require ("config.php");
// $datmem = $data[id_member];
// $perintah="select * from member";
// $hasil=mysql_query($perintah);
// $data = mysql_fetch_array($hasil);
// echo $data[nama];
?>
</td>
</tr>
<tr>
<td width="left" align="left" valign="top">ID Jadwal</td>
<td width="left" align="left" valign="top">:</td>
<td width="left" align="left" valign="top">
<label for="jadlist"></label>
<select name="jadlist" size="1" id="jadlist">
<?php
require ("config.php");
$perintah="select * from jadwal order by id_jadwal asc";
$hasil=mysql_query($perintah);
while ($data = mysql_fetch_array($hasil))
{
?>
<option value="<?php echo "$data[id_jadwal]"; ?>"><?php echo "$data[id_jadwal]"; }?></option>
</select></td>
</tr>
<tr>
<td align="left" valign="top"> </td>
<td align="left" valign="top"> </td>
<td align="left" valign="top"><hr color="black"/></td>
</tr>
<tr>
<td align="left" valign="top"> </td>
<td align="left" valign="top"> </td>
<td align="left" valign="top"><label>
<input type="submit" name="Submit" value="Simpan" />
</label>
<label>
<input type="reset" name="Submit2" value="Batal" />
</label>
</span></td>
</tr>
</table>
</form>
<file_sep>/Admin/member_hapus.php
<?php session_start();
if (ISSET($_SESSION['adminlogin']))
{
require("config.php");
$id_member = $_GET['id_member'];
$perintah = "DELETE from member where id_member = $id_member";
$result = mysql_query($perintah);
if ($result) {
header("location:member.php");
} else { echo "Data belum dapat di simpan!!";
}
}
?><file_sep>/Admin/jamberangkat_ubah_proses.php
<?php session_start();
if (ISSET($_SESSION['adminlogin']))
{
require("config.php");
$perintah = "UPDATE jamberangkat set jam = '$_POST[jamtxt]' where id_jam = '$_POST[idtxt]'";
$result = mysql_query($perintah);
if ($result) {
header("location:jamberangkat.php");
} else { echo "Data belum dapat di ubah!!";
}
}
?><file_sep>/Admin/pesanan_hapus.php
<?php session_start();
if (ISSET($_SESSION['adminlogin']))
{
require("config.php");
$id_pesanan = $_GET['id_pesanan'];
$perintah = "DELETE from pesanan where id_pesanan = '$id_pesanan'";
$result = mysql_query($perintah);
if ($result) {
header("location:pesanan.php");
} else { echo "Data belum dapat di simpan!!";
}
}
?><file_sep>/Admin/member_tambah.php
<?php session_start();
if (ISSET($_SESSION['adminlogin']))
{
require("config.php");
$nama = $_POST['namatxt'];
$alm = $_POST['almtxt'];
$tlp = $_POST['tlptxt'];
$eml = $_POST['emltxt'];
$usr = $_POST['usrtxt'];
$pss = $_POST['psstxt'];
$perintah = "INSERT INTO member (nama,alamat,telepon,email,username,password)
VALUES ('$nama','$alm','$tlp','$eml','$usr','$pss')";
$result = mysql_query($perintah);
if ($result) {
header("location:member.php");
} else { echo "Data belum dapat di simpan!!";
}
}
?><file_sep>/Admin/jadwal_form.php
<style type="text/css">
form {
font-family: "Segoe UI", "Segoe UI Light";
}
#form1 table {
font-size: 16px;
}
#form1 table tr td p {
font-size: 14px;
}
</style>
<form id="form1" name="form1" method="post" action="jadwal_tambah.php">
<table width="650" border="0" align="left">
<tr>
<td width="30%" align="left" valign="top">ID </td>
<td width="1%" align="left" valign="top">:</td>
<td width="69%" align="left" valign="top"><label>
<input name="idtxt" type="text" id="idtxt" size="40">
</label>
</span></td>
</tr>
<tr>
<td align="left" valign="top">ID Trayek</td>
<td align="left" valign="top">:</td>
<td align="left" valign="top"><label>
<label for="tralist"></label>
<select name="tralist" size="1" id="tralist">
<?php
require ("config.php");
$perintah="select * from trayek order by id_trayek asc";
$hasil=mysql_query($perintah);
while ($data = mysql_fetch_array($hasil))
{
?>
<option value="<?php echo "$data[id_trayek]"; ?>"><?php echo "$data[id_trayek]"; }?></option>
</select></td>
</tr>
<tr>
<td align="left" valign="top">ID Jam Berangkat</td>
<td align="left" valign="top">:</td>
<td align="left" valign="top">
<label for="jamlist"></label>
<select name="jamlist" size="1" id="jamlist">
<?php
require ("config.php");
$perintah="select * from jamberangkat order by id_jam asc";
$hasil=mysql_query($perintah);
while ($data = mysql_fetch_array($hasil))
{
?>
<option value="<?php echo "$data[id_jam]"; ?>"><?php echo "$data[id_jam]"; }?></option>
</select></td>
</tr>
<tr>
<td align="left" valign="top"> </td>
<td align="left" valign="top"> </td>
<td align="left" valign="top"><hr color="black"/></td>
</tr>
<tr>
<td align="left" valign="top"> </td>
<td align="left" valign="top"> </td>
<td align="left" valign="top"><label>
<input type="submit" name="Submit" value="Simpan" />
</label>
<label>
<input type="reset" name="Submit2" value="Batal" />
</label>
</span></td>
</tr>
</table>
</form><file_sep>/profile_isi.php
<?php
session_start();
if (ISSET($_SESSION['userlogin']))
{
}
else
header("location:index.php");
require ("config.php");
//$perintah="select * from member where username ='".$_GET['id_member']."'";
$perintah="select * from member where username ='".$_SESSION['userlogin']."'";
$hasil=mysql_query($perintah);
$data=mysql_fetch_array($hasil);
?>
<table>
<tr>
<td colspan="3">Profile<hr color="black" width="650"/></td>
</tr>
<tr>
<td width="30%" align="left" valign="top">Nama </td>
<td width="1%" align="left" valign="top">:</td>
<td width="69%" align="left" valign="top"><label for="namatxt">
<?php echo $data['nama']; ?></label></td>
</tr>
<tr>
<td align="left" valign="top">Alamat</td>
<td align="left" valign="top">:</td>
<td align="left" valign="top"><label for="almtxt"></label>
<?php echo $data['alamat'] ?></td>
</tr>
<tr>
<td align="left" valign="top">Telepon</td>
<td align="left" valign="top">:</td>
<td align="left" valign="top"><label for="tlptxt"></label>
<?php echo $data['telepon'] ?></td>
</tr>
<tr>
<td align="left" valign="top">Email</td>
<td align="left" valign="top">:</td>
<td align="left" valign="top"><label for="emltxt"></label>
<?php echo $data['email'] ?></td>
</tr>
<tr>
<td align="left" valign="top"> </td>
<td align="left" valign="top"> </td>
<td align="left" valign="top"><hr color="black"/></td>
</tr>
<tr>
<td align="left" valign="top"> </td>
<td align="left" valign="top"> </td>
<td align="left" valign="top"><label>
<?php echo'<a href="profile_ubah.php?id_member='.$data[id_member].'"><input type="submit" name="Submit" value="Edit" /></a>';?>
</label>
</span></td>
</tr>
</table>
<file_sep>/Admin/pesanan_ubah_form.php
<?php
require ("config.php");
$perintah="select * from pesanan where id_pesanan='".$_GET['id_pesanan']."'";
$hasil=mysql_query($perintah);
$data=mysql_fetch_array($hasil);
?>
<form id="form1" name="form1" method="post" action="pesanan_ubah_proses.php">
<table width="650" border="0" align="left">
<tr>
<td colspan="3">Form Ubah Data Pesanan<hr color="black" width="650"/></td>
</tr>
<tr>
<td align="30%" valign="top">ID</td>
<td align="1%" valign="top">:</td>
<td align="69%" valign="top"><label for="idtxt"></label>
<input name="idtxt" type="text" id="idtxt" value="<?php echo $data['id_pesanan'] ?>" readonly="readonly" /></td>
</tr>
<tr>
<td width="left" align="left" valign="top">Nomor Kursi </td>
<td width="left" align="left" valign="top">:</td>
<td width="left" align="left" valign="top"><label>
<input name="noktxt" type="text" id="noktxt" value="<?php echo $data['no_kursi'] ?>" />
</label>
</span></td>
</tr>
<tr>
<td width="left" align="left" valign="top">Tanggal Pesan </td>
<td width="left" align="left" valign="top">:</td>
<td width="left" align="left" valign="top"><label>
<input name="tgltxt" type="date" id="tgltxt" value="<?php echo $data['tanggal_pesan'] ?>"/>
</label>
</span></td>
</tr>
<tr>
<td width="left" align="left" valign="top">ID Member</td>
<td width="left" align="left" valign="top">:</td>
<td width="left" align="left" valign="top"><label for="memtxt"></label>
<label for="memlist"></label>
<select name="memlist" size="1" id="memlist">
<?php
require ("config.php");
$perintah="select * from member order by id_member asc";
$hasil=mysql_query($perintah);
while ($data = mysql_fetch_array($hasil))
{
?>
<option value="<?php echo "$data[id_member]"; ?>"><?php echo "$data[id_member]"; }?></option>
</select></td>
</tr>
<tr>
<td width="left" align="left" valign="top">ID Jadwal</td>
<td width="left" align="left" valign="top">:</td>
<td width="left" align="left" valign="top"><label for="jadtxt"></label>
<label for="jadlist"></label>
<select name="jadlist" size="1" id="jadlist">
<?php
require ("config.php");
$perintah="select * from jadwal order by id_jadwal asc";
$hasil=mysql_query($perintah);
while ($data = mysql_fetch_array($hasil))
{
?>
<option value="<?php echo "$data[id_jadwal]"; ?>"><?php echo "$data[id_jadwal]"; }?></option>
</select></td>
</tr>
<tr>
<td align="left" valign="top"> </td>
<td align="left" valign="top"> </td>
<td align="left" valign="top"><hr color="black"/></td>
</tr>
<tr>
<td align="left" valign="top"> </td>
<td align="left" valign="top"> </td>
<td align="left" valign="top"><label>
<input type="submit" name="Submit" value="Simpan" />
</label>
</span></td>
</tr>
</table>
</form>
<file_sep>/login.php
<?php session_start();
include("config.php");
$user = $_POST['usertxt'];
$user = str_replace("'","´",$user);
$psw=$_POST['pswtxt'];
$psw= str_replace("'","´",$psw);
$cek = "Select username,password from member where username='".$user."' and password='".$psw."'";
$hasil = mysql_query($cek);
$hasil_cek = mysql_num_rows($hasil);
if ($hasil_cek==0){
header("location:login_page.php");
}else{
session_start();
$_SESSION['userlogin'] =$user;
header("location:index.php");
}
?><file_sep>/Admin/jamberangkat_ubah_form.php
<?php
require ("config.php");
$perintah="select * from jamberangkat where id_jam='".$_GET['id_jam']."'";
$hasil=mysql_query($perintah);
$data=mysql_fetch_array($hasil);
//$tampil_deskripsi=str_replace("<br>","\r\n",$data['deskripsi']);
?>
<form id="form1" name="form1" method="post" action="jamberangkat_ubah_proses.php">
<table width="650" border="0" align="left">
<tr>
<td colspan="3">Form Ubah Data Jam Berangkat <hr color="black" width="650"/></td>
</tr>
<tr>
<td align="30%" valign="top">ID</td>
<td align="1%" valign="top">:</td>
<td align="69%" valign="top"><label for="idtxt"></label>
<input name="idtxt" type="text" id="idtxt" size="40" value="<?php echo $data['id_jam'] ?>" readonly="readonly" /></td>
</tr>
<tr>
<td width="left" align="left" valign="top">Jam Berangkat </td>
<td width="left" align="left" valign="top">:</td>
<td width="left" align="left" valign="top"><label>
<input name="jamtxt" type="text" id="jamtxt" size="40" value="<?php echo $data['jam'] ?>"/>
</label>
</span></td>
</tr>
<tr>
<td align="left" valign="top"> </td>
<td align="left" valign="top"> </td>
<td align="left" valign="top"><hr color="black"/></td>
</tr>
<tr>
<td align="left" valign="top"> </td>
<td align="left" valign="top"> </td>
<td align="left" valign="top"><label>
<input type="submit" name="Submit" value="Simpan" />
</label>
</span></td>
</tr>
</table>
</form>
<file_sep>/Admin/jadwal_ubah_form.php
<?php
require ("config.php");
$perintah="select * from jadwal where id_jadwal='".$_GET['id_jadwal']."'";
$hasil=mysql_query($perintah);
$data=mysql_fetch_array($hasil);
?>
<form id="form1" name="form1" method="post" action="jadwal_ubah_proses.php">
<table width="650" border="0" align="left">
<tr>
<td colspan="4">Form Ubah Data Jadwal <hr color="black" width="650"/></td>
</tr>
<tr>
<td align="30%" valign="top">ID</td>
<td align="1%" valign="top">:</td>
<td align="69%" valign="top"><label for="idtxt"></label>
<input name="idtxt" type="text" id="idtxt" value="<?php echo $data['id_jadwal'] ?>" /></td>
</tr>
<tr>
<td width="left" align="left" valign="top">ID Trayek</td>
<td width="left" align="left" valign="top">:</td>
<td width="left" align="left" valign="top"><label for="tratxt"></label>
<label for="tralist"></label>
<select name="tralist" size="1" id="tralist">
<?php
require ("config.php");
$perintah="select * from trayek";
$hasil=mysql_query($perintah);
while ($data = mysql_fetch_array($hasil))
{
?>
<option value="<?php echo "$data[id_trayek]"; ?>"><?php echo "$data[id_trayek]"; }?></option>
</select></td>
</tr>
<tr>
<td width="left" align="left" valign="top">ID Jam Berangkat</td>
<td width="left" align="left" valign="top">:</td>
<td width="left" align="left" valign="top"><label for="jamtxt"></label>
<label for="jamlist"></label>
<select name="jamlist" size="1" id="jamlist">
<?php
require ("config.php");
$perintah="select * from jamberangkat order by id_jam asc";
$hasil=mysql_query($perintah);
while ($data = mysql_fetch_array($hasil))
{
?>
<option value="<?php echo "$data[id_jam]"; ?>"><?php echo "$data[id_jam]"; }?></option>
</select></td>
</tr>
<tr>
<td align="left" valign="top"> </td>
<td align="left" valign="top"> </td>
<td align="left" valign="top" colspan="3"><hr color="black"/></td>
</tr>
<tr>
<td align="left" valign="top"> </td>
<td align="left" valign="top"> </td>
<td align="left" valign="top"><label>
<input type="submit" name="Submit" value="Simpan" />
</label>
</span></td>
</tr>
</table>
</form>
<file_sep>/Admin/pesanan_tambah.php
<?php session_start();
if (ISSET($_SESSION['adminlogin']))
{
require("config.php");
$id_pesanan = $_POST['idtxt'];
$no_kursi = $_POST['noktxt'];
$tanggal_pesan = $_POST['tgltxt'];
$id_member = $_POST['memlist'];
$id_jadwal = $_POST['jadlist'];
$perintah = "INSERT INTO pesanan (id_pesanan,no_kursi,tanggal_pesan,id_member,id_jadwal)
VALUES ('$id_pesanan','$no_kursi','$tanggal_pesan','$id_member','$id_jadwal')";
$result = mysql_query($perintah);
if ($result) {
header("location:pesanan.php");
} else { echo "Data belum dapat di simpan!!";
}
}
?><file_sep>/profile.php
<?php session_start();
if (ISSET($_SESSION['userlogin']))
{
//Tidak ada event, dalam artian menghindari jump page
}
else
header("location:index.php");
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Travel Online</title>
<link type="text/css" rel="Stylesheet" href="../css/imageslidermaker.css" />
<link href="http://fonts.googleapis.com/css?family=Ubuntu:300|Titillium+Web:300,400" rel="stylesheet" type="text/css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
function MM_swapImgRestore() { //v3.0
var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}
function MM_preloadImages() { //v3.0
var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}
function MM_findObj(n, d) { //v4.01
var p,i,x; if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
if(!x && d.getElementById) x=d.getElementById(n); return x;
}
function MM_swapImage() { //v3.0
var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}
</script>
</head>
<style type="text/css">
body {
background-image: url(../webtravel/gambar/background5.jpg);
background-repeat: no-repeat;
}
.bgtable {
background-image: url(../webtravel/gambar/bgtable3.gif);
background-repeat: no-repeat;
opacity:0.6;
fileter:alpha(opacity=75);
}
</style>
<body onload="MM_preloadImages('../webtravel/gambar/btnlogin2.png','../webtravel/gambar/btnprofileuser2.png','../webtravel/gambar/btnbookinguser2.png','../webtravel/gambar/btnaboutuser2.png')">
<table width="900" border="0" align="center" cellpadding="0" cellspacing="0" >
<tr height="300">
<td></td>
</tr>
<tr>
<td height="40" align="right">
<a href="logout.php" onmouseout="MM_swapImgRestore()" onmouseover="MM_swapImage('btnlogoutuser','','../webtravel/gambar/btnlogoutuser2.png',1)"><img src="../webtravel/gambar/btnlogoutuser.png" width="120" height="40" id="btnlogoutuser"/></a>
</td>
</tr>
<tr><td>
<table class="bgtable" width="900" height="700">
<tr>
<td align="center" valign="middle" height="100" colspan="2">
<table cellspacing="4" cellpadding="0" border="0">
<tr>
<td width="225" height="100" align="center" valign="middle">
<a href="homebaru.php" onmouseout="MM_swapImgRestore()" onmouseover="MM_swapImage('tmhome','','../webtravel/gambar/tmhome2.png',1)"><img src="../webtravel/gambar/tmhome.png" width="220" height="100" id="tmhome"/>
</td>
<td width="225" height="100" align="center" valign="middle">
<a href="profile.php" onmouseout="MM_swapImgRestore()" onmouseover="MM_swapImage('tmprofile','','../webtravel/gambar/tmprofile2.png',1)"><img src="../webtravel/gambar/tmprofile.png" width="220" height="100" id="tmprofile"/>
</td>
<td width="225" height="100" align="center" valign="middle">
<a href="booking.php" onmouseout="MM_swapImgRestore()" onmouseover="MM_swapImage('tmbooking','','../webtravel/gambar/tmbooking2.png',1)"><img src="../webtravel/gambar/tmbooking.png" width="220" height="100" id="tmbooking"/>
</td>
<td width="225" height="100" align="center" valign="middle">
<a href="aboutus.php" onmouseout="MM_swapImgRestore()" onmouseover="MM_swapImage('tmabout','','../webtravel/gambar/tmabout2.png',1)"><img src="../webtravel/gambar/tmabout.png" width="220" height="100" id="tmabout"/>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="200" valign="top">
<img src="../webtravel/gambar/profpic.jpg" id="profpic" width="200" height="200"/>
</td>
<td colspan="3" width="650" valign="top"><?php include "profile_isi.php"; ?></td>
</tr>
</table>
</td>
</table>
</body>
</head>
</html><file_sep>/Admin/pesanan_ubah_proses.php
<?php session_start();
if (ISSET($_SESSION['adminlogin']))
{
require("config.php");
$perintah = "UPDATE pesanan set no_kursi='$_POST[noktxt]',tanggal_pesan='$_POST[tgltxt]',id_member = '$_POST[memlist]' ,id_jadwal = '$_POST[jadlist]' where id_pesanan = '$_POST[idtxt]'";
$result = mysql_query($perintah);
if ($result) {
header("location:pesanan.php");
} else { echo "Data belum dapat di ubah!!";
}
}
?><file_sep>/login_form.php
<?php session_start();
if (ISSET($_SESSION['userlogin']))
{
header("location:index.php");
}
else
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Travel</title>
<style type="text/css">
.Menu_Login {
width: 200px;
font-family: "Times New Roman";
font-size: 16px;
margin-top: 10px;
margin-bottom: 10px;
}
.Login {
width: 100px;
font-family: "Times New Roman";
font-size: 24px;
margin-top: 30px;
margin-bottom: 30px;
}
.Note {
font-family: "Times New Roman";
font-style: italic;
font-size: 14px;
color: red;
}
</style>
<body>
<form id="form1" name="form1" method="post" action="login.php">
<table width="400" border="0" align="center" cellpadding="0" cellspacing="0">
<tr>
<td align="center" valign="middle" bgcolor="#FFFFF" class="Login" height="60">LOGIN</td>
</tr>
<tr>
<td bgcolor="#9b9191">
<table width="350" border="0" cellspacing="5" cellpadding="0" align="center">
<tr>
<td width="110" align="right">Username</td>
<td width="235">
<label for="usertxt"></label>
<input name="usertxt" type="text" class="Menu_Login" id="usertxt" />
</td>
</tr>
<tr>
<td align="right">Password</td>
<td>
<label for="pswtxt"></label>
<input name="pswtxt" type="password" class="Menu_Login" id="pswtxt" />
</td>
</tr>
<tr>
<td colspan="2" align="center">
<input name="logbtn" type="submit" id="logbtn" value="Login" />
<br>
Belum punya akun ?
<a href="register.php">Register</a>
</td>
</tr>
</table></td>
</tr>
<tr>
<td class="Note">*Silakan login terlebih dahulu <br>**Apabila belum punya akun, silakan register terlebih dahulu</td>
</tr>
</table>
</form>
</body><file_sep>/Admin/trayek_hapus.php
<?php session_start();
if (ISSET($_SESSION['adminlogin']))
{
require("config.php");
$id_trayek = $_GET['id_trayek'];
$perintah = "DELETE from trayek where id_trayek = '$id_trayek'";
$result = mysql_query($perintah);
if ($result) {
header("location:trayek.php");
} else { echo "Data belum dapat di simpan!!";
}
}
?><file_sep>/booking_proses.php
<?php session_start();
if (ISSET($_SESSION['userlogin']))
{
}
else
header("location:index.php");
require("config.php");
//ambil data dari inputan user
$pool = $_POST['pollist'];
$tujuan = $_POST['tjnlist'];
$jam = $_POST['jamlist'];
$tgl = $_POST['tgltxt'];
$nokur = $_POST['noktxt'];
//ambil id member dari sesi userlogin
$perintah1="select id_member
from member
where username ='".$_SESSION['userlogin']."'";
$hasil1=mysql_query($perintah1);
$data1=mysql_fetch_array($hasil1);
//ambil id trayek dari tabel trayek
$perintah2="select id_trayek
from trayek
where pool ='$pool' and tujuan='$tujuan'";
$hasil2=mysql_query($perintah2);
$data2=mysql_fetch_array($hasil2);
//ambil id jam dari tabel jamberangkat
$perintah3="select id_jam
from jamberangkat
where jam ='$jam'";
$hasil3=mysql_query($perintah3);
$data3=mysql_fetch_array($hasil3);
//ambil id jadwal dari tabel jadwal
$perintah4="select id_jadwal
from jadwal
where id_jam ='$data3[id_jam]' and id_trayek='$data2[id_trayek]'";
$hasil4=mysql_query($perintah4);
$data4=mysql_fetch_array($hasil4);
$perintah = "INSERT INTO pesanan (no_kursi, tanggal_pesan, id_member, id_jadwal)
VALUES ('$nokur','$tgl','$data1[id_member]','$data4[id_jadwal]')";
$result = mysql_query($perintah);
if ($result) {
header("location:booking.php");
} else { echo "Data belum dapat di simpan!!";
}
?><file_sep>/Admin/trayek_data.php
<?php
if (ISSET($_SESSION['adminlogin']))
{
}
else
header("location:index.php");
?>
<html>
<head>
<meta charset="utf-8">
<title>jQuery UI Dialog - Modal confirmation</title>
<link rel="stylesheet" href="style/style.css">
<link rel="stylesheet" href="js/jquery-ui-1.10.4.custom.css">
<script src="js/jquery-1.10.2.js"></script>
<script src="js/jquery.ui.core.js"></script>
<script src="js/jquery.ui.widget.js"></script>
<script src="js/jquery.ui.mouse.js"></script>
<script src="js/jquery.ui.button.js"></script>
<script src="js/jquery.ui.draggable.js"></script>
<script src="js/jquery.ui.position.js"></script>
<script src="js/jquery.ui.dialog.js"></script>
<link rel="stylesheet" href="js/jquery-ui-1.10.4.custom.min.css">
<script>
$(document).ready(function() {
var textPESAN = 'Anda yakin akan menghapus data tersebut ?';
$("#dialog").dialog({
modal: true,
bgiframe: true,
width: 500,
height: 200,
autoOpen: false,
title: 'Konfirmasi'
});
// Set link
$("a.confirm").click(function(link) {
link.preventDefault();
var ambilHREF = $(this).attr("href");
var setingPESAN = $(this).attr("pesan");
var textPESAN = (setingPESAN == undefined || setingPESAN == '') ? pesan_default : setingPESAN;
var gambarICON = '<span class="ui-icon ui-icon-alert" style="float:left; margin:0 5px 0 0;"></span>';
// set kotak dialog
$('#dialog').html('<P>' + gambarICON + textPESAN + '</P>');
$("#dialog").dialog('option', 'buttons', {
"Ya, Hapus" : function() {
window.location.href = ambilHREF;
},
"Batal" : function() {
$(this).dialog("close");
}
});
$("#dialog").dialog("open");
});
});
</script>
<style type="text/css">
form {
font-family: "Segoe UI", "Segoe UI Light";
}
#form1 table {
font-size: 16px;
}
#form1 table tr td p {
font-size: 14px;
}
</style>
<form id="form1" name="form1" method="post">
<table width="250" border="0" align="right">
<tr><hr widht="650" color="black">
<td align="right" valign="middle">
<label>
<input name="schtxt" type="text" id="schtxt" size="40" />
</label>
</td>
<td>
<label>
<input type="submit" name="Submit" value="Pencarian" />
</label>
</span>
</td>
</tr>
</table>
</form>
<table width="650" border="1" cellpadding="0" cellspacing="0" bgcolor="#3e9fdd">
<tr>
<th width="5%" align="left" scope="col" >ID</th>
<th width="30%" align="left" scope="col">Pool</th>
<th width="30%" align="left" scope="col">Tujuan</th>
<th width="25%" align="left" scope="col">Harga</th>
<th width="10%" align="center" scope="col">Aksi</th>
</tr>
<?php
require("config.php");
echo '<div class="CSSTableGenerator">';
$search = $_POST['schtxt'];
$query = "select * from trayek where id_trayek LIKE '%$search%' OR pool LIKE '%$search%' OR tujuan LIKE '%$search%' OR harga LIKE '%$search%'";
$hasil = mysql_query($query);
while ($data = mysql_fetch_array($hasil))
{
echo '<tr>
<td align="left" width="5%" bgcolor="#FFFFFF">'.$data['id_trayek'].'</td>
<td align="left" width="30%" bgcolor="#FFFFFF">'.$data['pool'].'</td>
<td align="left" width="30%" bgcolor="#FFFFFF">'.$data['tujuan'].'</td>
<td align="left" width="25%" bgcolor="#FFFFFF">'.$data['harga'].'</td>
<td align="center" width="10%" bgcolor="#FFFFFF">
<a href="trayek_ubah.php?id_trayek='.$data[id_trayek].'"><img width="15" src="../gambar/Ubah.png" height="15" border="0" valign="middle"></a>
<a href="trayek_hapus.php?id_trayek='.$data[id_trayek].'" class="confirm" pesan="Anda yakin akan menghapus data tersebut ?"><img width="15" src="../gambar/Hapus.png" height="15" border="0" valign="middle"></a></td>
</tr>';
}
echo '</div>';
?><div id="dialog"></div>
</table>
</body>
</html><file_sep>/booking_form.php
<style type="text/css">
.Content {
font-family: "Times New Roman";
font-size: 20px;
color: black;
}
</style>
<form id="form1" name="form1" method="post" action="booking_proses.php">
<table width="500" border="0" cellpadding="0" cellspacing="0" align="center">
<tr>
<td width ="500" height="50" colspan="3" bgcolor="#cdedf6" align="center" valign="middle" class="Content">.: B O O K I N G :.</td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td width="45%" height="50" align="right" valign="top" class="Content">Pool</td>
<td width="10%" align="center" valign="top">:</td>
<td width="45%" align="left" valign="top">
<label for="pollist"></label>
<select name="pollist" size="1" id="pollist">
<?php
require ("config.php");
$perintah="select distinct (pool) from trayek join jadwal using (id_trayek)";
$hasil=mysql_query($perintah);
while ($data = mysql_fetch_array($hasil))
{
?>
<option value="<?php echo "$data[pool]"; ?>"><?php echo "$data[pool]"; }?></option>
</select></td>
</tr>
<tr>
<td align="right" height="50" valign="top" class="Content">Tujuan</td>
<td align="center" valign="top">:</td>
<td align="left" valign="top">
<label for="tjnlist"></label>
<select name="tjnlist" size="1" id="tjnlist">
<?php
require ("config.php");
$perintah="select distinct (tujuan) from trayek join jadwal using (id_trayek)";
$hasil=mysql_query($perintah);
while ($data = mysql_fetch_array($hasil))
{
?>
<option value="<?php echo "$data[tujuan]"; ?>"><?php echo "$data[tujuan]"; }?></option>
</select></td>
</tr>
<tr>
<td align="right" height="50" valign="top" class="Content">Jam Berangkat</td>
<td align="center" valign="top">:</td>
<td align="left" valign="top">
<label for="jamlist"></label>
<select name="jamlist" size="1" id="jamlist">
<?php
require ("config.php");
$perintah="select distinct (jam) from jamberangkat join jadwal using (id_jam)";
$hasil=mysql_query($perintah);
while ($data = mysql_fetch_array($hasil))
{
?>
<option value="<?php echo "$data[jam]"; ?>"><?php echo "$data[jam]"; }?></option>
</select></td>
</tr>
<tr>
<td align="right" height="50" valign="top" class="Content">Tanggal Pesan </td>
<td align="center" valign="top">:</td>
<td align="left" valign="top"><label>
<input name="tgltxt" type="date" id="tgltxt" size="30"/>
</label>
</td>
</tr>
<tr>
<td align="right" height="50" valign="top" class="Content">Nomor Kursi </td>
<td align="center" valign="top">:</td>
<td align="left" valign="top"><label>
<input name="noktxt" type="text" id="noktxt" size="30"/><br>
*Nomor Kursi yang tersedia dari 1 sampai 9
</label>
</td>
</tr>
<tr>
<td align="center" valign="middle" colspan="3" ></td>
<td align="left" valign="top"> </td>
<td align="left" valign="top"> </td>
</tr>
<tr>
<td align="center" valign="middle" colspan="3"><hr color="black"/>
<label><input type="submit" name="Submit" value="Order Tiket" /></label>
</td>
<td align="left" valign="top"> </td>
<td align="left" valign="top"> </td>
</tr>
</table>
</form><file_sep>/Admin/trayek_tambah.php
<?php session_start();
if (ISSET($_SESSION['adminlogin']))
{
require("config.php");
$id_trayek = $_POST['idtxt'];
$pool = $_POST['poltxt'];
$tjn = $_POST['tjntxt'];
$hrg = $_POST['hrgtxt'];
$perintah = "INSERT INTO trayek (id_trayek,pool,tujuan,harga)
VALUES ('$id_trayek','$pool','$tjn','$hrg')";
$result = mysql_query($perintah);
if ($result) {
header("location:trayek.php");
} else { echo "Data belum dapat di simpan!!";
}
}
?><file_sep>/profile_ubah_form.php
<?php
require ("config.php");
$perintah="select * from member where id_member ='".$_GET['id_member']."'";
$hasil=mysql_query($perintah);
$data=mysql_fetch_array($hasil);
?>
<form id="form1" name="form1" method="post" action="profile_ubah_proses.php">
<table width="650" border="0" align="left">
<tr>
<td colspan="3">Form Ubah Data Member <hr color="black" width="650"/></td>
</tr>
<tr>
<td width="30%" align="left" valign="top">ID</td>
<td width="1%" align="left" valign="top">:</td>
<td width="69%" align="left" valign="top"><label for="idtxt"></label>
<?php echo $data['id_member'] ?></td>
</tr>
<tr>
<td align="left" valign="top">Nama </td>
<td align="left" valign="top">:</td>
<td align="left" valign="top"><label>
<input name="namatxt" type="text" id="namatxt" size="40" value="<?php echo $data['nama'] ?>" />
</label>
</span></td>
</tr>
<tr>
<td align="left" valign="top">Alamat</td>
<td align="left" valign="top">:</td>
<td align="left" valign="top"><label for="almtxt"></label>
<textarea name="almtxt" id="almtxt" cols="30" rows="5" value="<?php echo $data['alamat'] ?>"></textarea></td>
</tr>
<tr>
<td align="left" valign="top">Telepon</td>
<td align="left" valign="top">:</td>
<td align="left" valign="top"><label for="tlptxt"></label>
<input type="text" name="tlptxt" id="tlptxt" size="40" value="<?php echo $data['telepon'] ?>" /></td>
</tr>
<tr>
<td align="left" valign="top">Email</td>
<td align="left" valign="top">:</td>
<td align="left" valign="top"><label for="emltxt"></label>
<input type="text" name="emltxt" id="emltxt" size="40" value="<?php echo $data['email'] ?> "/></td>
</tr>
<tr>
<td align="left" valign="top">Username</td>
<td align="left" valign="top">:</td>
<td align="left" valign="top"><label for="usrtxt"></label>
<input type="text" name="usrtxt" id="usrtxt" size="40" value="<?php echo $data['username'] ?>" /></td>
</tr>
<tr>
<td align="left" valign="top">Password</td>
<td align="left" valign="top">:</td>
<td align="left" valign="top"><label for="psstxt"></label>
<input type="password" name="psstxt" id="psstxt" size="40" value="<?php echo $data['password'] ?>" /></td>
</tr>
<tr>
<td align="left" valign="top"> </td>
<td align="left" valign="top"> </td>
<td align="left" valign="top"><hr color="black"/></td>
</tr>
<tr>
<td align="left" valign="top"> </td>
<td align="left" valign="top"> </td>
<td align="left" valign="top">
<label>
<input type="submit" name="Submit" value="Simpan" />
</label>
<label>
<a href="profile.php"><input type="submit" value="Batal" /></a>
</label>
</span></td>
</tr>
</table>
</form>
<file_sep>/Admin/trayek_ubah_proses.php
<?php session_start();
if (ISSET($_SESSION['adminlogin']))
{
require("config.php");
$perintah = "UPDATE trayek set id_trayek = '$_POST[idtxt]',pool = '$_POST[poltxt]', tujuan = '$_POST[tjntxt]', harga = '$_POST[hrgtxt]' where id_trayek = '$_POST[idtxt]'";
$result = mysql_query($perintah);
if ($result) {
header("location:trayek.php");
} else { echo "Data belum dapat di ubah!!";
}
}
?><file_sep>/Admin/trayek_ubah_form.php
<?php
require ("config.php");
$perintah="select * from trayek where id_trayek='".$_GET['id_trayek']."'";
$hasil=mysql_query($perintah);
$data=mysql_fetch_array($hasil);
?>
<form id="form1" name="form1" method="post" action="trayek_ubah_proses.php">
<table width="650" border="0" align="left">
<tr>
<td colspan="3">Form Ubah Data Trayek <hr color="black" width="650"/></td>
</tr>
<tr>
<td width="30%" align="left" valign="top">ID</td>
<td width="1%" align="left" valign="top">:</td>
<td width="69%" align="left" valign="top"><label for="idtxt"></label>
<input name="idtxt" type="text" id="idtxt" size="40" value="<?php echo $data['id_trayek'] ?>" readonly="readonly"/></td>
</tr>
<tr>
<td align="left" valign="top">Pool </td>
<td align="left" valign="top">:</td>
<td align="left" valign="top"><label>
<input name="poltxt" type="text" id="poltxt" size="40" value="<?php echo $data['pool'] ?>"/>
</label>
</span></td>
</tr>
<tr>
<td align="left" valign="top">Tujuan</td>
<td align="left" valign="top">:</td>
<td align="left" valign="top"><label>
<input name="tjntxt" type="text" id="tjntxt" size="40" value="<?php echo $data['tujuan'] ?>"/>
</label>
</span></td>
</tr>
<tr>
<td align="left" valign="top">Harga</td>
<td align="left" valign="top">:</td>
<td align="left" valign="top"><label for="wrntxt"></label>
<input type="text" name="hrgtxt" id="hrgtxt" size="40" value="<?php echo $data['harga'] ?>"/></td>
</tr>
<tr>
<td align="left" valign="top"> </td>
<td align="left" valign="top"> </td>
<td align="left" valign="top"><hr color="black"/></td>
</tr>
<tr>
<td align="left" valign="top"> </td>
<td align="left" valign="top"> </td>
<td align="left" valign="top"><label>
<input type="submit" name="Submit" value="Simpan" />
</label>
</span></td>
</tr>
</table>
</form>
<file_sep>/Admin/jadwal_tambah.php
<?php session_start();
if (ISSET($_SESSION['adminlogin']))
{
require("config.php");
$id_jadwal = $_POST['idtxt'];
$id_trayek = $_POST['tralist'];
$id_jam = $_POST['jamlist'];
$perintah = "INSERT INTO jadwal (id_jadwal,id_trayek,id_jam)
VALUES ('$id_jadwal','$id_trayek','$id_jam')";
$result = mysql_query($perintah);
if ($result) {
header("location:jadwal.php");
} else { echo "Data belum dapat di simpan!!";
}
}
?><file_sep>/Admin/member_ubah_proses.php
<?php session_start();
if (ISSET($_SESSION['adminlogin']))
{
require("config.php");
$perintah = "UPDATE member set nama = '$_POST[namatxt]', alamat = '$_POST[almtxt]', telepon = '$_POST[tlptxt]', email = '$_POST[emltxt]', username = '$_POST[usrtxt]', password = '$_<PASSWORD>]' where id_member = '$_POST[idtxt]'";
$result = mysql_query($perintah);
if ($result) {
header("location:member.php");
} else { echo "Data belum dapat di ubah!!";
}
}
?><file_sep>/Admin/index.php
<?php session_start();
if (ISSET($_SESSION['adminlogin']))
{
header("location:home.php");
}
else
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Travel</title>
<style type="text/css">
.Menu_Kiri {
width: 100px;
font-family: "Segoe UI", "Segoe UI Light";
font-size: 16px;
margin-top: 10px;
margin-bottom: 10px;
}
.Menu_Tengah {
width: 200px;
margin-top: 10px;
margin-left: 10px;
margin-bottom: 10px;
font-family: "Trebuchet MS", Arial, Helvetica, sans-serif;
font-size: 12px;
}
.Menu_Login {
margin-top: 185px;
}
body {
background-image: url(../gambar/bglogin.jpg);
}
.Menu_Login table tr td {
font-family: "Segoe UI", "Segoe UI Light";
font-size: 24px;
color: #000;
}
.Menu_Login table tr td table tr td {
color: #000;
font-size: 16px;
}
.Menu_Login table tr td table {
font-size: 16px;
}
.Menu_Login table tr td {
color: #000;
}
</style>
<body>
<form id="form1" name="form1" method="post" action="login.php">
<div class="Menu_Login">
<table width="437" border="0" align="center" cellpadding="0" cellspacing="0">
<tr>
<td align="center" valign="middle" bgcolor="#3e9fdd">L O G I N
<hr /></td>
</tr>
<tr>
<td bgcolor="#3e9fdd"><table width="437" border="0" cellspacing="5" cellpadding="0">
<tr>
<td width="157" align="right">Username</td>
<td width="265">
<label for="usertxt3"></label>
<input name="usertxt" type="text" class="Menu_Kiri" id="usertxt3" />
</td>
</tr>
<tr>
<td align="right">Password</td>
<td>
<label for="pswtxt"></label>
<input name="pswtxt" type="<PASSWORD>" class="Menu_Kiri" id="pswtxt" />
</td>
</tr>
<tr>
<td> </td>
<td>
<input name="logbtn" type="submit" class="Menu_Kiri" id="logbtn" value="Login" />
</td>
</tr>
</table></td>
</tr>
<tr>
<td> </td>
</tr>
</table>
</div>
</form>
</body> | d7a15bebceab421dc7883580ff097f015131417e | [
"PHP"
]
| 27 | PHP | Ikaw/Website_Travel_SBD | dfbba9cf0924ce28543d2cc5b369fb567c3fa83d | fb43509e2173e615736386627d4413227324b1ca |
refs/heads/master | <repo_name>danchurchthomas/Los_Cedros_Xylaria_2012<file_sep>/ec2012_analysis3.R
###################### community comp matrix #########################
## systematically construct a df that matches all xylaria specimens and cultures
## to their respective name/number, grid, OTU, and life-phase (endo or strom)
## using Roo's latest otu list, SequencesR.csv, and mushroom master spreadsheet.
## This is going to be complicated.
name_etc <- function() {
library(reshape)
setwd('/home/daniel/R/Ec2012')
##start with roo's otu sheet:
aa <- read.csv("roo_otus_6-30-14_r.csv", as.is = TRUE)[,-4]
names(aa)[1] <- 'OTU'
aa <- aa[aa$cf.ID.genus == "Xylaria",]
##empty df
bb <- as.data.frame(matrix(nrow = nrow(aa), ncol = 4))
a <- 0
##now go cell by cell, keep all non-NAs
for (j in 1:nrow(aa)) {
for (i in 4:ncol(aa)) {
if (is.na(aa[j,i]) == FALSE) {
a <- a+1 ##counter
bb[a,1] <- aa[j,i]
bb[a,2] <- aa$cf.ID.genus[j]
bb[a,3] <- aa$cf.ID.species[j]
bb[a,4] <- aa$OTU[j]
}}}
colnames(bb) <- c("Name","Genus","species","OTU")
##now to assign Grids/Flag# to each Xylaria specimen/culture
cc <- read.csv('SequencesR.csv', as.is = TRUE)[,1:3] ##read the spreadsheet with grid #'s, leave out seqs
##note there is an error in the SequencesR.csv, gives the grid info for 875 as 12,
##really this is 12new. I will remove this here:
cc[cc$Name == '875',] <- NA
##now cycle through all the xylaria specimens/cultures we got from roo's latest OTUs,
## and attach Grid numbers from the SequencesR.csv spreadsheet:
dd <- NULL
for (i in 1:nrow(bb)) {
if (any(cc$Name == bb$Name[i], na.rm = TRUE)) {
if (is.na(cc[which(cc$Name == bb$Name[i]),2]) == FALSE) {
dd[i] <- cc[which(cc$Name == bb$Name[i]),2]
}} else {dd[i] <- NA}
}
bb$Grid <- dd
##mostly works, but not finding some: '78.4.1' in the SequenceR, for instance
##Not a problem, because culture names have their grid in the name, hope nothing else is missing
## attach endophyte/stromata designation
##cultures
bb$EorS <- NA
bb[grep('\\..\\.', bb$Name),]$EorS <- 'E' #use the periods in culture names to tell them apart
##endos everything else?
bb[is.na(bb$EorS),]$EorS <- 'S' ####doesn't work
##filling the holes in grid info:
##first, check endos:
bb[is.na(bb$Grid) & bb$EorS == 'E',] ##78.4.1 seems to be the only one missing, plug it in
bb[bb$Name == '78.4.1',]$Grid <-78
##the stromata are a lot messier...
##read in a pruned version of mushroom master list, with just the stromata
## found in the plot, at a flag, not including the "new" flag we declared
## near plot 12, can't use this for spatial analysis. Here goes...
ee <- read.csv('mush_mast_abbrev.csv', as.is = TRUE)
names(ee) <- c('Where', 'Grid', 'Name')
##just plots from that have numerical grid info this removes some points that just say 'BRL',
##but these are also lacking grid data, so foo: 1064, 1067, 1068, 1130, all of the R collections
##also 's.n.' specimens these points lack grid info will be removed, what are they? Also
##of interest is the collection without a name/number at plot 22, found on a leaf. Doubt it is
##a xylaria, but I will ask. For now, it stays out.
##so now we use this ee dframe to assign grid numbers to our stromata (better than SequencesR.csv for stromata)
bb[bb$EorS == 'S',]$Grid <- NA ##clear out old Grid info for stromata, to be filled in below in only the stromata we want
for (i in 1:nrow(bb)) {
if (any(ee$Name == bb$Name[i]) == TRUE) {
bb$Grid[i] <- ee[ee$Name == bb$Name[i],2]
}}
bb <- na.omit(bb) ##and get rid of specimens with NAs, should be all the ones from other years or not in our sampling scheme
##for the record, here are the OTUs that are in Roo's latest OTU sheet that are thrown out by me for
##our spatial analysis:
#br <- bb[bb$Name %in% ff$Name == FALSE,]
#save(br, file = 'OTUs_removed_7-22-14.RDATA')
rownames(bb) <- 1:nrow(bb)
mgo <- bb
mgo$OTU <- as.numeric(mgo$OTU)
mgo$Grid <- as.integer(mgo$Grid)
#save(mgo, file = "mgo.rdata")
#write.csv(mgo, file = "mgo.csv")
return(bb)
##and that is our new reference sheet, updated as of 5/21/2014
## This was a pain in the ass. goddamit, when I design my next study, specimens names will be simple numbers
}
################ spco #####################
spco2 <- function() {
setwd("/home/daniel/R/Ec2012/")
##lets write an aggregate function for reshape, that will categorize whether or not we have
##all stromata, all endophytes, both, or neither.
spco_code <- function(value){
if (length(value) == 0) {a <- 0}else{
if (all(value == 'S')) {a <- 1}else{
if(all(value == 'E')) {a <- 2}else{
a <- 3}}}
return(a)
}
setwd('/home/daniel/R/Ec2012')
library(reshape)
load('mgo.rdata')
spco <- cast(mgo, Grid ~ OTU, value = 'EorS', fun.aggregate = spco_code)
##wow, that actually worked. I don't totally understand the aggregate function, but okay.
##To fit into the old code for randomizations and such, fill out the zero grids
## and get rid of grid column:
##empty df
aa <- mat.or.vec(nr = 120, nc = ncol(spco)-1)
aa <- as.data.frame(aa)
rownames(aa) = 1:120; colnames(aa) <- colnames(spco[,-1])
##now fill with the spco.2 data
for (i in spco$Grid) {
aa[i,] <- spco[spco$Grid == i,-1]
}
spco <- aa
#save(spco, file = 'spco.rdata')
#write.csv(spco, file = 'spco.csv')
return(spco)
}
################# spatial points matrix #######################
spmat <- function(){
setwd("/home/daniel/R/Ec2012/")
library(sp)
plot_name <- 1:120
yy <- c(rep(seq(from = 2.5, to = 52.5, by = 5), times = 10),seq(from = 2.5, to = 47.5, by = (5))) #and similar for x-axis, in multiples of 10
xx <- c(rep(seq(from = 5, to = 95, by = 10), each = 11), rep(105, times = 10))
losced_mat <- cbind(xx,yy)
row.names(losced_mat) <- plot_name
losced_pts <-as.data.frame(losced_mat)
losced_sp <- SpatialPoints(losced_mat)
summary(losced_sp)
bbox(losced_sp)
write.csv(losced_pts, file = "losced_pts.csv")
save(losced_sp, file = 'losced_sp.rdata')
save(losced_pts, file = 'losced_pts.rdata')
return(losced_pts)
}
############# endophyte dataframe ##################
EndoOnly <- function(){
setwd("/home/daniel/R/Ec2012/")
load('spco.rdata')
losced_endo <- matrix(nrow = 120, ncol = length(spco[1,]))
for (j in 1:length(spco[1,])) {
for (i in 1:120) {
if (spco[i,j] == 2 | spco[i,j] == 3) {losced_endo[i,j] <- 1
} else {losced_endo[i,j] <- 0}
}}
losced_endo <- as.data.frame(losced_endo)
colnames(losced_endo) <- colnames(spco); rownames(losced_endo) <- 1:120
#write.csv (losced_endo, file = "endo_pa.csv")
#save(losced_endo, file = 'losced_endo.rdata')
}
############ stromata matrix ###################
StromOnly <- function(){
setwd("/home/daniel/R/Ec2012/")
load('spco.rdata')
losced_strom <- matrix(nrow = 120, ncol = length(spco[1,]))
for (j in 1:length(spco[1,])) {
for (i in 1:120) {
if (spco[i,j] == 1 | spco[i,j] == 3) {losced_strom[i,j] <- 1
} else {losced_strom[i,j] <- 0}
}}
losced_strom <- as.data.frame(losced_strom)
colnames(losced_strom) <- colnames(spco); rownames(losced_strom) <- 1:120
#write.csv(losced_strom, file = "strom_pa.csv")
#save(losced_strom, file = 'losced_strom.rdata')
}
############Individual species graphics ##############
##lets make some maps!
otu_maps <- function(){
setwd("/home/daniel/R/Ec2012/")
library(sp)
load('spco.rdata')
load('losced_sp.rdata')
load('mgo.rdata')
for (j in 1:ncol(spco)) {
losced_cd.j <- data.frame(spco[,j]); colnames(losced_cd.j) = "phase"
losced_spcd.j <- SpatialPointsDataFrame(losced_sp, losced_cd.j, match.ID = TRUE)
plcols <- c(0,"red","green","purple")
plsymb <- c(1, 23, 22, 21)
setwd("/home/daniel/R/Ec2012/sp_grids/grids_jpg")
filename.j <- paste("OTU",colnames(spco)[j],".jpg", sep = "")
jpeg(filename.j)
title1.j <- paste(mgo[mgo$OTU == colnames(spco)[j],2], mgo[mgo$OTU == colnames(spco)[j],3])
title2.j <- paste("OTU",colnames(spco)[j], sep = " ")
plot(losced_spcd.j, pch = plsymb[(losced_spcd.j$phase + 1)], cex = 2, bg = plcols[(losced_spcd.j$phase + 1)])
text(x = 55, y = 65, labels = title1.j, cex = 2)
text(x = 25, y = -10, labels = title2.j, cex = 1.5)
legend(x = 70, y = -2.5, leg = c("Decomposer", "Endophyte", "Both"), pch = c(23,22,21), pt.cex = 1., pt.bg = c("red","green","purple"))
dev.off()
}
setwd("/home/daniel/R/Ec2012/")
}
##surprisingly, that worked.
#############species accumulation curves, adapted from Roo ##############
acc_curves <- function() {
setwd("/home/daniel/R/Ec2012/")
library(reshape)
library(vegan)
load('losced_endo.rdata')
load('losced_strom.rdata')
##already have purely stromata and endophyte comm matrices, of just Xylaria:
endoacc <- specaccum(losced_endo)
stromacc <- specaccum(losced_strom)
png('ec2012_xylaria_acc.png')
#pdf('ec2012_xylaria_acc.pdf')
par("mar"=c(5,5.5,3,2)+1)
plot(endoacc, ci.type="polygon", ci.col="#9a9a9a39", lwd=2, ylim=c(0,41), ylab="", xlab="", main="")
par(new=T)
plot(stromacc, ci.type="polygon", ci.col="#858585DB", lwd=2, ylim=c(0,41), ylab="", xlab="", main="")
title(ylab="OTUs Recovered", xlab="Plots", cex.lab=2)
legend(x = -2, y = 42, legend=c("Endophytic Isolates","Saprotrophic Specimens"), pch=15, cex=.8, col=c("#9a9a9a39","#858585DB"))
dev.off()
specpool(losced_strom)
## Species chao chao.se jack1 jack1.se jack2 boot boot.se n
##All 36 52.33333 11.70549 49.88333 4.211212 57.79958 42.18927 2.302961 120
specpool(losced_endo)
## Species chao chao.se jack1 jack1.se jack2 boot boot.se n
##All 5 5 0 7.975 1.717617 10.925 6.105077 0.8337007 120
}
##okay, that wasn't too bad, thanks to Vegan
##now need to redo Roo's bar graph
#######################Frequency graph(s)######################
##Roo constructed a frequency plot, instead of an absolute abundance
##graph.
##get frequency of discovery of each OTU, as endo and strom
freq_graph <- function(){
setwd('/home/daniel/R/Ec2012')
load('losced_strom.rdata')
load('losced_endo.rdata')
load('mgo.rdata')
a <- colSums(losced_strom)/120
b <- colSums(losced_endo)/120
cc <- cbind(a,b) ##make a matrix, keep their OTU#s as a names
cc <- t(cc) ##transpose
cc <- cc[,order(-cc[1,])] ##order it by stromata freq
##works alright. now the names...this will be messy
dd <- dimnames(cc)[[2]] ##lift the (OTU)names off of the matrix
ee <- NULL; ff <- 0
gg <- as.character(mgo$OTU) ##cuz OTUs are numbers, causing funky decimals
for (i in dd){
ff <- ff+1 ##counter, since i is wonky OTU names
##dig which genus/species belongs to each OTU, glue them together
ee[ff] <- paste(mgo[gg == i,][1,2], mgo[gg == i,][1,3])
}
##so now we have a list of names that should match the order
##as the OTUs appear on the graph
png(file = 'specacc2.png',width = 7, height = 3.5, units = 'in', res = 700)
#pdf(file = 'specacc2.pdf',width = 7, height = 3.5)
mp <- barplot(cc, beside =TRUE, col=c("lightgrey","black"), names.arg = rep("", times = ncol(cc)*2),
axes = FALSE, cex.lab = 1.25, space = c(0,.5), ylab = "Frequency")
axis(2, at = c(0,.05,.1,.15,.2,.25), labels = c(0,.05,.1,.15,.2,.25), las = 2, xpd = NA)
text(colMeans(mp), srt = 45, labels = ee, y = -.008, cex = .75, xpd = NA, adj = 1)
legend("topright", c("Endophyte","Saprotroph"), cex=.8,
bty="n", fill=c("black","lightgrey"));
dev.off()
}
########### Nearest neighbors, take 5238 or whatever #################
##for each clade, stromata points and stromphyte points will have to be considered independently, then combined
##the flow: nearest neighbor analysis (NNA) of stromata --> NNA of stromphytes --> NNA of (stromata = stromphytes) ----
## --> stromphyte NNA of stromata --> Stromata NNA of stromphyte
##with these last two, we can address the FA
##code is messy, complicated, but I'll clean it up if we need it in the future.
fungal_cluster <- function(nenes, cycles) {
#########################Stromata NNA ######################
setwd("/home/daniel/R/Ec2012/")
library(vegan); library(sp)
load('mgo.rdata')
load('spco.rdata')
load('losced_strom.rdata')
load('losced_endo.rdata')
load('losced_sp.rdata')
pval.S_S <- NULL
strom_plots <- vector("list", length(spco[1,])) #individual OTU strom spatial plots will be stored here
for (i in 1:length(spco[1,])) {
## for each OTU, make a matrix of all points where that OTU is present
strom.i <- as.matrix(losced_strom[losced_strom[,i] == 1,i]); rownames(strom.i) <- rownames(losced_strom[losced_strom[,i] == 1,])
bb <- as.numeric(rownames(strom.i)) ##get the rows as numbers so as to...
pts.strom.i <- losced_pts[bb,] #get spatial info for all the points with our fungus
strom_plots[[i]] <- bb #store this for downstream analyses of both endos and stroms
if (sum(strom.i[,1]) < 2) {pval.S_S[i] <- NA} else { #if there are one or less fungi in the plot in this clade, stop here
dist.strom.i <- as.matrix(dist(pts.strom.i)) ##make a distance matrix of this OTU's stromata
##now sort this, create a matrix for containing all flag points with stromata of this OTU, and the distance to their
##nearest neighbors (= nenes)
cc <- NULL; dd <- matrix(nrow = nrow(strom.i), ncol = nenes)
for (j in 1:length(strom.i)) {
cc <- sort(dist.strom.i[,j])[2:(nenes+1)]
dd[j,] <- cc
}
##for each class of neighbor (1rst, 2nd, 3rd, etc), create averages for the
## entire sample area (the BRL plot) of this OTU
nn_means.strom <- colMeans(dd)
##sweet, so this seems to work for any OTU, with any number of neighbors.
## at this point, OTU #i has a matrix showing the nenes of all points with stromata,
## an average distance in all neighbor classes (our test statistics), and it has
##added its list of points with stromata to a list to be used later known as 'strom_plots[[i]]'
#####Stromata randomization#####
nn_means.ran <- matrix(ncol = nenes, nrow = cycles) ##empty bin for
for (k in 1:cycles) {
if (length(strom.i) != 0) { ##if there is more than one stromata for this OTU, then...
random_pts <- sample(1:120, length(strom.i), replace = FALSE) ##make a random, hypethical sampling area, same # of points w/stromata
random_pts_mat <- losced_pts[random_pts,] ## give these random stromata points geo info
dist.ran <- as.matrix(dist(random_pts_mat)) #a distance matrix of random points
##as above, sort and
cc.ran <- NULL; dd.ran <- matrix(nrow = length(strom.i), ncol = nenes)
for (j in 1:length(strom.i)) {
cc.ran <- sort(dist.ran[,j])[2:(nenes+1)]
dd.ran[j,] <- cc.ran
}
##store each permutation ('cycle') result
nn_means.ran[k,] <- colMeans(dd.ran)} else {nn_means.ran[k,] <- NA}
}
## so now we have a bunch of randomly generated equivalents to our single, real
## nearest neighbor classes from the section above. This is our distribution
## for our test statistics.
########## stromata p-values #################
aa <- nn_means.ran
for (h in 1:nenes) {
aa <- aa[aa[,h] <= nn_means.strom[h], , drop = FALSE]
} ####this recursively subsets the randomized dataframe, to ¨nenes¨-number-of-nearest-neighbors
pval.S_S.i <- length(aa)/length(nn_means.ran)
pval.S_S[i] <- pval.S_S.i #storing the pvalues
}}
## so we have a p-val for this OTU, for stromata clustering to stromata
## if I were writing this all over again, I would break up the function here
## but as is, I don't want to disturb things too much.
##################### Endophyte NNA ######################
## nene number set above
pval.E_E <- NULL
endo_plots <- vector("list", length(spco[1,])) #endo spatial plots will be stored here
for (i in 1:length(spco[1,])) {
endo.i <- as.matrix(losced_endo[losced_endo[,i] == 1,i]); rownames(endo.i) <- rownames(losced_endo[losced_endo[,i] == 1,])
#create a matrix of just endophytes from i clade
bb <- as.numeric(rownames(endo.i))
pts.endo.i <- losced_pts[bb,] #get spatial info for all the points with our fungus
endo_plots[[i]] <- bb #use for downstream analyses of both endos and stroms
if (sum(endo.i[,1]) < 2) {pval.E_E[i] <- NA} else { #if there are one or less fungi in the plot in this clade, stop here
dist.endo.i <- as.matrix(dist(pts.endo.i))
cc <- NULL; dd <- matrix(nrow = length(endo.i), ncol = nenes)
for (j in 1:length(endo.i)) {
cc <- sort(dist.endo.i[,j])[2:(nenes+1)]
dd[j,] <- cc
}
nn_means.endo <- colMeans(dd)
###sweet, so this seems to work for any clade, with any number of neighbors.
#####endo randomization#####
nn_means.ran <- matrix(ncol = nenes, nrow = cycles)
for (k in 1:cycles) {
if (length(endo.i) != 0) {
random_pts <- sample(1:120, length(endo.i), replace = FALSE)
random_pts_mat <- losced_pts[random_pts,]
dist.ran <- as.matrix(dist(random_pts_mat)) #a distance matrix of random points
cc.ran <- NULL; dd.ran <- matrix(nrow = length(endo.i), ncol = nenes)
for (j in 1:length(endo.i)) {
cc.ran <- sort(dist.ran[,j])[2:(nenes+1)]
dd.ran[j,] <- cc.ran
}
nn_means.ran[k,] <- colMeans(dd.ran)} else {nn_means.ran[k,] <- NA} #averages first, second...neighbor for each randomly generate plot and stores it
}
########## endo p-values #################
aa <- nn_means.ran
for (h in 1:nenes) {
aa <- aa[aa[,h] <= nn_means.endo[h], , drop = FALSE]
} ####this recursively subsets the randomized dataframe, to ¨nenes¨-number-of-nearest-neighbors
pval.E_E.i <- length(aa)/length(nn_means.ran)
pval.E_E[i] <- pval.E_E.i #storing the pvalues
}}
## Now I need a way to overlay the two life-history phases and analyze them from both "directions"
## start by overlaying the two spatial dataframes, endophyte and stromata
pval.S_E <- NULL; pval.E_S <- NULL
for (i in 1:length(spco[1,])) {
strom_c.i <- strom_plots[[i]] #pull clade i out of lists generated by previous all-endo/all-strom NNAs
endo_c.i <- endo_plots[[i]]
if (length(strom_c.i) == 0 | length(endo_c.i) == 0) {pval.S_E[i] <- NA; pval.E_S[i] <- NA} else {
combo_c.i <- strom_c.i[which (strom_c.i %in% endo_c.i == TRUE)] #shows us which pts have both endo and strom, don't need this now, maybe later.
pts.strom_c.i <- losced_pts[strom_c.i,]
pts.endo_c.i <- losced_pts[endo_c.i,]
######################### Stromata, nearest Endophyte neighbor ########################
dd <- matrix(nrow = length(strom_c.i), ncol = nenes)
for (k in 1:length(pts.strom_c.i[,1])) {
dist.S_E.k <- as.matrix(dist(rbind(pts.strom_c.i[k,], pts.endo_c.i))) #binds one stromata point to all the endos, constructs distance matrix
for (j in 1:nenes) {
dd[k,(j)] <- sort(dist.S_E.k[,1])[j+1] #extracts nearest endophyte neighbors to this one stromata
}}
nn_means.S_E <- colMeans(dd)
######################### Endophyte, nearest stromata neighbor ########################
dd <- matrix(nrow = length(endo_c.i), ncol = nenes)
for (k in 1:length(pts.endo_c.i[,1])) {
dist.E_S.k <- as.matrix(dist(rbind(pts.endo_c.i[k,], pts.strom_c.i))) #binds one endophyte point to all the strom, constructs distance matrix
for (j in 1:nenes) {
dd[k,(j)] <- sort(dist.E_S.k[,1])[j+1] #extracts nearest endophyte neighbors to this one endoata
}}
nn_means.E_S <- colMeans(dd)
###################################### randomization S_E (& E_S?) ######################################
#####Stromata randomization##
##make a big pile of random plots with same number of stromata
pts.strom_c.ran <- vector("list", length = cycles)
if (length(strom_c.i) != 0) {
for (k in 1:cycles) {
random_pts <- sample(1:120, length(strom_c.i), replace = FALSE)
pts.strom_c.ran[[k]] <- losced_pts[random_pts,]
}}
#####Endophyte randomization##
##make a big pile of random plots with same number of endophytes
pts.endo_c.ran <- vector("list", length = cycles)
if (length(endo_c.i) != 0) {
for (k in 1:cycles) {
random_pts <- sample(1:120, length(endo_c.i), replace = FALSE)
pts.endo_c.ran[[k]] <- losced_pts[random_pts,]
}}
########Stromata, randomized nearest endophyte neighbor averages############
nn_means.S_E.ran <- matrix(nrow = cycles, ncol = nenes)
for (j in 1:cycles) {
dd.ran <- matrix(nrow = length(strom_c.i), ncol = nenes)
for (l in 1:length(pts.strom_c.i[,1])) {
dist.S_E.ran <- as.matrix(dist(rbind(pts.strom_c.ran[[j]][l,], pts.endo_c.ran[[j]]))) #take one point from endophyte, tack it onto all the endos, make a distance matrix
for (h in 1:nenes) {
dd.ran[l,h] <- sort(dist.S_E.ran[,1])[h+1] #extracts nearest endophyte neighbors to this one stromata
}}
nn_means.S_E.ran[j,] <- colMeans(dd.ran)}
########Endophyte, randomized nearest stromata neighbor averages############
nn_means.E_S.ran <- matrix(nrow = cycles, ncol = nenes)
for (j in 1:cycles) {
dd.ran <- matrix(nrow = length(endo_c.i), ncol = nenes)
for (l in 1:length(pts.endo_c.i[,1])) {
dist.E_S.ran <- as.matrix(dist(rbind(pts.endo_c.ran[[j]][l,], pts.strom_c.ran[[j]]))) #take one point from endophyte of randomly generated plots, tack it onto all the stroms, make a distance matrix
for (h in 1:nenes) {
dd.ran[l,h] <- sort(dist.E_S.ran[,1])[h+1] #extracts nearest endophyte neighbors to this one stromata
}}
nn_means.E_S.ran[j,] <- colMeans(dd.ran)}
###################################### p-values S_E & E_S ########################################
########## Stromata, nearest endophyte neighbor (S_E) p-values #################
aa <- nn_means.S_E.ran
for (h in 1:nenes) {
aa <- aa[aa[,h] <= nn_means.S_E[h], , drop = FALSE]
} ####this recursively subsets the randomized dataframe, to ¨nenes¨-number-of-nearest-neighbors
pval.S_E[i] <- length(aa)/length(nn_means.S_E.ran) #store it
########## Endophyte, nearest endophyte neighbor (E_S) p-values #################
aa <- nn_means.E_S.ran
nn_means.E_S.ran
for (h in 1:nenes) {
aa <- aa[aa[,h] <= nn_means.E_S[h], , drop = FALSE]
} ####this recursively subsets the randomized dataframe, to ¨nenes¨-number-of-nearest-neighbors
pval.E_S[i] <- length(aa)/length(nn_means.E_S.ran) #store it
}}
##tie OTUs to Ju's IDs, export pvalues
Ju_ID <- NULL
aa <- 0
for (k in colnames(spco)) {
aa <- aa + 1
Ju_ID[aa] <- paste(mgo[mgo$OTU == k,][1,2], mgo[mgo$OTU == k,][1,3])
}
dan_NNA <- as.data.frame(cbind(Ju_ID, colnames(spco), pval.S_S, pval.E_E, pval.S_E, pval.E_S))
colnames(dan_NNA) <- c("Species","OTU","Pval.S-S","Pval.E-E","Pval.S-E","Pval.E-S")
save(dan_NNA, file = 'all_fung_pval.rda')
##both_lf_pval <- dan_NNA[!is.na(dan_NNA$pval.S_E),] ##gives us just the fungi with both lifecycles
##save(both_lf_pval, file = 'fungclust_pval.rda')
return(dan_NNA)
}
################### make environmental data frame ##############################
## will construct an environmental data object that will be used for the water
## and environmental analyses
enviro_df <- function(){
setwd("/home/daniel/R/Ec2012")
library(sp)
library(vegan)
env <- read.csv("/home/daniel/R/Ec2012/environmental/plot_env_data.csv")
env$eastvec <- cos(env$Aspect*pi/180) + 1; env$northvec <- sin(env$Aspect*pi/180) + 1
env <- env[,-c(1,3,6)] ##get rid of flag# (redundant) and path info (I´m not analysing)
#save(env, file = 'env.rda')
return(env)
}
################################################ water 2.0 #################################################
## so, lets see if endophytes are tending to cluster around water
## this will mimic the stromata-around-endophyte analysis
## revising this to fit the dependencies and variable names of ec2012_analysis3.R -Dan 7/28/14
## need all of these for the water analyses functions:
setwd('/home/daniel/R/Ec2012')
load('spco.rdata')
load('losced_strom.rdata')
load('losced_endo.rdata')
load('losced_pts.rdata')
load('env.rda')
stream_geo <- function() {
##need geographical info for the stream
env$xx <- losced_pts$xx; env$yy <- losced_pts$yy
##collapse this to just geo info of pts with a stream?
stream_pts <- env[env$Stream == 1,][,6:7]
#save(stream_pts, file = 'stream_pts.rda')
return(stream_pts)
}
########## finding nene averages from data #############
##make a function that generates the average distance to nearest fungal observation of a given OTU to each point on the stream
nearest_stream <- function(which_com, nenes, OTU) {
load('stream_pts.rda')
nearest_OTUs <- matrix(nrow = nrow(stream_pts), ncol = nenes)
##make/reset our storage bin for distances of nearest OTU observations from individual river flags
##get geo info for OTU of interest
## get the geo info for points that contain our OTU:
ptsOTU.i <- losced_pts[which_com[,which(colnames(which_com) == OTU)] > 0,]
##now we want to find the nenes of this OTU to each spot on the stream.
##gotta cycle through each stream flag, here is the basic kernel:
stream.j <- NULL
for (j in 1:nrow(stream_pts)) {
stream.j <- stream_pts[j,]; rownames(stream.j) <- "stream.j"
#this takes j-th row out of streams and gives a new name so rbind below won't get mad
s.j.OTUs <- rbind(stream.j,ptsOTU.i) #stacks the j-th line of stream onto all of the geo info of our OTU observations
dist.streamOTU.i <- as.matrix(dist(s.j.OTUs)) #constructs a distance matrix from this
nearest_OTUs.j <- sort(dist.streamOTU.i[1,])[2:(nenes+1)]
##sorts distances from stream to all OTU observations in ascending order, to number of nearest neighbors (+1, 1rst is self-ref)
##this needs to get stored as one row in a matrix that will hold all the nenes, columns to be averaged later:
nearest_OTUs[j,] <- nearest_OTUs.j
##and process repeated to get the nenes of other stream pts
}
stream_nene_avg_dist <- colMeans(nearest_OTUs)
##this averages the distances of nearest observations of OTU with every flag in contact with the stream
return(stream_nene_avg_dist)
}
############## randomizations ###############
##make a function that generates a distribution of averages distances of randomly distributed observations for a given otu.
generate_random_dist <- function(which_com, nenes, OTU, cycles) {
load('stream_pts.rda')
##nenes = number of nearest neighbors, which_com is the community matrix of choice, etc.etc.
##summing up the number of plots with a given OTU:
how_many_otu.i <- sum(which_com[,which(colnames(which_com) == OTU)] > 0)
ran.stream_nene_avg_dist <- matrix(nrow = cycles, ncol = nenes)
for (k in 1:cycles) { #from here each cycle is one random map and nenes from it, to be stored for the dist
random_pts <- sample(1:nrow(losced_pts), how_many_otu.i, replace = FALSE) #create the "observations"
random_pts_mat <- losced_pts[random_pts,] #geo info of our random observations
##now we want to find the nearest random observations to each spot on the stream.
##gotta cycle through each stream flag:
stream.ran.j <- NULL
ran.nearest_OTUs <- matrix(nrow = nrow(stream_pts), ncol = nenes) #bin for the nenes of each point in the stream, for this iteration
rownames(ran.nearest_OTUs) <- rownames(stream_pts)
for (j in 1:nrow(stream_pts)) {
stream.ran.j <- stream_pts[j,]; rownames(stream.ran.j) <- "stream.ran.j"
#this takes j-th row out of streams and gives a new name so rbind below won't get mad
ran.s.j.OTUs <- rbind(stream.ran.j,random_pts_mat) #stacks the j-th line of stream onto all of the geo info of our OTU observations
ran.dist.streamOTU.j <- as.matrix(dist(ran.s.j.OTUs)) #constructs a distance matrix from this
ran.nearest_OTUs.j <- sort(ran.dist.streamOTU.j[1,])[2:(nenes+1)]
##sorts distances from stream to all OTU observations in ascending order, to number of nearest neighbors (+1, 1rst is self-ref)
##this needs to get stored as one row in a matrix that will hold all the nenes, columns to be averaged later:
ran.nearest_OTUs[j,] <- ran.nearest_OTUs.j
##and process repeated to get the nenes of other stream pts
}
ran.stream_nene_avg_dist[k,] <- colMeans(ran.nearest_OTUs) }
return(ran.stream_nene_avg_dist)}
#####################generate stream pvalues##########################
generate_stream_pval <- function(which_com, nenes, OTU, cycles) {
how_many_otu.i <- sum(which_com[,which(colnames(which_com) == OTU)] > 0)
if (how_many_otu.i != 0) {
nearest_stream.1 <- nearest_stream(which_com, nenes, OTU)
generate_random_dist.1 <- generate_random_dist(which_com, nenes, OTU, cycles)
aa <- generate_random_dist.1
for (h in 1:nenes) {
aa <- aa[aa[,h] <= nearest_stream.1[h], , drop = FALSE]
} ####this recursively subsets the randomized dataframe, to ¨nenes¨-number-of-nearest-neighbors
##each step of the process, it retains only those with nearer h-th nearest neighbors than (or =) the data from the OTU
pval.stream <- length(aa)/length(generate_random_dist.1)
#print(aa)
#print(nearest_stream.1)
#print(generate_random_dist.1)
}
else {
pval.stream <- NA
}
return(pval.stream)
}
######################### sensitivity of our water pval-generator #########################
##a function to easily test out our p-val generator at different #'s of nearest neighbors
test.stream.pval <- function(which_com, nenes, OTU, cycles) {
dd <- NULL
for(w in 1:nenes) {
if (w > sum(which_com[,which(colnames(which_com) == OTU)] > 0)) {dd[w] <- NA} else {
dd[w] <- generate_stream_pval(which_com, w, OTU, cycles)
}}
return(dd)
}
##now lets see if life_history matters
## a function to compare endos, stroms, and both
test.stream.lifehist <- function(nenes, OTU, cycles) {
aa <- test.stream.pval(losced_endo, nenes, OTU, cycles)
bb <- test.stream.pval(losced_strom, nenes, OTU, cycles)
cc <- test.stream.pval(spco, nenes, OTU, cycles)
dd <- cbind(aa,bb,cc)
compare <- as.data.frame(dd); colnames(compare) <- c("endo","strom","both")
return(compare)
}
############ drawing the stream ##############
##need a visual of the stream
draw_water <- function(){
library(sp)
load('losced_sp.rdata')
load('env.rda') ##get env data
stream <- env[,3, drop = FALSE] #keep only stream data
stream$pch <- 21; stream$pch[which(stream$Stream == 1)] <- 22 ##change symbols
stream$color <- "00000000"; stream$color[which(stream$Stream == 1)] <- "blue" ##and color
##set up our spatial dataframe
losced_stream_pts <- SpatialPointsDataFrame(losced_sp, stream, match.ID = TRUE)
#jpeg("water_plot.jpeg")
plot(losced_stream_pts, pch = losced_stream_pts$pch, cex = 2, bg = losced_stream_pts$color)
title("The path of a stream \n through Los Cedros plot")
legend("bottomright", leg = c("Water"), pch = c(22), pt.cex = 2, pt.bg = c("blue"))
#dev.off()
save(losced_stream_pts, file = 'losced_stream_pts.rda') ##added 8/10/14
}
################################### Environmental Analysis ################################
#################### species x habitat matrix ###########################
specieshab <- function() {
setwd("/home/daniel/R/Ec2012")
load('mgo.rdata')
load('losced_pts.rdata')
load('env.rda')
##first, need to get a observation x habitat matrix, with columns for species ID and life-stage (endo/strom)
##these last two will be excluded as variables from the ordination, but used to color-code points
##in the final graphic
##we don't want to repeat flag# when one point had the same fungi multiple times, this may give the
##impression of habitat-specialization that is not actually present
##so only one endophyte and one stromata observation of each species from each flag
##order our observations by grid, then OTU, then lifestage
ec2012_obs <- mgo[order(mgo$Grid, mgo$OTU, mgo$EorS),]
##an empty dataframe to begin filtering out repeats of OTUs in grids
no_repeats <- as.data.frame(matrix(nrow = nrow(mgo), ncol = ncol(mgo)))
colnames(no_repeats) <- colnames(ec2012_obs)
no_repeats[1,] <- ec2012_obs[1,] # get the dataframe started
#now write a loop that looks through the ordered dataframe, sees if the OTU above it is the same, =repeated, if so it throws this out as NA:
for (i in 2:nrow(no_repeats)) {
if (ec2012_obs$Grid[i] == ec2012_obs$Grid[i-1] & ec2012_obs$OTU[i] == ec2012_obs$OTU[i-1] & ec2012_obs$EorS[i] == ec2012_obs$EorS[i-1]) { ##checks the line above for identical info
no_repeats[i,] <- NA
} else {
no_repeats[i,] <- ec2012_obs[i,]}
}
##seems to work. now get rid of NAs:
no_repeats <- na.omit(no_repeats)
##attach environmental data
nmes <- c(colnames(no_repeats), colnames(env), colnames(losced_pts))
no_repeats[,7:13] <- NA #make room for env info and geo info
colnames(no_repeats) <- nmes
##make a loop that matches up the three dataframes
for (i in 1:nrow(no_repeats)) {
no_repeats[i,7:11] <- env[which(rownames(env) == no_repeats$Grid[i]),] #find the row of env data to attach, using flag/grid#
no_repeats[i,12:13] <- losced_pts[which(rownames(losced_pts) == no_repeats$Grid[i]),]
}
##we need a column for proximity to water: this will be the distance of an observation
##from the closest stream point.
load('stream_pts.rda')
#make a small function that finds the closest stream pt to a given flag/point on our map:
str_dist <- function (pt){
load('stream_pts.rda')
dist_mat <- rbind(losced_pts[pt,], stream_pts) #put flag# on top of stream pts
rownames(dist_mat) <- c("pt",rownames(stream_pts)) #fix names
dist_mat <- as.matrix(dist(dist_mat)) #make a distance matrix (Euclid)
nearest_stream <- sort(dist_mat[1,])[2] #find the nearest stream pt
return(nearest_stream)
}
for (i in 1:nrow(no_repeats)) {no_repeats$Stream[i] <- str_dist(no_repeats$Grid[i])}
##attach host data:
trees <- read.csv(file = "trees_R.csv") ##tree data for each grid
##now go through the rows of the environmental dframe we're making, find the tree host
##from this "trees" dframe, plug it in
no_repeats$host <- NA
for (i in 1 : nrow(trees)) {
no_repeats[no_repeats$Grid == i,]$host[] <- as.character(trees$Genus_sp[i])
}
##get rid of specimen names and rename the dataframe:
Spec_Hab <- no_repeats[,-1]
##make some columns factors for the analysis to come
Spec_Hab$OTU <- as.factor(Spec_Hab$OTU)
Spec_Hab$Slope <- as.numeric(Spec_Hab$Slope)
Spec_Hab$EorS <- as.factor(Spec_Hab$EorS)
Spec_Hab$host <- as.factor(Spec_Hab$host)
write.csv(Spec_Hab, file = 'Spec_Hab.csv')
save(Spec_Hab, file = 'Spec_Hab.rda')
return (Spec_Hab)
}
###################### NMS with 5 OTUs of interest #########################
hab_NMS_2012 <- function(){
library(vegan)
library(RColorBrewer)
library(ellipse)
load('Spec_Hab.rda')
combos <- c(which(Spec_Hab$OTU == "10"),which(Spec_Hab$OTU == "63"),which(Spec_Hab$OTU == "96"),which(Spec_Hab$OTU == "43"),which(Spec_Hab$OTU == "53"))
combos_df <- Spec_Hab[combos,] ##subset to just the five OTUs that have both life-phases
combos_df <- droplevels(combos_df) ##get the levels to match after subsetting
aa <- combos_df[,6:10] ##keep just environmental data
mm <- metaMDS(aa) ##run nms, stresses seem okay, found a stable solution
combos_df$mds_X <- mm$points[,1]; combos_df$mds_Y <- mm$points[,2] ##add the nmds coords to combo_df
##get some colors
pal_combo <- brewer.pal(12, "Paired")[c(2,4,6,8,10)]
for (i in 1:nrow(combos_df)){
combos_df$Color[i] <- pal_combo[which(unique(combos_df$OTU) == combos_df[i,]$OTU)]
}
#save(combos_df, file = 'combos_df.rda')
##plots
##here is a general plot, without any bells/whistles
#plot(mm, type = "n") ##blank plot
#combos_df$mds_X <- mm$points[,1]; combos_df$mds_Y <- mm$points[,2] ##get the nmds coords
#points(cbind(combos_df$mds_X, combos_df$mds_Y), col = combos_df$Color, pch = 16) ## print points with colors
#title(main = "Habitat specificity for five \n xylariaceous endophytes/decomposers")
#ordihull(mm, combos_df$OTU, draw = "lines", col = "purple")
##but with this I can't color the lines according to OTU, so...
##make a function that lets us plot each OTU, one at a time
## will need to first plot the null plot (mm, type "n"), but
## this is done in the function below, "draw_NMS"
OTU_nms_plot <- function(OTU){
par(new = TRUE)
aa <- combos_df[which(combos_df$OTU == OTU),]
points(cbind(aa$mds_X, aa$mds_Y), col = aa$Color, pch = 16)
#ordiellipse(m2, combos_df$OTU, show.groups = OTU, col = "green")
ordihull(mm, combos_df$OTU, show.groups = OTU, draw = "lines", col = combos_df[which(combos_df$OTU == OTU),]$Color[1])
centroid.i <- colMeans(cbind(aa$mds_X,aa$mds_Y))
points(centroid.i[1], centroid.i[2], col = aa[which(aa$OTU == OTU),]$Color, pch = 3, cex = 2.5)
return(aa)
}
## we can then plot the colored lines. The stats that print here are
## from the perMANOVA done below.
draw_NMS <- function(){
png(file = "hab_spec_v3.png", width = 7, height = 7, units = 'in', res = 700)
#pdf(file = "hab_spec_v3.pdf")
plot(mm, type = "n", )
title(main = "Habitat specificity for five \n xylariaceous endophytes/decomposers")
text (x = 0.42, y = -.39, "PerMANOVA F(4,57) = 1.59, P-val = 0.10", cex = .75)
for (i in 1:length(unique(combos_df$OTU))) {
OTU <- unique(combos_df$OTU)[i]
OTU_nms_plot(OTU)
}
## make a legend:
ots <- unique(combos_df$OTU)
cols <- unique(combos_df$Color)
spc <- paste('X.',unique(combos_df$species))
legend("topright", legend = spc, fill = cols, cex = .8)
dev.off()
}
## this puts the perMANOVA results too far to the right on my X11/screen,
## but about right on the pdf. ?
draw_NMS()
return(mm)
}
##################### NMS with 5 OTUs of interest by life stage #########################
## adapt above function to graph NMS of be specific to either lifestyle. Argument "EnSt"
## is either "strom" or "endo"
## may have to adjust axis or location of labels to make the permanova results fit right,
## as is, they shift about, I don't force the scale of y or x axis here
indiv_NMS <- function(EnSt){
setwd('/home/daniel/R/Ec2012/')
library(vegan)
library(RColorBrewer)
library(ellipse)
load('Spec_Hab.rda')
combos <- c(which(Spec_Hab$OTU == "10"),which(Spec_Hab$OTU == "63"),which(Spec_Hab$OTU == "96"),which(Spec_Hab$OTU == "43"),which(Spec_Hab$OTU == "53"))
combos_df <- Spec_Hab[combos,] ##subset to just the five OTUs that have both life-phases
combos_df <- droplevels(combos_df) ##get the levels to match after subsetting
endos_df <- combos_df[combos_df$EorS == 'E',] ##subset endo env data
strom_df <- combos_df[combos_df$EorS == 'S',] ##subset strom env data
endos_mds <- metaMDS(endos_df[,6:10]) ##run nms for endos, stresses seem okay
strom_mds <- metaMDS(strom_df[,6:10]) ##run nms for strom, stresses seem okay
endos_df$mds_X <- endos_mds$points[,1]; endos_df$mds_Y <- endos_mds$points[,2] ##add the nmds coords to df's
strom_df$mds_X <- strom_mds$points[,1]; strom_df$mds_Y <- strom_mds$points[,2]
## assign ordination and data frame - endo or strom?
if (EnSt == 'endo') {phase <- endos_df
ord <- endos_mds
org <- "endophytes"
labl <- expression("PerMANOVA f(4,29)=0.45,"~R^2~"=0.06, P=0.94")
lx <- -0.15; ly <- -.44
} else {
if (EnSt == 'strom') {phase <- strom_df
ord <- strom_mds
org <- 'decomposers'
labl <- expression("PerMANOVA f(4,24)=1.84,"~R^2~"=0.23, P=0.07")
lx <- -0.23; ly <- -.59
} else {stop("weird input: Enter either \"endo\" or \"strom\"")}}
##get some colors
cols <- brewer.pal(12, "Paired")[c(2,4,6,8,10)]
##assign them
for (i in 1:nrow(phase)){
phase$Color[i] <- cols[which(unique(phase$OTU) == phase[i,]$OTU)]
}
##make a function that lets us plot each OTU, one at a time
## will need to first plot the null plot (mm, type "n"), but
## this is done in the function below, "draw_NMS"
OTU_nms_plot <- function(OTU){
par(new = TRUE)
aa <- phase[phase$OTU == OTU,]
points(cbind(aa$mds_X, aa$mds_Y), col = aa$Color, pch = 16)
ordihull(ord, phase$OTU, show.groups = OTU, draw = "lines", col = phase[phase$OTU == OTU,]$Color[1])
centroid.i <- colMeans(cbind(aa$mds_X,aa$mds_Y))
points(centroid.i[1], centroid.i[2], col = aa[which(aa$OTU == OTU),]$Color, pch = 3, cex = 2.0, lwd = 2.5)
return(aa)
}
## we can then plot the colored lines. The stats that print here are
## from the perMANOVA done below.
draw_NMS <- function(){
#png(file = paste(org,"_hab_nms.pdf", sep = ""), width = 7, height = 7, units = 'in', res = 700)
#pdf(file = paste(org,"_hab_nms.pdf", sep = ""), width = 7, height = 7)
plot(ord, type = "n", )
title(main = paste("Habitat specificity for five xylariaceous", org))
text (x = lx, y = ly, labels = labl, cex = .75)
for (i in 1:length(unique(combos_df$OTU))) {
OTU <- unique(combos_df$OTU)[i]
OTU_nms_plot(OTU)
}
## make a legend:
ots <- unique(phase$OTU)
cols <- unique(phase$Color)
spc <- paste('X.',unique(phase$species))
legend("bottomright", legend = spc, fill = cols, cex = .8)
#dev.off()
## this puts the perMANOVA results too far to the right on my X11/screen,
## but about right on the pdf. ?
}
draw_NMS()
return(ord)
}
######################## PerMANOVA tests #############################
##use PMANOVA/NPMANOVA to test for difference among the five species, using
##the above dissimilarity matrices
perTest <- function() {
setwd('/home/daniel/R/Ec2012')
library(vegan)
load('combos_df.rda')
env_dat <- combos_df[,6:10]
dist_combo <- vegdist(env_dat) #BC distance of our environmental data
anova(betadisper(dist_combo,combos_df$OTU))
##as I understand, betadispers calculates a sort of multi-variate variance for our groups of interest
##then we test with ANOVA to see if one or more variances are vastly unequal (which would be shown by a low P-val)
##we don't see a very low pval here (p = .30), I think it is okay to go forward
a1 <- adonis(env_dat~combos_df$OTU) ##test grouping by OTU, p = .12
a2 <- adonis(env_dat~combos_df$Stream) ##testing by distance to stream, p = .001
a3 <- adonis(env_dat~combos_df$EorS) ## p = .08, suggestive that endophytes and strom like diff habitat
a4 <- adonis(env_dat~combos_df$EorS, Strata = combos_df$OTU) ##nest LifeStage in OTU, p = .08, same
a5 <- adonis(env_dat~combos_df$OTU, Strata = combos_df$EorS) ##nest OTU in lifestage, p = same
a6 <- adonis(env_dat~combos_df$Canopy)
a7 <- adonis(env_dat~combos_df$Slope)
a8 <- adonis(env_dat~combos_df$eastvec)
a9 <- adonis(env_dat~combos_df$northvec)
## lets try some linear models, multiple explanatory variables
attach(combos_df)
a10 <- adonis(env_dat~Slope+Canopy+eastvec+northvec+Stream)
a11 <- adonis(env_dat~eastvec+Canopy+Stream+northvec+Slope)
a12 <- adonis(env_dat~eastvec+Slope+northvec+Stream+Canopy)
a13 <- adonis(env_dat~Canopy+Slope+Stream+northvec+eastvec)
a14 <- adonis(env_dat~Stream+Canopy+Slope+eastvec+northvec)
a15 <- adonis(env_dat~Stream+Canopy+Slope)
a16 <- adonis(env_dat~Stream+Slope+Canopy)
a17 <- adonis(env_dat~eastvec+northvec)
a18 <- adonis(env_dat~eastvec+Slope+northvec)
detach (combos_df)
## now lets see if there is a difference between endophytes and stromata
endo1 <- combos_df[combos_df$EorS == 'E',]
endo2 <- env_dat[combos_df$EorS == 'E',]
strom1 <- combos_df[combos_df$EorS == 'S',]
strom2 <- env_dat[combos_df$EorS == 'S',]
#############look for effect of OTU in just endos/ just stromata !!!!!!!!
#############look for clustering of all stromata, not just the 5 here, also linear models
####### Just Endophytes ############
attach (endo1)
a20 <- adonis(endo2~Slope+Canopy+eastvec+northvec+Stream) ##stream for endos: R2 = .21, P = .001
a21 <- adonis(endo2~Canopy+eastvec+northvec+Stream+Slope) ##slope for endos: R2 = .20, p =.001
a22 <- adonis(endo2~Slope+eastvec+northvec+Stream+Canopy) ##canopy for endos: R2 = .03, p =.015
a23 <- adonis(endo2~Canopy+Slope+Stream+eastvec+northvec) ##aspect. little effect
a24 <- adonis(endo2~OTU) ##OTU/endos R2=.06, P = .938
## lets check for host preference here, too. Got to rid of the the NA's,
## add a factor called "unknown":
levels(endo1$host) <- c(levels(endo1$host), "unknown")
endo1$host[c(2,33)] <- 'unknown'
a25 <- adonis(endo2~host) ##huh. very high R2 (=.619), but p = .15, probably due to vastly uneven sampling of hosts
detach (endo1)
########### Just Stromata ##############
attach (strom1)
a26 <- adonis(strom2~Slope+Canopy+eastvec+northvec+Stream) ##stream for stroms: F=112.42, R2=.44, P=.001
a27 <- adonis(strom2~Canopy+eastvec+northvec+Stream+Slope) ##slope for stroms: F=31.36, R2=.12, P=.001
a28 <- adonis(strom2~Slope+eastvec+northvec+Stream+Canopy) ##canopy for stroms: F=20.61, R2=.08, p =.001
a29 <- adonis(strom2~Canopy+Slope+Stream+eastvec+northvec) ##aspect, north. little effect
a30 <- adonis(strom2~Canopy+Slope+Stream+northvec+eastvec) ##aspect, east.
a31 <- adonis(strom2~OTU) ##R2 = .24, P = .061, much more pronounced than endophytes
detach (strom1)
## doing all these tests is probably a gross abuse of perMANOVA, but I'm not sure how else to
## tease out the effects of each environmental factor. This seems to be the only way to get
## a type III SS, by running the model with the various terms of interest at the end of the
## model. I'm told this is the most conservative statement of R2 values with perMANOVA
## Almost all of our environmental data is significant according to this test. Compare this to
## the mantel tests, which found no significant explanatory environmental variables. but I'm
## confusing myself. What I am doing here is not checking to see if an environmental
## variable has a direct effect on the presence or absence of species. I am merely subsetting the
## environmental data on each life stage, endophyte or stromata, and ranking what factors are
## most responsible for differences among the points. Low p-values are expected. Why? I am
## examining the effect of multiple variables on a distance matrix constructed entirely on those
## variables. Very little uncertainty in the system here.
## my understanding of adonis (PerMANOVA) is that in unbalanced designs order matters, that
## collinear variables will "hog" R2 values, with variables listed first receiving more of the R2
## to get the most conservative estimate of variation explained in our dissimilarity
## between observations that is explained by a variable, we put it after other correlated
## variables, or constrain permutations within "strata" arguments, (the equivalent of
## nesting).
## in general, proximity to water seems to be the strongest driver of dissimilarity among
## our observations, followed by slope, then canopy. Though highly significant, easterly
## and northerly exposure explain less of the variation (R2 = .02), and seem to be
## correlated with slope. checking correlations:
cor(env_dat)
## correlations. Nothing seems too horribly correlated. Odd that azimouth and
## streams are somewhat correlated, the streams at out site must run fairly
## straight north/south or east/west
## lets try looking at our tolerances/variance-inflation-factors (VIF). We'll
## use a dummy linear model/independent variable, because vif() won't accept adonis
## class objects. Doesn't matter, we're interested in the relationships among dependent
## variables
library(car)
cc <- lm(combos_df$xx ~ Slope + Canopy + Stream + eastvec + northvec)
vif(cc)
## all values between 1.13 and 1.5, seems okay. I guess this means my sampling is unbalanced
## but this not really our fault, that the enivronment in our plot is unequally different.
## Not much I can do, but use the most conservative SS, which I believe in adonis is done by
## rerunning the model multiple times, putting term of interest last. As above. These are the
## values I will report.
perPval <- list(a10,a11,a12)
return(perPval)
}
########################Host preference questions, take II ##################################
########################## faramea endophyte preference ##########################
## Spec_Hab is a df where multiple observations of an endophyte or stromatal OTU
## have been reduced to P/A, yes/no. Here we are going to ask if within all
## grids where our most common host, Faramea, is the host, were more of the
## endophytes a particular endophyte than we would expect?
## We expect that if there is no host preference, the number of times an endophyte
## appears in Faramea will be the same ratio as the number of times that endophyte
## appears in all host-trees as a group
faramea <- function(){
setwd('/home/daniel/R/Ec2012')
trees <- read.csv('trees_R.csv')
load('Spec_Hab.rda')
endos <- Spec_Hab[Spec_Hab$EorS == 'E',]
##df of endos with Faramea as host. multiple observations from one grid/tree
##have already been reduced to pres/abs:
faramea <- na.omit(endos[endos$host == 'Faramea_jasmin',])
length(unique(faramea$OTU)) ##how many otus is faramea hosting? 3
aa <- unique(endos$OTU) ##OTU #'s of all xylaria endophytes
droplevels(aa)
bb <- unique(faramea$OTU) #what species of endophyte did faramea host?
droplevels(bb)
##what proportion of the total observations in Faramea belong to each OTU?
cc <- NULL; a <- 0
for (i in aa) {a <- a+1; cc[a] <- sum(faramea$OTU == i)}
rm(a)
names(cc) <- aa
##what are the proportions of the total observations in all hosts belonging to
##each OTU?
dd <- NULL; a <- 0
for (i in aa) {a <- a+1; dd[a] <- sum(endos$OTU == i)}
rm(a)
names(dd) <- aa
## so now we have an expected (dd), and an observed (cc)
## lets do a chi-squared test, using Monte Carlo simulation
## since we so few observations, violates assumptions of
## traditional test
ee <- chisq.test(cc, p = dd/sum(dd), simulate.p.value = TRUE, B = 10000)
## X-squared = 2.4492, df = NA, p-value = 0.7563
##we see no evidence that Faramea has an "endophyte preference"
##seems that these species are roughly present in the same ratios
##as we see in the plot as a whole
ff <- list(cc,dd,ee)
return (ff)
}
######################## X. adscendens host pref ################################
## now to test for host preference from the perspective of the endophyte,
## using X. adscendens, our most common endophyte
## Given no host preference, Xylaria adscendens should be observed in a given
## host with the same frequency at which that host is present e.g. if there
## are 3 faramea trees hosting xylariaceae in the plot and 1 danea, the faramea
## should host three times more observations than the danea
############# all xylariaceous endophytes df ############
## for this, I will use the larger data-set of all xylariaceous endophytes,
## since our df containing just Xylaria has only five endophytes, need to
## make a new one:
allend <- function(){
setwd('/home/daniel/R/Ec2012')
trees <- read.csv('trees_R.csv')
hOTU <- read.csv('xylariaprojectsequenses_endos_R.csv', as.is =TRUE) ##host tree, sequence Name of endos
roo <- read.csv('roo_otus_6-30-14_r.csv', as.is = TRUE)
## search roo's OTU's sheet for each endo culture name & OTU#
for (i in 1:nrow(hOTU)) {
hOTU$Genus[i] <- roo[which(roo == hOTU$Name[i], arr.ind = TRUE)[1],2]
hOTU$species[i] <- roo[which(roo == hOTU$Name[i], arr.ind = TRUE)[1],3]
hOTU$OTU[i] <- roo[which(roo == hOTU$Name[i], arr.ind = TRUE)[1],1]
}
##get rid of repeats
## order df:
aa <- hOTU[order(hOTU$Grid, hOTU$OTU),]
rownames(aa) <- 1:nrow(aa)
bb <- as.data.frame(matrix(nrow = nrow(aa), ncol = ncol(aa)))
colnames(bb) <- colnames(aa)
bb[1,] <- aa[1,] # get the dataframe started
for (i in 2:nrow(aa)) {
if (aa$Grid[i] == aa$Grid[i-1] & aa$OTU[i] == aa$OTU[i-1]) { ##checks the line above for identical info
bb[i,] <- NA
} else {
bb[i,] <- aa[i,]}
}
##seems to work. now get rid of NAs:
cc <- na.omit(bb)
##remove names, meaningless now:
dd <- cc[,-4]
##give the df a better name, save it (maybe useful later)
all_endos <- dd
#save(all_endos, file = 'all_endos.rda')
return(all_endos)
}
###################### x. adsc chi-square #####################
xadsc <- function () {
load('all_endos.rda') ##all endos, host and grid info
adsc <- all_endos[all_endos$OTU == 63,] ##df of just x. adscendens
## okay, we have a df that gives pres/abs data at each grid for all
## endophytes, not just Xylaria.
## Now what?
## how many trees species are hosting endophytes? what are their
## ratios?
length(unique(all_endos$OTU)) ##24 spp
aa <- unique(all_endos$HostID) ##hosts of all xylaria endophytes
bb <- unique(adsc$HostID) #hosts of X. adscendens
##what proportion of the total observations in X. adsc belong to each host?
cc <- NULL; a <- 0
for (i in aa) {a <- a+1; cc[a] <- sum(adsc$HostID == i)}
rm(a)
names(cc) <- aa
## what are the proportions of trees hosting any endophyte in the enire
## sampling area?
dd <- NULL; a <- 0
for (i in aa) {a <- a+1; dd[a] <- sum(all_endos$HostID == i)}
rm(a)
names(dd) <- aa
## are the ratios of hosts of X. adsc different from the ratios of host trees in general?
ee <- chisq.test(cc, p = dd/sum(dd), simulate.p.value = TRUE, B = 10000)
## X-squared = 19.7986, df = NA, p-value = 0.8623
ff <- list(cc,dd,ee)
return (ff)
}
######################## combination stream and fungal maps ############################
## now to generate maps of the 5 OTUs that displayed both life histories, over stream
## points. These will be the most relevant maps for publication
withstream <- function() {
##lots of dependencies:
setwd("/home/daniel/R/Ec2012/")
library(sp)
load('spco.rdata')
load('losced_sp.rdata')
load('mgo.rdata')
load('env.rda')
setwd("/home/daniel/R/Ec2012/sp_grids/str_and_fung")
## make an function that gives a (1) border and (2) fill color values
## (3)symbols, (4) varying border thickness to indicate both the presence
## of stream and the life stage of the fungus, use this in the loop below:
strfung <- function(zz) {
aa <- NULL
##no fungi, no water:
if (zz[1] == 0 & zz[2] == 0) {aa[1] <- "black"; aa[2] <- "#00000000"; aa[3] <- 1; aa[4] <- 2}
##no fungi, water present:
if (zz[1] == 0 & zz[2] == 1) {aa[1] <- "blue"; aa[2] <- "blue"; aa[3] <- 21; aa[4] <- 1}
##stromata, no water:
if (zz[1] == 1 & zz[2] == 0) {aa[1] <- "black"; aa[2] <- "red"; aa[3] <- 23; aa[4] <- 1}
##stromata, water present:
if (zz[1] == 1 & zz[2] == 1) {aa[1] <- "blue"; aa[2] <- "red"; aa[3] <- 23; aa[4] <- 4}
##endophyte, no water:
if (zz[1] == 2 & zz[2] == 0) {aa[1] <- "black"; aa[2] <- "green"; aa[3] <- 22; aa[4] <- 1}
##endophyte, water present:
if (zz[1] == 2 & zz[2] == 1) {aa[1] <- "blue"; aa[2] <- "green"; aa[3] <- 22; aa[4] <- 4}
##stromata and endophyte, no water:
if (zz[1] == 3 & zz[2] == 0) {aa[1] <- "black"; aa[2] <- "purple"; aa[3] <- 21; aa[4] <- 1}
##stromata and endophyte, water present:
if (zz[1] == 3 & zz[2] == 1) {aa[1] <- "blue"; aa[2] <- "purple"; aa[3] <- 21; aa[4] <- 4}
return (aa)
}
##we'll map just OTUs with both endos and stromata:
endostrom <- c('10','43','53','63','96')
for (j in endostrom){
## merge water data and OTU.j data
losced_cd.j <- data.frame(spco[,j],env$Stream); colnames(losced_cd.j) = c("fungi", "stream")
## give a color, symbol, and border codes, using function from above
for (i in 1:nrow(losced_cd.j)){
losced_cd.j$border[i] <- strfung(losced_cd.j[i,])[1]
losced_cd.j$fill[i] <- strfung(losced_cd.j[i,])[2]
losced_cd.j$symbol[i] <- strfung(losced_cd.j[i,])[3]
losced_cd.j$thick[i] <- strfung(losced_cd.j[i,])[4]
}
##convert to numbers so plot() can read them:
losced_cd.j$symbol <- as.numeric(losced_cd.j$symbol)
losced_cd.j$thick <- as.numeric(losced_cd.j$thick)
##make a spatial data frame
losced_spcd.j <- SpatialPointsDataFrame(losced_sp, losced_cd.j, match.ID = TRUE)
filename.j <- paste("Str_OTU",j,".pdf", sep = "")
##plot
#pdf(filename.j)
png(file = )
plot(losced_spcd.j, pch = losced_spcd.j$symbol, cex = 2, lwd = losced_spcd.j$thick, bg = losced_spcd.j$fill, col = losced_spcd.j$border)
title1.j <- paste(mgo[mgo$OTU == j,2], mgo[mgo$OTU == j,3])[1]
title2.j <- paste("OTU", j, sep = " ") ##OTU subtitle
text(x = 55, y = 65, labels = title1.j, cex = 2)
#text(x = 25, y = -10, labels = title2.j, cex = 1.5)
#legend(x = 70, y = -2.5, leg = c("Decomposer", "Endophyte", "Both"), pch = c(23,22,21), pt.cex = 1., pt.bg = c("red","green","purple"))
dev.off()
}
setwd("/home/daniel/R/Ec2012/")
}
##################### Graph Roo's leaf-fall study ######################
## Fit leaf fall data to a linear model, create a figure
leaf <- function(){
setwd("/home/daniel/R/Ec2012/")
read.csv("2012_tree_leaf_fall.csv")->trees
## fit a model to tree 1
tree1 <- function(){
tree1 <- na.omit(trees[,1:5]) ## just tree1, now sort out leaf density by distance:
dist <- rep(tree1$Distance,4)
lvs <- c(tree1$Tree1.1, tree1$Tree1.2, tree1$Tree1.3, tree1$Tree1.4)
dilv <- as.data.frame(rbind(dist, lvs))
dilv <-dilv[ order(dist, lvs)]
aa <- as.numeric(dilv[1,]) ##dist
bb <- as.numeric(dilv[2,]) ##lvs
cc <- log(bb+1) ##log lvs, have to make all values non-zero
dd <- log(aa+1) ##log dist, have to make all values non-zero
## four models: untransformed (linear), logarithmic transformations of leaf counts
## or distance, both transformed log
lin <- lm(bb~aa)
lglv <- lm(cc~aa)
lgdi <- lm(bb~dd)
lgld <- lm(cc~dd)
## looks like a log decay function (really, a leaf decay function!)
## now draw a curve from model:
dists <- seq(0,3.5,.01)
llgdi <- predict.lm(lgdi, list(dd = dists))
#plot(bb~aa)
plot(bb ~ aa, xlim =c(0,25), ylim = c(0,35), col = 'red', ylab = '', xlab = '')
lines(x = exp(dists), y = llgdi)
}
##now tree 2, let's see if the same -log model will work
tree2 <- function(){
tree2 <- na.omit(trees[,-c(2:5)]) ## just tree 2
dist <- rep(tree2$Distance,4)
lvs <- c(tree2$Tree2.1, tree2$Tree2.2, tree2$Tree2.3, tree2$Tree2.4)
dilv <- as.data.frame(rbind(dist, lvs))
dilv <-dilv[ order(dist, lvs)]
aa <- as.numeric(dilv[1,]) ##dist
bb <- as.numeric(dilv[2,]) ##lvs
cc <- log(bb+1) ##log lvs, have to make all values non-zero
dd <- log(aa+1) ##log dist, have to make all values non-zero
lgdi <- lm(bb~dd) ##model, -log as with tree1
dists <- seq(0,3.5,.01)
llgdi <- predict.lm(lgdi, list(dd = dists))
#plot(bb~aa)
plot(bb ~ aa, xlim =c(0,25), ylim = c(0,35), col = 'blue',
main = 'Density of fallen leaves from two trees', pch = 5,
xlab = 'Distance from tree (m)', ylab =
'leaves per meter square')
lines(x = exp(dists), y = llgdi)
legend(x = 8, y= 34, legend = c(expression(italic('Caryodaphnopsis theobromifolia')),
expression(italic('<NAME>'))), cex=.8, bty="n", col =c("red","blue"), pch = c(1,5))
}
pdf('leaf_curves.pdf', width = 5, height = 5)
aa <- tree1()
par(new = TRUE)
bb <- tree2()
dev.off()
cc <- list(aa,bb)
return(cc)
}<file_sep>/README.md
Los_Cedros_Xylaria_2012
=======================
| 9195eb5ad96178317bd9bae215084d05cf452297 | [
"Markdown",
"R"
]
| 2 | R | danchurchthomas/Los_Cedros_Xylaria_2012 | 9ab2a2d42ce42e16474f76edb719eeb663273f7c | 734855f92ff280afaa63672222bebf9f7fc11cf7 |
refs/heads/master | <file_sep>var admin = require('firebase-admin');
var serviceAccount = require('../secrets/serviceAccount.json');
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: 'https://sandbox-328be.firebaseio.com',
});
const db = admin.firestore();
const FieldValue = admin.firestore.FieldValue;
module.exports.db = db;
module.exports.FieldValue = FieldValue;
<file_sep># Portfolio manager backend
Backend for the portfolio manager frontend app. It is responsible for retrieving quotes of stocks, cryptos and commodities and updating these in firestore.
## Tech stack
- [Firebase](https://firebase.google.com/) - A cloud-hosted NoSQL database that lets you store and sync data between your users in real-time.
- [Express](https://expressjs.com/) - Web framework for Node.js
## Installation
### Clone repo and install packages:
`npm install`
### Get API keys
You need to get API keys from these financial data prviders (they are all free):
- https://www.alphavantage.co
- https://www.quandl.com
- https://www.coinapi.io
Copy the API keys into /portfolioBackend/APIConfig.js
### Set firbase config
Copy the servcice account config of your firebase project into /portfolioBackend/fbConfig.js
### Start server
`npm start`
Then server is running on http://localhost:8000/
| 46d6b084105427976b15f61a724176acaca1bb51 | [
"JavaScript",
"Markdown"
]
| 2 | JavaScript | hochbruj/portfolio-manager-backend | c58ef3d361bc9f4bb20bbdfeb9660f8377fe0194 | b532c0d99178bcaa4044130fe1f2165e9123e3f2 |
refs/heads/master | <repo_name>parabol-studio/parabol-material<file_sep>/src/app/modules/text/text.component.ts
import {
Component,
Input,
Output,
EventEmitter,
ViewChild,
ElementRef,
AfterViewChecked,
ChangeDetectorRef,
OnInit
} from '@angular/core';
@Component({
selector: 'parabol-text',
templateUrl: './text.html'
})
export class ParabolTextComponent implements AfterViewChecked, OnInit {
public controlType: string;
public maskArray: Array<any>;
public maskControlArray: Array<any>;
public maskEditableIndexes: Array<any>;
public position: number;
public isMobile: boolean;
@Output() modelChange = new EventEmitter();
@Input() placeholder: string;
@Input() type: string;
@Input() mask: string;
@Input() model: string;
@ViewChild('input') input: ElementRef;
@ViewChild('maskLayer') maskLayer: ElementRef;
constructor(private cd: ChangeDetectorRef) {}
ngOnInit() {
this.isMobile = (typeof window.orientation !== 'undefined') || (navigator.userAgent.indexOf('IEMobile') !== -1);
if (this.isMobile) { this.mask = null; }
if (this.mask && !this.isMobile) {
this.maskArray = this.mask.split('');
this.maskControlArray = [];
const editableIndexes = [];
this.maskArray.forEach(function(char, index) {
if (char.match(/^[a-zA-Z0-9]*$/)) { editableIndexes.push(index); }
});
this.maskEditableIndexes = editableIndexes;
}
}
ngAfterViewChecked() {
if (!this.type) { this.type = 'text'; }
if (this.type === 'password') { this.controlType = 'password'; }
if (this.mask && !this.isMobile) { this.applyMask(null); }
this.cd.detectChanges();
}
showPassword() {
if (this.type === 'text') { this.type = 'password'; } else
if (this.type === 'password') { this.type = 'text'; }
}
applyMask(event) {
if (!this.isMobile) {
this.model = this.maskArray.join('');
this.input.nativeElement.style.color = 'transparent';
if (event) {
if (event.key === 'Backspace') { this.maskControlArray.pop(); }
if (this.maskControlArray.length < this.maskEditableIndexes.length && event.key.match(/^[a-zA-Z0-9]*$/) && event.key.length === 1) {
this.maskControlArray.push(event.key);
}
this.maskArray = this.mask.split('');
const maskArray = this.maskArray;
const editableIndexes = this.maskEditableIndexes;
this.maskControlArray.map(function(char, index) {
const editableIndex = editableIndexes[index];
maskArray[editableIndex] = char;
});
this.model = maskArray.join('');
this.input.nativeElement.value = this.model;
if (this.maskControlArray.length === this.maskEditableIndexes.length) { this.modelChange.emit(this.model); }
}
this.applyStyle(event);
}
}
applyStyle(event) {
this.maskLayer.nativeElement.innerHTML = this.model;
const editableIndexes = this.maskEditableIndexes;
const maskControlArray = this.maskControlArray;
let position = this.position;
const formattedChars = this.maskLayer.nativeElement.innerHTML.split('').map((char, index) => {
position = editableIndexes[maskControlArray.length - 1];
if (index === position) { return `<span class="char">${ char }</span><span class="carat"></span>`; }
else if (index <= position) { return `<span class="char">${ char }</span>`; }
else { return `<span>${ char }</span>`; }
});
if (position === undefined) { formattedChars['0'] = `<span class="carat"></span><span>${ this.maskArray[0] }</span>`; }
this.position = position;
this.maskLayer.nativeElement.innerHTML = formattedChars.join('');
}
emit(event) {
if (this.mask && !this.isMobile) { this.applyMask(event); }
else { this.modelChange.emit(this.model); }
}
}
<file_sep>/src/app/app.module.ts
import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { AngularFontAwesomeModule } from 'angular-font-awesome';
import { TextModule } from './modules/app/modules/text.module';
import { TextareaModule } from './modules/app/modules/textarea.module';
import { DatepickerModule } from './modules/app/modules/datepicker.module';
import { CheckboxModule } from './modules/app/modules/checkbox.module';
import { CheckboxGroupModule } from './modules/app/modules/checkbox-group.module';
import { RadioModule } from './modules/app/modules/radio.module';
import { SelectModule } from './modules/app/modules/select.module';
import { SliderModule } from './modules/app/modules/slider.module';
import { ModalModule } from './modules/app/modules/modal.module';
import { NotificationModule } from './modules/app/modules/notification.module';
import { LoadingModule } from './modules/app/modules/loading.module';
import { PendingModule } from './modules/app/modules/pending.module';
import { SelectButtonModule } from './modules/app/modules/select-button.module';
import { SidebarModule } from './modules/app/modules/sidebar.module';
import { DisplayModule } from './modules/app/modules/display.module';
import { ParabolSidebarModule } from './modules/sidebar/sidebar.module';
import { AppComponent } from './app.component';
@NgModule({
declarations: [ AppComponent ],
imports: [
BrowserAnimationsModule,
AngularFontAwesomeModule,
BrowserModule,
TextModule,
TextareaModule,
DatepickerModule,
CheckboxModule,
CheckboxGroupModule,
RadioModule,
SelectModule,
SliderModule,
ModalModule,
NotificationModule,
LoadingModule,
PendingModule,
SelectButtonModule,
SidebarModule,
DisplayModule,
ParabolSidebarModule
],
bootstrap: [ AppComponent ],
schemas: [ CUSTOM_ELEMENTS_SCHEMA ]
})
export class AppModule { }
<file_sep>/src/app/modules/checkbox/checkbox.component.ts
import { Component, Input, Output, EventEmitter } from '@angular/core';
/*
* @Component: ParabolCheckboxComponent
*
* Components are the main way we build and specify elements and logic on the page, through both
* custom elements and attributes that add functionality to our existing components.
*
* This component is used to build Parabol Material Checkbox.
*/
@Component({
selector: 'parabol-checkbox',
templateUrl: './checkbox.html'
})
export class ParabolCheckboxComponent {
@Output() modelChange = new EventEmitter();
@Input() model: string;
@Input() value: string;
@Input() label: string;
check() {
if (!this.model) { this.model = this.value; } else { this.model = null; }
this.modelChange.emit(this.model);
}
}
<file_sep>/src/app/modules/app/components/text.component.ts
import { Component, DoCheck } from '@angular/core';
@Component({
selector: 'app-text',
templateUrl: '../templates/text.html'
})
export class TextComponent implements DoCheck {
public prefill: boolean;
public data: string;
ngDoCheck() {
if (this.prefill) { this.data = '<NAME>'; }
}
}
<file_sep>/src/app/modules/datepicker/datepicker.module.ts
// Import Angular modules
import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { BrowserModule } from '@angular/platform-browser';
import { AngularFontAwesomeModule } from 'angular-font-awesome';
import { DatePipe } from '@angular/common';
// Import custom components
import { ParabolDatepickerComponent } from './datepicker.component';
// Import custom modules
import { ParabolTextModule } from '../text/text.module';
import { ParabolModalModule } from '../modal/modal.module';
import { ParabolSelectButtonModule } from '../select-button/select-button.module';
/*
* @NgModule: ParabolDatepickerModule
*
* An NgModule is a class adorned with the @NgModule decorator function. @NgModule takes a metadata
* object that tells Angular how to compile and run module code. It identifies the module's own
* components, directives, and pipes, making some of them public so external components can use them.
* @NgModule may add service providers to the application dependency injectors.
*
* This module is used to construct the /campaign_manager/datepicker page.
*/
@NgModule({
imports: [
FormsModule,
BrowserModule,
AngularFontAwesomeModule,
ParabolTextModule,
ParabolModalModule,
ParabolSelectButtonModule
],
exports: [ ParabolDatepickerComponent ],
declarations: [ ParabolDatepickerComponent ],
providers: [ DatePipe ],
schemas: [ CUSTOM_ELEMENTS_SCHEMA ]
})
export class ParabolDatepickerModule { }
<file_sep>/src/app/modules/slider/slider.module.ts
// Import Angular modules
import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { BrowserModule } from '@angular/platform-browser';
// Import custom components
import { ParabolSliderComponent } from './slider.component';
/*
* @NgModule: ParabolSliderModule
*
* An NgModule is a class adorned with the @NgModule decorator function. @NgModule takes a metadata
* object that tells Angular how to compile and run module code. It identifies the module's own
* components, directives, and pipes, making some of them public so external components can use them.
* @NgModule may add service providers to the application dependency injectors.
*/
@NgModule({
imports: [
FormsModule,
BrowserModule
],
exports: [ ParabolSliderComponent ],
declarations: [ ParabolSliderComponent ],
schemas: [ CUSTOM_ELEMENTS_SCHEMA ]
})
export class ParabolSliderModule { }
<file_sep>/src/app/modules/app/modules/loading.module.ts
import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HighlightModule } from 'ngx-highlightjs';
// Import custom modules
import { ParabolLoadingModule } from '../../loading/loading.module';
// Import custom components
import { LoadingComponent } from '../components/loading.component';
@NgModule({
imports: [
BrowserModule,
ParabolLoadingModule,
HighlightModule.forRoot({ theme: 'color-brewer' })
],
exports: [ LoadingComponent ],
declarations: [ LoadingComponent ],
schemas: [ CUSTOM_ELEMENTS_SCHEMA ]
})
export class LoadingModule { }
<file_sep>/src/app/modules/app/components/display.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-display',
templateUrl: '../templates/display.html'
})
export class DisplayComponent {
}
<file_sep>/src/app/modules/app/components/radio.component.ts
import { Component, DoCheck } from '@angular/core';
@Component({
selector: 'app-radio',
templateUrl: '../templates/radio.html'
})
export class RadioComponent implements DoCheck {
public prefill: boolean;
public radio_options: Array<Object>;
public data: string;
constructor() {
this.radio_options = [
{ label_alt: 'Option 1', value_alt: 'option_1' },
{ label_alt: 'Option 2', value_alt: 'option_2' },
{ label_alt: 'Option 3', value_alt: 'option_3' }
];
}
ngDoCheck() {
if (this.prefill) { this.data = 'option_2'; }
}
}
<file_sep>/src/app/modules/slider/slider.component.ts
// Import Angular modules
import { Component, Input, Output, EventEmitter, AfterViewChecked, ChangeDetectorRef } from '@angular/core';
/*
* @Component: ParabolSliderComponent
*
* Components are the main way we build and specify elements and logic on the page, through both
* custom elements and attributes that add functionality to our existing components.
*
* This component is used to build Parabol Material Slider component.
*/
@Component({
selector: 'parabol-slider',
templateUrl: './slider.html'
})
export class ParabolSliderComponent implements AfterViewChecked {
@Output() modelChange = new EventEmitter();
@Input() placeholder: string;
@Input() prefix: string;
@Input() suffix: string;
@Input() model: number;
@Input() max: number;
@Input() min: number;
constructor(private cd: ChangeDetectorRef) {}
ngAfterViewChecked() {
if (!this.max) { this.max = 100; }
if (!this.min) { this.min = 0; }
this.cd.detectChanges();
}
emit(event) {
this.model = event.srcElement.value;
this.modelChange.emit(this.model);
}
}
<file_sep>/src/app/modules/app/components/checkbox.component.ts
import { Component, DoCheck } from '@angular/core';
@Component({
selector: 'app-checkbox',
templateUrl: '../templates/checkbox.html'
})
export class CheckboxComponent implements DoCheck {
public prefill: boolean;
public checkbox_options: Array<Object>;
public data: string;
constructor() {
this.checkbox_options = [
{ label_alt: 'Option 1', value_alt: 'option_1' },
{ label_alt: 'Option 2', value_alt: 'option_2' },
{ label_alt: 'Option 3', value_alt: 'option_3' }
];
}
ngDoCheck() {
if (this.prefill) { this.data = 'clicked'; }
}
}
<file_sep>/src/app/modules/app/components/checkbox-group.component.ts
import { Component, DoCheck } from '@angular/core';
@Component({
selector: 'app-checkbox-group',
templateUrl: '../templates/checkbox-group.html'
})
export class CheckboxGroupComponent implements DoCheck {
public prefill: any;
public checkbox_options: Array<Object>;
public data: Array<string>;
constructor() {
this.checkbox_options = [
{ label_alt: 'Option 1', value_alt: 'option_1' },
{ label_alt: 'Option 2', value_alt: 'option_2' },
{ label_alt: 'Option 3', value_alt: 'option_3' }
];
}
ngDoCheck() {
if (this.prefill) { this.data = ['option_1', 'option_2']; }
}
}
<file_sep>/src/app/modules/datepicker/datepicker.component.ts
// Import Angular modules
import { Component, Input, Output, EventEmitter, AfterViewChecked, ChangeDetectorRef, ElementRef } from '@angular/core';
// Import npm modules
import range from 'lodash-es/range';
import times from 'lodash-es/times';
import * as moment_ from 'moment';
const moment = moment_;
/*
* @Component: ParabolDatepickerComponent
*
* Components are the main way we build and specify elements and logic on the page, through both
* custom elements and attributes that add functionality to our existing components.
*
* This component is used to build Parabol Material Datepicker.
*/
@Component({
selector: 'parabol-datepicker',
templateUrl: './datepicker.html'
})
export class ParabolDatepickerComponent implements AfterViewChecked {
public openDatepicker: boolean;
public dateInput: any;
public month: string;
public year: number;
public day: string;
public hour: string;
public minute: string;
public daysArray: Array<any>;
public hoursArray: Array<any>;
public minutesArray: Array<any>;
public yearOptions: Array<Object>;
public monthStartOffset: number;
public displayTime: boolean;
public monthsOptions = [
{ label: 'January', value: 'January' },
{ label: 'February', value: 'February' },
{ label: 'March', value: 'March' },
{ label: 'April', value: 'April' },
{ label: 'May', value: 'May' },
{ label: 'June', value: 'June' },
{ label: 'July', value: 'July' },
{ label: 'August', value: 'August' },
{ label: 'September', value: 'September' },
{ label: 'October', value: 'October' },
{ label: 'November', value: 'November' },
{ label: 'December', value: 'December' }
];
@Output() modelChange = new EventEmitter();
@Input() placeholder: string;
@Input() model: string;
@Input() years: string;
@Input() time: boolean;
@Input() offset: number;
constructor(private cdr: ChangeDetectorRef, private elem: ElementRef) {
elem.nativeElement.onkeyup = (elem) => {
elem.preventDefault();
this.openDatepicker = true;
};
this.setTimeOptions();
}
ngAfterViewChecked() {
if (this.model) {
this.model = (this.model.includes('Z')) ? this.model : `${ moment(this.model).local().format('YYYY-MM-DDTHH:mm:ss.SSS') }Z`;
if (this.time)
this.dateInput = moment(this.model).utc().format('Do, MMM YYYY - HH:mm');
else
this.dateInput = moment(this.model).utc().format('Do, MMM YYYY');
}
if (!this.offset) { this.offset = 0; }
this.getYearOptions();
this.getMonth();
this.cdr.detectChanges();
}
setTimeOptions() {
const hoursArray = [];
const minutesArray = [];
times(24, function(index) {
hoursArray.push({
label: ('0' + index).slice(-2),
value: ('0' + index).slice(-2)
});
});
times(60, function(index) {
minutesArray.push({
label: ('0' + index).slice(-2),
value: ('0' + index).slice(-2)
});
});
this.hoursArray = hoursArray;
this.minutesArray = minutesArray;
}
getYearOptions() {
const thisYear = new Date().getFullYear();
const yearRange = (this.years === 'future')
? range(thisYear + this.offset, thisYear + 100) : range(thisYear - this.offset, thisYear - 100);
const yearOptions = [];
yearRange.forEach((year) => yearOptions.push({ label: year, value: year }));
this.yearOptions = yearOptions;
}
getMonth() {
const monthMap = {
'January': '01',
'February': '02',
'March': '03',
'April': '04',
'May': '05',
'June': '06',
'July': '07',
'August': '08',
'September': '09',
'October': '10',
'November': '11',
'December': '12'
};
this.month = (this.month) ? this.month : moment().format('MMMM');
if (typeof this.offset === 'string') this.offset = parseInt(this.offset, 10);
if (!this.year) {
this.year = parseInt(moment().format('YYYY'), 10);
if (this.offset && this.years === 'future') this.year += this.offset;
else if (this.offset) this.year -= this.offset;
}
const chosenMonth = (this.month) ? monthMap[this.month] : moment().format('MM');
const chosenYear = (this.year) ? this.year : moment().format('YYYY');
const daysInMonth = moment(`${ chosenYear }-${ chosenMonth }`, 'YYYY-MM').daysInMonth();
this.monthStartOffset = range(1, moment(`${ chosenYear }-${ chosenMonth }-01`, 'YYYY-MM-DD').weekday() + 1);
this.daysArray = range(1, daysInMonth + 1);
}
checkTime() {
if (this.hour && this.minute) this.submitDate(null, true);
}
submitDate(day, isTimeSet) {
if (day) this.day = day;
if (this.time && !isTimeSet) this.displayTime = true;
else {
const monthMap = {
'January': '01',
'February': '02',
'March': '03',
'April': '04',
'May': '05',
'June': '06',
'July': '07',
'August': '08',
'September': '09',
'October': '10',
'November': '11',
'December': '12'
};
const month = monthMap[this.month];
if (this.day.toString().length === 1) this.day = `0${ this.day }`;
this.model = moment(`${ this.year }-${ month }-${ this.day }T${ this.hour || '00' }:${ this.minute || '00' }:00.000 Z`).toISOString();
if (this.time)
this.dateInput = moment(this.model).utc().format('Do, MMM YYYY - HH:mm');
else
this.dateInput = moment(this.model).utc().format('Do, MMM YYYY');
this.openDatepicker = false;
this.modelChange.emit(this.model);
}
}
}
<file_sep>/src/app/modules/select-button/select-button.component.ts
// Import Angular modules
import { Component, Input, Output, EventEmitter, AfterViewChecked, ChangeDetectorRef } from '@angular/core';
/*
* @Component: ParabolSelectButtonComponent
*
* Components are the main way we build and specify elements and logic on the page, through both
* custom elements and attributes that add functionality to our existing components.
*
* This component is used to build Parabol Material Select component.
*/
@Component({
selector: 'parabol-select-button',
templateUrl: './select-button.html'
})
export class ParabolSelectButtonComponent implements AfterViewChecked {
public showDropdown: boolean;
@Output() modelChange = new EventEmitter();
@Input() placeholder: string;
@Input() options: Array<any>;
@Input() keys: string;
@Input() model: string;
constructor(private cd: ChangeDetectorRef) {}
ngAfterViewChecked() {
if (!this.placeholder) { this.placeholder = 'Select'; }
if (!this.keys) { this.keys = 'label, value'; }
if (!this.options) {
this.options = [
{ label: '0', value: 0 },
{ label: '1', value: 1 },
{ label: '2', value: 2 },
{ label: '3', value: 3 },
{ label: '4', value: 4 },
{ label: '5', value: 5 },
{ label: '6', value: 6 },
{ label: '7', value: 7 },
{ label: '8', value: 8 },
{ label: '9', value: 9 },
{ label: '10', value: 10 }
];
}
this.assignKeys();
this.cd.detectChanges();
}
assignKeys() {
const keys = this.keys.replace(/\s/g, '').split(',');
this.options.forEach(function(option) {
if (!option['label']) { option['label'] = option[keys[0]]; delete option[keys[0]]; }
if (!option['value']) { option['value'] = option[keys[1]]; delete option[keys[1]]; }
});
}
select(value) {
this.model = value;
this.modelChange.emit(this.model);
this.showDropdown = false;
}
}
<file_sep>/src/app/modules/pending/pending.component.ts
// Import Angular modules
import { Component, Input } from '@angular/core';
/*
* @Component: ParabolPendingComponent
*
* Components are the main way we build and specify elements and logic on the page, through both
* custom elements and attributes that add functionality to our existing components.
*/
@Component({
selector: 'parabol-pending',
templateUrl: './pending.html'
})
export class ParabolPendingComponent {
@Input() pending: any;
}
<file_sep>/server.js
/* Node modules */
const express = require('express')
const path = require('path')
const app = express();
/* Middleware */
app.use(express.static(path.join(__dirname, 'dist')))
app.listen(8081, () => {
console.log(`Node server running on port 8081`);
});
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, `dist/index.html`));
});<file_sep>/src/app/modules/app/components/loading.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-loading',
templateUrl: '../templates/loading.html'
})
export class LoadingComponent {
public loading: string;
triggerLoading() {
this.loading = 'Loading some data...';
setTimeout(() => this.loading = null, 5000);
}
}
<file_sep>/src/app/modules/select/select.component.ts
// Import Angular modules
import { Component, Input, Output, EventEmitter, HostListener, OnChanges } from '@angular/core';
/*
* @Component: ParabolSelectComponent
*
* Components are the main way we build and specify elements and logic on the page, through both
* custom elements and attributes that add functionality to our existing components.
*
* This component is used to build Parabol Material Select component.
*/
@Component({
selector: 'parabol-select',
templateUrl: './select.html'
})
export class ParabolSelectComponent implements OnChanges {
public openDropdown: boolean;
public displayValue: any;
@Output() modelChange = new EventEmitter();
@Input() placeholder: string;
@Input() options: Array<any>;
@Input() keys: string;
@Input() model: string;
@HostListener('document:click', ['$event']) clickedOutside($event) {
this.openDropdown = false;
}
ngOnChanges() {
if (!this.keys) this.keys = 'label, value';
if (this.options) this.assignKeys();
if (this.model) this.reflectModel();
}
reflectModel() {
const model = this.model;
let displayValue;
this.options.forEach((option) => {
if (option.value === model) displayValue = option.label;
});
this.displayValue = displayValue;
}
focusInput($event) {
this.openDropdown = true;
$event.preventDefault();
$event.stopPropagation();
}
assignKeys() {
const keys = this.keys.replace(/\s/g, '').split(',');
this.options.forEach((option) => {
if (!option['label']) { option['label'] = option[keys[0]]; delete option[keys[0]]; }
if (!option['value']) { option['value'] = option[keys[1]]; delete option[keys[1]]; }
});
}
select(option) {
this.displayValue = option.label;
this.model = option.value;
this.openDropdown = false;
this.modelChange.emit(this.model);
}
}
<file_sep>/src/app/modules/app/components/notification.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-notification',
templateUrl: '../templates/notification.html'
})
export class NotificationComponent {
public notification: Object;
public data: Object;
triggerNotification(type) {
this.notification = { type: type, payload: 'This is a notification' };
}
}
<file_sep>/src/app/modules/radio/radio.component.ts
import { Component, Input, Output, EventEmitter, AfterViewChecked, ChangeDetectorRef } from '@angular/core';
/*
* @Component: ParabolRadioComponent
*
* Components are the main way we build and specify elements and logic on the page, through both
* custom elements and attributes that add functionality to our existing components.
*
* This component is used to build Parabol Material Checkbox.
*/
@Component({
selector: 'parabol-radio',
templateUrl: './radio.html'
})
export class ParabolRadioComponent implements AfterViewChecked {
private formattedOptions: any;
@Output() modelChange = new EventEmitter();
@Input() model: string;
@Input() options: any;
@Input() keys: any;
constructor(private cd: ChangeDetectorRef) {}
ngAfterViewChecked() {
if (!this.keys) { this.keys = 'label, value'; }
this.assignKeys();
this.cd.detectChanges();
}
assignKeys() {
const keys = this.keys.replace(/\s/g, '').split(',');
this.options.forEach(function(option) {
if (!option['label']) { option['label'] = option[keys[0]]; delete option[keys[0]]; }
if (!option['value']) { option['value'] = option[keys[1]]; delete option[keys[1]]; }
});
}
emit(option) {
this.model = option;
this.modelChange.emit(this.model);
}
}
<file_sep>/src/app/modules/checkbox/checkbox.module.ts
import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AngularFontAwesomeModule } from 'angular-font-awesome';
// Import custom components
import { ParabolCheckboxComponent } from './checkbox.component';
@NgModule({
imports: [ BrowserModule, AngularFontAwesomeModule ],
exports: [ ParabolCheckboxComponent ],
declarations: [ ParabolCheckboxComponent ],
schemas: [ CUSTOM_ELEMENTS_SCHEMA ]
})
export class ParabolCheckboxModule { }
<file_sep>/src/app/modules/checkbox_group/checkbox_group.component.ts
import { Component, Input, Output, EventEmitter, AfterViewChecked, ChangeDetectorRef } from '@angular/core';
// Import npm modules
import { xor } from 'lodash';
/*
* @Component: ParabolCheckboxComponent
*
* Components are the main way we build and specify elements and logic on the page, through both
* custom elements and attributes that add functionality to our existing components.
*
* This component is used to build Parabol Material Checkbox.
*/
@Component({
selector: 'parabol-checkbox-group',
templateUrl: './checkbox_group.html'
})
export class ParabolCheckboxGroupComponent implements AfterViewChecked {
@Output() modelChange = new EventEmitter();
@Input() model: Array<any>;
@Input() options: any;
@Input() keys: string;
constructor(private cd: ChangeDetectorRef) {}
ngAfterViewChecked() {
if (!this.keys) { this.keys = 'label, value'; }
this.assignKeys();
this.cd.detectChanges();
}
checked(option) {
if (this.model && this.model.indexOf(option) > -1) { return true; }
}
assignKeys() {
const keys = this.keys.replace(/\s/g, '').split(',');
this.options.forEach(function(option) {
if (!option['label']) { option['label'] = option[keys[0]]; delete option[keys[0]]; }
if (!option['value']) { option['value'] = option[keys[1]]; delete option[keys[1]]; }
});
}
toggleValue(value) {
this.model = xor(this.model, [ value ]);
this.modelChange.emit(this.model);
}
}
<file_sep>/src/app/modules/modal/modal.component.ts
// Import Angular modules
import { Component, Input, Output, EventEmitter, ChangeDetectorRef, AfterViewChecked } from '@angular/core';
/*
* @Component: ParabolModalComponent
*
* Components are the main way we build and specify elements and logic on the page, through both
* custom elements and attributes that add functionality to our existing components.
*
* This component is used to build Parabol Material Datepicker.
*/
@Component({
selector: 'modal-footer',
templateUrl: './modal.html'
})
export class ParabolModalFooterComponent implements AfterViewChecked {
@Output() model: EventEmitter<any> = new EventEmitter();
@Output() onConfirm: EventEmitter<any> = new EventEmitter();
@Output() onCancel: EventEmitter<any> = new EventEmitter();
@Input() label: string;
@Input() type: string;
constructor(private cd: ChangeDetectorRef) {}
ngAfterViewChecked() {
if (!this.type) { this.type = 'confirm'; }
if (!this.label) { this.label = 'OK'; }
this.cd.detectChanges();
}
emit(action) {
if (action === 'cancel') {
this.model.emit(false);
this.onCancel.emit();
}
if (action === 'submit') {
this.model.emit(false);
this.onConfirm.emit();
}
}
}
<file_sep>/src/app/modules/app/components/pending.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-pending',
templateUrl: '../templates/pending.html'
})
export class PendingComponent {
public pending: boolean;
constructor() { this.pending = true; }
}
<file_sep>/src/app/modules/app/modules/datepicker.module.ts
import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HighlightModule } from 'ngx-highlightjs';
// Import custom modules
import { ParabolCheckboxModule } from '../../checkbox/checkbox.module';
import { ParabolDatepickerModule } from '../../datepicker/datepicker.module';
// Import custom components
import { DatepickerComponent } from '../components/datepicker.component';
@NgModule({
imports: [
BrowserModule,
ParabolCheckboxModule,
ParabolDatepickerModule,
HighlightModule.forRoot({ theme: 'color-brewer' })
],
exports: [ DatepickerComponent ],
declarations: [ DatepickerComponent ],
schemas: [ CUSTOM_ELEMENTS_SCHEMA ]
})
export class DatepickerModule { }
<file_sep>/src/app/modules/app/modules/display.module.ts
import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HighlightModule } from 'ngx-highlightjs';
// Import custom modules
import { ParabolDisplayModule } from '../../display/display.module';
// Import custom components
import { DisplayComponent } from '../components/display.component';
@NgModule({
imports: [
BrowserModule,
ParabolDisplayModule,
HighlightModule.forRoot({ theme: 'color-brewer' })
],
exports: [ DisplayComponent ],
declarations: [ DisplayComponent ],
schemas: [ CUSTOM_ELEMENTS_SCHEMA ]
})
export class DisplayModule { }
<file_sep>/src/app/modules/app/modules/textarea.module.ts
import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HighlightModule } from 'ngx-highlightjs';
// Import custom modules
import { ParabolCheckboxModule } from '../../checkbox/checkbox.module';
import { ParabolTextareaModule } from '../../textarea/textarea.module';
// Import custom components
import { TextareaComponent } from '../components/textarea.component';
@NgModule({
imports: [
BrowserModule,
ParabolTextareaModule,
ParabolCheckboxModule,
HighlightModule.forRoot({ theme: 'color-brewer' })
],
exports: [ TextareaComponent ],
declarations: [ TextareaComponent ],
schemas: [ CUSTOM_ELEMENTS_SCHEMA ]
})
export class TextareaModule { }
<file_sep>/src/app/modules/checkbox_group/checkbox_group.module.ts
import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AngularFontAwesomeModule } from 'angular-font-awesome';
// Import custom components
import { ParabolCheckboxGroupComponent } from './checkbox_group.component';
@NgModule({
imports: [
BrowserModule,
AngularFontAwesomeModule
],
exports: [ ParabolCheckboxGroupComponent ],
declarations: [ ParabolCheckboxGroupComponent ],
schemas: [ CUSTOM_ELEMENTS_SCHEMA ]
})
export class ParabolCheckboxGroupModule { }
<file_sep>/src/app/modules/app/components/modal.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-modal',
templateUrl: '../templates/modal.html'
})
export class ModalComponent {
public data: Object;
public modal: Object;
cl(event) { console.log(event); }
}
<file_sep>/src/app/app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.html'
})
export class AppComponent {
public selection: string;
constructor() {
this.selection = 'display';
}
}
<file_sep>/src/app/modules/textarea/textarea.component.ts
import { Component, Input, Output, EventEmitter, ViewChild, ElementRef } from '@angular/core';
@Component({
selector: 'parabol-textarea',
templateUrl: './textarea.html'
})
export class ParabolTextareaComponent {
@Output() modelChange = new EventEmitter();
@Input() placeholder: string;
@Input() model: string;
@ViewChild('input') input: ElementRef;
emit() { this.modelChange.emit(this.model); }
}
<file_sep>/src/app/modules/select-button/select-button.module.ts
// Import Angular modules
import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
// Import custom components
import { ParabolSelectButtonComponent } from './select-button.component';
/*
* @NgModule: ParabolSelectButtonModule
*
* An NgModule is a class adorned with the @NgModule decorator function. @NgModule takes a metadata
* object that tells Angular how to compile and run module code. It identifies the module's own
* components, directives, and pipes, making some of them public so external components can use them.
* @NgModule may add service providers to the application dependency injectors.
*/
@NgModule({
imports: [ BrowserModule ],
exports: [ ParabolSelectButtonComponent ],
declarations: [ ParabolSelectButtonComponent ],
schemas: [ CUSTOM_ELEMENTS_SCHEMA ]
})
export class ParabolSelectButtonModule { }
<file_sep>/src/app/modules/display/display.component.ts
// Import Angular modules
import { Component } from '@angular/core';
/*
* @Component: ParabolDisplayComponent
*
* Components are the main way we build and specify elements and logic on the page, through both
* custom elements and attributes that add functionality to our existing components.
*
* This component is used to build Parabol Material Display.
*/
@Component({
selector: 'parabol-display',
templateUrl: './display.html'
})
export class ParabolDisplayComponent {
constructor() {}
}
<file_sep>/src/app/modules/app/modules/select.module.ts
import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HighlightModule } from 'ngx-highlightjs';
// Import custom modules
import { ParabolCheckboxModule } from '../../checkbox/checkbox.module';
import { ParabolSelectModule } from '../../select/select.module';
// Import custom components
import { SelectComponent } from '../components/select.component';
@NgModule({
imports: [
BrowserModule,
ParabolCheckboxModule,
ParabolSelectModule,
HighlightModule.forRoot({ theme: 'color-brewer' })
],
exports: [ SelectComponent ],
declarations: [ SelectComponent ],
schemas: [ CUSTOM_ELEMENTS_SCHEMA ]
})
export class SelectModule { }
<file_sep>/src/app/modules/app/components/datepicker.component.ts
import { Component, DoCheck } from '@angular/core';
@Component({
selector: 'app-datepicker',
templateUrl: '../templates/datepicker.html'
})
export class DatepickerComponent implements DoCheck {
public prefill: any;
public data: string;
ngDoCheck() {
if (this.prefill) { this.data = '2021-06-03'; }
/*if (this.prefill) { this.data = '2021-06-03T00:00:00.000'; }*/
}
}
<file_sep>/src/app/modules/sidebar/sidebar.directive.ts
import { Directive, Input, HostListener, AfterViewChecked } from '@angular/core';
import * as $_ from 'jquery';
const $ = $_;
@Directive({ selector: 'parabol-sidebar' })
export class ParabolSidebarDirective implements AfterViewChecked {
@Input() collapsed: string;
@HostListener('window:resize', ['$event']) onResize(event) {
if (event.target.innerWidth > 769 && this.collapsed !== 'true') { $('parabol-sidebar').addClass('open'); }
else { $('parabol-sidebar').removeClass('open'); }
}
ngAfterViewChecked() {
if (window.innerWidth > 769 && this.collapsed !== 'true') { $('parabol-sidebar').addClass('open'); }
if ($('.toggle').length === 0) {
$('parabol-sidebar').append('<div class="toggle"><div class="bar top"></div><div class="bar middle"></div><div class="bar bottom"></div></div>').click(() => $('parabol-sidebar').toggleClass('open'));
}
}
}
<file_sep>/public_api.ts
export * from './src/app/modules/checkbox/checkbox.module';
export * from './src/app/modules/checkbox_group/checkbox_group.module';
export * from './src/app/modules/datepicker/datepicker.module';
export * from './src/app/modules/radio/radio.module';
export * from './src/app/modules/text/text.module';
export * from './src/app/modules/textarea/textarea.module';
export * from './src/app/modules/select/select.module';
export * from './src/app/modules/slider/slider.module';
export * from './src/app/modules/modal/modal.module';
export * from './src/app/modules/notification/notification.module';
export * from './src/app/modules/loading/loading.module';
export * from './src/app/modules/pending/pending.module';
export * from './src/app/modules/select-button/select-button.module';
export * from './src/app/modules/sidebar/sidebar.module';
<file_sep>/src/app/modules/loading/loading.component.ts
// Import Angular modules
import { Component, Input, OnChanges } from '@angular/core';
import { trigger, state, style, animate, transition, keyframes } from '@angular/animations';
/*
* @Component: ParabolLoadingComponent
*
* Components are the main way we build and specify elements and logic on the page, through both
* custom elements and attributes that add functionality to our existing components.
*
* This component is used to build Parabol Material Loading.
*/
@Component({
selector: 'parabol-loading',
templateUrl: './loading.html',
animations: [
trigger('show', [
state('true' , style({ 'display': 'block', 'pointer-events': 'auto' })),
state('false', style({ 'display': 'none', 'pointer-events': 'none' })),
transition('0 => 1', animate('.1s')),
transition('1 => 0', animate('.3s'))
])
]
})
export class ParabolLoadingComponent implements OnChanges {
public loadingMessage: string;
public show = false;
@Input() loading: any;
ngOnChanges() {
this.show = (this.loading) ? true : false;
this.loading = (typeof this.loading === 'string') ? this.loadingMessage : 'Loading...';
}
}
<file_sep>/src/app/modules/notification/notification.component.ts
// Import Angular modules
import { Component, Input, OnChanges } from '@angular/core';
/*
* @Component: ParabolNotificationComponent
*
* Components are the main way we build and specify elements and logic on the page, through both
* custom elements and attributes that add functionality to our existing components.
*
* This component is used to build Parabol Material Currency input.
*/
@Component({
selector: 'parabol-notification',
templateUrl: './notification.html'
})
export class ParabolNotificationComponent implements OnChanges {
@Input() data: Object;
ngOnChanges() {
if (this.data) {
new Promise(function(resolve, reject) {
setTimeout(func => resolve(null), 3000);
}).then(value => this.data = value);
}
}
}
<file_sep>/README.md
# Material
The material repo contains shared, exported components to be used in all parabol applications.
<file_sep>/src/app/modules/app/modules/slider.module.ts
import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HighlightModule } from 'ngx-highlightjs';
// Import custom modules
import { ParabolCheckboxModule } from '../../checkbox/checkbox.module';
import { ParabolSliderModule } from '../../slider/slider.module';
// Import custom components
import { SliderComponent } from '../components/slider.component';
@NgModule({
imports: [
BrowserModule,
ParabolCheckboxModule,
ParabolSliderModule,
HighlightModule.forRoot({ theme: 'color-brewer' })
],
exports: [ SliderComponent ],
declarations: [ SliderComponent ],
schemas: [ CUSTOM_ELEMENTS_SCHEMA ]
})
export class SliderModule { }
<file_sep>/src/app/modules/app/templates/pending.html
<h2>Pending</h2>
<div class="inner-container">
<parabol-pending [pending]="pending"></parabol-pending>
</div>
<div class="outer-container">
<h3 class="subheading">Usage</h3>
<pre><code highlight>
<![CDATA[
<parabol-pending [pending]="pending"></parabol-pending>
]]>
</code></pre>
<h3 class="subheading">Data</h3>
<p class="param">
<span>pending</span><br> Show the pending component (boolean)
</p>
</div> | 46de22c6d1055e2ab2be7547ce84ff5990a86094 | [
"JavaScript",
"TypeScript",
"HTML",
"Markdown"
]
| 42 | TypeScript | parabol-studio/parabol-material | 7e5c5ff0082e45224124a6f89b6e4792e18d9d48 | 4e670783e41891d5d4a71d23c22ca8e2220c7762 |
refs/heads/master | <file_sep>import React from "react";
const ErrorPage = () => {
return <div className="error-page">This is Error page</div>;
};
export default ErrorPage;
<file_sep>export const createTest = (test) => {
const newTest = {};
newTest.name = test.name;
newTest.pre = "pre";
newTest.questions = [];
for (let i = 0; i < test.questions.length; ++i) {
newTest.questions[i] = {
text: test.questions[i],
id: i + 1,
answers: [],
};
for (let a = 0; a < test.answers.length; ++a) {
newTest.questions[i].answers[a] = {
text: test.answers[a],
id: a + 1,
};
}
newTest.questions[i].answers[0].points = test.reversed.includes(i + 1)
? 0
: 1;
newTest.questions[i].answers[1].points = test.reversed.includes(i + 1)
? 1
: 0;
}
return newTest;
};
<file_sep>import React from "react";
import { BrowserRouter } from "react-router-dom";
import App from "./components/App";
function AppWrapper() {
return (
<React.StrictMode>
<BrowserRouter>
<App />
</BrowserRouter>
</React.StrictMode>
);
}
export default AppWrapper;
<file_sep>import React from "react";
const EndQuiz = ({ points }) => {
return (
<div className="end-quiz">
<p>The quiz is finished</p>
<p>Your points are: {points}</p>
</div>
);
};
export default EndQuiz;
<file_sep>import React, { useState } from "react";
import "./quiz.style.scss";
import PreQuiz from "./preQuiz/preQuiz.component";
import EndQuiz from "./endQuiz/endQuiz.component";
import SingleQuestion from "./singleQuestion/singleQuestion.component";
import test from "../../db/empatia";
import { createTest } from "../../db/createTest";
const myTest = createTest(test);
const Quiz = () => {
const [getQuizState, setQuizState] = useState("start");
const [getQn, setQn] = useState(0);
const [getPoint, setPoint] = useState(0);
const nextQ = (i) => {
setPoint(getPoint + (i + 1));
setQn(getQn + 1);
if (getQn === test.questions.length - 1) {
setQuizState("end");
}
};
const show = () => {
switch (getQuizState) {
case "start":
return <PreQuiz text={myTest.pre} func={() => setQuizState("quiz")} />;
case "quiz":
return (
<SingleQuestion
question={test.questions[getQn]}
answers={test.answers}
ansFunc={(i) => nextQ(i)}
/>
);
case "end":
return <EndQuiz points={getPoint} />;
default:
break;
}
};
return (
<div className="quiz">
<div className="progress-bar"></div>
<div className="content">{show()}</div>
</div>
);
};
export default Quiz;
<file_sep>import React from "react";
import { Switch, Route } from "react-router-dom";
import "./main.style.scss";
import HomePage from "../../pages/homePage/homePage.page";
import QuizesPage from "../../pages/quizesPage/quizesPage.page";
import ErrorPage from "../../pages/errorPage/errorPage.page";
const Main = () => {
return (
<div className="main">
<Switch>
<Route exact path="/" component={HomePage} />
<Route exact path="/quizes" component={QuizesPage} />
<Route component={ErrorPage} />
</Switch>
</div>
);
};
export default Main;
<file_sep>import React from "react";
const PreQuiz = ({ text, func }) => {
return (
<div className="pre-quiz">
<p>{text}</p>
<button onClick={func}>START</button>
</div>
);
};
export default PreQuiz;
<file_sep>const test = {
pre: "this is pre test",
questions: ["quest1", "quest2", "quest3"],
answers: ["yes", "idk", "no"],
final: "this is final text",
};
export default test;
<file_sep>import React from "react";
import { Link } from "react-router-dom";
import "./header.style.scss";
const Header = () => {
return (
<div className="header">
<div className="header-inside">
<div className="logo" />
<ul className="top-nav">
<Link to="/">
<li>Home</li>
</Link>
<Link to="/quizes">
<li>Tests</li>
</Link>
<Link to="/about">
<li>About</li>
</Link>
<Link to="/contact">
<li>Contact</li>
</Link>
</ul>
</div>
</div>
);
};
export default Header;
| 45ad021674e33993c0e6fefc8b33bff35045bdd2 | [
"JavaScript"
]
| 9 | JavaScript | valiopld/psytest | f651890a5e7e2d0409758bbc139a5a2571a7489c | 46633e3eccdffcc5f873f85522bbb6a653418e93 |
refs/heads/master | <file_sep>export default class CategoryType {
categoryId?: number;
name?: string;
imagePath?: string;
parentCategoryId?: number | null;
} | 5c5685c7ba4cae326f6fbde3ced6e28ad5f343dd | [
"TypeScript"
]
| 1 | TypeScript | 30jovic03/webshop-react | 36c856db699703cc64b68a92df301437bd901aae | 5ba173924ae2e7f2e6d3bb56a261cc04df0e1d6a |
refs/heads/master | <repo_name>TurmericSama/Appoint.me<file_sep>/app/Http/Controllers/PagesController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use DB;
class PagesController extends Controller
{
public function __construct() {
$this->middleware( "auth" )->except( "Login", "SignUp", "LoginPost", "SignUpPost", "Fetch", "FetchPost", "GetSent" );
}
public function tokenfieldget( Request $req ){
$uid = $req->session()->get( "user" );
$var = $req->name;
$data =
DB::table('users')
->where('fname','like','%'.$var.'%')
->where('user_id','!=',$uid)
->select(
'fname as label',
'user_id as value'
)->get();
$data = json_encode($data);
echo $data;
}
//fetches all events today
public function Fetch( Request $req ) {
$query = DB::table('appointments')->join('users','=','');
$query = "
select
a.*,
b.*
from
appointments a join
users b
on
a.repeat!=\"Ended\" and
time( now() )>=a.start_time and
time( now() )<=a.end_time and
a.date>=date( now() ) left join
guests c
on
c.appointment_id=a.appointment_id
where
if (b.user_id=( c.user_id is not null, c.user_id, a.creator ))";
$data = json_encode( DB::select( $query ) );
echo $data;
}
//fetches all recorded events that are already sent
public function GetSent( Request $req ){
$ret = [];
$data = DB::table('sent_notifs')->where('for_date',date(now()))->select('appointment_id','user_id')->get();
foreach( $data as $x ) {
$t = [
"uid" => $x->user_id,
"aid" => $x->appointment_id
];
array_push( $ret, $t );
}
echo json_encode( $ret );
}
//inserts events events that has already occured
public function FetchPost( Request $req ) {
$query = DB::table('sent_notifs')->insert([
"appointment_id" => $req->aid,
"user_id" => $req->uid,
"date" => date( now())
]);
}
public function Dash( Request $req ){
return view('pages.Dash');
}
public function info( Request $req){
$id = $req->id;
$query = DB::table('appointments')->where('appointment_id',$id)->select('name','desc','date','start_time','end_time')->get();
$success = json_encode($query);
echo $success;
}
public function DashFetch( Request $req ) {
$uid = $req->session()->get( "user" );
$query =
DB::table('appointments')
->where( 'repeat', '!=', 'deleted' )
->where( 'date', '<=', 'date( now() )' )
->select(
'appointment_id',
'name',
'date',
'start_time',
'end_time',
'repeat'
)->get();
$pdata = [];
foreach( $query as $row ) {
$arr = [
"id" => $row->appointment_id,
"ename" => $row->name,
"edate" => $row->date,
"start_time" => $row->start_time,
"end_time" => $row->end_time,
"repeat" => $row->repeat
];
array_push( $pdata, $arr );
}
$data[ "data" ] = $pdata;
$data = json_encode( $data );
echo $data;
}
public function Events( Request $req ) {
return view( 'pages.Appointments' );
}
public function EventsFetch( Request $req ) {
$id = $req->session()->get( "user" );
$query =
DB::table('appointments')
->where( 'repeat','!=','deleted' )
->where( 'creator', '=', $id )
->select(
'appointment_id',
'name',
'desc',
'date',
'start_time',
'end_time',
'repeat'
)->get();
$data = json_encode($query);
echo $data;
}
public function AddPerson( Request $req ) {
return view('pages.AddUser');
}
public function AddPersonPost( Request $req ) {
$fname = $req->fname;
$lname = $req->lname;
$fname = $fname." ".$lname;
$psid = $req->psid;
$success = 0;
if( DB::table('users')->insert(["fname" => $fname, "user_type" => 0, "facebook_id" => $psid ])){
$success = 1;
}
echo json_encode(["success" => $success]);
}
public function Login( Request $req ) {
if( $req->session()->get( "user" ) ) {
return redirect( "/dash" );
} else {
return view('pages.Login' );
}
}
public function LoginPost( Request $req ) {
$uname = addslashes( $req->username );
$passwd = addslashes( $req->password );
$userq = DB::table('users')->where('uname',$uname)->select('user_id','password')->first();
$success = 0;
if( $userq ) {
if( password_verify( $passwd, $userq->password ) ) {
$req->session()->put( "user", $userq->user_id );
$success = 1;
} else{
$success = 0;
}
}
$json = [ "success" => $success, "user_id" => $req->user, "password" => $<PASSWORD> ];
echo json_encode( $json );
}
public function Add( Request $req ) {
return view('pages.Add');
}
public function AddPost( Request $req ) {
$creator = $req->session()->get( "user" );
$ename = addslashes( $req->ename );
$edesc = addslashes( $req->edesc );
$date = addslashes( $req->date );
$stime = addslashes( $req->stime );
$etime = addslashes( $req->etime );
$epart = addslashes($req->epart );
$epart = explode( ",", $epart );
$repeat = "None";
if( $req->repeatwhen )
$repeat = $req->repeatwhen;
$success = 0;
$error = "None";
$id = DB::table( "appointments" )->insertGetId([
"creator" => $creator,
"name" => $ename,
"desc" => $edesc,
"date" => $date,
"start_time" => $stime,
"end_time" => $etime,
"repeat" => $repeat
]);
if( $id ) {
if( $epartid[0] ) {
foreach( $epartid as $x ) {
if( !intval($x) ) {
continue;
}
$x = addslashes( $x );
$query = DB::table('users')->where('user_id', $x)->count();
if( $query ){
DB::table( "guests" )->insert([
"appointment_id" => $id,
"user_id" => "( select user_id from users where fname=\"$x\" )",
"for_date" => date('Y-m-d'),
"created_at" => now()
]);
$success = 1;
} else {
$error = $query;
}
}
} else {
$success = 1;
}
}
$json = [ "success" => $success, "error" => $error ];
echo json_encode( $json );
}
public function Edit( Request $req ) {
$id = addslashes( $req->id );
$query = "
select a.appointment_id, a.name, a.desc, a.date, a.start_time, a.end_time, a.repeat, b.user_id,c.fname from appointments a left join guests b on a.appointment_id = b.appointment_id join users c on b.user_id = c.user_id where a.appointment_id = $id
";
$fname = "";
$id = "";
$data = DB::select( $query );
foreach( $data as $info){
if( $info->fname == null){
} else{
$fname .= $info->fname.",";
$id .= $info->user_id.",";
}
}
return view( "pages.Edit", [
"data" => $data[0],
"fname" => $fname,
"id" => $id
]);
}
public function EditPost( Request $req ) {
$id = addslashes( $req->id );
$ename = addslashes( $req->ename );
$edesc = addslashes( $req->edesc );
$epartid = $req->epartid;
$epartid = explode( ",", $epartid );
$date = addslashes( $req->date );
$stime = addslashes( $req->stime );
$etime = addslashes( $req->etime );
$repeat = "None";
if( $req->repeat != "None" )
$repeat = addslashes( $req->repeatwhen );
$query = DB::table('appointments')->where('appointment_id', $id)->update([
"name" => $ename,
"desc" => $edesc,
"date" => $date,
"start_time" => $stime,
"end_time" => $etime,
"repeat" => $repeat
]);
$success = 0;
if( $query == 1 )
$success = 1;
$json = [ "success" => $success ];
echo json_encode( $json );
}
public function Delete( Request $req ) {
$id = addslashes( $req->id );
$query = DB::table('appointments')->where('appointment_id', $id )->update(['repeat' => "deleted"]);
$success = 0;
if( $query ){
$success = 1;
} else{
$success = 0;
}
$json = [ "success" => $success ];
echo json_encode( $json );
}
public function SignUp( Request $req ) {
return view('pages.SignUp');
}
public function SignUpPost( Request $req ) {
$uname = addslashes( $req->username );
$passwd = $req->password;
$fname = $req->fname;
$lname = $req->lname;
$fb_id = addslashes( $req->fb_id );
$full = addslashes($fname ." ". $lname );
$passwd = addslashes(password_hash($passwd, PASSWORD_BCRYPT));
$query = DB::table('users')->insert(["uname" => $uname, "password" => <PASSWORD>, "fname" => $full, "facebook_id" => $fb_id, "created_at" => now()]);
if( $query ){
$success = 1;
} else{
$success = 0;
}
$json = [ "success" => $success ];
echo json_encode( $json );
}
public function Logout( Request $req ) {
$req->session()->forget( "user" );
return redirect( "/login" );
}
}
<file_sep>/README.md
# Appoint.me
# Appoint.me
<file_sep>/database/migrations/2019_01_08_223525_create_sent_notifs_table.php
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateSentNotifsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('sent_notifs', function (Blueprint $table) {
$table->increments('snotif_id');
$table->integer( "appointment_id" )->references( "appointments" )->on( "appointment_id" );
$table->integer( "user_id" )->references( "users" )->on( "user_id" );
$table->date( "for_date" );
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('sent_notifs');
}
}
<file_sep>/database/migrations/2018_12_18_070604_create_appointments_table.php
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateAppointmentsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('appointments', function (Blueprint $table) {
$table->increments('appointment_id');
$table->integer( "creator" )->references( "user_id" )->on( "users" );
$table->string('name');
$table->mediumtext('desc');
$table->date('date');
$table->time('start_time');
$table->time('end_time');
$table->string('repeat');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('appointments');
}
}
<file_sep>/routes/web.php
<?php
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
return redirect( "/login" );
});
Route::get( "/addperson", "PagesController@AddPerson");
Route::post( "/addperson", "PagesController@AddPersonPost");
Route::get('/dash', 'PagesController@Dash' );
Route::get( "/dashfetch", "PagesController@DashFetch" );
Route::get( "/eventsfetch", "PagesController@EventsFetch" );
Route::get( "/fetch", "PagesController@Fetch" );
Route::post( "/fetchpost", "PagesController@FetchPost" );
Route::get('/dashgetinfo', 'PagesController@info');
Route::get("/tokenfieldget","PagesController@tokenfieldget");
Route::get('/appointments', 'PagesController@Events');
Route::get('/login', 'PagesController@Login');
Route::post('/login', 'PagesController@LoginPost');
Route::get('/appointments/add', 'PagesController@Add');
Route::post('/appointments/add', 'PagesController@AddPost');
Route::get('/appointments/edit', 'PagesController@Edit');
Route::post('/appointments/edit', 'PagesController@EditPost');
Route::get( "/appointments/delete", "PagesController@Delete");
Route::get("/getsent", "PagesController@GetSent");
Route::get('/signup', 'PagesController@SignUp');
Route::post( "/signup", "PagesController@SignUpPost" );
Route::get('/logout', 'PagesController@Logout');
Route::get('/bobo', function(){
return view("pages.bobo");
}); | d589449222d3bdd2faf43e478e55d70727322e44 | [
"Markdown",
"PHP"
]
| 5 | PHP | TurmericSama/Appoint.me | 2bf2ddf559b3c009462a6ad4ba348795c5158bbf | 65f270bae92f1c211a5c1419665662a943fd82a8 |
refs/heads/master | <repo_name>blpowell/parcel-farce<file_sep>/parcel-domain/src/main/java/uk/co/parcelfarce/domain/Priority.java
package uk.co.parcelfarce.domain;
public enum Priority {
Standard,
NextDay
}
<file_sep>/README.md
# parcel-farce
<file_sep>/parcel-domain/src/main/java/uk/co/parcelfarce/events/ParcelMoved.java
package uk.co.parcelfarce.events;
import uk.gov.dvla.osl.eventsourcing.api.Event;
import java.util.Date;
import java.util.UUID;
public class ParcelMoved implements Event {
private UUID parcelId;
private Date dateOfMovement;
private String location;
public UUID aggregateId() {
return parcelId;
}
}
<file_sep>/parcel-domain/src/main/java/uk/co/parcelfarce/domain/Parcel.java
package uk.co.parcelfarce.domain;
import lombok.*;
@Data
@NoArgsConstructor(access = AccessLevel.PUBLIC)
@AllArgsConstructor(access = AccessLevel.PUBLIC)
@Builder
public class Parcel {
private String recipientName;
private Address recipientAddress;
private String senderName;
private Address senderAddress;
private double weightInKg;
private Priority deliveryPriority;
}
<file_sep>/parcel-domain/src/main/java/uk/co/parcelfarce/domain/Address.java
package uk.co.parcelfarce.domain;
public class Address {
private String line1;
private String line2;
private String line3;
private String postTown;
private String postCode;
}
| a97bba79ece1751de3fbe6cac6d4cf0b0a3920c6 | [
"Markdown",
"Java"
]
| 5 | Java | blpowell/parcel-farce | 3175f4c2231fbe46a6d362eae56d44863889c43a | fdbfc3da57a2de30ae427c12cd6b64bf07690a42 |
refs/heads/master | <repo_name>tmantello/locadora<file_sep>/defes1/Models/GeneroModel.cs
using System;
namespace defes1.Models
{
public class GeneroModel
{
public bool GeneroSelecionado { get; set; }
public int GeneroID { get; set; }
public string GeneroNome { get; set; }
public DateTime GeneroCriacao { get; set; }
public bool GeneroAtivo { get; set; }
}
}
<file_sep>/defes1/Domain/usuario.cs
namespace defes1.Domain
{
public class Usuario
{
public int UsuarioID { get; set; }
public string UsuarioLogin { get; set; }
public string UsuarioSenha { get; set; }
public bool UsuarioAtivo { get; set; }
}
}
<file_sep>/README.md
# Locadora
Entity Framework (Code First) com Dapper
Conforme especificado:
- criar um usuário na área de segurança do SQL Server (EXPRESS - criei com o nome "base" e senha "<PASSWORD>" com permissão de criação de base "dbcreator")
- adicionar este usuário na string de conexão (web.config)
- o resto o EF Code First faz
Obs.: as datas na aplicação estão no formato americano (yyyy/MM/dd, ou seja, 4 dígitos p/ o ano, 2 dígitos para o mês e 2 dígitos para o dia).
<file_sep>/defes1/Models/FilmeModel.cs
using System;
namespace defes1.Models
{
public class FilmeModel
{
public int FilmeID { get; set; }
public string FilmeNome { get; set; }
public DateTime FilmeCriacao { get; set; }
public bool FilmeAtivo { get; set; }
public string Genero { get; set; }
}
}<file_sep>/defes1/Domain/contexto.cs
using System.Data.Entity;
namespace defes1.Domain
{
public class contexto : DbContext
{
public contexto() : base("contexto")
{
this.Configuration.LazyLoadingEnabled = false;
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Filme>()
.HasOptional(x => x.Genero)
.WithOptionalDependent()
.WillCascadeOnDelete(true);
modelBuilder.Entity<Locacao>()
.HasOptional(x => x.Filme)
.WithOptionalDependent()
.WillCascadeOnDelete(true);
}
public DbSet<Usuario> Usuarios { get; set; }
public DbSet<Cliente> Clientes { get; set; }
public DbSet<Locacao> Locacoes { get; set; }
public DbSet<Filme> Filmes { get; set; }
public DbSet<Genero> Generos { get; set; }
}
}
<file_sep>/defes1/Domain/locacao.cs
using System;
using System.Collections.Generic;
namespace defes1.Domain
{
public class Locacao
{
public int LocacaoID { get; set; }
public Filme Filme { get; set; }
public Cliente Cliente { get; set; }
public DateTime LocacaoData { get; set; }
public Usuario Usuario { get; set; }
}
}<file_sep>/defes1/Controllers/LocacaosController.cs
using defes1.Domain;
using defes1.Models;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web.Mvc;
namespace defes1.Controllers
{
public class LocacaosController : Controller
{
private contexto db = new contexto();
// GET: Locacaos
public ActionResult Index()
{
if (Session["UsuarioLogin"] != null)
{
@ViewBag.Usuario = getUser();
List<Locacao> objLocas = db.Locacoes.Include("Filme").Include("Cliente").Include("Usuario").ToList();
if (objLocas != null && objLocas.Count > 0)
{
List<LocacaoModel> objLM = new List<LocacaoModel>();
objLM = objLocas.Select(x => new LocacaoModel
{
LocacaoID = x.LocacaoID,
FilmeID = x.Filme != null ? x.Filme.FilmeID : 0,
FilmeNome = x.Filme != null ? x.Filme.FilmeNome : "INDISPONÍVEL",
ClienteID = x.Cliente != null ? x.Cliente.ClienteID : 0,
ClienteNome = x.Cliente != null ? x.Cliente.ClienteNome : "INDISPONÍVEL",
LocacaoData = x.LocacaoData,
UsuarioID = x.Usuario != null ? x.Usuario.UsuarioID : 0,
UsuarioLogin = x.Usuario != null ? x.Usuario.UsuarioLogin : "IND<PASSWORD>"
}).ToList();
return View(objLM);// db.Locacoes.ToList());
}
else
return View();
}
else
{
return RedirectToAction("Login"); //não logou, volta p/ página de acesso
}
}
// GET: Locacaos/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Locacao locacao = db.Locacoes.Find(id);
if (locacao == null)
{
return HttpNotFound();
}
return View(locacao);
}
// GET: Locacaos/Create
public ActionResult Create()
{
@ViewBag.Usuario = getUser();
//--------------------------
List<Filme> objFilmes = db.Filmes.ToList();
List<SelectListItem> objListaFilmes = new List<SelectListItem>();
foreach (Filme item in objFilmes)
objListaFilmes.Add(new SelectListItem { Text = item.FilmeNome, Value = item.FilmeID.ToString() });
@ViewBag.Filmes = objListaFilmes;
//--------------------------
List<Cliente> objClientes = db.Clientes.ToList();
List<SelectListItem> objListaClientes = new List<SelectListItem>();
foreach (Cliente item in objClientes)
objListaClientes.Add(new SelectListItem { Text = item.ClienteNome, Value = item.ClienteID.ToString() });
@ViewBag.Clientes = objListaClientes;
//--------------------------
List<Usuario> objUsuarios = db.Usuarios.ToList();
List<SelectListItem> objListaUsuarios = new List<SelectListItem>();
foreach (Usuario item in objUsuarios)
objListaUsuarios.Add(new SelectListItem { Text = item.UsuarioLogin, Value = item.UsuarioID.ToString() });
@ViewBag.Usuarios = objListaUsuarios;
//--------------------------
return View();
}
// POST: Locacaos/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "LocacaoID,LocacaoData")] Locacao locacao)
{
if (ModelState.IsValid)
{
locacao.Filme = db.Filmes.ToList().Find(p => p.FilmeID == int.Parse(Request.Form["Filmes"].ToString()));
locacao.Cliente = db.Clientes.ToList().Find(p => p.ClienteID == int.Parse(Request.Form["Clientes"].ToString()));
locacao.Usuario = db.Usuarios.ToList().Find(p => p.UsuarioID == int.Parse(Request.Form["Usuarios"].ToString()));
db.Locacoes.Add(locacao);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(locacao);
}
// GET: Locacaos/Edit/5
public ActionResult Edit(int? id)
{
@ViewBag.Usuario = getUser();
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Locacao locacao = db.Locacoes.Include("Filme").Include("Cliente").Include("Usuario").ToList().Find(p => p.LocacaoID == id);
if (locacao == null)
{
return HttpNotFound();
}
//--------------------------
List<Filme> objFilmes = db.Filmes.ToList();
List<SelectListItem> objListaFilmes = new List<SelectListItem>();
foreach (Filme item in objFilmes)
objListaFilmes.Add(new SelectListItem { Text = item.FilmeNome, Value = item.FilmeID.ToString(), Selected = locacao.Filme.FilmeID == item.FilmeID });
@ViewBag.Filmes = objListaFilmes;
//--------------------------
List<Cliente> objClientes = db.Clientes.ToList();
List<SelectListItem> objListaClientes = new List<SelectListItem>();
foreach (Cliente item in objClientes)
objListaClientes.Add(new SelectListItem { Text = item.ClienteNome, Value = item.ClienteID.ToString(), Selected = locacao.Cliente.ClienteID == item.ClienteID });
@ViewBag.Clientes = objListaClientes;
//--------------------------
List<Usuario> objUsuarios = db.Usuarios.ToList();
List<SelectListItem> objListaUsuarios = new List<SelectListItem>();
foreach (Usuario item in objUsuarios)
objListaUsuarios.Add(new SelectListItem { Text = item.UsuarioLogin, Value = item.UsuarioID.ToString(), Selected = locacao.Usuario.UsuarioID == item.UsuarioID });
@ViewBag.Usuarios = objListaUsuarios;
//--------------------------
return View(locacao);
}
// POST: Locacaos/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "LocacaoID,LocacaoData")] Locacao locacao)
{
if (ModelState.IsValid)
{
db.Entry(locacao).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(locacao);
}
// GET: Locacaos/Delete/5
public ActionResult Delete(int? id)
{
@ViewBag.Usuario = getUser();
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Locacao locacao = db.Locacoes.Include("Filme").Include("Cliente").Include("Usuario").ToList().Find(p => p.LocacaoID == id);
if (locacao == null)
{
return HttpNotFound();
}
return View(locacao);
}
// POST: Locacaos/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
Locacao locacao = db.Locacoes.Find(id);
db.Locacoes.Remove(locacao);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
public string getUser()
{
if (Session["UsuarioLogin"] != null)
return Session["UsuarioLogin"].ToString().Trim().Length > 1 ? Session["UsuarioLogin"].ToString().Trim().ToUpper() : Session["UsuarioLogin"].ToString().Trim();
else
return "";
}
}
}
<file_sep>/defes1/Controllers/FilmeController.cs
using defes1.Domain;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace defes1.Controllers
{
public class FilmeController : Controller
{
contexto db = new contexto();
// GET: Filme
public ActionResult Index()
{
return View(db.Filmes.ToList());
}
// GET: Filme/Details/5
public ActionResult Details(int id)
{
return View();
}
// GET: Filme/Create
public ActionResult Create()
{
return View();
}
// POST: Filme/Create
[HttpPost]
public ActionResult Create(FormCollection collection)
{
try
{
// TODO: Add insert logic here
return RedirectToAction("Index");
}
catch
{
return View();
}
}
// GET: Filme/Edit/5
public ActionResult Edit(int id)
{
return View();
}
// POST: Filme/Edit/5
[HttpPost]
public ActionResult Edit(int id, FormCollection collection)
{
try
{
// TODO: Add update logic here
return RedirectToAction("Index");
}
catch
{
return View();
}
}
// GET: Filme/Delete/5
public ActionResult Delete(int id)
{
return View();
}
// POST: Filme/Delete/5
[HttpPost]
public ActionResult Delete(int id, FormCollection collection)
{
try
{
// TODO: Add delete logic here
return RedirectToAction("Index");
}
catch
{
return View();
}
}
}
}
<file_sep>/defes1/Controllers/HomeController.cs
using defes1.Domain;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
namespace defes1.Controllers
{
public class HomeController : Controller
{
private contexto db = new contexto();
public ActionResult Index()
{
if (Session["UsuarioLogin"] != null)
{
string usuarioLogado = string.Empty;
usuarioLogado = Session["UsuarioLogin"].ToString().Trim().Length > 1 ? Session["UsuarioLogin"].ToString().Trim().ToUpper() : Session["UsuarioLogin"].ToString().Trim();
@ViewBag.Usuario = usuarioLogado;//MvcApplication.GetLoggedUser();
return View();
}
else
{
return RedirectToAction("Login"); //não logou, volta p/ página de acesso
}
}
public ActionResult About()
{
ViewBag.Message = "Your application description page.";
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
public ActionResult Login()
{
@ViewBag.URL = @Request.Url.AbsoluteUri + "Usuarios/Create";
return View();
}
public ActionResult Logout()
{
Session["UsuarioID"] = null;
Session["UsuarioLogin"] = null;
return RedirectToAction("Login");
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Login(Usuario u)
{
// post do login
if (ModelState.IsValid) // verifica estado
{
List<Usuario> objUsuarios = db.Usuarios.ToList();
if (objUsuarios != null)
{
if (objUsuarios.Find(p => p.UsuarioLogin == u.UsuarioLogin && p.UsuarioSenha == u.UsuarioSenha && p.UsuarioAtivo) != null)
{
Usuario objUsuario = objUsuarios.Find(p => p.UsuarioLogin == u.UsuarioLogin && p.UsuarioSenha == u.UsuarioSenha && p.UsuarioAtivo);
if (objUsuario != null)
{
Session["UsuarioID"] = objUsuario.UsuarioID.ToString(); // salva dados do usuário em sessão
Session["UsuarioLogin"] = objUsuario.UsuarioLogin;
FormsAuthentication.SetAuthCookie(objUsuario.UsuarioLogin, false); // autentica usuário e determina tempo de sessão
var authTicket = new FormsAuthenticationTicket(1, objUsuario.UsuarioLogin, DateTime.Now, DateTime.Now.AddMinutes(20), false, "admin");
string encryptedTicket = FormsAuthentication.Encrypt(authTicket);
var authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
HttpContext.Response.Cookies.Add(authCookie);
return RedirectToAction("Index", "Home");
}
}
}
}
return RedirectToAction("Login"); // caso não consiga logar, volta p/ página de acesso
}
}
}<file_sep>/defes1/Domain/cliente.cs
namespace defes1.Domain
{
public class Cliente
{
public int ClienteID { get; set; }
public string ClienteCPF { get; set; }
public string ClienteNome { get; set; }
}
}<file_sep>/defes1/Controllers/FilmesController.cs
using defes1.Domain;
using defes1.Models;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web.Mvc;
namespace defes1.Controllers
{
public class FilmesController : Controller
{
private contexto db = new contexto();
// GET: Filmes
public ActionResult Index()
{
if (Session["UsuarioLogin"] != null)
{
@ViewBag.Usuario = getUser();
List<Filme> objFilmes = db.Filmes.Include("Genero").ToList();
List<FilmeModel> objFM = objFilmes.Select(x => new FilmeModel
{
FilmeID = x.FilmeID,
FilmeNome = x.FilmeNome,
FilmeCriacao = x.FilmeCriacao,
FilmeAtivo = x.FilmeAtivo,
Genero = x.Genero != null ? x.Genero.GeneroNome : "INDISPONÍVEL"
}).ToList();
return View(objFM);//db.Filmes.ToList());
}
else
{
return RedirectToAction("Login"); //não logou, volta p/ página de acesso
}
}
// GET: Filmes/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Filme filme = db.Filmes.Find(id);
if (filme == null)
{
return HttpNotFound();
}
return View(filme);
}
// GET: Filmes/Create
public ActionResult Create() // carregar p/ criar novo filme
{
@ViewBag.Usuario = getUser();
List<Genero> objGeneros = db.Generos.ToList();
List<SelectListItem> objListaGeneros = new List<SelectListItem>();
foreach (Genero item in objGeneros)
objListaGeneros.Add(new SelectListItem {Text = item.GeneroNome, Value = item.GeneroID.ToString()});
ViewBag.Generos = objListaGeneros;
return View();
}
// POST: Filmes/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "FilmeID,FilmeNome,FilmeCriacao,FilmeAtivo")] Filme filme) // salvando novo filme
{
if (ModelState.IsValid)
{
filme.Genero = db.Generos.ToList().Find(p => p.GeneroID == int.Parse(Request.Form["Generos"].ToString()));
db.Filmes.Add(filme);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(filme);
}
// GET: Filmes/Edit/5
public ActionResult Edit(int? id) // editando
{
@ViewBag.Usuario = getUser();
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Filme filme = db.Filmes.Include("Genero").ToList().Find(p => p.FilmeID == id);
if (filme == null)
{
return HttpNotFound();
}
List<Genero> objGeneros = db.Generos.ToList();
List<SelectListItem> objListaGeneros = new List<SelectListItem>();
foreach (Genero item in objGeneros)
objListaGeneros.Add(new SelectListItem { Text = item.GeneroNome, Value = item.GeneroID.ToString(), Selected = filme.Genero.GeneroID == item.GeneroID });
ViewBag.Generos = objListaGeneros;
return View(filme);
}
// POST: Filmes/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "FilmeID,FilmeNome,FilmeCriacao,FilmeAtivo")] Filme filme) // atualizando após edição
{
if (ModelState.IsValid)
{
db.Entry(filme).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(filme);
}
// GET: Filmes/Delete/5
public ActionResult Delete(int? id) // excluindo
{
@ViewBag.Usuario = getUser();
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Filme filme = db.Filmes.Include("Genero").ToList().Find(p => p.FilmeID == id);
if (filme == null)
{
return HttpNotFound();
}
return View(filme);
}
// POST: Filmes/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id) // executando exclusão
{
Filme filme = db.Filmes.Find(id);
db.Filmes.Remove(filme);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
public string getUser()
{
if (Session["UsuarioLogin"] != null)
return Session["UsuarioLogin"].ToString().Trim().Length > 1 ? Session["UsuarioLogin"].ToString().Trim().ToUpper() : Session["UsuarioLogin"].ToString().Trim();
else
return "";
}
}
}
<file_sep>/defes1/Models/LocacaoModel.cs
using System;
namespace defes1.Models
{
public class LocacaoModel
{
public int LocacaoID { get; set; }
public int FilmeID { get; set; }
public string FilmeNome { get; set; }
public int ClienteID { get; set; }
public string ClienteNome { get; set; }
public DateTime LocacaoData { get; set; }
public int UsuarioID { get; set; }
public string UsuarioLogin { get; set; }
}
}<file_sep>/defes1/Domain/genero.cs
using System;
using System.ComponentModel.DataAnnotations;
namespace defes1.Domain
{
public class Genero
{
public int GeneroID { get; set; }
public string GeneroNome { get; set; }
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}")]
public DateTime GeneroCriacao { get; set; }
public bool GeneroAtivo { get; set; }
}
}<file_sep>/defes1/Controllers/GeneroesController.cs
using defes1.Domain;
using defes1.Models;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web.Mvc;
using System.Web;
namespace defes1.Controllers
{
public class GeneroesController : Controller
{
private contexto db = new contexto();
// GET: Generoes
public ActionResult Index()
{
if (Session["UsuarioLogin"] != null)
{
@ViewBag.Usuario = getUser();
List<Genero> objLista = db.Generos.ToList();
if (objLista != null && objLista.Count > 0)
{
List<GeneroModel> generoModels = new List<GeneroModel>();
foreach (Genero item in objLista)
{
generoModels.Add(new GeneroModel
{ GeneroAtivo = item.GeneroAtivo,
GeneroCriacao = item.GeneroCriacao,
GeneroID = item.GeneroID,
GeneroNome = item.GeneroNome
});
}
return View(generoModels);
}
else
return View();
}
else
{
return RedirectToAction("Login"); //não logou, volta p/ página de acesso
}
}
// ---------------------------------------------------
//[HttpPost]//, ActionName("Index")]
//[ValidateAntiForgeryToken]
//public ActionResult Index(IEnumerable<GeneroModel> GeneroModel)
//{
// if (GeneroModel.Count(x => x.GeneroSelecionado) == 0)
// return View(db.Generos.ToList()); // não faz nada
// else
// {
// foreach (GeneroModel item in GeneroModel)
// {
// if (item.GeneroSelecionado) // excluir selecionados
// {
// Genero genero = db.Generos.Find(item.GeneroID);
// db.Generos.Remove(genero);
// db.SaveChanges();
// }
// }
// }
// return View(db.Generos.ToList());
//}
[HttpPost]
public ActionResult Delete(IEnumerable<int> generoIdsToDelete)
{
List<Genero> objLista = db.Generos.ToList();
foreach (int item in generoIdsToDelete)
{
foreach (Genero gen in objLista)
{
if (item == gen.GeneroID)
{
Genero genero = db.Generos.Find(item);
db.Generos.Remove(genero);
db.SaveChanges();
break;
}
}
}
return RedirectToAction("Index");
}
// ---------------------------------------------------
// GET: Generoes/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Genero genero = db.Generos.Find(id);
if (genero == null)
{
return HttpNotFound();
}
return View(genero);
}
// GET: Generoes/Create
public ActionResult Create()
{
@ViewBag.Usuario = getUser();
return View();
}
// POST: Generoes/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "GeneroID,GeneroNome,GeneroCriacao,GeneroAtivo")] Genero genero)
{
if (ModelState.IsValid)
{
db.Generos.Add(genero);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(genero);
}
// GET: Generoes/Edit/5
public ActionResult Edit(int? id)
{
@ViewBag.Usuario = getUser();
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Genero genero = db.Generos.Find(id);
if (genero == null)
{
return HttpNotFound();
}
return View(genero);
}
// POST: Generoes/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "GeneroID,GeneroNome,GeneroCriacao,GeneroAtivo")] Genero genero)
{
if (ModelState.IsValid)
{
db.Entry(genero).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(genero);
}
// GET: Generoes/Delete/5
public ActionResult Delete(int? id)
{
@ViewBag.Usuario = getUser();
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Genero genero = db.Generos.Find(id);
if (genero == null)
{
return HttpNotFound();
}
return View(genero);
}
// POST: Generoes/Delete/5
//[HttpPost, ActionName("Delete")]
//[ValidateAntiForgeryToken]
//public ActionResult DeleteConfirmed(int id)
//{
// Genero genero = db.Generos.Find(id);
// db.Generos.Remove(genero);
// db.SaveChanges();
// return RedirectToAction("Index");
//}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
public string getUser()
{
if (Session["UsuarioLogin"] != null)
return Session["UsuarioLogin"].ToString().Trim().Length > 1 ? Session["UsuarioLogin"].ToString().Trim().ToUpper() : Session["UsuarioLogin"].ToString().Trim();
else
return "";
}
}
}
<file_sep>/defes1/Controllers/LocacaoController.cs
using defes1.Domain;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace defes1.Controllers
{
public class LocacaoController : Controller
{
contexto db = new contexto();
// GET: Locacao
public ActionResult Index()
{
return View(db.Locacoes.ToList());
}
// GET: Locacao/Details/5
public ActionResult Details(int id)
{
return View();
}
// GET: Locacao/Create
public ActionResult Create()
{
return View();
}
// POST: Locacao/Create
[HttpPost]
public ActionResult Create(FormCollection collection)
{
try
{
// TODO: Add insert logic here
return RedirectToAction("Index");
}
catch
{
return View();
}
}
// GET: Locacao/Edit/5
public ActionResult Edit(int id)
{
return View();
}
// POST: Locacao/Edit/5
[HttpPost]
public ActionResult Edit(int id, FormCollection collection)
{
try
{
// TODO: Add update logic here
return RedirectToAction("Index");
}
catch
{
return View();
}
}
// GET: Locacao/Delete/5
public ActionResult Delete(int id)
{
return View();
}
// POST: Locacao/Delete/5
[HttpPost]
public ActionResult Delete(int id, FormCollection collection)
{
try
{
// TODO: Add delete logic here
return RedirectToAction("Index");
}
catch
{
return View();
}
}
}
}
<file_sep>/defes1/Domain/filme.cs
using System;
namespace defes1.Domain
{
public class Filme
{
public int FilmeID { get; set; }
public string FilmeNome { get; set; }
public DateTime FilmeCriacao { get; set; }
public bool FilmeAtivo { get; set; }
public Genero Genero { get; set; }
}
} | 942bceb9ee5ebd5c52d46057620afb59862f1dc1 | [
"Markdown",
"C#"
]
| 16 | C# | tmantello/locadora | 719b687c937480f8cd7f5a992ff3d5097e22d243 | f11016ab6be754a25fe5c5afad22dbe5469f7d09 |
refs/heads/master | <file_sep>#ifndef MPSCREEN_H
#define MPSCREEN_H
#include <QObject>
#include <QRect>
class MpScreen : public QRect
{
public:
MpScreen(int, int, int, int);
MpScreen(QRect *);
};
#endif // MPSCREEN_H
<file_sep>//=============================================================================
// MuseScore
// Linux Music Score Editor
// $Id: icons.h 5246 2012-01-24 18:48:55Z wschweer $
//
// Copyright (C) 2002-2009 <NAME> and others
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 2.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
//=============================================================================
#ifndef __ICONS_H__
#define __ICONS_H__
#include "../all.h"
namespace Ms {
extern void genIcons();
#ifdef TABLET
enum class Icons : int
#else
enum class Icons : signed char
#endif
{ Invalid_ICON = -1,
longaUp_ICON, brevis_ICON, note_ICON, note2_ICON, note4_ICON, note8_ICON, note16_ICON,
note32_ICON, note64_ICON, note128_ICON,
natural_ICON, sharp_ICON, sharpsharp_ICON, flat_ICON, flatflat_ICON,
quartrest_ICON, dot_ICON, dotdot_ICON,
flip_ICON,
undo_ICON, redo_ICON, cut_ICON, copy_ICON, paste_ICON, swap_ICON, print_ICON, clef_ICON,
midiin_ICON, speaker_ICON, start_ICON, play_ICON, repeat_ICON, pan_ICON,
sbeam_ICON, mbeam_ICON, nbeam_ICON, beam32_ICON, beam64_ICON, abeam_ICON, fbeam1_ICON, fbeam2_ICON,
file_ICON, fileOpen_ICON, fileNew_ICON, fileSave_ICON, fileSaveAs_ICON,
window_ICON, acciaccatura_ICON, appoggiatura_ICON,
grace4_ICON, grace16_ICON, grace32_ICON,
grace8after_ICON, grace16after_ICON, grace32after_ICON,
noteEntry_ICON, // noteEntrySteptime_ICON, (using normal icon for the time being.)
noteEntryRepitch_ICON, noteEntryRhythm_ICON, noteEntryRealtimeAuto_ICON, noteEntryRealtimeManual_ICON,
keys_ICON, tie_ICON,
textBold_ICON, textItalic_ICON, textUnderline_ICON,
textLeft_ICON, textCenter_ICON, textRight_ICON, textTop_ICON, textBottom_ICON, textVCenter_ICON, textBaseline_ICON,
textSuper_ICON, textSub_ICON,
fotomode_ICON,
hraster_ICON, vraster_ICON,
formatListUnordered_ICON, formatListOrdered_ICON,
formatIndentMore_ICON, formatIndentLess_ICON,
loop_ICON, loopIn_ICON, loopOut_ICON, metronome_ICON, countin_ICON,
vframe_ICON, hframe_ICON, tframe_ICON, fframe_ICON, measure_ICON, checkmark_ICON,
helpContents_ICON, goHome_ICON, goPrevious_ICON, goNext_ICON, viewRefresh_ICON,
brackets_ICON,
timesig_allabreve_ICON, timesig_common_ICON, timesig_prolatio01_ICON, timesig_prolatio02_ICON,
timesig_prolatio03_ICON, timesig_prolatio04_ICON, timesig_prolatio05_ICON, timesig_prolatio07_ICON,
timesig_prolatio08_ICON, timesig_prolatio10_ICON, timesig_prolatio11_ICON, edit_ICON, reset_ICON, close_ICON,
arrowUp_ICON, arrowDown_ICON,
#ifdef TABLET
myscore_ICON, palette_ICON, clefs_ICON, keysignatures_ICON, timesignatures_ICON, accidentals_ICON,
articulations_ICON, lines_ICON, barlines_ICON, texts_ICON, tempi_ICON, dynamics_ICON, endings_ICON, jumps_ICON,
menu_lines_ICON, menu_dots_ICON, edit_tools_ICON, zoom_ICON, settings_ICON, mixer_ICON, exit_ICON,
#endif
voice1_ICON, voice2_ICON, voice3_ICON, voice4_ICON,
ICONS
};
extern QIcon* icons[];
} // namespace Ms
#endif
<file_sep>#include "mpmusepad.h"
#include "shortcut.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MusePad w;
w.show();
//tEST git
return a.exec();
}
<file_sep>#ifndef MPPALETTEBOX_H
#define MPPALETTEBOX_H
#include <QWidget>
#include "palette.h"
#include <QDockWidget>
#include <QVBoxLayout>
namespace Ui {
class MpPaletteBox;
class Palette;
}
class MpPaletteBox : public QDockWidget {
Q_OBJECT
QVBoxLayout* vbox;
public:
MpPaletteBox(QWidget *parent = nullptr );
~MpPaletteBox();
void mpSetPalette(QAction*, bool);
void mpAddPalette(Ms::Palette* p, QString label);
private:
struct PaletteItem {
~PaletteItem();
QString label; // used as index
Ms::Palette* palette;
};
QList<PaletteItem*> paletteList;
};
#endif // MPPALETTEBOX_H
<file_sep>#include "mppalettebox.h"
#include "ui_mppalettebox.h"
#include "palette.h"
#include <QPushButton>
#include <QMessageBox>
MpPaletteBox::MpPaletteBox(QWidget* parent)
: QDockWidget(tr("Palettes"), parent)
{
setObjectName("palette-box");
setAllowedAreas(Qt::LeftDockWidgetArea);
QWidget* w = new QWidget(this);
w->setContextMenuPolicy(Qt::NoContextMenu);
QVBoxLayout* vbox = new QVBoxLayout(w);
vbox->setMargin(0);
setWidget(w);
}
MpPaletteBox::~MpPaletteBox()
{
// delete ui;
}
void MpPaletteBox::mpAddPalette(Ms::Palette* p, QString label)
{
/* PaletteItem *pi = new PaletteItem();
pi->label = label;
pi->palette = p;
paletteList.append(pi);
*/
}
void MpPaletteBox::mpSetPalette(QAction* a, bool visible)
{
QString s = a->data().toString();
/*
for (int i=0;i<paletteList.size();i++){
if(s==paletteList[i]->label){
Ms::Palette* p = paletteList[i]->palette;
psa->setWidget(p); When we have a palette
psa->setWidget(b);
this->setVisible(true);
psa->setVisible(true);
break;
}
*/
QPushButton* b = new QPushButton (s);
vbox->addWidget(b);
}
<file_sep>//=============================================================================
// MuseScore
// Linux Music Score Editor
// $Id: icons.cpp 5246 2012-01-24 18:48:55Z wschweer $
//
// Copyright (C) 2002-2007 <NAME> and others
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 2.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
//=============================================================================
#include "mptablet.h"
#include "globals.h"
#include "icons.h"
#ifndef TABGUI
#include "libmscore/score.h"
#include "libmscore/style.h"
#include "libmscore/sym.h"
#include "libmscore/mscore.h"
#include "miconengine.h"
#endif
#include "preferences.h"
namespace Ms {
#ifndef TABLET
extern QString iconPath;
#else
QString iconPath = QString(":/data/icons/");
#endif
QIcon* icons[int(Icons::ICONS)];
//---------------------------------------------------------
// genIcons
// create some icons
//---------------------------------------------------------
static const char* iconNames[] = {
"note-longa.svg",
"note-breve.svg",
"note-1.svg",
"note-2.svg",
"note-4.svg",
"note-8.svg",
"note-16.svg",
"note-32.svg",
"note-64.svg",
"note-128.svg",
"note-natural.svg",
"note-sharp.svg",
"note-double-sharp.svg",
"note-flat.svg",
"note-double-flat.svg",
"rest.svg",
"note-dot.svg",
"note-double-dot.svg",
"stem-flip.svg",
"edit-undo.svg",
"edit-redo.svg",
"edit-cut.svg",
"edit-copy.svg",
"edit-paste.svg",
"edit-swap.svg",
"document-print.svg",
"clef.svg",
"midi-input.svg",
"sound-while-editing.svg",
"media-skip-backward.svg",
"media-playback-start.svg",
"media-playback-repeats.svg",
"media-playback-pan.svg",
"sbeam.svg",
"mbeam.svg",
"nbeam.svg",
"beam32.svg",
"beam64.svg",
"default.svg",
"fbeam1.svg",
"fbeam2.svg",
"document.svg",
"document-open.svg",
"document-new.svg",
"document-save.svg",
"document-save-as.svg",
"mscore.png",
"acciaccatura.svg",
"appoggiatura.svg",
"grace4.svg",
"grace16.svg",
"grace32.svg",
"grace8after.svg",
"grace16after.svg",
"grace32after.svg",
"mode-notes.svg",
// "mode-notes-steptime.svg", (using normal icon for the time being.)
"mode-notes-repitch.svg",
"mode-notes-rhythm.svg",
"mode-notes-realtime-auto.svg",
"mode-notes-realtime-manual.svg",
"insert-symbol.svg",
"note-tie.svg",
"format-text-bold.svg",
"format-text-italic.svg",
"format-text-underline.svg",
"format-justify-left.svg",
"format-justify-center.svg",
"format-justify-right.svg",
"align-vertical-top.svg",
"align-vertical-bottom.svg",
"align-vertical-center.svg",
"align-vertical-baseline.svg",
"format-text-superscript.svg",
"format-text-subscript.svg",
"mode-photo.svg",
"raster-horizontal.svg",
"raster-vertical.svg",
"list-unordered.svg",
"list-ordered.svg",
"format-indent-more.svg",
"format-indent-less.svg",
"media-playback-loop.svg",
"media-playback-loop-in.svg",
"media-playback-loop-out.svg",
"media-playback-metronome.svg",
"media-playback-countin.svg",
"frame-vertical.svg",
"frame-horizontal.svg",
"frame-text.svg",
"frame-fretboard.svg",
"measure.svg",
"object-select.svg",
"help-contents.svg",
"go-home.svg",
"go-previous.svg",
"go-next.svg",
"view-refresh.svg",
"brackets.svg",
"timesig_allabreve.svg",
"timesig_common.svg",
"timesig_prolatio01.svg",
"timesig_prolatio02.svg",
"timesig_prolatio03.svg",
"timesig_prolatio04.svg",
"timesig_prolatio05.svg",
"timesig_prolatio07.svg",
"timesig_prolatio08.svg",
"timesig_prolatio10.svg",
"timesig_prolatio11.svg",
"edit.svg",
"edit-reset.svg",
"window-close.svg",
"arrow_up.svg",
"arrow_down.svg",
#ifdef TABLET
"myscore-logo.svg",
"palette.png",
"palette-clefs.svg",
"palette-keysignatures.svg",
"palette-timesignatures.svg",
"palette-accidentals.svg",
"palette-articulations.svg",
"palette-lines.svg",
"palette-barlines.svg",
"palette-texts.svg",
"palette-tempi.svg",
"palette-dynamics.svg",
"palette-endings.svg",
"palette-jumps.svg",
"menu-3-lines.svg",
"menu-3-dots.svg",
"ballpoint-pen.png",
"magnifying-glass.svg",
"settings-dial.png",
"mixer.png",
"application-exit.svg",
#endif
};
void genIcons()
{
for (int i = 0; i < int(Icons::voice1_ICON); ++i) {
#ifndef TABLET
QIcon* icon = new QIcon(new MIconEngine);
#else
QIcon* icon = new QIcon();
#endif
icon->addFile(iconPath + iconNames[i]);
icons[i] = icon;
if (icons[i]->isNull() || icons[i]->pixmap(12).isNull()) {
qDebug("cannot load Icon <%s>", qPrintable(iconPath + iconNames[i]));
}
}
#ifndef TABLET
static const char* vtext[VOICES] = { "1","2","3","4" };
int iw = preferences.iconHeight * 2 / 3; // 16;
int ih = preferences.iconHeight; // 24;
for (int i = 0; i < VOICES; ++i) {
icons[int(Icons::voice1_ICON) + i] = new QIcon;
QPixmap image(iw, ih);
QColor c(MScore::selectColor[i].lighter(180));
image.fill(c);
QPainter painter(&image);
painter.setFont(QFont("FreeSans", 8));
painter.setRenderHint(QPainter::Antialiasing);
painter.setRenderHint(QPainter::TextAntialiasing);
painter.setPen(QPen(Qt::black));
painter.drawText(QRect(0, 0, iw, ih), Qt::AlignCenter, vtext[i]);
painter.end();
icons[int(Icons::voice1_ICON) +i]->addPixmap(image);
painter.begin(&image);
c = QColor(MScore::selectColor[i].lighter(140));
painter.fillRect(0, 0, iw, ih, c);
painter.setPen(QPen(Qt::black));
painter.drawText(QRect(0, 0, iw, ih), Qt::AlignCenter, vtext[i]);
painter.end();
icons[int(Icons::voice1_ICON) + i]->addPixmap(image, QIcon::Normal, QIcon::On);
}
#endif
}
} // Ms
<file_sep>#include "mpscreen.h"
MpScreen::MpScreen(int x, int y, int w, int h)
{
setX(x);
setY(y);
setWidth(w);
setHeight(h);
}
MpScreen::MpScreen(QRect *r)
{
setX(r->x());
setY(r->y());
setWidth(r->width());
setHeight(r->height());
}
<file_sep>#ifndef MPMUSEPAD_H
#define MPMUSEPAD_H
#include <QMainWindow>
#include <QtWidgets>
#include <QRect>
#include <string>
#include "mpkeyboard.h"
#include "mpvoices.h"
#include "mpscreen.h"
#include "mptoolbutton.h"
#include "mppalettebox.h"
#include "mpsettings.h"
#include "toolbuttonmenu.h"
#include "shortcut.h"
#include "globals.h"
#include "../libmscore/musescoreCore.h"
#include "../all.h"
namespace Ui {
class MusePad;
class Shortcut;
}
enum LayoutMode {
PAGE = 0,
LINE = 1 << 0,
SYSTEM = 1 << 1
};
class MusePad : public QMainWindow, public MuseScoreCore
{
Q_OBJECT
public:
explicit MusePad(QWidget *parent = 0);
~MusePad();
void genIcons();
QAction* getAction(const char* id);
private slots:
void mpCmd (const char *);
void mpCmd (QString, QString);
void mpCmd (QAction *);
void setBaseSize (QRect *);
void cmd (QAction *);
void helpBrowser1() const;
void tutorial () const;
void about();
void aboutQt();
void aboutMusicXML();
void reportBug();
void switchLayoutMode (int);
signals:
private:
Ui::MusePad *ui;
MpScreen *baseSize;
Ms::Shortcut *shortcut;
MpKeyboard *mpKeyboard;
MpVoices *mpVoiceBox;
MpPaletteBox *paletteBox;
MpSettings *settings;
QDockWidget *mpKeyboardPanel;
QDockWidget *palettePanel;
QToolBar *mpMainTools;
QToolBar *mpPlayTools;
QToolBar *paletteOneTools;
QToolBar *paletteTwoTools;
QToolButton *mpFileButton;
QToolButton *mpMagButton;
QToolButton *mpSettingsButton;
QToolButton *mpEditButton;
QToolButton *mpScoreButton;
Ms::ToolButtonMenu *mpNoteInputButton;
QMenu *mpFileMenu;
QMenu *mpMagMenu;
QMenu *mpSettingsMenu;
QMenu *mpEditMenu;
QMenu *mpScoreMenu;
QMenu *mpTupletsMenu;
QMenu *mpAddTextMenu;
QMenu *mpHelpMenu;
void mpInit();
void mpPrepareToolbars ();
void mpShowPalette(QAction* a);
QAction* mpGetAction (const char* id);
int getVoice ();
void showMessage(const QString& s, int timeout);
void setSize (QWidget*, MpScreen*);
QComboBox *viewModeCombo;
QAction *repeatAction;
QAction *panAction;
QAction *metronomeAction;
QAction *mpVoiceAction;
QAction *aboutAction;
QAction *aboutQtAction;
QAction *aboutMusicXMLAction;
QAction *tutorialAction;
QAction *reportBugAction;
QString currentPalette;
QAction *mpPaletteAction;
int m_voiceSet;
};
#endif // MPMUSEPAD_H
<file_sep>#ifndef MUSESCORECORE_H
#define MUSESCORECORE_H
#include "mptablet.h"
namespace Ui {
class MuseScoreCore;
}
class MuseScoreCore
{
protected:
#ifndef TABGUI
Score* cs { 0 }; // current score
QList<Score*> scoreList;
#endif
public:
static MuseScoreCore* mscoreCore;
// MuseScoreCore() { mscoreCore = this; }
MuseScoreCore();
#ifndef TABGUI//
Score* currentScore() const { return cs; }
void setCurrentScore(Score* score) { cs = score; }
virtual bool saveAs(Score*, bool /*saveCopy*/, const QString& /*path*/, const QString& /*ext*/) { return false; }
virtual void closeScore(Score*) {}
virtual void cmd(QAction* /*a*/) {}
virtual void setCurrentView(int /*tabIdx*/, int /*idx*/) {}
virtual int appendScore(Score* s) { scoreList.append(s); return 0; }
virtual void endCmd() {}
virtual Score* openScore(const QString& /*fn*/) { return 0;}
QList<Score*>& scores() { return scoreList; }
#endif
};
#endif // MUSESCORECORE_H
<file_sep>#include "musescorecore.h"
MuseScoreCore::MuseScoreCore()
{
}
<file_sep>#ifndef MPTABLET_H
#define MPTABLET_H
#define TABGUI
#define TABLET
#endif
<file_sep>#ifndef MPVOICES_H
#define MPVOICES_H
#include <QWidget>
namespace Ui {
class MpVoices;
}
class MpVoices : public QWidget
{
Q_OBJECT
public:
explicit MpVoices(QWidget *parent = nullptr);
~MpVoices();
private slots:
void on_voice1Button_clicked();
void on_voice2Button_clicked();
void on_voice3Button_clicked();
void on_voice4Button_clicked();
signals:
void voiceChanged (int);
private:
Ui::MpVoices *ui;
void setButtons(int);
void resetButtons();
int m_voiceSet;
};
#endif // MPVOICES_H
<file_sep>
#include <QGraphicsColorizeEffect>
#include <QToolButton>
#include "mptoolbutton.h"
MpToolButton::MpToolButton(QWidget* parent, QAction* defaultQAction ): QToolButton(parent)
{
setDefaultAction(defaultQAction);
setFocusPolicy(Qt::TabFocus);
setPopupMode(QToolButton::InstantPopup);
}
<file_sep>#ifndef MPKEYBOARD_H
#define MPKEYBOARD_H
#include "shortcut.h"
#include <QWidget>
namespace Ui {
class MpKeyboard;
}
class MpKeyboard : public QWidget
{
Q_OBJECT
public:
explicit MpKeyboard(QWidget *parent = 0);
~MpKeyboard();
public slots:
void setVoice(int);
private slots:
void on_noteEntry_clicked();
void on_keyA_clicked();
void on_keyB_clicked();
void on_keyC_clicked();
void on_keyD_clicked();
void on_keyE_clicked();
void on_keyF_clicked();
void on_keyG_clicked();
void on_keyRest_clicked();
void on_keyTie_clicked();
void on_keyIns_clicked();
void on_key128_clicked();
void on_key64_clicked();
void on_key32_clicked();
void on_key16_clicked();
void on_key8_clicked();
void on_key4_clicked();
void on_key2_clicked();
void on_key1_clicked();
void on_keyDot_clicked();
void on_keyDel_clicked();
void on_keySlur_clicked();
void on_keyFlip_clicked();
void on_keyTriplet_clicked();
void on_keySharp_clicked();
void on_keyFlat_clicked();
void on_keyNatural_clicked();
void on_keyShift_clicked();
void on_keyCmd_clicked();
void on_keyLeft_clicked();
void on_keyDown_clicked();
void on_keyUp_clicked();
void on_keyRight_clicked();
void on_voiceButton_clicked();
signals:
void keyAction (QAction *);
void keyAction (const char *);
void keyAction (int, int);
void keyAction (QString, QString);
private:
Ui::MpKeyboard *ui;
void pitchKey (int);
void durationKey (int);
void functionKey (int);
void specialKey (int);
void setFlat (int, bool);
void resetModifiers ();
void sendKey (int, int);
QAction* getAction(const char* id);
QWidget *_mpad;
bool shiftOn;
bool cmdOn;
bool dotOn;
bool noteEntryOn;
int m_currenDuration;
enum Key
{
KEY_NOTE,
KEY_SHIFT,
KEY_CMD,
KEY_INS,
KEY_DEL,
KEY_LEFT,
KEY_RIGHT,
KEY_UP,
KEY_DOWN,
KEY_SLUR,
KEY_FLIP,
KEY_DOT,
KEY_TIE,
KEY_TUPLET,
KEY_REST,
KEY_A,
KEY_B,
KEY_C,
KEY_D,
KEY_E,
KEY_F,
KEY_G,
KEY_SHARP,
KEY_FLAT,
KEY_NATURAL,
KEY_128,
KEY_64,
KEY_32,
KEY_16,
KEY_8,
KEY_4,
KEY_2,
KEY_1,
KEY_NONE
};
};
#endif // MPKEYBOARD_H
<file_sep>#include "mpsettings.h"
#include "ui_mpsettings.h"
MpSettings::MpSettings(QWidget *parent) :
QDialog(parent),
ui(new Ui::MpSettings)
{
ui->setupUi(this);
this->setWindowFlag(Qt::FramelessWindowHint);
on_smallPButton_clicked(true);
}
MpSettings::~MpSettings()
{
delete ui;
}
void MpSettings::accept()
{
emit setBaseSize(new QRect (baseX, baseY, baseWidth, baseHeight ));
done(1);
}
void MpSettings::on_smallPButton_clicked(bool checked)
{
if (checked)
{
baseX = 50;
baseY = 100;
baseWidth = 290;
baseHeight = 460;
}
}
void MpSettings::on_mediumPButton_clicked(bool checked)
{
if (checked)
{
baseX = 50;
baseY = 50;
baseWidth = 560;
baseHeight = 900;
}
}
void MpSettings::on_mediumLButton_clicked(bool checked)
{
if (checked)
{
baseX = 50;
baseY = 50;
baseWidth = 900;
baseHeight = 560;
}
}
<file_sep>#include "mpkeyboard.h"
#include "shortcut.h"
#include "ui_mpkeyboard.h"
MpKeyboard::MpKeyboard(QWidget *parent) :
QWidget(parent),
ui(new Ui::MpKeyboard)
{
ui->setupUi(this);
// -----------------------
// Initialize
// -----------------------
noteEntryOn = false;
setFlat(KEY_NOTE,false);
shiftOn = false;
setFlat(KEY_SHIFT, false);
cmdOn = false;
setFlat(KEY_CMD, false);
durationKey(KEY_4);
}
MpKeyboard::~MpKeyboard()
{
delete ui;
}
// -----------------------------
// Keyboard handlers
// -----------------------------
void MpKeyboard::resetModifiers()
{
ui->keyCmd->setChecked(false);
cmdOn = false;
ui->keyShift->setChecked(false);
shiftOn = false;
}
void MpKeyboard::pitchKey(int key)
{
if (shiftOn)
switch (key) {
case KEY_A: emit keyAction("chord-a");
break;
case KEY_B: emit keyAction("chord-b");
break;
case KEY_C: emit keyAction("chord-c");
break;
case KEY_D: emit keyAction("chord-d");
break;
case KEY_E: emit keyAction("chord-e");
break;
case KEY_F: emit keyAction("chord-f");
break;
case KEY_G: emit keyAction("chord-g");
break;
}
else
switch (key) {
case KEY_A: emit keyAction("note-a");
break;
case KEY_B: emit keyAction("note-b");
break;
case KEY_C: emit keyAction("note-c");
break;
case KEY_D: emit keyAction("note-d");
break;
case KEY_E: emit keyAction("note-e");
break;
case KEY_F: emit keyAction("note-f");
break;
case KEY_G: emit keyAction("note-g");
break;
case KEY_REST: emit keyAction("pad-rest");
break;
case KEY_SHARP: emit keyAction("sharp");
break;
case KEY_FLAT: emit keyAction("flat");
break;
case KEY_NATURAL: emit keyAction("nat");
break;
default:
break;
}
resetModifiers ();
}
void MpKeyboard::durationKey(int key)
{
// --------------------------
// Generate external signals for note duration
// --------------------------
if (shiftOn)
switch (key) {
case KEY_128: emit keyAction("interval1");
break;
case KEY_64: emit keyAction("interval2");
break;
case KEY_32: emit keyAction("interval3");
break;
case KEY_16: emit keyAction("interval4");
break;
case KEY_8: emit keyAction("interval5");
break;
case KEY_4: emit keyAction("interval6");
break;
case KEY_2: emit keyAction("interval7");
break;
case KEY_1: emit keyAction("interval8");
break;
default:
break;
}
else if (cmdOn)
switch (key) {
case KEY_128: emit keyAction("interval1");
break;
case KEY_64: emit keyAction("interval-2");
break;
case KEY_32: emit keyAction("interval-3");
break;
case KEY_16: emit keyAction("interval-4");
break;
case KEY_8: emit keyAction("interval-5");
break;
case KEY_4: emit keyAction("interval-6");
break;
case KEY_2: emit keyAction("interval-7");
break;
case KEY_1: emit keyAction("interval-8");
break;
default:
break;
}
else
switch (key) {
case KEY_128: emit keyAction("pad-note-128");
break;
case KEY_64: emit keyAction("pad-note-64");
break;
case KEY_32: emit keyAction("pad-note-32");
break;
case KEY_16: emit keyAction("pad-note-16");
break;
case KEY_8: emit keyAction("pad-note-8");
break;
case KEY_4: emit keyAction("pad-note-4");
break;
case KEY_2: emit keyAction("pad-note-2");
break;
case KEY_1: emit keyAction("pad-note-1");
break;
case KEY_DOT:
emit keyAction("pad-dot");
break;
default:
break;
}
// -------------------
// Ui handling
// -------------------
if (key != KEY_DOT)
{
if (!cmdOn && !shiftOn)
{
setFlat(m_currenDuration, false);
setFlat(key, true);
m_currenDuration = key;
setFlat(KEY_DOT, false);
dotOn = false;
}
}
else
{
if (!shiftOn && !cmdOn)
{
if (dotOn)
{
setFlat(KEY_DOT, false);
dotOn = false;
}
else
{
setFlat(KEY_DOT, true);
dotOn = true;
}
}
}
resetModifiers();
}
void MpKeyboard::specialKey (int key)
{
switch (key)
{
case KEY_NOTE:
resetModifiers ();
emit keyAction("note-input");
if (noteEntryOn)
{noteEntryOn = false; setFlat (KEY_NOTE, false);}
else
{noteEntryOn = true; setFlat (KEY_NOTE, true);}
break;
case KEY_CMD:
shiftOn = false; setFlat (KEY_SHIFT, false);
if (cmdOn)
{cmdOn = false; setFlat (KEY_CMD, false);}
else
{cmdOn = true; setFlat (KEY_CMD, true);}
break;
case KEY_SHIFT:
cmdOn = false; setFlat (KEY_CMD, false);
if (shiftOn)
{shiftOn = false; setFlat (KEY_SHIFT, false);}
else
{shiftOn = true; setFlat (KEY_SHIFT, true);}
break;
default:
// --------------------------------------------------------
// Arrow buttons
// --------------------------------------------------------
if (!shiftOn || !cmdOn)
{
if (shiftOn)
switch (key) {
case KEY_UP:
emit keyAction ("shift", "key-up");
break;
case KEY_DOWN:
emit keyAction ("shift", "key-down");
break;
case KEY_LEFT:
emit keyAction ("shift", "key-left");
break;
case KEY_RIGHT:
emit keyAction ("shift", "key-right");
break;
default:
break;
}
else if (cmdOn)
switch (key) {
case KEY_UP:
emit keyAction ("ctrl", "key-up");
break;
case KEY_DOWN:
emit keyAction ("ctrl", "key-down");
break;
case KEY_LEFT:
emit keyAction ("ctrl", "key-left");
break;
case KEY_RIGHT:
emit keyAction ("ctrl", "key-right");
break;
default:
break;
}
else
switch (key) {
case KEY_UP:
emit keyAction ("", "key-up");
break;
case KEY_DOWN:
emit keyAction ("", "key-down");
break;
case KEY_LEFT:
emit keyAction ("", "key-left");
break;
case KEY_RIGHT:
emit keyAction ("", "key-right");
break;
default:
break;
}
}
else
resetModifiers();
}
}
void MpKeyboard::functionKey(int key)
{
if (cmdOn)
switch (key) {
case KEY_INS: emit keyAction("append-measures");
break;
case KEY_DEL: emit keyAction("delete-measures");
break;
case KEY_TUPLET: emit keyAction("tuplets-menu");
// getAction("tuplets-menu")->trigger();
break;
default:
break;
}
else
switch (key) {
case KEY_INS: emit keyAction("insert-measures");
break;
case KEY_DEL: emit keyAction("delete");
break;
case KEY_TUPLET: emit keyAction("triplet");
break;
case KEY_FLIP: emit keyAction("flip");
break;
case KEY_TIE: emit keyAction("tie");
break;
case KEY_SLUR: emit keyAction("add-slur");
break;
default:
break;
}
resetModifiers ();
}
void MpKeyboard::setFlat(int key, bool on)
{
switch (key) {
case KEY_SHIFT: ui->keyShift->setChecked(on);break;
case KEY_CMD: ui->keyCmd->setChecked(on); break;
case KEY_128: {ui->key128->setFlat(on);} break;
case KEY_64: ui->key64->setFlat(on); break;
case KEY_32: ui->key32->setFlat(on); break;
case KEY_16: ui->key16->setFlat(on); break;
case KEY_8: ui->key8->setFlat(on); break;
case KEY_4: ui->key4->setFlat(on); break;
case KEY_2: ui->key2->setFlat(on); break;
case KEY_1: ui->key1->setFlat(on); break;
case KEY_DOT: ui->keyDot->setFlat(on); break;
default:
break;
}
}
// -----------------------------
// Keyboard events
// -----------------------------
void MpKeyboard::on_keyA_clicked()
{
pitchKey(KEY_A);
}
void MpKeyboard::on_keyB_clicked()
{
pitchKey(KEY_B);
}
void MpKeyboard::on_keyC_clicked()
{
pitchKey(KEY_C);
}
void MpKeyboard::on_keyD_clicked()
{
pitchKey(KEY_D);
}
void MpKeyboard::on_keyE_clicked()
{
pitchKey(KEY_E);
}
void MpKeyboard::on_keyF_clicked()
{
pitchKey(KEY_F);
}
void MpKeyboard::on_keyG_clicked()
{
pitchKey(KEY_G);
}
void MpKeyboard::on_keySharp_clicked()
{
pitchKey(KEY_SHARP);
}
void MpKeyboard::on_keyFlat_clicked()
{
pitchKey(KEY_FLAT);
}
void MpKeyboard::on_keyNatural_clicked()
{
pitchKey(KEY_NATURAL);
}
void MpKeyboard::on_keyRest_clicked()
{
pitchKey(KEY_REST);
}
void MpKeyboard::on_key128_clicked()
{
durationKey(KEY_128);
}
void MpKeyboard::on_key64_clicked()
{
durationKey(KEY_64);
}
void MpKeyboard::on_key32_clicked()
{
durationKey(KEY_32);
}
void MpKeyboard::on_key16_clicked()
{
durationKey(KEY_16);
}
void MpKeyboard::on_key8_clicked()
{
durationKey(KEY_8);
}
void MpKeyboard::on_key4_clicked()
{
durationKey(KEY_4);
}
void MpKeyboard::on_key2_clicked()
{
durationKey(KEY_2);
}
void MpKeyboard::on_key1_clicked()
{
durationKey(KEY_1);
}
void MpKeyboard::on_keyDot_clicked()
{
durationKey(KEY_DOT);
}
void MpKeyboard::on_keyTie_clicked()
{
functionKey(KEY_TIE);
}
void MpKeyboard::on_keySlur_clicked()
{
functionKey(KEY_SLUR);
}
void MpKeyboard::on_keyFlip_clicked()
{
functionKey(KEY_FLIP);
}
void MpKeyboard::on_keyTriplet_clicked()
{
functionKey(KEY_TUPLET);
}
void MpKeyboard::on_keyShift_clicked()
{
specialKey(KEY_SHIFT);
}
void MpKeyboard::on_keyCmd_clicked()
{
specialKey(KEY_CMD);
}
void MpKeyboard::on_keyIns_clicked()
{
functionKey(KEY_INS);
}
void MpKeyboard::on_keyDel_clicked()
{
functionKey(KEY_DEL);
}
void MpKeyboard::on_keyLeft_clicked()
{
specialKey(KEY_LEFT);
}
void MpKeyboard::on_keyDown_clicked()
{
specialKey(KEY_DOWN);
}
void MpKeyboard::on_keyUp_clicked()
{
specialKey(KEY_UP);
}
void MpKeyboard::on_keyRight_clicked()
{
specialKey(KEY_RIGHT);
}
void MpKeyboard::on_voiceButton_clicked()
{
emit keyAction ("toggle-voices");
// getAction("toggle-voices")->trigger();
}
void MpKeyboard::setVoice (int voice)
{
if (voice == 1)
ui->voiceButton->setText("1");
else if (voice == 2)
ui->voiceButton->setText("2");
else if (voice == 3)
ui->voiceButton->setText("3");
else if (voice == 4)
ui->voiceButton->setText("4");
}
<file_sep>#ifndef MPSETTINGS_H
#define MPSETTINGS_H
#include <QDialog>
namespace Ui {
class MpSettings;
}
class MpSettings : public QDialog
{
Q_OBJECT
public:
explicit MpSettings(QWidget *parent = nullptr);
~MpSettings();
private slots:
void on_smallPButton_clicked(bool checked);
void on_mediumPButton_clicked(bool checked);
void on_mediumLButton_clicked(bool checked);
signals:
void setBaseSize (QRect *);
private:
Ui::MpSettings *ui;
void accept();
int baseX;
int baseY;
int baseWidth;
int baseHeight;
};
#endif // MPSETTINGS_H
<file_sep>#include "mpmusepad.h"
#include "ui_mpmusepad.h"
#include "shortcut.h"
#include "icons.h"
#include <QApplication>
#include <QWidget>
MusePad::MusePad(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MusePad)
{
ui->setupUi(this);
QActionGroup* ag = Ms::Shortcut::getActionGroupForWidget(Ms::MsWidget::MAIN_WINDOW);
ag->setParent(this);
addActions(ag->actions());
connect(ag, SIGNAL(triggered(QAction*)), SLOT(cmd(QAction*)));
mpInit ();
}
MusePad::~MusePad()
{
delete ui;
}
void MusePad::mpInit ()
{
this->setIconSize(QSize(19,19));
baseSize = new MpScreen (50, 50, 290, 460);
setSize (this, baseSize);
setCentralWidget(ui->scoreEdit);
shortcut = new Ms::Shortcut ();
shortcut->init();
Ms::genIcons();
mpPrepareToolbars();
mpPaletteAction = new QAction(); //Hold info on last used palette.
mpKeyboardPanel = new QDockWidget (this);
mpKeyboardPanel->setAllowedAreas(Qt::BottomDockWidgetArea);
mpKeyboard = new MpKeyboard (mpKeyboardPanel);
mpKeyboardPanel->setWidget(mpKeyboard);
addDockWidget(Qt::BottomDockWidgetArea, mpKeyboardPanel);
connect (mpKeyboard, SIGNAL (keyAction(const char *)), SLOT (mpCmd(const char *)));
settings = new MpSettings (this);
settings->setVisible (true);
connect (settings, SIGNAL (setBaseSize (QRect *)), SLOT (setBaseSize (QRect *)));
mpVoiceBox = new MpVoices (this);
mpVoiceBox->setVisible(false);
connect (mpVoiceBox, SIGNAL(voiceChanged(int)),mpKeyboard,SLOT(setVoice(int)));
// Set Tablet defaults
mpKeyboardPanel->setVisible(true);
mpPlayTools->setVisible(false);
paletteOneTools->setVisible(false);
paletteTwoTools->setVisible(false);
palettePanel = new QDockWidget ("Palttes",this);
palettePanel->setAllowedAreas(Qt::LeftDockWidgetArea);
paletteBox = new MpPaletteBox (palettePanel);
palettePanel->setWidget(paletteBox);
addDockWidget(Qt::LeftDockWidgetArea, palettePanel);
palettePanel->setVisible(false);
}
// ----------------------------------------------------
// TABLET functions
// ----------------------------------------------------
void MusePad::mpPrepareToolbars ()
{
// -----------------------------------------
// Action Groups - Note Entry and View mode
//------------------------------------------
QActionGroup* noteEntryMethods = new QActionGroup(this);
noteEntryMethods->addAction(getAction("note-input-steptime"));
noteEntryMethods->addAction(getAction("note-input-repitch"));
noteEntryMethods->addAction(getAction("note-input-rhythm"));
for (QAction* a : noteEntryMethods->actions()) {
a->setCheckable(true);
a->setIconVisibleInMenu(true);
}
getAction("note-input-steptime")->setChecked(true);
//(Not used!) connect(noteEntryMethods, SIGNAL(triggered(QAction*)), this, SLOT(cmd(QAction*)));
QActionGroup* viewModes = new QActionGroup(this);
viewModes->addAction(getAction("viewmode-page"));
viewModes->addAction(getAction("viewmode-horizontal"));
viewModes->addAction(getAction("viewmode-vertical"));
getAction("viewmode-page")->setChecked(true);
connect(viewModes, SIGNAL(triggered(QAction*)), this, SLOT(mpCmd(QAction*)));
// ---------------------------------------------------
// Action Group - Tablet GUI actions
// ---------------------------------------------------
QActionGroup* tabletGui = Ms::Shortcut::getActionGroupForWidget(Ms::MsWidget::TABLET_GUI);
tabletGui->setParent(this);
addActions(tabletGui->actions());
connect(tabletGui, SIGNAL(triggered(QAction*)), SLOT(mpCmd(QAction*)));
// ---------------------------------------------------
// Main toolbar - Setings, File, and Zoom actions
// ---------------------------------------------------
addToolBarBreak();
mpMainTools= addToolBar("");
mpMainTools->setMovable(false);
mpSettingsButton = new MpToolButton(mpMainTools, getAction("settings-menu"));
mpMainTools->addWidget(mpSettingsButton);
mpMainTools->addAction(getAction("logo"));
mpNoteInputButton = new Ms::ToolButtonMenu(tr("Note Entry Methods"),
Ms::ToolButtonMenu::TYPES::ICON_CHANGED,
getAction("note-input"),
noteEntryMethods,
mpMainTools);
mpMainTools->addWidget(mpNoteInputButton);
mpMainTools->addWidget(new MpToolButton(mpMainTools,mpGetAction("")));
mpMagButton = new MpToolButton(mpMainTools, getAction("zoom-menu"));
mpMainTools->addWidget(mpMagButton);
mpMainTools->addAction (getAction("toggle-playback"));
mpMainTools->addWidget(new MpToolButton(mpMainTools,mpGetAction("")));
mpFileButton = new MpToolButton(mpMainTools, getAction("file-menu"));
mpMainTools->addWidget(mpFileButton);
mpEditButton =new MpToolButton(mpMainTools, getAction("edit-menu"));
mpMainTools->addWidget(mpEditButton);
mpMainTools->addAction (getAction("toggle-palette-tools"));
mpScoreButton =new MpToolButton(mpMainTools, getAction("score-menu"));
mpMainTools->addWidget(mpScoreButton);
// ----------------------------------------------------
// Playback tools
// ----------------------------------------------------
mpPlayTools = new QToolBar();
mpPlayTools->setAllowedAreas(Qt::BottomToolBarArea);
mpPlayTools->setMovable(false);
addToolBar(Qt::BottomToolBarArea, mpPlayTools);
mpPlayTools->setObjectName("playback-tools");
mpPlayTools->addAction(getAction("rewind"));
mpPlayTools->addAction(getAction("play"));
mpPlayTools->addAction(getAction("repeat"));
mpPlayTools->addAction(getAction("pan"));
mpPlayTools->addAction(getAction("metronome"));
mpPlayTools->addAction(getAction("toggle-mixer"));
getAction("repeat")->setChecked(true);
getAction("pan")->setChecked(true);
connect(mpMainTools,SIGNAL(actionTriggered (QAction*)),SLOT (mpCmd(QAction*)));
connect(mpPlayTools,SIGNAL(actionTriggered (QAction*)),SLOT (mpCmd(QAction*)));
// -----------------------------------------------------
// Palette toolbars
// -----------------------------------------------------
addToolBarBreak();
paletteOneTools = addToolBar("");
paletteOneTools->addAction(getAction("palette-clefs"));
paletteOneTools->addAction(getAction("palette-keysignatures"));
paletteOneTools->addAction(getAction("palette-timesignatures"));
paletteOneTools->addAction(getAction("palette-accidentals"));
paletteOneTools->addAction(getAction("palette-articulations"));
paletteOneTools->addAction(getAction("palette-gracenotes"));
paletteOneTools->addAction(getAction("palette-lines"));
paletteOneTools->setVisible(false);
paletteOneTools->setMovable(false);
paletteTwoTools = addToolBar("");
paletteTwoTools->addAction(getAction("palette-barlines"));
paletteTwoTools->addAction(getAction("palette-texts"));
paletteTwoTools->addAction(getAction("palette-tempi"));
paletteTwoTools->addAction(getAction("palette-dynamics"));
paletteTwoTools->addAction(getAction("palette-endings"));
paletteTwoTools->addAction(getAction("palette-jumps"));
paletteTwoTools->addAction(getAction("palette-beams"));
paletteTwoTools->setVisible(false);
paletteTwoTools->setMovable(false);
connect (paletteOneTools, SIGNAL(triggered(QAction*)),SLOT(mpCmd(QAction*)));
connect (paletteTwoTools, SIGNAL(triggered(QAction*)),SLOT(mpCmd(QAction*)));
// ---------------------------------------------
// Pop-up menus
// ---------------------------------------------
mpFileMenu = new QMenu();
mpFileButton->setMenu(mpFileMenu);
mpFileMenu->addAction (getAction("file-open"));
mpFileMenu->addAction (getAction("file-save"));
mpFileMenu->addAction (getAction("file-save-as"));
mpFileMenu->addAction (getAction("file-close"));
mpFileMenu->addSeparator();
mpFileMenu->addAction (getAction("file-new"));
connect(mpFileMenu, SIGNAL(triggered(QAction*)),SLOT (mpCmd(QAction*)));
mpMagMenu = new QMenu();
mpMagButton->setMenu(mpMagMenu);
mpMagMenu->addAction(getAction("zoomin"));
mpMagMenu->addAction(getAction("zoomout"));
mpMagMenu->addAction(getAction("zoom100"));
connect(mpMagMenu, SIGNAL(triggered(QAction*)),SLOT (mpCmd(QAction*)));
mpEditMenu = new QMenu;
mpEditButton->setMenu(mpEditMenu);
mpEditMenu->addAction(getAction("undo"));
mpEditMenu->addAction(getAction("redo"));
mpEditMenu->addAction(getAction("cut"));
mpEditMenu->addAction(getAction("copy"));
mpEditMenu->addAction(getAction("paste"));
connect(mpEditMenu, SIGNAL(triggered(QAction*)),SLOT (mpCmd(QAction*)));
mpTupletsMenu = new QMenu();
mpTupletsMenu->addAction(getAction("duplet"));
mpTupletsMenu->addAction(getAction("triplet"));
mpTupletsMenu->addAction(getAction("quadruplet"));
mpTupletsMenu->addAction(getAction("quintuplet"));
mpTupletsMenu->addAction(getAction("sextuplet"));
mpTupletsMenu->addAction(getAction("septuplet"));
mpTupletsMenu->addAction(getAction("octuplet"));
mpTupletsMenu->addAction(getAction("nonuplet"));
connect(mpTupletsMenu,SIGNAL(triggered (QAction*)),SLOT (mpCmd(QAction*)));
mpAddTextMenu = new QMenu();
mpAddTextMenu->addAction(getAction("title-text"));
mpAddTextMenu->addAction(getAction("subtitle-text"));
mpAddTextMenu->addAction(getAction("composer-text"));
mpAddTextMenu->addAction(getAction("poet-text"));
mpAddTextMenu->addAction(getAction("part-text"));
connect(mpAddTextMenu,SIGNAL(triggered (QAction*)),SLOT (mpCmd(QAction*)));
mpHelpMenu = new QMenu();
aboutAction = new QAction(tr("About..."), nullptr);
aboutAction->setMenuRole(QAction::AboutRole);
connect(aboutAction, SIGNAL(triggered()), this, SLOT(about()));
mpHelpMenu->addAction(aboutAction);
aboutQtAction = new QAction(tr("About Qt..."), nullptr);
aboutQtAction->setMenuRole(QAction::AboutQtRole);
connect(aboutQtAction, SIGNAL(triggered()), this, SLOT(aboutQt()));
mpHelpMenu->addAction(aboutQtAction);
aboutMusicXMLAction = new QAction(tr("About MusicXML..."), nullptr);
aboutMusicXMLAction->setMenuRole(QAction::ApplicationSpecificRole);
connect(aboutMusicXMLAction, SIGNAL(triggered()), this, SLOT(aboutMusicXML()));
mpHelpMenu->addAction(aboutMusicXMLAction);
mpHelpMenu->addSeparator();
tutorialAction = mpHelpMenu->addAction(tr("Tutorial"), this, SLOT(tutorial()));
reportBugAction = mpHelpMenu->addAction(tr("Report a bug"), this, SLOT(reportBug()));
// connect(mpHelpMenu,SIGNAL(triggered (QAction*)),SLOT (mpCmd(QAction*)));
mpSettingsMenu = new QMenu();
mpSettingsButton->setMenu(mpSettingsMenu);
mpSettingsMenu->addAction(getAction("file-export"));
mpSettingsMenu->addSeparator();
mpSettingsMenu->addAction(getAction("settings-dialog"));
mpSettingsMenu->addSeparator();
QAction* helpMenu = getAction("help-menu");
helpMenu->setMenu(mpHelpMenu);
mpSettingsMenu->addAction(helpMenu);
mpSettingsMenu->addSeparator();
mpSettingsMenu->addAction(getAction("exit"));
connect(mpSettingsMenu, SIGNAL(triggered(QAction*)),SLOT (mpCmd(QAction*)));
mpScoreMenu = new QMenu;
mpScoreButton->setMenu(mpScoreMenu);
mpScoreMenu->addAction(new QAction(tr("Note Input"), mpScoreMenu));
mpScoreMenu->addActions(noteEntryMethods->actions());
mpScoreMenu->addSeparator();
mpScoreMenu->addAction(new QAction(tr("Scroll mode"), mpScoreMenu));
mpScoreMenu->addActions(viewModes->actions());
mpScoreMenu->addSeparator();
mpScoreMenu->addAction(getAction("toggle-concertpitch"));
getAction("toggle-concertpitch")->setCheckable(true);
getAction("toggle-concertpitch")->setChecked(false);
mpScoreMenu->addAction(getAction("instruments"));
QAction* scoreInfo = getAction("info-menu");
scoreInfo->setMenu(mpAddTextMenu);
mpScoreMenu->addAction(scoreInfo);
connect(mpScoreMenu,SIGNAL(triggered (QAction*)),SLOT (mpCmd(QAction*)));
}
/*
void MusePad::mpSetVoiceIcon(int voice)
{
static QString vtxt[4];
QString s;
m_voiceSet = voice;
}
*/
int MusePad::getVoice ()
{
return m_voiceSet;
}
QAction* MusePad::getAction(const char* id)
{
Ms::Shortcut* s = Ms::Shortcut::getShortcut(id);
return s ? s->action() : nullptr;
}
QAction* MusePad::mpGetAction (const char* id)
{
QAction *a = new QAction ();
a->setData(QByteArray(id));
a->setIconVisibleInMenu(false);
QString cmdn = a->data().toString();
QString path = "icons/" + cmdn + ".png";
if (cmdn == "file-open")
{
a->setText("Open");
}
else if (cmdn == "open-entrytools")
a->setIcon(QIcon(path));
else if (cmdn == "close-entrytools")
a->setIcon(QIcon(path));
else if (cmdn == "open-voices")
a->setIcon(QIcon(path));
else if (cmdn == "accidentals")
a->setText("Accidentls");
else if (cmdn == "clefs")
a->setText("Clefs");
else if (cmdn == "timensignatures")
a->setText("Timesignatures");
else if (cmdn == "keysignatures")
a->setText("Keysignatures");
else if (cmdn == "gracenotes")
a->setText("Gracenotes");
// else if (cmdn == "clefs")
// a->setText("Clefs");
else
a->setText(id);
a->setIcon(QIcon(path));
return a;
}
void MusePad::mpCmd (const char *cmdn)
{
#ifndef TABGUI
getAction(cmdn)->trigger();
#else
getAction(cmdn)->trigger();
cmd(getAction(cmdn));
#endif
}
void MusePad::mpCmd (QString modifier, QString key)
{
if (modifier == "gui")
{
QPoint p = this->pos();
p.setX(p.x()+50);
p.setY(p.y()+75);
if (key == "score-info")
{
mpAddTextMenu->popup(p);
}
else if (key == "help-menu")
{
// mpHelpMenu->popup(p);
}
else if (key == "tuplet-menu")
{
mpTupletsMenu->popup(QPoint (p));
}
}
ui->scoreEdit->setText(modifier + " " + key);
}
void MusePad::mpCmd (QAction *a)
{
QString cmdn = (a->data().toString());
if (cmdn == "tuplets-menu")
{
QPoint p = this->pos();
p.setX(p.x()+50);
p.setY(p.y()+75);
mpTupletsMenu->popup(QPoint (p));
}
else if (cmdn == "settings-dialog")
{
if (!settings)
settings = new MpSettings (this);
settings->setVisible(true);
}
else if (cmdn == "toggle-voices")
{
if (mpVoiceBox->isVisible())
{
mpVoiceBox->setVisible(false);
}
else
{
mpVoiceBox->setVisible(true);
}
}
else if (cmdn == "toggle-playback")
{
if (getAction("toggle-playback")->isChecked())
mpPlayTools->setVisible(true);
else
mpPlayTools->setVisible(false);
if (mpPlayTools->isVisible())
mpKeyboardPanel->setVisible(false);
else
mpKeyboardPanel->setVisible(true);
}
else if (cmdn == "toggle-palette-tools")
{
if (paletteOneTools->isVisible())
{
paletteBox->setVisible(false);
paletteOneTools->setVisible(false);
paletteTwoTools->setVisible(true);
mpPaletteAction->setChecked(false);
}
else if (paletteTwoTools->isVisible())
{
paletteBox->setVisible(false);
paletteTwoTools->setVisible(false);
}
else
{
paletteOneTools->setVisible(true);
}
}
else if (cmdn.startsWith("palette-"))
{
mpShowPalette(a);
}
else if (cmdn == "viewmode-page")
{
emit (switchLayoutMode(LayoutMode::PAGE));
}
else if (cmdn == "viewmode-horizontal")
{
emit (switchLayoutMode(::LINE));
}
else if (cmdn == "viewmode-vertical")
{
emit (switchLayoutMode(LayoutMode::SYSTEM));
}
else
#ifdef TABGUI
cmd(a);
#endif
return;
}
void MusePad::cmd (QAction *a)
{
QString cmdn = (a->data().toString());
if (cmdn == "null")
cmdn = a->text();
ui->scoreEdit->setText(cmdn);
}
void MusePad::setBaseSize(QRect *r)
{
if(!baseSize)
baseSize = new MpScreen(r);
else
{
baseSize->setX(r->x());
baseSize->setY(r->y());
baseSize->setWidth(r->width());
baseSize->setHeight(r->height());
}
setSize (this, baseSize);
}
void MusePad::setSize (QWidget* w, MpScreen* baseSize)
{
w->move(baseSize->x(),baseSize->y());
w->setMinimumSize(baseSize->width(),baseSize->height());
w->setMaximumSize(baseSize->width(),baseSize->height());
}
void MusePad::mpShowPalette(QAction* a)
{
QString s = a->data().toString();
#ifdef TABGUI
ui->scoreEdit->setText(s);
#else
if (!mpPaletteAction) {
paletteBox->mpSetPalette(a, true);
paletteBox->setVisible(true);
mpPaletteAction = a;
}
else if (mpPaletteAction == a) {
paletteBox->mpSetPalette(a, false);
paletteBox->setVisible(false);
mpPaletteAction = nullptr;
}
else {
paletteBox->mpSetPalette(mpPaletteAction, false);
mpPaletteAction->setChecked(false);
mpPaletteAction = a;
paletteBox->mpSetPalette(a, true);
paletteBox->setVisible(true);
}
#endif
}
void MusePad::showMessage(const QString& s, int timeout)
{
ui->scoreEdit->setText(s);
}
// --------------------------------------------------
// Help Actions
// --------------------------------------------------
void MusePad::helpBrowser1() const{
ui->scoreEdit->setText("Online help request");
}
void MusePad::tutorial() const{
ui->scoreEdit->setText("Show tutorial");
}
void MusePad::about(){
ui->scoreEdit->setText("About MusePad");
}
void MusePad::aboutQt(){
ui->scoreEdit->setText("AboutQt");
}
void MusePad::aboutMusicXML(){
ui->scoreEdit->setText("About Music XML");
}
void MusePad::reportBug(){
ui->scoreEdit->setText("report bug");
}
void MusePad::switchLayoutMode(int mode){
if (mode == 0)
ui->scoreEdit->setText("layoyt mode 0");
else if (mode == 1)
ui->scoreEdit->setText("layoyt mode 1");
else if (mode == 2)
ui->scoreEdit->setText("layoyt mode 2");
else
ui->scoreEdit->setText("layoyt mode undef");
}
<file_sep>#include "mpvoices.h"
#include "ui_mpvoices.h"
MpVoices::MpVoices(QWidget *parent) :
QWidget(parent),
ui(new Ui::MpVoices)
{
ui->setupUi(this);
resetButtons();
setButtons(1);
this->setWindowFlag(Qt::FramelessWindowHint);
}
MpVoices::~MpVoices()
{
delete ui;
}
void MpVoices::setButtons(int currentVoice)
{
switch (currentVoice) {
case 1:
ui->voice1Button->setDisabled(true);
ui->voice1Button->setFlat(true);
break;
case 2:
ui->voice2Button->setDisabled(true);
ui->voice2Button->setFlat(true);
break;
case 3:
ui->voice3Button->setDisabled(true);
ui->voice3Button->setFlat(true);
break;
case 4:
ui->voice4Button->setDisabled(true);
ui->voice4Button->setFlat(true);
break;
default:
break;
}
}
void MpVoices::resetButtons()
{
ui->voice1Button->setDisabled(false);
ui->voice1Button->setFlat(false);
ui->voice2Button->setDisabled(false);
ui->voice2Button->setFlat(false);
ui->voice3Button->setDisabled(false);
ui->voice3Button->setFlat(false);
ui->voice4Button->setDisabled(false);
ui->voice4Button->setFlat(false);
}
void MpVoices::on_voice1Button_clicked()
{
resetButtons();
setButtons(1);
m_voiceSet = 1;
emit voiceChanged(m_voiceSet);
}
void MpVoices::on_voice2Button_clicked()
{
resetButtons();
setButtons(2);
m_voiceSet = 2;
emit voiceChanged(m_voiceSet);
}
void MpVoices::on_voice3Button_clicked()
{
resetButtons();
setButtons(3);
m_voiceSet = 3;
emit voiceChanged(m_voiceSet);
}
void MpVoices::on_voice4Button_clicked()
{
resetButtons();
setButtons(4);
m_voiceSet = 4;
emit voiceChanged(m_voiceSet);
}
<file_sep>//=============================================================================
// MusE Score
// Linux Music Score Editor
// $Id: palette.h 5395 2012-02-28 18:09:57Z wschweer $
//
// Copyright (C) 2002-2011 <NAME> and others
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 2.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
//=============================================================================
#ifndef __PALETTE_H__
#define __PALETTE_H__
#include "mptablet.h"
#include <QFile>
#include <QDialog>
#include <QScrollArea>
#include <QString>
#include <QList>
#ifndef TABGUI
#include "ui_palette.h"
#include "ui_cellproperties.h"
#include "libmscore/sym.h"
#endif
namespace Ms {
#ifndef TABGUI
class Element;
class Sym;
class XmlWriter;
class XmlReader;
#endif
class Palette;
//---------------------------------------------------------
// PaletteCell
//---------------------------------------------------------
struct PaletteCell {
~PaletteCell();
#ifndef TABGUI
Element* element { 0 };
#endif
QString name; // used for tool tip
QString tag;
bool drawStaff { false };
double x { 0.0 };
double y { 0.0 };
double xoffset { 0.0 };
double yoffset { 0.0 }; // in spatium units of "gscore"
#ifndef TABGUI
qreal mag { 1.0 };
#endif
bool readOnly { false };
};
//---------------------------------------------------------
// PaletteProperties
//---------------------------------------------------------
#ifndef TABGUI
class PaletteProperties : public QDialog, private Ui::PaletteProperties {
Q_OBJECT
Palette* palette;
virtual void accept();
virtual void hideEvent(QHideEvent*);
public:
PaletteProperties(Palette* p, QWidget* parent = 0);
};
#endif
//---------------------------------------------------------
// PaletteCellProperties
//---------------------------------------------------------
#ifndef TABGUI
class PaletteCellProperties : public QDialog, private Ui::PaletteCellProperties {
Q_OBJECT
PaletteCell* cell;
virtual void accept();
virtual void hideEvent(QHideEvent*);
public:
PaletteCellProperties(PaletteCell* p, QWidget* parent = 0);
};
#endif
//---------------------------------------------------------
// PaletteScrollArea
//---------------------------------------------------------
class PaletteScrollArea : public QScrollArea {
Q_OBJECT
bool _restrictHeight;
#ifndef TABGUI
virtual void resizeEvent(QResizeEvent*);
protected:
virtual void keyPressEvent(QKeyEvent* event) override;
virtual void keyPressEvent(QKeyEvent* event);
#endif
public:
PaletteScrollArea(Palette* w, QWidget* parent = 0);
#ifndef TABGUI
bool restrictHeight() const { return _restrictHeight; }
void setRestrictHeight(bool val) { _restrictHeight = val; }
#endif
};
//---------------------------------------------------------
// Palette
//---------------------------------------------------------
class Palette : public QWidget {
Q_OBJECT
QString _name;
QList<PaletteCell*> cells;
QList<PaletteCell*> dragCells; // used for filter & backup
int hgrid;
int vgrid;
int currentIdx;
int dragIdx;
int selectedIdx;
QPoint dragStartPosition;
qreal extraMag;
bool _drawGrid;
bool _selectable;
bool _disableDoubleClick { false };
bool _readOnly;
bool _systemPalette;
qreal _yOffset; // in spatium units of "gscore"
bool filterActive { false }; // bool if filter is active
bool _moreElements;
bool _showContextMenu { true };
#ifndef TABGUI
virtual void paintEvent(QPaintEvent*) override;
virtual void mousePressEvent(QMouseEvent*) override;
virtual void mouseDoubleClickEvent(QMouseEvent*) override;
virtual void mouseMoveEvent(QMouseEvent*) override;
virtual void leaveEvent(QEvent*) override;
virtual bool event(QEvent*) override;
virtual void resizeEvent(QResizeEvent*) override;
void applyPaletteElement(PaletteCell* cell);
virtual void dragEnterEvent(QDragEnterEvent*) override;
virtual void dragMoveEvent(QDragMoveEvent*) override;
virtual void dropEvent(QDropEvent*) override;
virtual void contextMenuEvent(QContextMenuEvent*) override;
int idx2(const QPoint&) const;
QRect idxRect(int) const;
const QList<PaletteCell*>* ccp() const { return filterActive ? &dragCells : &cells; }
QPixmap pixmap(int cellIdx) const;
private slots:
void actionToggled(bool val);
signals:
void boxClicked(int);
void changed();
void displayMore(const QString& paletteName);
#endif
public:
Palette(QWidget* parent = 0);
virtual ~Palette();
#ifndef TABGUI
void nextPaletteElement();
void prevPaletteElement();
void applyPaletteElement();
PaletteCell* append(Element*, const QString& name, QString tag = QString(),
qreal mag = 1.0);
PaletteCell* add(int idx, Element*, const QString& name,
const QString tag = QString(), qreal mag = 1.0);
void emitChanged() { emit changed(); }
void setGrid(int, int);
Element* element(int idx);
void setDrawGrid(bool val) { _drawGrid = val; }
bool drawGrid() const { return _drawGrid; }
bool read(const QString& path);
void write(const QString& path);
void read(XmlReader&);
void write(XmlWriter&) const;
bool read(QFile*);
void clear();
void setSelectable(bool val) { _selectable = val; }
bool selectable() const { return _selectable; }
int getSelectedIdx() const { return selectedIdx; }
void setSelected(int idx) { selectedIdx = idx; }
bool readOnly() const { return _readOnly; }
void setReadOnly(bool val);
void setDisableDoubleClick(bool val) { _disableDoubleClick = val; }
bool systemPalette() const { return _systemPalette; }
void setSystemPalette(bool val);
void setMag(qreal val);
qreal mag() const { return extraMag; }
void setYOffset(qreal val) { _yOffset = val; }
qreal yOffset() const { return _yOffset; }
int columns() const { return width() / hgrid; }
int rows() const;
int size() const { return filterActive ? dragCells.size() : cells.size(); }
PaletteCell* cellAt(int index) const { return ccp()->value(index); }
void setCellReadOnly(int c, bool v) { cells[c]->readOnly = v; }
QString name() const { return _name; }
void setName(const QString& s) { _name = s; }
int gridWidth() const { return hgrid; }
int gridHeight() const { return vgrid; }
bool moreElements() const { return _moreElements; }
void setMoreElements(bool val);
bool filter(const QString& text);
void setShowContextMenu(bool val) { _showContextMenu = val; }
int getCurrentIdx() { return currentIdx; }
void setCurrentIdx(int i) { currentIdx = i; }
bool isFilterActive() { return filterActive == true; }
QList<PaletteCell*> getDragCells() { return dragCells; }
virtual int heightForWidth(int) const;
virtual QSize sizeHint() const;
int idx(const QPoint&) const;
#endif
};
} // namespace Ms
#endif
<file_sep>//=============================================================================
// MuseScore
// Music Composition & Notation
// $Id:$
//
// Copyright (C) 2011 <NAME> and others
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 2
// as published by the Free Software Foundation and appearing in
// the file LICENSE.GPL
//=============================================================================
#ifndef __SHORTCUT_H__
#define __SHORTCUT_H__
/*---------------------------------------------------------
NOTE ON ARCHITECTURE
The Shortcut class describes the basic configurable shortcut element.
'Real' data are contained in 2 static member variables:
1) sc[], an array of Shortcut: contains the default, built-in data for each shortcut
except the key sequences; it is initialized at startup (code at the begining of
mscore/actions.cpp)
2) _shortcuts, a QMap using the shortcut xml tag name as hash value: is initialized from
data in sc via a call to Shortcut::init() in program main() (mscore/musescore.cpp).
This also load actual key sequences either from an external, hard-coded, file with
user customizations or from a resource (<= mscore/data/shortcuts.xml), if there are
no customizations.
Later during startup, QAction's are derived from each of its elements and pooled
in a single QActionGroup during MuseScore::MuseScore() costructor (mscore/musescore.cpp)
ShortcutFlags:
To be documented
State flags:
Defined in mscore/global.h (ScoreState enum): each shortcut is ignored if its _flags mask
does not include the current score state. This is different from (and additional to)
QAction processing performed by the Qt framework and happens only after the action has
been forwarded to the application (the action must be enabled).
The STATE_NEVER requires an explanation. It has been introduced to mark shortcuts
which need to be recorded (and possibly customized) but are never used directly.
Currently, this applies to a number of shortcuts which:
- have been split between a common and a TAB-specific variant AND
- are linked to tool bar buttons or menu items
If QAction's are created for both, Qt blocks either as duplicate; in addition, the button
or menu item may become disabled on state change. The currently implemented solution is
to create a QAction only for one of them (the common one) and swap the key sequences when
entering or leaving the relevant state.
Swapping is implemented in MuseScore::changeState() (mscore/musescore.cpp).
QAction creation for the 'other' shortcut is blocked in Shortcut::action() (mscore/shortcut.cpp).
This means that Shortcut::action() may return 0. When scanning the whole
shortcuts[] array, this has to be taken into account; currently it happens in two
cases:
- in MuseScore::MuseScore() constructor (mscore/musescore.cpp)
- in MuseScore::changeState() method (mscore/musescore.cpp)
Shortcuts marked with the STATE_NEVER state should NEVER used directly as shortcuts!
---------------------------------------------------------*/
#include "mptablet.h"
#include "icons.h"
#include "globals.h"
#include "../all.h"
namespace Ms {
#ifndef TABLET
class Xml;
class XmlReader;
#endif
//---------------------------------------------------------
// ShortcutFlags
//---------------------------------------------------------
enum class ShortcutFlags : char {
NONE = 0,
A_SCORE = 1,
A_CMD = 1 << 1,
A_CHECKABLE = 1 << 2,
A_CHECKED = 1 << 3
};
constexpr ShortcutFlags operator| (ShortcutFlags t1, ShortcutFlags t2) {
return static_cast<ShortcutFlags>(static_cast<int>(t1) | static_cast<int>(t2));
}
constexpr bool operator& (ShortcutFlags t1, ShortcutFlags t2) {
return static_cast<int>(t1) & static_cast<int>(t2);
}
static const int KEYSEQ_SIZE = 4;
//---------------------------------------------------------
// Shortcut
// hold the basic values for configurable shortcuts
//---------------------------------------------------------
class Shortcut {
MsWidget _assignedWidget; //! the widget where the action will be assigned
int _state { 0 }; //! shortcut is valid in this Mscore state
QByteArray _key; //! xml tag name for configuration file
QByteArray _descr; //! descriptor, shown in editor
QByteArray _text; //! text as shown on buttons or menus
QByteArray _help; //! ballon help
//! (or'd list of states)
Icons _icon { Icons::Invalid_ICON };
Qt::ShortcutContext _context { Qt::WindowShortcut };
ShortcutFlags _flags { ShortcutFlags::NONE };
QList<QKeySequence> _keys; //! shortcut list
QKeySequence::StandardKey _standardKey { QKeySequence::UnknownKey };
mutable QAction* _action { 0 }; //! cached action
static Shortcut _sc[];
static QHash<QByteArray, Shortcut*> _shortcuts;
public:
Shortcut() {}
Shortcut(
Ms::MsWidget assignedWidget,
int state,
const char* key,
const char* d = 0,
const char* txt = 0,
const char* h = 0,
Icons i = Icons::Invalid_ICON,
Qt::ShortcutContext cont = Qt::WindowShortcut,
ShortcutFlags f = ShortcutFlags::NONE
);
QAction* action() const;
const QByteArray& key() const { return _key; }
QString descr() const;
QString text() const;
QString help() const;
MsWidget assignedWidget() const { return _assignedWidget; }
#ifndef TABLET
void clear(); //! remove shortcuts
void reset(); //! reset to buildin
void addShortcut(const QKeySequence&);
#endif
int state() const { return _state; }
void setState(int v) { _state = v; }
bool needsScore() const { return _flags & ShortcutFlags::A_SCORE; }
bool isCmd() const { return _flags & ShortcutFlags::A_CMD; }
bool isCheckable() const { return _flags & ShortcutFlags::A_CHECKABLE; }
bool isChecked() const { return _flags & ShortcutFlags::A_CHECKED; }
Icons icon() const { return _icon; }
const QList<QKeySequence>& keys() const { return _keys; }
QKeySequence::StandardKey standardKey() const { return _standardKey; }
#ifndef TABLET
void setStandardKey(QKeySequence::StandardKey k);
void setKeys(const QList<QKeySequence>& ks);
bool compareKeys(const Shortcut&) const;
#endif
QString keysToString() const;
#ifndef TABLET
static QString getMenuShortcutString(const QMenu* menu);
void write(Ms::Xml&) const;
void read(Ms::XmlReader&);
#endif
static void init();
#ifndef TABLET
static void load();
static void save();
static void resetToDefault();
#endif
static bool dirty;
static Shortcut* getShortcut(const char* key);
static const QHash<QByteArray, Shortcut*>& shortcuts() { return _shortcuts; }
static QActionGroup* getActionGroupForWidget(MsWidget w);
static QActionGroup* getActionGroupForWidget(MsWidget w, Qt::ShortcutContext newShortcutContext);
static QString keySeqToString(const QKeySequence& keySeq, QKeySequence::SequenceFormat fmt);
static QKeySequence keySeqFromString(const QString& str, QKeySequence::SequenceFormat fmt);
};
} // namespace Ms
#endif
<file_sep>//=============================================================================
// toolbuttonmenu.h
//
// Copyright (C) 2016 <NAME> <<EMAIL>>
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 2
// as published by the Free Software Foundation and appearing in
// the file LICENCE.GPL
//=============================================================================
#ifndef TOOLBUTTONMENU_H
#define TOOLBUTTONMENU_H
#include "mptablet.h"
#ifdef TABLET
#include "mptoolbutton.h"
#else
#include "accessibletoolbutton.h"
#endif
namespace Ms {
//---------------------------------------------------------
// ToolButtonMenu
// ==============
// This creates a button with an arrow next to it. Clicking the button triggers the default
// action, while pressing the arrow brings up a menu of alternative actions and/or other
// actions. Selecting an alternative action has some effect on the default action's icon
// and/or its behavior. Other actions have no effect on the default action.
//---------------------------------------------------------
#ifdef TABLET
class ToolButtonMenu : public MpToolButton { // : public QToolButton {
#else
class ToolButtonMenu : public AccessibleToolButton { // : public QToolButton {
#endif
Q_OBJECT
public:
enum class TYPES {
// What happens to the default action if an alternative (non-default) action is triggered?
FIXED, // default action is also triggered but is otherwise unchanged.
ICON_CHANGED, // default action is triggered and its icon is modified and/or set to that of the triggering action.
ACTION_SWAPPED // default action is not triggered. Triggering action (and its icon) become the new default.
};
private:
TYPES _type;
QActionGroup* _alternativeActions;
public:
ToolButtonMenu(QString str,
TYPES type,
QAction* defaultAction,
QActionGroup* alternativeActions,
QWidget* parent);
#ifndef TABLET
void addAction(QAction* a) { menu()->addAction(a); }
void addSeparator() { menu()->addSeparator(); }
void addActions(QList<QAction*> actions) { for (QAction* a : actions) addAction(a); }
#endif
private:
void switchIcon(QAction* a) {
Q_ASSERT(_type == TYPES::ICON_CHANGED && _alternativeActions->actions().contains(a));
defaultAction()->setIcon(a->icon());
}
protected:
virtual void changeIcon(QAction* a) { switchIcon(a); }
private slots:
void handleAlternativeAction(QAction* a);
};
} // namespace Ms
#endif // TOOLBUTTONMENU_H
| b4050c8bb5d465a6ec09091a5af97440aa7f89c4 | [
"C",
"C++"
]
| 22 | C++ | neGjodsbol/myPad | 655f008c18fc2a2f0a573d8e65d780f71e5cc814 | 4b8303fb0ece978721cc7b02ffa53f0fb1a19f0a |
refs/heads/master | <repo_name>matheus2101/projetolp2<file_sep>/TaxiGenerator.java
public class TaxiGenerator extends Thread{
TaxiBuffer buffer;
String value;
public TaxiGenerator(TaxiBuffer b, String v)
{
buffer = b;
value = v;
}
public void run()
{
while(true)
{
buffer.deposit(); // tinha value + String.valueOf(i++) dentro do deposit
try {
Thread.sleep(15000); //espera 5 segundos para depositar novo taxi
} catch (InterruptedException e) {}
}
}
}
<file_sep>/ThreadedServer.java
/************************************************************************************************
* Servidor do bar by <NAME>
*
* O servidor deve ser iniciado depois do servidor de taxi
* cria socket para se comunicar com o servidor do taxi e outro para comunicar com os clientes
* Espera pelo menos um cliente entrar
* Se Todos clientes sairem, ninguem mais entra <===========MERDA MERDA MERDA
*
*************************************************************************************************/
import java.net.*;
import java.io.*;
public class ThreadedServer {
public static void main(String[] args) {
System.out.println("Bem-vindo ao servidor do bar!!");
try (
ServerSocket s = new ServerSocket(4444); //socket para receber mensagens do usuario
Socket ts = new Socket("localhost", 4441); //socket para mandar mensagens para o servidor de taxi
DataOutputStream outTaxi = new DataOutputStream(ts.getOutputStream());
DataInputStream inTaxi = new DataInputStream(ts.getInputStream());
){
System.out.println("Servidor aberto!! Esperando Clientes");
while(true){
Socket ns = s.accept();
new Thread(new EchoServerMultiThread(ns, ts, outTaxi, inTaxi)).start();
System.out.println("Novo cliente chegou!");
}
//s.close();
} catch (IOException e) {
System.out.println("Servidor do taxi nao encontrado... fechando.");
}
}
}
| e4a1fb345e95b509a4dea66c95797ab072cc1774 | [
"Java"
]
| 2 | Java | matheus2101/projetolp2 | 08f04bed0bcb04c36b1253534600ddfda38c9b7b | b2213954197df02db93a92fe3dd7e891c1a690f1 |
refs/heads/master | <repo_name>dennisjohn13/goLeaning<file_sep>/goWebSerivice/smartTrackerAPI.go
package main
import (
"encoding/json"
"fmt"
"github.com/gorilla/mux"
"gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
"log"
"net/http"
"time"
)
var (
session *mgo.Session
collection *mgo.Collection
)
type EventState struct {
EventStateId string `json:"eventId"`
EventStateDate string `json:"eventDate"`
EventState string `json:"eventState"`
EventStateNotes string `json:"eventNotes"`
HowDidItGo bool `json:"howDidItGo"`
}
type Event struct {
EventId string `json:"eventId"`
EventName string `json:"eventName"`
EventCoordiator string `json:"eventCoordinator"`
EventExpectedAmount float64 `json:"eventAmount"`
EventNegotiatedAmount float64 `json:"eventNegotiatedAmount"`
EventFinalAmount float64 `json:"eventFinalAmount"`
DoYouWantToShare bool `json:"doYouWantToShare"`
EventAcceptance bool `json:"eventAcceptance"`
EventStates []EventState `json:"events"`
}
type Company struct {
CompanyId string `json:"companyId"`
Company string `json:"company"`
Events []Event `json:"events"`
}
type User struct {
Id bson.ObjectId `bson:"_id",json:"id"`
UserFirstName string `json:"userFirstName"`
UserLastName string `json:"userLastName"`
Email string `json:"emailId"`
Companies []Company `json:"companies"`
Time time.Time `json:"timeStamp"`
}
const (
MGOSERVER = "127.0.0.1"
MGOCOLLECTION = "eventCollection"
MGODB = "event"
)
func mgoSession() *mgo.Session {
session, err := mgo.Dial(MGOSERVER)
if err != nil {
panic(err)
}
return session
}
func CreateNewUser(w http.ResponseWriter, r *http.Request) {
// NewUser := User{}
// NewUser.Email = r.FormValue("emailId")
// NewUser.UserFirstName = r.FormValue("userFirstName")
// NewUser.UserLastName = r.FormValue("userLastName")
NewUser := User{}
decoder := json.NewDecoder(r.Body)
fmt.Println(decoder)
err := decoder.Decode(&NewUser)
// err := json.NewDecoder(r.Body).Decode(&NewUser)
NewUser.Time = time.Now()
fmt.Println(NewUser)
output, err := json.Marshal(NewUser)
if err != nil {
log.Fatal(err)
}
fmt.Println(string(output))
err = collection.Insert(&NewUser)
if err != nil {
panic(err)
}
}
func testNewUser(w http.ResponseWriter, r *http.Request) {
log.Println("starting retreival")
var response = `{ "userFirstName" : "Dennis", "userLastName" : "John" }`
//Response := Users{}
//Response.Users = rows
output, _ := json.Marshal(response)
fmt.Fprintln(w, string(output))
}
func main() {
session = mgoSession()
collection = session.DB(MGODB).C(MGOCOLLECTION)
defer session.Close()
routes := mux.NewRouter()
routes.HandleFunc("api/users", CreateNewUser).Methods("POST")
routes.HandleFunc("api/users", testNewUser).Methods("GET")
http.Handle("/", routes)
http.ListenAndServe(":8080", nil)
}
<file_sep>/Interfaces/sortStrings.go
package main
import (
"fmt"
"sort"
)
func main() {
//Best way to sort a slice of strings.
s := []string{"papa", "mama", "boolean"}
fmt.Println(s)
sort.Strings(s)
fmt.Println(s)
}
<file_sep>/concurrancy/atomicity.go
package main
// Check the package package main https://golang.org/pkg/sync/atomic/#AddInt64
import (
"fmt"
"sync"
"sync/atomic"
"time"
)
var counter int64 // When coding normal go lang we can use int, but atomicity needs specifically int32 or int64.
var wg sync.WaitGroup
//var mEx sync.Mutex
func incrementer(s string) {
for i := 0; i <= 20; i++ {
time.Sleep(time.Duration(20 * time.Millisecond))
// mEx.Lock() // All the threads will go to a halt.
// x := counter
// x++
// counter = x
// mEx.Unlock() // All the threads will resume.
atomic.AddInt64(&counter, 1)
fmt.Println(s, i, "Counter", counter)
}
wg.Done()
}
func main() {
wg.Add(2)
go incrementer("Foo")
go incrementer("Bar")
wg.Wait()
}
<file_sep>/Interfaces/functionStruct.go
package main
import (
"fmt"
)
type theFellow struct {
name string
cer func() cerimony
}
type writeFunc func(p []byte) (n int, err error)
func (w writeFunc) Write()
func (t theFellow) printer() {
value, err := t.cer().(cerimony)
if err != nil {
fmt.Println(t.name + value.Sagunam())
}
}
type theInterface interface {
printer()
}
type kalyanam struct {
bride string
brideGroom string
marriageDate string
}
type mudalRathri struct {
bride string
brideGroom string
mudalDate string
}
func (k kalyanam) Sagunam() string {
if k.marriageDate == "00/00/000" {
return "Good"
} else {
return "Bad"
}
}
func (k mudalRathri) Sagunam() string {
if k.mudalDate == "01/01/001" {
return "Good"
} else {
return "Bad"
}
}
type cerimony interface {
Sagunam() string
}
func theExecuter(a theInterface) {
theInterface.printer(a)
}
func theReturner(value cerimony) cerimony {
return value
}
func main() {
kal := kalyanam{bride: "Samala", brideGroom: "Sambavam", marriageDate: "01/10/1000"}
mudal := mudalRathri{bride: "Samala", brideGroom: "Sambavam", mudalDate: "00/00/001"}
var meaning interface{}
meaning = theFellow{name: "Kalyaman", cer: theReturner(kal)}
theExecuter(meaning)
meaning = theFellow{name: "MudalRathri", cer: theReturner(mudal)}
theExecuter(meaning)
}
<file_sep>/concurrancy/mutexExample.go
package main
import (
"fmt"
"sync"
"time"
)
// To pass the value between calls we have to use Mutex -> Mutually Exclusive objects.
// This output will print to be 42
// go run -race mutexExample.go this should give no error.
var counter int
var wg sync.WaitGroup
var mEx sync.Mutex
func incrementer(s string) {
for i := 0; i <= 20; i++ {
time.Sleep(time.Duration(20 * time.Millisecond))
mEx.Lock() // All the threads will go to a halt.
x := counter
x++
counter = x
mEx.Unlock() // All the threads will resume.
fmt.Println(s, i, "Counter", counter)
}
wg.Done()
}
func main() {
wg.Add(2)
go incrementer("Foo")
go incrementer("Bar")
wg.Wait()
}
<file_sep>/Interfaces/converstionVsAsertion.go
package main
import (
"fmt"
//"strconv"
)
//Converstin is int to float
//Asserstion is for interfaces
func main() {
//Converstion examples
a := []rune{'a', 'b', 'b', 'd'}
b := string(a)
var c int32 = 'a'
d := []byte{'a', 'b', 'c', 'd'}
e := []byte("hello")
fmt.Println(a, b, c, string(c), d, string(d), e)
//Work on the below code
//i, err := strconv.Atoi("34")
//
//if err != nil {
// fmt.Println(i)
//}
//assetion example
var name interface{} = "Sydney"
str, ok := name.(string) // Syntax for assertion.
if ok {
fmt.Printf("%T\n", str)
fmt.Println("The Value is", str, "\n")
} else {
fmt.Printf("value is not a string \n")
}
var age interface{} = 45
fmt.Printf("%T\n", age)
//fmt.Println(7 + age) //THis will fail missmatched types.
fmt.Println(7 + age.(int)) //Assertion done
//Diffrence is assertion is the bracket is in the rite
//Converstion is on the left.
}
<file_sep>/tourOfGo/newtonSqRoot.go
package main
import (
"fmt"
"math"
)
//As a simple way to play with functions and loops, implement the square root function using Newton's method.
//
//In this case, Newton's method is to approximate Sqrt(x) by picking a starting point z and then repeating:
//
//
//To begin with, just repeat that calculation 10 times and see how close you get to the answer for various values (1, 2, 3, ...).
//
//Next, change the loop condition to stop once the value has stopped changing (or only changes by a very small delta). See if that's more or fewer iterations. How close are you to the math.Sqrt?
//
//Hint: to declare and initialize a floating point value, give it floating point syntax or use a conversion:
//Check https://tour.golang.org/flowcontrol/8
var s float64 = 100
var z float64
var delt float64 = 0.0000001
func sqrt(val float64) float64 {
for {
z = s - ((s*s - val) / (2 * s))
if math.Abs(s-z) < delt || z-s == 0 { // Why use abs, because if actual number val is larger than s then then s - z will give negative and the loop will satisfy.
return s
}
s = z
}
}
func main() {
fmt.Println("The squre root newtons Method is :", sqrt(232434234234))
fmt.Println("The math squre root is :", math.Sqrt(232434234234))
}
<file_sep>/channels/channelFactorialPipeline.go
package main
import (
"fmt"
"math/rand"
)
type factStruct struct {
value int
factorial int
}
func main() {
var slice []factStruct
c := factorialRange(slicer(10)...)
for n := range c {
slice = append(slice, n)
}
fmt.Println(slice)
}
func factorialRange(input ...int) <-chan factStruct {
c := make(chan factStruct)
done := make(chan bool)
for _, n := range input {
go func(n int) {
total := 1
for i := n; i > 0; i-- {
total *= i
}
c <- factStruct{n, total}
done <- true
}(n)
}
go func() {
for range input {
<-done
}
close(c)
}()
return c
}
func slicer(n int) []int {
var slicer []int
for i := 0; i < n; i++ {
slicer = append(slicer, rand.Intn(6)+1)
}
return slicer
}
<file_sep>/goWebSerivice/mongoTest.go
package main
import (
"fmt"
"gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
"log"
)
type Person struct {
Name string
Phone string
}
func main() {
session, err := mgo.Dial("127.0.0.1")
if err != nil {
panic(err)
}
defer session.Close()
c := session.DB("GO").C("goLangTest")
// err = c.Insert(&Person{"Dennis", "848574934793475"},
// &Person{"Joel", "8389203475892374"})
// if err != nil {
// log.Fatal(err)
// }
result := Person{}
err = c.Find(bson.M{"name": "Joel"}).One(&result)
if err != nil {
log.Fatal(err)
}
fmt.Println(result.Phone)
}
<file_sep>/Interfaces/plexInterfaceUnderstanding.go
package main
import (
"fmt"
)
type marriage struct {
personOne, personTwo string
personOneAge, personTwoAge int
}
func (self marriage) deterMineType() string {
if self.personOne == "Male" && self.personTwo == "Female" {
return "Straight"
} else if self.personOne == "Male" && self.personTwo == "Male" {
return "SameSex"
} else if self.personOne == "Male" && self.personTwo == "Male" {
return "SameSex"
}
return "Cannot Determine"
}
func (self marriage) deterMineLegal() string {
if self.personOneAge < 18 || self.personTwoAge < 18 {
return "Illegal"
} else {
return "Legal"
}
}
type courShip struct {
personOne, personTwo string
personOneAge, personTwoAge int
}
func (self courShip) deterMineType() string {
if self.personOne == "Male" && self.personTwo == "Female" {
return "Metior"
} else if self.personOne == "Male" && self.personTwo == "Male" {
return "Variance"
} else if self.personOne == "Male" && self.personTwo == "Male" {
return "Variance"
}
return "Cannot Determine"
}
func (self courShip) deterMineLegal() string {
if self.personOneAge < 16 || self.personTwoAge < 16 {
return "Illegal"
} else {
return "Legal"
}
}
type deterMineEvent interface {
deterMineType() string
deterMineLegal() string
}
type event struct {
personOne, personTwo string
personOneAge, personTwoAge int
eventType func() deterMineEvent
}
func (b *event) Build() (deterMineEvent) {
plug := b.eventType().(deterMineEvent)
return plug
}
func makeEvent(a interface{}) event {
//str, _ := a.(courShip)
var r event
//r.personTwo = a.personTwo
//r.personOne = a.personOne
//r.personOneAge = a.personOneAge
//r.personTwoAge = a.personTwoAge
switch t := a.(type) {
case courShip:
str, _ := a.(courShip)
r.personTwo = str.personTwo
r.personOne = str.personOne
r.personOneAge = str.personOneAge
r.personTwoAge = str.personTwoAge
r.eventType = func() deterMineEvent {
return deterMineEvent(str)
}
case marriage:
str, _ := a.(marriage)
r.personTwo = str.personTwo
r.personOne = str.personOne
r.personOneAge = str.personOneAge
r.personTwoAge = str.personTwoAge
r.eventType = func() deterMineEvent {
return deterMineEvent(str)
}
default:
_ = t
}
return r
}
func main() {
kalyanam := marriage{"Male", "Female", 23, 16}
var det deterMineEvent
det = kalyanam
fmt.Println(det.deterMineLegal())
fmt.Println(det.deterMineType())
court := courShip{"Male", "Female", 17, 16}
det = court
fmt.Println(det.deterMineLegal())
fmt.Println(det.deterMineType())
//theBig := event{court.personOne, court.personTwo, court.personOneAge, court.personTwoAge, det}
//fmt.Println(theBig.eventType.deterMineType() , theBig.eventType.deterMineLegal())
r := makeEvent(kalyanam)
fmt.Println("The value is :", r.eventType().deterMineType())
fmt.Printf("The type is %T\n", r.eventType())
fmt.Println(r.Build().deterMineType() , r.Build().deterMineLegal())
}
<file_sep>/channels/fanInFanOut.go
package main
import (
"fmt"
"math/rand"
)
type factStruct struct {
value int
factorial int
}
func main() {
var slice []factStruct
c := factorialRange(slicer(200))
for n := range c {
slice = append(slice, n)
}
fmt.Println(slice)
}
func factorialRange(in <-chan int, n int) <-chan factStruct {
c := make(chan factStruct)
done := make(chan bool)
for n := range in { //Fan Out. Multiple GO routines running in different CPU's
go func(n int) {
total := 1
for i := n; i > 0; i-- {
total *= i
}
c <- factStruct{n, total} //Fan in. Multiple GO routines puttting the value into one Channel.
done <- true
}(n)
}
go func() {
for i := 0; i < n; i++ {
<-done
}
close(c)
}()
return c
}
func slicer(n int) (<-chan int, int) {
c := make(chan int)
go func() {
for i := 0; i < n; i++ {
c <- rand.Intn(6) + 1 //Fan In
}
close(c)
}()
return c, n
}
<file_sep>/functions/callBackExample1.go
package main
import "fmt"
func visit(numbers []int, callBack func(int)) {
for _, n := range numbers {
callBack(n)
}
}
func main() {
visit([]int{5, 6, 7, 8, 8}, func(n int) {
fmt.Println(n)
}) // This is like Functional programming, something what we have in Javascript.
}
// Call back can be used in Go but it make confusing use it if only needed the same functionality can be achieved using normal call's
<file_sep>/Interfaces/methodSets.go
package main
import (
"fmt"
"math"
)
type circle struct {
radius float64
}
func (c circle) area() float64 { //Value receiver. Can pass address and value
return math.Pi * c.radius * c.radius
}
type square struct {
side float64
}
func (s *square) area() float64 { //Pointer receiver cant pass value
return s.side * s.side
}
type shape interface {
area() float64
}
func print(val shape) {
fmt.Println(val.area())
}
func main() {
cir := circle{10}
sq := square{50}
sq1 := square{}
print(&cir) // For a value receiver we can pass address
print(&sq) // For a pointer receiver we can only pass the address so this work.
print(cir) // For a value receiver we can pass both value and address
//print(sq) // This will not work it will fail, because it is a pointer receiver.
print(&sq1)
}
<file_sep>/Datastrucures/structMethods.go
package main
import "fmt"
type person struct {
fName string
lName string
age int
}
func (p person) fullName() string {
return p.fName + p.lName
}
func main() {
p1 := person{"Jumla", "Vumla", 18}
p2 := person{"Luis", "Suares", 29}
fmt.Println(p1.fullName())
fmt.Println(p2.fullName())
}
<file_sep>/goWebSerivice/apiMongo.go
package main
import (
"encoding/json"
"fmt"
"github.com/gorilla/mux"
"gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
"log"
"net/http"
"strconv"
"time"
)
var (
session *mgo.Session
collection *mgo.Collection
)
type User struct {
Id bson.ObjectId `bson:"_id",json:"id"`
Name string `json:"userName"`
Email string `json:"email"`
First string `json:"firstName"`
Last string `json:"lastName"`
Time time.Time `json:"timeStamp"`
}
type Users struct {
Users []User `json:"users"`
}
func getSession() *mgo.Session {
session, err := mgo.Dial("127.0.0.1")
if err != nil {
panic(err)
}
return session
}
func UserCreate(w http.ResponseWriter, r *http.Request) {
NewUser := User{}
NewUser.Name = r.FormValue("user")
NewUser.Email = r.FormValue("email")
NewUser.First = r.FormValue("first")
NewUser.Last = r.FormValue("last")
NewUser.Time = time.Now()
output, err := json.Marshal(NewUser)
if err != nil {
log.Fatal(err)
}
fmt.Println(string(output))
err = collection.Insert(&NewUser)
if err != nil {
log.Fatal(err)
}
}
func UsersRetrieve(w http.ResponseWriter, r *http.Request) {
log.Println("starting retreival")
start := 0
limit := 10
next := start + limit
nextUri := "<http://localhost:8080/api/users?start=" + strconv.Itoa(next) + "; rel=\"next\""
fmt.Println(nextUri)
w.Header().Set("Pragma", "no-cache")
w.Header().Set("Link", nextUri)
//var rows []User
Response := Users{}
err := collection.Find(nil).All(&Response.Users)
if err != nil {
panic(err)
}
//Response := Users{}
//Response.Users = rows
output, _ := json.Marshal(Response)
fmt.Fprintln(w, string(output))
}
func main() {
session = getSession()
collection = session.DB("GO").C("goWebServices")
defer session.Close()
routes := mux.NewRouter()
routes.HandleFunc("/api/users", c).Methods("POST")
routes.HandleFunc("/api/users", UsersRetrieve).Methods("GET")
http.Handle("/", routes)
http.ListenAndServe(":8080", nil)
}
<file_sep>/channels/channelsIncrementorExample.go
package main
import "fmt"
func main() {
fmt.Println("The total sum of runs is :", <-pull(incrament("Foo"))+<-pull(incrament("Bar")))
}
func incrament(str string) chan int {
out := make(chan int)
go func() {
for i := 0; i < 10; i++ {
out <- i
fmt.Println(str, i)
}
close(out)
}()
return out
}
func pull(c chan int) chan int {
out1 := make(chan int)
go func() {
var sum int
for n := range c {
sum += n
}
out1 <- sum
close(out1)
}()
return out1
}
<file_sep>/functions/functionsReturns02.go
package main
import "fmt"
func main() {
fmt.Println(greet2("Anju", "Job"))
fmt.Println(greet3("Anju", "Job"))
fmt.Println(greet4("Anju", "Job"))
}
func greet2(fname string, lname string) string { //This function returns one value string. It accepts two parameters.
return fmt.Sprint(fname, lname) //the fmt.Sprint will string print the values, its like concatinating the fname and lname but it will not print to stdOut.
}
func greet3(fname string, lname string) (s string) { //This is another way to return a named value. This is not recommended.
s = fmt.Sprint(fname, lname) //No need to assign the value s:= because s string is already assigned.
return //Since we have given s in the to be returned no need to specify value in return
}
func greet4(fname string, lname string) (string, string) { //This will return two paramenters. This kind of return is specific to GO it can return multiple values.
return fmt.Sprint(fname, lname), fmt.Sprint(lname, fname)
}
<file_sep>/channels/channelsExample5.go
package main
import "fmt"
func load(c chan int) {
for i := 0; i < 10; i++ {
c <- i
}
close(c)
}
func drain(c chan int, done chan bool) {
for i := range c {
fmt.Println(i)
}
done <- true
}
func main() {
c := make(chan int)
done := make(chan bool)
n := 10
go load(c)
for i := 0; i < n; i++ {
go drain(c, done)
}
for i := 0; i < n; i++ {
<-done
}
}
<file_sep>/goMiniProject/time.go
package main
import (
"fmt"
"time"
)
func main() {
currentTime := time.Now().Local()
fmt.Printf("%T\n", currentTime.Format("02-01-2006"))
fmt.Println("The current time is:", currentTime.Format("02-01-2006-15:04:05.0000000000 -0700:MST")) // You have to give Jan 02 2006 for format.
fmt.Println("The current time is:", currentTime)
}
<file_sep>/Datastrucures/structJsonMarshell.go
package main
import (
"encoding/json"
"fmt"
)
type Person struct {
FName string //Note the capitals the values are exported
LName string //Note the capitals the values are exported
age int //Note the value of the first byte is lower case so not exported
Salary float64 `json:"-"`
Position string `json:"Designation"`
}
func main() {
//Marselling
p1 := Person{"Noel", "Issac", 4, 786799.00, "Vice President"}
fmt.Println(p1)
bs, _ := json.Marshal(p1)
fmt.Println(bs)
fmt.Println(string(bs)) //This will not print the age because it is not exported. Not capitals. This JSON is converted to a string
// This will change the Position to Desgnation and the Salary will also be not printed when Marshaled because of json:"-".
//Unmarshelling
fmt.Println("UnMarshelling")
var p2 Person
fmt.Println(p2.age, "-", p2.FName, "-", p2.LName, "-", p2.Position, "-", p2.age, "-", p2.Salary)
bs1 := []byte(`{"FName":"James", "LName":"Robert", "age":34, "Salary":67767.90, "Designation":"Director"}`)
fmt.Println(bs1)
fmt.Println(string(bs1))
err := json.Unmarshal(bs1, &p2)
if err == nil {
fmt.Println(p2.age, "-", p2.FName, "-", p2.LName, "-", p2.Position, "-", p2.age, "-", p2.Salary)
} else {
fmt.Println("The error is:", err)
}
}
<file_sep>/functions/lengthOfEmma.go
package main
import "fmt"
func main() {
cupCake := "Emma JJJJJJ"
fmt.Println("Lenght of cupCake is ", len(cupCake))
}
<file_sep>/goExamples/factorialConcParr.go
package main
import (
"fmt"
"math/rand"
"sync"
"time"
)
func main() {
start := time.Now()
gen(10000000)
fmt.Println("Current Time:", time.Now(), "Start Time:", start, "Elapsed Time:", time.Since(start))
}
func gen(n int) {
p := n / 2
q := p + 1
i := 0
done := make(chan bool)
splitChan := make(chan []int64)
go splitGen(q, n, splitChan, done)
go splitGen(1, p, splitChan, done)
go func() {
<-done
<-done
close(splitChan)
}()
for n := range splitChan {
// fmt.Println(n)
for range n {
//fmt.Println(x)
i++
}
}
fmt.Println(i)
}
func splitGen(p, q int, splitChan chan []int64, done chan bool) {
var slice []int64
for i := p; i <= q; i++ {
slice = append(slice, factorial(rand.Intn(10)+1))
}
splitChan <- slice
done <- true
}
func factorial(n int) int64 {
p := n / 2
q := p + 1
ch := make(chan int64)
var wg sync.WaitGroup
wg.Add(2)
go func() {
ch <- fact(1, p)
wg.Done()
}()
go func() {
ch <- fact(q, n)
wg.Done()
}()
go func() {
wg.Wait()
close(ch)
}()
var factorial int64
factorial = 1
for n := range ch {
factorial *= n
}
return factorial
}
func fact(n, m int) int64 {
var fact int64
fact = 1
for i := n; i <= m; i++ {
fact *= int64(i)
}
return fact
}
<file_sep>/functions/exercise11.go
package main
import "fmt"
func main() {
half := func(n int) (float64, bool) {
return float64(n) / 2, n%2 == 0
}
val, isEven := half(3)
fmt.Println(val, isEven)
fmt.Println(half(6786))
}
<file_sep>/Interfaces/emptyInterfaceImportant.go
package main
import "fmt"
// If we need to pass any value to a funciton then we have to use the empty interface.
// If a function returns an empty interface then it will return any type.
// We can assign any type to an inteface.
func printMe(input interface{}) { // In this function if you pass any value it will accept it because it is an empty interface.
fmt.Printf("Just s: %T\n", input)
fmt.Println("This is what is passed:", input) // Basically fmt package will accept an empty interface.
}
func main() {
var empty interface{}
a := 5
b := "Hola"
empty = a
printMe(empty)
empty = b
printMe(empty)
printMe([]rune{'a', 'b', 'c'})
}
<file_sep>/Datastrucures/mapExample2.go
package main
import "fmt"
func main() {
multMap := make(map[string]map[string]int) //The below steps are one way to make a map.
subMap := map[string]int{
"Thomas": 0,
"John": 1,
"Dennis": 2,
"Joel": 3,
}
multMap["Plackal"] = subMap
subMap = map[string]int{
"Vilar": 0,
"Muskin": 1,
"Ramery": 2,
"Vinak": 3,
}
multMap["Zoria"] = subMap
fmt.Println(multMap)
multMap2 := make(map[string]map[string]string) //The below steps are another way to make a map.
multMap2["Smith"] = map[string]string{
"Valigan": "One",
"Zooligan": "Patti",
"Vilmar": "Rameneri",
}
multMap2["Mclean"] = map[string]string{
"Pillar": "One",
"Villar": "Patti",
"Zoomlar": "Rameneri",
}
fmt.Println(multMap2)
}
<file_sep>/channels/channelExample1.go
package main
import (
"fmt"
"sync"
)
var ws sync.WaitGroup
func main() {
c := make(chan int)
ws.Add(2)
go func() {
//ws.Add(1) // This will make the code not run because the ws.Add is adding the same value in two go routines.
for i := 0; i < 10; i++ {
c <- i
}
ws.Done()
}()
go func() {
//ws.Add(1) // This will make the code not run because the ws.Add is adding the same value in two go routines.
for i := 0; i < 10; i++ {
c <- i
}
ws.Done()
}()
go func() {
ws.Wait()
close(c)
}()
for n := range c {
fmt.Println("The value of channel is: ", n)
}
}
<file_sep>/functions/understandingPigGame.go
package main
//Functional Programing great example.
import (
"fmt"
"math/rand"
"time"
)
const (
win = 100
gamesPerSeries = 10
)
type Score struct {
player, opponent, thisTurn int
}
//Action is a function that returns a new Score and if turn is there or not.
type Action func(s Score) (result Score, thisTurnIsOver bool)
// This is a type of Action Function that will return a Score and Bool.
// This below function will simulate a dice throw.
func Roll(s Score) (Score, bool) {
throwDice := rand.Intn(6) + 1 //THis will return a random number from 0 to 5 add 1 to simulate a dice throw
//If you check randome funciton it will give the same number each time. Because the random number is determined by the environmental variables.
//So use Seed funciton to make sure the number is random.
if throwDice == 1 {
return Score{s.opponent, s.player, 0}, true
}
return Score{s.player, s.opponent, s.thisTurn + throwDice}, false
}
// If the player wants to stay the below function will simulate the stay.
func Stay(s Score) (Score, bool) {
return Score{s.opponent, s.player + s.thisTurn, 0}, true
}
type Strategy func(s Score) Action
func StayAtK(k int) Strategy {
return func(s Score) Action {
if s.thisTurn >= k {
return Stay
}
return Roll
}
}
func Play(Strategy1, Strategy2 Strategy) int {
Strategys := []Strategy{Strategy1, Strategy2}
var s Score
var turnIsOver bool
currentPlayer := rand.Intn(2)
for s.player+s.thisTurn < win {
action := Strategys[currentPlayer](s)
s, turnIsOver = action(s)
if turnIsOver {
currentPlayer = (currentPlayer + 1) % 2
}
}
return currentPlayer
}
func RoundRobin(Strategys []Strategy) ([]int, int) {
wins := make([]int, len(Strategys))
for i := 0; i < len(wins); i++ {
for j := i + 1; j < len(wins); j++ {
for k := 0; k < gamesPerSeries; k++ {
winner := Play(Strategys[i], Strategys[j])
if winner == 0 {
wins[i]++
} else {
wins[j]++
}
}
}
}
gamesPerStrategy := gamesPerSeries * (len(Strategys) - 1) // NO self play
return wins, gamesPerStrategy
}
func RatioString(vals ...int) string {
total := 0
for _, val := range vals {
total += val
}
s := ""
for _, val := range vals {
if s != "" {
s += ", "
}
pct := 100 * float64(val) / float64(total)
s += fmt.Sprintf("%d/%d (%0.1f%%)", val, total, pct)
}
return s
}
func main() {
rand.Seed(time.Now().UnixNano())
Statergies := make([]Strategy, win)
for k := range Statergies {
Statergies[k] = StayAtK(k + 1)
}
wins, games := RoundRobin(Statergies)
for k := range Statergies {
fmt.Printf("Wins, losses staying at k =% 4d: %s\n",
k+1, RatioString(wins[k], games-wins[k]))
}
strategy1 := StayAtK(67)
strategy2 := StayAtK(20)
winner := Play(strategy1, strategy2)
if winner == 0 {
fmt.Println("The player with stay at 67 is the winner")
} else {
fmt.Println("The player with stay at 20 is the winner")
}
}
<file_sep>/functions/passByValueSlice.go
package main
import "fmt"
func changeMe(z map[string]int) { //Slices Maps and Channels are always pass by value. Do not need to pass the address, it is always pass by value
z["Emma"] = 0
}
func changeMeSlice(z []string) {
z[0] = "Emma"
z[1] = "Grace"
z[2] = "Plackal"
}
func main() {
m := make(map[string]int)
changeMe(m)
fmt.Println(m["Emma"]) // The value of m is getting modified in the changeMe function.
z := make([]string, 3, 25)
changeMeSlice(z)
fmt.Println(z)
}
// IN go everything is pass by value. In the above case the value of m "Map" is getting changed because map is a referenece type. When m is passed it will
// Pass the underlying address of m to z
// Same case with a slice which is passed to ChangeMeSlice. Slice is a reference type.
<file_sep>/channels/channelsExample4.go
package main
import "fmt"
func load(c chan int) {
for i := 0; i < 1000; i++ {
c <- i
}
close(c)
}
func drain(c chan int, done chan bool) {
for i := range c {
fmt.Println(i)
}
done <- true
}
func main() {
c := make(chan int)
done := make(chan bool)
go load(c)
go drain(c, done)
go drain(c, done)
<-done
<-done
}
<file_sep>/goExamples/interfaceUnderstanding2.go
package main
import "fmt"
type Dog struct {
}
func (d Dog) Sound() {
fmt.Println("Woof")
}
func (d Dog) Pound() {
fmt.Println("No")
}
type Cat struct {
}
func (c Cat) Sound() {
fmt.Println("Meaw")
}
func (d Cat) Pound() {
fmt.Println("Yes")
}
type Animal interface {
Sound()
Pound()
}
type AnimalSound interface {
Sound()
}
func main() {
boomer := Dog{}
kate := Cat{}
var ani Animal
ani = boomer
makeSound(ani)
ani = kate
makeSound(ani)
}
func makeSound(a AnimalSound) {
a.Sound()
}
<file_sep>/channels/channelsExample6.1.go
package main
import (
"fmt"
//"time"
)
//In the below example, when the increment is launched a go routine is launched.
//Processor receives the channel and runs a go routines which drains out the channel.
//So it is kind of a
func increment() chan int {
c := make(chan int)
go func() {
for i := 0; i < 5; i++ {
c <- i
}
close(c)
}()
return c
}
func processor(c chan int) chan int {
out := make(chan int)
go func() {
var sum int
for n := range c {
sum += n
out <- sum
}
close(out)
}()
return out
}
func main() {
sum := processor(increment())
for n := range sum {
fmt.Println(n)
}
}
<file_sep>/tourOfGo/rPQuit.go
package main
import (
"fmt"
"math/rand"
"time"
)
func main() {
quit := make(chan bool)
c := boaring("Joe!", quit)
for i := 10; i > 0; i-- {
quit <- false
fmt.Println(<-c)
}
quit <- true
for {
select {
case c <- fmt.Sprintf("Hola"):
//Do nothing
case <-quit:
fmt.Println("Stoped")
return
}
}
}
func boaring(msg string, quit chan bool) chan string {
c := make(chan string)
go func() {
for i := 0; ; i++ {
if <-quit == true {
return
}
c <- fmt.Sprintf("%s %d", msg, i)
time.Sleep(time.Duration(rand.Intn(1e3)) * time.Millisecond)
}
}()
return c
}
<file_sep>/Datastrucures/jsonEncodDecod.go
package main
//The diffrence between Encoder/Decoder to Marshal/Unmarshal we are dealing with "External" and within the program respectively.
//When a streamed data is comming as an API then we have to use Decoder to read the API data
//To write back to the API we have use Encoder.
//Whereas Marshal/Unmarshal can be used for dealing the data within the program.
import (
"encoding/json"
"fmt"
"os"
"strings"
)
type Gymnist struct {
First string
Last string
Medal int
}
func main() {
p1 := Gymnist{"Mary", "Lyone", 4}
json.NewEncoder(os.Stdout).Encode(p1) //In this case the data is written back to the STDOUT
fmt.Println("Decoding")
var p2 Gymnist
rdr := strings.NewReader(`{"First":"Zara","Last":"Mepar","Medal":1}`) //Simulating somehting like a webserver. This will take a string.
json.NewDecoder(rdr).Decode(&p2)
fmt.Println(p2)
}
<file_sep>/Datastrucures/slice2Dimention.go
package main
import "fmt"
func main() {
records := make([][]string, 5)
student1 := make([]string, 4, 10)
student1[0] = "Froster"
student1[1] = "Lamesha"
student1[2] = "100.00"
student1[3] = "65.00"
records = append(records, student1)
student2 := make([]string, 4, 10)
student2[0] = "Milla"
student2[1] = "Ramesha"
student2[2] = "98.00"
student2[3] = "99.00"
records = append(records, student2)
fmt.Println(records)
fmt.Println(records[5][0], cap(records))
fmt.Println(records[5], cap(records))
}
<file_sep>/goWebSerivice/webServiceMongoDB.go
package main
import (
"encoding/json"
"fmt"
"github.com/gorilla/mux"
"gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
"log"
"net/http"
"time"
)
var (
session *mgo.Session
collection *mgo.Collection
)
type User struct {
Id bson.ObjectId `_id,omitempty`
Name string `json:"userName",bson:"user_name"`
Email string `json:"email",bson:"email"`
First string `json:"firstName",bson:"first_name"`
Last string `json:"lastName",bson:"last_name"`
Time time.Time `json:"timeStamp",bson:"create_timestamp"`
}
type Users struct {
Users []User `json:"users"`
}
func getSession() *mgo.Session {
session, err := mgo.Dial("127.0.0.1")
if err != nil {
panic(err)
}
return session
}
func CreateUser(w http.ResponseWriter, r *http.Request) {
// session := getSession()
// defer session.Close()
// c := session.DB("GO").C("goWebServices")
NewUser := User{}
NewUser.Name = r.FormValue("user")
NewUser.Email = r.FormValue("email")
NewUser.First = r.FormValue("first")
NewUser.Last = r.FormValue("last")
NewUser.Time = time.Now()
output, err := json.Marshal(NewUser)
if err != nil {
log.Fatal(err)
}
fmt.Println(string(output))
err = collection.Insert(&NewUser)
if err != nil {
log.Fatal(err)
}
}
func GetUser(w http.ResponseWriter, r *http.Request) {
// session := getSession()
// defer session.Close()
// collection := session.DB("GO").C("goWebServices")
w.Header().Set("Pragma", "no-cache")
urlParams := mux.Vars(r)
id := urlParams["id"]
ReadUser := User{}
err := collection.FindId(bson.ObjectIdHex(id)).One(&ReadUser)
switch {
case err != nil:
fmt.Println("This is an error:" + id)
log.Fatal(err)
case ReadUser.Id == "":
fmt.Fprintf(w, "No Such Id - "+id)
default:
output, _ := json.Marshal(ReadUser)
fmt.Fprintf(w, string(output))
}
}
func main() {
session = getSession()
collection = session.DB("GO").C("goWebServices")
defer session.Close()
routes := mux.NewRouter()
routes.HandleFunc("/api/user/create", CreateUser)
routes.HandleFunc("/api/user/read/{id:[0-9a-zA-Z]+}", GetUser)
http.Handle("/", routes)
http.ListenAndServe(":8080", nil)
}
<file_sep>/Datastrucures/mapExample.go
package main
//Map is not ordered it will come in any order. Maps are reference types.
import "fmt"
func main() {
dict := make(map[string]int) // This is one way to make a map.
dict["k1"] = 67
dict["k2"] = 78
fmt.Println(dict)
delete(dict, "k2") // Delete an etry in map.
fmt.Println(dict)
v, ok := dict["k2"] // To find out if the value is present or not.
fmt.Println(v, ok)
_, ok = dict["k1"]
fmt.Println(ok)
n := map[string]string{"fName": "Kate", "lName": "Wince"} // This is one way to make a map.
fmt.Println(n)
fmt.Println(n["fName"])
fmt.Println(len(n)) //Lenght of the map.
// var maper map[string]int // Wrong way to create a map. Because it will create a map and it is nill. But for map you cannot assign value to it
//In the case of Slice you can create a variable like above but you have append function which will append value to the slice.
var maper = make(map[string]int) // YOu can make a map this way using var. this is exactly same as maper := make(map[string]int
maper["Ager"] = 467
fmt.Println(maper)
fmt.Println(len(maper))
//Under a slice it is array. under a Map it is a Hash table.
}
<file_sep>/underStandPackageUnsafe/main.go
package main
import (
"fmt"
"time"
"unsafe"
)
type st struct {
fName string
lName string
TimeStamp time.Time
}
func main() {
var x float64 = 3333333333333333333333333333333333333333
var gm float64 = float64(6776)
var gm1 unsafe.Pointer = unsafe.Pointer(&gm)
z := st{"Tip", "Zip", time.Now(),gm1}
fmt.Printf("The value is %T \n", unsafe.Alignof(x))
fmt.Println("The value is", unsafe.Alignof(x))
//fmt.Printf("The value is %T \n", unsafe.Offsetof(x))
//fmt.Println("The value is", unsafe.Offsetof(x))
fmt.Printf("The value is %T \n", unsafe.Sizeof(x))
fmt.Println("The value is", unsafe.Sizeof(x))
fmt.Printf("The value is %T \n", unsafe.Alignof(z))
fmt.Println("The value is", unsafe.Alignof(z))
//fmt.Printf("The value is %T \n", unsafe.Offsetof(z))
//fmt.Println("The value is", unsafe.Offsetof(z))
fmt.Printf("The value is %T \n", unsafe.Sizeof(z))
fmt.Println("The value is", unsafe.Sizeof(z))
fmt.Println("The Value of struct is :" , z)
}
<file_sep>/Datastrucures/mapRangeLoop.go
package main
import "fmt"
func main() {
rangeMap := map[string]int{
"Maths": 5,
"Physics": 6,
"Chemistry": 7,
}
for key, val := range rangeMap {
fmt.Println(key, "-", val)
}
}
<file_sep>/Datastrucures/sliceDefineDiffrentWays.go
package main
import "fmt"
func main() {
var sliceVar []string //var way
slice := []string{} //Straight Hand method
slice3 := make([]int, 10, 10) //Make way
var sliceVarMake = make([]int, 3, 3) //This can be a best way to make a slice, In this the 3 and 3 can be parameterised
//fmt.Println(slice[0]) //This will give index out of range. Because slice is not yet built.
slice = append(slice, "1")
sliceVar = append(sliceVar, "1")
fmt.Println(sliceVar[0])
fmt.Println(slice[0]) //In the case of straight hand method you have to use to append to create the slice. This wont fail.
fmt.Println(slice3[0]) //This will not give any value because using Make clause the slice will be build with 10 underlying array
fmt.Println(sliceVarMake[1]) //Best way to make a slice.
}
<file_sep>/functions/variadicFuncitons.go
package main
import "fmt"
func main() {
total1, average1 := variadicFunction(67, 78.90, 56665.78, 56, 45, 34, 6767.99)
fmt.Println("The totals1 of input is : ", total1)
fmt.Println("The average1 of input is : ", average1)
st := []float64{6, 7, 5, 6, 7, 8, 6.99, 7887.999999999}
total2, average2 := variadicFunction(st...) // This is a variadic argument for the arguments the ... are in the end
fmt.Println("The totals2 of input is : ", total2)
fmt.Println("The average2 of input is : ", average2)
}
func variadicFunction(st ...float64) (float64, float64) { // For Parameters the arguments are the begining
fmt.Println("The value of the input is : ", st)
total := 0.00
for _, num := range st {
total += num
}
average := total / float64(len(st))
fmt.Println("The totals of input is : ", total)
fmt.Println("The average of input is : ", average)
return total, average
}
<file_sep>/functions/exercise2.go
package main
import "fmt"
func greatest(num ...int) int {
var largest int
for _, i := range num {
if i > largest {
largest = i
}
}
return largest
}
func main() {
val := greatest(0, 0, 0, 0, 0, 0, 0)
fmt.Println(val)
slice := []int{5, 6, 7, 4, 23, 44444, 55, 0, 1000000000}
fmt.Println(greatest(slice...))
fmt.Println(greatest())
}
<file_sep>/concurrancy/conCurRace.go
package main
import (
"fmt"
"sync"
"time"
)
//Race is when multiple Go routines runs concurently then the variables will get overriden.
//The below example is a Race condition.
// The value of the conter should be ideally 40 but it is only 21. Because overridding will happen.
// go run -race conCurRace.go --> This will give the race condition. --> Found 1 data race(s).
var counter int
var wg sync.WaitGroup
func incrementer(s string) {
for i := 0; i <= 20; i++ {
x := counter
x++
time.Sleep(time.Duration(20 * time.Millisecond))
counter = x
fmt.Println(s, i, "Counter", counter)
}
wg.Done()
}
func main() {
wg.Add(2)
go incrementer("Foo")
go incrementer("Bar")
wg.Wait()
}
<file_sep>/channels/channelsExample3.go
package main
import (
"fmt"
"time"
)
func goRunTwo(c chan int, done chan bool) {
for i := 0; i < 5; i++ {
time.Sleep(time.Second)
c <- i
}
done <- true
}
func drain(c chan int, done chan bool) {
<-done
<-done
<-done
close(c)
}
func printC(c chan int) {
for i := range c {
time.Sleep(time.Second)
fmt.Println(i)
}
}
func main() {
c := make(chan int)
done := make(chan bool)
go func() {
for i := 0; i < 5; i++ {
c <- i
}
done <- true
}()
go goRunTwo(c, done)
go goRunTwo(c, done)
go drain(c, done)
printC(c)
}
<file_sep>/channels/channelsPipelines.go
package main
import (
"fmt"
)
// We already checked this how it works.
func main() {
c := input(4, 5, 6, 76, 6, 66)
for n := range squre(c) {
fmt.Println(n)
}
for n := range squre(squre(squre(input(5, 6, 7)))) { //This is pipelining, the channels output is passed again and again.
fmt.Println(n)
}
}
func input(num ...int) <-chan int {
out := make(chan int)
go func() {
for _, n := range num {
out <- n
}
close(out)
}()
return out
}
func squre(s <-chan int) <-chan int {
out := make(chan int)
go func() {
for n := range s {
out <- n * n
}
close(out)
}()
return out
}
<file_sep>/Interfaces/mapOfInterfacs.go
package main
import "fmt"
func main() {
maper := make(map[string]interface{})
maper["Zola"] = "Variance"
maper["3234"] = 2342342
maper["65768.90"] = []string{"234", "454", "4545"}
fmt.Println(maper)
}
<file_sep>/smartTrackerAPI/smartTracker.go
package main
import (
"encoding/json"
"fmt"
"github.com/gorilla/mux"
"gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
"log"
"net/http"
"strconv"
"time"
"errors"
)
var (
session *mgo.Session
collection *mgo.Collection
)
type InputValidator interface {
Validator(r *http.Request) error
}
type Transaction struct {
Id bson.ObjectId `bson:"_id,omitempty"`
AccountNumber string `json:"accountNumber"`
TransactionId string `json:"transactionId"`
TransactionDate string `json:"transactionDate"`
TransactionDetails string `json:"transactionDetails"`
TransactionAmount float64 `json:"transactionAmount"`
TimeStamp time.Time `json:"timeStamp"`
HasInsurance bool `json:"hasInsurance"`
HasOffers bool `json:"hasOffers"`
}
func (tran *Transaction) InputValidator(r *http.Request) error {
dec := json.NewDecoder(r.Body)
var v map[string]interface{}
if err := dec.Decode(&v); err != nil {
panic(err)
}
for k := range v {
if k == "transactionAmount" {
_, ok := v[k].(float64)
if ok == false {
errors.New("Invalid transactionAmount")
}
}
if k == "hasInsurance" {
_, ok := v[k].(bool)
if ok == false {
errors.New("Invalid hasInsurance")
}
}
if k == "hasOffers" {
_, ok := v[k].(bool)
if ok == false {
errors.New("Invalid hasOffers")
}
}
}
return nil
}
type Transactions struct {
Transactions []Transaction `json:"entries"`
}
func getSession() *mgo.Session {
session, err := mgo.Dial("127.0.0.1")
if err != nil {
panic(err)
}
return session
}
func createTransaction(w http.ResponseWriter, r *http.Request) {
decoder := json.NewDecoder(r.Body)
fmt.Println(decoder)
var v map[string]interface{}
fmt.Println("THis is a session")
if err := decoder.Decode(&v); err != nil {
fmt.Println(err)
fmt.Println("This is a error")
return
}
for k := range v {
fmt.Println("hola", v[k])
if k == "transactionAmount" {
val, ok := v[k].(float64)
if ok == true {
fmt.Println("This is the value transaction:", val)
} else {
fmt.Println("This went wrong transaction :", val)
}
}
if k == "hasInsurance" {
val, ok := v[k].(bool)
if ok == true {
fmt.Println("This is the value hasInsurance:" , val)
} else {
fmt.Println("This went wrong hasInsurance:" , val)
}
}
}
newTran := Transaction{}
err := decoder.Decode(&newTran)
//var v map[string]interface{}
//fmt.Println("THis is a session")
//if err := decoder.Decode(&v); err != nil {
// fmt.Println(err)
// fmt.Println("This is a error")
// return
//}
//for k := range v {
// fmt.Println("hola", v[k])
//}
fmt.Println(newTran)
fmt.Println(newTran.TransactionAmount, newTran.HasInsurance)
// newTran.TransactionAmount = strconv.ParseFloat(r.FormValue("transactionAmount"), 64)
//tranAmt, err := strconv.ParseFloat(r.FormValue("transactionAmount"), 64)
//if err != nil {
// panic(err)
//}
//newTran.TransactionAmount = tranAmt
//if r.FormValue("hasInsurance") == "true" {
// newTran.HasInsurance = true
//} else {
// newTran.HasInsurance = false
//}
//if r.FormValue("hasOffers") == "true" {
// newTran.HasOffers = true
//} else {
// newTran.HasOffers = false
//}
newTran.TimeStamp = time.Now()
output, err := json.Marshal(newTran)
if err != nil {
log.Fatal(err)
}
fmt.Println(output)
err = collection.Insert(&newTran)
if err != nil {
log.Fatal(err)
}
}
func retrieveTransactions(w http.ResponseWriter, r *http.Request) {
log.Println("Starting Retreival")
start := 0
limit := 10
next := start + limit
nextUri := "<http://localhost:8080/api/users?start=" + strconv.Itoa(next) + "; rel=\"next\""
fmt.Println(nextUri)
w.Header().Set("Pragma", "no-cache")
w.Header().Set("Link", nextUri)
Response := Transactions{}
err := collection.Find(nil).All(&Response.Transactions)
if err != nil {
panic(err)
}
output, _ := json.Marshal(Response)
fmt.Fprintln(w, string(output))
}
func testNewUser(w http.ResponseWriter, r *http.Request) {
log.Println("starting retreival")
var response = `{"userFirstName":"Dennis","userLastName":"John"}`
//Response := Users{}
//Response.Users = rows
output, _ := json.Marshal(response)
fmt.Fprintln(w, string(output))
}
func main() {
session = getSession()
collection = session.DB("goWebServiceStudy").C("transactions")
defer session.Close()
routes := mux.NewRouter()
routes.HandleFunc("/api/transactions", createTransaction).Methods("POST")
routes.HandleFunc("/api/transactions", retrieveTransactions).Methods("GET")
routes.HandleFunc("/api/test", testNewUser).Methods("GET")
http.Handle("/", routes)
http.ListenAndServe(":8080", nil)
}
<file_sep>/functions/variadicFunctions.go
package main
import (
"fmt"
"reflect"
)
func main() {
variFunc(45, 45, 45, 45, 34, 55, 45.55, 55.78879) // You can pass any number for float64 values to the variadic function.
}
func variFunc(st ...float64) { //This is an example of variadic function, we can pass any number of values to variadicFunction
fmt.Println("The test vlaue is : ", st) //st will be a slice
fmt.Println("The type of the value passed is : ", reflect.TypeOf(st))
total := 0.00
for _, num := range st { //This is an example using Range
total += num
}
average := total / float64(len(st))
fmt.Println("The total is : ", total)
fmt.Println("The average is : ", average)
}
<file_sep>/Datastrucures/slice2DimInt.go
package main
import "fmt"
func main() {
transactions := make([][]int, 0, 3) //Make sure give as the Lenght of 0 or else the empty slice will be created.
for i := 0; i < 3; i++ {
transaction := make([]int, 0, 3)
for j := 0; j < 3; j++ {
transaction = append(transaction, j)
}
transactions = append(transactions, transaction)
}
fmt.Println(transactions)
trans := make([][]int, 3, 3)
for i := 0; i < 3; i++ {
tran := make([]int, 3, 3)
for j := 0; j < 3; j++ {
tran[j] = j
}
trans[i] = tran
}
fmt.Println(trans)
fullTran := make([][]int, 3, 3)
for i := 0; i < len(fullTran); i++ {
fullTran[i] = []int{4, 5, 6, 4, 4, 5}
}
fmt.Println(fullTran)
}
<file_sep>/goExamples/factorialSequencial.go
package main
import (
"fmt"
// "math/rand"
//"runtime"
"math/rand"
"time"
)
func main() {
start := time.Now()
//for _, n := range factorial(gen(10000)...) {
// fmt.Println("The random Factorial is:", n)
//}
var i int
for range factorial(gen(10000000)...) {
i++
}
fmt.Println("Count:", i)
fmt.Println("Current Time:", time.Now(), "Start Time:", start, "Elapsed Time:", time.Since(start))
}
func gen(n int) []int {
out := make([]int, 0, n)
for i := 0; i < n; i++ {
out = append(out, rand.Intn(20)+1)
//out = append(out, 10)
}
println(len(out))
return out
}
func factorial(val ...int) []int {
out := make([]int, 0, len(val))
for _, n := range val {
fa := calcFact(n)
out = append(out, fa)
}
return out
}
func calcFact(c int) int {
if c == 0 {
return 1
} else {
return calcFact(c-1) * c
}
}
//###End of Factorial sequential processing
<file_sep>/Datastrucures/slice3.go
package main
import "fmt"
func main() {
sl := []string{"Monday", "Tuesday"} // This will create a slice of len 2 and capacity 2. If you want to make a slice with known capacity use "make"
slMother := []string{"Wednesday", "Thursday", "Friday"}
fmt.Println(sl)
sl = append(sl, slMother...) // Append command will create a new slice sl with sl and slMother appended.
fmt.Println("len:", len(sl), "capacity:", cap(sl), "value:", sl)
sl = append(sl[:2], sl[3:]...) // This is kind of deleting from a slice. Wednesday will be deleted.
fmt.Println("len:", len(sl), "capacity:", cap(sl), "value:", sl) //If you check the capacity will 5 and length will be 4
}
<file_sep>/Datastrucures/mapExample1.go
package main
import "fmt"
func main() {
greet := map[int]string{
0: "Good Morning",
1: "Bonjour!",
2: "Namaskaram",
}
fmt.Println(greet)
if val, exists := greet[0]; exists {
fmt.Println("The value exists:", val)
} else {
fmt.Println("The value does not exist:")
}
delete(greet, 2)
if val, exists := greet[2]; exists {
fmt.Println("The value exists:", val)
} else {
fmt.Println("The value does not exist")
}
}
<file_sep>/Datastrucures/sliceIncrement.go
package main
import "fmt"
func main() {
var slice = make([]int, 1)
slice[0] = 1
fmt.Println(slice)
// slice[1] = 3 //If you run this before appending then this will fail with index out of range because the underlying array is of lengh only 1
slice = append(slice, 3) //Append to add another element
fmt.Println(slice)
slice[1]++ //This will make the element slice[1] increment by 1 so 3 will become 4. This is equvalent to slice[1] = slice[1] + 1.
fmt.Println(slice)
slice[0] += 8 //This is another way to add 8 to slice[0] so 1 will become 9
fmt.Println(slice)
}
<file_sep>/goWebServerExample/apiMongoExample.go
package main
import (
"encoding/json"
"fmt"
"github.com/gorilla/mux"
"gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
"log"
"net/http"
"strconv"
"time"
)
var (
session *mgo.Session
collection *mgo.Collection
)
type Transaction struct {
Id bson.ObjectId `bson:"_id,omitempty"`
AccountNumber string `json:"accountNumber"`
TransactionId string `json:"transactionId"`
TransactionDate string `json:"transactionDate"`
TransactionDetails string `json:"transactionDetails"`
TransactionAmount float64 `json:"transactionAmount"`
TimeStamp time.Time `json:"timeStamp"`
HasInsurance bool `json:"hasInsurance"`
HasOffers bool `json:"hasOffers"`
}
type Transactions struct {
Transactions []Transaction `json:"entries"`
}
func getSession() *mgo.Session {
session, err := mgo.Dial("127.0.0.1")
if err != nil {
panic(err)
}
return session
}
func createTransaction(w http.ResponseWriter, r *http.Request) {
newTran := Transaction{}
newTran.AccountNumber = r.FormValue("accountNumber")
newTran.TransactionId = r.FormValue("transactionId")
newTran.TransactionDate = r.FormValue("transactionDate")
newTran.TransactionDetails = r.FormValue("transactionDetails")
// newTran.TransactionAmount = strconv.ParseFloat(r.FormValue("transactionAmount"), 64)
tranAmt, err := strconv.ParseFloat(r.FormValue("transactionAmount"), 64)
if err != nil {
panic(err)
}
newTran.TransactionAmount = tranAmt
if r.FormValue("hasInsurance") == "true" {
newTran.HasInsurance = true
} else {
newTran.HasInsurance = false
}
if r.FormValue("hasOffers") == "true" {
newTran.HasOffers = true
} else {
newTran.HasOffers = false
}
newTran.TimeStamp = time.Now()
output, err := json.Marshal(newTran)
if err != nil {
log.Fatal(err)
}
fmt.Println(output)
err = collection.Insert(&newTran)
if err != nil {
log.Fatal(err)
}
}
func retrieveTransactions(w http.ResponseWriter, r *http.Request) {
log.Println("Starting Retreival")
start := 0
limit := 10
next := start + limit
nextUri := "<http://localhost:8080/api/users?start=" + strconv.Itoa(next) + "; rel=\"next\""
fmt.Println(nextUri)
w.Header().Set("Pragma", "no-cache")
w.Header().Set("Link", nextUri)
Response := Transactions{}
err := collection.Find(nil).All(&Response.Transactions)
if err != nil {
panic(err)
}
output, _ := json.Marshal(Response)
fmt.Fprintln(w, string(output))
}
func main() {
session = getSession()
collection = session.DB("goWebServiceStudy").C("transactions")
defer session.Close()
routes := mux.NewRouter()
routes.HandleFunc("/api/transactions", createTransaction).Methods("POST")
routes.HandleFunc("/api/transactions", retrieveTransactions).Methods("GET")
http.Handle("/", routes)
http.ListenAndServe(":8080", nil)
}
<file_sep>/goExamples/understandingInterface6.go
package main
import "fmt"
type car struct {
wheels string
seats string
name string
}
func (c *car) String() string {
return fmt.Sprintf("My name is %s I got %s wheels and %s seats", c.name, c.wheels, c.seats)
}
func main() {
c := &car{"4", "5", "Tony"}
fmt.Println(c)
}
<file_sep>/channels/deadLockChallenge.go
package main
import "fmt"
func main() {
// The commented code will restult in dead lock. Why because when c gets a value of 1 no one is there to receive it.
// It is when you put a value in a channel, the code pointer will not go to a diffrent line until some one takes the value from the channel.
// so when c <- 1 the code is not moving to the next line because no one is taking the value from the channel.
// So if the c <- 1 is in a seperate go routine it will execute of its own and fmt.Println(<-c) will execute to take the value out of channel.
//c := make(chan int)
//c <- 1
//fmt.Println(<-c)
c := make(chan int)
go func() {
c <- 1
c <- 2
}()
fmt.Println(<-c)
fmt.Println(<-c)
}
<file_sep>/functions/passByValue.go
package main
import "fmt"
func main() {
age := 44 // I am assigning a value to age
fmt.Println(age) // Printing the value it will 44
fmt.Println(&age) // Printing the vlaue of the address of where age is stored it will be 0xc82000a2e0
makeMeYoung(&age) // Calling the function that accepts the address
fmt.Println(age) // Print the value it will be 22
fmt.Println(&age) // Print the value of the address of where age is stored it will be 0xc82000a2e0
}
func makeMeYoung(z *int) { // This function will only accept the address of arguments passed
fmt.Println(z) // This will print the address because address is only passed to z
fmt.Println(*z) // This will print the value *z will derefference the address it will print the value.
*z = 22 //22 is stored in the address 0xc82000a2e0
fmt.Println(z) // will print 0xc82000a2e0
fmt.Println(*z) // will print 22
}
//note for slices , maps and channels it is already an address so no need to pass the address if you pass the actual value it is passing the address
//Check and code how it works it is not done yet.
<file_sep>/functions/recurstion.go
package main
//Recursion is a function calling itself, the below example is used for factorial.
//Check how to pass a huge number and its factorial
import (
"fmt"
)
func factorial(x float64) float64 {
if x == 0 {
return 1
}
return x * factorial(x-1)
}
func main() {
xs := factorial(42)
fmt.Println(xs)
}
<file_sep>/Datastrucures/structOverride.go
package main
import "fmt"
//very good example to understand Struct override and methods
type Person struct {
fName string
lName string
tag string // Tag is repeated in both Person and DoubleZero
}
type DoubleZero struct {
Person
specialAgent bool
tag string // tag in DoubleZero will overide the tag in Person.
}
func (p Person) Greeting() string {
return p.fName + p.lName + " I am a normal human being " + p.tag
}
func (d DoubleZero) Greeting() string {
return d.fName + d.lName + "I am Jamesbond" + d.tag + d.Person.tag
}
func main() {
d := DoubleZero{
Person: Person{
fName: "James",
lName: "Bond",
tag: "007",
},
specialAgent: true,
tag: "008",
}
p := Person{"Loyal", "Flight", "009"}
d1 := DoubleZero{p, false, "0010"}
d2 := DoubleZero{Person{"Fulham", "Brunet", "02322"}, true, "887887"}
fmt.Println(d.Greeting())
fmt.Println(d1.Greeting())
fmt.Println(d.Person.Greeting())
fmt.Println(d1.Person.Greeting())
fmt.Println(p.Greeting())
fmt.Println(d2.Greeting())
point := &Person{"DDD", "YYY", "789"} //Struct Pointer.
fmt.Println(point.Greeting() + " " + point.tag)
}
<file_sep>/functions/UnderstandingPigGameForTwoPlayers.go
//Pig game winner
package main
import (
"fmt"
"math/rand"
"time"
)
const (
win = 100
)
type person struct {
player, opponent, thisTurn int
}
type action func(p person) (NewPerson person, isTurnOver bool)
func roll(p person) (person, bool) {
random := rand.Intn(6) + 1 //To get a random number from 1 to 6
if random == 1 {
return person{p.opponent, p.player, 0}, true
}
return person{p.player, p.opponent, p.thisTurn + random}, false
}
func stay(p person) (person, bool) {
return person{p.opponent, p.player + p.thisTurn, 0}, true
}
type strategy func(p person) action
func stayAtValue(k int) strategy {
return func(p person) action {
if p.thisTurn >= k {
return stay
} else {
return roll
}
}
}
func play(strategy1, strategy2 strategy) int {
strategies := []strategy{strategy1, strategy2}
var onGoing person
var turnOver bool
currentPlayer := rand.Intn(2)
fmt.Println("Who is the current Player:", currentPlayer)
for onGoing.player+onGoing.thisTurn < win {
action := strategies[currentPlayer](onGoing)
onGoing, turnOver = action(onGoing)
fmt.Println("The value of the onGoing is:", onGoing, turnOver)
if turnOver {
currentPlayer = (currentPlayer + 1) % 2
}
}
return currentPlayer
}
func main() {
rand.Seed(time.Now().UnixNano()) //This will give a randomness to the rand. Because rand will generate the number based on env so the number will be same all the time.
//Check the https://tour.golang.org/basics/1
strategy1 := stayAtValue(25)
strategy2 := stayAtValue(20)
winner := play(strategy1, strategy2)
if winner == 0 {
fmt.Println("The player with stay at 25 is the winner")
} else {
fmt.Println("The player with stay at 20 is the winner")
}
}
<file_sep>/functions/closure.go
package main
import "fmt"
var x int
var y int
func increment() {
x++
}
func increment1() int {
y++
return y
}
func wrapper() func() int {
m := 0
return func() int {
m++
return m
}
}
func main() {
increment()
fmt.Println(x)
increment()
fmt.Println(x)
fmt.Println(increment1())
fmt.Println(increment1())
z := 0
increment2 := func() int {
z++
return z
}
fmt.Println(increment2())
fmt.Println(increment2())
wrap := wrapper()
fmt.Println("Hola ", wrap())
fmt.Println("Hola ", wrap())
}
<file_sep>/channels/channelsUnderstanding.go
package main
import (
"fmt"
"time"
)
func main() {
c := make(chan int)
go testChan(c)
fmt.Println(<-c)
fmt.Println(<-c)
fmt.Println(<-c)
fmt.Println(<-c)
time.Sleep(time.Second)
}
func testChan(c chan int) {
// c := make(chan int)
for i := 0; i < 10; i++ {
fmt.Println("Test", i)
c <- i
}
close(c)
}
<file_sep>/Datastrucures/sliceUnderstanding.go
package main
import "fmt"
func main() {
sl := make([]int, 0, 5)
fmt.Println(len(sl))
fmt.Println(cap(sl))
fmt.Println(sl)
for i := 0; i < 80; i++ {
sl = append(sl, i)
fmt.Println("Len:", len(sl), "Cap:", cap(sl), "Value:", sl[i])
}
}
// THis example shows how the slice increses its Capacity by doubling its Cpacity.
// If you are doubling the capacity then it will have performance implication because the first array is copied and then a new array is created with a new
// value. So give as much as possible a correct Capacity for a slice.
// Go does the doubling of capacity upto 100000 or not sure then it will do another algorithm which will increase by percentage this is for performance.
<file_sep>/goWebServerExample/advancedRoutersGorilla.go
package main
import (
"fmt"
"github.com/gorilla/mux"
"net/http"
)
func main() {
r := mux.NewRouter()
//r.HandleFunc("/api/users/{key:[A-Za-z0-9]}", homeHandler)
r.HandleFunc("/api/users/{key:[0-9A-Za-z-]+}", homeHandler)//This reqex accepts Numbers Alpha characters A To Z and a to z and hypen
http.Handle("/", r)
err := http.ListenAndServe(":8080", nil)
if err != nil {
panic(err.Error())
}
}
func homeHandler(w http.ResponseWriter, req *http.Request) {
urlParms := mux.Vars(req)
key := urlParms["key"]
fmt.Fprintln(w, "Entra to site:", key)
//fmt.Fprintf(w, "Hi there, I love %s!", req.URL.Path[1:])
// w.Write([]byte("This is a sample Application"))
}
<file_sep>/Datastrucures/array1.go
package main
import "fmt"
func main() {
var array [58]string
for i := 65; i <= 122; i++ {
array[i-65] = string(i)
}
fmt.Println(array)
}
<file_sep>/Interfaces/sortExample1.go
package main
import (
"fmt"
"sort"
)
type people []string
func (p people) Len() int {
return len(p)
}
func (p people) Swap(i, j int) {
p[i], p[j] = p[j], p[i]
}
func (p people) Less(i, j int) bool {
return p[i] < p[j]
}
//typeSlice is similar to StringSlice
//type typeSlice []string
//
//func (p typeSlice) Len() int {
// return len(p)
//}
//
//func (p typeSlice) Swap(i, j int) {
// p[i], p[j] = p[j], p[i]
//}
//
//func (p typeSlice) Less(i, j int) bool {
// return p[i] < p[j]
//}
//
//func (p typeSlice) Sort() {
// sort.Sort(p)
//}
func main() {
//Sorting using the standard method.
studyGroup := people{"Zeno", "John", "Al", "Jenny"}
fmt.Println(studyGroup)
sort.Sort(studyGroup) // If you check the sort package the data Interface note the capitals Interface
// There is a Interface interface in sort package that expects len, swap and less methods
// So it is mandatory to have these in underlying type people.
fmt.Println(studyGroup)
//Second method
s := []string{"Zeno", "John", "Al", "Jenny"}
// In the above case of studyGroup it was of a type people and so we can attach methods to it. Len, swap and less and for
// Sort interface these three methods are required
// in this case we cant attach methords to s. So we have to convert it to a type variable and then attachmenthods
// Or we can use string slice.
fmt.Println(s)
sort.StringSlice(s).Sort() // the S is type cased to a Type with methodes Len, Swap and less attached to it.
// fmt.Println(typeSlice(s))
fmt.Println(s)
}
<file_sep>/goExamples/interfaceUnderstanding3.go
package main
import "fmt"
//func PrintAll(vals []interface{}) { // This will fail becaust and array of string cannot be conveted to a interface.
// for _, val := range vals {
// fmt.Println(val)
// }
//}
func PrintAll(vals []interface{}) { // This will fail becaust and array of string cannot be conveted to a interface.
for _, val := range vals {
fmt.Println(val)
}
}
func PrintOne(val interface{}) {
fmt.Println("This is a print one interface value :", val)
}
func main() {
names := []string{"stanley", "david", "oscar"}
v := make([]interface{}, 0, len(names))
for _, x := range names {
v = append(v, x)
}
PrintAll(v)
PrintOne(454445)
}
<file_sep>/channels/channelsChallenge2.go
package main
import "fmt"
func main() {
c := make(chan int)
go func() {
for i := 0; i < 10; i++ {
c <- i
}
close(c)
}()
//fmt.Println(<-c) // There is no race or no deadlock, but only 0 is printed because only one value is taken out of the channel c
// The below commentd code will give dead lock.
//for {
// fmt.Println(<-c) // He will be waiting for the c but the loop ends after 10.
//}
for n := range c { // If you range use close(c) // This should work no problemo.
fmt.Println(n)
}
}
<file_sep>/goMiniProject/tableExtract.go
package main
import (
"fmt"
"gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
"time"
)
type transaction struct {
AccountNumber string `bson:"accountNumber"`
TransactionId string `bson:"transactionId"`
TransactionDate string `bson:"transactionDate"`
TransactionDetails string `bson:"transactionDetails"`
TransactionAmount float64 `bson:"transactionAmount"`
TimeStamp time.Time `bson:"timeStamp"`
HasInsurance bool `bson:"hasInsurance"`
HasOffers bool `bson:"hasOffers"`
}
type summary struct {
AccountNumber string
TotalTransaction float64
}
type statement struct {
ID bson.ObjectId `bson:"_id,omitempty"`
Transactions []transaction `bson:"transactions"`
Insurance []transaction `bson:"insuarnceTransactions"`
Offers []transaction `bson:"offersTransactions"`
Summary summary `bson:"transactionsSummary"`
InsuranceSummary summary `bson:"insuranceTransactionsSummary"`
OffersSummary summary `bson:"offersTransactionsSummary"`
}
func main() {
start := time.Now()
session, err := mgo.Dial("127.0.0.1")
if err != nil {
panic(err)
}
defer session.Close()
// Optional. Switch the session to a monotonic behavior.
session.SetMode(mgo.Monotonic, true)
c := session.DB("goWebServiceStudy").C("transactions")
var results []string
err = c.Find(nil).Distinct("accountNumber", &results)
fmt.Println(results)
//statements := []statement{}
c1 := session.DB("goWebServiceStudy").C("statements")
for i := 0; i < len(results); i++ {
local := statement{}
local.Transactions, local.Summary = tranProcessing(results[i], c)
local.Insurance, local.InsuranceSummary = insuranceProcessing(results[i], c)
local.Offers, local.OffersSummary = offersProcessing(results[i], c)
//for j := 0; j < len(local.Transactions); j++ {
// fmt.Println(local.Transactions[j])
//}
//fmt.Println(local.Summary)
//for j := 0; j < len(local.Insurance); j++ {
// fmt.Println(local.Insurance[j])
//}
//fmt.Println(local.InsuranceSummary)
//for j := 0; j < len(local.Offers); j++ {
// fmt.Println(local.Offers[j])
//}
//fmt.Println(local.OffersSummary)
err = c1.Insert(&local)
if err != nil {
panic(err.Error())
}
//statements = append(statements, local)
}
//fmt.Println(statements)
fmt.Println("Current Time:", time.Now(), "Start Time:", start, "Elapsed Time:", time.Since(start))
}
func tranProcessing(accountNumber string, c *mgo.Collection) ([]transaction, summary) {
var transactions []transaction
err := c.Find(bson.M{"accountNumber": accountNumber}).All(&transactions)
if err != nil {
panic(err)
}
var sumTransaction float64
for i := 0; i < len(transactions); i++ {
sumTransaction += transactions[i].TransactionAmount
}
summary := summary{accountNumber, sumTransaction}
return transactions, summary
}
func insuranceProcessing(accountNumber string, c *mgo.Collection) ([]transaction, summary) {
var transactions []transaction
err := c.Find(bson.M{"accountNumber": accountNumber, "hasInsurance": true}).All(&transactions)
if err != nil {
panic(err)
}
//fmt.Println(transactions)
var sumTransaction float64
for i := 0; i < len(transactions); i++ {
sumTransaction += transactions[i].TransactionAmount
}
summary := summary{accountNumber, sumTransaction}
return transactions, summary
}
func offersProcessing(accountNumber string, c *mgo.Collection) ([]transaction, summary) {
var transactions []transaction
err := c.Find(bson.M{"accountNumber": accountNumber, "hasOffers": true}).All(&transactions)
if err != nil {
panic(err)
}
var sumTransaction float64
for i := 0; i < len(transactions); i++ {
sumTransaction += transactions[i].TransactionAmount
}
summary := summary{accountNumber, sumTransaction}
return transactions, summary
}
<file_sep>/functions/functions01.go
package main
import "fmt"
func main() {
greet("Dennis") //The value passed "Dennis" is the argument that is passed to the fucntion greet()
greet("Joel")
greetTwo("Joel", "Plackal")
}
func greet(name string) { //This function only accepts one parameter name. There are no receivers or return values in this function. This function just prints the argument passed to it.
fmt.Println("Hello! " + name)
}
func greetTwo(fname string, lname string) { //This function accepts two parameterers.
fmt.Println("Hello! " + fname + " " + lname)
}
//Diffrence between Parameter and arugment. The argument is one that is passed to the function i.e "Joel" is an argument. The parameters are the one the function accepts i.e name in the function
//greet is a parameter.
<file_sep>/channels/semaphoreChannel.go
package main
import "fmt"
func main() {
c := make(chan int)
done := make(chan bool)
go func() {
for i := 0; i < 10; i++ {
c <- i
}
done <- true
}()
go func() {
for i := 0; i < 10; i++ {
c <- i
}
done <- true
}()
go func() {
<-done // This will spit out the channel done. It will wait until there is some thing in the done channel.
var doneValue bool = <-done // This done will spit the value to doneValue.
fmt.Println(doneValue)
close(c)
}()
for n := range c {
fmt.Println(n)
}
//Test to check commit changes ignore this comment.
}
<file_sep>/Datastrucures/slice1.go
package main
import "fmt"
func main() {
mySlice := []int{1, 2, 3, 4, 5, 6}
fmt.Printf("%T\n", mySlice)
fmt.Println(mySlice, len(mySlice), cap(mySlice))
fmt.Println(mySlice[1:4]) // the indexing will start at 0 and it will stop at 4 - 1. This will print [2 3 4]
fmt.Println(string("<NAME>"[9])) //This is string converted value of a indexed name. It gives h
fmt.Println("<NAME>"[9]) //A String can be indexed and accessed using index numbers but it gives the ASCII value of it.
}
//Slice got an underlying array.
//Slice accepts three prarameters what type of slice it is String or Int, lenght - what is the initial length of slice, capacity - what is the intitial
//lenth of the underlying array.
//if the lenght of the capacity increses the Go Programe will double the size of the slice with capacity.
<file_sep>/functions/pigGame.go
package main
import (
"fmt"
"math/rand"
)
/*
This program simulates the PIG game between two players.
If the player rolls a 1, they score nothing and it becomes the next player's turn.
If the player rolls any other number, it is added to their turn total and the player's turn continues.
If a player chooses to "hold", their turn total is added to their score, and it becomes the next player's turn.
The first player to score 100 or more points wins.
For example, the first player, Ann, begins a turn with a roll of 5. Ann could hold and score 5 points, but chooses to roll again.
Ann rolls a 2, and could hold with a turn total of 7 points, but chooses to roll again. Ann rolls a 1, and must end her turn without scoring.
The next player, Bob, rolls the sequence 4-5-3-5-5, after which he chooses to hold, and adds his turn total of 22 points to his score.
*/
const (
win = 100 // A player should reach one
gamesPerSeries = 10 // Number of games Per series
)
// Pointes scored by the player - player
// Pointes scored by the opponent Player - opponent
// Pointes scored by the current player - thisTurn
type score struct {
player, opponent, thisTurn int
}
// Find out how this works
type action func(current score) (result score, turnIsOver bool)
// This simulates the roll of the die.
func roll(s score) (score, bool) {
outcome := rand.Intn(6) + 1 // This will generate a random number for 1 - 6 like a die throw
if outcome == 1 {
return score{s.opponent, s.player, 0}, true // If the outcome is 1 then the turn switches, the player becomes opoonent, opponent becomes player
}
return score{s.player, s.opponent, s.thisTurn + outcome}, false // If the outcome is not 1 then the turn stayes and the points get added up.
}
//This simulates the stay if the player is wishing to stay.
//The role swaps the total accumulates and gives a bool turnIsOver.
func stay(s score) (score, bool) {
return score{s.opponent, s.player + s.thisTurn, 0}, true
}
// Find out how this works
type strategy func(score) action
//Stay at k. This returns a stategy to stay if the person rolls k.
func stayAtK(k int) strategy {
return func(s score) action {
if s.thisTurn >= k {
return stay
}
return roll
}
}
//This will simumlate the play between two players.
func play(strategy0, strategy1 strategy) int {
strategys := []strategy{strategy0, strategy1} // Convert the stratergy into a slice of stratergy.
var s score
var turnIsOver bool
currentPlayer := rand.Intn(2) // This will get the random number between 0 and 1, i.e. Player 1 or Player 2.
for s.player+s.thisTurn < win {
action := strategys[currentPlayer](s) // call the strategy funciton. strategy accepts s score and returns and action. (Stay or roll functions)
s, turnIsOver = action(s) // action accepts a score and returns a new score , turn over bool.
if turnIsOver {
currentPlayer = (currentPlayer + 1) % 2 //This will swap to the next player.
}
}
return currentPlayer //This will return the current player who is the winner.
}
func roundRobin(strategies []strategy) ([]int, int) {
wins := make([]int, len(strategies))
for i := 0; i < len(strategies); i++ {
for j := i + 1; j < len(strategies); j++ {
for k := 0; k < gamesPerSeries; k++ {
winner := play(strategies[i], strategies[j])
if winner == 0 {
wins[i]++
} else {
wins[j]++
}
}
}
}
gamesPerStrategy := gamesPerSeries * (len(strategies) - 1) // NO self play
return wins, gamesPerStrategy
}
func ratioString(vals ...int) string {
total := 0
for _, val := range vals {
total += val
}
s := ""
for _, val := range vals {
if s != "" {
s += ", "
}
pct := 100 * float64(val) / float64(total)
s += fmt.Sprintf("%d/%d (%0.1f%%)", val, total, pct)
}
return s
}
func main() {
strategies := make([]strategy, 100) //This will make the strategy function 100 times because win is 100
for k := range strategies {
strategies[k] = stayAtK(k + 1)
}
wins, games := roundRobin(strategies)
for k := range strategies {
fmt.Printf("Wins, losses staying at k =% 4d: %s\n",
k+1, ratioString(wins[k], games-wins[k]))
}
}
<file_sep>/goExamples/factConcParrIdeal.go
package main
import (
"fmt"
"math/rand"
"time"
)
func main() {
start := time.Now()
gen(10000000)
fmt.Println("Current Time:", time.Now(), "Start Time:", start, "Elapsed Time:", time.Since(start))
}
func gen(n int) {
p := n / 2
q := p + 1
i := 0
done := make(chan bool)
splitChan := make(chan []int64)
go splitGen(q, n, splitChan, done)
go splitGen(1, p, splitChan, done)
go func() {
<-done
<-done
close(splitChan)
}()
for n := range splitChan {
// fmt.Println(n)
//for _, x := range n {
for range n {
//fmt.Println(x)
i++
}
}
fmt.Println(i)
}
func splitGen(p, q int, splitChan chan []int64, done chan bool) {
//var slice []int64
slice := make([]int64, 0, (q + 1 - p))
for i := p; i <= q; i++ {
slice = append(slice, factorial(rand.Intn(20)+1))
}
splitChan <- slice
done <- true
}
func factorial(n int) int64 {
return fact(1, n)
}
func fact(n, m int) int64 {
var fact int64
fact = 1
for i := n; i <= m; i++ {
fact *= int64(i)
}
return fact
}
<file_sep>/Interfaces/interfacesExample2.go
package main
import (
"fmt"
// "io"
// "os"
)
type Human struct {
name string
age int
phone string
}
type Student struct {
Human
school string
loan float64
}
type Employee struct {
Human
company string
salary float64
}
//Defining a method for Human
func (h Human) SayHi() {
fmt.Printf("Hi, I am %s you can call me on %s\n", h.name, h.phone)
}
//Defining a method for Human sing a song
func (h Human) Sing(lyrics string) {
fmt.Println("La la la la...", lyrics)
}
//Defining a method for Employee the same SayHi Method for Human but
//With diffrent message.
func (e Employee) SayHi() {
fmt.Printf("Hi, I am %s, I work for %s. Call me on %s\n", e.name, e.company, e.phone)
}
func (e Employee) Vedikai() {
fmt.Printf("Eppo vedikai paaru %s\n", e.company)
}
//Interface Men is implementing Human, Student and Employee
type Men interface {
SayHi()
Sing(lyrics string)
}
type Emp interface {
Vedikai()
}
func cryOut(m Men, song string) {
m.SayHi()
m.Sing(song)
}
func main() {
mike := Student{Human{"Mike", 25, "222-222-XXX"}, "MIT", 0.00}
paul := Student{Human{"Paul", 26, "111-222-XXX"}, "Harvard", 100}
sam := Employee{Human{"Sam", 36, "444-222-XXX"}, "Golang Inc.", 1000}
Tom := Employee{Human{"Sam", 36, "444-222-XXX"}, "Things Ltd.", 5000}
cryOut(mike, "Hoo La la la")
cryOut(sam, "Hola Hola Hola")
var i Men
var j Emp
i = paul
i.Sing("<NAME>")
i.SayHi()
i = Tom
j = Tom
i.SayHi()
i.Sing("<NAME>")
j.Vedikai()
// var w io.Writer
// w = os.Stdout
// w.Write()
}
<file_sep>/goExamples/factorialSlightlyDiffrent.go
package main
import (
"fmt"
"sync"
)
func main() {
ch := make(chan int)
r := 10
result := 1
go fact(r, ch)
for i := range ch {
result *= i
}
fmt.Println(result)
}
func fact(n int, ch chan int) {
p := n / 2
q := p + 1
var wg sync.WaitGroup
wg.Add(2)
go func() {
ch <- factPQ(1, p)
wg.Done()
}()
go func() {
ch <- factPQ(q, n)
wg.Done()
}()
go func() {
wg.Wait()
close(ch)
}()
}
func factPQ(p, q int) int {
r := 1
for i := p; i <= q; i++ {
r *= i
}
return r
}
<file_sep>/channels/channelsRange.go
package main
import "fmt"
// In this example "in channel" and "in range" will be printing kind of alternatively. because the channel will hold the execution of the particular go routine until the
// the channel is free by the range.
func main() {
c := make(chan int)
go func() {
for i := 0; i < 25; i++ {
fmt.Println("in Channel")
c <- i // This will put the value to the channel.
}
close(c) // Close will close the channel then the channel will be gone. then the range go routine will get over
}()
for n := range c { // This will take out the value from the channel.
fmt.Println("In range")
fmt.Println(n)
}
}
<file_sep>/functions/exercise1.go
package main
import "fmt"
func number(n int) (float64, bool) {
return float64(n) / 2, n%2 == 0
// if z == 0 {
// return float64(n / 2.00), true
// }
// return float64(n / 2.00), false
}
func main() {
m, isEven := number(46567757884)
fmt.Println(m, isEven)
x, isEven := number(8)
fmt.Println(x, isEven)
}
<file_sep>/goWebServiceStudy/connectToMongoDB.go
package main
import (
"gopkg.in/mgo.v2"
"time"
)
type simpleUser struct {
FName string `bson:"firstName"`
LName string `bson:"lastName"`
TimeStamp time.Time `bson:"timeStamp"`
}
const (
IsDrop = true
)
func main() {
session, err := mgo.Dial("127.0.0.1")
if err != nil {
panic(err)
}
defer session.Close()
session.SetMode(mgo.Monotonic, true)
if IsDrop {
err = session.DB("goWebServiceStudy").DropDatabase()
if err != nil {
panic(err)
}
}
c := session.DB("goWebServiceStudy").C("simpleUser")
err = c.Insert(&simpleUser{"Jacob", "Ochova", time.Now()})
if err != nil {
panic(err)
}
}
<file_sep>/functions/selfExecutingFunctions.go
package main
import "fmt"
func main() {
func() {
fmt.Println("I am coding")
}()
}
//This is anonymus self executing funcitons
<file_sep>/goWebServerExample/webServerWithTemplate.go
package main
import (
"fmt"
"github.com/gorilla/mux"
"net/http"
)
func main() {
r := mux.NewRouter()
r.HandleFunc("/", homeHandler)
http.Handle("/", r)
err := http.ListenAndServe(":8080", nil)
if err != nil {
panic(err.Error())
}
}
func homeHandler(w http.ResponseWriter, req *http.Request) {
fmt.Println("Entra to site")
//fmt.Fprintf(w, "Hi there, I love %s!", req.URL.Path[1:])
w.Write([]byte("This is a sample Application"))
}
<file_sep>/Interfaces/interfaceExample1.go
package main
import (
"fmt"
"math"
"net/http"
)
type Square struct {
side float64
}
type Circle struct {
radius float64
}
func (z Square) area() float64 {
return z.side * z.side
}
func (z Circle) area() float64 {
return z.radius * z.radius * (math.Pi)
}
type Shape interface {
area() float64
}
func info(z Shape) {
fmt.Println(z.area())
fmt.Println(z)
}
func main() {
s := Square{10}
info(s)
z := Circle{10}
info(z)
res, err := http.Get("Mannar and company")
}
<file_sep>/goMiniProject/tableLoad.go
package main
// This program will load transactions into Mongo Database.
import (
"gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
"log"
"math/rand"
"strconv"
"time"
)
type transaction struct {
ID bson.ObjectId `bson:"_id,omitempty"`
AccountNumber string `bson:"accountNumber"`
TransactionId string `bson:"transactionId"`
TransactionDate string `bson:"transactionDate"`
TransactionDetails string `bson:"transactionDetails"`
TransactionAmount float64 `bson:"transactionAmount"`
TimeStamp time.Time `bson:"timeStamp"`
HasInsurance bool `bson:"hasInsurance"`
HasOffers bool `bson:"hasOffers"`
}
const (
IsDrop = true
)
func main() {
session, err := mgo.Dial("127.0.0.1")
if err != nil {
panic(err)
}
defer session.Close()
// Optional. Switch the session to a monotonic behavior.
session.SetMode(mgo.Monotonic, true)
if IsDrop {
err = session.DB("goWebServiceStudy").DropDatabase()
if err != nil {
panic(err)
}
}
c := session.DB("goWebServiceStudy").C("transactions")
for i := 0; i <= 10; i++ {
x := randomAccountNumberGenerator()
for j := 1; j <= 10; j++ {
err = c.Insert(randomTransactionGenerator(j, x))
if err != nil {
log.Fatal(err)
}
}
}
}
func randomAccountNumberGenerator() string {
var randomAccountNumber string
//randomAccountNumber += string(rand.Intn(9)) + string(rand.Intn(9)) + string(rand.Intn(9)) + string(rand.Intn(9)) + string(rand.Intn(9))
// The above code will convert the number to its equvalent
////string not a number.
randomAccountNumber += strconv.Itoa(rand.Intn(9)) + strconv.Itoa(rand.Intn(9)) + strconv.Itoa(rand.Intn(9)) + strconv.Itoa(rand.Intn(9)) + strconv.Itoa(rand.Intn(9))
return randomAccountNumber
}
func randomTransactionGenerator(n int, account string) transaction {
var tr transaction
var x int
tr.AccountNumber = account
tr.TransactionId = strconv.Itoa(n)
tr.TransactionDate = time.Now().Format("02-01-2006")
tr.TransactionDetails = "This is a transaction details for : " + strconv.Itoa(n)
tr.TransactionAmount = 7.0 + float64(n*rand.Intn(56))
tr.TimeStamp = time.Now()
x = rand.Intn(9)
if x == 3 || x == 5 || x == 6 || x == 7 || x == 8 {
tr.HasInsurance = true
tr.HasOffers = false
} else {
tr.HasInsurance = false
tr.HasOffers = true
}
return tr
}
<file_sep>/goExamples/factorialConcurrent.go
package main
import (
"fmt"
"math/rand"
"sync"
"time"
//"runtime"
)
func main() {
start := time.Now()
printFact(fact(gen(1000000)))
fmt.Println("Current Time:", time.Now(), "Start Time:", start, "Elapsed Time:", time.Since(start))
// panic("Error Stack!")
}
func gen(n int) <-chan int {
c := make(chan int)
go func() {
for i := 0; i < n; i++ {
c <- rand.Intn(20) + 1
// c <- 10
}
close(c)
}()
return c
}
func fact(in <-chan int) <-chan int {
out := make(chan int)
var wg sync.WaitGroup
for n := range in {
wg.Add(1)
go func(n int) {
//temp := 1
//for i := n; i > 0; i-- {
// temp *= i
//}
temp := calcFact(n)
out <- temp
wg.Done()
}(n)
}
go func() {
wg.Wait()
close(out)
}()
return out
}
func printFact(in <-chan int) {
//for n := range in {
// fmt.Println("The random Factorial is:", n)
//}
var i int
for range in {
i++
}
fmt.Println("Count:", i)
}
func calcFact(c int) int {
if c == 0 {
return 1
} else {
return calcFact(c-1) * c
}
}
//###End of Factorial Concurrent
<file_sep>/Interfaces/sortReverse.go
package main
import (
"fmt"
"sort"
)
func main() {
s := []string{"Zeno", "Samper", "Velma", "Sulia"}
fmt.Println(s)
//This will sort the string passed.
sort.StringSlice(s).Sort()
fmt.Println(s)
//The reverse string method.
//sort.Sort(sort.Reverse(sort.StringSlice(s)))
//fmt.Println(s)
// The below code says how the whole thing works, But need more digging in of the sort package should be done.
s = sort.StringSlice(s)
fmt.Printf("Just s: %T\n", s)
t := sort.StringSlice(s)
fmt.Printf("Just s: %T\n", t)
fmt.Printf("This is a test %T\n", sort.StringSlice(s))
//fmt.Printf("This is a test %T\n" , sort.Sort(sort.StringSlice(s)))
fmt.Printf("This is a test %T\n", sort.Reverse(sort.StringSlice(s)))
i := sort.Reverse(sort.StringSlice(s))
fmt.Printf("This is a test reverse %T\n", i)
fmt.Println(i)
sort.Sort(i)
fmt.Println(s)
}
<file_sep>/functions/booleanExpressions.go
package main
import "fmt"
func main() {
if true {
fmt.Println("Hola")
}
if !true {
fmt.Println("<NAME>")
}
}
<file_sep>/goExamples/interfaceSimpleUnderstanding.go
package main
import "fmt"
func main() {
d := Dog{}
var a animal
a = d
a.Speak()
}
type animal interface {
Speak()
}
type Dog struct {
}
func (d Dog) Speak() {
fmt.Println("Woof")
}
type human struct {
}
func (h human) Speak() {
fmt.Println("Sing")
}
<file_sep>/functions/deferExample.go
package main
import "fmt"
func world() {
fmt.Println("world !")
}
func hello() {
fmt.Print("Hello ")
}
func main() {
defer world() //Defer key world will make the function world to execute just before the main exits.
hello() //Hello function runs first and then world because defer key world is there
}
<file_sep>/goExamples/interfaceUnderstanding4.go
package main
import "fmt"
func main() {
animals := []animal{new(Dog), &human{}} //Or instead of new you can use &Dog{} you are passing a pointer because the Speak of Dog has a
// Receiver of Pointer type. But even though human is accepting value you can pass a pointer to it. Both will work if the receiver is
// Receive by value. If the receiver is pointer then only address should be passed.
for _, x := range animals {
x.Speak()
}
}
type animal interface {
Speak()
}
type Dog struct {
}
func (d *Dog) Speak() {
fmt.Println("Woof")
}
type human struct {
}
func (h human) Speak() {
fmt.Println("Sing")
}
<file_sep>/Datastrucures/structExample.go
package main
import "fmt"
type person struct {
age int
fName string
lName string
}
func main() {
p1 := person{25, "D", "P"}
p2 := person{67, "J", "P"}
fmt.Println(p1.age, p1.fName, p1.lName)
fmt.Println(p2.age, p2.fName, p2.lName)
}
| 238aa338541241a32358fc96e7f66fcc3eb410ce | [
"Go"
]
| 89 | Go | dennisjohn13/goLeaning | d2ba224b85b9fed9b244636b8670ab6ed4e2b7d1 | e09f741b3f510ad2fe8d726d3e1aa84f77403380 |
refs/heads/main | <repo_name>khagerman/react-customhooks<file_sep>/src/hooks/useFlip.js
import React, { useState } from "react";
// const flipCard = () => {
// setIsFacingUp((isUp) => !isUp);
// };
const useFlip = () => {
const [state, setState] = useState(true);
const flipState = () => {
setState((state) => !state);
};
return [state, flipState];
};
export default useFlip;
<file_sep>/src/hooks/useAxios.js
import React, { useState } from "react";
import axios from "axios";
import uuid from "uuid";
const useAxios = (url) => {
const [state, setState] = useState([]);
const addCard = async (name) => {
let urlName = name ? `${url}/${name}` : url;
const response = await axios.get(urlName);
setState((state) => [...state, { ...response.data, id: uuid() }]);
console.log(state);
};
return [state, addCard];
};
export default useAxios;
// const [cards, setCards] = useState([]);
// const addCard = async () => {
// const response = await axios.get(
// "https://deckofcardsapi.com/api/deck/new/draw/"
// );
// setCards((cards) => [...cards, { ...response.data, id: uuid() }]);
// };
| 338a454b1ec5b39b0ab1f8b85768949c386f2579 | [
"JavaScript"
]
| 2 | JavaScript | khagerman/react-customhooks | 2ab9732d8491a8416d2ffe750b44c1a8770afeca | 809d11e668819c1ff5110ae4744d90e418913442 |
refs/heads/master | <repo_name>matthewstclaire/oo-email-parser-onl01-seng-ft-081720<file_sep>/lib/email_parser.rb
class EmailAddressParser
attr_accessor :csv_emails
def initialize (csv_emails)
@csv_emails = csv_emails
end
def parse
csv_emails.split.collect {|emails| emails.split /\,/}.flatten.uniq
end
end
| 8311c2074b178b028708314af63384a4fec5173e | [
"Ruby"
]
| 1 | Ruby | matthewstclaire/oo-email-parser-onl01-seng-ft-081720 | 5580c0b7e9cef5ae685f8c8ac70dd58b430da0b4 | 994b2140dcbc39d2ad007deef0da7fe96177bee6 |
refs/heads/master | <repo_name>Devin44G/node-api2-project<file_sep>/posts/posts-router.js
const express = require('express');
const Posts = require('../data/db.js');
const router = express.Router();
/******** POSTS ENDPOINTS ********/
router.get('/', (req, res) => {
// res.status(200).json({post: "here we are"});
Posts.find(req.query)
.then(post => {
res.status(200).json(post);
})
.catch(err => {
res.status(500).json({ error: "Error receiving post data" });
});
});
router.post('/', (req, res) => {
Posts.insert(req.body)
.then(post => {
res.status(201).json(post);
})
.catch(err => {
if(!req.body.title || !req.body.contents) {
res.status(400).json({ error: "Please provide title and contents for the post." });
} else {
res.status(500).json({ error: "There was an error while saving the post to the database." });
}
});
});
/******** POSTS ENDPOINT BY ID ********/
router.get('/:id', (req, res) => {
Posts.findById(req.params.id)
.then(post => {
if(post) {
res.status(200).json(post);
} else {
res.status(404).json({ error: "The post with the specified ID does not exist." });
}
})
.catch(err => {
res.status(500).json({ error: "The post information could not be retrieved." });
});
});
router.delete('/:id', (req, res) => {
Posts.remove(req.params.id)
.then(post => {
if(!post) {
res.status(404).json({ error: "The post with the specified ID does not exist." });
} else {
res.status(200).json({ message: "Post was deleted" });
}
})
.catch(err => {
res.status(500).json({ error: "The post could not be removed" });
})
});
router.put('/:id', (req, res) => {
Posts.update(req.params.id, req.body)
.then(post => {
if(post) {
res.status(200).json(post);
} else {
res.status(404).json({ error: "The post with the specified ID does not exist." });
}
})
.catch(err => {
res.status(500).json({ error: "Post information could not be retrieved . . ." });
});
});
/******** COMMENTS ENDPOINTS ********/
router.get('/:id/comments', (req, res) => {
Posts.findPostComments(req.params.id)
.then(post => {
if(post) {
res.status(200).json(post.comments);
} else {
res.status(404).json({ error: "The post with the specified ID does not exist." })
}
})
.catch(err => {
res.status(500).json({ error: "Error receiving comments data" })
});
});
router.post("/:id/comments", (req, res) => {
if (req.body.text.length === 0) {
res.status(400).json({ errorMessage: "Please provide text for the comment." });
} else {
Posts.insertComment(req.body)
.then(comment => {
if (comment) {
Posts.findCommentById(comment.id)
.then(comment => {
res.status(201).json(comment);
})
.catch(error => {
res.status(500).json({ error: "error retrieving data" });
});
} else {
res.status(404).json({
message: "The post with the specified ID does not exist."
});
}
})
.catch(error => {
console.log(error);
res.status(500).json({
error: "There was an error while saving the comment to the database"
});
});
}
});
module.exports = router;
| 1d2ac6d04d4f02c230abb78f7a110001813829d8 | [
"JavaScript"
]
| 1 | JavaScript | Devin44G/node-api2-project | 64848f7241ebb0a96221396339e4a9998830f39e | 94d71c4e1253e572ec15705ed190f3d1aeaba911 |
refs/heads/master | <file_sep>import React from "react";
export class EnterTask extends React.Component{
state = {
prompt:'',
validEnter: false
}
handlePrompt = (e) => {
this.setState({
prompt: e.currentTarget.value
})
}
handleAdd = (e) => {
const { prompt } = this.state
this.props.method({prompt});
}
handleClear = (e) => {
this.setState({
prompt: '',
})
}
render() {
return (
<div className="fragment-enter">
<div className="buffer">
<h4 className="enter-text">Enter your task</h4>
<input type="text" className="field" placeholder=" Here" value={this.state.prompt} onChange={this.handlePrompt}/>
<br/>
<input type="button" disabled={this.state.prompt.length ? false : true} onClick={this.handleAdd} className="button" value="Enter"/>
<input type="button" onClick={this.handleClear} className="button" value="Clear"/>
</div>
</div>
);
}
} | d9edfae5b9c49f1b3cce6a683582399a8058ad7a | [
"JavaScript"
]
| 1 | JavaScript | primal-csd1v/react-custom-webpack-task-app | 67be419d7cf22bf5bacf37e4de721502c7885677 | e860a4f12cf419cce1019d224581998dc3784cf8 |
refs/heads/master | <repo_name>CharmWang/restaurant_system<file_sep>/framework/libs/core/VIEW.class.php
<?php
/*
*author : wangkang
*time : 2016/12/1
*
*/
class VIEW{
public static $view;
public static function init($viewtype,$config){
self::$view=new $viewtype;
foreach($config as $key=>$value){
self::$view->$key=$value;
}
}
//以下两种方法都是对smarty类中的方法进行封装
public static function assign($data){
foreach($data as $key=>$value){
self::$view->assign($key,$value);
}
}
public static function display($template){
self::$view->display($template);
}
}
?><file_sep>/template_c/5d289c597d8d3d7b69315956447d513b9258cfbe_0.file.login.html.php
<?php
/* Smarty version 3.1.31-dev/34, created on 2017-03-14 10:34:24
from "D:\Apache24\htdocs\restaurant_system\tpl\index\login.html" */
/* @var Smarty_Internal_Template $_smarty_tpl */
if ($_smarty_tpl->_decodeProperties($_smarty_tpl, array (
'version' => '3.1.31-dev/34',
'unifunc' => 'content_58c756b0a85ab5_10391018',
'has_nocache_code' => false,
'file_dependency' =>
array (
'5d289c597d8d3d7b69315956447d513b9258cfbe' =>
array (
0 => 'D:\\Apache24\\htdocs\\restaurant_system\\tpl\\index\\login.html',
1 => 1489456473,
2 => 'file',
),
),
'includes' =>
array (
),
),false)) {
function content_58c756b0a85ab5_10391018 (Smarty_Internal_Template $_smarty_tpl) {
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>登陆</title>
<link href="http://127.0.0.1:8080/restaurant_system/tpl/image/resturant.png" rel="icon" />
<link href="http://127.0.0.1:8080/restaurant_system/tpl/css/general.css" type="text/css" rel="stylesheet" />
</head>
<body>
<div class="mid-part">
<div class="img">
<img src="http://127.0.0.1:8080/restaurant_system/tpl/image/banji.png" />
</div>
<span style="float:right; font-size:12px;"><a href="http://127.0.0.1:8080/restaurant_system/tpl/index/register.html">没有账户?点此注册</a></span>
<form method="post" action="http://127.0.0.1:8080/restaurant_system/index.php?controller=index&method=login" onSubmit="return checkForm()">
<span class="span">登录您的餐厅通行证</span><br />
<input type="text" id="username" name="username" placeholder="请输入用户名" onBlur="checkuname()"/>
<span id="userNameHint" ></span><br />
<input type="<PASSWORD>" id="password" name="password" placeholder="<PASSWORD>" />
<span id="passwordHint" ></span><br />
<input class="btn" type="submit" value="登 陆" name="submit"/>
</form>
</div>
</body>
</html>
<?php echo '<script'; ?>
type="text/javascript">
function checkForm(){
var username=document.getElementById("username").value;
var password=document.getElementById("password").value;
if(username==""){
// 判断用户名是否可用,后面跟着相应的提示
document.getElementById("userNameHint").innerHTML="用户名不能为空";
document.getElementById("userNameHint").style.color="#FF0000";
return false;
}else{
document.getElementById("userNameHint").innerHTML="";
}
if(password==""){
// 判断密码是否可用,后面跟着相应的提示
document.getElementById("passwordHint").innerHTML="密码不能为空";
document.getElementById("passwordHint").style.color="#FF0000";
return false;
}else{
document.getElementById("passwordHint").innerHTML="";
}
return true;
}
<?php echo '</script'; ?>
>
<?php }
}
<file_sep>/tpl/company/readme.txt
这个文件夹是专门针对公司介绍,也就是对餐厅的所有介绍,包括但不限于:
1.最新活动 -------->activity.html
2.联系我们 -------->contact.html
3.关于我们 -------->about.html
4.连锁加盟 -------->joinus.html
5.广告服务 -------->ad.html
ps:这个文件夹专门放这几个界面,之后也许会在继续增加<file_sep>/tpl/Readme.txt
admin:存放后台的视图文件夹
communal:存放公共的模板文件夹
company:存放关于公司(餐厅)的视图文件夹
css:存放样式的文件夹
image:存放图片的文件夹
index:存放前台首页界面的视图文件夹
js:存放.js的文件夹<file_sep>/template_c/7bc6dfc4958c106f58f0435d56b8890a537d9c71_0.file.joinus.html.php
<?php
/* Smarty version 3.1.31-dev/34, created on 2017-04-10 18:03:45
from "D:\Apache24\htdocs\restaurant_system\tpl\company\joinus.html" */
/* @var Smarty_Internal_Template $_smarty_tpl */
if ($_smarty_tpl->_decodeProperties($_smarty_tpl, array (
'version' => '3.1.31-dev/34',
'unifunc' => 'content_58eb58813f66a2_93918251',
'has_nocache_code' => false,
'file_dependency' =>
array (
'7bc6dfc4958c106f58f0435d56b8890a537d9c71' =>
array (
0 => 'D:\\Apache24\\htdocs\\restaurant_system\\tpl\\company\\joinus.html',
1 => 1491818618,
2 => 'file',
),
),
'includes' =>
array (
'file:tpl/communal/native.html' => 1,
),
),false)) {
function content_58eb58813f66a2_93918251 (Smarty_Internal_Template $_smarty_tpl) {
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>header</title>
<link href="http://127.0.0.1:8080/restaurant_system/tpl/image/resturant.png" rel="icon" />
<link rel="stylesheet" href="tpl/css/general.css" />
<link rel="stylesheet" href="tpl/css/bootstrap.min.css">
<?php echo '<script'; ?>
src="tpl/js/jquery.min.js"><?php echo '</script'; ?>
>
<?php echo '<script'; ?>
src="tpl/js/bootstrap.min.js"><?php echo '</script'; ?>
>
</head>
<body>
<!--this is for head-->
<div class="head">
<div class="setmarquee">
<marquee loop="-1" behavior="alternate" scrollamount="10" scrolldelay="5" onMouseOver="stop()" onMouseOut="start()"><font style="color:#666666; font-size:30px; font-family:Georgia, 'Times New Roman', Times, serif; ">不"2"餐厅</font></marquee>
</div>
</div>
<!--this is for native,all the same-->
<?php $_smarty_tpl->_subTemplateRender('file:tpl/communal/native.html', $_smarty_tpl->cache_id, $_smarty_tpl->compile_id, 0, $_smarty_tpl->cache_lifetime, array(), 0, false);
?>
<!--*********************************下面是关于公司的介绍*********************************-->
<div class="tab_box">
<!--这是左边导航栏的介绍,共用list-left-->
<div class="list-left">
<ul>
<li><span>> </span><a href="index.php?controller=index&method=company&action=activity">最新活动</a></li>
<li><span>> </span><a href="index.php?controller=index&method=company&action=contact">联系我们</a></li>
<li><span>> </span><a href="index.php?controller=index&method=company&action=about">关于我们</a></li>
<li><span>> </span><a href="#" style="color:#0058b8;font-weight:600;">连锁加盟</a></li>
<li><span>> </span><a href="index.php?controller=index&method=company&action=ad">广告服务</a></li>
</ul>
</div>
<!--这是右边具体的介绍-->
<div class="tab_box_right">
这里是加入我们
</div>
</div>
</body>
</html>
<?php }
}
<file_sep>/template_c/676798a1feef946f9bbe16e596661098945571af_0.file.cp_head.html.php
<?php
/* Smarty version 3.1.31-dev/34, created on 2017-03-06 14:55:57
from "D:\Apache24\htdocs\restaurant_system\tpl\communal\cp_head.html" */
/* @var Smarty_Internal_Template $_smarty_tpl */
if ($_smarty_tpl->_decodeProperties($_smarty_tpl, array (
'version' => '3.1.31-dev/34',
'unifunc' => 'content_58bd07fd5ec607_42003587',
'has_nocache_code' => false,
'file_dependency' =>
array (
'676798a1feef946f9bbe16e596661098945571af' =>
array (
0 => 'D:\\Apache24\\htdocs\\restaurant_system\\tpl\\communal\\cp_head.html',
1 => 1488783328,
2 => 'file',
),
),
'includes' =>
array (
),
),false)) {
function content_58bd07fd5ec607_42003587 (Smarty_Internal_Template $_smarty_tpl) {
?>
<!--this is for native 导航页-->
<nav class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="#">首页</a>
</div
><div>
<ul class="nav navbar-nav">
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
菜系
<b class="caret"></b>
</a>
<ul class="dropdown-menu">
<li class="divider"></li>
<li><a href="#">苏菜</a></li>
<li class="divider"></li>
<li><a href="#">闽菜</a></li>
<li class="divider"></li>
<li><a href="#">川菜</a></li>
<li class="divider"></li>
<li><a href="#">鲁菜</a></li>
<li class="divider"></li>
<li><a href="#">粤菜</a></li>
<li class="divider"></li>
<li><a href="#">湘菜</a></li>
<li class="divider"></li>
<li><a href="#">浙菜</a></li>
<li class="divider"></li>
<li><a href="#">徽菜</a></li>
<li class="divider"></li>
<li><a href="#">东北菜</a></li>
<li class="divider"></li>
<li><a href="#">京菜</a></li>
<li class="divider"></li>
<li><a href="#">清真菜</a></li>
<li class="divider"></li>
<li><a href="#">上海菜</a></li>
<li class="divider"></li>
<li><a href="#">湖北菜</a></li>
</ul>
</li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
美食天地
<b class="caret"></b>
</a>
<ul class="dropdown-menu">
<li class="divider"></li>
<li><a href="#">清蒸类</a></li>
<li class="divider"></li>
<li><a href="#">红烧类</a></li>
<li class="divider"></li>
<li><a href="#">海鲜类</a></li>
<li class="divider"></li>
<li><a href="#">卤菜类</a></li>
<li class="divider"></li>
<li><a href="#">凉菜类</a></li>
<li class="divider"></li>
<li><a href="#">干煸类</a></li>
<li class="divider"></li>
<li><a href="#">汤类</a></li>
</ul>
</li>
<li><a href="#">最新活动</a></li>
<li><a href="#">联系我们</a></li>
<li><a href="#">关于我们</a></li>
<li><a href="#">连锁加盟</a></li>
<li><a href="#">广告服务</a></li>
<li><a href="#">讨论区</a></li>
<li><a href="index.php?controller=index&method=selectOne">用户中心</a></li>
</ul>
</div>
</div>
</nav>
<?php }
}
<file_sep>/libs/Model/foodsModel.class.php
<?php
class foodsModel {
/*这个类是专门来处理所有和foods_db表有关的所有操作
*
* 以下是关于foods_db的操作
* 1.
* 2.管理员查询所有的菜品
*/
public $table="foods_db";
//查询放在点餐界面的图片
public function find_by_cuisines($cuisines,$count){
$sql='select * from '.$this->table.' where cuisines ="'.$cuisines.'" LIMIT '.($count*12).',12';
return DB::findAll($sql);
}
//逆序查询数据库中菜单的名字,主界面中第三部分
public function find_foodname(){
$sql='select * from '.$this->table.' order by Id DESC LIMIT 0,4 ';
return DB::findAll($sql);
}
//用户点击美食天地的时候,跳转到主界面,根据销量排序
public function order_by_number(){
$sql='select * from '.$this->table.' order by foodNumber DESC LIMIT 0,12 ';
return DB::findAll($sql);
}
//用户点击搜索按钮,按照输入的内容来匹配,这里主要是搜索菜单表
public function find_all_result($food_name){
$sql='select * from '.$this->table.' where foodName like "%'.$food_name.'%"';
return DB::findAll($sql);
}
public function get_count_food(){
$sql='select * from '.$this->table.' LIMIT 0,12';
return DB::findAll($sql);
}
//用户点击支付以后,付款成功,需要对foods_db表中的foodNumber进行加一操作
public function add_one_time($foodName){
$sql='update '.$this->table.' set foodNumber = foodNumber+1 where foodName ="'.$foodName.'"';
return DB::query($sql);
}
//**********************************************************************************************
//*******************************************以下是管理员的操作************************************
//管理员得到所有foods_db相应的信息
public function get_count_foods(){
$sql='select * from '.$this->table.' order by Id DESC';
return DB::findAll($sql);
}
//管理员删除指定id的菜品
public function delete_foods($id){
$where=" Id = ".$id;
return DB::del($this->table,$where);
}
//管理员点击查询或者修改菜品的信息,通过id返回这个菜品的信息
public function change_foods($id){
$sql='select * from '.$this->table.' where Id='.$id;
return DB::findOne($sql);
}
//管理员确认修改这个菜品
public function save_foods($arr,$id){
$where=" Id = ".$id;
return DB::update($this->table,$arr,$where);
}
//管理员添加菜品
public function add_foods($array){
return DB::insert($this->table,$array);
}
}
?><file_sep>/template_c/e962611b808aaba5108a6781ad106bb215e4e7d7_0.file.user_consume.html.php
<?php
/* Smarty version 3.1.31-dev/34, created on 2017-05-18 23:37:58
from "D:\Apache24\htdocs\restaurant_system\tpl\index\user_consume.html" */
/* @var Smarty_Internal_Template $_smarty_tpl */
if ($_smarty_tpl->_decodeProperties($_smarty_tpl, array (
'version' => '3.1.31-dev/34',
'unifunc' => 'content_591dbfd6f10170_26262748',
'has_nocache_code' => false,
'file_dependency' =>
array (
'e962611b808aaba5108a6781ad106bb215e4e7d7' =>
array (
0 => 'D:\\Apache24\\htdocs\\restaurant_system\\tpl\\index\\user_consume.html',
1 => 1495121869,
2 => 'file',
),
),
'includes' =>
array (
'file:tpl/communal/native.html' => 1,
),
),false)) {
function content_591dbfd6f10170_26262748 (Smarty_Internal_Template $_smarty_tpl) {
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>用户消费信息</title>
<link href="http://127.0.0.1:8080/restaurant_system/tpl/image/resturant.png" rel="icon" />
<link rel="stylesheet" href="tpl/css/general.css" />
<link rel="stylesheet" href="tpl/css/bootstrap.min.css">
<?php echo '<script'; ?>
src="tpl/js/jquery.min.js"><?php echo '</script'; ?>
>
<?php echo '<script'; ?>
src="tpl/js/bootstrap.min.js"><?php echo '</script'; ?>
>
</head>
<body>
<!--this is for head-->
<div class="head">
<div class="setmarquee">
<marquee loop="-1" behavior="alternate" scrollamount="10" scrolldelay="5" onMouseOver="stop()" onMouseOut="start()"><font style="color:#666666; font-size:30px; font-family:Georgia, 'Times New Roman', Times, serif; ">不"2"餐厅</font></marquee>
</div>
<div class="setuser">
<a href="#"><?php echo $_smarty_tpl->tpl_vars['username']->value;?>
</a>
<a>|</a>
<a href="index.php?controller=index&method=logout">退出</a>
</div>
</div>
<!--this is for native,all the same-->
<?php $_smarty_tpl->_subTemplateRender('file:tpl/communal/native.html', $_smarty_tpl->cache_id, $_smarty_tpl->compile_id, 0, $_smarty_tpl->cache_lifetime, array(), 0, false);
?>
<!--这是用户中心的左半边的代码-->
<div class="list-left">
<ul>
<!--这里两个链接都是先传给index控制器,参数是用户名,然后返回到相应的界面-->
<li><span>> </span><a href="index.php?controller=index&method=identify">我的信息</a></li>
<li><span>> </span><a href="#" style="color:#0058b8;font-weight:600;">消费记录</a></li>
<li><span>> </span><a href="index.php?controller=index&method=find_shopping">我的购物车</a></li>
</ul>
</div>
<div class="list-right">
<span>消费记录</span>
<div class="div-hr"></div>
<table>
<tr>
<td class="td">菜单 </td>
<td class="td">消费总额</td>
<td class="td">消费日期</td>
<td class="td">消费时间</td>
<td class="td">选项</td>
</tr>
<?php
$__section_index_0_saved = isset($_smarty_tpl->tpl_vars['__smarty_section_index']) ? $_smarty_tpl->tpl_vars['__smarty_section_index'] : false;
$__section_index_0_loop = (is_array(@$_loop=$_smarty_tpl->tpl_vars['consume_record']->value) ? count($_loop) : max(0, (int) $_loop));
$__section_index_0_total = $__section_index_0_loop;
$_smarty_tpl->tpl_vars['__smarty_section_index'] = new Smarty_Variable(array());
$__section_index_0_show = (bool) true ? $__section_index_0_total != 0 : false;
if ($__section_index_0_show) {
for ($__section_index_0_iteration = 1, $_smarty_tpl->tpl_vars['__smarty_section_index']->value['index'] = 0; $__section_index_0_iteration <= $__section_index_0_total; $__section_index_0_iteration++, $_smarty_tpl->tpl_vars['__smarty_section_index']->value['index']++){
?>
<tr>
<td class="td" style="font-size:9px"><?php echo $_smarty_tpl->tpl_vars['consume_record']->value[(isset($_smarty_tpl->tpl_vars['__smarty_section_index']->value['index']) ? $_smarty_tpl->tpl_vars['__smarty_section_index']->value['index'] : null)]['foodNames'];?>
</td>
<td class="td"><?php echo $_smarty_tpl->tpl_vars['consume_record']->value[(isset($_smarty_tpl->tpl_vars['__smarty_section_index']->value['index']) ? $_smarty_tpl->tpl_vars['__smarty_section_index']->value['index'] : null)]['acount'];?>
</td>
<td class="td"><?php echo $_smarty_tpl->tpl_vars['consume_record']->value[(isset($_smarty_tpl->tpl_vars['__smarty_section_index']->value['index']) ? $_smarty_tpl->tpl_vars['__smarty_section_index']->value['index'] : null)]['date'];?>
</td>
<td class="td"><?php echo $_smarty_tpl->tpl_vars['consume_record']->value[(isset($_smarty_tpl->tpl_vars['__smarty_section_index']->value['index']) ? $_smarty_tpl->tpl_vars['__smarty_section_index']->value['index'] : null)]['time'];?>
</td>
<td class="td"><a href="index.php?controller=index&method=delete_consume_record&Id=<?php echo $_smarty_tpl->tpl_vars['consume_record']->value[(isset($_smarty_tpl->tpl_vars['__smarty_section_index']->value['index']) ? $_smarty_tpl->tpl_vars['__smarty_section_index']->value['index'] : null)]['Id'];?>
">删除</a></td>
</tr>
<?php
}
}
if ($__section_index_0_saved) {
$_smarty_tpl->tpl_vars['__smarty_section_index'] = $__section_index_0_saved;
}
?>
</table>
</div>
</body>
</html>
<?php }
}
<file_sep>/framework/function/factory_mvc.class.php
<?php
class Factory_mvc{
/**********************************controller模型***************************************************/
//给controller模型定义一个函数,传递name和method(统一化)
function C($name,$method){
require_once('/libs/Controller/'.$name.'Controller.class.php');
//eval函数的作用是将括号里的内容执行一遍
eval('$obj=new '.$name.'Controller();$obj->'.$method.'(); ');
}
/***********************************model模型***************************************************/
//给model模型定义一个函数,方便调用(模型中的方法往往带有参数,所以模型函数中没有方法参数)
function M($name){
require_once('/libs/Model/'.$name.'Model.class.php');
eval('$obj=new '.$name.'Model();');
//eval函数调用比较简单,但是不安全,可以用其他的语句来代替
/*
$model=$name.'Model()';
$obj=new $model;
return obj;
*/
return $obj;
}
/***********************************view模型***************************************************/
//给view模型定义一个函数
function V($name){
require_once('/libs/View/'.$name.'View.class.php');
eval('$obj=new '.$name.'View();');
return $obj;
}
/***********************************函数用来对字符进行转义***********************************/
//检查字符的合法性,对一些非法字符进行转义
function daddslashes($str){
//addslashes:对单引号进行转义,get_magic_quotes_gpc:判断魔法符号是否打开(是否需要进行转义)
return (!get_magic_quotes_gpc()?addslashes($str):$str);
}
}
?><file_sep>/config.php
<?php
/*这是一个配置文件*/
$config=array(
'viewconfig'=>array('left_delimiter'=>'{' ,'right_delimiter'=>'}' ,'template_dir'=>'tpl','compile_dir'=>'template_c'),
'dbconfig' =>array('dbhost'=>'localhost','dbuser'=>'root','dbpsw'=>'wangkang','dbname'=>'restaurant_db','dbcharset'=>'utf-8')
);
?><file_sep>/template_c/bffb7eb0e2003e02573770a1c173ab89e6616469_0.file.main.html.php
<?php
/* Smarty version 3.1.31-dev/34, created on 2017-05-19 14:47:42
from "D:\Apache24\htdocs\restaurant_system\tpl\index\main.html" */
/* @var Smarty_Internal_Template $_smarty_tpl */
if ($_smarty_tpl->_decodeProperties($_smarty_tpl, array (
'version' => '3.1.31-dev/34',
'unifunc' => 'content_591e950e520773_72683857',
'has_nocache_code' => false,
'file_dependency' =>
array (
'bffb7eb0e2003e02573770a1c173ab89e6616469' =>
array (
0 => 'D:\\Apache24\\htdocs\\restaurant_system\\tpl\\index\\main.html',
1 => 1495176030,
2 => 'file',
),
),
'includes' =>
array (
'file:tpl/communal/native.html' => 1,
'file:tpl/communal/footer.html' => 1,
),
),false)) {
function content_591e950e520773_72683857 (Smarty_Internal_Template $_smarty_tpl) {
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>header</title>
<link href="tpl/image/resturant.png" rel="icon" />
<link rel="stylesheet" href="tpl/css/general.css" />
<link rel="stylesheet" href="tpl/css/bootstrap.min.css">
<?php echo '<script'; ?>
src="tpl/js/jquery.min.js"><?php echo '</script'; ?>
>
<?php echo '<script'; ?>
src="tpl/js/bootstrap.min.js"><?php echo '</script'; ?>
>
</head>
<style>
* { padding:0; margin:0;}
body { height:100%; overflow:hidden; font-size:14px; line-height:2; position:relative;}
html { height:100%; overflow:hidden;}
.fixed { position:absolute; bottom:10px; right:28px; width:148px; height:200px; background:#ffffff; border:1px solid #075fb6; display:none;overflow:scroll;}
.wrapper { height:100%; overflow:scroll; overflow-x:hidden;}
.tdf{ padding-left:2px; color:#075fb6;}
.tds{ padding-left:10px;color:#075fb6;}
</style>
<body>
<!--这里是浮动窗口-->
<div class="fixed" id="fixed">
<table style="margin-left:2; margin-top:1px;" id="table">
</table>
<a onclick="add_shopping();">加入购物车 </a><a onclick="pay_shopping();">付款</a>
</div>
<div class="wrapper">
<!--this is for head , not be all the same-->
<div class="head">
<div class="setmarquee">
<marquee loop="-1" behavior="alternate" scrollamount="10" scrolldelay="5" onMouseOver="stop()" onMouseOut="start()" ><font style="color:#666666; font-size:30px; font-family:Georgia, 'Times New Roman', Times, serif; ">不"2"餐厅</font></marquee> <br />
</div>
<div class="setuser">
<a href="#"><?php echo $_smarty_tpl->tpl_vars['user']->value['username'];?>
</a>
<a>|</a>
<a href="index.php?controller=index&method=logout">退出</a>
</div>
</div>
<!--this is for native,all the same-->
<?php $_smarty_tpl->_subTemplateRender('file:tpl/communal/native.html', $_smarty_tpl->cache_id, $_smarty_tpl->compile_id, 0, $_smarty_tpl->cache_lifetime, array(), 0, false);
?>
<!--这里是餐厅点餐的主界面-->
<div class="container">
<div class="row">
<!--这是左边的导航栏-->
<div class="col-xs-3" id="myScrollspy">
<ul class="nav nav-tabs nav-stacked" data-spy="affix" data-offset-top="125">
<li id="1"><a href="index.php?controller=index&method=getCuisines&action=1">川菜</a></li>
<li id="2"><a href="index.php?controller=index&method=getCuisines&action=2">鲁菜</a></li>
<li id="3"><a href="index.php?controller=index&method=getCuisines&action=3">湘菜</a></li>
<li id="4"><a href="index.php?controller=index&method=getCuisines&action=4">浙菜</a></li>
<li id="5"><a href="index.php?controller=index&method=getCuisines&action=5">东北菜</a></li>
<li id="6"><a href="index.php?controller=index&method=getCuisines&action=6">京菜</a></li>
<li id="7"><a href="index.php?controller=index&method=getCuisines&action=7">上海菜</a></li>
<li id="7"><a href="index.php?controller=index&method=getCuisines&action=8">其他菜系</a></li>
</ul>
</div>
<!--这里是右边的点餐界面-->
<div class="col-xs-8">
<div class="row">
<?php
$__section_index_0_saved = isset($_smarty_tpl->tpl_vars['__smarty_section_index']) ? $_smarty_tpl->tpl_vars['__smarty_section_index'] : false;
$__section_index_0_loop = (is_array(@$_loop=$_smarty_tpl->tpl_vars['foods']->value) ? count($_loop) : max(0, (int) $_loop));
$__section_index_0_total = $__section_index_0_loop;
$_smarty_tpl->tpl_vars['__smarty_section_index'] = new Smarty_Variable(array());
$__section_index_0_show = (bool) true ? $__section_index_0_total != 0 : false;
if ($__section_index_0_show) {
for ($__section_index_0_iteration = 1, $_smarty_tpl->tpl_vars['__smarty_section_index']->value['index'] = 0; $__section_index_0_iteration <= $__section_index_0_total; $__section_index_0_iteration++, $_smarty_tpl->tpl_vars['__smarty_section_index']->value['index']++){
?>
<!-- 一个界面中放12张图片,因此在这个循环中,到11结束 -->
<div class="col-xs-3">
<div class="thumbnail">
<img src="tpl/image/food/<?php echo $_smarty_tpl->tpl_vars['foods']->value[(isset($_smarty_tpl->tpl_vars['__smarty_section_index']->value['index']) ? $_smarty_tpl->tpl_vars['__smarty_section_index']->value['index'] : null)]['foodUrl'];?>
"
alt="通用的占位符缩略图">
<div class="caption">
<a style="color:#003045; font-size:5px" href="index.php?controller=index&method=detail_foods&id=<?php echo $_smarty_tpl->tpl_vars['foods']->value[(isset($_smarty_tpl->tpl_vars['__smarty_section_index']->value['index']) ? $_smarty_tpl->tpl_vars['__smarty_section_index']->value['index'] : null)]['Id'];?>
"><?php echo $_smarty_tpl->tpl_vars['foods']->value[(isset($_smarty_tpl->tpl_vars['__smarty_section_index']->value['index']) ? $_smarty_tpl->tpl_vars['__smarty_section_index']->value['index'] : null)]['foodName'];?>
</a>
<a style="color:#003045"><?php echo $_smarty_tpl->tpl_vars['foods']->value[(isset($_smarty_tpl->tpl_vars['__smarty_section_index']->value['index']) ? $_smarty_tpl->tpl_vars['__smarty_section_index']->value['index'] : null)]['foodMoney'];?>
</a>
<a onclick="addFood('<?php echo $_smarty_tpl->tpl_vars['foods']->value[(isset($_smarty_tpl->tpl_vars['__smarty_section_index']->value['index']) ? $_smarty_tpl->tpl_vars['__smarty_section_index']->value['index'] : null)]['foodName'];?>
',<?php echo $_smarty_tpl->tpl_vars['foods']->value[(isset($_smarty_tpl->tpl_vars['__smarty_section_index']->value['index']) ? $_smarty_tpl->tpl_vars['__smarty_section_index']->value['index'] : null)]['foodMoney'];?>
);" >
<img src="tpl/image/add.png"
alt="通用的占位符缩略图" style="display:inline">
</a>
<a href="#">
<img src="tpl/image/sub.png"
alt="通用的占位符缩略图" style="display:inline">
</a>
</div>
</div>
</div>
<?php
}
}
if ($__section_index_0_saved) {
$_smarty_tpl->tpl_vars['__smarty_section_index'] = $__section_index_0_saved;
}
?>
</div>
<!--这里是分页功能-->
<div class="row">
<div class="col-xs-3"></div>
<div class="col-xs-5">
<ul class="pagination">
<li><a href="#">«</a></li>
<li><a href="#">1</a></li>
<li><a href="#">2</a></li>
<li><a href="#">3</a></li>
<li><a href="#">4</a></li>
<li><a href="#">5</a></li>
<li><a href="#">»</a></li>
</ul>
</div>
</div>
</div>
<!--右边的点餐界面结束-->
</div>
</div>
<!--这里是页脚部分-->
<?php $_smarty_tpl->_subTemplateRender('file:tpl/communal/footer.html', $_smarty_tpl->cache_id, $_smarty_tpl->compile_id, 0, $_smarty_tpl->cache_lifetime, array(), 0, false);
?>
</div>
</body>
</html>
<?php echo '<script'; ?>
type="text/javascript">
var price_account=0;
var foods="";
function addFood(name,price){
//更改display属性
$("#fixed").css('display','block');
//price_account数据改变
price_account+=price;
foods=name+","+foods;
//将foodName和price加入到购物车中
$("#table").after("<tr><td class='tdf'>"+name+"</td><td class='tds'>"+price+"</td><td class='tds'>1</td></tr>");
}
function add_shopping(){
window.location.href='index.php?controller=index&method=add_shopping&foodname='+foods+'&account='+price_account;
}
function pay_shopping(){
window.location.href='index.php?controller=index&method=direct_pay&foodname='+foods+'&account='+price_account;
}
<?php echo '</script'; ?>
><?php }
}
<file_sep>/framework/readme.txt
这是自己做的一个微型框架:<file_sep>/tpl/admin/readme.txt
pay attention to it!
这是专门负责后台的界面的文件夹!
包括:
1.查看、删除用户
2.查看并删除交易记录
3.查看、添加、删除菜单
4.发布公告
5.热点消息的发布修改
6.美食的做法
ps:这些统一由admin去添加,普通用户无法进入
********************************************************************************
各个文件的作用:
1.index.html:后台界面的首页
2.leftmenu.html:后台界面首页的左半部分
3.login.html:后台的登录界面<file_sep>/libs/Model/userModel.class.php
<?php
/*
这个类的功能如下:
1.进行用户名和密码的核对
2.判断用户名是否存在
3.用户查询和删除自己的消费信息
4.用户修改自己的信息
5.用户根据菜系和烹饪方式来查询相应的菜单
6.
*/
class userModel{
//用户登录的全局变量
private $user="";
//构造方法,判断session是否有值
function __construct(){
if(isset($_SESSION['user'])&&!empty($_SESSION['user'])){
//当session['user']中有值的时候,保存值
$this->user=$_SESSION['user'];
}
}
//返回user中的值
function getuser(){
return $this->user;
}
//*************************************************************************************************************
//********************************************1、2登录,验证用户名是否存在以及注册操作*****************************
//核对用户名和密码是否匹配
public function check_user($username,$password){
$indexobj=M('index');
return $indexobj->check_by_uname_pwd($username,$password);
}
//验证注册时,用户名是否已经存在了
public function check_uname_exist($username){
$userobj=M('index');
return $userobj->check_uname_exist($username);
}
//注册用户---->增加一个用户
public function add_one_user($username,$password,$phoneNumber,$email){
$userobj=M('index');
//将数据拼装成一维数组的形式
$userObject=array('username'=>$username,'password'=>$<PASSWORD>,'phoneNumber'=>$phoneNumber,'email'=>$email);
return $userobj->add_one_user($userObject);
}
//*************************************************************************************************************
//*************************************************************************************************************
//*******************************************3、用户查看和删除消费情况以及修改基本信息**************************************
public function find_consume_record($username){
//通过用户名来查询其消费记录,用户名通过session或者$this->user来取得
$userobj=M('consume');
return $userobj->find_consume_record($username);
}
public function delete_consume_record($id){
//删除消费记录
$userobj=M('consume');
return $userobj->delete_consume_record($id);
}
public function change_username($username,$username2){
//更改用户名,第一个参数是原来的用户名,第二个参数是更改后的用户名
$userobj=M('index');
$userObject=array('username'=>$username2);
$where=' username = "'.$username.'"';
return $userobj->change_username($userObject,$where);
}
//*************************************************************************************************************
//********************************************5.用户根据菜系来查询相应的菜单*************************************
public function find_by_cuisines($cuisines,$count=0){
$userobj=M('foods');
return $userobj->find_by_cuisines($cuisines,$count);
}
//******************************************************************************************************
}
?><file_sep>/framework/libs/core/DB.class.php
<?php
/*
*author : wangkang
*time : 2016/12/1
*主要是对mysql操作类进行一下封装
*
*/
class DB{//类名在php里面是全局变量 ,使用DB::属性 进行调用,比较方便
//保存实例化以后的对象
public static $db;
/*
*@param : $dbtype string 传递的是哪种类型的数据库
*@param : $config array 传递的是关于数据库的所有配置信息以及视图引擎的配置信息
*对数据库进行初始化操作,连接数据库
*/
public static function init($dbtype,$config){
self::$db=new $dbtype;
self::$db->connect($config);
}
/*
*@param : $sql string 传递一个sql语句
*以下都是类似,和mysql类里面的方法一一对应
*/
public static function query($sql){
return self::$db->query($sql);
}
public static function findAll($sql){
$query=self::$db->query($sql);
return self::$db->findAll($query);
}
public static function findOne($sql){
$query=self::$db->query($sql);
return self::$db->findOne($query);
}
public static function findResult($sql){
$query=self::$db->query($sql);
return self::$db->findResult($query);
}
public static function insert($table,$arr){
return self::$db->insert($table,$arr);
}
public static function update($table,$arr,$where){
return self::$db->update($table,$arr,$where);
}
public static function del($table,$where){
return self::$db->del($table,$where);
}
}
?><file_sep>/README.txt
****************************************
author : 汪康
time : 2017.02.24
****************************************
framework:微型框架
libs:MVC模式架构包
template_c:存储的临时模板文件
tpl:存储视图文件
admin.php:后台入口文件
config.php:全局的配置文件,包括smarty配置文件和数据库的配置文件
index.php:前台入口文件
<file_sep>/template_c/f1b4a9bf805e0bb2a87d6dbfec4d39ce8ebb83b8_0.file.header.html.php
<?php
/* Smarty version 3.1.31-dev/34, created on 2016-12-09 20:34:48
from "D:\Apache24\htdocs\restaurant_system\tpl\communal\header.html" */
/* @var Smarty_Internal_Template $_smarty_tpl */
if ($_smarty_tpl->_decodeProperties($_smarty_tpl, array (
'version' => '3.1.31-dev/34',
'unifunc' => 'content_584aa4e8f07810_16391465',
'has_nocache_code' => false,
'file_dependency' =>
array (
'f1b4a9bf805e0bb2a87d6dbfec4d39ce8ebb83b8' =>
array (
0 => 'D:\\Apache24\\htdocs\\restaurant_system\\tpl\\communal\\header.html',
1 => 1481273667,
2 => 'file',
),
),
'includes' =>
array (
),
),false)) {
function content_584aa4e8f07810_16391465 (Smarty_Internal_Template $_smarty_tpl) {
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>公司首页</title>
<link rel="stylesheet" href="http://cdn.static.runoob.com/libs/bootstrap/3.3.7/css/bootstrap.min.css">
<?php echo '<script'; ?>
src="http://cdn.static.runoob.com/libs/jquery/2.1.1/jquery.min.js"><?php echo '</script'; ?>
>
<?php echo '<script'; ?>
src="http://cdn.static.runoob.com/libs/bootstrap/3.3.7/js/bootstrap.min.js"><?php echo '</script'; ?>
>
</head>
<body>
<div >
<marquee loop="-1" behavior="alternate" scrollamount="10" scrolldelay="5" onMouseOver="stop()" onMouseOut="start()"><font style="color:#666666; font-size:30px; font-family:Georgia, 'Times New Roman', Times, serif; ">不"2"餐厅</font></marquee><br />
</div>
<nav class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="#">首页</a>
</div
><div>
<ul class="nav navbar-nav">
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
菜系
<b class="caret"></b>
</a>
<ul class="dropdown-menu">
<li class="divider"></li>
<li><a href="#">川菜</a></li>
<li class="divider"></li>
<li><a href="#">湘菜</a></li>
<li class="divider"></li>
<li><a href="#">粤菜</a></li>
<li class="divider"></li>
<li><a href="#">上海菜</a></li>
<li class="divider"></li>
<li><a href="#">湖北菜</a></li>
</ul>
</li>
<li><a href="#">美食天地</a></li>
<li><a href="#">联系我们</a></li>
<li><a href="#">联系我们</a></li>
<li><a href="#">关于我们</a></li>
<li><a href="#">连锁加盟</a></li>
<li><a href="#">联系我们</a></li>
<li><a href="#">讨论区</a></li>
<li><a href="#">用户中心</a></li>
</ul>
</div>
</div>
</nav>
</body>
</html><?php }
}
<file_sep>/framework/include.list.php
<?php
//这是所有的文件清单
$paths= array(
'function/function.php',
'libs/core/DB.class.php',
'libs/core/VIEW.class.php',
'libs/db/mysql.class.php',
'libs/view/Smarty/Smarty.class.php');
?><file_sep>/template_c/0f0de829c0bfc9aed60279f4f9235a1d20710cf2_0.file.detail_notice.html.php
<?php
/* Smarty version 3.1.31-dev/34, created on 2017-05-25 10:12:30
from "D:\Apache24\htdocs\restaurant_system\tpl\admin\detail_notice.html" */
/* @var Smarty_Internal_Template $_smarty_tpl */
if ($_smarty_tpl->_decodeProperties($_smarty_tpl, array (
'version' => '3.1.31-dev/34',
'unifunc' => 'content_59263d8e11ef41_62875502',
'has_nocache_code' => false,
'file_dependency' =>
array (
'0f0de829c0bfc9aed60279f4f9235a1d20710cf2' =>
array (
0 => 'D:\\Apache24\\htdocs\\restaurant_system\\tpl\\admin\\detail_notice.html',
1 => 1495653101,
2 => 'file',
),
),
'includes' =>
array (
'file:admin/leftmenu.html' => 1,
),
),false)) {
function content_59263d8e11ef41_62875502 (Smarty_Internal_Template $_smarty_tpl) {
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8"/>
<title>后台管理中心</title>
<link rel="stylesheet" href="tpl/css/layout.css" type="text/css" media="screen" />
<link rel="stylesheet" href="tpl/css/general.css" type="text/css" media="screen" />
<?php echo '<script'; ?>
src="tpl/js/jquery.min.js" type="text/javascript"><?php echo '</script'; ?>
>
<?php echo '<script'; ?>
src="tpl/js/hideshow.js" type="text/javascript"><?php echo '</script'; ?>
>
<?php echo '<script'; ?>
src="tpl/js/jquery.tablesorter.min.js" type="text/javascript"><?php echo '</script'; ?>
>
<?php echo '<script'; ?>
type="text/javascript" src="tpl/js/jquery.equalHeight.js"><?php echo '</script'; ?>
>
<?php echo '<script'; ?>
type="text/javascript">
$(document).ready(function()
{
$(".tablesorter").tablesorter();
}
);
$(document).ready(function() {
//When page loads...
$(".tab_content").hide(); //Hide all content
$("ul.tabs li:first").addClass("active").show(); //Activate first tab
$(".tab_content:first").show(); //Show first tab content
//On Click Event
$("ul.tabs li").click(function() {
$("ul.tabs li").removeClass("active"); //Remove any "active" class
$(this).addClass("active"); //Add "active" class to selected tab
$(".tab_content").hide(); //Hide all tab content
var activeTab = $(this).find("a").attr("href"); //Find the href attribute value to identify the active tab + content
$(activeTab).fadeIn(); //Fade in the active ID content
return false;
});
$("#file2").click(function(){
$('#file3').click();
if($('#file3').val()!=null){
var arr=$('#file3').val().split('\\');
$('#file1').attr('value',arr[2]);
}
});
});
<?php echo '</script'; ?>
>
<?php echo '<script'; ?>
type="text/javascript">
$(function(){
$('.column').equalHeight();
});
<?php echo '</script'; ?>
>
</head>
<body>
<header id="header">
<hgroup>
<h1 class="site_title"><a href="#">后台管理面板</a></h1>
<h2 class="section_title"></h2><div class="btn_view_site"><a href="index.php">查看网站</a></div>
</hgroup>
</header> <!-- end of header bar -->
<section id="secondary_bar">
<div class="user">
<p><?php echo $_smarty_tpl->tpl_vars['username']->value;?>
</p>
<!-- <a class="logout_user" href="#" title="Logout">Logout</a> -->
</div>
<div class="breadcrumbs_container">
<article class="breadcrumbs"><a href="admin.php?controller=admin">后台管理中心</a> <div class="breadcrumb_divider"></div> <a class="current">通告内容</a></article>
</div>
</section><!-- end of secondary bar -->
<?php $_smarty_tpl->_subTemplateRender('file:admin/leftmenu.html', $_smarty_tpl->cache_id, $_smarty_tpl->compile_id, 0, $_smarty_tpl->cache_lifetime, array(), 0, false);
?>
<section id="main" class="column">
<div style="text-align:center; margin-top:20px;">
<table style="width:600px;margin:0px auto;">
<caption style="text-align:center; background-color:#F9F9F9;color:#0033CC;">
<?php echo $_smarty_tpl->tpl_vars['notice']->value['title'];?>
</caption>
<tr style="visibility:hidden">
<td>1</td>
</tr>
<tr style="text-align:center;background-color:#F9F9F9; color:#0033CC;">
<td>发布人:<?php echo $_smarty_tpl->tpl_vars['notice']->value['announcer'];?>
</td>
<td style="text-align:right;">时间:<?php echo $_smarty_tpl->tpl_vars['notice']->value['date'];?>
<?php echo $_smarty_tpl->tpl_vars['notice']->value['time'];?>
</td>
</tr>
<tr style="visibility:hidden">
<td>2</td>
</tr>
<tr style="height:400px; border:#0000CC solid 1px;">
<td colspan="2" valign="top" style="text-align:center;"><?php echo $_smarty_tpl->tpl_vars['notice']->value['context'];?>
</td>
</tr>
</table>
</div>
<div class="spacer"></div>
</section>
</body>
</html><?php }
}
<file_sep>/template_c/595c4b6673f439870784670c2a63a986e3a8d520_0.file.leftmenu.html.php
<?php
/* Smarty version 3.1.31-dev/34, created on 2017-05-24 00:09:08
from "D:\Apache24\htdocs\restaurant_system\tpl\admin\leftmenu.html" */
/* @var Smarty_Internal_Template $_smarty_tpl */
if ($_smarty_tpl->_decodeProperties($_smarty_tpl, array (
'version' => '3.1.31-dev/34',
'unifunc' => 'content_59245ea45fe0a3_87965563',
'has_nocache_code' => false,
'file_dependency' =>
array (
'595c4b6673f439870784670c2a63a986e3a8d520' =>
array (
0 => 'D:\\Apache24\\htdocs\\restaurant_system\\tpl\\admin\\leftmenu.html',
1 => 1495555170,
2 => 'file',
),
),
'includes' =>
array (
),
),false)) {
function content_59245ea45fe0a3_87965563 (Smarty_Internal_Template $_smarty_tpl) {
?>
<aside id="sidebar" class="column">
<h3>用户管理</h3>
<ul class="toggle">
<li class="icn_categories"><a href="admin.php?controller=admin&method=see_users">查看用户</a></li>
</ul>
<h3>交易记录</h3>
<ul class="toggle">
<li class="icn_categories"><a href="admin.php?controller=admin&method=see_consume">查看交易记录</a></li>
</ul>
<h3>菜品管理</h3>
<ul class="toggle">
<li class="icn_categories"><a href="admin.php?controller=admin&method=see_foods">查看菜单</a></li>
<li class="icn_categories"><a href="admin.php?controller=admin&method=add_foods">添加菜品</a></li>
</ul>
<h3>通知管理</h3>
<ul class="toggle">
<li class="icn_new_article"><a href="admin.php?controller=admin&method=see_notice">公告管理</a></li>
<!--<li class="icn_new_article"><a href="#">关注热点</a></li>-->
</ul>
<h3>管理员管理</h3>
<ul class="toggle">
<li class="icn_jump_back"><a href="admin.php?controller=admin&method=logout">退出登录</a></li>
</ul>
<footer>
</footer>
</aside><!-- end of sidebar --><?php }
}
<file_sep>/template_c/9c4ad191c4a5bfa07c3b62e03d3498810aaab5d2_0.file.native.html.php
<?php
/* Smarty version 3.1.31-dev/34, created on 2017-05-19 15:21:17
from "D:\Apache24\htdocs\restaurant_system\tpl\communal\native.html" */
/* @var Smarty_Internal_Template $_smarty_tpl */
if ($_smarty_tpl->_decodeProperties($_smarty_tpl, array (
'version' => '3.1.31-dev/34',
'unifunc' => 'content_591e9ced085b16_12620841',
'has_nocache_code' => false,
'file_dependency' =>
array (
'9c4ad191c4a5bfa07c3b62e03d3498810aaab5d2' =>
array (
0 => 'D:\\Apache24\\htdocs\\restaurant_system\\tpl\\communal\\native.html',
1 => 1495178042,
2 => 'file',
),
),
'includes' =>
array (
),
),false)) {
function content_591e9ced085b16_12620841 (Smarty_Internal_Template $_smarty_tpl) {
?>
<!--this is for native 导航页-->
<nav class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="index.php">首页</a>
</div
><div>
<ul class="nav navbar-nav">
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
菜系
<b class="caret"></b>
</a>
<ul class="dropdown-menu">
<li class="divider"></li>
<li><a href="index.php?controller=index&method=getCuisines&action=1">川菜</a></li>
<li class="divider"></li>
<li><a href="index.php?controller=index&method=getCuisines&action=2">鲁菜</a></li>
<li class="divider"></li>
<li><a href="index.php?controller=index&method=getCuisines&action=3">湘菜</a></li>
<li class="divider"></li>
<li><a href="index.php?controller=index&method=getCuisines&action=4">浙菜</a></li>
<li class="divider"></li>
<li><a href="index.php?controller=index&method=getCuisines&action=5">东北菜</a></li>
<li class="divider"></li>
<li><a href="index.php?controller=index&method=getCuisines&action=6">京菜</a></li>
<li class="divider"></li>
<li><a href="index.php?controller=index&method=getCuisines&action=7">上海菜</a></li>
<li class="divider"></li>
<li><a href="index.php?controller=index&method=getCuisines&action=7">其他菜系</a></li>
</ul>
</li>
<!--
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
美食天地
<b class="caret"></b>
</a>
<ul class="dropdown-menu">
<li class="divider"></li>
<li><a href="#">清蒸</a></li>
<li class="divider"></li>
<li><a href="#">红烧</a></li>
<li class="divider"></li>
<li><a href="#">海鲜</a></li>
<li class="divider"></li>
<li><a href="#">凉菜</a></li>
<li class="divider"></li>
<li><a href="#">汤</a></li>
</ul>
</li>-->
<li><a href="index.php?controller=index&method=order_by_number">美食天地</a></li>
<li><a href="index.php?controller=index&method=company&action=activity">最新活动</a></li>
<li><a href="index.php?controller=index&method=company&action=contact">联系我们</a></li>
<li><a href="index.php?controller=index&method=company&action=about">关于我们</a></li>
<li><a href="index.php?controller=index&method=company&action=joinus">连锁加盟</a></li>
<li><a href="index.php?controller=index&method=company&action=ad">广告服务</a></li>
<li><a href="#">讨论区</a></li>
<li><a href="index.php?controller=index&method=selectOne">用户中心</a></li>
</ul>
<form class="navbar-form navbar-right" role="search" method="post" action="index.php?controller=index&method=find_all_result">
<div class="form-group">
<input type="text" class="form-control" name="food_name" placeholder="搜菜">
</div>
<button type="submit" class="btn btn-default">搜索</button>
</form>
</div>
</div>
</nav>
<?php }
}
<file_sep>/template_c/fa63a2d14bd92db5bfa3de4dbf8f00f94bc7a5e4_0.file.register.html.php
<?php
/* Smarty version 3.1.31-dev/34, created on 2017-05-24 02:05:06
from "D:\Apache24\htdocs\restaurant_system\tpl\index\register.html" */
/* @var Smarty_Internal_Template $_smarty_tpl */
if ($_smarty_tpl->_decodeProperties($_smarty_tpl, array (
'version' => '3.1.31-dev/34',
'unifunc' => 'content_592479d2c3f980_49454073',
'has_nocache_code' => false,
'file_dependency' =>
array (
'fa63a2d14bd92db5bfa3de4dbf8f00f94bc7a5e4' =>
array (
0 => 'D:\\Apache24\\htdocs\\restaurant_system\\tpl\\index\\register.html',
1 => 1489456481,
2 => 'file',
),
),
'includes' =>
array (
),
),false)) {
function content_592479d2c3f980_49454073 (Smarty_Internal_Template $_smarty_tpl) {
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>注册</title>
<link href="http://127.0.0.1:8080/restaurant_system/tpl/image/resturant.png" rel="icon" />
<link href="../css/general.css" type="text/css" rel="stylesheet" />
</head>
<body>
<div class="mid-part">
<div class="img">
<img src="../image/banji.png" />
</div>
<form method="post" action="../../index.php?controller=index&method=register" onSubmit="return check()" >
<span class="span">请注册你的餐厅通行证</span><br />
<input type="text" placeholder="请输入用户名" id="username"name="username" onBlur="checkUserName();"/>
<span id="uesrnameHint"></span><br />
<input type="password" placeholder="请输入密码" id="password" name="password" />
<input type="password" placeholder="请确认密码" id="checkPassword" onChange="show();"/><br />
<input type="text" placeholder="请输入手机号码" id="phone" name="phone" onBlur="checkPhone();"/>
<span id="phoneHint"></span><br />
<input type="text" placeholder="请输入邮箱" id="email" name="email"/><br />
<input class="btn" type="submit" value="注 册" name="submit"/>
</form>
</div>
</body>
</html>
<?php echo '<script'; ?>
>
var xmlHttp;
function createXmlHttp(){
if(window.XMLHttpRequest){
xmlHttp=new XMLHttpRequest();
}else{
xmlHttp=new ActiveXObject(Microsoft.XMLHttp);
}
} //使用ajax技术,用户名输入完毕以后向服务器发起异步请求,检查用户是否存在,通过回调函数接收服务器返回的数据,根据返回的数据来执行相应的操作
function checkUserName(){
//1.创建异步请求对象XMLHttpRequest
createXmlHttp();
//2.设置该对象的相关属性(请求的方式post或get,请求的url地址,请求的参数,回调函数的名字)
var userName=document.getElementById("username").value;
if(userName==""){
document.getElementById("uesrnameHint").innerHTML="<font color=red size=1px>用户名不能为空!</font>";
}else{
xmlHttp.open("get","../../index.php?controller=index&method=verifyUname&Uname="+userName);
xmlHttp.onreadystatechange=userNameCheckCallBack;
//3.
xmlHttp.send(null);}
}
//自定义的回调函数
function userNameCheckCallBack(){
if(xmlHttp.readyState==4){
if(xmlHttp.status==200){
//接收返回的信息
var ret=xmlHttp.responseText;
/*
*具体的逻辑处理
*返回的字符串多出五个长度的字符,可以注册的话不返回任何信息
*/
// alert(ret);
//alert(ret.length);
if(ret.length==5){
document.getElementById("uesrnameHint").innerHTML="<font color=green size=1px>恭喜你,该用户名可以用来注册!</font>";
}else{
document.getElementById("uesrnameHint").innerHTML="<font color=red size=1px>很遗憾,该用户名已经被注册了!</font>";
}
}
}
}
//判断密码是否两次输入的都一样
function show(){
if(password.value!=checkPassword.value){
alert("两次输入的密码不一致,请重新输入");
}
}
//对手机号码的判断,这里只是简单的判断了一下长度,可以使用ajax判断是否已经注册过
function checkPhone(){
var phone=document.getElementById('phone').value;
if(phone.length==11){
document.getElementById("phoneHint").innerHTML="<font color=green size=1px>恭喜你,该手机号可以用来注册!</font>";
}else{
document.getElementById('phoneHint').innerHTML="<font color=red size=1px>输入的手机号有误,请重新输入!</font>";
}
//针对邮箱的判断,这里暂时不做任何判断
}
<?php echo '</script'; ?>
><?php }
}
<file_sep>/libs/Controller/adminController.class.php
<?php
//管理员登录验证
class adminController{
//用session来判断用户是否已经登录
public $auth='';
//构造方法,判断用户是不是已经登录
//如果没有登录,就执行登录操作
function __construct(){
$authobj=M('auth');
$this->auth=$authobj->getauth();
if( (empty($this->auth) ||$this->auth=="") && (PC::$method!='login')){
$this->showmessage('请先登录','admin/login.html');
}
}
//************************************************************************************************************
//***************************************index默认方法,查询菜品种类和消费记录条数*********************************
//index()是默认方法
public function index(){
//设置用户名
$username=$_SESSION['username'];
//查询菜品种类和消费记录并传递
$adminobj=M('consume');
$consume_record=$adminobj->get_count_consume_record();
$adminobj2=M('foods');
$count_foods=$adminobj2->get_count_foods();
VIEW::assign(array('username'=>$username,'count_consume'=>count($consume_record),'count_foods'=>count($count_foods)));
VIEW::display('admin/index.html');
}
//**************************************************************************************************************
//*****************************************login、logout方法*****************************************************
//当点击登录时调用login()
public function login(){
//判断是否是直接登录,还是输入了账号密码以后登录
if(isset($_POST['submit'])){
$username=$_POST['username'];
$password=$_POST['<PASSWORD>'];
//执行登录操作
$authobj=M('auth');
//$this->check_uname_psw($username,$password);
if ($authobj->checkuser($username, $password)){ //登录成功以后进入index.html
echo "<script>alert('登录成功');</script>";
$this->index();
}else{
//登录失败输出相应的信息
$info="账号密码不匹配,请重新输入";
$this->showmessage($info,'admin/login.html');
}
}else{
//显示登录界面
VIEW::display('admin/login.html');
}
}
//用户退出
public function logout(){
//使得session失效,然后返回相应的界面
session_destroy();
$this->showmessage("退出成功","admin/login.html");
}
//*******************************************************************************************************************
//*******************************************************************************************************************
//*******************************************管理员查看所有的用户信息、删除用户*******************************************
//查看所有的用户
public function see_users(){
$adminobj=M('index');
$all_users=$adminobj->find_all_user();
VIEW::assign(array('all_users'=>$all_users,'username'=>$_SESSION['username']));
VIEW::display('admin/user.html');
}
//管理员删除用户
public function delete_user(){
$id=$_GET['id'];
$adminobj=M('index');
if($adminobj->delete_user($id)){
//删除成功
echo "<script>alert('删除成功!');</script>";
}else{
echo "<script>alert('操作失败,请重新再试!');</script>";
}
$this->see_users();
}
//******************************************************************************************************************
//************************************************************************************************************
//****************************************管理员查看、删除用户的消费信息*******************************
//管理员查看用户的消费信息
public function see_consume(){
//1.调用userModel中的find_consume_record()方法,用户名通过session来获得,返回的是结果集(二维数组)
$adminobj=M('consume');
$result=$adminobj->find_all_consume_record();
//2.跳转到user_consume.html界面,并将数据传递过去
VIEW::assign(array('consume_record'=>$result,'username'=>$_SESSION['username']));
VIEW::display('admin/user_consume.html');
}
//管理员删除用户的消费信息
public function delete_consume_record(){
$id=$_GET['Id'];
//2.根据id来删除数据库中的数据
$adminobj=M('user');
if($adminobj->delete_consume_record($id)){
//成功删除
echo "<script>alert('删除成功!');</script>";
}else{
echo "<script>alert('删除失败,请重新再试!');</script>";
}
$this->see_consume();
}
//****************************************************************************************************
//****************************************************************************************************
//*****************************************管理员查看菜单、删除菜单、修改菜单、添加菜单*********************
//1.管理员查看菜单
public function see_foods(){
$adminobj=M('foods');
$result=$adminobj->get_count_foods();
//2.跳转到foods.html界面,并将数据传递过去
VIEW::assign(array('all_foods'=>$result,'username'=>$_SESSION['username']));
VIEW::display('admin/foods.html');
}
//2.管理员删除菜品
public function delete_foods(){
$id=$_GET['id'];
$adminobj=M('foods');
if($adminobj->delete_foods($id)){
echo "<script>alert('删除成功');</script>";
}else{
echo "<script>alert('删除失败,请重新再试');</script>";
}
$this->see_foods();
}
//3.管理员修改菜品,在界面上显示这个菜品的所有信息
public function change_foods(){
$id=$_GET['id'];
$adminobj=M('foods');
$result=$adminobj->change_foods($id);
VIEW::assign(array('foods'=>$result,'username'=>$_SESSION['username']));
VIEW::display('admin/change_foods.html');
}
//4.管理员确认修改这个菜品的信息
public function save_foods(){
//1.接收相应的参数
@ $id=$_GET['id'];
$foodName=$_POST['food_name'];
$foodMoney=$_POST['food_money'];
$cooking=$_POST['food_cooking'];
$cuisines=$_POST['food_cuisines'];
$foodUrl=$_POST['food_url'];
$array=array("foodName"=>$foodName,"cuisines"=>$cuisines,"foodUrl"=>$foodUrl,"cooking"=>$cooking,"foodMoney"=>$foodMoney);
$adminobj=M('foods');
if($id){
//当id不为空的时候,表示是修改菜品
//2.插入数据库
if($adminobj->save_foods($array,$id)){
echo "<script>alert('修改成功');</script>";
}else{
echo "<script>alert('修改失败,请重新再试');</script>";
}
}else{
//当id为空的时候,表示是添加菜品
//1.将图片放到指定的文件目录下
if ($_FILES["food_file"]["error"] > 0){
// echo "错误:". $_FILES["food_file"]["error"] . "<br>";
}
else{
// 如果没有 food 目录,你需要创建它,food 目录权限为 777
if(!file_exists("tpl/image/food/")){
mkdir("tpl/image/food/",0777);
}
// 将文件上传到 food 目录下(file_exists函数检查当前目录下所有权限,在这里有错误,所以换一种方式来做)
move_uploaded_file($_FILES["food_file"]["tmp_name"], "tpl/image/food/". iconv("UTF-8", "gb2312",$_FILES["food_file"]["name"]));
}
//2.将数据存入数据库中
if($adminobj->add_foods($array)){
echo "<script>alert('添加成功');</script>";
}else{
echo "<script>alert('添加失败,请重新再试');</script>";
}
}
$this->see_foods();
}
//5.管理员查看某个菜品的详情
public function detail_foods(){
//1.接收传来的菜品名称
$id=$_GET['id'];
$adminobj=M('foods');
//得到菜品的详细信息
$result=$adminobj->change_foods($id);
$result['cooking']=nl2br($result['cooking']);
//跳转到相应的界面
VIEW::assign(array('foods'=>$result));
VIEW::display('admin/detail_food.html');
}
//6.管理员点击添加菜品
public function add_foods(){
VIEW::assign(array('username'=>$_SESSION['username']));
VIEW::display('admin/add_foods.html');
}
//****************************************************************************************************
//****************************************************************************************************
//*******************************************管理员进行公告管理******************************************
//1.管理员查看所有通知
public function see_notice(){
$adminobj=M('notice');
$result=$adminobj->see_notices();
VIEW::assign(array('notice'=>$result,'username'=>$_SESSION['username']));
VIEW::display('admin/notice.html');
}
//2.管理员查看具体通知
public function detail_notice(){
$id=$_GET['id'];
$adminobj=M('notice');
$result=$adminobj->detail_notices($id);
$result['context']=nl2br($result['context']);
VIEW::assign(array('notice'=>$result,'username'=>$_SESSION['username']));
VIEW::display('admin/detail_notice.html');
}
//3.管理员删除通知
public function delete_notice(){
$id=$_GET['id'];
$adminobj=M('notice');
if($adminobj->delete_notice($id)){
echo "<script>alert('删除成功');</script>";
}else{
echo "<script>alert('删除失败,请重新再试');</script>";
}
$this->see_notice();
}
//4.管理员添加通知
public function add_notice(){
$date=date("Y-m-d");
$time=date("H:i:s");
VIEW::assign(array('username'=>$_SESSION['username'],'date'=>$date,'time'=>$time));
VIEW::display('admin/add_notices.html');
}
//5.管理员修改通知
public function change_notice(){
$id=$_GET['id'];
$adminobj=M('notice');
$result=$adminobj->detail_notices($id);
VIEW::assign(array('notice'=>$result,'username'=>$_SESSION['username']));
VIEW::display('admin/change_notice.html');
}
//6.管理员确定修改信息以及添加信息
public function save_notice(){
//1.接收相应的参数
@ $id=$_GET['id'];
$notice_title=$_POST['notice_title'];
$notice_announcer=$_POST['notice_announcer'];
$notice_date=$_POST['notice_date'];
$notice_time=$_POST['notice_time'];
$notice_context=$_POST['notice_context'];
$array=array("title"=>$notice_title,"announcer"=>$notice_announcer,"date"=>$notice_date,"time"=>$notice_time,"context"=>$notice_context);
$adminobj=M('notice');
if($id){
//当id不为空的时候,表示是修改通知
//2.插入数据库
if($adminobj->save_notices($array,$id)){
echo "<script>alert('修改成功');</script>";
}else{
echo "<script>alert('修改失败,请重新再试');</script>";
}
}else{
//当id为空的时候,表示是添加通知
//2.将数据存入数据库中
if($adminobj->add_notices($array)){
echo "<script>alert('添加成功');</script>";
}else{
echo "<script>alert('添加失败,请重新再试');</script>";
}
}
$this->see_notice();
}
//****************************************************************************************************
//封装showmessage()方法用来展示信息并跳转界面
private function showmessage($info,$url){
echo "<script>alert('$info');</script>";
VIEW::display($url);
}
}
?><file_sep>/template_c/9ec0183a25da96b8574614b97d1432c149e93713_0.file.shouye.html.php
<?php
/* Smarty version 3.1.31-dev/34, created on 2017-05-23 23:17:56
from "D:\Apache24\htdocs\restaurant_system\tpl\index\shouye.html" */
/* @var Smarty_Internal_Template $_smarty_tpl */
if ($_smarty_tpl->_decodeProperties($_smarty_tpl, array (
'version' => '3.1.31-dev/34',
'unifunc' => 'content_592452a476e632_54433983',
'has_nocache_code' => false,
'file_dependency' =>
array (
'9ec0183a25da96b8574614b97d1432c149e93713' =>
array (
0 => 'D:\\Apache24\\htdocs\\restaurant_system\\tpl\\index\\shouye.html',
1 => 1495552675,
2 => 'file',
),
),
'includes' =>
array (
'file:tpl/communal/native.html' => 1,
'file:tpl/communal/footer.html' => 1,
),
),false)) {
function content_592452a476e632_54433983 (Smarty_Internal_Template $_smarty_tpl) {
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>不二餐厅</title>
<link href="tpl/image/resturant.png" rel="icon" />
<link rel="stylesheet" href="tpl/css/general.css" />
<link rel="stylesheet" href="tpl/css/bootstrap.min.css">
<?php echo '<script'; ?>
src="tpl/js/jquery.min.js"><?php echo '</script'; ?>
>
<?php echo '<script'; ?>
src="tpl/js/bootstrap.min.js"><?php echo '</script'; ?>
>
</head>
<body>
<!--this is for head , not be all the same-->
<div class="head">
<div class="setmarquee">
<marquee loop="-1" behavior="alternate" scrollamount="10" scrolldelay="5" onMouseOver="stop()" onMouseOut="start()" ><font style="color:#666666; font-size:30px; font-family:Georgia, 'Times New Roman', Times, serif; ">不"2"餐厅</font></marquee> <br />
</div>
<div class="setuser">
<a href="tpl/index/login.html">登录</a>
<a>|</a>
<a href="tpl/index/register.html">注册</a>
</div>
</div>
<!--this is for native,all the same-->
<?php $_smarty_tpl->_subTemplateRender('file:tpl/communal/native.html', $_smarty_tpl->cache_id, $_smarty_tpl->compile_id, 0, $_smarty_tpl->cache_lifetime, array(), 0, false);
?>
<!--this is for 轮播界面-->
<div id="myCarousel" class="carousel slide">
<!-- 轮播(Carousel)指标 -->
<ol class="carousel-indicators">
<li data-target="#myCarousel" data-slide-to="0" class="active"></li>
<li data-target="#myCarousel" data-slide-to="1"></li>
<li data-target="#myCarousel" data-slide-to="2"></li>
</ol>
<!-- 轮播(Carousel)项目,里面的图片都是 -->
<div class="carousel-inner">
<div class="item active">
<img src="tpl/image/mengxiang2.jpg" alt="First slide">
</div>
<div class="item">
<img src="tpl/image/mengxiang2.jpg" alt="Second slide">
</div>
<div class="item">
<img src="tpl/image/mengxiang2.jpg" alt="Third slide">
</div>
</div>
<!-- 轮播(Carousel)导航 -->
<a class="carousel-control left" href="#myCarousel"
data-slide="prev">‹</a>
<a class="carousel-control right" href="#myCarousel"
data-slide="next">›</a>
</div>
<!--三列:美食、热点讨论、公告(暂时做出一个链接#,时间足够再写)-->
<div class="three-part">
<!--************************************第一部分***************************************-->
<div class="first_part">
<!--标题-->
<div class="part-title">美食</div>
<!--内容-->
<ul class="list-group">
<?php
$__section_index_0_saved = isset($_smarty_tpl->tpl_vars['__smarty_section_index']) ? $_smarty_tpl->tpl_vars['__smarty_section_index'] : false;
$__section_index_0_loop = (is_array(@$_loop=$_smarty_tpl->tpl_vars['foodName']->value) ? count($_loop) : max(0, (int) $_loop));
$__section_index_0_total = $__section_index_0_loop;
$_smarty_tpl->tpl_vars['__smarty_section_index'] = new Smarty_Variable(array());
$__section_index_0_show = (bool) true ? $__section_index_0_total != 0 : false;
if ($__section_index_0_show) {
for ($__section_index_0_iteration = 1, $_smarty_tpl->tpl_vars['__smarty_section_index']->value['index'] = 0; $__section_index_0_iteration <= $__section_index_0_total; $__section_index_0_iteration++, $_smarty_tpl->tpl_vars['__smarty_section_index']->value['index']++){
?>
<li class="list-group-item">
<span class="badge">新</span>
<a href="index.php?controller=index&method=detail_foods&id=<?php echo $_smarty_tpl->tpl_vars['foodName']->value[(isset($_smarty_tpl->tpl_vars['__smarty_section_index']->value['index']) ? $_smarty_tpl->tpl_vars['__smarty_section_index']->value['index'] : null)]['Id'];?>
"><?php echo (isset($_smarty_tpl->tpl_vars['__smarty_section_index']->value['index']) ? $_smarty_tpl->tpl_vars['__smarty_section_index']->value['index'] : null)+1;?>
.<?php echo $_smarty_tpl->tpl_vars['foodName']->value[(isset($_smarty_tpl->tpl_vars['__smarty_section_index']->value['index']) ? $_smarty_tpl->tpl_vars['__smarty_section_index']->value['index'] : null)]['foodName'];?>
</a></li>
<?php
}
}
if ($__section_index_0_saved) {
$_smarty_tpl->tpl_vars['__smarty_section_index'] = $__section_index_0_saved;
}
?>
<li class="list-group-item"><a href="#">更多>></a></li>
</ul>
</div>
<!--**************************************第二部分****************************************-->
<div class="second-part">
<!--标题-->
<div class="part-title">热点讨论</div>
<!--内容-->
<ul class="list-group">
<li class="list-group-item">
<span class="badge">新</span>
<a href="#">1.土豆丝怎么做好吃?</a></li>
<li class="list-group-item">
<a href="#"> 2.最新活动怎么解读?</a></li>
<li class="list-group-item">
<a href="#">3.第一次使用的功能</a></li>
<li class="list-group-item">
<a href="#">4.对不二餐厅的评价</a>
</li>
<li class="list-group-item"><a href="#">更多>></a></li>
</ul>
</div>
<!--***************************************第三部分****************************************-->
<div class="thrid-part">
<!--标题-->
<div class="part-title">公告</div>
<!--内容-->
<ul class="list-group">
<?php
$__section_index_1_saved = isset($_smarty_tpl->tpl_vars['__smarty_section_index']) ? $_smarty_tpl->tpl_vars['__smarty_section_index'] : false;
$__section_index_1_loop = (is_array(@$_loop=$_smarty_tpl->tpl_vars['notice']->value) ? count($_loop) : max(0, (int) $_loop));
$__section_index_1_total = $__section_index_1_loop;
$_smarty_tpl->tpl_vars['__smarty_section_index'] = new Smarty_Variable(array());
$__section_index_1_show = (bool) true ? $__section_index_1_total != 0 : false;
if ($__section_index_1_show) {
for ($__section_index_1_iteration = 1, $_smarty_tpl->tpl_vars['__smarty_section_index']->value['index'] = 0; $__section_index_1_iteration <= $__section_index_1_total; $__section_index_1_iteration++, $_smarty_tpl->tpl_vars['__smarty_section_index']->value['index']++){
?>
<li class="list-group-item">
<span class="badge">新</span>
<a href="index.php?controller=index&method=detail_notice¬ice_id=<?php echo $_smarty_tpl->tpl_vars['notice']->value[(isset($_smarty_tpl->tpl_vars['__smarty_section_index']->value['index']) ? $_smarty_tpl->tpl_vars['__smarty_section_index']->value['index'] : null)]['Id'];?>
"><?php echo (isset($_smarty_tpl->tpl_vars['__smarty_section_index']->value['index']) ? $_smarty_tpl->tpl_vars['__smarty_section_index']->value['index'] : null)+1;?>
.<?php echo $_smarty_tpl->tpl_vars['notice']->value[(isset($_smarty_tpl->tpl_vars['__smarty_section_index']->value['index']) ? $_smarty_tpl->tpl_vars['__smarty_section_index']->value['index'] : null)]['title'];?>
</a></li>
<?php
}
}
if ($__section_index_1_saved) {
$_smarty_tpl->tpl_vars['__smarty_section_index'] = $__section_index_1_saved;
}
?>
<li class="list-group-item"><a href="#">更多>></a></li>
</ul>
</div>
</div>
<!--这里是页脚部分-->
<?php $_smarty_tpl->_subTemplateRender('file:tpl/communal/footer.html', $_smarty_tpl->cache_id, $_smarty_tpl->compile_id, 0, $_smarty_tpl->cache_lifetime, array(), 0, false);
?>
</body>
</html>
<?php }
}
<file_sep>/template_c/742aec5ca5542302443a3770ada8d5714d4fdc5d_0.file.head.html.php
<?php
/* Smarty version 3.1.31-dev/34, created on 2017-03-06 14:40:25
from "D:\Apache24\htdocs\restaurant_system\tpl\communal\head.html" */
/* @var Smarty_Internal_Template $_smarty_tpl */
if ($_smarty_tpl->_decodeProperties($_smarty_tpl, array (
'version' => '3.1.31-dev/34',
'unifunc' => 'content_58bd04593a1349_51851498',
'has_nocache_code' => false,
'file_dependency' =>
array (
'742aec5ca5542302443a3770ada8d5714d4fdc5d' =>
array (
0 => 'D:\\Apache24\\htdocs\\restaurant_system\\tpl\\communal\\head.html',
1 => 1488782242,
2 => 'file',
),
),
'includes' =>
array (
),
),false)) {
function content_58bd04593a1349_51851498 (Smarty_Internal_Template $_smarty_tpl) {
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>header</title>
<link rel="stylesheet" href="tpl/css/general.css" />
<link rel="stylesheet" href="tpl/css/bootstrap.min.css">
<?php echo '<script'; ?>
src="tpl/js/jquery.min.js"><?php echo '</script'; ?>
>
<?php echo '<script'; ?>
src="tpl/js/bootstrap.min.js"><?php echo '</script'; ?>
>
</head>
<body>
<!--this is for head-->
<div class="head">
<div class="setmarquee">
<marquee loop="-1" behavior="alternate" scrollamount="10" scrolldelay="5" onMouseOver="stop()" onMouseOut="start()" ><font style="color:#666666; font-size:30px; font-family:Georgia, 'Times New Roman', Times, serif; ">不"2"餐厅</font></marquee> <br />
</div>
<div class="setuser">
<a href="tpl/index/login.html">登录</a>
<a>|</a>
<a href="tpl/index/register.html">注册</a>
</div>
</div>
<!--this is for native 导航页-->
<nav class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="communal/head.html">首页</a>
</div
><div>
<ul class="nav navbar-nav">
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
菜系
<b class="caret"></b>
</a>
<ul class="dropdown-menu">
<li class="divider"></li>
<li><a href="#">苏菜</a></li>
<li class="divider"></li>
<li><a href="#">闽菜</a></li>
<li class="divider"></li>
<li><a href="#">川菜</a></li>
<li class="divider"></li>
<li><a href="#">鲁菜</a></li>
<li class="divider"></li>
<li><a href="#">粤菜</a></li>
<li class="divider"></li>
<li><a href="#">湘菜</a></li>
<li class="divider"></li>
<li><a href="#">浙菜</a></li>
<li class="divider"></li>
<li><a href="#">徽菜</a></li>
<li class="divider"></li>
<li><a href="#">东北菜</a></li>
<li class="divider"></li>
<li><a href="#">京菜</a></li>
<li class="divider"></li>
<li><a href="#">清真菜</a></li>
<li class="divider"></li>
<li><a href="#">上海菜</a></li>
<li class="divider"></li>
<li><a href="#">湖北菜</a></li>
</ul>
</li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
美食天地
<b class="caret"></b>
</a>
<ul class="dropdown-menu">
<li class="divider"></li>
<li><a href="#">清蒸类</a></li>
<li class="divider"></li>
<li><a href="#">红烧类</a></li>
<li class="divider"></li>
<li><a href="#">海鲜类</a></li>
<li class="divider"></li>
<li><a href="#">卤菜类</a></li>
<li class="divider"></li>
<li><a href="#">凉菜类</a></li>
<li class="divider"></li>
<li><a href="#">干煸类</a></li>
<li class="divider"></li>
<li><a href="#">汤类</a></li>
</ul>
</li>
<li><a href="#">最新活动</a></li>
<li><a href="#">联系我们</a></li>
<li><a href="#">关于我们</a></li>
<li><a href="#">连锁加盟</a></li>
<li><a href="#">广告服务</a></li>
<li><a href="#">讨论区</a></li>
<li><a href="index.php?controller=index&method=selectOne">用户中心</a></li>
</ul>
</div>
</div>
</nav>
<!--this is for 轮播界面-->
<div id="myCarousel" class="carousel slide">
<!-- 轮播(Carousel)指标 -->
<ol class="carousel-indicators">
<li data-target="#myCarousel" data-slide-to="0" class="active"></li>
<li data-target="#myCarousel" data-slide-to="1"></li>
<li data-target="#myCarousel" data-slide-to="2"></li>
</ol>
<!-- 轮播(Carousel)项目 -->
<div class="carousel-inner">
<div class="item active">
<img src="tpl/image/mengxiang2.jpg" alt="First slide">
</div>
<div class="item">
<img src="tpl/image/mengxiang2.jpg" alt="Second slide">
</div>
<div class="item">
<img src="tpl/image/mengxiang2.jpg" alt="Third slide">
</div>
</div>
<!-- 轮播(Carousel)导航 -->
<a class="carousel-control left" href="#myCarousel"
data-slide="prev">‹</a>
<a class="carousel-control right" href="#myCarousel"
data-slide="next">›</a>
</div>
</body>
</html>
<?php }
}
<file_sep>/README.md
# restaurant_system
餐厅--毕业设计
<file_sep>/template_c/0e2fbef0d422c43adb00de4de72f08125098b868_0.file.footer.html.php
<?php
/* Smarty version 3.1.31-dev/34, created on 2017-03-21 15:26:33
from "D:\Apache24\htdocs\restaurant_system\tpl\communal\footer.html" */
/* @var Smarty_Internal_Template $_smarty_tpl */
if ($_smarty_tpl->_decodeProperties($_smarty_tpl, array (
'version' => '3.1.31-dev/34',
'unifunc' => 'content_58d0d5a9562088_51166467',
'has_nocache_code' => false,
'file_dependency' =>
array (
'0e2fbef0d422c43adb00de4de72f08125098b868' =>
array (
0 => 'D:\\Apache24\\htdocs\\restaurant_system\\tpl\\communal\\footer.html',
1 => 1490081190,
2 => 'file',
),
),
'includes' =>
array (
),
),false)) {
function content_58d0d5a9562088_51166467 (Smarty_Internal_Template $_smarty_tpl) {
?>
<!--这里是页脚部分的样式-->
<div class="footer">
<!--在这个div中写样式-->
<div class="footer-part">
<!--这里是与公司简介相关的-->
<div class="footer-company">
<a href="index.php?controller=index&method=company&action=activity">最新活动</a>
<a href="index.php?controller=index&method=company&action=contact">联系我们</a>
<a href="index.php?controller=index&method=company&action=about">关于我们</a>
<a href="index.php?controller=index&method=company&action=joinus">连锁加盟</a>
<a href="index.php?controller=index&method=company&action=ad">广告服务</a>
</div>
<!--这里是网站都会有的备案-->
<div class="footer-backup">
©2017-2018 Spark Intelligence All Rights Reserved
</div>
</div>
</div>
<?php }
}
<file_sep>/libs/Model/consumeModel.class.php
<?php
class consumeModel{
/*
*这个表主要是所有与consume表有关的操作,包括以下操作:
*1.用户查询自己的消费信息
*2.用户删除自己的消费信息
*3.管理员查看用户的消费信息
*4.管理员删除用户的消费信息(暂时留着不写)
*/
public $table='consume';
//***********************************************************************************************************
//********************************************这里是用户的操作*************************************************
//用户查询自己的消费信息,返回的是一个结果集
public function find_consume_record($username){
$sql='select * from '.$this->table.' where username = "'.$username.'" group by date,time';
return DB::findAll($sql);
}
//用户和管理员删除自己的消费信息
public function delete_consume_record($id){
$where='Id ='.$id;
return DB::del($this->table,$where);
}
//管理员查询所有用户的消费信息
public function find_all_consume_record(){
$sql='select * from '.$this->table .' group by username,date,time';
return DB::findAll($sql);
}
//用户支付了以后插入一条数据
public function pay_shopping($arr){
return DB::insert($this->table,$arr);
}
//**************************************************************************************************************
//**********************************************这里是管理员的操作*************************************************
//得到所有的消费记录
public function get_count_consume_record(){
$sql='select * from '.$this->table;
return DB::findAll($sql);
}
}
?><file_sep>/libs/Controller/indexController.class.php
<?php
class indexController{
//用session来判断用户是否已经登录
public $user='';
//默认方法,index()是首页
public function index(){
//逆序读取美食的名字
$userobj=M('foods');
$foodName=$userobj->find_foodname();
$userobj2=M('notice');
$notice=$userobj2->findall_notice();
VIEW::assign( array('foodName'=>$foodName,'notice'=>$notice));
//当用户存在时,将用户名称传过去
if( @ $_SESSION['user']!=null){
VIEW::assign( array('user'=>$_SESSION['user']) );
VIEW::display('index/shouye_login.html');
}else{
VIEW::display('index/shouye.html');
}
}
//***************************************************************************************************************
//***************************************************************************************************************
//******************以下是用户的登录注册,ajax判断用户名是否存在,以及登出***********************************************
//***************************************************************************************************************
//当用户点击用户中心的时候,判断是进行登录还是直接跳转到user.html界面
public function selectOne(){
$indexobj=M('user');
$this->user=$indexobj->getuser();
if($this->user==null){
//未登录的时候
$this->showmessage('您还未登录,请先登录!','index/login.html');
}else{
//登录了以后,拼装用户所有数据传输过去,在用户界面显示
VIEW::assign( array('user'=>$this->user) );
VIEW::display('index/user.html');
}
}
//首页中的登录方法
public function login(){
//判断是直接通过地址登录,还是在登录界面登录
if(isset($_POST['submit'])){
//1.得到传过来的账号和密码
$username=$_POST['username'];
$password=$_POST['password'];
//2.验证账号的密码是否正确
$userobj=M('user');
$this->user=$userobj->check_user($username,$password);
if(!$this->user==""&&!empty($this->user)){
//3.如果账号密码匹配的话,跳转到用户界面user.html,并将用户保存在session['user']中
$_SESSION['user']=$this->user;
//将用户的数据传到user.html界面
VIEW::assign(array('user'=>$_SESSION['user']) );
$this->showmessage('登录成功!','index/user.html');
}else{
//4.如果不匹配的话,就提示登录失败
$this->showmessage('账号密码不匹配,请重新输入','index/login.html');
}
}else{
VIEW::display('index/login.html');
}
}
/*
*ajax判断用户名是否可用
*
*1.得到传过来的用户名
*2.判断用户名是否已经被注册了
*3.如果被注册了,不输出任何信息,如果用户名可用,输出任意文本信息
*4.前端界面得到的是输出的所有的文本信息
*@author:warwick
**/
public function verifyUname(){
$username='';
if(isset($_GET['Uname']) ){
$username=$_GET['Uname'];
//判断用户名是否在数据库中已经存在了
$userobj=M('user');
if(!$userobj->check_uname_exist($username)){
//在数据库中不存在用户名
echo "";
}else{
echo "error";
}
}
}
/*
*当点击注册的时候到这个方法中
*
*1.得到用户在界面中填写的数据(因为数据在register.html中已经判断过了,所以传递过来的数据都是正确的)
*2.将数据插入到用户表中
*@author:warwick
*/
public function register(){
//1.判断是通过网址直接到这里还是点击了注册按钮
if( isset($_POST['submit'])){
$username =$_POST['username'];
$password =$_POST['password'];
$phoneNumber=$_POST['phone'];
$email =$_POST['email'];
$userobj=M('user');
//返回的是一个空值
if($userobj->add_one_user($username,$password,$phoneNumber,$email)){
//如果注册成功的话,将注册的数据放入session中
$users=array('username'=>$username,'password'=>$<PASSWORD>,
'phoneNumber'=>$phoneNumber,'email'=>$email);
$_SESSION['user']=$users;
//将用户的所有数据通过smarty传递到user.html界面中
//当注册的时候可以直接得到用户的一些信息,默认用户的积分是0
VIEW::assign(array('user'=> $_SESSION['user']) );
$this->showmessage('恭喜注册成功','index/user.html');
}else{
$this->showmessage('系统出现错误,请重试!','index/register.html');
}
}else{
$this->showmessage('请先登录!','index/login.html');
}
}
//当用户点击退出的时候,启动此方法
/*
*1.销毁session中的数据
*2.返回到首页
*/
public function logout(){
unset($_SESSION['user']);
$this->index();
}
//**************************************************************************************************************
//**************************************************************************************************************
//**************************************************************************************************************
//**************************************************************************************************************
//*************在user.html和user_consume.html界面中展示删除用户的消费信息和修改用户的基本信息、购物车以及支付*************
public function consume_record(){
//跳转到uers_consume.html界面中,需要查询当前用户的消费信息,查询表consume
//1.调用userModel中的find_consume_record()方法,用户名通过session来获得,返回的是结果集(二维数组)
$userobj=M('user');
$result=$userobj->find_consume_record($_SESSION['user']['username']);
//2.跳转到user_consume.html界面,并将数据传递过去
VIEW::assign(array('consume_record'=>$result));
VIEW::assign(array('username'=>$_SESSION['user']['username']));
VIEW::display('index/user_consume.html');
}
public function identify(){
//当点击我的消息时,跳转到user.html界面中,考虑到用户积分的变化,读取一次数据库
$userobj=M('index');
$result=$userobj->user_info( $_SESSION['user']['username']);
VIEW::assign(array('user'=> $result) );
VIEW::display('index/user.html');
}
public function delete_consume_record(){
//1.得到传过来的ID记录
$id=$_GET['Id'];
//2.根据id来删除数据库中的数据
$userobj=M('user');
if($userobj->delete_consume_record($id)){
//成功删除
echo "<script>alert('删除成功!');</script>";
}else{
echo "<script>alert('删除失败,请重新再试!');</script>";
}
$this->consume_record();
}
public function change_username(){
//得到传过来的username
$username=$_POST['username'];
//更改数据库中的数据
$userobj=M('user');
if($userobj->change_username($_SESSION['user']['username'],$username)){
//更新成功
$_SESSION['user']['username']=$username;
}
$this->identify();
}
//用户点击加入购物车
public function add_shopping(){
//接收传递过来的参数
$foodname=$_GET['foodname'];
$account=$_GET['account'];
$arr=array('username'=>$_SESSION['user']['username'],'foodname'=>$foodname,'account'=>$account);
$userobj=M('shopping');
if($userobj->add_shopping($arr)){
$this->find_shopping();
}else{
echo "<script>alert('加入购物车失败,请重新再试!');</script>";
}
}
//用户查询自己购物车的数据
public function find_shopping(){
$userobj=M('shopping');
@$result=$userobj->find_shopping($_SESSION['user']['username']);
@VIEW::assign(array('user'=>$_SESSION['user'],'shopping'=>$result) );
VIEW::display('index/gouwuche.html');
}
//用户从购物车中支付自己的购物清单
public function pay_shopping(){
@ $id=$_GET['id'];
$userobj=M('shopping');
$result=$userobj->find_shopping_by_id($id);
if($result){
//用户得到该条需要支付的所有信息,首先将消息插入信息表
//得到日期时间数据
$date=date("Y-m-d");
$time=date("H:i:s");
$arr=array('username'=>$_SESSION['user']['username'],'foodNames'=>$result['foodname'],'acount'=>$result['account'],'date'=>$date,'time'=>$time);
$userobj2=M('consume');
if($userobj2->pay_shopping($arr)){
//在shopping表中删除这条记录
if($userobj->delete_shopping($id)){
echo "<script>alert('支付成功,马上上菜');</script>";
$food_name=explode(",",$result['foodname']);
$userobj3=M('foods');
//销量加一操作
for($i=0;$i<count($food_name)-1;$i++){
if(!$userobj3->add_one_time($food_name[$i])){
echo "<script>alert('添加入数据库出现错误,请重新尝试!');</script>";
break;
}
}
//给用户增加积分
$userobj4=M('index');
$userobj4->add_point($_SESSION['user']['username'],$result['account']);
$this->find_shopping();
}else{
echo "<script>alert('支付失败,请重新再试!');</script>";
}
}else{
echo "<script>alert('支付失败,请重新再试!');</script>";
}
}
}
//用户直接在界面上进行支付
public function direct_pay(){
//接收传递过来的参数
$foodNames=$_GET['foodname'];
$acount=$_GET['account'];
//得到日期时间数据
$date=date("Y-m-d");
$time=date("H:i:s");
$arr=array('username'=>$_SESSION['user']['username'],'foodNames'=>$foodNames,'acount'=>$acount,'date'=>$date,'time'=>$time);
$userobj=M('consume');
if($userobj->pay_shopping($arr)){
echo "<script>alert('支付成功,马上上菜!');</script>";
//支付成功以后,需要对foods_db表进行销量加一的操作,循环操作数据库
$food_name=explode(",",$foodNames);
$userobj2=M('foods');
for($i=0;$i<count($food_name)-1;$i++){
if(!$userobj2->add_one_time($food_name[$i])){
echo "<script>alert('添加入数据库出现错误,请重新尝试!');</script>";
break;
}
}
//给用户增加积分
$userobj4=M('index');
$userobj4->add_point($_SESSION['user']['username'],$acount);
//跳转到自己的消费信息
$this->consume_record();
}else{
echo "<script>alert('支付失败,请重新再试!');</script>";
}
}
//**************************************************************************************************************
//**************************************************************************************************************
//********************************************当用户点击跳转到公司的界面********************************************
public function company(){
//1.判断传过来的参数是什么
$action=$_GET['action'];
//2.跳转到相应的界面
switch($action)
{
case 'activity':
VIEW::display('company/activity.html');
break;
case 'contact':
VIEW::display('company/contact.html');
break;
case 'about':
VIEW::display('company/about.html');
break;
case 'joinus':
VIEW::display('company/joinus.html');
break;
case 'ad':
VIEW::display('company/ad.html');
break;
default:
$this->showmessage('出错误了','index/shouye.html');
}
}
//**************************************************************************************************************
//**************************************************************************************************************
//**********************************当用户点击菜系和美食天地时,跳转到查询菜品的界面***********************************
public function getCuisines(){
//1.判断传过来的参数
$action=$_GET['action'];
//2.根据参数的值来判断是哪个菜系
$cuisines="";
switch ($action){
case 1:
$cuisines="川菜";
break;
case 2:
$cuisines="鲁菜";
break;
case 3:
$cuisines="湘菜";
break;
case 4:
$cuisines="浙菜";
break;
case 5:
$cuisines="东北菜";
break;
case 6:
$cuisines="京菜";
break;
case 7:
$cuisines="上海菜";
break;
case 8:
$cuisines="其他菜系";
break;
}
//3.根据$cuisines值来查询数据库的信息,返回一个数组
$userobj=M('user');
$result=$userobj->find_by_cuisines($cuisines);
@VIEW::assign(array('user'=>$_SESSION['user'],'foods'=>$result) );
//4.跳转到main.php界面中
VIEW::display('index/main.html');
}
public function order_by_number(){
$userobj=M('foods');
$result=$userobj->order_by_number();
@VIEW::assign(array('user'=>$_SESSION['user'],'foods'=>$result) );
//4.跳转到main.php界面中
VIEW::display('index/main.html');
}
//***************************************************************************************************************
//***************************************************************************************************************
//*****************************************用户点击搜索,在这里是查询菜单foods_db、查询菜单详情***********************
public function find_all_result(){
//接收传过来的name关键字
$food_name=$_POST['food_name'];
//在foods_db中查询相应的菜单
$userobj=M('foods');
$result=$userobj->find_all_result($food_name);
//在这里对结果进行判断,当没查询到结果的时候,提示相应信息,并展示其他的菜单
if($result==null){
echo "<script>alert('没查询到结果');</script>";
$result=$userobj->get_count_food();
}
VIEW::assign(array('user'=>$_SESSION['user'],'foods'=>$result));
//查询到结果.跳转到main.php界面中
VIEW::display('index/main.html');
}
//当用户查看菜单详情页的时候
public function detail_foods(){
$id=$_GET['id'];
$userobj=M('foods');
$result=$userobj->change_foods($id);
//将换行符的作用显示出来
$result['cooking']=nl2br($result['cooking']);
VIEW::assign(array('user'=>$_SESSION['user'],'foods'=>$result));
//查询到结果.跳转到main.php界面中
VIEW::display('index/detail_food.html');
}
//***************************************************************************************************************
//*************************************************用户查看通知的时候**********************************************
public function detail_notice(){
$id=$_GET['notice_id'];
$userobj=M('notice');
$result=$userobj->find_notice_by_id($id);
$result['context']=nl2br($result['context']);
VIEW::assign(array('user'=>$_SESSION['user'],'notice'=>$result));
VIEW::display('index/notice.html');
}
//***************************************************************************************************************
//封装showmessage()方法用来展示信息并跳转界面
private function showmessage($info,$url){
echo "<script>alert('$info');</script>";
VIEW::display($url);
}
}
?><file_sep>/template_c/33482643a2369bbc18b9c668086aa4144674994c_0.file.login.html.php
<?php
/* Smarty version 3.1.31-dev/34, created on 2017-02-28 16:35:13
from "D:\Apache24\htdocs\restaurant_system\tpl\admin\login.html" */
/* @var Smarty_Internal_Template $_smarty_tpl */
if ($_smarty_tpl->_decodeProperties($_smarty_tpl, array (
'version' => '3.1.31-dev/34',
'unifunc' => 'content_58b53641af42f1_20536602',
'has_nocache_code' => false,
'file_dependency' =>
array (
'33482643a2369bbc18b9c668086aa4144674994c' =>
array (
0 => 'D:\\Apache24\\htdocs\\restaurant_system\\tpl\\admin\\login.html',
1 => 1488270898,
2 => 'file',
),
),
'includes' =>
array (
),
),false)) {
function content_58b53641af42f1_20536602 (Smarty_Internal_Template $_smarty_tpl) {
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8"/>
<title>后台登录</title>
<link rel="stylesheet" href="tpl/css/layout.css" type="text/css" media="screen" />
<?php echo '<script'; ?>
src="tpl/js/jquery.min.js" type="text/javascript"><?php echo '</script'; ?>
>
<?php echo '<script'; ?>
src="tpl/js/hideshow.js" type="text/javascript"><?php echo '</script'; ?>
>
<?php echo '<script'; ?>
src="tpl/js/jquery.tablesorter.min.js" type="text/javascript"><?php echo '</script'; ?>
>
<?php echo '<script'; ?>
type="text/javascript" src="tpl/js/jquery.equalHeight.js"><?php echo '</script'; ?>
>
<?php echo '<script'; ?>
type="text/javascript">
$(document).ready(function()
{
$(".tablesorter").tablesorter();
}
);
$(document).ready(function() {
//When page loads...
$(".tab_content").hide(); //Hide all content
$("ul.tabs li:first").addClass("active").show(); //Activate first tab
$(".tab_content:first").show(); //Show first tab content
//On Click Event
$("ul.tabs li").click(function() {
$("ul.tabs li").removeClass("active"); //Remove any "active" class
$(this).addClass("active"); //Add "active" class to selected tab
$(".tab_content").hide(); //Hide all tab content
var activeTab = $(this).find("a").attr("href"); //Find the href attribute value to identify the active tab + content
$(activeTab).fadeIn(); //Fade in the active ID content
return false;
});
});
<?php echo '</script'; ?>
>
<?php echo '<script'; ?>
type="text/javascript">
$(function(){
$('.column').equalHeight();
});
<?php echo '</script'; ?>
>
</head>
<body>
<header id="header">
<hgroup>
<h1 class="site_title"><a href="index.html">后台管理面板</a></h1>
<h2 class="section_title"></h2><div class="btn_view_site"><a href="index.php">查看网站</a></div>
</hgroup>
</header> <!-- end of header bar -->
<section id="secondary_bar">
<div class="user">
<p>请在右侧登录</p>
</div>
<div class="breadcrumbs_container">
<article class="breadcrumbs"><a href="admin.php?controller=admin">后台管理中心</a> <div class="breadcrumb_divider"></div> <a class="current">登录</a></article>
</div>
</section><!-- end of secondary bar -->
<aside id="sidebar" class="column">
<h3>登录后台</h3>
<ul class="toggle">
<li class="icn_security"><a href="#">登录后台</a></li>
</ul>
</aside><!-- end of sidebar -->
<section id="main" class="column">
<h4 class="alert_info" style="width:46%">请使用您的用户名和密码在下面登录.</h4>
<form id="form1" name="form1" method="post" action="admin.php?controller=admin&method=login" onSubmit="return checkForm()">
<article class="module width_half">
<header><h3>管理员登录</h3></header>
<div class="module_content">
<fieldset>
<label>用户名</label>
<input type="text" name="username" style="width:92%;" id="username" >
</fieldset>
<fieldset>
<label>密码</label>
<input type="<PASSWORD>" name="password" style="width:92%;" id="password" >
</fieldset>
<div class="clear"></div>
</div>
<footer>
<div class="submit_link">
<input type="submit" name="submit" value="开始登录" class="alt_btn" >
</div>
</footer>
</article>
</form>
<div class="spacer"></div>
</section>
<?php echo '<script'; ?>
type="text/javascript">
/*这里用来判断用户名和密码是否为空,方便后面进行判断
function check_username(){
if(username.value==null || username.value==""){
alert("用户名不能为空,请重新输入");
}
}
function check_password(){
if(password.value==null || password.value=""){
alert("密码不能为空,请重新输入");
}
}*/
function checkForm(){
var username=document.getElementById('username').value
var password=document.getElementById('password').value
if(username==""||username==null){
alert("用户名不能为空");
return false;
}else{
if(password==""||password==null){
alert("密码不能为空");
return false;
}
return true;
}
}
<?php echo '</script'; ?>
>
</body>
</html><?php }
}
<file_sep>/framework/libs/view/smarty/smarty_config.php
<?php
/*
*这里是smarty的相关配置信息(相对路径)
*/
//设置smarty的路径,如果换成是绝对路径的话,define ('SMARTY_PATH',$_SERVER['DOCUMENT_ROOT'].'文件目录/smarty/');
define ('SMARTY_PATH',$_SERVER['DOCUMENT_ROOT'].'/news/framework/libs/view/smarty/');
//加载smarty类文件
require SMARTY_PATH.'Smarty.class.php';
//实例化一个smarty对象
$smarty =new Smarty();
//设置模板文件的路径
$smarty->template_dir = SMARTY_PATH.'templates';
//设置模板编译文件的路径
$smarty->compile_dir = SMARTY_PATH.'templates_c';
//设置配置文件的路径
$smarty->config_dir = SMARTY_PATH.'configs';
//设置缓存文件的路径
$smarty->cache_dir = SMARTY_PATH.'cache';
//这是直接实例化一个类,也可以自己写一个类继承Smarty类,比如写一个MySmarty类
/* define ('SMARTY_PATH',$_SERVER['DOCUMENT_ROOT'].'./student_manager_system/smarty/');
require SMARTY_PATH.'Smarty.class.php';
class MySmarty extends Smarty{
//添加构造方法
function MySmarty (){
$this->template_dir = SMARTY_PATH.'templates';
$this->compile_dir = SMARTY_PATH.'templates_c';
$this->config_dir = SMARTY_PATH.'configs';
$this->cache_dir = SMARTY_PATH.'cache';
}
}
*/
?><file_sep>/tpl/communal/test.php
<?php
$foodNames="糖醋尖椒,酸辣藕丁,小炒肉,";
$food_name=explode(",",$foodNames);
for($i=0;$i<count($food_name)-1;$i++){
echo $i." ".$food_name[$i]."</br>";
}
?><file_sep>/template_c/96da0ff79808d06ae494c1daef3b69d6bdd0c0a7_0.file.user.html.php
<?php
/* Smarty version 3.1.31-dev/34, created on 2017-05-18 23:38:01
from "D:\Apache24\htdocs\restaurant_system\tpl\index\user.html" */
/* @var Smarty_Internal_Template $_smarty_tpl */
if ($_smarty_tpl->_decodeProperties($_smarty_tpl, array (
'version' => '3.1.31-dev/34',
'unifunc' => 'content_591dbfd93ba402_64256827',
'has_nocache_code' => false,
'file_dependency' =>
array (
'96da0ff79808d06ae494c1daef3b69d6bdd0c0a7' =>
array (
0 => 'D:\\Apache24\\htdocs\\restaurant_system\\tpl\\index\\user.html',
1 => 1495121862,
2 => 'file',
),
),
'includes' =>
array (
'file:tpl/communal/native.html' => 1,
),
),false)) {
function content_591dbfd93ba402_64256827 (Smarty_Internal_Template $_smarty_tpl) {
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>用户基本信息</title>
<link href="http://127.0.0.1:8080/restaurant_system/tpl/image/resturant.png" rel="icon" />
<link rel="stylesheet" href="tpl/css/general.css" />
<link rel="stylesheet" href="tpl/css/bootstrap.min.css">
<?php echo '<script'; ?>
src="tpl/js/jquery.min.js"><?php echo '</script'; ?>
>
<?php echo '<script'; ?>
src="tpl/js/bootstrap.min.js"><?php echo '</script'; ?>
>
</head>
<body>
<!--this is for head-->
<div class="head">
<div class="setmarquee">
<marquee loop="-1" behavior="alternate" scrollamount="10" scrolldelay="5" onMouseOver="stop()" onMouseOut="start()"><font style="color:#666666; font-size:30px; font-family:Georgia, 'Times New Roman', Times, serif; ">不"2"餐厅</font></marquee>
</div>
<div class="setuser">
<a href="#"><?php echo $_smarty_tpl->tpl_vars['user']->value['username'];?>
</a>
<a>|</a>
<a href="index.php?controller=index&method=logout">退出</a>
</div>
</div>
<!--this is for native,all the same-->
<?php $_smarty_tpl->_subTemplateRender('file:tpl/communal/native.html', $_smarty_tpl->cache_id, $_smarty_tpl->compile_id, 0, $_smarty_tpl->cache_lifetime, array(), 0, false);
?>
<!--这是用户中心的左半边的代码-->
<div class="list-left">
<ul>
<li><span>> </span><a href="#" style="color:#0058b8;font-weight:600;">我的信息</a></li>
<li><span>> </span><a href="index.php?controller=index&method=consume_record">消费记录</a></li>
<li><span>> </span><a href="index.php?controller=index&method=find_shopping">我的购物车</a></li>
</ul>
</div>
<div class="list-right">
<span>用户中心</span>
<div class="div-hr"></div>
<table>
<tr>
<td class="td">用户名:</td>
<td class="td"><?php echo (($tmp = @$_smarty_tpl->tpl_vars['user']->value['username'])===null||$tmp==='' ? 'wangkang' : $tmp);?>
</td>
<td class="td"><button id="btn1" type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal1">修改</button></td>
</tr>
<tr>
<td class="td">密 码:</td>
<td class="td">********</td>
<td class="td"><a href="#">修改</a></td>
</tr>
<tr>
<td class="td">手机号:</td>
<td class="td"><?php echo (($tmp = @$_smarty_tpl->tpl_vars['user']->value['phoneNumber'])===null||$tmp==='' ? 'wangkang' : $tmp);?>
</td>
</tr>
<tr>
<td class="td">邮 箱:</td>
<td class="td"><?php echo (($tmp = @$_smarty_tpl->tpl_vars['user']->value['email'])===null||$tmp==='' ? 'wangkang' : $tmp);?>
</td>
<td class="td"><a href="#">修改</a></td>
</tr>
<tr>
<td class="td">积 分:</td>
<td class="td"><?php echo (($tmp = @$_smarty_tpl->tpl_vars['user']->value['point'])===null||$tmp==='' ? 0 : $tmp);?>
</td>
</tr>
</table>
</div>
<!-- ============模态框=============== -->
<!-- 修改用户名界面-->
<div class="modal fade" id="myModal1" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" >修改用户名</h4>
</div>
<div class="modal-body">
<!-- ==================== -->
<!-- 修改用户名 -->
<!-- ==================== -->
<form class="form-inline" action="index.php?controller=index&method=change_username" method="post">
<div class="form-group">
<label for="addusername">输入新用户名:</label>
<input type="text" class="form-control" name="username" id="username" placeholder="">
</div> </br></br>
<div class="form-group">
<label for="writetime">再 次 输 入:</label>
<input type="text" class="form-control" name="username2" id="username2">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
<input type="submit" class="btn btn-primary" value="确 定" onclick="check()"/>
</div>
<form/>
</div>
</div>
</div>
</div>
</body>
<?php echo '<script'; ?>
language="javascript">
//判断两次输入的用户名密码以及其他信息是否相同
<?php echo '</script'; ?>
>
</html>
<?php }
}
<file_sep>/template_c/c5e214f5b449c4b9fbf5d2741c9d0feb7580c539_0.file.detail_food.html.php
<?php
/* Smarty version 3.1.31-dev/34, created on 2017-05-23 23:10:54
from "D:\Apache24\htdocs\restaurant_system\tpl\index\detail_food.html" */
/* @var Smarty_Internal_Template $_smarty_tpl */
if ($_smarty_tpl->_decodeProperties($_smarty_tpl, array (
'version' => '3.1.31-dev/34',
'unifunc' => 'content_592450febb7921_75891678',
'has_nocache_code' => false,
'file_dependency' =>
array (
'c5e214f5b449c4b9fbf5d2741c9d0feb7580c539' =>
array (
0 => 'D:\\Apache24\\htdocs\\restaurant_system\\tpl\\index\\detail_food.html',
1 => 1495552249,
2 => 'file',
),
),
'includes' =>
array (
'file:tpl/communal/native.html' => 1,
),
),false)) {
function content_592450febb7921_75891678 (Smarty_Internal_Template $_smarty_tpl) {
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>菜单详情</title>
<link href="tpl/image/resturant.png" rel="icon" />
<link rel="stylesheet" href="tpl/css/general.css" />
<link rel="stylesheet" href="tpl/css/bootstrap.min.css">
<?php echo '<script'; ?>
src="tpl/js/jquery.min.js"><?php echo '</script'; ?>
>
<?php echo '<script'; ?>
src="tpl/js/bootstrap.min.js"><?php echo '</script'; ?>
>
</head>
<body>
<div class="head">
<div class="setmarquee">
<marquee loop="-1" behavior="alternate" scrollamount="10" scrolldelay="5" onMouseOver="stop()" onMouseOut="start()" ><font style="color:#666666; font-size:30px; font-family:Georgia, 'Times New Roman', Times, serif; ">不"2"餐厅</font></marquee> <br />
</div>
<div class="setuser">
<?php ob_start();
echo (($tmp = @$_smarty_tpl->tpl_vars['user']->value['username'])===null||$tmp==='' ? '' : $tmp);
$_prefixVariable1=ob_get_clean();
if ($_prefixVariable1 != '') {?>
<a href="#"><?php echo $_smarty_tpl->tpl_vars['user']->value['username'];?>
</a>
<a>|</a>
<a href="index.php?controller=index&method=logout">退出</a>
<?php } else { ?>
<a href="tpl/index/login.html">登录</a>
<a>|</a>
<a href="tpl/index/register.html">注册</a>
<?php }?>
</div>
</div>
<!--this is for native,all the same-->
<?php $_smarty_tpl->_subTemplateRender('file:tpl/communal/native.html', $_smarty_tpl->cache_id, $_smarty_tpl->compile_id, 0, $_smarty_tpl->cache_lifetime, array(), 0, false);
?>
<div style="display:inline; float:left;">
<div style="margin-left:100px; margin-top:50px;">
<img src="tpl/image/food/<?php echo $_smarty_tpl->tpl_vars['foods']->value['foodUrl'];?>
"
alt="通用的占位符缩略图">
</div>
<div style="margin-top:10px; margin-left:100px;">
<span><?php echo $_smarty_tpl->tpl_vars['foods']->value['foodName'];?>
</span>
<span style="margin-left:80px;">价格:<?php echo $_smarty_tpl->tpl_vars['foods']->value['foodMoney'];?>
</span>
</div>
</div>
<div style="padding-top:50px; margin-left:370px;" >
<span>做法:</span>
<div>
<?php echo $_smarty_tpl->tpl_vars['foods']->value['cooking'];?>
</div>
</div>
</body>
</html>
<?php }
}
<file_sep>/framework/pc.php
<?php
//读取include.list.php文件清单
$currentdir=dirname(__File__);
include_once($currentdir.'/include.list.php');
foreach ($paths as $path){
include_once($currentdir.'/'.$path);
}
class PC{
public static $controller;
public static $method;
public static $config;
//初始化数据库
private static function init_db(){
DB::init('mysql',self::$config['dbconfig']);
}
//初始化view
private static function init_view(){
VIEW::init('Smarty',self::$config['viewconfig']);
}
//初始化,可以指定默认的网页,以下类似
private static function init_controller(){
self::$controller =isset($_GET['controller'])?daddslashes($_GET['controller']):'index';
}
private static function init_method(){
self::$method=isset($_GET['method'])?daddslashes($_GET['method']):'index';
}
public static function run($config){
self::$config=$config;
self::init_db();
self::init_view();
self::init_controller();
self::init_method();
C(self::$controller,self::$method);
}
}
?><file_sep>/template_c/3789c09f31cbaa9aabaa4938a65e3e84f6dbddcb_0.file.head.php.php
<?php
/* Smarty version 3.1.31-dev/34, created on 2016-12-09 17:46:57
from "D:\Apache24\htdocs\restaurant_system\tpl\communal\head.php" */
/* @var Smarty_Internal_Template $_smarty_tpl */
if ($_smarty_tpl->_decodeProperties($_smarty_tpl, array (
'version' => '3.1.31-dev/34',
'unifunc' => 'content_584a7d91c5faa9_68352722',
'has_nocache_code' => false,
'file_dependency' =>
array (
'3789c09f31cbaa9aabaa4938a65e3e84f6dbddcb' =>
array (
0 => 'D:\\Apache24\\htdocs\\restaurant_system\\tpl\\communal\\head.php',
1 => 1481276809,
2 => 'file',
),
),
'includes' =>
array (
),
),false)) {
function content_584a7d91c5faa9_68352722 (Smarty_Internal_Template $_smarty_tpl) {
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>header</title>
<link rel="stylesheet" href="../css/genenal.css"/>
</head>
<body>
<div class="head">
<marquee loop="-1" behavior="alternate" scrollamount="10" scrolldelay="5" onMouseOver="stop()" onMouseOut="start()" bgcolor="#000000"><font style="color:#666666; font-size:30px; font-family:Georgia, 'Times New Roman', Times, serif; ">不"2"餐厅</font></marquee> <br />
</div>
</body>
</html>
<?php }
}
<file_sep>/framework/libs/db/mysql.class.php
<?php
/***************************以下是php操作mysql数据库的部分***********************************/
/*
*author :wangkang
*time : 2016/11/25
*/
class mysql{
public static $_con='';
/*
*报错函数
*@param string $error
*/
function __construct(){
//echo "everything is okay!"; //这是调试语句
}
function __destruct(){
mysqli_close(self::$_con);
}
function err($error){
//die有两种作用,输出和终止,相当于echo & exit的组合
die("对不起,您的操作有误,错误原因为:".$error);
}
/****************************以下是连接数据库操作***********************************/
/*
*连接数据库
*@param string $config(配置数组 array($dbhost,$dbuser,$dbpsw,$dbname,$dbcharset))
*@return bool :连接成功或者不成功
*/
function connect($config){
//将数组还原成相应的变量
extract($config);
//mysql的连接函数
$con=mysqli_connect($dbhost,$dbuser,$dbpsw,$dbname);
self::$_con=$con;
if (!$con){
$this->err(mysqli_error($con));
}else{
return $con;
}
}
/*
* 执行sql语句
*param string $sql
*return bool :返回执行成功或者失败
*/
function query($sql){
//执行sql语句
$con =self::$_con;
$query=mysqli_query($con,$sql);
if(!$query){
//error报错
$this->err($sql.":<br/>".mysqli_error($con));
}else{
return $query;
}
}
/**********************以下是查询(query)操作(列表,单条信息,指定)************************/
/*
*查询一个列表数据
*@param source:$query ,通过mysql_query执行出来的资源
*@return array:返回数组列表
*/
function findAll($query){
//mysql_fetch_array函数把查询结果转化成数组,一次转换出一行数组
while($rs=mysqli_fetch_array($query,MYSQL_ASSOC)){
$list[]=$rs;
}
//如果有了查询结果,就返回数组结果,如果查询没结果则返回空
return isset($list)?$list:"";
}
/*
*取单条数据
*
*@param source:$query ,通过mysql_query执行出来的资源
*@return array:返回单条信息数组
*/
function findOne($query){
//查询并返回一条信息
$rs=mysqli_fetch_array($query,MYSQL_ASSOC);
if($rs){
return $rs;
}else{
return false;
}
}
/*
*指定行的指定字段的值
*
*@param source:$query,sql语句通过mysqli_query执行出来的资源
*@return array :指定行的指定字段的值
*/
//默认的$row $col都是0
function findResult($query){
if($rs=mysqli_fetch_array($query)){
$count=$rs[0];
}else{
$count=0;
}
return $count;
}
/****************************以下是增加(insert)操作***********************************/
/*
*添加函数
*
*@param string $table:表名
*@param array $arr:添加数组 (包含字段和值的一维数组)
*@return id:插入的数据的主键的值
*/
function insert($table,$arr){
//首先循环遍历数组$arr
$con =self::$_con;
foreach($arr as $key=>$value){
//这个函数是对传入进来的值进行过滤操作,对系统更加的安全
$value=mysqli_real_escape_string($con,$value);
$key=mysqli_real_escape_string($con,$key);
//把$arr数组中的键名保存到$keyArr数组中
$keyArr[]=$key; //把$arr数组中的值保存到$valueArr数组中,由于key和value大多数是值,而在sql语句中insert语句中,如果值是字符串的话,要加单引号!所以进行这样格式的转换
$valueArr[]="'".$value."'";
}
//使用implode函数把数组组合成字符串,格式:implode(分隔符,数组)
$keys=implode(",",$keyArr);
$values=implode(",",$valueArr);
//将keys和values拼装成sql语句
$sql='insert into '.$table.' ('.$keys.') values ('.$values.')';
//调用之前已经写好的query方法
if($this->query($sql)){
return true;
}else{
return false;
}
//返回插入的数据的主键的值
//return mysqli_insert_id();
}
/****************************以下是修改(update)操作***********************************/
/*
*修改函数
*
*@param string $table:表名
*@param string $arr:修改数组(包含字段和值的一维数组)
*@param string $where:条件
*/
function update($table,$arr,$where){
foreach($arr as $key=>$value){
//和insert语句类似
//$value=mysqli_real_escape_string($value);
$keyAndvalueArr[]=$key."='".$value."'";
}
$keyAndvalues=implode(",",$keyAndvalueArr);
//拼装成mysql语句
$sql="update ".$table." set " .$keyAndvalues. " where " .$where;
//查询数据库
if($this->query($sql)){
return true;
}else{
return false;
}
}
/****************************以下是删除(delete)操作***********************************/
/*
*删除函数
*
*@param string $table :表名
*@param string $where:查询条件
*/
function del($table,$where){
//删除sql语句格式:delete from 表名+where条件
$sql="delete from ".$table." where ".$where;
return $this->query($sql) ;
}
}
?><file_sep>/libs/Model/authModel.class.php
<?php
/*
*这个类主要是负责以下两个功能:
*1.用户登录验证
*2.修改密码
*/
class authModel{
//用于全局变量
private $auth='';
function __construct(){
//首先判断用户是否已经登录了
if(isset($_SESSION['auth']) && !empty($_SESSION['auth'])){
$this->auth=$_SESSION['auth'];
}
}
//验证用户名和密码
public function checkuser($username,$password){
$adminobj=M('admin');
//查询结果,并将结果赋值给auth
$this->auth=$adminobj->findOne_by_uname_psw($username,$password);
if($this->auth){
$_SESSION['auth']=$this->auth;
$_SESSION['username']=$username;
return true;
}else{
return false;
}
}
function getauth(){
return $this->auth;
}
}
?><file_sep>/libs/Model/noticeModel.class.php
<?php
class noticeModel{
public $table="notice";
//得到notice的前四条数据,在首页显示标题
public function findall_notice(){
$sql='select * from '.$this->table.' order by Id DESC LIMIT 0,4';
return DB::findAll($sql);
}
//根据id查找通知
public function find_notice_by_id($id){
$sql='select * from '.$this->table.' where Id ='.$id;
return DB::findOne($sql);
}
//********************************************管理员******************
//查看所有通知
public function see_notices(){
$sql='select * from '.$this->table;
return DB::findAll($sql);
}
//删除ID对应的通知
public function delete_notice($id){
$where=" Id = ".$id;
return DB::del($this->table,$where);
}
//查看id对应的通知
public function detail_notices($id){
$sql='select * from '.$this->table.' where Id='.$id;
return DB::findOne($sql);
}
//确认修改id对应的通知
public function save_notices($arr,$id){
$where=" Id = ".$id;
return DB::update($this->table,$arr,$where);
}
//添加一个通知
public function add_notices($array){
return DB::insert($this->table,$array);
}
}
?><file_sep>/libs/Model/readme.txt
pay attention to it!
模型:(按照文件名称、函数名称以及作用来介绍)
一、adminModel.class.php:
1.findOne_by_uname_psw($username,$password):主要是通过用户名和密码来核对是否能登录成功
二、authModel.class.php:执行所有admin的逻辑操作
1.__construct():构造方法,判断用户是否已经登录过了(通过session)
2.checkuser($username,$password):验证用户名和密码(调用findOne_by_uname_psw($username,$password)方法,实现过程和具体方法的分离,更加方便明白整个流程)
三、indexModel.class.php(所有与users这张表有关的操作都在这个类里面):
1.check_by_uname_pwd():核对用户名和密码是否匹配
2.check_uname_exist():判断用户名是否已经存在了
3.add_one_user():注册的时候添加一个用户
四、userModel.class.php(这个类是来执行所有用户的逻辑操作):
1.check_by_uname_pwd():核对用户名和密码是否匹配
2.check_uname_exist():判断用户名是否已经存在了
3.add_one_user():注册的时候添加一个用
4.__construct():构造方法,判断用户是否已经登录过了(通过session)
5.getuser():取得session中的数据
<file_sep>/template_c/714f9bd099fb23d13e2ee69bf78dce82a46213b9_0.file.main.php.php
<?php
/* Smarty version 3.1.31-dev/34, created on 2017-05-11 12:52:03
from "D:\Apache24\htdocs\restaurant_system\tpl\index\main.php" */
/* @var Smarty_Internal_Template $_smarty_tpl */
if ($_smarty_tpl->_decodeProperties($_smarty_tpl, array (
'version' => '3.1.31-dev/34',
'unifunc' => 'content_5913edf330c967_09254073',
'has_nocache_code' => false,
'file_dependency' =>
array (
'714f9bd099fb23d13e2ee69bf78dce82a46213b9' =>
array (
0 => 'D:\\Apache24\\htdocs\\restaurant_system\\tpl\\index\\main.php',
1 => 1493719421,
2 => 'file',
),
),
'includes' =>
array (
'file:tpl/communal/native.html' => 1,
'file:tpl/communal/footer.html' => 1,
),
),false)) {
function content_5913edf330c967_09254073 (Smarty_Internal_Template $_smarty_tpl) {
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>不二餐厅</title>
<link href="tpl/image/resturant.png" rel="icon" />
<link rel="stylesheet" href="tpl/css/general.css" />
<link rel="stylesheet" href="tpl/css/bootstrap.min.css">
<?php echo '<script'; ?>
src="tpl/js/jquery.min.js"><?php echo '</script'; ?>
>
<?php echo '<script'; ?>
src="tpl/js/bootstrap.min.js"><?php echo '</script'; ?>
>
</head>
<body>
<!--this is for head , not be all the same-->
<div class="head">
<div class="setmarquee">
<marquee loop="-1" behavior="alternate" scrollamount="10" scrolldelay="5" onMouseOver="stop()" onMouseOut="start()" ><font style="color:#666666; font-size:30px; font-family:Georgia, 'Times New Roman', Times, serif; ">不"2"餐厅</font></marquee> <br />
</div>
<div class="setuser">
<a href="#"><?php echo $_smarty_tpl->tpl_vars['user']->value['username'];?>
</a>
<a>|</a>
<a href="index.php?controller=index&method=logout">退出</a>
</div>
</div>
<!--this is for native,all the same-->
<?php $_smarty_tpl->_subTemplateRender('file:tpl/communal/native.html', $_smarty_tpl->cache_id, $_smarty_tpl->compile_id, 0, $_smarty_tpl->cache_lifetime, array(), 0, false);
?>
<!--这里是餐厅点餐的主界面-->
<!--这里是左边的导航栏-->
<div class="container">
<div class="row">
<div class="col-xs-3" >
<ul class="nav nav-tabs nav-stacked" data-spy="affix" data-offset-top="125">
<li class="active" id="1"><a href="">川菜</a></li>
<li id="2"><a href="">鲁菜</a></li>
<li id="3"><a href="">湘菜</a></li>
<li id="4"><a href="">浙菜</a></li>
<li id="5"><a href="">东北菜</a></li>
<li id="6"><a href="">京菜</a></li>
<li id="7"><a href="">上海菜</a></li>
</ul>
</div>
</div>
<div class="row">
<div class=".col-xs-4">
</div>
<div class=".col-xs-4">
</div>
<div class=".col-xs-4">
</div>
</div>
</div>
<input type="button" value="55555" onclick="test();"/>
<!--这里是页脚部分-->
<?php $_smarty_tpl->_subTemplateRender('file:tpl/communal/footer.html', $_smarty_tpl->cache_id, $_smarty_tpl->compile_id, 0, $_smarty_tpl->cache_lifetime, array(), 0, false);
?>
</body>
</html>
<?php echo '<script'; ?>
language="javascript">
document.getElementById("1").click(){
alert('45454545454545');
}
<?php echo '</script'; ?>
><?php }
}
<file_sep>/libs/Controller/readme.txt
pay attention to it!
这个文件夹是属于控制器:
一、adminController.class.php:专门负责管理员的登录
1.__construct():构造方法,通过session判断当前用户是否已经登录过,如果没登录过,就进入登录界面
2.index():跳转到admin/index.php文件中
3.login():登录界面,首先判断是通过网址到登录界面,还是在登录界面进行账号密码登录,前者的话就直接到admin/login.html文件中,后者的话会执行登录操作,调用check_uname_psw($username,$password)方法,不为空时调用authModel.class.php中的checkuser($username, $password)方法,判断是否用户名和密码匹配
4.logout():登出,销毁session中存储的用户数据
5.check_uname_psw($username,$password):判断用户名或者密码是否已经填写
6.showmessage($info, $url):弹框输出$info信息,并跳转到$url
二、indexController.class.php:
1.index():这个方法是用来显示网站的首页
2.selectOne():通过session来判断,用户是否已经登录过了,登录过了就进入用户的界面user.html,没有登录过,就到登录的界面
3.login():用户登录的方法
4.verifyUname():核对用户名,是否已经注册过了的
5.register():用户注册时调用
6.showmessage():显示信息,并跳转到相应的界
<file_sep>/libs/Model/shoppingModel.class.php
<?php
class shoppingModel{
/*
*这个表主要是所有与shoppong表有关的操作,包括以下操作:
*1.用户加入购物车的操作
*2.用户查询购物车
*/
public $table='shopping';
//向shopping表中添加数据
public function add_shopping($arr){
return DB::insert($this->table,$arr);
}
//通过foodname查找所有数据
public function find_shopping($name){
$sql='select * from '.$this->table.' where username = "'.$name.'"';
return DB::findAll($sql);
}
//通过Id 查找这个shopping记录的信息
public function find_shopping_by_id($id){
$sql='select * from '.$this->table.' where Id ='.$id;
return DB::findOne($sql);
}
//当付款成功以后通过id删除shopping表这条记录
public function delete_shopping($id){
$where=" Id =".$id;
return DB::del($this->table,$where);
}
}
?><file_sep>/admin.php
<?php
/*这是一个入口文件*/
//防止乱码
header("Content-type:text/html;charset=utf-8");
session_start();
//引入配置文件
require_once('config.php');
require_once('framework/pc.php');
PC::run($config);
?><file_sep>/libs/Model/adminModel.class.php
<?php
class adminModel{
/*
这个Model是专门处理所有有关于admin的任何操作:
1.管理员登录
*/
public $_table='admin';
//通过用户名和密码查询结果
public function findOne_by_uname_psw($username,$password){
$sql='select * from '.$this->_table.' where
username = "'.$username.'" and password = "'.$password.'"';
return DB::findOne($sql);
}
}
?><file_sep>/libs/Model/indexModel.class.php
<?php
/*
这个类是用来处理所有有关于表users的操作:
1.用户登录时进行用户名和密码的核对
2.用户注册时进行增加操作
3.用户修改信息
4.判断用户名是否已经存在了
5.管理员查看所有的用户
6.删除用户
*/
class indexModel{
public $table='users';
//1.核对用户的用户名和密码
public function check_by_uname_pwd($username,$password){
$sql='select * from '.$this->table.' where username = "'.$username.'" and password="'.$password.'" ';
return DB::findOne($sql);
}
//2.用户注册,一条插入语句
//@param: 二维数组
public function add_one_user($array){
return DB::insert($this->table,$array);
}
//3.更改用户名,update语句
public function change_username($array,$where){
return DB::update($this->table,$array,$where);
}
//4.用户注册时,判断用户名是否已经被注册了
public function check_uname_exist($username){
$sql='select * from '.$this->table.' where username ="'.$username.'"';
return DB::findOne($sql);
}
//5.管理员查看所有的用户
public function find_all_user(){
$sql='select * from '.$this->table;
return DB::findAll($sql);
}
//6.管理员删除用户
public function delete_user($id){
$where=' Id = '.$id;
return DB::del($this->table,$where);
}
//7.用户增加积分
public function add_point($name,$point){
$sql='update '.$this->table.' set point = point+'.$point.' where username = "'.$name.'"';
return DB::query($sql);
}
//更新用户积分后,查看用户信息
public function user_info($name){
$sql='select * from '.$this->table.' where username = "'.$name.'"';
return DB::findOne($sql);
}
}
?> | e6931453562d5d0f5d1e4ebe2bed79f59251e3c7 | [
"Markdown",
"Text",
"PHP"
]
| 46 | PHP | CharmWang/restaurant_system | 35f40f6428759aec00f3c5bd4fa38d8e9388377a | 8089e7eb75d431814b9d737e3778fbfd9b27df78 |
refs/heads/master | <file_sep>mongoengine==0.15.0
pytest==3.4.0
falcon==1.4.1
waitress==1.1.0
<file_sep>def isEmpty(data):
for key,value in data.items():
if not value:
return key
return None<file_sep>import falcon
import json
import common
from models import Service, Configuration, WSDL_URLS
class ConfigResource(object):
def on_get(self,request,response):
# Return 400 if <tenant> query string does not exist
if not request.get_param("tenant"):
raise falcon.HTTPBadRequest('Argument <tenant> is missing')
# Return 400 if <integration_type> query string does not exist
if not request.get_param("integration_type"):
raise falcon.HTTPBadRequest('Argument <integration_type> is missing')
tenant = request.get_param("tenant")
integration_type = request.get_param("integration_type")
# Query data from database
result = Service.objects(tenant__iexact=tenant, integration_type__iexact=integration_type).exclude('id')
# Return bad request if no data
if result.count() < 1:
raise falcon.HTTPBadRequest('No result')
# Response
response.status = falcon.HTTP_200
response.body = result.to_json()
def on_post(self,request,response):
# Get raw data from request body
try:
raw_data = request.stream.read()
except Exception as ex:
raise falcon.HTTPBadRequest(ex.message)
# Jsonify the raw data
try:
data = json.loads(raw_data,encoding='utf-8')
except ValueError:
raise falcon.HTTPError(falcon.HTTP_400,'Unrecognized JSON','Unable to decode request body')
# Return 404 if <tenant> does not exist
if not data['tenant']:
response.status = falcon.HTTP_404
return
# Return 404 if <integration_type> does not exist
if not data['integration_type']:
response.status = falcon.HTTP_404
return
# Validate data
emptyValueKey = common.isEmpty(data['configuration'])
if emptyValueKey:
raise falcon.HTTPBadRequest('{} is missing'.format(emptyValueKey))
return
emptyValueKey = common.isEmpty(data['configuration']['wsdl_urls'])
if emptyValueKey:
raise falcon.HTTPBadRequest('{} is missing'.format(emptyValueKey))
return
# Query data from database
result = Service.objects(tenant__iexact=data['tenant'], integration_type__iexact=data['integration_type']).exclude('id')
## No record found - insert new record. Else, update the existing record
if result.count() < 1:
new_config = Service(**data)
new_config.save()
else:
result.modify(upsert=True, new=True, set__configuration=data['configuration'])
# Response
response.status = falcon.HTTP_200
response.body = result.to_json()
def create():
app = falcon.API()
config = ConfigResource()
app.add_route('/config',config)
return app
app = create()
<file_sep>from mongoengine import *
connect('configapi')
class WSDL_URLS(EmbeddedDocument):
session_url = StringField(required=True)
booking_url = StringField(required=True)
class Configuration(EmbeddedDocument):
username = StringField(required=True)
password = StringField(required=True)
wsdl_urls = EmbeddedDocumentField(WSDL_URLS)
class Service(Document):
tenant = StringField(required=True)
integration_type = StringField(required=True)
configuration = EmbeddedDocumentField(Configuration)
<file_sep># Python : Falcon RESTFul API - MongoEngine - MongoDB - PyTest - Waitress
## To start API server,
1. Install the required dependencies from **requirements.txt**
```
pip install -r requirements.txt
```
2. Start MongoDB server. Update connection string in **/src/models.py** if needed
```Python
connect('configapi') # Modify this if needed. Refer to Falcon's documentation
```
3. Navigate to **/src** and start **Waitress** server (for Windows only)
```
cd src
waitress-serve --port=8000 app:app
```
4. Browse the URL using browser or Postman Chrome App
## To run test using PyTest
1. Navigate to **/src** and run **Pytest**. PyTest will run **test_api.py** automatically
```
cd src
pytest
```
## To generate coverage report with PyTest
1. Install **pytest-cov**
```
pip install pytest-cov
```
2. Navigate to **/src** and run PyTest as follow
```
cd src
pytest --cov=app
```
<file_sep>from falcon import testing
import pytest
import app
data = {"tenant": "acme_test", "integration_type": "flight-information-system", "configuration": { "username": "acme_user", "password": "<PASSWORD>", "wsdl_urls": { "session_url": "https://session.manager.svc", "booking_url": "https://booking.manager.svc"}}}
@pytest.fixture()
def client():
return testing.TestClient(app.create())
def test_post_config(client):
result = client.simulate_post('/config',json=data)
print(result)
assert result.json[0] == data
def test_get_config(client):
params = {"tenant":"acme_test","integration_type":"flight-information-system"}
result = client.simulate_get('/config',params=params)
assert result.json[0] == data
#def test_delete_config | f0e28824cd24cd670d717956796733f8a787f606 | [
"Markdown",
"Python",
"Text"
]
| 6 | Text | clho40/python-falcon-api | a75d7999b8ade018bcee757c483443ea658df98a | 9d16077ab5618d1e35c9353130ccd189bc766041 |
refs/heads/master | <file_sep>import sys, os
from random import shuffle
from random import seed
from random import randint
INT_MIN = 1
INT_MAX = 50000
LEN_TEXT = 247
# helper function
def usage():
print "This program aims at generating a dataset of random value for CS386D Lab 01 and 02."
print "Usage: "
print " python generator.py [num_rows] [out_file]"
def generate_random_integer(lower=INT_MIN, upper=INT_MAX):
return randint(lower, upper)
def generate_random_text(length=LEN_TEXT):
chars = [ chr(randint(48,90)) for i in range(length) ]
result = "".join(chars)
result = result.replace("\n", "n")
result = result.replace(",", "c")
result = result.replace('''"''', "'")
return result
def quote(word):
return '''"''' + str(word) + '''"'''
def random_generate(v1fout, num_rows):
for v1key in range(num_rows):
# generate random values for each columns
ht = generate_random_integer(0, 99999)
tt = generate_random_integer(0, 9999)
ot = generate_random_integer(0, 999)
filler = generate_random_text()
# generate strings for output
v1instance = (v1key, ht, tt, ot, filler)
v1string = ",".join(quote(val) for val in v1instance)
# write to out file
v1fout.write(v1string)
v1fout.write("\r\n")
# update v1key
v1key += 1
# main entrance
if __name__ == "__main__":
# examine arguments
nargs = len(sys.argv)
if nargs != 3:
usage()
sys.exit(-1)
# parse arguments
num_rows = int(sys.argv[1])
v1ofname = sys.argv[2]
# generate data of random values and write to <ofname>
v1fout = open(v1ofname, "w+")
seed(1)
data = random_generate(v1fout, num_rows)
v1fout.close()
<file_sep>for i in $(seq 1 15)
do
echo "Processing queries/$i"
x=$(cat queries/$i)
echo "$x"
mysql LAB02 --execute="$x" #> results/$i.txt
echo ""
done
<file_sep>mysql -u root -p --local-infile
| e1c5ba92391fe3ae29253393e729deb5dd9e60cd | [
"Python",
"Shell"
]
| 3 | Python | xinlin192/Lab02CS386D | 49b05cfaf7598c80687eb3ec0c00a4bcf1ccef76 | a10a475f7a4a5dd907419890d50bb14f0ec0dcbe |
refs/heads/master | <repo_name>Erin-Renee/SDPre<file_sep>/JavaTheHardWay/EnterPIN.java
import java.util.Scanner;
public class EnterPIN {
public static void main( String[] args ) {
Scanner keyboard = new Scanner(System.in);
int pin, entry;
pin = 12345;
System.out.println("WELCOME TO THE BANK OF JAVA.");
System.out.print("ENTER YOUR PIN: ");
entry = keyboard.nextInt();
while ( entry != pin ) { //while loops!
System.out.println("\nINCORRECT PIN. TRY AGAIN.");
System.out.print("ENTER YOUR PIN: ");
entry = keyboard.nextInt();
}
System.out.println("\nPIN ACCEPTED. YOUR ACCOUNT BALANCE IS $425.17");
}
}
/*
while loops are similar to an if statement. THey both hava a condition in the
parenthesis that is checked to see if it is true or false. If it is false, they both will skip all the code in the body.
The difference is that if statements are true will execute all of the code in curly brackets only once.
While loops will execute true statements then go back up to check it again over and over again until it eventually is false.
The wile loop will then move on to the rest of the code.
While loops prevent you from having to repeditively type out code....
*/
<file_sep>/JavaTheHardWay/ThereAndBackAgain.java
public class ThereAndBackAgain { //Ex 33: Calling a Function
public static void main( String[] args ) {
System.out.println( "Here." );
erebor();
System.out.println( "Back first time." );
//erebor();
System.out.println( "Back second time." );
} //end of body "main"
public static void erebor() { //function called erebor is defined
System.out.println( "There." );
} //end of body "erebor"
}
/*
STUDY DRILLS
1. what happens when you remove the parenthesis at the end of the first function
call on line 4?
the program will not compile. Without the parentesis it is no longer a function
and is a variable that is not defined.
2. When you take out the function on line 6 "erebor" it no longer prints "there".
The original program runs:
Here.
There.
back first time.
there.
back second time.
edited version runs:
Here.
There.
back first time.
back second time.
*/
<file_sep>/JavaTheHardWay/CollegeAdmissionExpanded.java
import static java.lang.System.*;
import java.util.Scanner;
public class CollegeAdmissionExpanded {
public static void main( String[] args ) {
Scanner keyboard = new Scanner(System.in);
int math;
out.println( "Welcome to the UT Austin College Admissions Interface!" );
out.print( "Please enter your SAT math score (200-800): " );
math = keyboard.nextInt();
out.print( "Admittance status: " );
if ( math >= 790 ) {
out.print( "CERTAIN " );
}
else {
if ( math >= 710 ) {
out.print( "SAFE " );
}
else {
if ( math >= 580 ) {
out.print( "PROBABLE " );
}
else {
if ( math >= 500 ) {
out.print( "UNCERTAIN " );
}
else {
if ( math >= 390 ) {
out.print( "UNLIKELY " );
}
else { // below 390 DENIED
out.print( "DENIED " );
}
}
}
}
}
out.println();
}
}
/* import static java.lang.System.*;
-shortcut that imports everything from inside the class
java.lang.System into the current namespace. It is not needed to name System
in System.out.print() with this import.
Curly brackets are omitted because if statements are only one line of code,
and because the if statements are in order.
Drill #1: if you remove all of the elses except for the last one, it will
print all of the if statements.
Drill #2: Moving lines 23 and 24 to the line between 16 and 17 caused
the program to almost always print the unlikely if statement. Putting the if
statements out of order caused the system to pring unlikely even for scores
that should have caused the program to print safe, probable, and uncertain.
Drill #3:
*/
/* ORIGINAL
import static java.lang.System.*;
import java.util.Scanner;
public class CollegeAdmission {
public static void main( String[] args ) {
Scanner keyboard = new Scanner(System.in);
int math;
out.println( "Welcome to the UT Austin College Admissions Interface!" );
out.print( "Please enter your SAT math score (200-800): " );
math = keyboard.nextInt();
out.print( "Admittance status: " );
if ( math >= 790 )
out.print( "CERTAIN " );
else if ( math >= 390 )
out.print( "UNLIKELY " );
else if ( math >= 710 )
out.print( "SAFE " );
else if ( math >= 580 )
out.print( "PROBABLE " );
else if ( math >= 500 )
out.print( "UNCERTAIN " );
else // below 390 DENIED
out.print( "DENIED " );
out.println();
}
}
*/
<file_sep>/JavaTheHardWay/PrintingChoicesEscapes.java
public class PrintingChoicesEscapes {
public static void main( String[] args ) {
System.out.println( "Alpha\nBravo\nCharlie\nDelta\n\nEchoFoxtrotGolf\nHotel\nIndia\n\nI am learning Java the Hard Way!\n\n" );
}
}
// Exercise 4: Escape Sequences and comments Study Drill #2
// rewrite exercise 3 so that it has identitcal looking output but only uses a single println()
<file_sep>/JavaTheHardWay/GenderTitles.java
import java.util.Scanner;
public class GenderTitles {
public static void main( String[] args ) {
Scanner keyboard = new Scanner(System.in);
String title;
System.out.print( "First name: " );
String first = keyboard.next();
System.out.print( "Last name: " );
String last = keyboard.next();
System.out.print( "Gender (M/F): " );
String gender = keyboard.next();
System.out.print( "Age: " );
int age = keyboard.nextInt();
if ( age < 20 ) {
title = first;
}
else {
if ( gender.equals("F") ) {
System.out.print( "Are you married, "+first+"? (Y/N): " );
String married = keyboard.next();
if ( married.equals("Y") ) {
title = "Mrs.";
}
else {
title = "Ms.";
}
}
else {
title = "Mr.";
}
}
System.out.println( "\n" + title + " " + last );
}
}
/*
Study Drill # 1:
if you change the else on line 31 to an if statement, the human could type
something besides "M" or "F" and neither if statement would be true. With
the else statement, title has a value no matter what path is taken.You keep
the if statement you can fix the error by initalizing totle right when you declare it.
*/
/*
instead of declaring variables at the beginning, they are defined
on the same line the value was put into them for the first time. (except title0)
You do not have to declare a variable until you're ready to use it.
Scope - refers to the places in your program where a variable is visible.
Title was still declared at the beginning of the program instead of on line 18 because
if put on line 18 it would only be seen in that body and not in scope for the rest of
the program.
It is helpful to declare a variable on the same line where its initial value is given
if you only want it used in that specific body and not the rest of the program.
*/
<file_sep>/JavaTheHardWay/GasolineReceipt.java
public class GasolineReceipt {
public static void main( String[] args ) {
System.out.println( "+-----------------------+" );
System.out.println( "| |" );
System.out.println( "| CORNER STORE |" );
System.out.println( "| |" );
System.out.println( "| 2019-10-23 04:38PM |" );
System.out.println( "| |" );
System.out.println( "| Gallons: 12.870 |" );
System.out.println( "| Price/Gallon: $ 2.250 |" );
System.out.println( "| |" );
System.out.println( "| Fuel total: $ 28.957 |" );
System.out.println( "| |" );
System.out.println( "+-----------------------+" );
}
}
<file_sep>/JavaTheHardWay/ThirtyDays.java
import java.util.Scanner;
public class ThirtyDays {
public static void main( String[] args ) {
Scanner keyboard = new Scanner(System.in);
int month, days;
String monthName;
System.out.print( "Which month? (1-12) " );
month = keyboard.nextInt();
switch(month) { //not allowed to declare any variables inside the switch statement.
case 1: monthName = "January"; //the case, the value that the variable in parenthesis (month) might equal, and code....
break; //break marks the end of a case
case 2: monthName = "February";
break;
case 3: monthName = "March";
break;
case 4: monthName = "April";
break;
case 5: monthName = "May";
break;
case 6: monthName = "June";
break;
case 7: monthName = "July";
break;
case 8: monthName = "August";
break;
case 9: monthName = "September";
break;
case 10: monthName = "October";
break;
case 11: monthName = "November";
break;
case 12: monthName = "December";
break;
default: monthName = "error"; //runs if none of the cases match.
}
/* All months hath 30 days except 5 months. September April, June and November
hath 30 days, and February hath 28 days.
*/
switch(month) {
case 9:
case 4:
case 6:
case 11: days = 30;
break;
case 2: days = 28;
break;
default: days = 31;
}
System.out.println( days + " days hath " + monthName );
}
}
/* When a switch statement runs the computer figures out the current value of
the variable inside the parenthesis. Once it finds a match, it runs the code until the break.
*/
<file_sep>/JavaTheHardWay/BMICalculator.java
import java.util.Scanner;
public class BMICalculator {
public static void main( String[] args ) {
Scanner keyboard = new Scanner(System.in);
double m, kg, lbs, bmi, ft, a, b, x, y, z, in;
a = 0.0254;
x = 12;
b = 2.20;
System.out.println( "How tall are you? Please enter your height in feet, then enter the inches separately." );
System.out.print( "your height in feet: " );
ft = keyboard.nextDouble();
System.out.print( "your height in inches: " );
in = keyboard.nextDouble();
y = (ft*x);
z = in + y;
m = z*a;
System.out.print( "your weight in pounds: " );
lbs = keyboard.nextDouble();
kg = (lbs /b);
bmi = kg / (m*m);
System.out.println( "Your BMI is " + bmi );
}
}
<file_sep>/Labs/Objective2Lab3.java
public class Objective2Lab3 {
public static void main(String[] args) {
String food1, food2, food3, first, second, third;
food1 = "Cherries";
food2 = "Chocolate";
food3 = "Bananas";
first = "1. ";
second = "2. ";
third = "3. ";
System.out.println( "My Favorite Foods Are:");
System.out.println( first + food1 );
System.out.println( second + food2 );
System.out.println( third + food3 );
}
}
<file_sep>/Labs/Objective1Lab2.java
public class Objective1Lab2{
public static void main(String[] args){
System.out.println("<NAME>");
System.out.println("31");
}
}
| 32973bb33cf76bdd61823d084dc276361c86899e | [
"Java"
]
| 10 | Java | Erin-Renee/SDPre | 1fdfdaa0f2623efd8c82d85c4b3f56f093c4cd55 | 365acb3b8b189acb9e4cdf0b027e7689d3f295bb |
refs/heads/master | <repo_name>kalilmvp/spring-boot-project<file_sep>/src/main/resources/db/migration/postgres/V2__insert_tb_empresa.sql
INSERT into tb_empresa (razao_social, data_atualizacao) values ('primeira empresa', '1994-12-29');<file_sep>/src/main/java/ao/com/spring/dto/EmpresaDTO.java
package ao.com.spring.dto;
import java.util.Date;
import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.NotEmpty;
public class EmpresaDTO {
private Long id;
private String razaoSocial;
private Date dataAtualizacao;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
@NotEmpty(message = "Razão Social deve sempre estar preenchida")
@Length(min = 5, max = 200, message = "Razão social deve conter entre 5 e 200 caracteres")
public String getRazaoSocial() {
return razaoSocial;
}
public void setRazaoSocial(String razaoSocial) {
this.razaoSocial = razaoSocial;
}
public Date getDataAtualizacao() {
return dataAtualizacao;
}
public void setDataAtualizacao(Date dataAtualizacao) {
this.dataAtualizacao = dataAtualizacao;
}
}<file_sep>/README.md
[](https://travis-ci.org/kalilmvp/spring-boot-project)
# spring-boot-project
Spring Boot Project
<file_sep>/src/main/resources/db/migration/postgres/V1__create_table.sql
CREATE TABLE tb_empresa(
id SERIAL,
razao_social VARCHAR(100),
data_atualizacao DATE
); | b608b29c770c492f6bcc66a98129c12c0ea62c3b | [
"Java",
"SQL",
"Markdown"
]
| 4 | SQL | kalilmvp/spring-boot-project | 4c04316732b297af94fee34c9e3dfc4bc88bc293 | ed1bb871f84e4ffef8adc2e568b719ad429664af |
refs/heads/master | <file_sep># Pylint seems to be looking at python2.7's PySimpleGUI libraries so we need the following:
# pylint: disable=E1101 # Module 'PySimpleGUIQt' has no 'XXXX' member (no-member)
""" A plugin to support Grbl 1.1 controller hardware. """
from typing import List, Any, Optional, Deque, Tuple, Dict
import time
from queue import Queue, Empty
from collections import deque
from pygcode import GCode, Block
from PySimpleGUI_loader import sg
from definitions import ConnectionState
from controllers._controller_serial_base import _SerialControllerBase
from controllers.state_machine import StateMachineGrbl as State
REPORT_INTERVAL = 1.0 # seconds
SERIAL_INTERVAL = 0.02 # seconds
RX_BUFFER_SIZE = 127
def sort_gcode(block: Block) -> str:
""" Reorder gcode to a manner that is friendly to clients.
eg: Feed rate should proceed "G01" and "G00". """
return_val = ""
for gcode in sorted(block.gcodes):
return_val += str(gcode) + " "
return return_val
#class Test:
# pass
class Grbl1p1Controller(_SerialControllerBase):
""" A plugin to support Grbl 1.1 controller hardware. """
# Set this True for any derived class that is to be used as a plugin.
is_valid_plugin = True
# GRBL1.1 only supports the following subset of gcode.
# https://github.com/gnea/grbl/wiki/Grbl-v1.1-Commands
SUPPORTED_GCODE = set((
b"G00", b"G01", b"G02", b"G03", b"G38.2", b"G38.3", b"G38.4", b"G38.5", b"G80",
b"G54", b"G55", b"G56", b"G57", b"G58", b"G59",
b"G17", b"G18", b"G19",
b"G90", b"G91",
b"G91.1",
b"G93", b"G94",
b"G20", b"G21",
b"G40",
b"G43.1", b"G49",
b"M00", b"M01", b"M02", b"M30",
b"M03", b"M04", b"M05",
b"M07", b"M08", b"M09",
b"G04", b"G10 L2", b"G10 L20", b"G28", b"G30", b"G28.1", b"G30.1",
b"G53", b"G92", b"G92.1",
b"F", b"T", b"S"
))
SLOWCOMMANDS = (b"G10L2", b"G10L20", b"G28.1", b"G30.1", b"$x=", b"$I=",
b"$Nx=", b"$RST=", b"G54", b"G55", b"G56", b"G57", b"G58",
b"G59", b"G28", b"G30", b"$$", b"$I", b"$N", b"$#")
def __init__(self, label: str = "grbl1.1", _time = time) -> None:
# pylint: disable=E1136 # Value 'Queue' is unsubscriptable
super().__init__(label)
# Allow replacing with a mock version when testing.
self._time: Any = _time
# State machine to track current GRBL state.
self.state: State = State(self.publish_from_here)
# Populate with GRBL commands that are processed immediately and don't need queued.
self._command_immediate: Queue[bytes] = Queue()
# Populate with GRBL commands that are processed sequentially.
self._command_streaming: Queue[bytes] = Queue()
# Data received from GRBL that does not need processed immediately.
self._received_data: Queue[bytes] = Queue()
self._partial_read: bytes = b""
self._last_write: float = 0
self._error_count: int = 0
self._ok_count: int = 0
self._send_buf_lens: Deque[int] = deque()
self._send_buf_actns: Deque[Tuple[bytes, Any]] = deque()
self.running_jog: bool = False
self.running_gcode: bool = False
self.running_mode_at: float = self._time.time()
self.first_receive: bool = True
# Certain gcode commands write to EPROM which disabled interrupts which
# would interfere with serial IO. When one of these commands is executed we
# should pause before continuing with serial IO.
self.flush_before_continue = False
def _complete_before_continue(self, command: bytes) -> bool:
""" Determine if we should allow current command to finish before
starting next one.
Certain gcode commands write to EPROM which disabled interrupts which
would interfere with serial IO. When one of these commands is executed we
should pause before continuing with serial IO.
"""
for slow_command in self.SLOWCOMMANDS:
if slow_command in command:
return True
return False
def gui_layout_view(self) -> List[List[sg.Element]]:
""" Layout information for the PySimpleGUI interface. """
components: Dict[str, Any] = self.gui_layout_components()
layout: List[Any] = [
components["view_label"],
components["view_serial_port"],
[sg.Multiline(default_text="Machine state",
size=(60, 10),
key=self.key_gen("state"),
autoscroll=True,
disabled=True,
),],
components["view_connection"],
components["view_buttons"],
]
return layout
def gui_layout_edit(self) -> List[List[sg.Element]]:
""" Layout information for the PySimpleGUI interface. """
components = self.gui_layout_components()
layout = [
components["edit_label"],
components["edit_serial_port"],
components["edit_buttons"],
]
return layout
def parse_incoming(self, incoming: Optional[bytes]) -> None:
""" Process data received from serial port.
Handles urgent updates here and puts the rest in _received_data buffer for
later processing. """
if incoming is None:
incoming = b""
if self._partial_read:
incoming = self._partial_read + incoming
if not incoming:
return
pos = incoming.find(b"\r\n")
if pos < 0:
self._partial_read = incoming
return
tmp_incoming = incoming[:pos + 2]
self._partial_read = incoming[pos + 2:]
incoming = tmp_incoming
incoming = incoming.strip()
if not incoming:
return
# Handle time critical responses here. Otherwise defer to main thread.
if incoming.startswith(b"error:"):
self._incoming_error(incoming)
self._received_data.put(incoming)
elif incoming.startswith(b"ok"):
self._incoming_ok()
else:
self._received_data.put(incoming)
if self.first_receive:
# Since we are definitely connected, let's request a status report.
self.first_receive = False
# Request a report on the modal state of the GRBL controller.
self._command_streaming.put(b"$G")
# Grbl settings report.
self._command_streaming.put(b"$$")
def _incoming_error(self, incoming: bytes) -> None:
""" Called when GRBL returns an "error:". """
self._error_count += 1
self._send_buf_lens.popleft()
action = self._send_buf_actns.popleft()
print("error: '%s' due to '%s' " % (incoming.decode("utf-8"), action[0].decode("utf-8")))
# Feed Hold:
self._command_immediate.put(b"!")
def _incoming_ok(self) -> None:
""" Called when GRBL returns an "ok". """
if not self._send_buf_lens:
return
self._ok_count += 1
self._send_buf_lens.popleft()
action = self._send_buf_actns.popleft()
print("'ok' acknowledges: %s" % action[0].decode("utf-8"), type(action[1]))
if isinstance(action[1], GCode):
self._received_data.put(b"[sentGcode:%s]" % \
str(action[1].modal_copy()).encode("utf-8"))
def _write_immediate(self) -> bool:
""" Write entries in the _command_immediate buffer to serial port. """
task = None
try:
task = self._command_immediate.get(block=False)
except Empty:
return False
#print("_write_immediate", task)
return self._serial_write(task)
def _pop_task(self) -> Tuple[Any, bytes, bytes]:
""" Pop a task from the command queue. """
task = None
try:
task = self._command_streaming.get(block=False)
except Empty:
return (None, b"", b"")
task_string = task
if isinstance(task, Block):
task_string = str(task).encode("utf-8")
task_string = task_string.strip()
task_string_human = task_string
task_string = task_string.replace(b" ", b"")
return (task, task_string, task_string_human)
def _write_streaming(self) -> bool:
""" Write entries in the _command_streaming buffer to serial port. """
# GRBL can not queue gcode commands while jogging
# and cannot queue jog commands while executing gcode.
assert not (self.running_gcode and self.running_jog), \
"Invalid state: Jog and Gcode modes active at same time."
if self.flush_before_continue:
if sum(self._send_buf_lens) > 0:
# Currently processing a task that must be completed before
# moving on to the next in the queue.
return False
self.flush_before_continue = False
if sum(self._send_buf_lens) >= RX_BUFFER_SIZE:
# Input buffer full. Come back later.
return False
if self.state.machine_state in (b"Idle", b"ClearJog") and \
self._time.time() - self.running_mode_at > 2 * REPORT_INTERVAL and \
(self.running_gcode or self.running_jog):
# print("!!! Timeout !!! running_gcode: %s running_jog: %s" % \
# (self.running_gcode, self.running_jog))
self.running_gcode = False
self.running_jog = False
task, task_string, task_string_human = self._pop_task()
if not task:
return False
# print("_write_streaming: %s running_jog: %s running_gcode: %s" %
# (task_string.decode('utf-8'), self.running_jog, self.running_gcode))
jog = task_string.startswith(b"$J=")
if jog:
if self.running_gcode:
self.publish(
"user_feedback:command_state",
"Can't start jog while performing gcode for: %s\n" %
task_string_human.decode('utf-8'))
print("Can't start jog while performing gcode")
# Since the Jog command has already been de-queued it is lost.
# This is appropriate behaviour.
return False
self.running_jog = True
self.running_mode_at = self._time.time()
else:
if self.running_jog:
self.publish(
"user_feedback:command_state",
"Cancelling active Jog action to perform Gcode action for: %s\n" \
% task_string_human.decode('utf-8'))
self.cancel_jog()
self.running_gcode = True
self.running_mode_at = self._time.time()
if self._complete_before_continue(task_string):
# The task about to be processes writes to EPROM or does something
# else non-standard with the microcontroller.
# No further tasks should be executed until this task has been
# completed.
# See "EEPROM Issues" in
# https://github.com/gnea/grbl/wiki/Grbl-v1.1-Interface
self.flush_before_continue = True
if self._serial_write(task_string + b"\n"):
self._send_buf_lens.append(len(task_string) + 1)
self._send_buf_actns.append((task_string_human, task))
return True
return False
def _periodic_io(self) -> None:
""" Read from and write to serial port.
Called from a separate thread.
Blocks while serial port remains connected. """
while self.connection_status is ConnectionState.CONNECTED:
# Read
read = self._serial_read()
while read or (b"\r\n" in self._partial_read):
self.parse_incoming(read)
read = self._serial_read()
#Write
if not self._write_immediate():
self._write_streaming()
# Request status update periodically.
if self._last_write < self._time.time() - REPORT_INTERVAL:
self._command_immediate.put(b"?")
self._last_write = self._time.time()
self._time.sleep(SERIAL_INTERVAL)
if self.testing:
break
def _handle_gcode(self, gcode_block: Block) -> None:
""" Handler for the "command:gcode" event. """
valid_gcode = True
if not self.is_gcode_supported(gcode_block):
# Unsupported gcode.
# TODO: Need a way of raising an error.
print("Unsupported gcode: %s" % str(gcode_block))
# GRBL feed hold.
self._command_immediate.put(b"!")
valid_gcode = False
if valid_gcode:
self._command_streaming.put(str(sort_gcode(gcode_block)).encode("utf-8"))
def _handle_move_absolute(self,
x: Optional[float] = None, # pylint: disable=C0103
y: Optional[float] = None, # pylint: disable=C0103
z: Optional[float] = None, # pylint: disable=C0103
f: Optional[float] = None # pylint: disable=C0103
) -> None:
""" Handler for the "command:move_absolute" event.
Move machine head to specified coordinates. """
jog_command_string = b"$J=G90 "
if f is None:
# Make feed very large and allow Grbls maximum feedrate to apply.
f = 10000000
jog_command_string += b"F%s " % str(f).encode("utf-8")
if x is not None:
jog_command_string += b"X%s " % str(x).encode("utf-8")
if y is not None:
jog_command_string += b"Y%s " % str(y).encode("utf-8")
if z is not None:
jog_command_string += b"Z%s " % str(z).encode("utf-8")
self._command_streaming.put(jog_command_string)
def _handle_move_relative(self,
x: Optional[float] = None, # pylint: disable=C0103
y: Optional[float] = None, # pylint: disable=C0103
z: Optional[float] = None, # pylint: disable=C0103
f: Optional[float] = None # pylint: disable=C0103
) -> None:
""" Handler for the "command:move_relative" event.
Move machine head to specified coordinates. """
jog_command_string = b"$J=G91 "
if f is None:
# Make feed very large and allow Grbls maximum feedrate to apply.
f = 10000000
jog_command_string += b"F%s " % str(f).encode("utf-8")
if x is not None:
jog_command_string += b"X%s " % str(x).encode("utf-8")
if y is not None:
jog_command_string += b"Y%s " % str(y).encode("utf-8")
if z is not None:
jog_command_string += b"Z%s " % str(z).encode("utf-8")
self._command_streaming.put(jog_command_string)
def cancel_jog(self) -> None:
""" Cancel currently running Jog action. """
print("Cancel jog")
self._command_immediate.put(b"\x85")
while self._write_immediate():
pass
self.state.machine_state = b"ClearJog"
# All Grbl internal buffers are cleared of Jog commands and we should
# only have Jog commands in there so it's safe to clear our buffers too.
self._send_buf_lens.clear()
self._send_buf_actns.clear()
self.running_jog = False
def early_update(self) -> bool:
""" Called early in the event loop, before events have been received. """
super().early_update()
# Process data received over serial port.
received_line = None
try:
received_line = self._received_data.get(block=False)
except Empty:
pass
if received_line is not None:
#print("received_line:", received_line)
self.state.parse_incoming(received_line)
# Display debug info: Summary of machine state.
if self.connection_status is ConnectionState.CONNECTED:
if self.state.changes_made:
self.publish(self.key_gen("state"), self.state)
self.state.changes_made = False
return True
def on_connected(self) -> None:
""" Executed when serial port first comes up. """
super().on_connected()
self.ready_for_data = True
# Clear any state from before a disconnect.
self.running_jog = False
self.running_gcode = False
self.running_mode_at = self._time.time()
self.flush_before_continue = False
self._send_buf_lens.clear()
self._send_buf_actns.clear()
self.first_receive = True
# Perform a soft reset of Grbl.
# With a lot of testing we could avoid needing this reset and keep state
# between disconnect/connect cycles.
self._command_immediate.put(b"\x18")
def on_activate(self) -> None:
""" Called whenever self.active is set True. """
if self.connection_status is ConnectionState.CONNECTED:
# The easiest way to replay the following events is to just request
# the data from the Grbl controller again.
# This way the events get re-sent when fresh data arrives.
# (The alternative would be to have the StateMachine re-send the
# cached data but it is possible the StateMachine is stale.)
# Request a report on the modal state of the GRBL controller.
self._command_streaming.put(b"$G")
# Grbl settings report.
self._command_streaming.put(b"$$")
<file_sep>""" Terminals are the plugins used for providing input and receiving output.
This contains code common to all terminals. """
from typing import Dict, Any, Type
from core.component import _ComponentBase
from interfaces._interface_base import _InterfaceBase
from controllers._controller_base import _ControllerBase
def diff_dicts(original: Dict[str, Any], new: Dict[str, Any]) -> Dict[str, Any]:
""" Compare 2 Dicts, returning any values that differ.
It is presumed that the new Dict will contain all keys that are in the
original Dict. The new Dict may have some keys that were not in the original.
We also convert any numerical string values to floats as this is the most
likely use.
Args:
original: A Dict to compare "new" against.
new: A Dict of the expected values.
Returns:
A Dict of key:value pairs from "new" where either the key did not exist
in "original" or the value differs. """
if not isinstance(original, Dict) or not isinstance(new, Dict):
print("ERROR: %s or %s not Dict" % (original, new))
return {}
diff = {}
for key in new:
# Values got from the GUI tend to be converted to strings.
# Safest to presume they are floats.
try:
new[key] = float(new[key])
except ValueError:
pass
except TypeError:
pass
value = new[key]
if key in original:
if value != original[key]:
diff[key] = value
else:
# New key:value.
# key did not exist in original.
diff[key] = value
return diff
class _TerminalBase(_ComponentBase):
active_by_default = True
plugin_type = "terminal"
def __init__(self, label: str = "_guiBase") -> None:
super().__init__(label)
self.active = False
self.interfaces: Dict[str, _InterfaceBase] = {}
self.controllers: Dict[str, _ControllerBase] = {}
self.controller_classes: Dict[str, Type[_ControllerBase]] = {}
self.sub_components: Dict[str, Any] = {}
def setup(self,
interfaces: Dict[str, _InterfaceBase],
controllers: Dict[str, _ControllerBase],
controller_classes: Dict[str, Type[_ControllerBase]]) -> None:
""" Any configuration to be done after __init__ once other components
are active. """
self.interfaces = interfaces
self.controllers = controllers
self.controller_classes = controller_classes
def early_update(self) -> bool:
""" To be called once per frame.
Returns:
bool: True: Continue execution.
False: An "Exit" or empty event occurred. Stop execution. """
raise NotImplementedError
return True # pylint: disable=W0101 # Unreachable code (unreachable)
def close(self) -> None:
""" Perform any cleanup here. """
<file_sep>""" A GUI page plugin for selecting and configuring controllers. """
from typing import List, Dict, Type, Any
from collections import namedtuple
from controllers._controller_base import _ControllerBase
from gui_pages._page_base import _GuiPageBase
# pylint: disable=E1101 # Module 'PySimpleGUIQt' has no 'XXXX' member (no-member)
from PySimpleGUI_loader import sg
Section = namedtuple("Section", ["name", "lines", "errors"])
ParsedLine = namedtuple("ParsedLine", ["raw", "gcode_word_key", "count", "iterations"])
GcodeIteration = namedtuple("GcodeIteration", ["gcode", "errors", "metadata"])
GcodeMetadata = namedtuple("GcodeMetadata", ["point", "distance"])
# Icons from here:
# http://www.iconarchive.com/show/small-n-flat-icons-by-paomedia.html
ERROR = b"<KEY>"
OK = b"<KEY>
MEH = b"<KEY>
class GcodeLoader(_GuiPageBase):
""" A GUI page plugin for selecting and configuring controllers. """
is_valid_plugin = True
label = "GcodeLoader"
def __init__(self,
controllers: Dict[str, _ControllerBase],
controller_classes: Dict[str, Type[_ControllerBase]]) -> None:
super().__init__(controllers, controller_classes)
self.filename_candidate: str = ""
self.gcode_parsed: List[Section] = []
self.widgets: Dict[str, Any] = {}
self.event_subscriptions["_TREE_"] = ("_on_tree", None)
self.event_subscriptions[self.key_gen("selected_gcode_file")] = ("_on_file_picked", "")
self.event_subscriptions["core_gcode:parsed_gcode_loaded"] = ("_on_parsed_gcode", None)
self.event_subscriptions["gui:select_file_gcode"] = ("_on_select_file_gcode", None)
def _file_picker(self) -> sg.Frame:
""" Create a widget for selecting a gcode file from disk. """
# TODO: Make last used directory sticky.
if "file_picker_frame" in self.widgets:
return self.widgets["file_picker_frame"]
self.widgets["file_picker"] = sg.Input(
size=(30, 1), key=self.key_gen("selected_gcode_file"), visible=False)
self.widgets["file_browse"] = sg.FileBrowse(
size=(5, 1), file_types=(("gcode", "*.ng*"), ("All files", "*.*"),))
self.widgets["feedback"] = sg.Text(key=self.key_gen("feedback"))
self.widgets["file_picker_frame"] = sg.Frame(
"File picker",
[
[sg.Text("Filename")],
[self.widgets["file_picker"], self.widgets["file_browse"]],
[self.widgets["feedback"]],
],
size=(30, 30),
#visible=visible,
)
return self.widgets["file_picker_frame"]
def _tree(self) -> sg.Tree:
""" Create a tree widget for displaying loaded gcode. """
if "tree" in self.widgets:
return self.widgets["tree"]
treedata = sg.TreeData()
self.widgets["tree"] = sg.Tree(data=treedata,
headings=["distance",
"status",
"count",
"enabled",
"expanded"],
change_submits=True,
enable_events=True,
auto_size_columns=True,
num_rows=20,
col0_width=50,
def_col_width=50,
key='_TREE_',
#size=(800, 300),
)
self.widgets["tree"].Size = (800, 300)
return self.widgets["tree"]
def gui_layout(self) -> List[List[List[sg.Element]]]:
""" Return the GUI page for uploading Gcode. """
output = [
[self._file_picker()],
[self._tree()],
]
return output
def _on_tree(self, event: str, value: str) -> None:
""" Called whenever the selected line on the tree widget changes. """
#print("_on_tree", event, value)
def _on_file_picked(self, _: str, event_value: Any) -> None:
""" Called in response to gcode file being selected. """
if not event_value:
return
self.filename_candidate = event_value
lines = []
try:
with open(self.filename_candidate) as file_:
while True:
line = file_.readline()
if not line:
break
line = line.strip()
if line:
lines.append(line)
except IOError as error:
self.widgets["feedback"].Update(value="Error: %s" % str(error))
if lines:
self.widgets["feedback"].Update(value="Loaded: %s" % self.filename_candidate)
self.publish("core_gcode:gcode_raw_loaded", lines)
else:
self.widgets["feedback"].Update(value="File empty: %s" % self.filename_candidate)
def _on_parsed_gcode(self, _: str, gcode: List[Section]) -> None:
""" Called in response to gcode being parsed, sanitised, etc. """
self.gcode_parsed = gcode
treedata = sg.TreeData()
for section in gcode:
assert len(section) == 5
section_key = self.key_gen("section__%s" % section.name)
colum_data = ["", "", "", section.enabled, section.expanded]
if section.errors:
# Errors present.
treedata.Insert("", section_key, section.name, colum_data, MEH)
else:
treedata.Insert("", section_key, section.name, colum_data, OK)
counter = 0
for parsed_line in section.lines:
block_key = self.key_gen("block__%s__%s" % (section.name, counter))
data = ""
if parsed_line.iterations[0].gcode:
data = str(parsed_line.iterations[0].gcode)
else:
data = parsed_line.raw
icon = OK
if parsed_line.iterations[0].errors:
icon = ERROR
data += " : %s" % str(parsed_line.iterations[0].errors)
distance = str(parsed_line.iterations[0].metadata.distance)
if distance == "None":
distance = ""
treedata.Insert(section_key,
block_key,
data,
[distance,
icon,
parsed_line.count,]
)
counter += 1
self.widgets["tree"].Update(treedata)
def _on_select_file_gcode(self, _: str, __: Any) -> None:
""" Called in response to select_file_gcode event. """
self.publish("gui:set_tab", "GcodeLoader")
self.widgets["file_browse"].Click()
<file_sep>""" Plugin providing interface to control of some aspect of the active controller. """
from typing import Union
from pygcode import block, GCodeCoordSystemOffset
from interfaces._interface_base import _InterfaceBase
class _InterfaceMovementBase(_InterfaceBase):
""" A base class for user input objects used for controlling movement aspects
of the machine. """
def move_relative(self, **argkv: Union[str, float]) -> None:
""" Move the machine head relative to it's current position.
Note this may or may not be translated to gcode by the controller later
depending on the controller's functionality.
Args:
argkv: A dict containing one or more of the following parameters:
command: The gcode command as a string. Defaults to "G01".
x: The x coordinate.
y: The y coordinate.
z: The z coordinate.
f: The feed rate.
"""
self.publish("command:move_relative", argkv)
def move_absolute(self, **argkv: Union[str, float]) -> None:
""" Move the machine head to a absolute position.
Note this may or may not be translated to gcode by the controller later
depending on the controller's functionality.
Args:
argkv: A dict containing one or more of the following parameters:
command: The gcode command as a string. Defaults to "G01".
x: The x coordinate.
y: The y coordinate.
z: The z coordinate.
f: The feed rate.
"""
self.publish("command:move_absolute", argkv)
def g92_offsets(self, **argkv: Union[str, float]) -> None:
""" Set work position offset.
http://linuxcnc.org/docs/2.6/html/gcode/coordinates.html#cha:coordinate-system
"""
gcode = block.Block()
gcode.gcodes.append(GCodeCoordSystemOffset(**argkv))
self.publish("command:gcode", gcode)
<file_sep>""" Base class for top level GUI pages. Each page gets it's own tab. """
from typing import Dict, Type
from core.component import _ComponentBase
from controllers._controller_base import _ControllerBase
class _GuiPageBase(_ComponentBase):
""" Base class for layout of GUI tabs. """
is_valid_plugin = False
plugin_type = "gui_pages"
def __init__(self,
controllers: Dict[str, _ControllerBase],
controller_classes: Dict[str, Type[_ControllerBase]]) -> None:
super().__init__(self.label)
self.controllers: Dict[str, _ControllerBase] = controllers
self.controller_classes: Dict[str, Type[_ControllerBase]] = controller_classes
<file_sep># Pylint seems to be looking at python2.7's PySimpleGUI libraries so we need the following:
# pylint: disable=E1101 # Module 'PySimpleGUIQt' has no 'XXXX' member (no-member)
""" Send Gcode to active controller in response to GUI button presses. """
from typing import Dict, List
from math import log10, floor
from PySimpleGUI_loader import sg
from interfaces._interface_movement_base import _InterfaceMovementBase
def round_1_sf(number: float) -> float:
""" Round a float to 1 significant figure. """
return round(number, -int(floor(log10(abs(number)))))
class JogWidget(_InterfaceMovementBase):
""" Allows user to directly control various machine settings. eg: Jog the
head to given coordinates. """
# Set this True for any derived class that is to be used as a plugin.
is_valid_plugin = True
def __init__(self, label: str = "jogWidget") -> None:
super().__init__(label)
# Map incoming events to local member variables and callback methods.
self.event_subscriptions = {
self.key_gen("xyMultiply"): ("_xy_jog_step_multiply", 10),
self.key_gen("xyDivide"): ("_xy_jog_step_multiply", 0.1),
self.key_gen("xyJogStep"): ("_xy_jog_step", None),
self.key_gen("zMultiply"): ("_z_jog_step_multiply", 10),
self.key_gen("zDivide"): ("_z_jog_step_multiply", 0.1),
self.key_gen("zJogStep"): ("_z_jog_step", None),
self.key_gen("ul"): ("_move_handler", (-1, 1, 0)),
self.key_gen("uc"): ("_move_handler", (0, 1, 0)),
self.key_gen("ur"): ("_move_handler", (1, 1, 0)),
self.key_gen("cl"): ("_move_handler", (-1, 0, 0)),
self.key_gen("cr"): ("_move_handler", (1, 0, 0)),
self.key_gen("dl"): ("_move_handler", (-1, -1, 0)),
self.key_gen("dc"): ("_move_handler", (0, -1, 0)),
self.key_gen("dr"): ("_move_handler", (1, -1, 0)),
self.key_gen("uz"): ("_move_handler", (0, 0, 1)),
self.key_gen("dz"): ("_move_handler", (0, 0, -1)),
"active_controller:work_pos:x": ("_wpos_handler_x", None),
"active_controller:work_pos:y": ("_wpos_handler_y", None),
"active_controller:work_pos:z": ("_wpos_handler_z", None),
self.key_gen("work_pos:x"): ("_wpos_handler_x_update", None),
self.key_gen("work_pos:y"): ("_wpos_handler_y_update", None),
self.key_gen("work_pos:z"): ("_wpos_handler_z_update", None),
}
self._xy_jog_step: float = 10
self._z_jog_step: float = 10
self._w_pos: Dict[str, float] = {}
def _xy_jog_step_multiply(self, multiplier: float) -> None:
self._xy_jog_step = round_1_sf(self._xy_jog_step * multiplier)
# Need to explicitly push this here as the GUI also sends an update with
# the old value. This publish will take effect later.
self.publish(self.key_gen("xyJogStep"), self._xy_jog_step)
def _z_jog_step_multiply(self, multiplier: float) -> None:
self._z_jog_step = round_1_sf(self._z_jog_step * multiplier)
# Need to explicitly push this here as the GUI also sends an update with
# the old value. This publish will take effect later.
self.publish(self.key_gen("zJogStep"), self._z_jog_step)
def _move_handler(self, values: List[int]) -> None:
self.move_relative(x=self._xy_jog_step * values[0],
y=self._xy_jog_step * values[1],
z=self._z_jog_step * values[2],
)
def _wpos_handler_x(self, value: float) -> None:
""" Called in response to an active_controller:work_pos:x event. """
self._w_pos["x"] = value
self.publish(self.key_gen("work_pos:x"), value)
def _wpos_handler_y(self, value: float) -> None:
""" Called in response to an active_controller:work_pos:y event. """
self._w_pos["y"] = value
self.publish(self.key_gen("work_pos:y"), value)
def _wpos_handler_z(self, value: float) -> None:
""" Called in response to an active_controller:work_pos:z event. """
self._w_pos["z"] = value
self.publish(self.key_gen("work_pos:z"), value)
def _wpos_handler_x_update(self, value: float) -> None:
""" Called in response to a local :work_pos:x event. """
try:
float(value)
except ValueError:
return
if "x" in self._w_pos and value == self._w_pos["x"]:
# Nothing to do.
return
self._w_pos["x"] = value
self.g92_offsets(**self._w_pos)
def _wpos_handler_y_update(self, value: float) -> None:
""" Called in response to a local :work_pos:y event. """
try:
float(value)
except ValueError:
return
if "y" in self._w_pos and value == self._w_pos["y"]:
# Nothing to do.
return
self._w_pos["y"] = value
self.g92_offsets(**self._w_pos)
def _wpos_handler_z_update(self, value: float) -> None:
""" Called in response to a local :work_pos:z event. """
try:
float(value)
except ValueError:
return
if "z" in self._w_pos and value == self._w_pos["z"]:
# Nothing to do.
return
self._w_pos["z"] = value
self.g92_offsets(**self._w_pos)
def gui_layout(self) -> List[List[sg.Element]]:
""" Layout information for the PySimpleGUI interface. """
but_w = 5
but_h = 1.5
def txt(label: str, but_w: float = but_w, but_h: float = but_h) -> sg.Frame:
""" Text output. """
return sg.Text(
label, justification="center", size=(int(but_w), int(but_h)),
#background_color="grey"
)
def but(label: str, key: str) -> sg.Button:
""" Square button. """
return sg.Button(label, key=self.key_gen(key), size=(int(but_w), int(but_h)))
def drp(key: str) -> sg.Drop:
""" Drop down chooser for feed rates. """
drop = sg.Drop(key=self.key_gen(key),
#enable_events=False,
values=[0.001, 0.01, 0.1, 1, 10, 100, 1000],
default_value=self._xy_jog_step, size=(but_w, 1))
return drop
coord_w: float = 10
coord_h: float = 1
def w_coord(key: str) -> sg.InputText:
""" Text field for workspace coordinate positions. """
return sg.InputText(key,
key=self.key_gen(key),
size=(int(coord_w), int(coord_h)),
justification="right",
pad=(0, 0),
#background_color="grey",
)
def m_coord(key: str) -> sg.InputText:
""" Text field for machine coordinate positions. (Not updatable) """
return sg.InputText(key,
key="active_controller:%s" % key,
size=(int(coord_w), int(coord_h)),
justification="right",
pad=(0, 0),
disabled=True,
background_color="grey",
)
def f_coord(key: str) -> sg.InputText:
""" Text field for feed rate coordinate values. (Not updatable) """
return sg.InputText(key,
key="active_controller:%s" % key,
size=(int(coord_w / 2), int(coord_h)),
justification="right",
pad=(0, 0),
disabled=True,
background_color="grey",
)
pos = [
[txt("machine_pos:", coord_w, coord_h),
m_coord("machine_pos:x"),
m_coord("machine_pos:y"),
m_coord("machine_pos:z")],
[txt("work_pos:", coord_w, coord_h),
w_coord("work_pos:x"),
w_coord("work_pos:y"),
w_coord("work_pos:z")],
]
feed = [
[txt("Max feed:", coord_w, coord_h),
f_coord("feed_rate_max:x"),
f_coord("feed_rate_max:y"),
f_coord("feed_rate_max:z")],
[txt("Feed accel:", coord_w, coord_h),
f_coord("feed_rate_accel:x"),
f_coord("feed_rate_accel:y"),
f_coord("feed_rate_accel:z")],
[txt("Current feed:", coord_w, coord_h),
f_coord("feed_rate")]
]
layout_xy = [
# pylint: disable=C0326 # Exactly one space required after comma
[txt(""), txt(""), txt("Y"), txt("")],
# pylint: disable=C0326 # Exactly one space required after comma
[txt(""), but("", "ul"), but("^", "uc"), but("", "ur")],
# pylint: disable=C0326 # Exactly one space required after comma
[txt("X"), but("<", "cl"), but("0", "cc"), but(">", "cr")],
# pylint: disable=C0326 # Exactly one space required after comma
[txt(""), but("", "dl"), but("v", "dc"), but("", "dr")],
# pylint: disable=C0326 # Exactly one space required after comma
[txt("")],
# pylint: disable=C0326 # Exactly one space required after comma
[txt(""), but("/10","xyDivide"), drp("xyJogStep"), but("x10", "xyMultiply")],
]
layout_z = [
[txt(""), txt("Z")],
[txt(""), but("^", "uz")],
[txt(""), but("0", "cz")],
[txt(""), but("v", "dz")],
[txt("")],
[but("/10", "zDivide"), drp("zJogStep"), but("x10", "zMultiply")],
]
layout = [
[sg.Column(pos),
sg.Column(feed),
sg.Stretch()
],
[sg.Column(layout_xy, pad=(0, 0), size=(1, 1)),
sg.Column(layout_z, pad=(0, 0), size=(1, 1)),
sg.Stretch()
]
]
return layout
<file_sep># pylint: disable=E1101 # Module 'PySimpleGUIQt' has no 'XXXX' member (no-member)
# pylint: disable=C0103 # Module name "PySimpleGUIXX_loader" doesn't conform to snake_case naming style (invalid-name)
""" Load specific version of PySimpleGUI. """
import sys
import os
BASEDIR = os.path.dirname(os.path.abspath(sys.modules['__main__'].__file__))
sys.path.insert(0, os.path.join(BASEDIR, "PySimpleGUI/PySimpleGUIQt/"))
# pylint: disable=C0413 # Import "import PySimpleGUIQt as sg" should be placed at the top of the module (wrong-import-position)
import PySimpleGUIQt as sg
#import PySimpleGUI as sg
if hasattr(sg, "__version__"):
print("%s version: %s" % (sg.__name__, sg.__version__))
elif hasattr(sg, "version"):
print("%s version: %s" % (sg.__name__, sg.version))
<file_sep>#!/usr/bin/env python3
""" Testing Grbl controller plugin. """
#pylint: disable=protected-access
import unittest
import loader # pylint: disable=E0401,W0611
from definitions import ConnectionState
from controllers.grbl_1_1 import Grbl1p1Controller, RX_BUFFER_SIZE, REPORT_INTERVAL
class MockSerial:
""" Mock version of serial port. """
def __init__(self):
self.dummy_data = []
self.written_data = []
def readline(self): # pylint: disable=C0103
""" Do nothing or return specified value for method. """
if self.dummy_data:
return self.dummy_data.pop(0)
return None
def write(self, data):
""" Record paramiter for method. """
self.written_data.append(data)
def inWaiting(self) -> bool: # pylint: disable=C0103
""" Mock version of method. """
return bool(self.dummy_data)
class MockTime:
""" Mock version of "time" library. """
def __init__(self):
self.return_values = []
def time(self):
""" Do nothing or return specified value for method. """
if self.return_values:
return self.return_values.pop(0)
return 0
def sleep(self, value): # pylint: disable=R0201, W0613
""" Do nothing for sleep method. """
return
class TestControllerReceiveDataFromSerial(unittest.TestCase):
""" Parsing data received over serial port. """
def setUp(self):
self.controller = Grbl1p1Controller()
self.controller._serial = MockSerial()
self.controller._time = MockTime()
self.controller.connection_status = ConnectionState.CONNECTED
self.controller.desired_connection_status = ConnectionState.CONNECTED
self.controller.state.changes_made = False
self.controller.first_receive = False
self.controller.testing = True
self.assertTrue(self.controller._command_immediate.empty())
self.assertTrue(self.controller._command_streaming.empty())
self.assertTrue(self.controller._received_data.empty())
self.assertEqual(self.controller._error_count, 0)
self.assertEqual(self.controller._ok_count, 0)
def test_basic(self):
""" Basic input as would be seen when everything is going perfectly. """
self.controller._serial.dummy_data = [b"test\r\n", b"test2\r\n"]
self.controller._periodic_io()
self.assertEqual(self.controller._received_data.qsize(), 2)
self.assertEqual(self.controller._received_data.get(), b"test")
self.assertEqual(self.controller._received_data.get(), b"test2")
def test_two_in_one(self):
""" 2 input lines are received in a single cycle. """
self.controller._serial.dummy_data = [b"test\r\ntest2\r\n", b"test3\r\n"]
self.controller._periodic_io()
self.assertEqual(self.controller._received_data.qsize(), 3)
self.assertEqual(self.controller._received_data.get(), b"test")
self.assertEqual(self.controller._received_data.get(), b"test2")
self.assertEqual(self.controller._received_data.get(), b"test3")
def test_split_line(self):
""" A line is split over 2 reads. """
self.controller._serial.dummy_data = [b"te", b"st\r\n"]
self.controller._periodic_io()
self.assertEqual(self.controller._received_data.qsize(), 1)
self.assertEqual(self.controller._received_data.get(), b"test")
def test_split_line_before_eol(self):
""" A line is split over 2 reads between content and EOL. """
self.controller._serial.dummy_data = [b"test", b"\r\ntest2\r\n"]
self.controller._periodic_io()
self.assertEqual(self.controller._received_data.qsize(), 2)
self.assertEqual(self.controller._received_data.get(), b"test")
self.assertEqual(self.controller._received_data.get(), b"test2")
def test_split_line_mid_eol(self):
""" A line is split over 2 reads between EOL chars. """
self.controller._serial.dummy_data = [b"test\r", b"\ntest2\r\n"]
self.controller._periodic_io()
self.assertEqual(self.controller._received_data.qsize(), 2)
self.assertEqual(self.controller._received_data.get(), b"test")
self.assertEqual(self.controller._received_data.get(), b"test2")
def test_delayed_input(self):
""" A line is split over 2 reads with empty read in between. """
self.controller._serial.dummy_data = [b"te", None, b"st\r\n", None, b"test2\r\n"]
self.controller._periodic_io()
self.controller._periodic_io() # "None" in data stopped read loop.
self.controller._periodic_io() # "None" in data stopped read loop.
self.assertEqual(self.controller._received_data.qsize(), 2)
self.assertEqual(self.controller._received_data.get(), b"test")
self.assertEqual(self.controller._received_data.get(), b"test2")
def test_empty_line(self):
""" Empty line are ignored. """
self.controller._serial.dummy_data = [b"\r\n", b"\r\n"]
self.controller._periodic_io()
self.assertEqual(self.controller._received_data.qsize(), 0)
self.controller._serial.dummy_data = [b"\r\n", b"\r\n", b"test\r\n", b"\r\n"]
self.controller._periodic_io()
self.assertEqual(self.controller._received_data.qsize(), 1)
self.controller._serial.dummy_data = []
self.controller._periodic_io()
self.assertEqual(self.controller._received_data.qsize(), 1)
self.assertEqual(self.controller._received_data.get(), b"test")
def test_receive_ok(self):
""" Lines starting with "ok" are handled in the local thread.
They change counters relating to current buffer state; As "ok" arrives,
we know a buffer entry has been consumed. """
self.controller._serial.dummy_data = [b"test\r\n", b"ok\r\n", b"test2\r\n", b"ok\r\n"]
self.controller._send_buf_lens.append(5)
self.controller._send_buf_actns.append((b"dummy", None))
self.controller._send_buf_lens.append(10)
self.controller._send_buf_actns.append((b"dummy", None))
self.controller._send_buf_lens.append(20)
self.controller._send_buf_actns.append((b"dummy", None))
self.controller._periodic_io()
# 1 "ok" processed. Entry removed from _bufferLengths.
self.assertEqual(len(self.controller._send_buf_lens), 1)
self.assertEqual(self.controller._ok_count, 2)
# 2 other messages.
self.assertEqual(self.controller._received_data.qsize(), 2)
self.assertEqual(self.controller._received_data.get(), b"test")
self.assertEqual(self.controller._received_data.get(), b"test2")
def test_receive_error(self):
""" Lines starting with "error:" are handled in the local thread.
Errors should halt execution imidiately. ("!" halts the machine in GRBL."""
self.controller._serial.dummy_data = [
b"test\r\n", b"error:12\r\n", b"test2\r\n", b"error:42\r\n"]
self.controller._send_buf_lens.append(5)
self.controller._send_buf_actns.append((b"dummy", None))
self.controller._send_buf_lens.append(10)
self.controller._send_buf_actns.append((b"dummy", None))
self.controller._periodic_io()
self.assertEqual(self.controller._error_count, 2)
# Errors are passed to the parent thread as well as being dealt with here.
self.assertEqual(self.controller._received_data.qsize(), 4)
self.assertEqual(self.controller._serial.written_data[-1], b"!")
self.assertEqual(self.controller._received_data.get(), b"test")
self.assertEqual(self.controller._received_data.get(), b"error:12")
self.assertEqual(self.controller._received_data.get(), b"test2")
self.assertEqual(self.controller._received_data.get(), b"error:42")
def test_whitespace(self):
""" Whitespace should be stripped from ends of lines but not middle. """
self.controller._serial.dummy_data = [b" test \r\n",
b"test 2\r\n",
b" \r\n",
b"\t\r\n",
b"\n\r\n",
b"\r\r\n",
b"test\t3\r\n",
b"\ntest\n4\n\r\n",
]
self.controller._periodic_io()
self.assertEqual(self.controller._received_data.qsize(), 4)
self.assertEqual(self.controller._received_data.get(), b"test")
self.assertEqual(self.controller._received_data.get(), b"test 2")
self.assertEqual(self.controller._received_data.get(), b"test\t3")
self.assertEqual(self.controller._received_data.get(), b"test\n4")
class TestControllerSendDataToSerial(unittest.TestCase):
""" Send data to controller over serial port. """
def setUp(self):
self.controller = Grbl1p1Controller(_time = MockTime())
self.controller._serial = MockSerial()
self.controller.connection_status = ConnectionState.CONNECTED
self.controller.desired_connection_status = ConnectionState.CONNECTED
self.controller.state.changes_made = False
self.controller.first_receive = False
self.controller.testing = True
self.assertTrue(self.controller._command_immediate.empty())
self.assertTrue(self.controller._command_streaming.empty())
self.assertTrue(self.controller._received_data.empty())
self.assertEqual(self.controller._error_count, 0)
self.assertEqual(self.controller._ok_count, 0)
def test_immediate(self):
""" Some commands should be processed as soon as they arrive on the serial
port. """
self.controller._command_immediate.put("test command")
self.controller._command_immediate.put("test command 2")
self.assertFalse(self.controller._command_streaming.qsize())
self.controller._serial.written_data = []
# Process everything in the buffer.
self.controller._periodic_io()
self.controller._periodic_io()
self.controller._periodic_io()
# Commands have been sent out serial port.
self.assertEqual(self.controller._serial.written_data[-2], "test command")
self.assertEqual(self.controller._serial.written_data[-1], "test command 2")
self.assertEqual(len(self.controller._serial.written_data), 2)
def test_streaming_mode_fail(self):
""" Controller may not be in both running_gcode and running_jog mode at
the same time. """
self.controller.running_gcode = True
self.controller.running_jog = True
with self.assertRaises(AssertionError):
self.controller._periodic_io()
def test_streaming_mode_transition_to_gcode(self):
""" If no mode selected, allow transition to gcode mode. """
self.controller.running_gcode = False
self.controller.running_jog = False
self.controller._command_streaming.put(b"G0 X0 Y0 F10")
self.controller.state.machine_state = b"Idle"
self.controller._periodic_io()
self.assertTrue(self.controller.running_gcode)
self.assertFalse(self.controller.running_jog)
self.assertEqual(self.controller._serial.written_data[-1], b"G0X0Y0F10\n")
self.assertEqual(len(self.controller._serial.written_data), 1)
def test_streaming_mode_transition_to_gcode_from_jog_1(self):
""" if in jog mode, cancel any active Jog command and transition to gcode
mode. """
self.controller.running_gcode = False
self.controller.running_jog = True
self.controller._command_streaming.put(b"G0 X0 Y0 F10")
self.controller.state.machine_state = b"Jog"
self.controller._periodic_io()
self.assertTrue(self.controller.running_gcode)
self.assertFalse(self.controller.running_jog)
# Cancel Jog = b"\x85"
self.assertEqual(self.controller._serial.written_data[-2], b"\x85")
self.assertEqual(self.controller._serial.written_data[-1], b"G0X0Y0F10\n")
self.assertEqual(len(self.controller._serial.written_data), 2)
def test_streaming_mode_transition_to_gcode_from_jog_2(self):
""" if in jog mode, cancel any active Jog command and transition to gcode
mode. """
self.controller.running_gcode = False
self.controller.running_jog = True
self.controller._command_streaming.put(b"G0 X0 Y0 F10")
self.controller.state.machine_state = b"Idle"
self.controller._periodic_io()
self.assertTrue(self.controller.running_gcode)
self.assertFalse(self.controller.running_jog)
# It is possible a jog command has been issued since
# controller.state.machine_state has been updated.
# Best to clear any jog command with b"\x85".
self.assertEqual(self.controller._serial.written_data[-2], b"\x85")
self.assertEqual(self.controller._serial.written_data[-1], b"G0X0Y0F10\n")
self.assertEqual(len(self.controller._serial.written_data), 2)
def test_streaming_mode_transition_to_jog(self):
""" If no mode selected, allow transition to jog mode. """
self.controller.running_gcode = False
self.controller.running_jog = False
# "$J=..." is a GRBL Jog command.
self.controller._command_streaming.put(b"$J=X0Y0")
self.controller.state.machine_state = b"Idle"
self.controller._periodic_io()
self.assertFalse(self.controller.running_gcode)
self.assertTrue(self.controller.running_jog)
self.assertEqual(self.controller._serial.written_data[-1], b"$J=X0Y0\n")
self.assertEqual(len(self.controller._serial.written_data), 1)
def test_streaming_mode_transition_to_jog_fail(self):
""" if in gcode mode, do not allow transition to jog mode. """
self.controller.running_gcode = True
self.controller.running_jog = False
# "$J=..." is a GRBL Jog command.
self.controller._command_streaming.put(b"$J=X0Y0")
self.controller.state.machine_state = b"Idle"
self.controller._periodic_io()
self.assertTrue(self.controller.running_gcode)
self.assertFalse(self.controller.running_jog)
self.assertEqual(len(self.controller._serial.written_data), 0)
def test_streaming_mode_timeout(self):
""" if in gcode mode but inactive for a while, allow transition to jog mode. """
self.controller.running_gcode = True
self.controller.running_jog = False
self.running_mode_at = 1.0
self.controller._time.return_values = [(1 + (3 * REPORT_INTERVAL))] * 2
self.controller.state.machine_state = b"Idle"
self.controller._periodic_io()
self.assertFalse(self.controller.running_gcode)
self.assertFalse(self.controller.running_jog)
self.assertEqual(len(self.controller._serial.written_data), 0)
def test_streaming_flush_before_continue(self):
""" Any command in SLOWCOMMANDS should block until an acknowledgement has
been received from the Grbl hardware. """
self.controller._command_streaming.put(b"test command 1")
self.controller._command_streaming.put(b"G59 A slow command")
self.controller._command_streaming.put(b"test command 2")
self.controller._serial.written_data = []
# Process everything in the buffer.
self.controller._periodic_io()
self.controller._periodic_io()
self.controller._periodic_io()
# Commands up to the slow command has been sent out serial port but
# remaining command is still queued until the GRBL send buffer has been
# drained.
self.assertEqual(self.controller._serial.written_data[-2], b"testcommand1\n")
self.assertEqual(self.controller._serial.written_data[-1], b"G59Aslowcommand\n")
self.assertEqual(len(self.controller._serial.written_data), 2)
# 2 commands have been sent and 2 have not been acknowledged yet.
self.assertEqual(self.controller._ok_count, 0)
self.assertEqual(len(self.controller._send_buf_lens), 2)
# Simulate an "OK" being received acknowledges the 1st sent command
self.controller._incoming_ok()
self.controller._periodic_io()
# 2 commands have been sent and 1 has not been acknowledged yet.
self.assertEqual(self.controller._ok_count, 1)
self.assertEqual(len(self.controller._send_buf_lens), 1)
# Slow command still blocking the last command.
self.assertEqual(self.controller._serial.written_data[-2], b"testcommand1\n")
self.assertEqual(self.controller._serial.written_data[-1], b"G59Aslowcommand\n")
self.assertEqual(len(self.controller._serial.written_data), 2)
# Simulate an "OK" being received acknowledges the sent slow command
self.controller._incoming_ok()
self.controller._periodic_io()
# Receiving the "OK" acknowledging the slow command unblocks the last command.
# Now we should see all 3 commands having been sent.
self.assertEqual(self.controller._serial.written_data[-3], b"testcommand1\n")
self.assertEqual(self.controller._serial.written_data[-2], b"G59Aslowcommand\n")
self.assertEqual(self.controller._serial.written_data[-1], b"testcommand2\n")
self.assertEqual(len(self.controller._serial.written_data), 3)
# Last command has been sent but has not been acknowledged yet.
self.assertEqual(self.controller._ok_count, 2)
self.assertEqual(len(self.controller._send_buf_lens), 1)
# Simulate an "OK" being received acknowledges the last command
self.controller._incoming_ok()
# All pending commands have been acknowledged.
self.assertEqual(self.controller._ok_count, 3)
self.assertEqual(len(self.controller._send_buf_lens), 0)
def test_max_send_buffer_size(self):
""" Receive buffer never overflows.
Grbl receive buffer has a known limited size. "OK" messages will be
received when Grbl has processed a command and removed it from the buffer.
"""
def str_len(strings):
""" Returns the combined lengths of all strings in collection. """
len_ = 0
for s in strings:
len_ += len(s)
return len_
# Fill most of the buffer.
self.controller._command_streaming.put(b"a" * (RX_BUFFER_SIZE - 2))
# Now some small commands.
self.controller._command_streaming.put(b"b")
self.controller._command_streaming.put(b"c")
self.controller._command_streaming.put(b"d")
# Process everything in the buffer.
self.controller._periodic_io()
self.controller._periodic_io()
self.controller._periodic_io()
self.controller._periodic_io()
self.controller._periodic_io()
# First 2 commands made it out the serial port.
self.assertEqual(len(self.controller._send_buf_lens), 2)
# Recorded length of tracked data matches what went out the serial port.
self.assertEqual(sum(self.controller._send_buf_lens),
str_len(self.controller._serial.written_data))
# Next 2 commands still waiting to go.
self.assertEqual(self.controller._command_streaming.qsize(), 2)
# "OK" acknowledges the first command. Will now be space for the
# remaining commands.
self.controller._incoming_ok()
self.controller._periodic_io()
self.controller._periodic_io()
self.controller._periodic_io()
# Recorded length of tracked data matches what went out the serial port.
self.assertEqual(sum(self.controller._send_buf_lens),
str_len(self.controller._serial.written_data[1:]))
# All commands have been sent.
self.assertEqual(self.controller._command_streaming.qsize(), 0)
def test_max_send_buffer_size_off_by_1(self):
""" Receive buffer never overflows.
Grbl receive buffer has a known limited size. "OK" messages will be
received when Grbl has processed a command and removed it from the buffer.
"""
def str_len(strings):
""" Returns the combined lengths of all strings in collection. """
len_ = 0
for s in strings:
len_ += len(s)
return len_
# Fill most of the buffer.
self.controller._command_streaming.put(b"a" * (RX_BUFFER_SIZE - 3))
# Now some small commands.
self.controller._command_streaming.put(b"b")
self.controller._command_streaming.put(b"c")
self.controller._command_streaming.put(b"d")
# Process everything in the buffer.
self.controller._periodic_io()
self.controller._periodic_io()
self.controller._periodic_io()
self.controller._periodic_io()
self.controller._periodic_io()
# First 2 commands made it out the serial port.
self.assertEqual(len(self.controller._send_buf_lens), 2)
# Recorded length of tracked data matches what went out the serial port.
self.assertEqual(sum(self.controller._send_buf_lens),
str_len(self.controller._serial.written_data))
# Next 2 commands still waiting to go.
self.assertEqual(self.controller._command_streaming.qsize(), 2)
# "OK" acknowledges the first command. Will now be space for the
# remaining commands.
self.controller._incoming_ok()
self.controller._periodic_io()
self.controller._periodic_io()
self.controller._periodic_io()
# Recorded length of tracked data matches what went out the serial port.
self.assertEqual(sum(self.controller._send_buf_lens),
str_len(self.controller._serial.written_data[1:]))
# All commands have been sent.
self.assertEqual(self.controller._command_streaming.qsize(), 0)
def test_send_zero_lenght(self):
""" Zero length commands should not be sent to Grbl. """
self.controller._command_streaming.put(b"a")
self.controller._command_streaming.put(b"")
self.controller._command_streaming.put(b"c")
# Process everything in the buffer.
self.controller._periodic_io()
self.controller._periodic_io()
self.controller._periodic_io()
# All commands have been sent.
self.assertEqual(self.controller._command_streaming.qsize(), 0)
# Only non-empty commands were actually sent.
self.assertEqual(self.controller._serial.written_data[0], b"a\n")
self.assertEqual(self.controller._serial.written_data[1], b"c\n")
self.assertEqual(len(self.controller._serial.written_data), 2)
self.assertEqual(sum(self.controller._send_buf_lens), 4)
if __name__ == "__main__":
unittest.main()
<file_sep>""" A GUI page for selecting and configuring controllers. """
from typing import List, Dict, Type, Any
from controllers._controller_base import _ControllerBase
from gui_pages._page_base import _GuiPageBase
# pylint: disable=E1101 # Module 'PySimpleGUIQt' has no 'XXXX' member (no-member)
from PySimpleGUI_loader import sg
class ControllerPicker(_GuiPageBase):
""" A GUI page for selecting and configuring controllers. """
is_valid_plugin = True
label = "ControllerPicker"
def __init__(self,
controllers: Dict[str, _ControllerBase],
controller_classes: Dict[str, Type[_ControllerBase]]) -> None:
super().__init__(controllers, controller_classes)
self.controller_widgets: Dict[str, sg.Frame] = {}
self.controller_buttons: Dict[str, sg.Button] = {}
self.enabled: str = ""
# Repopulate GUI fields after a GUI restart.
self.event_subscriptions["gui:has_restarted"] = ("redraw", None)
for controller in self.controllers:
self.event_subscriptions["%s:active" % controller] = \
("_on_activated_controller", controller)
self.event_subscriptions["__coordinator__:new_controller"] = \
("_on_new_controller", None)
self.event_subscriptions["##new_controller:picker"] = \
("_on_activated_controller", "##new_controller")
def _button(self, label: str) -> sg.Button:
""" Return a button widget for selecting which controller is selected. """
key = "%s:active_buttonpress" % label
self.event_subscriptions[key] = ("_on_button_press", label)
if label == self.enabled:
color = ("white", "red")
else:
color = ("white", "green")
button = sg.Button(label,
key=key,
size=(15, 1),
pad=(0, 0),
button_color=color)
self.controller_buttons[key] = button
return button
def _on_button_press(self, event_name: str, controller_label: str) -> None:
""" Called in response to `_button()` press."""
if controller_label == "##new_controller":
self._on_activated_controller(event_name, controller_label)
return
self.publish("%s:set_active" % controller_label, True)
def _view_widget(self, label: str, controller: _ControllerBase) -> sg.Frame:
""" Return a widget for viewing/configuring a controller. """
visible = bool(label == self.enabled)
key = self.key_gen("view_%s" % label)
widget = sg.Frame(label,
controller.gui_layout(),
key=key,
visible=visible,
)
self.controller_widgets[key] = widget
return widget
def _new_widget(self) -> sg.Frame:
""" Return a widget for selecting what type of new controller is wanted. """
visible = bool(self.enabled == "##new_controller")
layout = []
for label in self.controller_classes:
key = self.key_gen("new_controller__%s" % label)
self.event_subscriptions[key] = ("_new_controller", label)
button = sg.Button(label, key=key,)
layout.append([button])
widget = sg.Frame("New controller",
layout,
visible=visible,)
key = self.key_gen("view_##new_controller")
self.controller_widgets[key] = widget
return widget
def gui_layout(self) -> List[List[List[sg.Element]]]:
""" Return the GUI page with sections for all controllers. """
chooser_elements = []
view_elements = []
self.controller_widgets = {}
self.controller_buttons = {}
# TODO: Make the enabled value persistent.
if not self.enabled:
self.enabled = list(self.controllers.keys())[0]
for label, controller in self.controllers.items():
choose = self._button(label)
chooser_elements.append([choose])
view = self._view_widget(label, controller)
view_elements.append(view)
button = self._button("##new_controller")
chooser_elements.append([button])
widget = self._new_widget()
view_elements.append(widget)
chooser = sg.Column(chooser_elements, pad=(0, 0), background_color="grey")
output = [
[chooser] + view_elements,
[sg.Button("Restart", size=(8, 2), key="gui:restart")],
]
return output
def _on_activated_controller(self, event_name: str, event_value: str) -> None:
""" Display GUI for a particular controller. """
#print("gui_pages._on_activated_controller", event_name, event_value)
if not event_value:
return
label = event_name.split(":", 1)[0]
self.enabled = label
widget_key = self.key_gen("view_%s" % label)
for key, widget in self.controller_widgets.items():
if widget_key == key:
widget.Update(visible=True)
else:
widget.Update(visible=False)
button_key = "%s:active_buttonpress" % label
for key, button in self.controller_buttons.items():
if button_key == key:
button.Update(button_color=("white", "red"))
else:
button.Update(button_color=("white", "green"))
self.publish("gui:set_tab", self.label)
def redraw(self, _: str = "", __: Any = None) -> None:
""" Publish events of all controller parameters to re-populate page. """
for controller in self.controllers.values():
controller.sync()
def _new_controller(self, _: str, label: str) -> None:
""" Delegate creating a new controller to the coordinator. """
self.enabled = "new"
self.publish("request_new_controller", label)
def _on_new_controller(self, _: str, label: str) -> None:
""" Response to a __coordinator__:new_controller event. """
self.event_subscriptions["%s:active" % label] = \
("_on_activated_controller", label)
<file_sep>""" Plugin providing interface to control of some aspect of the active controller. """
from typing import List
from PySimpleGUI_loader import sg
from core.component import _ComponentBase
class _InterfaceBase(_ComponentBase):
""" A base class for user input objects used for controlling the machine. """
# Type of component. Used by the plugin loader.
plugin_type = "interface"
def gui_layout(self) -> List[List[sg.Element]]:
""" Layout information for the PySimpleGUI interface. """
assert False, "gui_layout() not implemented."
return []
<file_sep>
from core.component import _ComponentBase
class _CoreComponentBase(_ComponentBase):
""" Base class for layout of GUI tabs. """
is_valid_plugin = False
plugin_type = "core_components"
<file_sep># Pylint seems to be looking at python2.7's PySimpleGUI libraries so we need the following:
# pylint: disable=E1101 # Module 'PySimpleGUIQt' has no 'XXXX' member (no-member)
""" Interface to allow text entry of raw Gcode. """
from typing import List, Deque, Optional, Dict, Type, Tuple
from collections import deque
from pygcode import Line
from pygcode.exceptions import GCodeWordStrError
from PySimpleGUI_loader import sg
from controllers._controller_base import _ControllerBase
from gui_pages._page_base import _GuiPageBase
class Terminal(_GuiPageBase):
""" Allows user to enter raw Gcode as text. """
# Set this True for any derived class that is to be used as a plugin.
is_valid_plugin = True
label = "terminal"
def __init__(self,
controllers: Dict[str, _ControllerBase],
controller_classes: Dict[str, Type[_ControllerBase]]) -> None:
super().__init__(controllers, controller_classes)
# Map incoming events to local member variables and callback methods.
self.event_subscriptions = {
self.key_gen("gcode_newline"): ("_gcode_update", None),
self.key_gen("gcode_submit"): ("_gcode_submit", None),
"user_feedback:command_state": ("_user_feedback", None),
# TODO: Subscribe to other events we want to see in the terminal.
}
self.widget_log: Optional[sg.Multiline] = None
self.widget_newline: Optional[sg.Input] = None
self.newline: str = ""
# TODO Workaround for https://github.com/PySimpleGUI/PySimpleGUI/issues/2623
# Remove this when the `autoscroll` parameter works.
self.log: Deque[Tuple[str, bool]] = deque()
def _user_feedback(self, value: str) -> None:
self.log.append((str(value), False))
self._update_content()
def _gcode_update(self, gcode: str) -> None:
self.newline = gcode
# pylint: disable=W0613 # Unused argument
def _gcode_submit(self, key: str, value: str) -> None:
if not self.widget_newline:
return
self.widget_newline.Update(value="")
# TODO The rest of this method is a workaround for
# https://github.com/PySimpleGUI/PySimpleGUI/issues/2623
# When the `autoscroll` parameter works we will be able to use:
# self.widget_log.Update(value=newline, append=True)
valid = self._raw_gcode(self.newline)
newline = "> %s\n" % (str(self.newline) if valid else self.newline)
self.log.append((str(newline), valid))
self.newline = ""
self._update_content()
def _update_content(self) -> None:
""" Redraw the terminal window contents. """
if not self.widget_log:
return
while len(self.log) > self.widget_log.metadata["size"][1]:
self.log.popleft()
self.widget_log.Update(value="")
for line in self.log:
text_color = "blue" if line[1] else "red"
self.widget_log.Update(
value=line[0], append=True, text_color_for_value=text_color)
def gui_layout(self) -> List[List[sg.Element]]:
""" Layout information for the PySimpleGUI interface. """
log_size = (60, 10)
self.widget_log = sg.Multiline(
key=self.key_gen("log"),
size=log_size,
disabled=True,
autoscroll=True,
metadata={"skip_update": True, "size": log_size},
)
self.widget_newline = sg.Input(
size=(60, 1),
key=self.key_gen("gcode_newline"),
metadata={"skip_update": True},
focus=True,
)
layout = [
[sg.Text("Title:", size=(20, 1))],
[self.widget_log],
[self.widget_newline],
[sg.Button(
"Submit",
visible=False,
key=self.key_gen("gcode_submit"),
bind_return_key=True,
)],
]
return layout
def _raw_gcode(self, raw_gcode: str) -> bool:
try:
line = Line(str(raw_gcode).strip())
except GCodeWordStrError:
return False
self.publish("command:gcode", line.block)
# print(line.block)
return True
<file_sep>#!/usr/bin/env python3
""" Control computerised machine tools using G-Code programming language.
https://en.wikipedia.org/wiki/G-code
Uses plugins for different hardware controller types. (Eg, Grbl, etc.)
Uses plugins for different operating modes. (Eg. Jog, run GCode file, etc.)
"""
from typing import List, Type
import argparse
import core.common
from core.coordinator import Coordinator
from terminals._terminal_base import _TerminalBase
from controllers._controller_base import _ControllerBase
from interfaces._interface_base import _InterfaceBase
def main() -> None:
""" Main program loop. """
# Component plugin classes.
class_terminals = core.common.load_plugins("terminals")
class_controllers = core.common.load_plugins("controllers")
class_interfaces = core.common.load_plugins("interfaces")
# Component plugin instances.
terminals: List[_TerminalBase] = \
[]
controllers: List[Type[_ControllerBase]] = \
[controller for active, controller in class_controllers if active]
# Instantiate the interfaces here.
interfaces: List[_InterfaceBase] = \
[interface() for active, interface in class_interfaces if active]
# Command line arguments.
parser = argparse.ArgumentParser(description="A UI for CNC machines.")
parser.add_argument("-debug_show_events",
action="store_true",
help="Display events.")
for active_by_default, terminal in class_terminals:
if active_by_default:
parser.add_argument("-no_%s" % terminal.get_classname(),
dest=terminal.get_classname(),
action="store_false",
help="terminal.description")
else:
parser.add_argument("-%s" % terminal.get_classname(),
dest=terminal.get_classname(),
action="store_true",
help="terminal.description")
args = parser.parse_args()
print(args)
# Instantiate terminals according to command line flags.
for _, terminal in class_terminals:
if getattr(args, terminal.get_classname()):
terminal_instance = terminal()
terminal_instance.debug_show_events = args.debug_show_events
terminals.append(terminal_instance)
# Populate and start the coordinator.
coordinator = Coordinator(terminals, interfaces, controllers, args.debug_show_events)
# Main program loop.
while True:
if not coordinator.update_components():
break
# Cleanup and exit.
coordinator.close()
print("done")
if __name__ == "__main__":
main()
<file_sep>#!/usr/bin/env python3
""" Testing Grbl controller plugin. """
#pylint: disable=protected-access
from pygcode import Block, Line
import unittest
import loader # pylint: disable=E0401,W0611
from definitions import ConnectionState
from controllers.debug import DebugController
class MockTime:
""" Mock version of "time" library. """
def __init__(self):
self.return_values = []
def time(self):
""" Do nothing or return specified value for method. """
if self.return_values:
return self.return_values.pop(0)
return 0
def sleep(self, value): # pylint: disable=R0201, W0613
""" Do nothing for sleep method. """
return
class TestControllerConnectionStates(unittest.TestCase):
""" Connect and disconnect to controller. """
def setUp(self) -> None:
self.controller = DebugController()
self.controller._time = MockTime()
self.controller.connection_status = ConnectionState.CONNECTED
self.controller.desired_connection_status = ConnectionState.CONNECTED
self.assertEqual(len(self.controller.log), 0)
def test_connect(self) -> None:
""" Controller transitions to CONNECTED state after a delay. """
self.controller.connection_status = ConnectionState.NOT_CONNECTED
self.assertEqual(self.controller.desired_connection_status,
ConnectionState.CONNECTED)
self.controller._time.return_values = [1000, 2000]
self.controller.early_update()
self.assertEqual(self.controller.connection_status,
ConnectionState.CONNECTING)
self.assertFalse(self.controller.ready_for_data)
self.controller._time.return_values = [3000, 4000]
self.controller.early_update()
self.assertEqual(self.controller.connection_status,
ConnectionState.CONNECTED)
self.assertTrue(self.controller.ready_for_data)
def test_disconnect(self) -> None:
""" Controller transitions to NOT_CONNECTED state after a delay. """
self.assertEqual(self.controller.connection_status, ConnectionState.CONNECTED)
self.controller.desired_connection_status = ConnectionState.NOT_CONNECTED
self.controller._time.return_values = [1000, 2000]
self.controller.early_update()
self.assertEqual(self.controller.connection_status,
ConnectionState.DISCONNECTING)
self.assertFalse(self.controller.ready_for_data)
self.controller._time.return_values = [3000, 4000]
self.controller.early_update()
self.assertEqual(self.controller.connection_status,
ConnectionState.NOT_CONNECTED)
self.assertFalse(self.controller.ready_for_data)
class TestControllerSendData(unittest.TestCase):
""" Send data to controller. """
def setUp(self) -> None:
self.controller = DebugController()
self.controller._time = MockTime()
self.controller.connection_status = ConnectionState.CONNECTED
self.controller.desired_connection_status = ConnectionState.CONNECTED
self.controller.active = True
self.controller.ready_for_data = True
self.assertEqual(len(self.controller.log), 0)
self.assertEqual(self.controller.state.machine_pos,
{"x": 0, "y": 0, "z": 0, "a": 0, "b": 0})
self.assertEqual(self.controller.state.work_pos,
{"x": 0, "y": 0, "z": 0, "a": 0, "b": 0})
def test_incoming_event(self) -> None:
""" Incoming events gets processed by controller. """
fake_event = ("command:gcode", Line("G0 X10 Y20").block)
self.controller._delivered.append(fake_event)
self.controller.update()
self.controller._delivered.clear()
self.assertEqual(len(self.controller.log), 1)
self.assertEqual(self.controller.state.machine_pos,
{"x": 10, "y": 20, "z": 0, "a": 0, "b": 0})
# Further calls to self.controller.update() should have no affect as
# there is no new data.
self.controller.update()
self.assertEqual(len(self.controller.log), 1)
self.assertEqual(self.controller.state.machine_pos,
{"x": 10, "y": 20, "z": 0, "a": 0, "b": 0})
def test_incoming_gcode_g92(self) -> None:
""" Local G92 implementation.
G92: GCodeCoordSystemOffset is not handled by pygcode's VM so we manually
compute the offset. """
fake_event = ("command:gcode", Line("G92 X10 Y20").block)
self.controller._delivered.append(fake_event)
self.controller.update()
self.controller._delivered.clear()
# G92 should have created a diff between machine_pos and work_pos.
self.assertEqual(len(self.controller.log), 1)
self.assertEqual(self.controller.state.machine_pos,
{"x": 0, "y": 0, "z": 0, "a": 0, "b": 0})
self.assertEqual(self.controller.state.work_pos,
{"x": 10, "y": 20, "z": 0, "a": 0, "b": 0})
# Now move and observe diff between machine_pos and work_pos.
fake_event = ("command:gcode", Line("G0 X10 Y20").block)
self.controller._delivered.append(fake_event)
self.controller.update()
self.controller._delivered.clear()
self.assertEqual(len(self.controller.log), 2)
self.assertEqual(self.controller.state.machine_pos,
{"x": 10, "y": 20, "z": 0, "a": 0, "b": 0})
self.assertEqual(self.controller.state.work_pos,
{"x": 20, "y": 40, "z": 0, "a": 0, "b": 0})
# Further G92's work as expected.
fake_event = ("command:gcode", Line("G92 X0 Y0").block)
self.controller._delivered.append(fake_event)
self.controller.update()
self.controller._delivered.clear()
self.assertEqual(len(self.controller.log), 3)
self.assertEqual(self.controller.state.machine_pos,
{"x": 10, "y": 20, "z": 0, "a": 0, "b": 0})
self.assertEqual(self.controller.state.work_pos,
{"x": 0, "y": 0, "z": 0, "a": 0, "b": 0})
fake_event = ("command:gcode", Line("G0 X0 Y0").block)
self.controller._delivered.append(fake_event)
self.controller.update()
self.controller._delivered.clear()
self.assertEqual(len(self.controller.log), 4)
self.assertEqual(self.controller.state.machine_pos,
{"x": 0, "y": 0, "z": 0, "a": 0, "b": 0})
self.assertEqual(self.controller.state.work_pos,
{"x": -10, "y": -20, "z": 0, "a": 0, "b": 0})
def test_incoming_gcode_g92p1(self) -> None:
""" Local G92.1 implementation.
G92.1: GCodeResetCoordSystemOffset is not handled by pygcode's VM so we
manually compute the offset. """
# Use G92 to create a diff between machine_pos and work_pos.
fake_event = ("command:gcode", Line("G92 X10 Y20").block)
self.controller._delivered.append(fake_event)
self.controller.update()
self.controller._delivered.clear()
self.assertEqual(len(self.controller.log), 1)
self.assertEqual(self.controller.state.machine_pos,
{"x": 0, "y": 0, "z": 0, "a": 0, "b": 0})
self.assertEqual(self.controller.state.work_pos,
{"x": 10, "y": 20, "z": 0, "a": 0, "b": 0})
# Now G92.1
fake_event = ("command:gcode", Line("G92.1").block)
self.controller._delivered.append(fake_event)
self.controller.update()
self.controller._delivered.clear()
# G92.1 should have reset the diff between machine_pos and work_pos.
self.assertEqual(len(self.controller.log), 2)
self.assertEqual(self.controller.state.machine_pos,
{"x": 0, "y": 0, "z": 0, "a": 0, "b": 0})
self.assertEqual(self.controller.state.work_pos,
{"x": 0, "y": 0, "z": 0, "a": 0, "b": 0})
if __name__ == '__main__':
unittest.main()
<file_sep># Pylint seems to be looking at python2.7's PySimpleGUI libraries so we need the following:
# pylint: disable=E1101 # Module 'PySimpleGUIQt' has no 'XXXX' member (no-member)
""" A controller for use when testing which mimics an actual hardware controller. """
from typing import List, Callable, Any, Deque, Tuple
try:
from typing import Literal # type: ignore
except ImportError:
from typing_extensions import Literal # type: ignore
import time
from collections import deque
from pygcode import Machine, GCodeCoordSystemOffset, \
GCodeResetCoordSystemOffset, Block
from PySimpleGUI_loader import sg
from definitions import ConnectionState
from controllers._controller_base import _ControllerBase
from controllers.state_machine import StateMachineBase
CONNECT_DELAY = 4 # seconds
PUSH_DELAY = 1 # seconds
class DebugController(_ControllerBase):
""" A controller for use when testing which mimics an actual hardware controller. """
# Set this True for any derived class that is to be used as a plugin.
is_valid_plugin = True
# Limited by pygcode's virtual machine:
# https://github.com/fragmuffin/pygcode/wiki/Supported-gcodes
# TODO: Prune this list back to only those supported.
SUPPORTED_GCODE = set((
"G00", "G01", "G02", "G03",
"G54", "G55", "G56", "G57", "G58", "G59",
"G17", "G18", "G19",
"G90", "G91",
"G91.1",
"G93", "G94",
"G20", "G21",
"G40",
"G43.1", "G49",
"M00", "M01", "M02", "M30",
"M03", "M04", "M05",
"M07", "M08", "M09",
"G04", "G10 L2", "G10 L20", "G28", "G30", "G28.1", "G30.1", "G53", "G92", "G92.1",
))
def __init__(self, label: str = "debug") -> None:
super().__init__(label)
# A record of all gcode ever sent to this controller.
self.log: Deque[Tuple[str, str, Any]] = deque()
self._connect_time: float = 0
self._last_receive_data_at: float = 0
# State machine reflecting _virtual_cnc state.
self.state: StateMachinePygcode = StateMachinePygcode(self.publish_from_here)
# Allow replacing with a mock version when testing.
self._time: Any = time
def gui_layout_view(self) -> List[List[sg.Element]]:
""" Layout information for the PySimpleGUI interface. """
components = self.gui_layout_components()
layout = [
components["view_label"],
[sg.Multiline(default_text="gcode",
size=(60, 10),
key=self.key_gen("gcode"),
autoscroll=True,
disabled=True,
enable_events=False,
),],
components["view_connection"],
components["view_buttons"],
]
return layout
def gui_layout_edit(self) -> List[List[sg.Element]]:
""" Layout information for the PySimpleGUI interface. """
components = self.gui_layout_components()
layout = [
components["edit_label"],
components["edit_buttons"],
]
return layout
def connect(self) -> Literal[ConnectionState]:
if self.connection_status in [
ConnectionState.CONNECTING,
ConnectionState.CONNECTED,
ConnectionState.MISSING_RESOURCE]:
return self.connection_status
self.set_connection_status(ConnectionState.CONNECTING)
self._connect_time = self._time.time()
return self.connection_status
def disconnect(self) -> Literal[ConnectionState]:
if self.connection_status in [
ConnectionState.DISCONNECTING,
ConnectionState.NOT_CONNECTED]:
return self.connection_status
self.set_connection_status(ConnectionState.DISCONNECTING)
self._connect_time = self._time.time()
self.ready_for_data = False
return self.connection_status
def early_update(self) -> bool:
if self.connection_status != self.desired_connection_status:
if self._time.time() - self._connect_time >= CONNECT_DELAY:
if self.connection_status == ConnectionState.CONNECTING:
self.set_connection_status(ConnectionState.CONNECTED)
elif self.connection_status == ConnectionState.DISCONNECTING:
self.set_connection_status(ConnectionState.NOT_CONNECTED)
if self.desired_connection_status == ConnectionState.CONNECTED:
self.connect()
elif self.desired_connection_status == ConnectionState.NOT_CONNECTED:
self.disconnect()
if self.connection_status == ConnectionState.CONNECTED:
if self._time.time() - self._last_receive_data_at >= PUSH_DELAY:
self.ready_for_data = True
else:
self.ready_for_data = False
return True
def update(self) -> None:
super().update()
if self._queued_updates:
self._last_receive_data_at = self._time.time()
# Process local event buffer.
for event, data in self._queued_updates:
# Generate output for debug log.
component_name, action = event.split(":", 1)
self.log.append((component_name, action, data))
debug_output = ""
for log_line in self.log:
debug_output += "%s\t%s\t%s\n" % log_line
self.publish(self.key_gen("gcode"), debug_output)
# Update the state machine to reflect the pygcode virtual machine.
self.state.update()
def _handle_gcode(self, gcode_block: Block) -> None:
""" Update the virtual machine with incoming gcode. """
# Gcode which deals with work offsets is not handled correctly by _virtual_cnc.
# Track and update self.state offsets here instead.
for gcode in gcode_block.gcodes:
if isinstance(gcode, GCodeCoordSystemOffset):
work_offset = {}
for key, value in gcode.get_param_dict().items():
work_offset[key.lower()] = self.state.machine_pos[key.lower()] - value
self.state.work_offset = work_offset
return
if isinstance(gcode, GCodeResetCoordSystemOffset):
self.state.work_offset = {"x": 0, "y": 0, "z": 0, "a": 0, "b": 0}
return
# TODO Check for more gcode in same block.
# _virtual_cnc can handle all other gcode.
self.state.proces_gcode(gcode_block)
class StateMachinePygcode(StateMachineBase):
""" State Machine reflecting the state of a pygcode virtual machine.
https://github.com/fragmuffin/pygcode/wiki/Interpreting-gcode """
def __init__(self, on_update_callback: Callable[[str, Any], None]) -> None:
super().__init__(on_update_callback)
self._virtual_cnc = Machine()
def update(self) -> None:
""" Populate this state machine values from self._virtual_cnc. """
self._parse_modal()
self.machine_pos = self._virtual_cnc.pos.values
self.feed_rate = self._virtual_cnc.mode.feed_rate.word.value
def _parse_modal(self) -> None:
""" Update current modal group values. """
for modal in self._virtual_cnc.mode.gcodes:
modal_bytes = str(modal).encode('utf-8')
if modal_bytes in self.MODAL_COMMANDS:
modal_group = self.MODAL_COMMANDS[modal_bytes]
self.gcode_modal[modal_group] = modal_bytes
elif chr(modal_bytes[0]).encode('utf-8') in self.MODAL_COMMANDS:
modal_group = self.MODAL_COMMANDS[chr(modal_bytes[0]).encode('utf-8')]
self.gcode_modal[modal_group] = modal_bytes
else:
print("TODO: ", modal)
# print(self.gcode_modal)
def proces_gcode(self, gcode_block: Block) -> None:
""" Have the pygcode VM parse incoming gcode. """
self._virtual_cnc.process_block(gcode_block)
<file_sep>""" Base class for all CNC machine control hardware. """
from typing import Any, Deque, Set, Optional, List, Dict
try:
from typing import Literal # type: ignore
except ImportError:
from typing_extensions import Literal
from collections import deque
from pygcode import Block, GCode, Line
# pylint: disable=E1101 # Module 'PySimpleGUIQt' has no 'XXXX' member (no-member)
from PySimpleGUI_loader import sg
from core.component import _ComponentBase
from definitions import ConnectionState
from controllers.state_machine import StateMachineBase, keys_to_lower
class _ControllerBase(_ComponentBase):
""" Base class for all CNC machine control hardware. """
# Strings of the gcode commands this controller supports.
SUPPORTED_GCODE: Set[GCode] = set()
# Type of component. Used by the plugin loader.
plugin_type = "controller"
data_to_sync = (
"connection_status",
"desired_connection_status",
"label"
)
def __init__(self, label: str) -> None:
super().__init__(label)
self.__active: bool = False
self.ready_for_data: bool = False
self.connection_status: ConnectionState = ConnectionState.UNKNOWN
self.desired_connection_status: ConnectionState = ConnectionState.NOT_CONNECTED
self._new_gcode = None
self._new_move_absolute = None
self._new_move_relative = None
self._queued_updates: Deque[Any] = deque()
self.state = StateMachineBase(self.publish_from_here)
self._pending_config: Dict[str, Any] = {}
self.__edit_buttons: List[sg.Button] = []
# Map incoming events to local member variables and callback methods.
self.label = label
self.event_subscriptions = {
self.key_gen("connect"):
("set_desired_connection_status", ConnectionState.CONNECTED),
self.key_gen("disconnect"):
("set_desired_connection_status", ConnectionState.NOT_CONNECTED),
"command:gcode": ("_new_gcode", None),
"command:move_absolute": ("_new_move_absolute", None),
"command:move_relative": ("_new_move_relative", None),
}
self.set_connection_status(ConnectionState.UNKNOWN)
self.set_desired_connection_status(ConnectionState.NOT_CONNECTED)
self.sync()
def gui_layout_view(self) -> List[List[sg.Element]]:
""" Layout information for the PySimpleGUI interface. """
return []
def gui_layout_edit(self) -> List[List[sg.Element]]:
""" Layout information for the PySimpleGUI interface. """
return []
def gui_layout(self) -> List[List[sg.Element]]:
""" Layout information for the PySimpleGUI interface. """
tabs = []
if self.label != "new":
tabs.append(sg.Tab("View", self.gui_layout_view(), key=self.key_gen("view")))
tabs.append(sg.Tab("Edit", self.gui_layout_edit(), key=self.key_gen("edit")))
return [[sg.TabGroup([tabs], key="controller_%s_tabs" % self.label)]]
def gui_layout_components(self) -> Dict[str, List[sg.Element]]:
""" Return a dict of GUI widgets to be included in controller related pages. """
button_col = sg.LOOK_AND_FEEL_TABLE[sg.theme()]["BUTTON"]
disabled_button_col = ("grey", button_col[1])
components = {}
components["view_label"] = [
sg.Text("Title:", size=(12, 1)),
sg.Text(self.label, key=self.key_gen("label"), size=(20, 1)),
]
components["edit_label"] = [
sg.Text("Title:", size=(12, 1)),
sg.InputText(self.label, key=self.key_gen("label_edit"), size=(20, 1)),
]
components["view_buttons"] = [
sg.Button("Connect", key=self.key_gen("connect"), size=(10, 1), pad=(2, 2)),
sg.Button('Disconnect', key=self.key_gen("disconnect"), size=(10, 1), pad=(2, 2)),
]
components["edit_buttons"] = [
sg.Button("Save",
key=self.key_gen("save_edit"),
size=(10, 1),
pad=(2, 2),
disabled=True,
button_color=disabled_button_col),
sg.Button("Cancel",
key=self.key_gen("cancel_edit"),
size=(10, 1),
pad=(2, 2),
disabled=True,
button_color=disabled_button_col),
sg.Button("Delete", size=(10, 1), pad=(2, 2)),
]
components["view_connection"] = [
sg.Text("Connection state (desired/actual):", size=(24, 1)),
sg.Text(key=self.key_gen("desired_connection_status"), size=(15, 1), pad=(0, 0)),
sg.Text(key=self.key_gen("connection_status"), size=(15, 1), pad=(0, 0), justification="left"),
]
self.__edit_buttons = components["edit_buttons"]
self.event_subscriptions[self.key_gen("label_edit")] = ("_modify_controller", None)
self.event_subscriptions[self.key_gen("cancel_edit")] = ("_undo_modify_controller", None)
return components
def _modify_controller(self, event: str, value: Any) -> None:
print("_modify_controller", event, value)
event_label, parameter = event.split(":")
parameter = parameter.rsplit("_edit")[0]
assert event_label == self.label, "Unexpected event passed to _modify_controller."
assert hasattr(self, parameter), "Trying to modify an invalid property: %s" % parameter
if isinstance(value, str):
value = value.strip()
original_value = getattr(self, parameter).strip()
if value == original_value:
return
self._pending_config[parameter] = value
print("_modify_controller", self._pending_config)
button_col = sg.LOOK_AND_FEEL_TABLE[sg.theme()]["BUTTON"]
self.__edit_buttons[0].Update(button_color=button_col, disabled=False)
self.__edit_buttons[1].Update(button_color=button_col, disabled=False)
def _undo_modify_controller(self, _: str, __: Any) -> None:
for parameter in self._pending_config:
key = "%s_edit" % self.key_gen(parameter)
self.publish(key, getattr(self, parameter))
self._pending_config = {}
button_col = sg.LOOK_AND_FEEL_TABLE[sg.theme()]["BUTTON"]
disabled_button_col = ("grey", button_col[1])
self.__edit_buttons[0].Update(button_color=disabled_button_col, disabled=True)
self.__edit_buttons[1].Update(button_color=disabled_button_col, disabled=True)
def sync(self) -> None:
""" Publish all paramiters listed in self.data_to_sync. """
for parameter in self.data_to_sync:
assert hasattr(self, parameter), \
"Parameter: %s does not exist in: %s" % (parameter, self)
self.publish(self.key_gen(parameter), getattr(self, parameter))
def publish_from_here(self, variable_name: str, variable_value: Any) -> None:
""" A method wrapper to pass on to the StateMachineBase so it can
publish events. """
self.publish(self.key_gen(variable_name), variable_value)
@property
def active(self) -> bool:
""" Getter. """
return self.__active
@active.setter
def active(self, value: bool) -> None:
""" Setter. """
self.__active = value
if value:
self.on_activate()
else:
self.on_deactivate()
def on_activate(self) -> None:
""" Called whenever self.active is set True. """
def on_deactivate(self) -> None:
""" Called whenever self.active is set False. """
def set_desired_connection_status(self, connection_status: Literal[ConnectionState]) -> None:
""" Set connection status we would like controller to be in.
The controller should then attempt to transition to this state. """
self.desired_connection_status = connection_status
self.publish(self.key_gen("desired_connection_status"), connection_status)
def set_connection_status(self, connection_status: Literal[ConnectionState]) -> None:
""" Set connection status of controller. """
self.connection_status = connection_status
self.publish(self.key_gen("connection_status"), connection_status)
def connect(self) -> Literal[ConnectionState]:
""" Make connection to controller. """
raise NotImplementedError
# pylint: disable=W0101 # Unreachable code (unreachable)
return ConnectionState.UNKNOWN
def disconnect(self) -> Literal[ConnectionState]:
""" Disconnect from controller. """
raise NotImplementedError
# pylint: disable=W0101 # Unreachable code (unreachable)
return ConnectionState.UNKNOWN
def is_gcode_supported(self, command: Any) -> bool:
""" Check a gcode command line contains only supported gcode statements. """
if isinstance(command, Block):
return_val = True
for gcode in sorted(command.gcodes):
return_val = return_val and self.is_gcode_supported(gcode)
return return_val
if isinstance(command, GCode):
modal = str(command.word_key or command.word_letter).encode("utf-8")
return self.is_gcode_supported(modal)
if isinstance(command, bytes):
return command in self.SUPPORTED_GCODE
raise AttributeError("Cannot tell if %s is valid gcode." % command)
def update(self) -> None:
self._queued_updates.clear()
if(self._delivered and
self.connection_status is ConnectionState.CONNECTED and
self.active and
self.ready_for_data):
# Process incoming events.
for event, value in self._delivered:
## TODO: Flags.
if event in ("command:gcode",
"command:move_absolute",
"command:move_relative"):
# Make a copy of events processes for derived classes that
# need a record of work done here.
self._queued_updates.append((event, value))
# Call handler functions for incoming events.
action = event.split(":", 1)[1]
assert hasattr(self, "_handle_%s" % action),\
"Missing handler for %s event." % action
if isinstance(value, dict):
getattr(self, "_handle_%s" % action)(**keys_to_lower(value))
else:
getattr(self, "_handle_%s" % action)(value)
def _handle_gcode(self, gcode_block: Block) -> None:
""" Handler for the "command:gcode" event. """
raise NotImplementedError
def _handle_move_absolute(self,
# pylint: disable=C0103 # invalid-name
x: Optional[float] = None,
y: Optional[float] = None,
z: Optional[float] = None,
f: Optional[float] = None
) -> None:
""" Handler for the "command:move_absolute" event.
Move machine head to specified coordinates. """
distance_mode_save = self.state.gcode_modal.get(b"distance", b"G90")
gcode = "G90 G00 "
if x is not None:
gcode += "X%s " % x
if y is not None:
gcode += "Y%s " % y
if z is not None:
gcode += "Z%s " % z
if f is not None:
gcode += "F%s " % f
self._handle_gcode(Line(gcode).block)
if distance_mode_save != b"G90":
# Restore modal distance_mode.
self._handle_gcode(Line(distance_mode_save.decode()).block)
def _handle_move_relative(self,
# pylint: disable=C0103 # invalid-name
x: Optional[float] = None,
y: Optional[float] = None,
z: Optional[float] = None,
f: Optional[float] = None
) -> None:
""" Handler for the "command:move_relative" event.
Move machine head to specified coordinates. """
distance_mode_save = self.state.gcode_modal.get(b"distance", b"G91")
gcode = "G91 G00 "
if x is not None:
gcode += "X%s " % x
if y is not None:
gcode += "Y%s " % y
if z is not None:
gcode += "Z%s " % z
if f is not None:
gcode += "F%s " % f
self._handle_gcode(Line(gcode).block)
if distance_mode_save != b"G91":
# Restore modal distance_mode.
self._handle_gcode(Line(distance_mode_save.decode()).block)
<file_sep>#!/usr/bin/env python3
""" Base infrastructure tests.
Plug in components will be tested in separate test files. """
#pylint: disable=protected-access
import unittest
import loader # pylint: disable=E0401,W0611
from core.coordinator import Coordinator
from controllers.debug import DebugController
from controllers.mock_controller import MockController
from interfaces.jog import JogWidget
from definitions import ConnectionState
from controllers import debug
class TestController(unittest.TestCase):
""" Controllers base functionality. """
def setUp(self):
self.mock_controller = MockController()
def test_initilise(self):
""" Connect and disconnect the controller. """
self.assertEqual(self.mock_controller.connection_status, ConnectionState.UNKNOWN)
self.assertFalse(self.mock_controller.ready_for_data)
self.mock_controller.early_update()
self.assertEqual(self.mock_controller.connection_status, ConnectionState.UNKNOWN)
self.mock_controller.connect()
self.assertEqual(self.mock_controller.connection_status, ConnectionState.CONNECTING)
self.assertFalse(self.mock_controller.ready_for_data)
self.mock_controller.early_update()
self.mock_controller.ready_for_data = True # Will stay set while still connected.
self.assertEqual(self.mock_controller.connection_status, ConnectionState.CONNECTED)
self.assertTrue(self.mock_controller.ready_for_data)
self.mock_controller.connect()
self.mock_controller.early_update()
self.assertEqual(self.mock_controller.connection_status, ConnectionState.CONNECTED)
self.assertTrue(self.mock_controller.ready_for_data)
self.mock_controller.disconnect()
self.assertEqual(self.mock_controller.connection_status, ConnectionState.DISCONNECTING)
self.assertFalse(self.mock_controller.ready_for_data)
self.mock_controller.early_update()
self.assertEqual(self.mock_controller.connection_status, ConnectionState.NOT_CONNECTED)
self.assertFalse(self.mock_controller.ready_for_data)
self.mock_controller.disconnect()
self.mock_controller.early_update()
self.assertEqual(self.mock_controller.connection_status, ConnectionState.NOT_CONNECTED)
self.mock_controller.connect()
self.assertEqual(self.mock_controller.connection_status, ConnectionState.CONNECTING)
self.assertFalse(self.mock_controller.ready_for_data)
self.mock_controller.early_update()
self.assertEqual(self.mock_controller.connection_status, ConnectionState.CONNECTED)
def test_valid_gcode_by_string(self):
""" TODO """
def test_valid_gcode_by_line(self):
""" TODO """
def test_disabled_not_reacts_to_event(self):
""" TODO """
def test_enabled_reacts_to_event(self):
""" TODO """
class TestCoordinator(unittest.TestCase):
""" Coordinator interaction with components. """
def setUp(self):
def coordinator_load_config(instance: Coordinator, filename: str) -> None:
""" Override Coordinator._load_config for test. """
instance.config = {'controllers': {'mockController': {'type': 'MockController'}}}
Coordinator._load_config = coordinator_load_config
self.mock_widget = JogWidget()
self.coordinator = Coordinator([], [self.mock_widget], [MockController])
self.mock_controller = self.coordinator.controllers["mockController"]
self.coordinator.active_controller = self.mock_controller
self.coordinator.active_controller.connect()
self.coordinator.update_components() # Push events to subscribed targets.
# Pacify linter.
self.mock_controller1 = None
self.mock_controller2 = None
self.mock_controller3 = None
self.mock_controller4 = None
def tearDown(self):
self.mock_widget._event_queue.clear()
self.assertEqual(len(self.mock_controller._event_queue), 0)
self.coordinator.close()
def test_controller_create_from_config(self):
""" Instances created from the config should be added to various
collections. """
self.coordinator.config = {"controllers": {
"debug": {"type": "MockController"},
"debug": {"type": "MockController"},
}}
self.coordinator._setup_controllers()
self.assertTrue(self.coordinator.controllers["debug"].active)
self.assertIs(self.coordinator.active_controller,
self.coordinator.controllers["debug"])
self.assertIn("debug", self.coordinator.controllers)
self.assertIn(self.coordinator.controllers["debug"],
self.coordinator.all_components)
self.assertEqual(self.coordinator.all_components.count(
self.coordinator.controllers["debug"]), 1)
def test_activate_controller_tiebreaker(self):
""" The "debug" controller gets enabled if no others are eligible. """
self.coordinator.config = {"controllers": {
"owl": {"type": "MockController"},
"tiger": {"type": "MockController"},
"debug": {"type": "MockController"},
}}
self.coordinator._setup_controllers()
self.assertFalse(self.coordinator.controllers["owl"].active)
self.assertFalse(self.coordinator.controllers["tiger"].active)
self.assertTrue(self.coordinator.controllers["debug"].active)
self.assertIs(self.coordinator.active_controller,
self.coordinator.controllers["debug"])
def test_debug_controller_autocreate(self):
""" Automatically create "debug" controller if DebugController class
exists. """
self.coordinator.config = {"controllers": {
"owl": {"type": "MockController"},
"tiger": {"type": "MockController"},
}}
self.coordinator.controller_classes["DebugController"] = DebugController
self.coordinator._setup_controllers()
self.assertFalse(self.coordinator.controllers["owl"].active)
self.assertFalse(self.coordinator.controllers["tiger"].active)
self.assertTrue(self.coordinator.controllers["debug"].active)
self.assertIs(self.coordinator.active_controller,
self.coordinator.controllers["debug"])
def test_activate_controller_active_flag(self):
""" The first controller with it's "active" flag set gets enabled. """
self.coordinator.config = {"controllers": {
"owl": {"type": "MockController"},
"tiger": {"type": "MockController"},
"debug": {"type": "MockController"},
}}
self.coordinator._setup_controllers()
self.coordinator.controllers["owl"].active = False
self.coordinator.controllers["tiger"].active = True
self.coordinator.controllers["debug"].active = False
self.coordinator.activate_controller()
self.assertFalse(self.coordinator.controllers["owl"].active)
self.assertTrue(self.coordinator.controllers["tiger"].active)
self.assertFalse(self.coordinator.controllers["debug"].active)
self.assertIs(self.coordinator.active_controller,
self.coordinator.controllers["tiger"])
def test_activate_controller_multi_active_flag(self):
""" The first controller with it's "active" flag set gets enabled. """
self.coordinator.config = {"controllers": {
"owl": {"type": "MockController"},
"tiger": {"type": "MockController"},
"debug": {"type": "MockController"},
}}
self.coordinator._setup_controllers()
self.coordinator.controllers["owl"].active = True
self.coordinator.controllers["tiger"].active = True
self.coordinator.controllers["debug"].active = False
self.coordinator.activate_controller()
self.assertTrue(self.coordinator.controllers["owl"].active)
self.assertFalse(self.coordinator.controllers["tiger"].active)
self.assertFalse(self.coordinator.controllers["debug"].active)
self.assertIs(self.coordinator.active_controller,
self.coordinator.controllers["owl"])
def test_activate_controller_prefer_not_debug(self):
""" The first controller with it's "active" flag set gets enabled but
prefer one that isn't the debug one."""
self.coordinator.config = {"controllers": {
"owl": {"type": "MockController"},
"tiger": {"type": "MockController"},
"debug": {"type": "MockController"},
}}
self.coordinator._setup_controllers()
self.coordinator.controllers["debug"].active = True
self.coordinator.controllers["tiger"].active = False
self.coordinator.controllers["owl"].active = True
self.coordinator.activate_controller()
self.assertFalse(self.coordinator.controllers["tiger"].active)
self.assertFalse(self.coordinator.controllers["debug"].active)
self.assertTrue(self.coordinator.controllers["owl"].active)
self.assertIs(self.coordinator.active_controller,
self.coordinator.controllers["owl"])
def test_activate_controller_add_later(self):
""" Add a new controller later. """
self.coordinator.config = {"controllers": {
"owl": {"type": "MockController"},
"tiger": {"type": "MockController"},
"debug": {"type": "MockController"},
}}
self.coordinator._setup_controllers()
self.coordinator.controllers["owl"].active = False
self.coordinator.controllers["tiger"].active = True
self.coordinator.controllers["debug"].active = False
self.coordinator.activate_controller()
self.assertFalse(self.coordinator.controllers["owl"].active)
self.assertTrue(self.coordinator.controllers["tiger"].active)
self.assertFalse(self.coordinator.controllers["debug"].active)
self.assertIs(self.coordinator.active_controller,
self.coordinator.controllers["tiger"])
self.mock_controller4 = MockController("KingKong")
self.mock_controller4.active = False
self.coordinator.activate_controller(controller=self.mock_controller4)
# The new one is now added and active.
self.assertFalse(self.coordinator.controllers["owl"].active)
self.assertFalse(self.coordinator.controllers["tiger"].active)
self.assertFalse(self.coordinator.controllers["debug"].active)
self.assertTrue(self.coordinator.controllers["KingKong"].active)
self.assertIn("KingKong", self.coordinator.controllers)
self.assertIn(self.coordinator.controllers["KingKong"],
self.coordinator.all_components)
self.assertEqual(self.coordinator.all_components.count(
self.coordinator.controllers["KingKong"]), 1)
self.assertIs(self.coordinator.active_controller,
self.coordinator.controllers["KingKong"])
def test_activate_controller_by_instance(self):
""" Enable a controller specified by instance. """
self.coordinator.config = {"controllers": {
"owl": {"type": "MockController"},
"tiger": {"type": "MockController"},
"debug": {"type": "MockController"},
}}
self.coordinator._setup_controllers()
self.coordinator.controllers["owl"].active = False
self.coordinator.controllers["tiger"].active = True
self.coordinator.controllers["debug"].active = False
self.coordinator.activate_controller()
self.assertFalse(self.coordinator.controllers["owl"].active)
self.assertTrue(self.coordinator.controllers["tiger"].active)
self.assertFalse(self.coordinator.controllers["debug"].active)
self.assertIs(self.coordinator.active_controller,
self.coordinator.controllers["tiger"])
# Specify a new active controller.
self.coordinator.activate_controller(controller=self.coordinator.controllers["owl"])
# The specified one is now active.
self.assertTrue(self.coordinator.controllers["owl"].active)
self.assertFalse(self.coordinator.controllers["tiger"].active)
self.assertFalse(self.coordinator.controllers["debug"].active)
self.assertEqual(self.coordinator.all_components.count(
self.coordinator.controllers["owl"]), 1)
self.assertIs(self.coordinator.active_controller,
self.coordinator.controllers["owl"])
def test_activate_controller_by_label(self):
""" The controller with the specified label gets enabled. """
self.coordinator.config = {"controllers": {
"owl": {"type": "MockController"},
"tiger": {"type": "MockController"},
"debug": {"type": "MockController"},
}}
self.coordinator._setup_controllers()
self.coordinator.controllers["owl"].active = False
self.coordinator.controllers["tiger"].active = True
self.coordinator.controllers["debug"].active = False
self.coordinator.activate_controller()
self.assertFalse(self.coordinator.controllers["owl"].active)
self.assertTrue(self.coordinator.controllers["tiger"].active)
self.assertFalse(self.coordinator.controllers["debug"].active)
self.assertIs(self.coordinator.active_controller,
self.coordinator.controllers["tiger"])
# Specify a new active controller.
self.coordinator.activate_controller(label="owl")
# The specified one is now active.
self.assertTrue(self.coordinator.controllers["owl"].active)
self.assertFalse(self.coordinator.controllers["tiger"].active)
self.assertFalse(self.coordinator.controllers["debug"].active)
self.assertEqual(self.coordinator.all_components.count(
self.coordinator.controllers["owl"]), 1)
self.assertIs(self.coordinator.active_controller,
self.coordinator.controllers["owl"])
def test_activate_controller_on_event_set(self):
""" The "_on_activate_controller" event handler changes active controller. """
self.coordinator.config = {"controllers": {
"owl": {"type": "MockController"},
"tiger": {"type": "MockController"},
"debug": {"type": "MockController"},
}}
self.coordinator._setup_controllers()
self.coordinator.controllers["owl"].active = False
self.coordinator.controllers["tiger"].active = True
self.coordinator.controllers["debug"].active = False
self.coordinator.activate_controller()
self.assertFalse(self.coordinator.controllers["owl"].active)
self.assertTrue(self.coordinator.controllers["tiger"].active)
self.assertFalse(self.coordinator.controllers["debug"].active)
self.assertIs(self.coordinator.active_controller,
self.coordinator.controllers["tiger"])
# "_on_activate_controller" changes the default controller.
self.coordinator._on_activate_controller("owl:set_active", True)
self.assertTrue(self.coordinator.controllers["owl"].active)
self.assertFalse(self.coordinator.controllers["tiger"].active)
self.assertFalse(self.coordinator.controllers["debug"].active)
self.assertIs(self.coordinator.active_controller,
self.coordinator.controllers["owl"])
def test_activate_controller_on_event_unset(self):
""" The "_on_activate_controller" event handler un-sets active controller,
returning it to "debug". """
self.coordinator.config = {"controllers": {
"owl": {"type": "MockController"},
"tiger": {"type": "MockController"},
"debug": {"type": "MockController"},
}}
self.coordinator._setup_controllers()
self.coordinator.controllers["owl"].active = False
self.coordinator.controllers["tiger"].active = True
self.coordinator.controllers["debug"].active = False
self.coordinator.activate_controller()
self.assertFalse(self.coordinator.controllers["owl"].active)
self.assertTrue(self.coordinator.controllers["tiger"].active)
self.assertFalse(self.coordinator.controllers["debug"].active)
self.assertIs(self.coordinator.active_controller,
self.coordinator.controllers["tiger"])
# "_on_activate_controller" un-sets the currently active.
# The default controller ("debug") will be made the active.
self.coordinator._on_activate_controller("tiger:set_active", False)
self.assertFalse(self.coordinator.controllers["owl"].active)
self.assertFalse(self.coordinator.controllers["tiger"].active)
self.assertTrue(self.coordinator.controllers["debug"].active)
self.assertIs(self.coordinator.active_controller,
self.coordinator.controllers["debug"])
def test_push_from_interface_to_controller(self):
""" Data pushed as an event is processed by the controller. """
def data_match(gcode, data):
for section in gcode.gcodes:
param_dict = section.get_param_dict()
if section.word_letter == "G":
self.assertEqual(param_dict["X"], data["X"])
self.assertEqual(param_dict["Y"], data["Y"])
elif section.word_letter == "F":
self.assertEqual(str(section), "F%s" % data["F"])
self.assertIs(self.coordinator.active_controller, self.mock_controller)
self.assertEqual(self.mock_controller.connection_status, ConnectionState.CONNECTED)
# No data on mock_controller yet.
self.assertEqual(len(self.mock_controller.log), 0)
# Send data to controller.
data = {"X": 10, "Y": 20, "F": 100}
self.mock_widget.move_absolute(**data)
self.coordinator.update_components() # Push event from mock_widget onto queue.
self.coordinator.update_components() # Push event from queue to mock_controller.
self.assertEqual(len(self.mock_controller.log), 1)
self.assertEqual(self.mock_controller.log[-1], ("command", "move_absolute", data))
# Send more data to controller.
data = {"X": 1.2345, "Y": -6.7889, "F": 1000}
self.mock_widget.move_absolute(**data)
self.coordinator.update_components() # Push event from mock_widget onto queue.
self.coordinator.update_components() # Push event from queue to mock_controller.
self.assertEqual(len(self.mock_controller.log), 2)
self.assertEqual(self.mock_controller.log[-1], ("command", "move_absolute", data))
def test_swap_controllers(self):
""" Push to one controller, set a different controller active, push there
then revert and confirm original has correct state. """
self.assertIs(self.coordinator.active_controller, self.mock_controller)
self.assertEqual(self.mock_controller.connection_status, ConnectionState.CONNECTED)
# No data on mock_controller yet.
self.assertEqual(len(self.mock_controller.log), 0)
# Send data to controller.
self.mock_widget.move_absolute(x=10, y=20, f=100)
self.coordinator.update_components() # Push event from mock_widget onto queue.
self.coordinator.update_components() # Push event from queue to mock_controller.
self.mock_widget.move_absolute(x=50, y=100, f=100)
self.coordinator.update_components() # Push event from mock_widget onto queue.
self.coordinator.update_components() # Push event from queue to mock_controller.
self.assertEqual(len(self.mock_controller.log), 2)
# Create new controller and make it active.
self.mock_controller2 = MockController("owl")
self.mock_controller2.connect()
self.mock_controller2.early_update() # Move from CONNECTING to CONNECTED
self.coordinator.activate_controller(controller=self.mock_controller2)
self.assertEqual(self.mock_controller2.connection_status, ConnectionState.CONNECTED)
self.assertFalse(self.mock_controller.active)
self.assertTrue(self.mock_controller2.active)
self.assertIs(self.coordinator.active_controller, self.mock_controller2)
# No data on mock_controller2 yet.
self.assertEqual(len(self.mock_controller2.log), 0)
# Push data to new controller.
self.mock_widget.move_absolute(x=100, y=200, f=1000)
self.coordinator.update_components() # Push event from mock_widget onto queue.
self.coordinator.update_components() # Push event from queue to mock_controller.
# Has not changed data on old (inactive) controller.
self.assertEqual(len(self.mock_controller.log), 2)
# Has changed data on new (active) controller.
self.assertEqual(len(self.mock_controller2.log), 1)
# Back to original controller.
self.coordinator.activate_controller(controller=self.mock_controller)
# Push data to original controller.
self.mock_widget.move_absolute(x=-1, y=-2, f=1)
self.coordinator.update_components() # Push event from mock_widget onto queue.
self.coordinator.update_components() # Push event from queue to mock_controller.
# New data on old (active) controller.
self.assertEqual(len(self.mock_controller.log), 3)
# No change on new (inactive) controller.
self.assertEqual(len(self.mock_controller2.log), 1)
def test_component_names_match(self):
""" Coordinator stores components keyed by their label. """
self.coordinator.config = {'controllers': {
'owl': {'type': 'MockController'},
'tiger': {'type': 'MockController'},
}}
self.coordinator._setup_controllers()
self.assertSetEqual(set(["owl", "tiger"]), set(self.coordinator.controllers.keys()))
class TestEvents(unittest.TestCase):
""" Test event handling.
Note that this works without the input of the Controller but in the real
world it would be used to clear the _event_queue between iterations. """
def setUp(self):
self.mock_controller = MockController()
self.mock_widget = JogWidget()
self.mock_widget._event_queue.clear()
self.assertEqual(len(self.mock_controller._event_queue), 0)
def tearDown(self):
self.mock_widget._event_queue.clear()
self.assertEqual(len(self.mock_controller._event_queue), 0)
self.mock_controller._delay_events[0] = False
def test_publish_event_basic(self):
""" Subscribe to some events on one component, publish on another. """
# Set up some subscriptions.
self.mock_widget.event_subscriptions = {
"pubSub1": None,
"pubSub2": None,
"pubSub3": None,
"pubSub4": None,
# Its fine to subscribe to things that don't arrive.
"missing": None,
}
# Publish some things, populating the shared _event_queue.
self.mock_controller.publish("pubSub1", "root")
self.mock_controller.publish("pubSub1", "toot")
self.mock_controller.publish("pubSub2", True)
self.mock_controller.publish("pubSub3", 1)
self.mock_controller.publish("pubSub4", None)
self.assertEqual(len(self.mock_controller._event_queue), 5)
# Now call the receive on the other component making it read the _event_queue.
self.mock_widget.receive()
# Nothing delivered to the sender.
self.assertEqual(0, len(self.mock_controller._delivered))
# Full set delivered to the receiver.
self.assertEqual(len(self.mock_widget._delivered), 5)
def test_publish_event_to_callback_missing(self):
""" Missing callback method/variable. """
# Set up some subscriptions.
self.mock_widget.event_subscriptions = {
"pubSub1": ("callback", None),
}
# Publish some things, populating the shared _event_queue.
self.mock_controller.publish("pubSub1", "root")
self.mock_controller.publish("pubSub1", "toot")
self.assertEqual(len(self.mock_controller._event_queue), 2)
# Now call the receive on the other component making it read the _event_queue.
self.mock_widget.receive()
# Nothing delivered to the sender.
self.assertEqual(0, len(self.mock_controller._delivered))
# Full set delivered to the receiver.
self.assertEqual(len(self.mock_widget._delivered), 2)
# Subscription to event should fire callback but callback method/variable
# is missing from self.mock_widget.
with self.assertRaises(AttributeError):
self.mock_widget._update()
def test_publish_event_to_callback_method(self):
""" Callback on receiving event. """
# Set callback method on self.mock_widget.
callback_received_1 = []
self.mock_widget.callback_1 = lambda in_: callback_received_1.append(in_)
callback_received_2 = []
self.mock_widget.callback_2 = lambda in_: callback_received_2.append(in_)
# Set up some subscriptions.
self.mock_widget.event_subscriptions = {
"pubSub1": ("callback_1", None),
"pubSub2": ("callback_2", "default"),
}
# Publish some things, populating the shared _event_queue.
self.mock_controller.publish("pubSub1", "root")
self.mock_controller.publish("pubSub1", "toot")
self.mock_controller.publish("pubSub1", None)
self.mock_controller.publish("pubSub1", True)
self.mock_controller.publish("pubSub1", False)
self.mock_controller.publish("pubSub1", 1.1)
self.mock_controller.publish("pubSub2", "flibertygibblets")
self.mock_controller.publish("pubSub2", None)
self.assertEqual(len(self.mock_controller._event_queue), 8)
# Now call the receive on the other component making it read the _event_queue.
self.mock_widget.receive()
# Nothing delivered to the sender.
self.assertEqual(0, len(self.mock_controller._delivered))
# Full set delivered to the receiver.
self.assertEqual(len(self.mock_widget._delivered), 8)
# Callback fires when processing event.
self.mock_widget._update()
self.assertEqual(len(callback_received_1), 6)
self.assertIn("root", callback_received_1)
self.assertIn("toot", callback_received_1)
self.assertIn(None, callback_received_1)
self.assertIn(True, callback_received_1)
self.assertIn(False, callback_received_1)
self.assertIn(1.1, callback_received_1)
self.assertEqual(len(callback_received_2), 2)
self.assertIn("flibertygibblets", callback_received_2)
# No value specified by `publish(...)` so use the one in `event_subscriptions`.
self.assertIn("default", callback_received_2)
def test_publish_event_to_variable(self):
""" Store in variable on receiving event. """
# Set variable to store value on self.mock_widget.
self.mock_widget.subscribed_value_1 = None
self.mock_widget.subscribed_value_2 = None
# Set up some subscriptions.
self.mock_widget.event_subscriptions = {
"pubSub1": ("subscribed_value_1", "default_1"),
"pubSub2": ("subscribed_value_2", "default_2"),
}
# Publish some things, populating the shared _event_queue.
self.mock_controller.publish("pubSub1", "root")
self.mock_controller.publish("pubSub1", "toot")
self.mock_controller.publish("pubSub2", None)
self.assertEqual(len(self.mock_controller._event_queue), 3)
# Now call the receive on the other component making it read the _event_queue.
self.mock_widget.receive()
# Nothing delivered to the sender.
self.assertEqual(0, len(self.mock_controller._delivered))
# Full set delivered to the receiver.
self.assertEqual(len(self.mock_widget._delivered), 3)
# Callback fires when processing event.
self.mock_widget._update()
# Order events arrive in is undefined so could be either value.
self.assertIn(self.mock_widget.subscribed_value_1, ("root", "toot"))
# No value specified by `publish(...)` so use the one in `event_subscriptions`.
self.assertEqual(self.mock_widget.subscribed_value_2, "default_2")
def test_publish_while_processing_events(self):
""" If an event is published while the coordinator is performing `receive()`
on it's components, event will go into a different queue and be deferred until
next pass. """
def coordinator_load_config(instance: Coordinator, filename: str) -> None:
""" Override Coordinator._load_config for test. """
instance.config = {'controllers': {'mockController': {'type': 'MockController'}}}
Coordinator._load_config = coordinator_load_config
self.coordinator = Coordinator([], [self.mock_widget], [MockController])
self.coordinator._event_queue.clear()
# The _event_queue is shared between all components.
self.assertIs(self.coordinator._event_queue, self.mock_widget._event_queue)
self.assertIs(self.coordinator._delayed_event_queue,
self.mock_widget._delayed_event_queue)
self.assertEqual(len(self.mock_widget._event_queue), 0)
self.assertEqual(len(self.mock_widget._delayed_event_queue), 0)
# Events are published as normal.
self.coordinator.publish("pubSub1", "root")
self.assertEqual(len(self.mock_widget._event_queue), 1)
# Once we start processing the _event_queue, we need to temporarily put
# new events in a different queue.
self.coordinator.receive()
self.assertTrue(self.coordinator._delay_events[0])
self.coordinator.publish("pubSub2", "toot")
# No change in regular queue.
self.assertEqual(len(self.mock_widget._event_queue), 1)
# New event has gone in _delayed_event_queue.
self.assertEqual(len(self.mock_widget._delayed_event_queue), 1)
# When the coordinator clears the _event_queue the contents of _delayed_event_queue
# is copied to _event_queue.
self.coordinator._clear_events()
self.assertEqual(len(self.mock_widget._event_queue), 1)
self.assertEqual(len(self.mock_widget._delayed_event_queue), 0)
self.assertEqual(self.mock_widget._event_queue[0], ("pubSub2", "toot"))
if __name__ == '__main__':
unittest.main()
<file_sep>""" State machines reflecting the state of hardware controllers.
Typically each hardware controller type will have it's own SM class inheriting
from StateMachineBase. """
from typing import Dict, List, Callable, Optional, Any
from definitions import MODAL_GROUPS, MODAL_COMMANDS
def keys_to_lower(dict_: Dict[str, Any]) -> Dict[str, Any]:
""" Translate a dict's keys to lower case. """
return {k.lower(): v for k, v in dict_.items()}
class StateMachineBase:
""" Base class for State Machines reflecting the state of hardware controllers. """
machine_properties = [
"machine_pos",
"machine_pos_max",
"machine_pos_min",
"work_pos",
"work_offset",
"feed_rate",
"feed_rate_max",
"feed_rate_accel",
#"feed_override",
#"rapid_override",
"spindle_rate",
"spindle_override",
"limit_x",
"limit_y",
"limit_z",
"limit_a",
"limit_b",
"probe",
"pause",
"pause_park", # Gracefully parking head after a pause event.
"parking",
"halt",
"door",
]
# Cheaper than global lookups
MODAL_GROUPS: Dict[str, Any] = MODAL_GROUPS
MODAL_COMMANDS = MODAL_COMMANDS
def __init__(self, on_update_callback: Callable[[str, Any], None]) -> None:
self.on_update_callback = on_update_callback
self.__machine_pos: Dict[str, float] = {"x": 0, "y": 0, "z": 0, "a": 0, "b": 0}
self.__machine_pos_max: Dict[str, float] = {"x": 0, "y": 0, "z": 0, "a": 0, "b": 0}
self.__machine_pos_min: Dict[str, float] = {"x": 0, "y": 0, "z": 0, "a": 0, "b": 0}
self.__work_pos: Dict[str, float] = {"x": 0, "y": 0, "z": 0, "a": 0, "b": 0}
self.__work_offset: Dict[str, float] = {"x": 0, "y": 0, "z": 0, "a": 0, "b": 0}
self.__feed_rate: float = 0
self.__feed_rate_max: Dict[str, float] = {"x": 0, "y": 0, "z": 0, "a": 0, "b": 0}
self.__feed_rate_accel: Dict[str, float] = {"x": 0, "y": 0, "z": 0, "a": 0, "b": 0}
self.__feed_override: float = 100
self.__rapid_override: float = 100
self.__spindle_rate: float = 0
self.__spindle_override: int = 100
self.__limit_x: float = False
self.__limit_y: float = False
self.__limit_z: float = False
self.__limit_a: float = False
self.__limit_b: float = False
self.__probe: bool = False
self.__pause: bool = False
self.pause_reason: List[str] = []
self.__pause_park: bool = False
self.__parking: bool = False
self.__halt: bool = False
self.halt_reason: List[str] = []
self.__door: bool = False
self.gcode_modal: Dict[bytes, bytes] = {}
self.version: List[str] = [] # Up to the controller how this is populated.
self.machine_identifier: List[str] = [] # Up to the controller how this is populated.
self.changes_made: bool = True
def __str__(self) -> str:
output = ("Pause: {self.pause}\tHalt: {self.halt}\n")
output += ("machine_pos x: {self.machine_pos[x]} y: {self.machine_pos[y]} "
"z: {self.machine_pos[z]} a: {self.machine_pos[a]} "
"b: {self.machine_pos[b]}\r\n")
if self.machine_pos != self.work_pos:
output += ("work_pos x: {self.work_pos[x]} y: {self.work_pos[y]} "
"z: {self.work_pos[z]} a: {self.work_pos[a]} "
"b: {self.work_pos[b]}\r\n")
output += ("work_offset x: {self.work_offset[x]} y: {self.work_offset[y]} "
"z: {self.work_offset[z]} a: {self.work_offset[a]} "
"b: {self.work_offset[b]}\r\n")
output += "feed_rate: {self.feed_rate}\r\n"
output += "gcode_modalGroups: {self.gcode_modal}\r\n"
return output.format(self=self)
def sync(self) -> None:
""" Publish all machine properties. """
for prop in self.machine_properties:
value = getattr(self, prop)
# Publish whole property.
self.on_update_callback(prop, value)
# Also publish component parts if property is a dict.
if isinstance(value, dict):
for sub_prop, sub_value in value.items():
self.on_update_callback("%s:%s" % (prop, sub_prop), sub_value)
@property
def work_offset(self) -> Dict[str, float]:
""" Getter. """
return self.__work_offset
@work_offset.setter
def work_offset(self, pos: Dict[str, float]) -> None:
""" Setter. """
pos = keys_to_lower(pos)
data_changed = False
pos_x = pos.get("x")
pos_y = pos.get("y")
pos_z = pos.get("z")
pos_a = pos.get("a")
pos_b = pos.get("b")
if pos_x is not None:
if self.__work_offset["x"] != pos_x:
data_changed = True
self.__work_offset["x"] = pos_x
self.__work_pos["x"] = self.machine_pos["x"] - pos_x
if pos_y is not None:
if self.__work_offset["y"] != pos_y:
data_changed = True
self.__work_offset["y"] = pos_y
self.__work_pos["y"] = self.machine_pos["y"] - pos_y
if pos_z is not None:
if self.__work_offset["z"] != pos_z:
data_changed = True
self.__work_offset["z"] = pos_z
self.__work_pos["z"] = self.machine_pos["z"] - pos_z
if pos_a is not None:
if self.__work_offset["a"] != pos_a:
data_changed = True
self.__work_offset["a"] = pos_a
self.__work_pos["a"] = self.machine_pos["a"] - pos_a
if pos_b is not None:
if self.__work_offset["b"] != pos_b:
data_changed = True
self.__work_offset["b"] = pos_b
self.__work_pos["b"] = self.machine_pos["b"] - pos_b
if data_changed:
self.on_update_callback("work_offset:x", self.work_offset["x"])
self.on_update_callback("work_offset:y", self.work_offset["y"])
self.on_update_callback("work_offset:z", self.work_offset["z"])
self.on_update_callback("work_offset:a", self.work_offset["a"])
self.on_update_callback("work_offset:b", self.work_offset["b"])
self.on_update_callback("work_offset", self.work_offset)
self.on_update_callback("work_pos:x", self.work_pos["x"])
self.on_update_callback("work_pos:y", self.work_pos["y"])
self.on_update_callback("work_pos:z", self.work_pos["z"])
self.on_update_callback("work_pos:a", self.work_pos["a"])
self.on_update_callback("work_pos:b", self.work_pos["b"])
self.on_update_callback("work_pos", self.work_pos)
@property
def machine_pos_max(self) -> Dict[str, float]:
""" Getter. """
return self.__machine_pos_max
@machine_pos_max.setter
def machine_pos_max(self, pos: Dict[str, float]) -> None:
""" Setter. """
pos = keys_to_lower(pos)
data_changed = False
pos_x = pos.get("x")
pos_y = pos.get("y")
pos_z = pos.get("z")
pos_a = pos.get("a")
pos_b = pos.get("b")
if pos_x is not None:
if self.machine_pos_max["x"] != pos_x:
data_changed = True
self.machine_pos_max["x"] = pos_x
if pos_y is not None:
if self.machine_pos_max["y"] != pos_y:
data_changed = True
self.machine_pos_max["y"] = pos_y
if pos_z is not None:
if self.machine_pos_max["z"] != pos_z:
data_changed = True
self.machine_pos_max["z"] = pos_z
if pos_a is not None:
if self.machine_pos_max["a"] != pos_a:
data_changed = True
self.machine_pos_max["a"] = pos_a
if pos_b is not None:
if self.machine_pos_max["b"] != pos_b:
data_changed = True
self.machine_pos_max["b"] = pos_b
if data_changed:
self.on_update_callback("machine_pos_max:x", self.machine_pos_max["x"])
self.on_update_callback("machine_pos_max:y", self.machine_pos_max["y"])
self.on_update_callback("machine_pos_max:z", self.machine_pos_max["z"])
self.on_update_callback("machine_pos_max:a", self.machine_pos_max["a"])
self.on_update_callback("machine_pos_max:b", self.machine_pos_max["b"])
self.on_update_callback("machine_pos_max", self.machine_pos_max)
@property
def machine_pos_min(self) -> Dict[str, float]:
""" Getter. """
return self.__machine_pos_min
@machine_pos_min.setter
def machine_pos_min(self, pos: Dict[str, float]) -> None:
""" Setter. """
pos = keys_to_lower(pos)
data_changed = False
pos_x = pos.get("x")
pos_y = pos.get("y")
pos_z = pos.get("z")
pos_a = pos.get("a")
pos_b = pos.get("b")
if pos_x is not None:
if self.machine_pos_min["x"] != pos_x:
data_changed = True
self.machine_pos_min["x"] = pos_x
if pos_y is not None:
if self.machine_pos_min["y"] != pos_y:
data_changed = True
self.machine_pos_min["y"] = pos_y
if pos_z is not None:
if self.machine_pos_min["z"] != pos_z:
data_changed = True
self.machine_pos_min["z"] = pos_z
if pos_a is not None:
if self.machine_pos_min["a"] != pos_a:
data_changed = True
self.machine_pos_min["a"] = pos_a
if pos_b is not None:
if self.machine_pos_min["b"] != pos_b:
data_changed = True
self.machine_pos_min["b"] = pos_b
if data_changed:
self.on_update_callback("machine_pos_min:x", self.machine_pos_min["x"])
self.on_update_callback("machine_pos_min:y", self.machine_pos_min["y"])
self.on_update_callback("machine_pos_min:z", self.machine_pos_min["z"])
self.on_update_callback("machine_pos_min:a", self.machine_pos_min["a"])
self.on_update_callback("machine_pos_min:b", self.machine_pos_min["b"])
self.on_update_callback("machine_pos_min", self.machine_pos_min)
@property
def machine_pos(self) -> Dict[str, float]:
""" Getter. """
return self.__machine_pos
@machine_pos.setter
def machine_pos(self, pos: Dict[str, float]) -> None:
""" Setter. """
pos = keys_to_lower(pos)
data_changed = False
pos_x = pos.get("x")
pos_y = pos.get("y")
pos_z = pos.get("z")
pos_a = pos.get("a")
pos_b = pos.get("b")
if pos_x is not None:
if self.machine_pos["x"] != pos_x:
data_changed = True
self.machine_pos["x"] = pos_x
self.work_pos["x"] = pos_x - self.work_offset.get("x", 0)
if pos_y is not None:
if self.machine_pos["y"] != pos_y:
data_changed = True
self.machine_pos["y"] = pos_y
self.work_pos["y"] = pos_y - self.work_offset.get("y", 0)
if pos_z is not None:
if self.machine_pos["z"] != pos_z:
data_changed = True
self.machine_pos["z"] = pos_z
self.work_pos["z"] = pos_z - self.work_offset.get("z", 0)
if pos_a is not None:
if self.machine_pos["a"] != pos_a:
data_changed = True
self.machine_pos["a"] = pos_a
self.work_pos["a"] = pos_a - self.work_offset.get("a", 0)
if pos_b is not None:
if self.machine_pos["b"] != pos_b:
data_changed = True
self.machine_pos["b"] = pos_b
self.work_pos["b"] = pos_b - self.work_offset.get("b", 0)
if data_changed:
self.on_update_callback("machine_pos:x", self.machine_pos["x"])
self.on_update_callback("machine_pos:y", self.machine_pos["y"])
self.on_update_callback("machine_pos:z", self.machine_pos["z"])
self.on_update_callback("machine_pos:a", self.machine_pos["a"])
self.on_update_callback("machine_pos:b", self.machine_pos["b"])
self.on_update_callback("machine_pos", self.machine_pos)
self.on_update_callback("work_pos:x", self.work_pos["x"])
self.on_update_callback("work_pos:y", self.work_pos["y"])
self.on_update_callback("work_pos:z", self.work_pos["z"])
self.on_update_callback("work_pos:a", self.work_pos["a"])
self.on_update_callback("work_pos:b", self.work_pos["b"])
self.on_update_callback("work_pos", self.work_pos)
@property
def work_pos(self) -> Dict[str, float]:
""" Getter. """
return self.__work_pos
@work_pos.setter
def work_pos(self, pos: Dict[str, float]) -> None:
""" Setter. """
pos = keys_to_lower(pos)
data_changed = False
pos_x = pos.get("x")
pos_y = pos.get("y")
pos_z = pos.get("z")
pos_a = pos.get("a")
pos_b = pos.get("b")
if pos_x is not None:
if self.work_pos["x"] != pos_x:
data_changed = True
self.work_pos["x"] = pos_x
self.machine_pos["x"] = pos_x + self.__work_offset.get("x", 0)
if pos_y is not None:
if self.work_pos["y"] != pos_y:
data_changed = True
self.work_pos["y"] = pos_y
self.machine_pos["y"] = pos_y + self.__work_offset.get("y", 0)
if pos_z is not None:
if self.work_pos["z"] != pos_z:
data_changed = True
self.work_pos["z"] = pos_z
self.machine_pos["z"] = pos_z + self.__work_offset.get("z", 0)
if pos_a is not None:
if self.work_pos["a"] != pos_a:
data_changed = True
self.work_pos["a"] = pos_a
self.machine_pos["a"] = pos_a + self.__work_offset.get("a", 0)
if pos_b is not None:
if self.work_pos["b"] != pos_b:
data_changed = True
self.work_pos["b"] = pos_b
self.machine_pos["b"] = pos_b + self.__work_offset.get("b", 0)
if data_changed:
self.on_update_callback("machine_pos:x", self.machine_pos["x"])
self.on_update_callback("machine_pos:y", self.machine_pos["y"])
self.on_update_callback("machine_pos:z", self.machine_pos["z"])
self.on_update_callback("machine_pos:a", self.machine_pos["a"])
self.on_update_callback("machine_pos:b", self.machine_pos["b"])
self.on_update_callback("machine_pos", self.machine_pos)
self.on_update_callback("work_pos:x", self.work_pos["x"])
self.on_update_callback("work_pos:y", self.work_pos["y"])
self.on_update_callback("work_pos:z", self.work_pos["z"])
self.on_update_callback("work_pos:a", self.work_pos["a"])
self.on_update_callback("work_pos:b", self.work_pos["b"])
self.on_update_callback("work_pos", self.work_pos)
@property
def feed_rate(self) -> float:
""" Getter. """
return self.__feed_rate
@feed_rate.setter
def feed_rate(self, feed_rate: float) -> None:
""" Setter. """
if self.__feed_rate != feed_rate:
self.on_update_callback("feed_rate", feed_rate)
self.__feed_rate = feed_rate
@property
def feed_rate_max(self) -> Dict[str, float]:
""" Getter. """
return self.__feed_rate_max
@feed_rate_max.setter
def feed_rate_max(self, feedrate: Dict[str, float]) -> None:
""" Setter. """
data_changed = False
pos_x = feedrate.get("x")
pos_y = feedrate.get("y")
pos_z = feedrate.get("z")
pos_a = feedrate.get("a")
pos_b = feedrate.get("b")
if pos_x is not None:
if self.feed_rate_max["x"] != pos_x:
data_changed = True
self.feed_rate_max["x"] = pos_x
if pos_y is not None:
if self.feed_rate_max["y"] != pos_y:
data_changed = True
self.feed_rate_max["y"] = pos_y
if pos_z is not None:
if self.feed_rate_max["z"] != pos_z:
data_changed = True
self.feed_rate_max["z"] = pos_z
if pos_a is not None:
if self.feed_rate_max["a"] != pos_a:
data_changed = True
self.feed_rate_max["a"] = pos_a
if pos_b is not None:
if self.feed_rate_max["b"] != pos_b:
data_changed = True
self.feed_rate_max["b"] = pos_b
if data_changed:
self.on_update_callback("feed_rate_max:x", self.feed_rate_max["x"])
self.on_update_callback("feed_rate_max:y", self.feed_rate_max["y"])
self.on_update_callback("feed_rate_max:z", self.feed_rate_max["z"])
self.on_update_callback("feed_rate_max:a", self.feed_rate_max["a"])
self.on_update_callback("feed_rate_max:b", self.feed_rate_max["b"])
self.on_update_callback("feed_rate_max", self.feed_rate_max)
@property
def feed_rate_accel(self) -> Dict[str, float]:
""" Getter. """
return self.__feed_rate_accel
@feed_rate_accel.setter
def feed_rate_accel(self, feedrate: Dict[str, float]) -> None:
""" Setter. """
data_changed = False
pos_x = feedrate.get("x")
pos_y = feedrate.get("y")
pos_z = feedrate.get("z")
pos_a = feedrate.get("a")
pos_b = feedrate.get("b")
if pos_x is not None and self.feed_rate_accel["x"] != pos_x:
data_changed = True
self.feed_rate_accel["x"] = pos_x
if pos_y is not None and self.feed_rate_accel["y"] != pos_y:
data_changed = True
self.feed_rate_accel["y"] = pos_y
if pos_z is not None and self.feed_rate_accel["z"] != pos_z:
data_changed = True
self.feed_rate_accel["z"] = pos_z
if pos_a is not None and self.feed_rate_accel["a"] != pos_a:
data_changed = True
self.feed_rate_accel["a"] = pos_a
if pos_b is not None and self.feed_rate_accel["b"] != pos_b:
data_changed = True
self.feed_rate_accel["b"] = pos_b
if data_changed:
self.on_update_callback("feed_rate_accel:x", self.feed_rate_accel["x"])
self.on_update_callback("feed_rate_accel:y", self.feed_rate_accel["y"])
self.on_update_callback("feed_rate_accel:z", self.feed_rate_accel["z"])
self.on_update_callback("feed_rate_accel:a", self.feed_rate_accel["a"])
self.on_update_callback("feed_rate_accel:b", self.feed_rate_accel["b"])
self.on_update_callback("feed_rate_accel", self.feed_rate_accel)
@property
def feed_override(self) -> float:
""" Getter. """
return self.__feed_override
@feed_override.setter
def feed_override(self, feed_override: int) -> None:
""" Setter. """
if self.__feed_override != feed_override:
self.__feed_override = feed_override
self.on_update_callback("feed_override", self.feed_override)
@property
def rapid_override(self) -> float:
""" Getter. """
return self.__rapid_override
@rapid_override.setter
def rapid_override(self, rapid_override: int) -> None:
""" Setter. """
if self.__rapid_override != rapid_override:
self.__rapid_override = rapid_override
self.on_update_callback("rapid_override", self.rapid_override)
@property
def spindle_rate(self) -> float:
""" Getter. """
return self.__spindle_rate
@spindle_rate.setter
def spindle_rate(self, spindle_rate: int) -> None:
""" Setter. """
if self.__spindle_rate != spindle_rate:
self.__spindle_rate = spindle_rate
self.on_update_callback("spindle_rate", self.spindle_rate)
@property
def spindle_override(self) -> float:
""" Getter. """
return self.__spindle_override
@spindle_override.setter
def spindle_override(self, spindle_override: int) -> None:
""" Setter. """
if self.__spindle_override != spindle_override:
self.__spindle_override = spindle_override
self.on_update_callback("spindle_override", self.spindle_override)
@property
def limit_x(self) -> float:
""" Getter. """
return self.__limit_x
@limit_x.setter
def limit_x(self, limit_x: float) -> None:
""" Setter. """
if self.__limit_x != limit_x:
self.__limit_x = limit_x
self.on_update_callback("limit_x", self.limit_x)
@property
def limit_y(self) -> float:
""" Getter. """
return self.__limit_y
@limit_y.setter
def limit_y(self, limit_y: float) -> None:
""" Setter. """
if self.__limit_y != limit_y:
self.__limit_y = limit_y
self.on_update_callback("limit_y", self.limit_y)
@property
def limit_z(self) -> float:
""" Getter. """
return self.__limit_z
@limit_z.setter
def limit_z(self, limit_z: float) -> None:
""" Setter. """
if self.__limit_z != limit_z:
self.__limit_z = limit_z
self.on_update_callback("limit_z", self.limit_z)
@property
def limit_a(self) -> float:
""" Getter. """
return self.__limit_a
@limit_a.setter
def limit_a(self, limit_a: float) -> None:
""" Setter. """
if self.__limit_a != limit_a:
self.__limit_a = limit_a
self.on_update_callback("limit_a", self.limit_a)
@property
def limit_b(self) -> float:
""" Getter. """
return self.__limit_b
@limit_b.setter
def limit_b(self, limit_b: float) -> None:
""" Setter. """
if self.__limit_b != limit_b:
self.__limit_b = limit_b
self.on_update_callback("limit_b", self.limit_b)
@property
def probe(self) -> bool:
""" Getter. """
return self.__probe
@probe.setter
def probe(self, probe: bool) -> None:
""" Setter. """
if self.__probe != probe:
self.__probe = probe
self.on_update_callback("probe", self.probe)
@property
def pause(self) -> bool:
""" Getter. """
return self.__pause
@pause.setter
def pause(self, pause: bool, reason: Optional[str] = None) -> None:
""" Setter. """
if self.__pause != pause:
self.__pause = pause
self.on_update_callback("pause", self.pause)
if not pause:
self.pause_reason.clear()
self.on_update_callback("pause_reason", self.pause_reason)
@property
def pause_park(self) -> bool:
""" Getter. """
return self.__pause_park
@pause_park.setter
def pause_park(self, pause_park: bool) -> None:
""" Setter. """
if self.__pause_park != pause_park:
self.__pause_park = pause_park
self.on_update_callback("pause_park", self.pause_park)
@property
def parking(self) -> bool:
""" Getter. """
return self.__parking
@parking.setter
def parking(self, parking: bool) -> None:
""" Setter. """
if self.__parking != parking:
self.__parking = parking
self.on_update_callback("parking", self.parking)
@property
def halt(self) -> bool:
""" Getter. """
return self.__halt
@halt.setter
def halt(self, halt: bool) -> None:
""" Setter. """
if self.__halt != halt:
self.__halt = halt
self.on_update_callback("halt", self.halt)
if not halt:
self.halt_reason.clear()
self.on_update_callback("halt_reason", self.halt_reason)
@property
def door(self) -> bool:
""" Getter. """
return self.__door
@door.setter
def door(self, door: bool) -> None:
""" Setter. """
if self.__door != door:
self.__door = door
self.on_update_callback("door", self.door)
class StateMachineGrbl(StateMachineBase):
""" State Machine reflecting the state of a Grbl hardware controller. """
GRBL_STATUS_HEADERS = {b"MPos": "machine_pos",
b"WPos": "work_pos",
b"FS": "feed_rate", # Variable spindle.
b"F": "feed_rate", # Non variable spindle.
b"Pn": "inputPins",
b"WCO": "workCoordOffset",
b"Ov": "overrideValues",
b"Bf": "bufferState",
b"Ln": "lineNumber",
b"A": "accessoryState"
}
MACHINE_STATES = [
b"Idle", b"Run", b"Hold", b"Jog", b"Alarm", b"Door", b"Check", b"Home", b"Sleep"]
def __init__(self, on_update_callback: Callable[[str, Any], None]) -> None:
super().__init__(on_update_callback)
self.machine_state = b"Unknown"
def __str__(self) -> str:
output = super().__str__()
new_output = ("Grbl state: {self.machine_state}\n")
return output + new_output.format(self=self)
def parse_incoming(self, incoming: bytes) -> None:
""" Parse incoming string from Grbl controller. """
if incoming.startswith(b"error:"):
self._parse_incoming_error(incoming)
elif incoming.startswith(b"ok"):
assert False, "'ok' response should not have been passed to state machine."
elif incoming.startswith(b"ALARM:"):
self._parse_incoming_alarm(incoming)
elif incoming.startswith(b"<"):
self._parse_incoming_status(incoming)
elif incoming.startswith(b"["):
self._parse_incoming_feedback(incoming)
elif incoming.startswith(b"$"):
self._parse_setting(incoming)
elif incoming.startswith(b">"):
self._parse_startup(incoming)
elif incoming.startswith(b"Grbl "):
self._parse_welcome(incoming)
else:
print("Input not parsed: %s" % incoming.decode('utf-8'))
def _parse_incoming_error(self, incoming: bytes) -> None:
print(b"ERROR:", incoming, b"TODO")
def _parse_incoming_status(self, incoming: bytes) -> None:
""" "parse_incoming" determined a "status" message was received from the
Grbl controller. Parse the status message here. """
assert incoming.startswith(b"<") and incoming.endswith(b">")
incoming = incoming.strip(b"<>")
fields = incoming.split(b"|")
machine_state = fields[0]
self._set_state(machine_state)
for field in fields[1:]:
identifier, value = field.split(b":")
assert identifier in self.GRBL_STATUS_HEADERS
if identifier in [b"MPos", b"WPos", b"WCO"]:
self._set_coordinates(identifier, value)
elif identifier == b"Ov":
self._set_overrides(value)
elif identifier == b"FS":
feed, spindle = value.split(b",")
self.feed_rate = int(float(feed))
self.spindle_rate = int(float(spindle))
elif identifier == b"F":
self.feed_rate = int(float(value))
else:
print("TODO. Unparsed status field: ", identifier, value)
self.changes_made = True
def _parse_incoming_feedback_modal(self, msg: bytes) -> None:
""" Parse report on which modal option was last used for each group.
Report comes fro one of 2 places:
1. In response to a "$G" command, GRBL sends a G-code Parser State Message
in the format:
[GC:G0 G54 G17 G21 G90 G94 M5 M9 T0 F0.0 S0]
2. A Gcode line in the form "G0 X123 Y345 F2000" would update the "Motion"
group (G0) and the Feed group (F2000).
self.MODAL_COMMANDS maps these words to a group. eg: G0 is in the "motion" group. """
modals = msg.split(b" ")
update_units = False
for modal in modals:
units: Dict[str, Any] = self.MODAL_GROUPS["units"]
if modal.decode() in units:
modal_group = self.MODAL_COMMANDS[modal]
if modal_group in self.gcode_modal and \
self.gcode_modal[modal_group] != modal:
# Grbl has changed from mm to inches or vice versa.
update_units = True
if modal in self.MODAL_COMMANDS:
modal_group = self.MODAL_COMMANDS[modal]
self.gcode_modal[modal_group] = modal
elif chr(modal[0]).encode('utf-8') in self.MODAL_COMMANDS:
modal_group = self.MODAL_COMMANDS[chr(modal[0]).encode('utf-8')]
self.gcode_modal[modal_group] = modal
else:
assert False, "Gcode word does not match any mmodal group: %s" % \
modal.decode('utf-8')
self.on_update_callback("gcode_modal", self.gcode_modal)
assert not update_units, \
"TODO: Units have changed. Lots of things will need recalculated."
def _parse_incoming_feedback(self, incoming: bytes) -> None:
""" "parse_incoming" determined a "feedback" message was received from the
Grbl controller. Parse the message here and store parsed data. """
assert incoming.startswith(b"[") and incoming.endswith(b"]")
incoming = incoming.strip(b"[]")
msg_type, msg = incoming.split(b":")
if msg_type == b"MSG":
print(msg_type, incoming, "TODO")
elif msg_type in [b"GC", b"sentGcode"]:
self._parse_incoming_feedback_modal(msg)
elif msg_type == b"HLP":
# Response to a "$" (print help) command. Only ever used by humans.
pass
elif msg_type in [b"G54", b"G55", b"G56", b"G57", b"G58", b"G59", b"G28",
b"G30", b"G92", b"TLO", b"PRB"]:
# Response to a "$#" command.
print(msg_type, incoming, "TODO")
elif msg_type == b"VER":
if len(self.version) < 1:
self.version.append("")
self.version[0] = incoming.decode('utf-8')
elif msg_type == b"OPT":
while len(self.version) < 2:
self.version.append("")
self.version[1] = incoming.decode('utf-8')
elif msg_type == b"echo":
# May be enabled when building GRBL as a debugging option.
pass
else:
assert False, "Unexpected feedback packet type: %s" % msg_type.decode('utf-8')
def _parse_incoming_alarm(self, incoming: bytes) -> None:
""" "parse_incoming" determined a "alarm" message was received from the
Grbl controller. Parse the alarm here. """
print("ALARM:", incoming)
def _parse_setting(self, incoming: bytes) -> None:
""" "parse_incoming" determined one of the EPROM registers is being displayed.
Parse and save the value here. """
incoming = incoming.lstrip(b"$")
setting, value = incoming.split(b"=")
if setting == b"0":
# Step pulse, microseconds
pass
elif setting == b"1":
# Step idle delay, milliseconds
pass
elif setting == b"2":
# Step port invert, mask
pass
elif setting == b"3":
# Direction port invert, mask
pass
elif setting == b"4":
# Step enable invert, boolean
pass
elif setting == b"5":
# Limit pins invert, boolean
pass
elif setting == b"6":
# Probe pin invert, boolean
pass
elif setting == b"10":
# Status report, mask
pass
elif setting == b"11":
# Junction deviation, mm
pass
elif setting == b"12":
# Arc tolerance, mm
pass
elif setting == b"13":
# Report inches, boolean
pass
elif setting == b"20":
# Soft limits, boolean
pass
elif setting == b"21":
# Hard limits, boolean
pass
elif setting == b"22":
# Homing cycle, boolean
pass
elif setting == b"23":
# Homing dir invert, mask
pass
elif setting == b"24":
# Homing feed, mm/min
pass
elif setting == b"25":
# Homing seek, mm/min
pass
elif setting == b"26":
# Homing debounce, milliseconds
pass
elif setting == b"27":
# Homing pull-off, mm
pass
elif setting == b"30":
# Max spindle speed, RPM
pass
elif setting == b"31":
# Min spindle speed, RPM
pass
elif setting == b"32":
# Laser mode, boolean
pass
elif setting == b"100":
# X steps/mm
pass
elif setting == b"101":
# Y steps/mm
pass
elif setting == b"102":
# Z steps/mm
pass
elif setting == b"110":
# X Max rate, mm/min
value_int = int(float(value))
self.feed_rate_max = {"x": value_int}
elif setting == b"111":
# Y Max rate, mm/min
value_int = int(float(value))
self.feed_rate_max = {"y": value_int}
elif setting == b"112":
# Z Max rate, mm/min
value_int = int(float(value))
self.feed_rate_max = {"z": value_int}
elif setting == b"120":
# X Acceleration, mm/sec^2
value_int = int(float(value))
self.feed_rate_accel = {"x": value_int}
elif setting == b"121":
# Y Acceleration, mm/sec^2
value_int = int(float(value))
self.feed_rate_accel = {"y": value_int}
elif setting == b"122":
# Z Acceleration, mm/sec^2
value_int = int(float(value))
self.feed_rate_accel = {"z": value_int}
elif setting == b"130":
# X Max travel, mm
pass
elif setting == b"131":
# Y Max travel, mm
pass
elif setting == b"132":
# Z Max travel, mm
pass
else:
assert False, "Unexpected setting: %s %s" % (
setting.decode('utf-8'), value.decode('utf-8'))
@staticmethod
def _parse_startup(incoming: bytes) -> None:
""" "parse_incoming" determined Grbl's startup blocks are being received.
These are strings of Gcode that get executed on every restart. """
print("Grbl executed the following gcode on startup: %s" %
incoming.lstrip(b">").rstrip(b":ok").decode('utf-8'))
assert incoming.startswith(b">") and incoming.endswith(b":ok")
@staticmethod
def _parse_welcome(incoming: bytes) -> None:
""" "parse_incoming" determined Grbl's welcome message is being received.
Perform any tasks appropriate to a Grbl restart here. """
print("Startup:", incoming)
print("Startup successful. TODO: Clear Alarm states.")
def _set_overrides(self, value: bytes) -> None:
""" A message from Grbl reporting one of the overrides is being applied
has been received. Parse message and apply data here. """
feed_override, rapid_override, spindle_override = value.split(b",")
feed_override_int = int(float(feed_override))
rapid_override_int = int(float(rapid_override))
spindle_override_int = int(float(spindle_override))
if 10 <= feed_override_int <= 200:
self.feed_override = feed_override_int
if rapid_override_int in [100, 50, 20]:
self.rapid_override = rapid_override_int
if 10 <= spindle_override_int <= 200:
self.spindle_override = spindle_override_int
def _set_coordinates(self, identifier: bytes, value: bytes) -> None:
""" Set machine position according to message received from Grbl controller. """
if identifier == b"MPos":
self.machine_pos = self._parse_coordinates(value)
elif identifier == b"WPos":
self.work_pos = self._parse_coordinates(value)
elif identifier == b"WCO":
self.work_offset = self._parse_coordinates(value)
else:
print("Invalid format: %s Expected one of [MPos, WPos, WCO]" %
identifier.decode('utf-8'))
@staticmethod
def _parse_coordinates(string: bytes) -> Dict[str, float]:
""" Parse bytes for coordinate information. """
parts = string.split(b",")
if len(parts) < 3:
print(string, parts)
assert len(parts) >= 3, \
"Malformed coordinates: %s" % string.decode('utf-8')
assert len(parts) <= 4, \
"TODO: Handle more than 4 coordinates. %s" % string.decode('utf-8')
coordinates = {}
coordinates["x"] = float(parts[0])
coordinates["y"] = float(parts[1])
coordinates["z"] = float(parts[2])
if len(parts) > 3:
coordinates["a"] = float(parts[3])
return coordinates
def _set_state(self, state: bytes) -> None:
""" Apply State. State has been reported by Grbl controller. """
states = state.split(b":")
assert len(states) <= 2, "Invalid state: %s" % state.decode('utf-8')
state = states[0]
assert state in self.MACHINE_STATES, "Invalid state: %s" % state.decode('utf-8')
self.machine_state = state
if state in (b"Idle", b"Run", b"Jog", b"Home"):
self.pause = False
self.pause_park = False
self.halt = False
self.door = False
elif state == b"Hold":
# self.pause_park = False
self.halt = False
self.door = False
self.pause = True
elif state == b"Alarm":
self.pause = False
self.pause_park = False
self.door = False
self.halt = True
elif state == b"Door":
self.pause = False
self.pause_park = False
self.halt = False
self.door = True
elif state == b"Check":
pass
elif state == b"Sleep":
pass
<file_sep>""" Code required by all components. """
from typing import Dict, Any, Tuple, Deque, Optional
from collections import deque
class _ComponentBase:
""" General methods required by all components. """
Event = Tuple[str, Any]
# Single shared instance for all components.
_delayed_event_queue: Deque[Event] = deque()
_event_queue: Deque[Event] = deque()
_delay_events = [False,]
# Unique copy per instance.
event_subscriptions: Dict[str, Any]
_delivered: Deque[Any]
# Set this True for any derived class that is to be used as a plugin.
is_valid_plugin = False
# Overridden in base classes to be one of "controller", "interface" or "terminal".
plugin_type: Optional[str] = None
def __init__(self, label: str) -> None:
self.label: str = label
# Events to be delivered to this class with callback as value.
if not hasattr(self, "event_subscriptions"):
self.event_subscriptions: Dict[str, Any] = {
# "$COMPONENTNAME:$DESCRIPTION": ("$CALLBACK", None),
# "$COMPONENTNAME:$DESCRIPTION": ("$CALLBACK", $DEFAULTVALUE),
# "$COMPONENTNAME:$DESCRIPTION": ("$PROPERTYNAME", $DEFAULTVALUE)
}
self._delivered = deque()
self.debug_show_events = False
@classmethod
def get_classname(cls) -> str:
""" Return class name. """
return cls.__qualname__
def key_gen(self, tag: str) -> str:
""" Return an event name prepended with the component name.
eg: "componentName:event_name". """
return "%s:%s" % (self.label, tag)
# pylint: disable=R0201 # Method could be a function (no-self-use)
def early_update(self) -> bool:
""" To be called periodically.
Any housekeeping tasks should happen here. """
return True
def publish(self, event_name: str, event_value: Any) -> None:
""" Distribute an event to all subscribed components. """
if self._delay_events[0]:
print("##delayed", (event_name, event_value))
self._delayed_event_queue.append((event_name, event_value))
else:
self._event_queue.append((event_name, event_value))
def receive(self) -> None:
""" Receive events this object is subscribed to. """
#print(self.label, "receive", self._event_queue)
if not hasattr(self, "event_subscriptions"):
return
# Put any events that arrive from now on in the `_delayed_event_queue`
# instead of the regular `_event_queue`.
self._delay_events[0] = True
for event, value in self._event_queue:
if event in self.event_subscriptions:
self._delivered.append((event, value))
def update(self) -> None:
""" Called after events get delivered. """
# for event in self._delivered:
# print(self.label, event)
def _update(self) -> None:
""" Populate class variables and callbacks in response to configured events. """
# This will be done after /all/ events have been delivered for all
# components and the existing event queue cleared.
# Some of the actions performed by this method will cause new events to be
# scheduled.
for event_name, event_value in self._delivered:
action, default_value = self.event_subscriptions[event_name]
if event_value is None:
# Use the one configured in this class.
event_value = default_value
if not isinstance(action, str):
raise AttributeError("Action (in self.event_subscriptions) should be a "
"string of the property name")
if not hasattr(self, action):
raise AttributeError("Property for event \"%s\" does not exist." % action)
callback = getattr(self, action)
if callable(callback):
# Refers to a class method.
try:
callback(event_value)
except TypeError:
callback(event_name, event_value)
else:
# Refers to a class variable.
setattr(self, action, event_value)
<file_sep># pylint: disable=W0223
# Method '_handle_gcode' is abstract in class '_ControllerBase' but is not
# overridden (abstract-method)
""" Base class for hardware controllers that use a serial port to connect. """
from typing import Optional, List, Set, Dict
try:
from typing import Literal # type: ignore
except ImportError:
from typing_extensions import Literal # type: ignore
import os.path
import threading
import serial
import serial.tools.list_ports
# pylint: disable=E1101 # Module 'PySimpleGUIQt' has no 'XXXX' member (no-member)
from PySimpleGUI_loader import sg
from controllers._controller_base import _ControllerBase
from definitions import ConnectionState
SERIAL_INTERVAL = 0.02 # seconds
# Path to grbl-sim instance.
FAKE_SERIAL = "/tmp/ttyFAKE"
class _SerialControllerBase(_ControllerBase):
""" Base class for hardware controllers that use a serial port to connect. """
_serial_port_in_use: Set[str] = set()
def __init__(self, label: str = "serialController") -> None:
super().__init__(label)
#self.serial_port = "spy:///tmp/ttyFAKE?file=/tmp/serialspy.txt"
self.serial_port: str = ""
self.serial_baud = 115200
self._serial = None
self.testing: bool = False # Prevent _periodic_io() from blocking during tests.
self._serial_thread: Optional[threading.Thread] = None
self.event_subscriptions[self.key_gen("device_picker")] = ("set_device", None)
self.event_subscriptions[self.key_gen("serial_port_edit")] = ("set_device", None)
self.event_subscriptions[self.key_gen("device_scan")] = ("search_device", None)
self.ports: List[str] = []
self.device_picker: sg.Combo = None
def gui_layout_components(self) -> Dict[str, List[sg.Element]]:
""" GUI layout common to all derived classes. """
components = super().gui_layout_components()
self.device_picker = sg.Combo(values=["to_populate"],
size=(25, 1),
key=self.key_gen("device_picker"),
default_value=self.serial_port,
enable_events=True,
)
device_scan = sg.Button("Scan",
size=(5, 1),
key=self.key_gen("device_scan"),
tooltip="Scan for serial ports.",
)
self.search_device()
components["view_serial_port"] = [sg.Text("Serial port:",
size=(12, 1)),
sg.Text(self.serial_port,
key=self.key_gen("serial_port"))]
components["edit_serial_port"] = [sg.Text("Serial port:",
size=(12, 1)),
self.device_picker, device_scan]
return components
def set_device(self, device: str) -> None:
""" Set serial port when selected by menu. """
print("set_device", device)
if not device:
return
# Disconnect from any other serial port.
# TODO: Move this to the Save method?
self.disconnect()
if self.device_picker:
self.device_picker.Update(value=device)
self._modify_controller(self.key_gen("serial_port_edit"), device)
def search_device(self, _: str = "", __: None = None) -> None:
""" Search system for serial ports. """
self.ports = [x.device for x in serial.tools.list_ports.comports() \
if x.vid is not None \
and x.pid is not None \
and x.device is not None]
if os.path.exists(FAKE_SERIAL):
self.ports.append(FAKE_SERIAL)
if not self.ports:
self.ports.append("No serial ports autodetected")
# print("Found ports {}".format(self.ports))
if self.serial_port not in self.ports:
# Likely got this port name from the config file.
self.ports.append(self.serial_port)
if not self.serial_port:
self.serial_port = self.ports[0]
if self.device_picker:
try:
self.device_picker.Update(values=self.ports,
value=self.serial_port
)
print("search_device", self.serial_port)
except AttributeError:
# self.device_picker not configured.
pass
def connect(self) -> Literal[ConnectionState]:
""" Try to open serial port. Set connection_status to CONNECTING. """
# print("connect")
if self.connection_status in [
ConnectionState.CONNECTING,
ConnectionState.CONNECTED,
ConnectionState.MISSING_RESOURCE]:
return self.connection_status
if self.serial_port in self._serial_port_in_use:
self.connection_status = ConnectionState.BLOCKED
return self.connection_status
self.set_connection_status(ConnectionState.CONNECTING)
try:
self._serial = serial.serial_for_url(
self.serial_port, self.serial_baud, timeout=0)
except AttributeError:
try:
self._serial = serial.Serial(
self.serial_port, self.serial_baud, timeout=0)
except serial.serialutil.SerialException:
self.set_connection_status(ConnectionState.MISSING_RESOURCE)
except serial.serialutil.SerialException:
self.set_connection_status(ConnectionState.MISSING_RESOURCE)
self._serial_port_in_use.add(self.serial_port)
return self.connection_status
def disconnect(self) -> Literal[ConnectionState]:
""" Close serial port, shut down serial port thread, etc.
Set connection_status to DISCONNECTING. """
if self.connection_status in [
ConnectionState.DISCONNECTING,
ConnectionState.NOT_CONNECTED]:
return self.connection_status
if self.connection_status in [
ConnectionState.CONNECTED,
ConnectionState.CONNECTING]:
print("Disconnecting %s %s" % (self.label, self.serial_port))
self.set_desired_connection_status(ConnectionState.NOT_CONNECTED)
self.ready_for_data = False
if self._serial is None:
self.set_connection_status(ConnectionState.NOT_CONNECTED)
else:
self.set_connection_status(ConnectionState.DISCONNECTING)
self._serial_thread.join()
self._serial.close()
self.ready_for_data = False
return self.connection_status
def on_connected(self) -> None:
""" Executed when serial port first comes up.
Check serial port is open then start serial port thread.
Set connection_status to CONNECTED. """
if self._serial is None:
self.set_connection_status(ConnectionState.FAIL)
return
if not self._serial.is_open:
return
print("Connected %s %s" % (self.label, self.serial_port))
self.set_connection_status(ConnectionState.CONNECTED)
# Drain the buffer of any noise.
self._serial.flush()
while self._serial.readline():
pass
self._serial_thread = threading.Thread(target=self._periodic_io)
self._serial_thread.daemon = True
self._serial_thread.start()
def on_disconnected(self) -> None:
""" Executed when serial port is confirmed closed.
Check serial port was closed then set connection_status to NOT_CONNECTED. """
if self._serial is None:
self.set_connection_status(ConnectionState.FAIL)
return
if self._serial.is_open:
return
print("Serial disconnected.")
self.set_connection_status(ConnectionState.NOT_CONNECTED)
self._serial_port_in_use.discard(self.serial_port)
self._serial = None
self.publish(self.key_gen("state"),
"Connection state: %s" %
self.connection_status.name)
#self.search_device()
def _serial_write(self, data: bytes) -> bool:
""" Send data to serial port. """
if self._serial is None:
self.set_connection_status(ConnectionState.FAIL)
return False
try:
self._serial.write(data)
except serial.serialutil.SerialException:
self.set_connection_status(ConnectionState.FAIL)
return False
return True
def _serial_read(self) -> bytes:
""" Read data from serial port. """
if self._serial is None:
self.set_connection_status(ConnectionState.FAIL)
return b""
try:
if not self._serial.inWaiting():
return b""
except OSError:
self.set_connection_status(ConnectionState.FAIL)
line = None
try:
line = self._serial.readline()
except serial.serialutil.SerialException:
self.set_connection_status(ConnectionState.FAIL)
return line
def early_update(self) -> bool:
""" Called early in the event loop, before events have been received. """
if self.connection_status != self.desired_connection_status:
# Transition between connection states.
if self.connection_status is ConnectionState.CONNECTING:
# Connection process already started.
self.on_connected()
elif self.connection_status is ConnectionState.DISCONNECTING:
# Trying to disconnect.
self.on_disconnected()
elif self.connection_status in [ConnectionState.FAIL,
ConnectionState.MISSING_RESOURCE,
ConnectionState.BLOCKED]:
# A serial port error occurred either # while opening a serial port or
# on an already open port.
self.publish(self.key_gen("state"),
"Connection state: %s" %
self.connection_status.name)
self.set_desired_connection_status(ConnectionState.NOT_CONNECTED)
self.set_connection_status(ConnectionState.CLEANUP)
elif self.desired_connection_status is ConnectionState.CONNECTED:
# Start connection process.
self.connect()
elif self.desired_connection_status is ConnectionState.NOT_CONNECTED:
# Start disconnection.
self.disconnect()
return True
def _periodic_io(self) -> None:
""" Read from and write to serial port.
Called from a separate thread.
Blocks while serial port remains connected. """
# while self.connection_status is ConnectionState.CONNECTED:
# print("do read and write here.")
# self._time.sleep(SERIAL_INTERVAL)
# if self.testing:
# break
def update(self) -> None:
super().update()
if not self.ports:
self.search_device()
<file_sep>""" Plugin to provide GUI using PySimpleGUI. """
from typing import List, Dict, Any, Type
from enum import Enum
# pylint: disable=E1101 # Module 'PySimpleGUIQt' has no 'XXXX' member (no-member)
from PySimpleGUI_loader import sg
import core.common
from terminals._terminal_base import _TerminalBase, diff_dicts
from interfaces._interface_base import _InterfaceBase
from controllers._controller_base import _ControllerBase
class Gui(_TerminalBase):
""" Display GUI interface.
Will display the widgets in any other component loaded as a plugin's "layout"
property. See the "JogWidget" component as an example. """
# Active unless disabled with flag at runtime.
active_by_default = True
# Set this True for any derived class that is to be used as a plugin.
is_valid_plugin = True
def __init__(self, label: str = "gui") -> None:
super().__init__(label)
self.layout: List[List[sg.Element]] = []
self.selected_tab_key: str = ""
self._lastvalues: Dict[str, Any] = {}
self._diffvalues: Dict[str, Any] = {}
self.description = "GUI interface."
self.window: Any = None
self.config: Dict[str, Any] = {}
self.position = (1, 1) # TODO: Make the window position persistent.
self.size = (800, 600)
self._setup_done: bool = False
self._first_pass_done: bool = False
def setup(self,
interfaces: Dict[str, _InterfaceBase],
controllers: Dict[str, _ControllerBase],
controller_classes: Dict[str, Type[_ControllerBase]]) -> None:
""" Since this component relies on data from many other components,
we cannot do all the setup in __init__.
Call this once layout data exists. """
assert not self._setup_done, \
"WARNING: Attempting to run setup() more than once on %s" % self.label
super().setup(interfaces, controllers, controller_classes)
sg.SetOptions(element_padding=(1, 1))
#sg.theme("BlueMono")
sg.theme("DarkGrey")
if not self.sub_components:
class_pages = core.common.load_plugins("gui_pages")
# Instantiate all gui_pages.
self.sub_components = {page.label: page(controllers, controller_classes)
for _, page in class_pages}
layouts = {}
for key, value in {**self.interfaces,
**self.sub_components}.items():
if hasattr(value, "gui_layout"):
layouts[key] = value.gui_layout()
tabs: List[List[sg.Element]] = []
for label, layout in layouts.items():
tabs.append(sg.Tab(label, layout, key="tabs_%s" % label))
self.layout = [[sg.Menu(self._menu_bar(), key=self.key_gen("menubar")),
sg.TabGroup([tabs], key=self.key_gen("tabs"))]]
self.window = sg.Window("CNCtastic",
self.layout,
resizable=True,
return_keyboard_events=True,
#auto_size_text=False,
#auto_size_buttons=False,
#default_element_size=(4, 2),
#default_button_element_size=(4, 2),
use_default_focus=False,
location=self.position,
size=self.size,
)
self.window.Finalize()
# Subscribe to events matching GUI widget keys.
for event in self.window.AllKeysDict:
self.event_subscriptions[event] = None
self.event_subscriptions[self.key_gen("restart")] = ("_restart", None)
self.event_subscriptions["__coordinator__:new_controller"] = ("_restart", None)
self.event_subscriptions["gui:set_tab"] = ("_set_tab", True)
self._setup_done = True
self._first_pass_done = False
def _menu_bar(self) -> List[Any]:
""" Layout of window menu bar. """
controllers = []
for label in self.controllers:
controllers.append("%s::__FILE_OPEN_CONTROLLER_%s" % (label, label))
menu = [['&File', ['&Open', ['&Gcode::__FILE_OPEN_GCODE',
'&Controller::__FILE_OPEN_CONTROLLER', controllers],
'&Save', ['&Gcode::__FILE_SAVE_GCODE',
'&Controller::__FILE_SAVE_CONTROLLER'],
'&New', ['&Gcode::__FILE_NEW_GCODE',
'&Controller::__FILE_NEW_CONTROLLER'],
'---',
'E&xit::_EXIT_']
],
['&Edit', ['Paste', ['Special', 'Normal',], 'Undo'],],
['&Help', '&About...'],]
return menu
def _on_menubar(self, event: str, value: Any) -> None:
""" Called in response to a "menubar" event. """
print("_on_menubar", event, value)
if not value:
return
label, key = value.split("::__", 1)
tokens = key.split("_")
if tokens[0] == "FILE":
if tokens[1] == "OPEN":
if tokens[2] == "GCODE":
# TODO
self.publish("gui:select_file_gcode", None)
elif tokens[2] == "CONTROLLER":
self.publish("%s:set_active" % label, True)
elif tokens[1] == "NEW":
if tokens[2] == "GCODE":
# TODO
pass
elif tokens[2] == "CONTROLLER":
self.publish("##new_controller:picker", "##new_controller")
#self.publish("request_new_controller", label)
def early_update(self) -> bool:
""" To be called once per frame.
Returns:
bool: True: Continue execution.
False: An "Exit" or empty event occurred. Stop execution. """
if not self._setup_done:
return False
event, values = self.window.read(timeout=10)
if event is None or values in [None, "_EXIT_"]:
print("Quitting via %s" % self.label)
return False
self._diffvalues = diff_dicts(self._lastvalues, values)
self._lastvalues = values
# Combine events with the values. Put the event key in there with empty value.
if not event == "__TIMEOUT__":
key_value = None
if len(event) == 1 or event.startswith("special "):
# This is a key-press of a regular "qwerty" key.
key_value = event
event = "gui:keypress"
if event not in self._diffvalues:
self._diffvalues[event] = key_value or None
if(event != "__TIMEOUT__" or self._diffvalues) and self.debug_show_events:
print(event, self._diffvalues)
self._publish_widgets()
return event not in (None, ) and not event.startswith("Exit")
def update(self) -> None:
super().update()
if not self._first_pass_done:
self._first_pass_done = True
self.publish(self.key_gen("has_restarted"), True)
if self.selected_tab_key:
self.window[self.selected_tab_key].select()
def _publish_widgets(self) -> None:
""" Publish all button presses and other GUI widget updates. """
for event_, value in self._diffvalues.items():
#if isinstance(value, str):
# value = value.strip()
self.publish(event_, value)
def receive(self) -> None:
""" Receive events this object is subscribed to. """
super().receive()
# Since latency is important in the GUI, lets update the screen as soon
# as possible after receiving the event.
# This also helps with event loops when multiple things update a widget
# that in turn sends an event.
while self._delivered:
event, value = self._delivered.popleft()
if event in (self.key_gen("restart"), "__coordinator__:new_controller"):
self._restart()
continue
if event == "gui:set_tab":
self._set_tab(value)
continue
if not self.window.FindElement(event, silent_on_error=True):
print("WARNING: Unexpected event: %s" % event)
continue
if(hasattr(self.window[event], "metadata") and
self.window[event].metadata and
self.window[event].metadata.get("skip_update", False)):
# GUI widget has "skip_update" set so will not use the default
# update method.
continue
if isinstance(value, Enum):
self.window[event].update(value.name)
elif isinstance(value, float):
if int(value) == value:
value = int(value)
self.window[event].update(value)
elif event == self.key_gen("menubar"):
self._on_menubar(event, value)
elif value == (None, None):
continue
else:
try:
self.window[event].update(value.rstrip())
except IndexError:
pass
except AttributeError:
# Some PySimpleGUI element types can't be updates until they
# have been populated with data. eg: the "Graph" element in
# PySimpleGUIQt.
pass
def _restart(self) -> None:
self.selected_tab_key = self.window[self.key_gen("tabs")].get()
try:
# If using QT...
self.size = self.window.QT_QMainWindow.size().toTuple()
geom = self.window.QT_QMainWindow.frameGeometry()
self.position = (geom.left(), geom.top())
except AttributeError:
self.size = self.window.Size
self.position = self.window.CurrentLocation()
print("restart",
self.position,
self.size,
self.selected_tab_key)
self.close()
self.setup(self.interfaces, self.controllers, self.controller_classes)
def close(self) -> None:
""" Close GUI window. """
if not self._setup_done:
return
self._setup_done = False
self.window.close()
def __del__(self) -> None:
self.close()
def _set_tab(self, tab_key: str) -> None:
""" Set which tab is active in response to "set_tab" event. """
self.selected_tab_key = "tabs_%s" % tab_key
self.window[self.selected_tab_key].select()
<file_sep># pylint: disable=E1101 # Module 'PySimpleGUIQt' has no 'XXXX' member (no-member)
""" Display Gcode and machine movement in the GUI. """
from typing import List, Tuple, Dict, Union, Optional, Any, Type
import numpy as np
from PySide2.QtCore import Qt, QRectF
from PySide2.QtGui import QPainter
from PySimpleGUI_loader import sg
from pygcode import GCodeRapidMove
from controllers._controller_base import _ControllerBase
from gui_pages._page_base import _GuiPageBase
NODE_SIZE = 3
class Geometry:
""" A collection of nodes and edges that make up some geometry in 3d space. """
def __init__(self, graph_elem: sg.Graph) -> None:
self.graph_elem = graph_elem
self.nodes = np.zeros((0, 4))
self.display_nodes = np.zeros((0, 4))
self.edges: List[Tuple[int, int, Optional[str]]] = []
self.update_edges_from: int = 0
self.calculate_center_include = True
self.node_circle_offset = (-NODE_SIZE / 2, NODE_SIZE / 2, 0, 0)
def calculate_nodes_center(self) -> Tuple[float, float, float]:
""" Return the center of all the nodes. """
extremities = self.calculate_bounding_box()
return (-(extremities[0][0] + extremities[1][0]) / 2,
-(extremities[0][1] + extremities[1][1]) / 2,
-(extremities[0][2] + extremities[1][2]) / 2)
def calculate_bounding_box(self) -> \
Tuple[Tuple[float, float, float], Tuple[float, float, float]]:
""" Return the maximum and minimum values for each axis. """
if not self.nodes.any():
return ((0, 0, 0), (1, 1, 1))
max_x = self.nodes[0][0]
min_x = self.nodes[0][0]
max_y = self.nodes[0][1]
min_y = self.nodes[0][1]
max_z = self.nodes[0][2]
min_z = self.nodes[0][2]
for node in self.nodes:
if node[0] > max_x:
max_x = node[0]
if node[0] < min_x:
min_x = node[0]
if node[1] > max_y:
max_y = node[1]
if node[1] < min_y:
min_y = node[1]
if node[2] > max_z:
max_z = node[2]
if node[2] < min_z:
min_z = node[2]
return ((min_x, min_y, min_z), (max_x, max_y, max_z))
def redraw(self) -> None:
""" Reset display_nodes so they get recalculated. """
self.display_nodes = np.zeros((0, 4))
self.update_edges_from = 0
self.graph_elem.Erase()
def transform(self,
nodes: np.array,
scale: float,
rotate: Tuple[float, float, float],
center: Tuple[float, float, float]
) -> np.array:
""" Apply a transformation defined by a center of points, desired scale
and desired viewing angle. """
canvas_size = self.graph_elem.CanvasSize
modifier = self.translation_matrix(*center)
modifier = np.dot(modifier, self.scale_matrix(scale, scale, scale))
modifier = np.dot(modifier, self.rotate_z_matrix(rotate[2]))
modifier = np.dot(modifier, self.rotate_y_matrix(rotate[1]))
modifier = np.dot(modifier, self.rotate_x_matrix(rotate[0]))
modifier = np.dot(modifier, self.translation_matrix(
canvas_size[0] / 2, canvas_size[1] / 2, 0))
return_nodes = np.dot(nodes, modifier)
return return_nodes
@classmethod
def translation_matrix(cls,
dif_x: float = 0,
dif_y: float = 0,
dif_z: float = 0) -> np.array:
""" Return matrix for translation along vector (dif_x, dif_y, dif_z). """
return np.array([[1, 0, 0, 0],
[0, 1, 0, 0],
[0, 0, 1, 0],
[dif_x, dif_y, dif_z, 1]])
@classmethod
def scale_matrix(cls,
scale_x: float = 0,
scale_y: float = 0,
scale_z: float = 0) -> np.array:
""" Return matrix for scaling equally along all axes. """
return np.array([[scale_x, 0, 0, 0],
[0, scale_y, 0, 0],
[0, 0, scale_z, 0],
[0, 0, 0, 1]])
@classmethod
def rotate_x_matrix(cls, radians: float) -> np.array:
""" Return matrix for rotating about the x-axis by 'radians' radians """
cos = np.cos(radians)
sin = np.sin(radians)
return np.array([[1, 0, 0, 0],
[0, cos, -sin, 0],
[0, sin, cos, 0],
[0, 0, 0, 1]])
@classmethod
def rotate_y_matrix(cls, radians: float) -> np.array:
""" Return matrix for rotating about the y-axis by 'radians' radians """
cos = np.cos(radians)
sin = np.sin(radians)
return np.array([[cos, 0, sin, 0],
[0, 1, 0, 0],
[-sin, 0, cos, 0],
[0, 0, 0, 1]])
@classmethod
def rotate_z_matrix(cls, radians: float) -> np.array:
""" Return matrix for rotating about the z-axis by 'radians' radians """
cos = np.cos(radians)
sin = np.sin(radians)
return np.array([[cos, -sin, 0, 0],
[sin, cos, 0, 0],
[0, 0, 1, 0],
[0, 0, 0, 1]])
def add_nodes(self, nodes: np.array) -> None:
""" Add points to geometry. """
ones_column = np.ones((len(nodes), 1))
ones_added = np.hstack((nodes, ones_column))
self.nodes = np.vstack((self.nodes, ones_added))
def add_edges(self, edge_list: List[Tuple[int, int, Optional[str]]]) -> None:
""" Add edges between 2 nodes. """
self.edges += edge_list
def update(self,
scale: float,
rotate: Tuple[float, float, float],
center: Tuple[float, float, float]
) -> bool:
""" Draw/redraw any nodes and edges that have been added since last update.
Returns: Boolean value indicating if anything was done. """
work_done = False
color: Optional[str]
if len(self.nodes) > len(self.display_nodes):
work_done = True
update_nodes_from = len(self.display_nodes)
new_nodes = self.transform(
self.nodes[update_nodes_from:], scale, rotate, center)
color = "blue"
for node in new_nodes:
corrected = node + self.node_circle_offset
self.graph_elem.DrawCircle(tuple(corrected[:2]), NODE_SIZE, color)
self.display_nodes = np.vstack((self.display_nodes, new_nodes))
if self.update_edges_from < len(self.edges):
work_done = True
for edge in self.edges[self.update_edges_from:]:
color = "blue"
if len(edge) > 2:
color = edge[2]
node_0 = self.display_nodes[edge[0]]
node_1 = self.display_nodes[edge[1]]
self.graph_elem.DrawLine(tuple(node_0[:2]),
tuple(node_1[:2]),
width=10,
color=color)
self.update_edges_from = len(self.edges)
return work_done
class TestCube(Geometry):
""" A Geometry object with some sample data added. """
def __init__(self, graph_elem: sg.Graph) -> None:
super().__init__(graph_elem)
self.add_nodes([(x, y, z) for x in (0, 1) for y in (0, 1) for z in (0, 1)])
self.add_edges([(0, 4, "red")])
self.add_edges([(n, n + 4, None) for n in range(1, 4)])
self.add_edges([(n, n + 1, None) for n in range(0, 8, 2)])
self.add_edges([(n, n + 2, None) for n in (0, 1, 4, 5)])
class Axis(Geometry):
""" Geometry object displaying X, Y & Z axis. """
def __init__(self, graph_elem: sg.Graph) -> None:
super().__init__(graph_elem)
self.add_nodes([(0, 0, 0), (10, 0, 0), (0, 10, 0), (0, 0, 10)])
self.add_edges([(0, 1, "red"), (0, 2, "green"), (0, 3, "blue")])
self.calculate_center_include = False
class CanvasWidget(_GuiPageBase):
""" Allows user to directly control various machine settings. eg: Jog the
head to given coordinates. """
# Set this True for any derived class that is to be used as a plugin.
is_valid_plugin = True
label = "canvasWidget"
def __init__(self,
controllers: Dict[str, _ControllerBase],
controller_classes: Dict[str, Type[_ControllerBase]]) -> None:
super().__init__(controllers, controller_classes)
width = 800
height = 800
self.graph_elem = sg.Graph((width, height),
(0, 0),
(width, height),
key="+GRAPH+",
tooltip="Graph",
background_color="white",
enable_events=True,
drag_submits=True)
self.rotation: Dict[str, float] = {"x": 0.6161012, "y": 0, "z": 3.141 / 4}
self.scale: float = 50
self.mouse_move: Optional[Tuple[float, float]] = None
# Display a cube for debugging purposes.
self.structures: Dict[str, Geometry] = {}
self.structures["test_cube"] = TestCube(self.graph_elem)
self.structures["axis"] = Axis(self.graph_elem)
self.structures["machine_position"] = Geometry(self.graph_elem)
self.structures["gcode"] = Geometry(self.graph_elem)
self.center: Tuple[float, float, float] = self.calculate_center()
self.event_subscriptions = {
"active_controller:machine_pos": ("_machine_pos_handler", None),
"gui:keypress": ("_keypress_handler", None),
"gui:restart": ("redraw", None),
"gui:has_restarted": ("_startup", None),
"core_gcode:parsed_gcode_loaded": ("_gcode_handler", None),
}
self.dirty: bool = True
def _startup(self, _: Any) -> None:
try:
self.graph_elem.QT_QGraphicsView.mouse_moveEvent = self.mouse_move_event
self.graph_elem.QT_QGraphicsView.mousePressEvent = self.mouse_press_event
self.graph_elem.QT_QGraphicsView.mouseReleaseEvent = self.mouse_release_event
self.graph_elem.QT_QGraphicsView.resizeEvent = self.resize_event
self.graph_elem.QT_QGraphicsView.wheelEvent = self.wheel_event
self.graph_elem.QT_QGraphicsView.DragMode = \
self.graph_elem.QT_QGraphicsView.ScrollHandDrag
self.graph_elem.QT_QGraphicsView.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
self.graph_elem.QT_QGraphicsView.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
self.graph_elem.QT_QGraphicsView.setRenderHints(
QPainter.Antialiasing|QPainter.SmoothPixmapTransform)
#self.graph_elem.QT_QGraphicsView.setAlignment(Qt.AlignCenter)
except AttributeError:
pass
self.dirty = True
def _machine_pos_handler(self, pos: Dict[str, float]) -> None:
""" Event handler for "active_controller:machine_pos".
Called when the machine position is updated."""
machine_position = self.structures["machine_position"]
machine_position.add_nodes([(pos["x"], pos["y"], pos["z"])])
def _gcode_handler(self, gcode: str) -> None:
""" Draw gcode primitives. """
# TODO
print("canvas._gcode_handler")
nodes = []
edges = []
for section in gcode:
print("section:", section.name)
for line in section.lines:
if line.iterations[0].errors:
continue
if not line.gcode_word_key:
continue
point = line.iterations[0].metadata.point
if np.isnan(np.sum(point)):
continue
nodes.append(point)
color = "green"
if line.gcode_word_key == GCodeRapidMove().word_key:
color = "red"
if len(nodes) > 1:
edges.append((len(nodes) - 2, len(nodes) - 1, color))
self.structures["gcode"].add_nodes(nodes)
self.structures["gcode"].add_edges(edges)
self.dirty = True
def _keypress_handler(self, key: Union[int, slice]) -> None:
# TODO: Replace "special xxxx" with sensible named variable.
if key == "special 16777234":
self.rotation["z"] += 0.01
elif key == "special 16777236":
self.rotation["z"] -= 0.01
elif key == "special 16777235":
self.rotation["x"] -= 0.01
elif key == "special 16777237":
self.rotation["x"] += 0.01
elif key == "+":
self.scale *= 1.1
elif key == "-":
self.scale /= 1.1
self.redraw()
def gui_layout(self) -> List[List[sg.Element]]:
""" Layout information for the PySimpleGUI interface. """
frame = [
[self.graph_elem, sg.Stretch()],
]
layout = [
[sg.Text('Plot test', size=(50, 2), key="foobar")],
[sg.Frame('Graphing Group', frame)],
]
return layout
def calculate_bounding_box(self) -> Tuple[Tuple[float, float, float],
Tuple[float, float, float]]:
""" Calculate minimum and maximum coordinate values encompassing all points. """
# Would have preferred to use None here but mypy doesn't like Optional[float].
max_value: float = 9999999999
combined_minimums: List[float] = [max_value, max_value, max_value]
combined_maximums: List[float] = [-max_value, -max_value, -max_value]
for structure in self.structures.values():
if not structure.calculate_center_include:
continue
extremities = structure.calculate_bounding_box()
mimimums = extremities[0]
for index, value in enumerate(mimimums):
assert -max_value < value < max_value, "Coordinate out of range."
if value < combined_minimums[index]:
combined_minimums[index] = value
maximums = extremities[1]
for index, value in enumerate(maximums):
assert -max_value < value < max_value, "Coordinate out of range."
if value > combined_maximums[index]:
combined_maximums[index] = value
for value in combined_minimums:
if value == max_value:
return (0, 0, 0)
for value in combined_maximums:
if value == -max_value:
return (0, 0, 0)
return (combined_minimums, combined_maximums)
def calculate_center(self) -> Tuple[float, float, float]:
""" Calculate the center of all geometry. """
combined_minimums, combined_maximums = self.calculate_bounding_box()
return (-(combined_minimums[0] + combined_maximums[0]) / 2,
-(combined_minimums[1] + combined_maximums[1]) / 2,
-(combined_minimums[2] + combined_maximums[2]) / 2)
def redraw(self, *_: Any) -> None:
""" Redraw all geometry to screen. """
for structure in self.structures.values():
structure.redraw()
self.dirty = False
def mouse_move_event(self, event: Any) -> None:
""" Called on mouse button move inside canvas element. """
if self.mouse_move:
move = (event.x() - self.mouse_move[0], event.y() - self.mouse_move[1])
self.mouse_move = (event.x(), event.y())
self.center = (
self.center[0] + move[0] / 10,
self.center[1] + move[1] / 10,
self.center[2])
self.dirty = True
def mouse_press_event(self, event: Any) -> None:
""" Called on mouse button down inside canvas element. """
print("There are", len(self.graph_elem.QT_QGraphicsView.items(event.pos())),
"items at position", self.graph_elem.QT_QGraphicsView.mapToScene(event.pos()))
self.graph_elem.QT_QGraphicsView.setDragMode(
self.graph_elem.QT_QGraphicsView.ScrollHandDrag)
self.mouse_move = (event.x(), event.y())
def mouse_release_event(self, event: Any) -> None:
""" Called on mouse button release inside canvas element. """
self.graph_elem.QT_QGraphicsView.setDragMode(self.graph_elem.QT_QGraphicsView.NoDrag)
self.mouse_move = None
def resize_event(self, event: Any) -> None:
""" Called on window resize. """
print(event)
#self.dirty = True
def wheel_event(self, event: Any) -> None:
""" Called on mousewheel inside canvas element. """
if event.delta() > 0:
scale = 1.1
else:
scale = 0.9
self.graph_elem.QT_QGraphicsView.scale(scale, scale)
#self.scale += float(event.delta()) / 16
#if self.scale < 1:
# self.scale = 1
#else:
# self.dirty = True
def set_viewport(self) -> None:
for structure in self.structures.values():
if len(structure.nodes) != len(structure.display_nodes):
# This structure is not finished being drawn to the scene.
# We don't want to re-size until everything is displayed or
# we might flicker between scales as things are drawing.
return
self.center = self.calculate_center()
try:
# If we are using QT...
screenRect = self.graph_elem.QT_QGraphicsView.scene().itemsBoundingRect()
self.graph_elem.QT_QGraphicsView.setSceneRect(screenRect)
except AttributeError:
pass
def update(self) -> None:
""" Update all Geometry objects. """
super().update()
if self.dirty:
self.redraw()
rotate = (self.rotation["x"], self.rotation["y"], self.rotation["z"])
work_done = False
for structure in self.structures.values():
work_done |= structure.update(self.scale, rotate, self.center)
if work_done:
self.set_viewport()
<file_sep>""" Mock controller for use in unit-tests. """
from controllers.debug import DebugController
from definitions import ConnectionState
class MockController(DebugController):
""" Mock controller for use in unit-tests. """
# Set False as we don't want it to be used as a plugin.
is_valid_plugin = False
def early_update(self) -> bool:
""" Called early in the event loop, before events have been received. """
if self.connection_status == ConnectionState.CONNECTING:
self.connection_status = ConnectionState.CONNECTED
elif self.connection_status == ConnectionState.DISCONNECTING:
self.connection_status = ConnectionState.NOT_CONNECTED
if self.connection_status == ConnectionState.CONNECTED:
self.ready_for_data = True
else:
self.ready_for_data = False
return True
<file_sep>""" Add code to be tested to the path so includes can find it. """
import sys
import os
TESTDIR = os.path.dirname(__file__)
SRCDIR = '../'
sys.path.insert(0, os.path.abspath(os.path.join(TESTDIR, SRCDIR)))
<file_sep>""" Parse and process gcode supplied in text format by event. """
from typing import Any, List, Set
from collections import namedtuple
import numpy as np
from pygcode import Line, GCodeMotion
from pygcode.exceptions import GCodeWordStrError
from core_components._core_component_base import _CoreComponentBase
Section = namedtuple("Section", ["name", "lines", "errors", "enabled", "expanded"])
ParsedLine = namedtuple("ParsedLine", ["raw", "gcode_word_key", "count", "iterations"])
GcodeIteration = namedtuple("GcodeIteration", ["gcode", "errors", "metadata"])
GcodeMetadata = namedtuple("GcodeMetadata", ["point", "distance"])
class CoreGcode(_CoreComponentBase):
""" Parse and process gcode supplied in text format by event. """
# Set this True for any derived class that is to be used as a plugin.
is_valid_plugin = True
label = "__core_gcode__"
def __init__(self) -> None:
super().__init__(self.label)
self.gcode_raw: List[str] = []
self.gcode_raw_error: bool = False
self.gcode_parsed: List[Section] = []
self.section_names_previous: Set[str] = set()
self.event_subscriptions["core_gcode:gcode_raw_loaded"] = (
"_on_gcode_raw", "")
def _on_gcode_raw(self, _: str, gcode_raw: Any) -> None:
self.gcode_raw = gcode_raw
self.gcode_parsed = []
self.section_names_previous = set()
section_name = "unnamed"
section_content: List[ParsedLine] = []
section_errors: List[str] = []
section_expanded = False
section_enabled = False
last_point = np.array([np.nan, np.nan, np.nan])
count = 0
for line in gcode_raw:
(section_name_parsed,
section_enabled_parsed,
section_expanded_parsed,
parsed_line) = self._gcode_parse_line(last_point, count, line)
if section_name_parsed:
# New section.
if section_content:
# Save old section.
self.gcode_parsed.append(Section(section_name,
section_content,
section_errors,
section_enabled,
section_expanded))
section_content = []
section_errors = []
section_expanded = False
section_enabled = False
section_name = section_name_parsed
else:
if section_enabled_parsed is not None:
section_enabled = section_enabled_parsed
if section_expanded_parsed is not None:
section_expanded = section_expanded_parsed
if parsed_line.iterations[0].gcode:
# Valid gcode line containing more than just comment.
last_point = parsed_line.iterations[0].metadata.point
if section_enabled_parsed is None and section_expanded_parsed is None:
section_content.append(parsed_line)
count += 1
if parsed_line.iterations[0].errors:
for error_ in parsed_line.iterations[0].errors:
section_errors.append("%s: %s" % (error_, line))
if section_content:
# Save remainder of section.
self.gcode_parsed.append(Section(section_name,
section_content,
section_errors,
section_enabled,
section_expanded))
self.publish("core_gcode:parsed_gcode_loaded", self.gcode_parsed)
def _gcode_parse_line(self,
last_point: np.array,
count: int,
line: str) -> (str, Any, Any, ParsedLine):
section_name = ""
errors = []
point = np.array([np.nan, np.nan, np.nan])
gcode_word_key = None
distance = None
gcode_line = None
enabled = None
expanded = None
try:
gcode_line = Line(line)
except GCodeWordStrError:
errors.append("Invalid gcode")
if gcode_line:
point, point_errors, gcode_word_key = self._gcode_to_point(gcode_line, last_point)
errors += point_errors
distance = self._dist_between_points(last_point, point)
if np.isnan(distance):
distance = None
if isinstance(gcode_line, Line) and not gcode_line.block and gcode_line.comment:
# Only a comment in this line. No other gcode.
comment = str(gcode_line.comment)
if comment.upper().replace(" ", "").startswith("(BLOCK-NAME:"):
new_section_name = comment.split(":", 1)[1].rstrip(")").strip()
section_name = self._increment_name(new_section_name)
elif comment.upper().replace(" ", "").startswith("(BLOCK-ENABLE:"):
value = comment.split(":", 1)[1].rstrip(")").strip()
try:
enabled = bool(int(value))
except ValueError:
enabled = False
elif comment.upper().replace(" ", "").startswith("(BLOCK-EXPAND:"):
value = comment.split(":", 1)[1].rstrip(")").strip()
try:
expanded = bool(int(value))
except ValueError:
expanded = False
metadata = GcodeMetadata(point, distance)
gcode_iteration = GcodeIteration(gcode_line, errors, metadata)
return (section_name,
enabled,
expanded,
ParsedLine(line, gcode_word_key, count, [gcode_iteration]))
def _increment_name(self, name):
""" Gcode sections should have a unique name for display. """
try:
label, number = name.rsplit(" | ", 1)
number = int(number)
except ValueError:
label = name
number = 2
if name not in self.section_names_previous:
self.section_names_previous.add(name)
return name
while "%s | %s" % (name, number) in self.section_names_previous:
number += 1
name = "%s | %s" % (name, number)
self.section_names_previous.add(name)
return name
def _gcode_append_comment(self, line: Line, comment: str) -> None:
""" Add new comment or append to existing comment. """
line.comment = "%s ; %s" % (line.comment, comment)
def _dist_between_points(self, point_1: np.array, point_2: np.array) -> Any:
return np.linalg.norm(point_1 - point_2)
def _gcode_to_point(self, line: Line, last: np.array) -> np.array:
return_value = last.copy()
gcode_word_key = None
errors = []
found_motion = False
for gcode in line.block.gcodes:
if isinstance(gcode, GCodeMotion):
if found_motion:
errors.append("Multiple GCodeMotion on one line")
found_motion = True
params = gcode.get_param_dict()
if "X" in params:
return_value[0] = params["X"]
if "Y" in params:
return_value[1] = params["Y"]
if "Z" in params:
return_value[2] = params["Z"]
gcode_word_key = gcode.word_key
return (return_value, errors, gcode_word_key)
<file_sep>""" Definitions that are called from everywhere throughout the codebase. """
from enum import Enum
from pygcode import (GCodeLinearMove, GCodeRapidMove, GCodeArcMoveCW,
GCodeArcMoveCCW, GCodeStraightProbe, GCodeCancelCannedCycle,
GCodeIncrementalDistanceMode, GCodeAbsoluteDistanceMode,
GCodeUseMillimeters, GCodeUseInches,
GCodeCoordSystemOffset, GCodeResetCoordSystemOffset,
GCodeRestoreCoordSystemOffset)
class ConnectionState(Enum):
""" Connection state of one of the controller components.
Used extensively by _ControllerBase and it's derivatives."""
UNKNOWN = 0
NOT_CONNECTED = 1
MISSING_RESOURCE = 2
BLOCKED = 3
CONNECTING = 4
CONNECTED = 5
DISCONNECTING = 6
FAIL = 7
CLEANUP = 8
# Mapping of modal groups to the individual gcode commands they contain.
MODAL_GROUPS = {
# "G" codes
"motion": {
"G00": GCodeRapidMove,
"G01": GCodeLinearMove,
"G02": GCodeArcMoveCW,
"G03": GCodeArcMoveCCW,
"G38.2": GCodeStraightProbe,
"G38.3": GCodeStraightProbe,
"G38.4": GCodeStraightProbe,
"G38.5": GCodeStraightProbe,
"G80": GCodeCancelCannedCycle
},
"plane_selection": {
},
"distance": {
"G90": GCodeAbsoluteDistanceMode,
"G91": GCodeIncrementalDistanceMode
},
"arc_ijk_distance": {
},
"feed_rate_mode": {
},
"units": {
"G20": GCodeUseInches,
"G21": GCodeUseMillimeters,
},
"cutter_diameter_comp": {
},
"tool_length_offset": {
},
"canned_cycles_return": {
},
"coordinate_system": {
},
"control_mode": {
},
"spindle_speed_mode": {
},
"lathe_diameter": {
},
# "M" codes
"stopping": {
},
"spindle": {
},
"coolant": {
},
"override_switches": {
},
"user_defined": {
},
# Other
"non_modal": {
"G92": GCodeCoordSystemOffset,
"G92.1": GCodeResetCoordSystemOffset,
"G92.2": GCodeResetCoordSystemOffset,
"G92.3": GCodeRestoreCoordSystemOffset,
}
}
# Map individual gcode commands to the modal groups they belong to.
MODAL_COMMANDS = {
b"G0": b"motion",
b"G00": b"motion",
b"G1": b"motion",
b"G01": b"motion",
b"G2": b"motion",
b"G02": b"motion",
b"G3": b"motion",
b"G03": b"motion",
b"G38.2": b"motion",
b"G38.3": b"motion",
b"G38.4": b"motion",
b"G38.5": b"motion",
b"G80": b"motion",
b"G54": b"coordinate_system",
b"G55": b"coordinate_system",
b"G56": b"coordinate_system",
b"G57": b"coordinate_system",
b"G58": b"coordinate_system",
b"G59": b"coordinate_system",
b"G17": b"plane_selection",
b"G18": b"plane_selection",
b"G19": b"plane_selection",
b"G90": b"distance", # Absolute
b"G91": b"distance", # Incremental
b"G91.1": b"arc_ijk_distance",
b"G93": b"feed_rate_mode", # 1/time
b"G94": b"feed_rate_mode", # units/min
b"G20": b"units", # Inches
b"G21": b"units", # mm
b"G40": b"cutter_diameter_comp",
b"G43.1": b"tool_length_offset",
b"G49": b"tool_length_offset",
b"G61": b"path_control_mode",
b"G61.1": b"path_control_mode",
b"G64": b"path_control_mode",
b"M0": b"stopping",
b"M00": b"stopping",
b"M1": b"stopping",
b"M01": b"stopping",
b"M2": b"stopping",
b"M02": b"stopping",
b"M30": b"stopping",
b"M3": b"spindle",
b"M03": b"spindle",
b"M4": b"spindle",
b"M04": b"spindle",
b"M5": b"spindle",
b"M05": b"spindle",
b"M19": b"spindle",
b"G96": b"spindle",
b"G97": b"spindle",
b"M7": b"coolant",
b"M07": b"coolant",
b"M8": b"coolant",
b"M08": b"coolant",
b"M9": b"coolant",
b"M09": b"coolant",
# The next 3 are not strictly Modal groups but the fit well here,
b"F": b"feed_rate",
b"S": b"spindle_speed",
b"T": b"tool",
}
<file_sep># pylint: disable=E1101 # Module 'curses' has no 'XXXX' member (no-member)
""" Plugin to provide command line IO using curses library. """
from typing import Optional, Any, Union
import atexit
from io import StringIO
import sys
import os
import curses
from terminals._terminal_base import _TerminalBase
class Cli(_TerminalBase):
""" Plugin to provide command line IO using curses library. """
# Not active unless enabled with flag at runtime.
active_by_default = False
# Set this True for any derived class that is to be used as a plugin.
is_valid_plugin = True
# pylint: disable=W0613
def __init__(self, label: str = "cli") -> None:
super().__init__(label)
self.description = "CLI interface for console operation."
os.environ.setdefault('ESCDELAY', '25')
# Replace default stdout (terminal) with a stream so it doesn't mess with
# curses.
self.temp_stdout = StringIO()
sys.stdout = self.temp_stdout
self.temp_stdout_pos = 0
# Undo curses stuff in the event of a crash.
atexit.register(self.close)
self.stdscr = curses.initscr()
if curses.has_colors():
curses.start_color()
curses.init_pair(1, curses.COLOR_RED, curses.COLOR_WHITE)
curses.noecho()
curses.cbreak()
self.stdscr.keypad(True)
self.stdscr.nodelay(True)
self.stdscr.clear()
begin_x = 0
begin_y = 0
height = curses.LINES
width = int(curses.COLS / 2)
self.win_main_border = self.stdscr.subwin(height, width, begin_y, begin_x)
self.win_main_border.border()
self.win_mainout = curses.newwin(height - 2, width - 2, begin_y + 1, begin_x + 1)
self.win_mainout.scrollok(True)
begin_x = int(curses.COLS / 2)
begin_y = 0
self.win_stdout_border = self.stdscr.subwin(height, width, begin_y, begin_x)
self.win_stdout_border.border()
self.win_stdout = curses.newwin(height - 2, width - 2, begin_y + 1, begin_x + 1)
self.win_stdout.scrollok(True)
#self.stdscr.addstr(2,2,"hello")
#self.stdscr.addstr(10,10,"world", curses.A_REVERSE)
#if curses.has_colors():
# self.stdscr.addstr(3,3,"Pretty text", curses.color_pair(1))
self.stdscr.refresh()
self.win_yes_no: Optional[Any] = None
def yesno(self, message: str = "") -> None:
""" Display confirmation window. """
if message:
begin_x = int(curses.COLS / 2 - 10)
begin_y = int(curses.LINES / 2 - 3)
height = 6
width = 20
self.win_yes_no = curses.newwin(height, width, begin_y, begin_x)
self.win_yes_no.clear()
self.win_yes_no.border()
self.win_yes_no.addstr(2, 2, message)
self.win_yes_no.refresh()
else:
del self.win_yes_no
self.win_yes_no = None
self.win_mainout.touchwin()
self.win_stdout.touchwin()
self.win_main_border.refresh()
self.win_stdout_border.refresh()
self.win_mainout.refresh()
self.win_stdout.refresh()
def early_update(self) -> bool:
""" To be called once per frame.
Returns:
bool: True: Continue execution.
False: An "Exit" or empty event occurred. Stop execution. """
character: Union[str, bytes, int, None] = None
#character = self.stdscr.getkey() # read a keypress
character = self.stdscr.getch() # read a keypress
if character is not None and isinstance(character, int) and character > -1:
self.win_mainout.addstr("%r %r\n" % (character, curses.keyname(character)))
self.win_mainout.refresh()
if self.temp_stdout.tell() > self.temp_stdout_pos:
self.temp_stdout.seek(self.temp_stdout_pos)
val = self.temp_stdout.read()
self.temp_stdout_pos = self.temp_stdout.tell()
self.win_stdout.addstr(val)
self.win_stdout.refresh()
if self.win_yes_no:
if character == 27: # Esc
# Cancel yesno.
self.yesno()
elif character == 10: # Enter
# Quit.
return False
elif character == 27:
# Enable yesno.
self.yesno("Enter to quit.")
return True
def close(self) -> None:
""" Close curses session, restore shell settings. """
curses.nocbreak()
self.stdscr.keypad(False)
curses.echo()
#input()
curses.endwin()
# Replace stdout
sys.stdout = sys.__stdout__
#sys.stdout.write(self.temp_stdout.getvalue())
<file_sep>""" Misc library methods. """
from typing import Any, Set, Iterator
import pkgutil
import importlib
import os
import sys
import inspect
#from controllers import debug
from core.component import _ComponentBase
BASEDIR = os.path.dirname(sys.argv[0])
def get_component_from_module(module: Any) -> Iterator[_ComponentBase]:
""" Yields plugin classes when provided with """
for _, object_ in inspect.getmembers(module):
is_valid_plugin = False
try:
is_valid_plugin = getattr(object_, "is_valid_plugin")
except AttributeError:
pass
else:
if is_valid_plugin:
yield object_
def load_plugins(directory: str) -> Set[Any]:
""" Load plugins.
Plugins whose filename starts with "_" will be ignored.
Args:
directory: Directory relative to main.py.
Returns:
A Set of plugins. """
print("Loading %s plugins:" % directory)
plugins: Set[Any] = set([])
full_dir = os.path.join(BASEDIR, directory)
full_mod_path = full_dir.replace("/", ".").strip(".")
# for finder, name, ispkg in pkgutil.iter_modules([full_dir]):
# print(finder, name, ispkg, full_mod_path + "." + name)
discovered_plugins = [
importlib.import_module(full_mod_path + "." + name)
for finder, name, ispkg in pkgutil.iter_modules([full_mod_path])
if name and not name.startswith('_')
]
# print(discovered_plugins)
for module in discovered_plugins:
for thing in get_component_from_module(module):
if(isinstance(thing.plugin_type, str) and
directory.startswith(thing.plugin_type)):
active_by_default: bool = True
if "active_by_default" in dir(thing):
active_by_default = getattr(thing, "active_by_default")
if (active_by_default, thing) not in plugins:
print(" type: %s\tname: %s\tactive_by_default: %s\t" %
(thing.plugin_type, thing.get_classname(), active_by_default))
plugins.add((active_by_default, thing))
return plugins
<file_sep>""" Coordinator handles interactions between components.
Coordinator polls all components for published events and delivers them to
subscribers. """
from typing import List, Dict, Optional, Deque, Tuple, Any, Type
from collections import deque
import sys
from pathlib import Path
import pprint
# pylint: disable=E1101 # Module 'PySimpleGUIQt' has no 'XXXX' member (no-member)
from ruamel.yaml import YAML, YAMLError # type: ignore
import core.common
from core.component import _ComponentBase
from terminals._terminal_base import _TerminalBase
from interfaces._interface_base import _InterfaceBase
from controllers._controller_base import _ControllerBase
from core_components._core_component_base import _CoreComponentBase
class Coordinator(_ComponentBase):
""" Coordinator handles interactions between components.
Coordinator polls all components for published events and delivers them to
subscribers. """
def __init__(self,
terminals: List[_TerminalBase],
interfaces: List[_InterfaceBase],
controller_classes: List[Type[_ControllerBase]],
debug_show_events: bool = False) -> None:
"""
Args:
interfaces: A list of objects deriving from the _InterfaceBase class.
controllers: A list of objects deriving from the _ControllerBase class.
"""
super().__init__("__coordinator__")
self.terminals: Dict[str, _TerminalBase] = \
{terminal.label:terminal for terminal in terminals}
self.interfaces: Dict[str, _InterfaceBase] = \
{interface.label:interface for interface in interfaces}
self.controller_classes: Dict[str, Type[_ControllerBase]] = \
{controller.get_classname(): controller for controller in controller_classes}
self.controllers: Dict[str, _ControllerBase] = {}
self.terminal_sub_components: Dict[str, Any] = {}
self.core_components: Dict[str, _CoreComponentBase] = {}
self._load_core_components()
self.debug_show_events = debug_show_events
self.active_controller: Optional[_ControllerBase] = None
self.config: Dict[str, Any] = {}
self.all_components: List[_ComponentBase] = []
self.all_components += list(terminals)
self.all_components += list(interfaces)
self.all_components += list(self.core_components.values())
self.event_subscriptions = {}
self._load_config("config.yaml")
self._setup_controllers()
self._setup_terminals()
self.running = True
def _load_core_components(self) -> None:
""" Load and instantiate core_component plugins. """
core_components = core.common.load_plugins("core_components")
for _, core_component in core_components:
self.core_components[core_component.label] = core_component()
def _setup_controllers(self) -> None:
self.controllers = {}
self.all_components = list(
filter(lambda i: isinstance(i, _ControllerBase) is False,
self.all_components))
if "DebugController" in self.controller_classes:
instance = self.controller_classes["DebugController"]("debug")
self.controllers[instance.label] = instance
self.all_components.append(instance)
if "controllers" in self.config:
for label, controller in self.config["controllers"].items():
assert controller["type"] in self.controller_classes, \
"Controller type '%s' specified in config file does not exist." \
% controller["type"]
class_ = self.controller_classes[controller["type"]]
instance = class_(label)
for property_, value in controller.items():
if hasattr(instance, property_):
setattr(instance, property_, value)
elif property_ not in ["type"]: # Ignore any in the list.
print("Unrecognised config parameter "
"[controller, property, value]: %s, %s, %s" %
(label, property_, value))
self.controllers[label] = instance
self.all_components.append(instance)
self.activate_controller()
# Change which controller is active in response to event.
for controller in self.controllers:
self.event_subscriptions["%s:set_active" % controller] = \
("_on_activate_controller", None)
self.event_subscriptions["request_new_controller"] = \
("_new_controller", None)
def _load_config(self, filename: str) -> None:
path = Path(filename)
yaml = YAML(typ='safe')
try:
self.config = yaml.load(path)
except YAMLError as error:
print("--------")
print("Problem in configuration file: %s" % error.problem_mark.name)
print(" line: %s column: %s" %
(error.problem_mark.line, error.problem_mark.column))
print("--------")
sys.exit(0)
print("Config:")
pprint.pprint(self.config)
def _setup_terminals(self) -> None:
""" Do configuration that was not possible before all other components
were instantiated. """
for terminal in self.terminals.values():
print("Terminal %s of type %s is being activated." %
(terminal.label, terminal.get_classname()))
terminal.setup(self.interfaces, self.controllers, self.controller_classes)
# Add sub_components to the list of things to be updated by this
# controller.
for label, sub_component in terminal.sub_components.items():
assert label not in self.terminal_sub_components, \
"Duplicate sub component name: %s" % label
self.terminal_sub_components[label] = sub_component
self.all_components += list(self.terminal_sub_components.values())
def _clear_events(self) -> None:
""" Clear the event queue after all events have been delivered. """
#if(self._event_queue):
# print("Clearing event queue: ", self._event_queue)
self._delay_events[0] = False
self._event_queue.clear()
# Move any events that arrived during `self.receive()` to the main queue.
while True:
try:
event = self._delayed_event_queue.pop()
except IndexError:
break
print("#####copying delayed event.", event)
self._event_queue.append(event)
def _debug_display_events(self) -> None:
""" Display all events to console. """
if not self.debug_show_events:
return
for event in self._event_queue:
print("*********", event)
def activate_controller(self,
label: Optional[str] = None,
controller: Optional[_ControllerBase] = None) -> None:
""" Set a specified controller as the active one.
Args:
label: If set, the active controller will be the one matching "label"
parameter.
controller: If set, the active controller will be the one matching
this instance. If no matching instance is found, it will be
added as a candidate and activated.
"""
def _activate(candidate: _ControllerBase) -> None:
""" Set specified controller as the active one. """
if self.active_controller:
self.active_controller.active = False
self.active_controller = candidate
def _only_one_active() -> None:
""" Set "active" flag on the active_controller. """
assert self.active_controller, "No active controller set."
for candidate_controller in self.controllers.values():
if candidate_controller is self.active_controller:
candidate_controller.active = True
else:
candidate_controller.active = False
for candidate_controller in self.controllers.values():
if candidate_controller.label == "debug":
_activate(candidate_controller)
candidate_controller.active = False
for candidate_controller in self.controllers.values():
if candidate_controller.active:
_activate(candidate_controller)
break
for candidate_controller in self.controllers.values():
if candidate_controller.label == label:
_activate(candidate_controller)
break
for candidate_controller in self.controllers.values():
if candidate_controller is controller:
_activate(candidate_controller)
break
if not self.active_controller and not controller:
# Don't have an self.active_controller yet.
# Let's just take the first.
self.active_controller = list(self.controllers.values())[0]
if self.active_controller and not controller:
_only_one_active()
return
if (self.active_controller and controller and
self.active_controller.label == controller.label):
_only_one_active()
return
if self.active_controller and self.active_controller is controller:
_only_one_active()
return
# Label was not specified as one of the input arguments.
assert label is None, "Could not find controller matching '%s'" % label
assert controller, "Controller not passed in as an argument."
# This is a new controller.
self.controllers[controller.label] = controller
self.all_components.append(controller)
self.active_controller = controller
_only_one_active()
def _on_activate_controller(self, event: str, event_value: bool) -> None:
""" Make whichever controller has it's "active" property set the active
one. """
#print("coordinator._on_activate_controller", event, event_value)
event_controller_name, event_name = event.split(":", maxsplit=1)
assert event_name == "set_active", "Unexpected event name: %s" % event_name
assert isinstance(event_value, bool), "Expected value should be boolean."
if self.controllers[event_controller_name].active == event_value:
# No change
self.publish("%s:active" % event_controller_name, event_value)
return
print("Controller: %s is %s" %
(event_controller_name, "active" if event_value else "inactive"))
assert event_controller_name in self.controllers, \
"Event received from invalid controller."
if event_value:
for controller in self.controllers.values():
controller.active = False
self.controllers[event_controller_name].active = event_value
# This will check only one controller has the active flag set
# or assign the "debug" controller active if none are set.
self.activate_controller()
for controller_name, controller in self.controllers.items():
self.publish("%s:active" % controller_name, controller.active)
def _copy_active_controller_events(self) -> None:
""" Copy the active controller's events into the "active_controller:xxxx"
namespace.
All controllers publish events under their own name. Subscribers
are usually only interested in the active controller.
Here we make copies of the active controller's events under the name
"active_controller:xxxx" to save working this out on every consumer."""
assert self.active_controller, "No active controller."
active = self.active_controller.label
tmp_event_queue: Deque[Tuple[str, Any]] = deque()
for event_name, event_value in self._event_queue:
if not isinstance(event_name, str):
continue
if event_name.find(":") < 0:
continue
component, event = event_name.split(":", maxsplit=1)
if component != active:
continue
tmp_event_queue.append(("active_controller:%s" % event, event_value))
self._event_queue.extend(tmp_event_queue)
def update_components(self) -> bool:
""" Iterate through all components, delivering and acting upon events. """
for terminal in self.terminals.values():
self.running = self.running and terminal.early_update()
for interface in self.interfaces.values():
interface.early_update()
for core_component in self.core_components.values():
core_component.update()
for controller in self.controllers.values():
controller.early_update()
self._copy_active_controller_events()
# Deliver all events to consumers.
self.receive()
for component in self.all_components:
component.receive()
self._debug_display_events()
self._clear_events()
self._update()
#if self._delivered:
# print(self.label, self._delivered)
self._delivered.clear()
for component in self.all_components:
#if component._delivered:
# print(component.label, component._delivered)
#else:
# print(component.label)
component._update()
component.update()
component._delivered.clear()
return self.running
def close(self) -> None:
""" Cleanup components on shutdown. """
for controller in self.controllers.values():
controller.disconnect()
for terminal in self.terminals.values():
terminal.close()
def _new_controller(self, event: str, controller_class: str) -> None:
print("_new_controller", event, controller_class)
instance = self.controller_classes[controller_class]("new")
self.controllers[instance.label] = instance
self.all_components.append(instance)
self.activate_controller(controller=instance)
self.publish(self.key_gen("new_controller"), instance.label)
self.event_subscriptions["new:set_active"] = \
("_on_activate_controller", None)
| 726b6d2054133a3e1bc8b55fa0a03c17d22f9fbd | [
"Python"
]
| 29 | Python | mrdunk/CNCtastic | 499c3632f716395a831506508e9a2d6f45283ad1 | a1a832399e7be6471702ea32afa84392db9c8d82 |
refs/heads/master | <file_sep>/*
* File name: hello.c
*/
#include <linux/init.h>
#include <linux/module.h>
static int __init hello_init(void)
{
printk("hello world init\n");
return 0;
}
static void __exit hello_exit(void)
{
/* printk("goodbye\n"); */
}
module_init(hello_init);
module_exit(hello_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Lin");
MODULE_DESCRIPTION("my hello world module");
MODULE_ALIAS("modhello");
<file_sep>#include <unistd.h>
#include <stdio.h>
#include <time.h>
int global_val = 0;
int main(void)
{
pid_t pid;
if ((pid = fork()) < 0)
printf("fork error\n");
else if (pid == 0) {
global_val++;
} else {
sleep(2);
}
printf("pid = %ld, global_val = %d\n", (long)getpid(), global_val);
return 0;
}
<file_sep>/*
* File name: empty_sizeof.c
*/
#include <stdio.h>
struct list {
};
int main(void)
{
struct list l1[10];
int a[10];
printf("%d\n", sizeof(&a[0]));
}
<file_sep>/*
* File name: section_3.cpp
*/
#include <iostream>
#include <vector>
using namespace std;
int main(void)
{
string s1 = "hello world";
cout << s1 << endl;
string s2(10, 'c');
cout << s2 << endl;
string line;
getline(cin, line);
cout << line << endl;
string s5 = "jarvis," + s1;
cout << s5 << endl;
for (auto c : s5)
cout << c << endl;
for (auto &c : s5) {
c = toupper(c);
cout << c << endl;
}
vector<int> v1(10, 2);
// cout << v1 << endl;
for (auto v : v1)
cout << v << endl;
cout << "end of iteration" << endl;
v1.push_back(15);
for (auto v = v1.begin(); v < v1.end(); v++)
cout << *v << endl;
int ia[5] = {1, 2, 3, 4, 5};
auto ia2(ia);
cout << *ia2 << endl;
decltype(ia) ia3 = {5, 4, 3, 2, 1};
int ia4[2][3] = {
{1, 2, 3},
{4, 5, 6},
};
cout << "multiple array" << endl;
for (auto &row : ia4) {
for (auto col : row) {
cout << col << endl;
}
}
}
<file_sep>An practice from <https://github.com/Gazler/githug>
It is a game about git operation from easy to hard, so Let's start.
## Mission 1 - git init
```
git init
```
## Mission 2 - git config
```
#local
git config --local user.name "xxx"
git config --local user.email "xxx"
#global
git config --global user.name "xxx"
git config --global user.email "xxx"
```
## Mission 3 - git add
```
git add xxx
# add all file
git add --all
```
## Mission 4 - git commit
```
git commit -m "first commit"
```
## Mission 5 - git clone
```
git clone <https://github.com/Gazler/cloneme>
```
## Mission 6-git clone to folder
```
git clone <https://github.com/Gazler/cloneme> my_cloned_repo
```
## Mission 7 - ignore file
```
# ignore all files ending in ".swp"
echo "*.swp" >> .gitignore
```
## Mission 8 - include a specific file
```
# ignore all *.a except lib.a
# modify .gitignore
*.a
!lib.a
```
## Mission 9 - git status
```
# use to see file's status
git status
```
## Mission 10 - number of files committed
```
# only files add by git will be committed
```
## Mission 11 - git rm
```
git rm xxx
```
## Mission 12 - git reset
```
# git add a file accidentally, cancel it
git reset xxx
```
## Mission 13 - git stash
```
# want to save changes but don't want to commit
# save
git stash
# restore change
git stash pop
# git stash use structure like stack, so it's a LIFO
```
## Mission 14 - git mv
```
# move or rename a file
git mv old_name new_name
```
## Mission 15 - git move
```
# move file to src
mkdir src
git mv *.html src
```
## Mission 16 - git log
```
# see git log
git log
```
## Mission 17 - git tag
```
# tag current commit as a tag_name
git tag tag_name
```
## Mission 18 - push tag
```
# push tag_name to remote
git push origin tag_name
```
## Mission 19 - git commit amend
```
# modify commit message
# use vim as default editor
# git config --global core.editor vim
git commit --amend
# forget to add one file
git add xxx
git commit --amend
# will auto add the file to the last commit
```
## Mission 20 - git commit —date
```
# commit in a furture time
git commit -m "xxx" --date="2019-02-02"
```
## Mission 21 - git reset
```
# cancle git add
git reset HEAD xxx_file
```
## Mission 22 - git reset —soft
```
# cancle the last commit
git reset --soft commit_id
# commit_id is the id before the commit you cancle.
# like commit 2, commit 1, want to cancle commit 2,
# so commit_id should be commit 1
```
## Mission 23 - git checkout
```
# discard change
git checkout xxx_file
```
## Mission 24 - git remote
```
# see remote repo name
git remote -v
```
## Mission 27 - git pull
```
git pull <remote> <branch>
```
## Mission 28 - add remote repo
```
git remote add origin https://github.com/githug/githug
```
<file_sep># Assume the source tree is where the running kernel was built
# You should set KERNELDIR in the environment if it's elsewhere
KERNELDIR ?= /lib/modules/$(shell uname -r)/build
# The current directory is passed to sub-makes as argument
PWD := $(shell pwd)
modules:
$(MAKE) -C $(KERNELDIR) M=$(PWD) modules
modules_install:
$(MAKE) -C $(KERNELDIR) M=$(PWD) modules_install
clean:
rm -rf *.o *~ core .depend .*.cmd *.ko *.mod.c .tmp_versions *.order *.symvers
.PHONY: modules modules_install clean
obj-m := hello.o
<file_sep>BASEINCLUDE ?= /home/parallels/wspace/linux/runninglinuxkernel_4.0-nogitlog
# BASEINCLUDE ?= /lib/modules/`uname -r`/build
miscchar-objs := misc_char.o
obj-m := miscchar.o
all :
$(MAKE) -C $(BASEINCLUDE) M=$(PWD) modules;
clean:
$(MAKE) -C $(BASEINCLUDE) SUBDIRS=$(PWD) clean;
rm -f *.ko
<file_sep>/*
* File name: server.c
*/
/* socket */
#include <sys/socket.h>
/* #include <netinet/in.h> */
/* inet_pton */
#include <arpa/inet.h>
/* printf */
#include <stdio.h>
/* exit */
#include <stdlib.h>
/* memset */
#include <string.h>
/* write */
#include <unistd.h>
#include <time.h>
/*
* If use mac OS as server, please pay attention:
* the max count of socket connection is 128 as default.
* use 'sudo sysctl -w kern.ipc.somaxconn=512' to change it.
*/
#define SERV_PORT 1234
int main(void)
{
int listenfd, connfd;
pid_t childpid;
socklen_t clilen;
time_t cur_time;
struct tm *p_tm;
struct sockaddr_in cliaddr, servaddr;
listenfd = socket(AF_INET, SOCK_STREAM, 0);
memset(&servaddr, 0, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(SERV_PORT);
bind(listenfd, (struct sockaddr *)&servaddr, sizeof(servaddr));
listen(listenfd, 1000);
for ( ; ; ) {
clilen = sizeof(cliaddr);
connfd = accept(listenfd, (struct sockaddr *)&cliaddr, &clilen);
if ((childpid = fork()) == 0) {
char buf[128], read_buf[128];
close(listenfd);
read(connfd, read_buf, 128);
time(&cur_time);
p_tm = localtime(&cur_time);
sprintf(buf, "current time is %s", asctime(p_tm));
write(connfd, buf, 128);
exit(0);
}
close(connfd);
}
exit(0);
}
<file_sep>/*
* File name: list.c
*/
#include <stdio.h>
#include <string.h>
typedef struct List {
int element;
struct List *next;
} List_t;
int list_insert(List_t *head, int val)
{
List_t *pnew = (List_t*)malloc(sizeof(List_t));
pnew->element = val;
pnew->next = NULL;
if (pnew == NULL)
return -1;
List_t *pnode = head;
while (pnode->next) {
pnode = pnode->next;
}
pnode->next = pnew;
return 0;
}
int list_remove(List_t *head, int val)
{
List_t *pnode = head;
while(pnode->next) {
if (pnode->next->element == val) {
pnode->next = pnode->next->next;
break;
} else
pnode = pnode->next;
}
return 0;
}
int list_traverse(List_t *head)
{
if (head == NULL)
return -1;
else {
List_t *pnode = head->next;
while (pnode) {
printf("%d ", pnode->element);
pnode = pnode->next;
}
}
}
void list_traverse_from_tail(List_t *head)
{
if (head->next) {
list_traverse_from_tail(head->next);
}
printf("%d ", head->element);
}
int main(void)
{
List_t *head = (List_t*)malloc(sizeof(List_t));
head->next = NULL;
list_insert(head, 123);
list_insert(head, 455);
/* list_remove(head, 455); */
printf("traverse list: ");
list_traverse(head);
printf("\n");
printf("traverse list from tail: ");
list_traverse_from_tail(head->next);
printf("\n");
}
<file_sep>/*
* File name: section_5.cpp
*/
#include <iostream>
#include <vector>
using namespace std;
int main(void)
{
vector<int> v1 = {1, 2, 3, 4, 5};
try {
for (auto v : v1)
cout << v << endl;
}
catch (exception) {
cout << "exception" << endl;
}
}
<file_sep>#!/bin/bash
arm-linux-gnueabi-gcc test.c -o test.o --static
<file_sep>/*
* File name: merge_sort.c
*/
#include "stdio.h"
#include "stdlib.h"
void m_sort(int *data, int *tmp, int left, int right)
{
if (left >= right)
return;
int center = (left + right) / 2;
m_sort(data, tmp, left, center);
m_sort(data, tmp, center + 1, right);
int l_pos = left;
int r_pos = center + 1;
int tmp_pos = left;
while (l_pos <= center && r_pos <= right) {
if (data[l_pos] <= data[r_pos])
tmp[tmp_pos++] = data[l_pos++];
else
tmp[tmp_pos++] = data[r_pos++];
}
while(l_pos <= center)
tmp[tmp_pos++] = data[l_pos++];
while(r_pos <= right)
tmp[tmp_pos++] = data[r_pos++];
for (int i = left; i <= right; i ++)
data[i] = tmp[i];
}
void merge_sort(int *data, int size)
{
int *tmp = malloc(size * sizeof(int));
if (tmp == NULL) {
printf("fatal, can't malloc\n");
return;
}
m_sort(data, tmp, 0, size - 1);
free(tmp);
}
int main(void)
{
int data[20] = {1, 6, 2, 7, -10, 0, 11, 4, 20, 5, 13, -1, 22, 8, 14, 17, -22, 32, 19, 20};
merge_sort(data, sizeof(data) / sizeof(data[0]));
printf("sort data: ");
for (int i = 0; i < (int)(sizeof(data) / sizeof(data[0])); i++)
printf("%d ", data[i]);
printf("\n");
return 0;
}
<file_sep>#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
pthread_t demo_tid1;
pthread_t demo_tid2;
void cleanup(void *arg)
{
printf("cleanup %s\n", (char*)arg);
}
void *demo_func1(void *arg)
{
pthread_cleanup_push(cleanup, "demo1 thread first clean");
pthread_cleanup_push(cleanup, "demo1 thread second clean");
printf("thread1 return\n");
#ifdef __APPLE__
pthread_exit((void*)1);
#else
return((void*)1);
#endif
pthread_cleanup_pop(0);
pthread_cleanup_pop(0);
}
void *demo_func2(void *arg)
{
pthread_cleanup_push(cleanup, "demo2 thread first clean");
pthread_cleanup_push(cleanup, "demo2 thread second clean");
printf("thread2 exit\n");
pthread_exit((void*)2);
pthread_cleanup_pop(0);
pthread_cleanup_pop(0);
}
int main(void)
{
int err = 0;
void *tret;
err = pthread_create(&demo_tid1, NULL, demo_func1, NULL);
if (err != 0)
printf("err, can't create thread1\n");
err = pthread_create(&demo_tid2, NULL, demo_func2, NULL);
if (err != 0)
printf("err, can't create thread2\n");
err = pthread_join(demo_tid1, &tret);
if (err != 0)
printf("err, can't join thread1\n");
printf("thread1 exit code %ld\n", (long)tret);
err = pthread_join(demo_tid2, &tret);
if (err != 0)
printf("err, can't join thread2\n");
printf("thread2 exit code %ld\n", (long)tret);
return 0;
}
<file_sep>/*
* File name: reverse_string.c
*/
#include "stdio.h"
char *reverse(char *string)
{
if (string == NULL)
return NULL;
int len = strlen(string);
for (int i = 0; i < len / 2; i++) {
char tmp;
tmp = string[i];
string[i] = string[len - 1 - i];
string[len - 1 - i] = tmp;
}
return string;
}
int main(void)
{
char string[] = "hello world";
char *re;
re = reverse(string);
printf("%s\n", re);
}
<file_sep>/*
* File name: simple_mod.c
*/
#include "linux/module.h"
#include "linux/fs.h"
#include "linux/uaccess.h"
#include "linux/init.h"
#include "linux/cdev.h"
#define DEMO_NAME "simple_char_dev"
static dev_t char_dev;
static struct cdev *char_cdev;
static signed count = 1;
static int simple_char_open(struct inode *inode, struct file *file)
{
int major = MAJOR(inode->i_rdev);
int minor = MINOR(inode->i_rdev);
printk("%s : major=%d, minor=%d\n", __func__, major, minor);
return 0;
}
static int simple_char_release(struct inode *inode, struct file *file)
{
return 0;
}
static ssize_t
simple_char_read(struct file *file, char __user *buf, size_t count,
loff_t *f_pos)
{
printk("%s enter\n", __func__);
return 0;
}
static ssize_t
simple_char_write(struct file *file, const char __user *buf, size_t count,
loff_t *f_pos)
{
printk("%s enter\n", __func__);
return 0;
}
static const struct file_operations simple_char_fops = {
.owner = THIS_MODULE,
.open = simple_char_open,
.release = simple_char_release,
.read = simple_char_read,
.write = simple_char_write,
};
static int __init simple_char_init(void)
{
int ret;
ret = alloc_chrdev_region(&char_dev, 0, count, DEMO_NAME);
if (ret) {
printk("failed to allocate char device region\n");
return ret;
}
char_cdev = cdev_alloc();
if (!char_cdev) {
printk("cdev_alloc failed\n");
goto unregister_chrdev;
}
cdev_init(char_cdev, &simple_char_fops);
ret = cdev_add(char_cdev, char_dev, count);
if (ret) {
printk("cdev_add failed\n");
goto cdev_fail;
}
printk("successeed register char device: %s\n", DEMO_NAME);
printk("Major number = %d, minor number = %d\n", MAJOR(char_dev), MINOR(char_dev));
return 0;
cdev_fail:
cdev_del(char_cdev);
unregister_chrdev:
unregister_chrdev_region(char_dev, count);
return ret;
}
static void __exit simple_char_exit(void)
{
printk("removing device\n");
if (char_cdev)
cdev_del(char_cdev);
unregister_chrdev_region(char_dev, count);
}
module_init(simple_char_init);
module_exit(simple_char_exit);
MODULE_AUTHOR("Lin");
MODULE_LICENSE("GPL v2");
MODULE_DESCRIPTION("simple char device");
<file_sep>/*
* File name: monitor_keyboard.c
*/
#include <sys/ioctl.h>
#include <stdio.h>
#include <sys/select.h>
#include <fcntl.h>
#include <sys/types.h>
#include <linux/input.h>
#include <unistd.h>
#include <time.h>
#include <stdlib.h>
#define MAX_KEY_FD 128
int handle_key_event(int fd1, int fd2);
int main(void)
{
int fd1, fd2;
fd1 = open("/dev/input/event5", O_RDONLY);
if (fd1 <= 0) {
printf("can't open event5\n");
return 0;
}
fd2 = open("/dev/input/event6", O_RDONLY);
if (fd2 <= 0) {
printf("can't open event6\n");
return 0;
}
handle_key_event(fd1, fd2);
close(fd1);
close(fd2);
return 0;
}
int handle_key_event(int fd1, int fd2)
{
int ret;
fd_set readfds;
printf("%s\n", __func__);
struct input_event t;
struct timeval timeout;
timeout.tv_sec = 2;
timeout.tv_usec = 0;
/* while (1) */
/* { */
/* if (read (fd, &t, sizeof (t)) == sizeof (t)) */
/* { */
/* printf("ffffff\n"); */
/* if (t.type == EV_KEY) */
/* if (t.value == 0 || t.value == 1) */
/* { */
/* printf ("key %d %s\n", t.code, */
/* (t.value) ? "Pressed" : "Released"); */
/* if(t.code==KEY_ESC) */
/* break; */
/* } */
/* } */
/* } */
FD_ZERO(&readfds);
FD_SET(fd1, &readfds);
FD_SET(fd2, &readfds);
while (1) {
ret = select(MAX_KEY_FD + 1, &readfds, NULL, NULL, NULL);
switch (ret) {
case -1:
exit(0);
case 0:
printf("timeout\n");
break;
default:
/* if (FD_ISSET(fd, &readfds)) { */
printf("receive a read event\n");
/* } */
break;
}
}
return 0;
}
<file_sep>/*
* File name: search_in_sorted_array.c
*/
#include <stdio.h>
int a[][] = {
{1, 2, 8, 9},
{2, 4, 9, 12},
{4, 7, 10, 13},
{6, 8, 11, 15},
};
bool find_num(int **a, int )
int main(void)
{
}
<file_sep>/*
* File name: test.c
*/
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#define DEVICE_DEV_NAME "/dev/simple_char"
int main(void)
{
char buffer[64];
int fd;
fd = open(DEVICE_DEV_NAME, O_RDONLY);
if (fd < 0) {
printf("open device %s failed\n", DEVICE_DEV_NAME);
return -1;
}
read(fd, buffer, 64);
close(fd);
return 0;
}
<file_sep>/*
* File name: simple_mod.c
*/
#include <linux/module.h>
#include <linux/fs.h>
#include <linux/uaccess.h>
#include <linux/init.h>
#include <linux/cdev.h>
#include <linux/device.h>
#include <linux/miscdevice.h>
#include <linux/kfifo.h>
#include <linux/wait.h>
#include <linux/sched.h>
#include <linux/slab.h>
#include <linux/poll.h>
/*
* mknod /dev/buffer_char0 c 252 0
* mknod /dev/buffer_char1 c 252 1
*/
#define MAX_DEVICE_BUFFER_SIZE 64
#define DEMO_NAME "buffer_char"
#define MYDEMO_FIFO_SIZE 64
static dev_t dev;
static struct cdev *demo_cdev;
struct mydemo_device_t {
char name[64];
struct device *dev;
wait_queue_head_t read_queue;
wait_queue_head_t write_queue;
struct kfifo mydemo_fifo;
};
struct mydemo_private_data {
struct mydemo_device_t *device;
char name[64];
};
#define MYDEMO_MAX_DEVICES 8
static struct mydemo_device_t *mydemo_device[MYDEMO_MAX_DEVICES];
static int buffer_char_open(struct inode *inode, struct file *file)
{
unsigned int minor = iminor(inode);
struct mydemo_private_data *data;
struct mydemo_device_t *device = mydemo_device[minor];
printk("%s: major=%d, minor=%d, device=%s\n", __func__,
MAJOR(inode->i_rdev), MINOR(inode->i_rdev), device->name);
data = kmalloc(sizeof(struct mydemo_private_data), GFP_KERNEL);
if (!data)
return -ENOMEM;
sprintf(data->name, "private_data_%d", minor);
data->device = device;
file->private_data = data;
return 0;
}
static int buffer_char_release(struct inode *inode, struct file *file)
{
struct mydemo_private_data *data = file->private_data;
kfree(data);
return 0;
}
static ssize_t
buffer_char_read(struct file *file, char __user *buf, size_t count,
loff_t *f_pos)
{
int actual_readed;
int ret;
struct mydemo_private_data *data = file->private_data;
struct mydemo_device_t *device = data->device;
if (kfifo_is_empty(&device->mydemo_fifo)) {
if (file->f_flags & O_NONBLOCK)
return -EAGAIN;
printk("%s:%s pid=%d, going to sleep, %s\n", __func__, device->name, current->pid, data->name);
ret = wait_event_interruptible(device->read_queue,
!kfifo_is_empty(&device->mydemo_fifo));
if (ret)
return ret;
}
ret = kfifo_to_user(&device->mydemo_fifo, buf, count, &actual_readed);
if (ret)
return -EIO;
if (!kfifo_is_full(&device->mydemo_fifo))
wake_up_interruptible(&device->write_queue);
printk("%s:%s, pid=%d, actual_readed=%d, pos=%lld\n",__func__,
device->name, current->pid, actual_readed, *f_pos);
return actual_readed;
}
static ssize_t
buffer_char_write(struct file *file, const char __user *buf, size_t count,
loff_t *f_pos)
{
int actual_write;
int ret;
struct mydemo_private_data *data = file->private_data;
struct mydemo_device_t *device = data->device;
if (kfifo_is_full(&device->mydemo_fifo)){
if (file->f_flags & O_NONBLOCK)
return -EAGAIN;
printk("%s:%s pid=%d, going to sleep\n", __func__, device->name, current->pid);
ret = wait_event_interruptible(device->write_queue,
!kfifo_is_full(&device->mydemo_fifo));
if (ret)
return ret;
}
ret = kfifo_from_user(&device->mydemo_fifo, buf, count, &actual_write);
if (ret)
return -EIO;
if (!kfifo_is_empty(&device->mydemo_fifo))
wake_up_interruptible(&device->read_queue);
printk("%s:%s pid=%d, actual_write =%d, f_pos=%lld, ret=%d\n", __func__,
device->name, current->pid, actual_write, *f_pos, ret);
return actual_write;
}
static unsigned int buffer_char_poll(struct file *file, poll_table *wait)
{
int mask = 0;
struct mydemo_private_data *data = file->private_data;
struct mydemo_device_t *device = data->device;
poll_wait(file, &device->read_queue, wait);
poll_wait(file, &device->write_queue, wait);
if (!kfifo_is_empty(&device->mydemo_fifo))
mask |= POLLIN | POLLRDNORM;
if (!kfifo_is_full(&device->mydemo_fifo))
mask |= POLLOUT | POLLWRNORM;
return mask;
}
static const struct file_operations buffer_char_fops = {
.owner = THIS_MODULE,
.open = buffer_char_open,
.release = buffer_char_release,
.read = buffer_char_read,
.write = buffer_char_write,
.poll = buffer_char_poll,
};
static int __init buffer_char_init(void)
{
int ret;
int i;
struct mydemo_device_t *device;
ret = alloc_chrdev_region(&dev, 0, MYDEMO_MAX_DEVICES, DEMO_NAME);
if (ret) {
printk("failed to allocate char device region");
return ret;
}
demo_cdev = cdev_alloc();
if (!demo_cdev) {
printk("cdev_alloc failed\n");
goto unregister_chrdev;
}
cdev_init(demo_cdev, &buffer_char_fops);
ret = cdev_add(demo_cdev, dev, MYDEMO_MAX_DEVICES);
if (ret) {
printk("cdev_add failed\n");
goto cdev_fail;
}
for (i = 0; i < MYDEMO_MAX_DEVICES; i++) {
device = kmalloc(sizeof(struct mydemo_device_t), GFP_KERNEL);
if (!device) {
ret = -ENOMEM;
goto free_device;
}
sprintf(device->name, "%s%d", DEMO_NAME, i);
mydemo_device[i] = device;
init_waitqueue_head(&device->read_queue);
init_waitqueue_head(&device->write_queue);
ret = kfifo_alloc(&device->mydemo_fifo,
MYDEMO_FIFO_SIZE,
GFP_KERNEL);
if (ret) {
ret = -ENOMEM;
goto free_kfifo;
}
printk("mydemo_fifo=%p\n", &device->mydemo_fifo);
}
printk("succeeded register char device: %s\n", DEMO_NAME);
return 0;
free_kfifo:
for (i =0; i < MYDEMO_MAX_DEVICES; i++)
if (&device->mydemo_fifo)
kfifo_free(&device->mydemo_fifo);
free_device:
for (i =0; i < MYDEMO_MAX_DEVICES; i++)
if (mydemo_device[i])
kfree(mydemo_device[i]);
cdev_fail:
cdev_del(demo_cdev);
unregister_chrdev:
unregister_chrdev_region(dev, MYDEMO_MAX_DEVICES);
return ret;
}
static void __exit buffer_char_exit(void)
{
int i;
printk("removing device\n");
if (demo_cdev)
cdev_del(demo_cdev);
unregister_chrdev_region(dev, MYDEMO_MAX_DEVICES);
for (i =0; i < MYDEMO_MAX_DEVICES; i++)
if (mydemo_device[i])
kfree(mydemo_device[i]);
}
module_init(buffer_char_init);
module_exit(buffer_char_exit);
MODULE_AUTHOR("Lin");
MODULE_LICENSE("GPL v2");
MODULE_DESCRIPTION("buffer char device");
<file_sep>/*
* File name: hello_world.c
*/
#include <linux/init.h>
#include <linux/module.h>
MODULE_LICENSE("Dual BSD/GPL");
#define SCULL_MAJOR 0
#define SCULL_MINOR 0
#define SCULL_NR_DEVS 4
int scull_major = SCULL_MAJOR;
int scull_minor = SCULL_MINOR;
int scull_nr_devs = SCULL_NR_DEVS; /* number of bare scull devices */
static int scull_init(void)
{
int ret;
dev_t dev = 0;
dev = MKDEV(scull_major, scull_minor);
ret = register_chrdev_region(dev, scull_nr_devs, "scull");
printk(KERN_ALERT "Hello, world\n");
return 0;
}
static void scull_exit(void)
{
printk(KERN_EMERG "Goodbye, cruel world\n");
}
module_init(scull_init);
module_exit(scull_exit);
<file_sep>/*
* File name: test.c
*/
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#define DEVICE_DEV_NAME "/dev/buffer_char"
int main(void)
{
char buffer[64];
int fd;
size_t len;
char message[] = "testing the virtual FIFO device";
char *read_buffer;
int ret;
len = sizeof(message) / sizeof(message[0]);
fd = open(DEVICE_DEV_NAME, O_RDWR);
if (fd < 0) {
printf("open device %s failed\n", DEVICE_DEV_NAME);
return -1;
}
ret = write(fd, message, len);
if (ret != len) {
printf("write fail\n");
/* return -1; */
}
read_buffer = malloc(2 * len);
memset(read_buffer, 0, 2 * len);
close(fd);
fd = open(DEVICE_DEV_NAME, O_RDWR);
if (fd < 0) {
printf("open device %s failed\n", DEVICE_DEV_NAME);
return -1;
}
ret = read(fd, read_buffer, 2 * len);
printf("read %d buffer\n", ret);
printf("read buffer %s\n", read_buffer);
close(fd);
return 0;
}
<file_sep>/*
* File name: section_2.cpp
*/
#include <iostream>
using namespace std;
int reused = 10;
int main(void)
{
cout << ::reused << endl;
// reference
int val = 11;
int &rval = val;
cout << rval <<endl;
// pointer
int *pval = &val;
cout << *pval <<endl;
// reference from pointer
int *&prval = pval;
cout << *prval << endl;
// const pointer
const double pi = 3.14;
const double *ppi = π
cout << *ppi << endl;
// top-level const and low-level const
int i = 0;
int *const p1 = &i;
const int ci = 42;
const int *pci = &ci;
cout << *p1 << endl;
cout << *pci << endl;
// constexpr
constexpr int mf = 20;
constexpr int limit = mf + 1;
cout << limit << endl;
// auto
int b = 20;
auto bb = b;
cout << bb << endl;
const int c = 21;
const auto cc = c;
cout << cc << endl;
// decltype
const int d = 1;
decltype(d) x = 11;
cout << x << endl;
decltype((d)) dd = d;
cout << dd << endl;
}
<file_sep>#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <stdint.h>
#include <stdlib.h>
pthread_t demo_tid;
pthread_mutex_t mutex;
/*#define MUTEX_RECURSIVE*/
void *demo_func(void *arg)
{
pthread_mutex_lock(&mutex);
pthread_mutex_lock(&mutex);
pthread_mutex_lock(&mutex);
printf("hello world, a new thread\n");
pthread_mutex_unlock(&mutex);
pthread_mutex_unlock(&mutex);
pthread_mutex_unlock(&mutex);
return((void*)0);
}
int main(void)
{
int err = 0;
#ifdef MUTEX_RECURSIVE
pthread_mutexattr_t attr;
err = pthread_mutexattr_init(&attr);
err = pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
err = pthread_mutex_init(&mutex, &attr);
#else
err = pthread_mutex_init(&mutex, NULL);
#endif
err = pthread_create(&demo_tid, NULL, demo_func, NULL);
if (err != 0)
printf("err, can't create thread\n");
#ifdef MUTEX_RECURSIVE
err = pthread_mutexattr_destroy(&attr);
#endif
sleep(1);
return 0;
}
<file_sep>/*
* File name: simple_mod.c
*/
#include "linux/module.h"
#include "linux/fs.h"
#include "linux/uaccess.h"
#include "linux/init.h"
#include "linux/cdev.h"
#include "linux/miscdevice.h"
#define DEMO_NAME "misc_char_dev"
static struct device *misc_dev;
static int misc_char_open(struct inode *inode, struct file *file)
{
int major = MAJOR(inode->i_rdev);
int minor = MINOR(inode->i_rdev);
printk("%s : major=%d, minor=%d\n", __func__, major, minor);
return 0;
}
static int misc_char_release(struct inode *inode, struct file *file)
{
return 0;
}
static ssize_t
misc_char_read(struct file *file, char __user *buf, size_t count,
loff_t *f_pos)
{
printk("%s enter\n", __func__);
return 0;
}
static ssize_t
misc_char_write(struct file *file, const char __user *buf, size_t count,
loff_t *f_pos)
{
printk("%s enter\n", __func__);
return 0;
}
static const struct file_operations misc_char_fops = {
.owner = THIS_MODULE,
.open = misc_char_open,
.release = misc_char_release,
.read = misc_char_read,
.write = misc_char_write,
};
static struct miscdevice misc_char_device = {
.minor = MISC_DYNAMIC_MINOR,
.name = DEMO_NAME,
.fops = &misc_char_fops,
};
static int __init misc_char_init(void)
{
int ret;
ret = misc_register(&misc_char_device);
if (ret) {
printk("failed to register misc device\n");
return ret;
}
misc_dev = misc_char_device.this_device;
printk("successed to register misc char device: %s\n", DEMO_NAME);
return 0;
}
static void __exit misc_char_exit(void)
{
printk("removing device\n");
misc_deregister(&misc_char_device);
}
module_init(misc_char_init);
module_exit(misc_char_exit);
MODULE_AUTHOR("Lin");
MODULE_LICENSE("GPL v2");
MODULE_DESCRIPTION("misc char device");
<file_sep>#!/bin/bash
FILE=$1
if [ ! -d "build" ]
then
mkdir build
fi
if [ ! -f $FILE ]
then
echo "File is not exist"
exit
fi
cd build
cmake ../ -DSOURCE_FILE=$FILE
make
cp test_process.o ../
<file_sep>/*
* File name: 8-1.cpp
*/
#include <iostream>
using namespace std;
istream& read_file(istream &io)
{
string s;
io.tie(&cout);
while (io >> s)
cout << s;
return io;
}
int main(void)
{
istream &io = cin;
auto old_state = io.rdstate();
io.clear();
read_file(io);
cout << "byebye" << endl;
io.setstate(old_state);
return 0;
}
<file_sep>#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
#include <signal.h>
#include <stdlib.h>
pthread_t demo_tid;
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t waitlock = PTHREAD_COND_INITIALIZER;
int quitflag;
sigset_t mask;
void *demo_func(void *arg)
{
int err, signo;
for ( ; ; ) {
err = sigwait(&mask, &signo);
if (err != 0) {
printf("wait signal err\n");
exit(0);
}
switch (signo) {
case SIGINT:
/* Ctrl C */
printf("\ninterrupt\n");
break;
case SIGQUIT:
/* Ctrl \ */
printf("\nquit\n");
pthread_mutex_lock(&lock);
quitflag = 1;
pthread_mutex_unlock(&lock);
pthread_cond_signal(&waitlock);
return (0);
default:
printf("unexcept signal\n");
exit(1);
}
}
}
int main(void)
{
int err = 0;
sigset_t oldmask;
sigemptyset(&mask);
sigaddset(&mask, SIGINT);
sigaddset(&mask, SIGQUIT);
if ((err = pthread_sigmask(SIG_BLOCK, &mask, &oldmask)) != 0) {
printf("SIG_BLOCK error");
exit(0);
}
err = pthread_create(&demo_tid, NULL, demo_func, NULL);
if (err != 0)
printf("err, can't create thread\n");
pthread_mutex_lock(&lock);
while (quitflag == 0)
pthread_cond_wait(&waitlock, &lock);
pthread_mutex_unlock(&lock);
quitflag = 0;
if (sigprocmask(SIG_SETMASK, &oldmask, NULL) < 0)
printf("SIG_SETMASK error");
exit(0);
}
<file_sep>/*
* File name: section_6.cpp
*/
#include <iostream>
#include <vector>
using namespace std;
// reference
int func1(int &r)
{
r = 10;
}
// const
void func2(cont int i)
{
}
// array
void func3(const int *beg, const int* end)
{
}
// reference array
void fun4(int (&arr)[10])
{
}
// change parameter
void func5(initializer_list<string> il)
{
}
// return a vector
void func6(void)
{
return {1, 2};
}
// override
void func7(int i)
{
}
void func7(const int i)
{
}
// const_cast override
const string &shortstring(const string &s1, const string &s2)
{
retyurn s1.size() <= s2.size() ? s1 : s2;
}
string &shortstring(string &s1, string &s2)
{
auto &r = shortstring(const_cast<const string&>s1,
const_cast<const string&>s2);
reutrn const_cast<string&>(r);
}
void func8(int i = 2, int j)
{
}
inline void func8(int i)
{
}
constexpr int new_sz() { reutrn 32;}
constexpr int foo = new_sz();
int main(void)
{
vector<int> v1 = {1, 2, 3, 4, 5};
try {
for (auto v : v1)
cout << v << endl;
}
catch (exception) {
cout << "exception" << endl;
}
}
<file_sep>/*
* File name: find_k_node_from_end.c
*/
#include <stdio.h>
typedef struct list {
int element;
struct list *next;
} list_t;
list_t* find_tail_k_node(list_t *head, int k)
{
if (k <= 0)
return NULL;
if (head == NULL)
return NULL;
list_t *p_head = head, *p_tail = head;
int n = k - 1;
while(p_head->next) {
p_head = p_head->next;
n--;
if (n < 0) {
p_tail = p_tail->next;
}
}
if (n > 0)
return NULL;
return p_tail;
}
#define ARRAY_SIZE(a) sizeof(a) / sizeof(a[0])
int main(void)
{
list_t test[5];
int i;
for(i = 0; i < ARRAY_SIZE(test) - 1; i++) {
test[i].element = i;
test[i].next = &test[i + 1];
}
test[i].element = i;
test[i].next = NULL;
list_t *k_node = find_tail_k_node(&test[0], 6);
if (k_node)
printf("%d \n", k_node->element);
else
printf("NULL\n");
return 0;
}
<file_sep>#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
pthread_t demo_tid;
void *demo_func(void *arg)
{
printf("hello world, a new thread\n");
return((void*)0);
}
int main(void)
{
int err = 0;
err = pthread_create(&demo_tid, NULL, demo_func, NULL);
if (err != 0)
printf("err, can't create thread\n");
sleep(1);
return 0;
}
<file_sep>cmake_minimum_required(VERSION 3.7.1)
project(APUE_process)
message("build $SOURCE_FILE")
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -W -g -pthread")
add_executable(test_process.o ${SOURCE_FILE})
<file_sep>/*
* File name: section_7.cpp
*/
#include <iostream>
#include <vector>
using namespace std;
int main(void)
{
}
class Demo {
public:
Demo() = default;
Demo(int i, int ii): num(i) { };
Demo(int ii): Demo(i, 0) { };
int func(int i);
int func2(Demo&);
explicit int fun3(Demo&);
friend int func4(int i) {return i}
mutable int access_i;
void access() const { return access_i++; }
Demo &func4();
Demo &func4() const;
static int sta_i;
private:
int num;
int num2 = 10;
}
Demo::func(int i)
{
}
int i = 10;
demo.func2(i);
struct Data {
int i;
string s;
}
<file_sep>/*
* File name: insert_sort.c
*/
#include <stdio.h>
#include <stdint.h>
void insert_sort(int *data, int size)
{
for (int i = 1; i < size; i++) {
int j;
int tmp = data[i];
for (j = i; j > 0 && data[j - 1] > tmp; j--)
data[j] = data[j - 1];
data[j] = tmp;
}
}
int main(void)
{
int data[20] = {1, 6, 2, 7, -10, 0, 11, 4, 20, 5, 13, -1, 22, 8, 14, 17, -22, 32, 19, 20};
insert_sort(data, sizeof(data) / sizeof(data[0]));
printf("sort data: ");
for (int i = 0; i < (int)(sizeof(data) / sizeof(data[0])); i++)
printf("%d ", data[i]);
printf("\n");
return 0;
}
<file_sep>cmake_minimum_required(VERSION 3.7.1)
project(APUE_thread)
message("build $SOURCE_FILE")
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -W -g -pthread")
add_executable(test_pthread.o ${SOURCE_FILE})
<file_sep>/*
* File name: bubble_sort.c
*/
#include <stdio.h>
#include <stdint.h>
void bubble_sort(int *data, int size)
{
for (int i = 0; i < size; i++) {
for (int j = 0; j < size - i - 1; j++) {
if (data[j] > data[j + 1]) {
int tmp = data[j];
data[j] = data[j + 1];
data[j + 1] = tmp;
}
}
}
}
int main(void)
{
int data[20] = {1, 6, 2, 7, -10, 0, 11, 4, 20, 5, 13, -1, 22, 8, 14, 17, -22, 32, 19, 20};
bubble_sort(data, sizeof(data) / sizeof(data[0]));
printf("sort data: ");
for (int i = 0; i < (int)(sizeof(data) / sizeof(data[0])); i++)
printf("%d ", data[i]);
printf("\n");
return 0;
}
<file_sep>/*
* File name: client.c
*/
/* socket */
#include <sys/socket.h>
/* #include <netinet/in.h> */
/* inet_pton */
#include <arpa/inet.h>
/* printf */
#include <stdio.h>
/* exit */
#include <stdlib.h>
/* memset */
#include <string.h>
/* write */
#include <unistd.h>
#include <pthread.h>
#define SERV_ADDR "127.0.0.1"
#define SERV_PORT 1234
pthread_mutex_t id_mutex;
int thread_id = 0;
void *query_date(void *arg)
{
int sockfd;
struct sockaddr_in servaddr;
sockfd = socket(AF_INET, SOCK_STREAM, 0);
memset(&servaddr, 0, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(SERV_PORT);
inet_pton(AF_INET, SERV_ADDR, &servaddr.sin_addr);
connect(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr));
write(sockfd, "query date", sizeof("query date"));
char read_buf[128];
read(sockfd, read_buf, 128);
close(sockfd);
pthread_mutex_lock(&id_mutex);
printf("thread %3d query time is %s", ++thread_id, read_buf);
pthread_mutex_unlock(&id_mutex);
return((void*)0);
}
/* int main(int argc, char **argv) */
int main(void)
{
/* if (argc != 2) { */
/* printf("type server address\n"); */
/* exit(0); */
/* } */
pthread_mutex_init(&id_mutex, NULL);
for (int i = 0; i < 500; i++) {
pthread_t pid;
pthread_create(&pid, NULL, query_date, NULL);
}
sleep(2);
}
<file_sep>/*
* File name: tie.cpp
*/
// redefine tied object
#include <iostream> // std::ostream, std::cout, std::cin
#include <fstream> // std::ofstream
int main () {
std::ostream *prevstr;
std::ofstream ofs;
ofs.open ("test.txt");
std::cout << "tie example:\n";
*std::cin.tie() << "This is inserted into cout";
prevstr = std::cin.tie (&ofs);
*std::cin.tie() << "This is inserted into the file";
std::cin.tie (prevstr);
ofs.close();
return 0;
}
<file_sep>#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
pthread_t demo_tid1;
pthread_t demo_tid2;
void *demo_func1(void *arg)
{
printf("thread1 return\n");
return((void*)1);
}
void *demo_func2(void *arg)
{
printf("thread2 exit\n");
pthread_exit((void*)2);
}
int main(void)
{
int err = 0;
void *tret;
err = pthread_create(&demo_tid1, NULL, demo_func1, NULL);
if (err != 0)
printf("err, can't create thread1\n");
err = pthread_create(&demo_tid2, NULL, demo_func2, NULL);
if (err != 0)
printf("err, can't create thread2\n");
err = pthread_join(demo_tid1, &tret);
if (err != 0)
printf("err, can't join thread1\n");
printf("thread1 exit code %ld\n", (long)tret);
err = pthread_join(demo_tid2, &tret);
if (err != 0)
printf("err, can't join thread2\n");
printf("thread2 exit code %ld\n", (long)tret);
return 0;
}
<file_sep>/*
* File name: replace_char.c
*/
#include "stdio.h"
char *replace(char *string)
{
if (string == NULL)
return NULL;
int blank = 0;
int len = strlen(string);
for (int i = 0; i < len; i++) {
if (string[i] == ' ')
blank++;
}
int tail = len + 2 * blank - 1;
for (int i = len - 1; i > 0; i--) {
if (string[i] == ' ') {
string[tail--] = '0';
string[tail--] = '2';
string[tail--] = '%';
} else
string[tail--] = string[i];
}
return string;
}
int main(void)
{
char string[50] = "we are happy";
char *re;
re = replace(string);
printf("%s\n", re);
}
<file_sep>/*
* File name: simple_mod.c
*/
#include <linux/module.h>
#include <linux/fs.h>
#include <linux/uaccess.h>
#include <linux/init.h>
#include <linux/cdev.h>
#include <linux/device.h>
#include <linux/miscdevice.h>
#include <linux/kfifo.h>
#define MAX_DEVICE_BUFFER_SIZE 64
#define DEMO_NAME "buffer_char"
DEFINE_KFIFO(my_dev_fifo, char, 64);
static struct device *buffer_dev;
static int buffer_char_open(struct inode *inode, struct file *file)
{
int major = MAJOR(inode->i_rdev);
int minor = MINOR(inode->i_rdev);
printk("%s : major=%d, minor=%d\n", __func__, major, minor);
return 0;
}
static int buffer_char_release(struct inode *inode, struct file *file)
{
return 0;
}
static ssize_t
buffer_char_read(struct file *file, char __user *buf, size_t count,
loff_t *f_pos)
{
int actual_readed;
int ret;
ret = kfifo_to_user(&my_dev_fifo, buf, count, &actual_readed);
if (ret)
return -EIO;
printk("%s, actual_readed=%d, pos=%lld, %p\n", __func__, actual_readed, *f_pos, f_pos);
return actual_readed;
}
static ssize_t
buffer_char_write(struct file *file, const char __user *buf, size_t count,
loff_t *f_pos)
{
int actual_write;
int ret;
ret = kfifo_from_user(&my_dev_fifo, buf, count, &actual_write);
printk("%s, actual_write=%d, pos=%lld, %p\n", __func__, actual_write, *f_pos, f_pos);
return actual_write;
}
static const struct file_operations buffer_char_fops = {
.owner = THIS_MODULE,
.open = buffer_char_open,
.release = buffer_char_release,
.read = buffer_char_read,
.write = buffer_char_write,
};
static struct miscdevice buffer_char_device = {
.minor = MISC_DYNAMIC_MINOR,
.name = DEMO_NAME,
.fops = &buffer_char_fops,
};
static int __init buffer_char_init(void)
{
int ret;
ret = misc_register(&buffer_char_device);
if (ret) {
printk("failed to register buffer device\n");
return ret;
}
buffer_dev = buffer_char_device.this_device;
printk("successed to register buffer char device: %s\n", DEMO_NAME);
return 0;
}
static void __exit buffer_char_exit(void)
{
printk("removing device\n");
misc_deregister(&buffer_char_device);
}
module_init(buffer_char_init);
module_exit(buffer_char_exit);
MODULE_AUTHOR("Lin");
MODULE_LICENSE("GPL v2");
MODULE_DESCRIPTION("buffer char device");
<file_sep>/*
* File name: quick_sort.c
*/
#include <stdio.h>
#include <stdint.h>
void swap(int *a, int *b)
{
int tmp = *b;
*b = *a;
*a = tmp;
}
int median3(int *data, unsigned long left, unsigned long right)
{
int center = (left + right) / 2;
if (data[left] > data[center])
swap(&data[left], &data[center]);
if (data[center] > data[right])
swap(&data[center], &data[right]);
if (data[left] > data[right])
swap(&data[left], &data[right]);
swap(&data[center], &data[right]);
return data[right];
}
void q_sort(int *data, int left, int right)
{
int pivot;
if (left >= right)
return;
pivot = median3(data, left, right);
/* pivot = data[right]; */
int i = left - 1;
for (int j = left; j <= right - 1; j++) {
if (data[j] <= pivot) {
i++;
swap(&data[i], &data[j]);
}
}
swap(&data[i + 1], &data[right]);
q_sort(data, left, i);
q_sort(data, i + 2, right);
}
void quick_sort(int *data, unsigned long size)
{
q_sort(data, 0, size - 1);
}
int main(void)
{
int data[20] = {1, 6, 2, 7, -10, 0, 11, 4, 20, 5, 13, -1, 22, 8, 14, 17, -22, 32, 19, 20};
/* int data[3] = {1, 6, 2}; */
quick_sort(data, sizeof(data) / sizeof(data[0]));
printf("sort data: ");
for (unsigned long i = 0; i < (sizeof(data) / sizeof(data[0])); i++)
printf("%d ", data[i]);
printf("\n");
return 0;
}
<file_sep>#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <stdint.h>
#include <stdlib.h>
/*
* This demo doesn't work fine on Mac OS, but works on Linux
* Mac OS
* malloc addr: 0x7fb911800000
* hello world, a new thread
* thread stack addr: 0xffffffffffffb000, size is 20480
* thread stack size is 20480
*
* Linux
* malloc addr: 0x563b91a1f010
* thread stack addr: 0x563b91a1f010, size is 25600
* thread stack size is 25600
* hello world, a new thread
*/
pthread_t demo_tid;
void *demo_func(void *arg)
{
printf("hello world, a new thread\n");
return((void*)0);
}
int main(void)
{
int err = 0;
size_t stacksize;
void *cus_stack;
void *read_stack;
pthread_attr_t attr;
err = pthread_attr_init(&attr);
if (err != 0)
return err;
err = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
err = pthread_attr_setstacksize(&attr, 20480);
cus_stack = malloc(25600);
printf("malloc addr: %p\n", cus_stack);
err = pthread_attr_setstack(&attr, cus_stack, 25600);
err = pthread_create(&demo_tid, &attr, demo_func, NULL);
if (err != 0)
printf("err, can't create thread\n");
err = pthread_attr_getstack(&attr, &read_stack, &stacksize);
printf("thread stack addr: %p, size is %ld\n", read_stack, stacksize);
err= pthread_attr_getstacksize(&attr, &stacksize);
printf("thread stack size is %ld\n", stacksize);
pthread_attr_destroy(&attr);
sleep(1);
return 0;
}
<file_sep>#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
#include <time.h>
pthread_t demo_tid1;
pthread_t demo_tid2;
#define LOCK
#ifdef LOCK
pthread_mutex_t demo_mutex;
#endif
int count[10] = {0};
void *demo_func1(void *arg)
{
int *p;
while (1) {
#ifdef LOCK
pthread_mutex_lock(&demo_mutex);
#endif
for (int i = 0; i < 10; i++)
count[i] = 1;
printf("thread1 count: ");
for (int i = 0; i < 10; i++)
printf(" %d ", count[i]);
printf("\n");
#ifdef LOCK
pthread_mutex_unlock(&demo_mutex);
#endif
usleep(100 * 1000);
}
}
void *demo_func2(void *arg)
{
int tmp;
while (1) {
#ifdef LOCK
pthread_mutex_lock(&demo_mutex);
#endif
for (int i = 0; i < 10; i++)
count[i] = 2;
usleep(1 * 1000);
printf("thread2 count: ");
for (int i = 0; i < 10; i++)
printf(" %d ", count[i]);
printf("\n");
#ifdef LOCK
pthread_mutex_unlock(&demo_mutex);
#endif
usleep(100 * 1000);
}
}
int main(void)
{
int err = 0;
void *tret;
err = pthread_create(&demo_tid1, NULL, demo_func1, NULL);
if (err != 0)
printf("err, can't create thread1\n");
err = pthread_create(&demo_tid2, NULL, demo_func2, NULL);
if (err != 0)
printf("err, can't create thread2\n");
#ifdef LOCK
pthread_mutex_init(&demo_mutex, NULL);
#endif
err = pthread_join(demo_tid1, &tret);
if (err != 0)
printf("err, can't join thread1\n");
printf("thread1 exit code %ld\n", (long)tret);
err = pthread_join(demo_tid2, &tret);
if (err != 0)
printf("err, can't join thread2\n");
printf("thread2 exit code %ld\n", (long)tret);
return 0;
}
<file_sep>/*
* File name: section_4.cpp
*/
#include <iostream>
using namespace std;
int main(void)
{
int a = 10;
double b = static_cast<double>(a);
cout << b << endl;
const char *p;
char *pc = const_cast<char*>(p);
int *pp;
char *ppc = reinterpret_cast<char*>(pp);
}
<file_sep>/*
* File name: keyboard.c
*/
#include "stdio.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <linux/input.h>
#include <sys/select.h>
#include <sys/time.h>
int main(void){
int fd;
int ret;
char *node = "/dev/input/event0";
fd_set rfds;
struct timeval tv;
FD_ZERO(&rfds);
if ((fd = open(node, O_RDWR | O_NDELAY)) < 0){
printf("APP open %s failed", node);
return 0;
}
FD_SET(fd, &rfds);
while (1) {
tv.tv_sec = 2;
tv.tv_usec = 0;
ret = select(FD_SETSIZE, &rfds, NULL, NULL, &tv);
if (ret < 0) {
printf("select error\n");
return 0;
}
if (FD_ISSET(fd, &rfds)) {
struct input_event t;
printf("select read able\n");
read(fd, &t, sizeof(t));
if (t.type == EV_KEY) {
printf("key %d %s\n", t.code, (t.value) ? "Pressed" : "Released");
}
}
}
close(fd);
}
<file_sep>/*
* File name: 100m_file_read_write.cpp
*/
// solution 1, one thread
#include <iostream>
#include <thread>
#include <fstream>
using namespace std;
// use command to create 1M random file
// dd if=/dev/urandom of=test.file count=1024 bs=1024
void handler(void)
{
ifstream rfile;
ofstream wfile;
string line;
cout << "11111" << endl;
rfile.open("./test.file");
wfile.open("./write.file");
while (!rfile.eof()) {
getline(rfile, line, '\n');
wfile << line << flush;
}
rfile.close();
wfile.close();
}
int main(void)
{
thread t(handler);
t.join();
}
| f904b9696e4742b504d03e2173af7f7e9ab13f71 | [
"CMake",
"Markdown",
"Makefile",
"C",
"C++",
"Shell"
]
| 46 | C | linvis/coding_practice | 227992bca4da96f57a8e0681ee2647e8eb41b7e3 | 8a64ebcffa3c09ad5ed1d3a2c0e1b22a2a794a83 |
refs/heads/master | <file_sep>package com.example.roundedbutton.Activity;
import android.graphics.drawable.Drawable;
public class UserChoiceClass {
String id;
String title;
String imageURL;
Drawable drawable;
String fragmentName;
Boolean selected;
public UserChoiceClass() {
this.imageURL = "";
this.title = "";
}
public UserChoiceClass(String id, String title, String imageURL, Drawable drawable, String fragmentName) {
this.id = id;
this.title = title;
this.imageURL = imageURL;
this.drawable = drawable;
this.fragmentName = fragmentName;
this.selected = false;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getImageURL() {
return imageURL;
}
public void setImageURL(String imageURL) {
this.imageURL = imageURL;
}
public Drawable getDrawable() {
return drawable;
}
public void setDrawable(Drawable drawable) {
this.drawable = drawable;
}
public String getFragmentName() {
return fragmentName;
}
public void setFragmentName(String fragmentName) {
this.fragmentName = fragmentName;
}
public Boolean getSelected() {
return selected;
}
public void setSelected(Boolean selected) {
this.selected = selected;
}
}
<file_sep>package com.example.roundedbutton.Widgets;
import android.content.Context;
import android.content.Intent;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.roundedbutton.Activity.TopicNewsActivity;
import com.example.roundedbutton.Adapter.NewsRecyclerViewAdapter;
import com.example.roundedbutton.Adapter.SmallNewsCardAdapter;
import com.example.roundedbutton.R;
import com.example.roundedbutton.Utils.Constants;
import com.kwabenaberko.newsapilib.NewsApiClient;
import com.kwabenaberko.newsapilib.models.Article;
import com.kwabenaberko.newsapilib.models.request.EverythingRequest;
import com.kwabenaberko.newsapilib.models.request.TopHeadlinesRequest;
import com.kwabenaberko.newsapilib.models.response.ArticleResponse;
import java.util.ArrayList;
import java.util.List;
public class NewsTopicWidget extends FrameLayout {
String topic, type;
TextView tvTopic;
ImageView ivMoreNews;
RecyclerView recyclerView;
List<Article> articleList;
List<Article> test = new ArrayList<>();
private SmallNewsCardAdapter newsRecyclerViewAdapter;
public NewsTopicWidget(Context context) {
this(context, null);
}
public NewsTopicWidget(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public NewsTopicWidget(final Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflater.inflate(R.layout.widget_news_topic, this, true);
tvTopic = findViewById(R.id.tvNewsTopic);
ivMoreNews = findViewById(R.id.ivMoreNews);
recyclerView = findViewById(R.id.newsWidgetRecyclerView);
articleList = new ArrayList<>();
newsRecyclerViewAdapter = new SmallNewsCardAdapter(getContext(), articleList);
recyclerView.setLayoutManager(new LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false));
recyclerView.setAdapter(newsRecyclerViewAdapter);
ivMoreNews.setOnClickListener(view -> {
Intent intent = new Intent(getContext(), TopicNewsActivity.class);
intent.putExtra("type", type);
intent.putExtra("topic", topic);
getContext().startActivity(intent);
});
}
public void setTypeandTopic(String type, String topic) {
this.type = type;
this.topic = topic;
}
public void setText(String s) {
tvTopic.setText(s);
}
public void load(String s) {
NewsApiClient newsApiClient = new NewsApiClient(Constants.API_KEY);
newsApiClient.getTopHeadlines(new TopHeadlinesRequest.Builder().language("en")
.category(s)
.language("en")
.build(),
new NewsApiClient.ArticlesResponseCallback() {
@Override
public void onSuccess(ArticleResponse articleResponse) {
test = articleResponse.getArticles();
articleList.addAll(test);
newsRecyclerViewAdapter.addAll(test);
}
@Override
public void onFailure(Throwable throwable) {
Log.d("LakError", throwable.getMessage());
}
}
);
}
public void loadc(String country) {
NewsApiClient newsApiClient = new NewsApiClient(Constants.API_KEY);
newsApiClient.getTopHeadlines(new TopHeadlinesRequest.Builder().language("en")
.country(country)
.language("en")
.build(),
new NewsApiClient.ArticlesResponseCallback() {
@Override
public void onSuccess(ArticleResponse articleResponse) {
test = articleResponse.getArticles();
articleList.addAll(test);
newsRecyclerViewAdapter.addAll(test);
}
@Override
public void onFailure(Throwable throwable) {
Log.d("LakError", throwable.getMessage());
}
}
);
}
public void loadq(String query) {
NewsApiClient newsApiClient = new NewsApiClient(Constants.API_KEY);
newsApiClient.getEverything(
new EverythingRequest.Builder()
.language("en")
.q(query)
.build(),
new NewsApiClient.ArticlesResponseCallback() {
@Override
public void onSuccess(ArticleResponse articleResponse) {
test = articleResponse.getArticles();
articleList.addAll(test);
newsRecyclerViewAdapter.addAll(test);
}
@Override
public void onFailure(Throwable throwable) {
Log.d("LakError", throwable.getMessage());
}
}
);
}
}
<file_sep>package com.example.roundedbutton.Fragment;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.roundedbutton.Adapter.InterestRecyclerViewAdapter;
import com.example.roundedbutton.Adapter.NewsVideoItemAdapter;
import com.example.roundedbutton.NewsVideoItem;
import com.example.roundedbutton.R;
import java.util.ArrayList;
import java.util.List;
public class LiveTvFragment extends Fragment {
private RecyclerView recyclerView;
List<NewsVideoItem> newsVideoItemList;
NewsVideoItemAdapter newsVideoItemAdapter;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
newsVideoItemList = new ArrayList<>();
setupNewsVideoItemList();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_live_tv, container, false);
recyclerView = v.findViewById(R.id.videoRecyclerView);
newsVideoItemAdapter = new NewsVideoItemAdapter(getContext(), newsVideoItemList);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.setAdapter(newsVideoItemAdapter);
return v;
}
void setupNewsVideoItemList() {
newsVideoItemList.add(new NewsVideoItem("India TV", "https://indiatvnews.com", "LZcMzgx8c0Y"));
newsVideoItemList.add(new NewsVideoItem("NDTV India", "https://ndtv.com", "MN8p-Vrn6G0"));
newsVideoItemList.add(new NewsVideoItem("Aaj Tak", "https://aajtak.in", "cnX9fQEq59A"));
newsVideoItemList.add(new NewsVideoItem("ABP News", "https://news.abplive.com", "odmHZVWb7ws", "https://upload.wikimedia.org/wikipedia/en/9/90/ABP_News_Logo.png"));
newsVideoItemList.add(new NewsVideoItem("Republic World", "https://www.republicworld.com/", "4QDUnBTrphQ", "https://upload.wikimedia.org/wikipedia/commons/7/7a/Republic_TV.jpg"));
newsVideoItemList.add(new NewsVideoItem("India Today", "https://www.indiatoday.in/", "heFq-5rmUTY"));
newsVideoItemList.add(new NewsVideoItem("DD News", "http://ddnews.gov.in/", "YTYL9VyMvC8", "https://upload.wikimedia.org/wikipedia/commons/e/e9/DD_News.png"));
newsVideoItemList.add(new NewsVideoItem("CNBC News", "https://www.cnbc.com", "Kxwrqig5UV4"));
newsVideoItemList.add(new NewsVideoItem("News 18", "https://www.news18.com/", "GCIUMx73QlQ"));
newsVideoItemList.add(new NewsVideoItem("DD National", "https://prasarbharati.gov.in", "oEu-PmkVBBE"));
//newsVideoItemList.add(new NewsVideoItem("ABC News", "https://abcnews.go.com/", "w_Ma8oQLmSM", "https://s.abcnews.com/assets/beta/assets/abcn_images/abcnews_pearl_stacked.png"));
newsVideoItemList.add(new NewsVideoItem("CNA 24x7", "https://www.channelnewsasia.com/", "XWq5kBlakcQ"));
newsVideoItemList.add(new NewsVideoItem("SKY News", "https://news.sky.com/", "9Auq9mYxFEE"));
}
}<file_sep>package com.example.roundedbutton.Activity;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.example.roundedbutton.NewsVideoItem;
import com.example.roundedbutton.R;
import com.pierfrancescosoffritti.androidyoutubeplayer.core.player.PlayerConstants;
import com.pierfrancescosoffritti.androidyoutubeplayer.core.player.YouTubePlayer;
import com.pierfrancescosoffritti.androidyoutubeplayer.core.player.listeners.AbstractYouTubePlayerListener;
import com.pierfrancescosoffritti.androidyoutubeplayer.core.player.listeners.YouTubePlayerFullScreenListener;
import com.pierfrancescosoffritti.androidyoutubeplayer.core.player.listeners.YouTubePlayerListener;
import com.pierfrancescosoffritti.androidyoutubeplayer.core.player.utils.YouTubePlayerUtils;
import com.pierfrancescosoffritti.androidyoutubeplayer.core.player.views.YouTubePlayerView;
import com.pierfrancescosoffritti.androidyoutubeplayer.core.ui.menu.YouTubePlayerMenu;
public class LiveNewsDetailActivity extends AppCompatActivity {
YouTubePlayerView youTubePlayerView;
String videoId;
ImageView channelIcon;
TextView tvChannelName, tvChannelWebsite;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_live_news_detail);
Intent intent = getIntent();
NewsVideoItem newsVideoItem = intent.getParcelableExtra("newsVideoItem");
Toolbar toolbar = findViewById(R.id.liveTVToolbar);
toolbar.setTitle("Live News");
toolbar.setTitleTextColor(Color.WHITE);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
videoId = newsVideoItem.getVideoId();
channelIcon = findViewById(R.id.channelIcon);
tvChannelName = findViewById(R.id.channelName);
tvChannelWebsite = findViewById(R.id.visitWebsite);
youTubePlayerView = findViewById(R.id.liveVideoPlayer);
getLifecycle().addObserver(youTubePlayerView);
Glide.with(this).load(newsVideoItem.getImageUrl()).into(channelIcon);
tvChannelName.setText(newsVideoItem.getChannelName());
youTubePlayerView.addYouTubePlayerListener(new AbstractYouTubePlayerListener() {
@Override
public void onReady(YouTubePlayer youTubePlayer) {
super.onReady(youTubePlayer);
youTubePlayer.loadVideo(videoId, 0);
}
@Override
public void onError(YouTubePlayer youTubePlayer, PlayerConstants.PlayerError error) {
super.onError(youTubePlayer, error);
Log.d("LakPlayerError", error.toString());
}
});
tvChannelWebsite.setOnClickListener(view -> {
Intent intent1 = new Intent(this, WebViewActivity.class);
intent1.putExtra("articleUrl", newsVideoItem.getWebsiteUrl());
startActivity(intent1);
});
}
@Override
protected void onSaveInstanceState(@NonNull Bundle outState) {
super.onSaveInstanceState(outState);
//outState.putAll(youTubePlayerView);
}
@Override
public void onBackPressed() {
super.onBackPressed();
}
@Override
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}
}<file_sep>include ':app'
rootProject.name = "RoundedButton"<file_sep>package com.example.roundedbutton.Entities;
import androidx.room.ColumnInfo;
import androidx.room.Entity;
import androidx.room.PrimaryKey;
import com.kwabenaberko.newsapilib.models.Article;
@Entity(tableName = "savedArticle")
public class SavedArticle {
@PrimaryKey(autoGenerate = true)
private int id;
private String title;
private String description;
private String sourceName;
private String category;
private String url;
private String urlToImage;
private String publishedAt;
public SavedArticle(String title, String description, String sourceName, String category, String url, String urlToImage, String publishedAt) {
this.title = title;
this.description = description;
this.sourceName = sourceName;
this.category = category;
this.url = url;
this.urlToImage = urlToImage;
this.publishedAt = publishedAt;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getSourceName() {
return sourceName;
}
public void setSourceName(String sourceName) {
this.sourceName = sourceName;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getUrlToImage() {
return urlToImage;
}
public void setUrlToImage(String urlToImage) {
this.urlToImage = urlToImage;
}
public String getPublishedAt() {
return publishedAt;
}
public void setPublishedAt(String publishedAt) {
this.publishedAt = publishedAt;
}
}
<file_sep>package com.example.roundedbutton.Activity;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.webkit.WebView;
import com.example.roundedbutton.R;
public class WebViewActivity extends AppCompatActivity {
WebView webView;
String articleUrl;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_web_view);
Intent intent = getIntent();
articleUrl = intent.getStringExtra("articleUrl");
webView = findViewById(R.id.webview);
Log.d("Lakshyaurl", articleUrl);
if (articleUrl.charAt(4) != 's') articleUrl = articleUrl.replaceFirst("^http", "https");
Log.d("Lakshyaurlnew", articleUrl);
webView.loadUrl(articleUrl);
}
}<file_sep>package com.example.roundedbutton.Adapter;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager2.widget.ViewPager2;
import com.bumptech.glide.Glide;
import com.example.roundedbutton.Activity.WebViewActivity;
import com.example.roundedbutton.R;
import com.example.roundedbutton.Utils.utils;
import com.kwabenaberko.newsapilib.models.Article;
import java.util.List;
public class SwipeCardAdapter extends RecyclerView.Adapter<SwipeCardAdapter.SwipeViewHolder> {
private List<Article> articleList;
private ViewPager2 viewPager2;
Context mContext;
public SwipeCardAdapter(Context context, List<Article> articleList, ViewPager2 viewPager2) {
this.articleList = articleList;
this.viewPager2 = viewPager2;
this.mContext = context;
}
@NonNull
@Override
public SwipeViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View view = inflater.inflate(R.layout.swipe_card_detail, parent, false);
return new SwipeCardAdapter.SwipeViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull SwipeViewHolder holder, int position) {
holder.setArticle(articleList.get(position));
}
@Override
public int getItemCount() {
return articleList.size();
}
public void clearAll() {
articleList.clear();
notifyDataSetChanged();
}
public void addAll(List<Article> articleList1) {
Log.d("LakAddAllSwipe", " " + articleList1.size());
articleList.addAll(articleList1);
notifyDataSetChanged();
}
class SwipeViewHolder extends RecyclerView.ViewHolder {
ImageView articleImage, articleSave, goLeft, goRight, articleWebView, articleShare;
TextView articleHeadline, articleTopic, articlePublisher, articleDescription;
public SwipeViewHolder(@NonNull View itemView) {
super(itemView);
articleImage = itemView.findViewById(R.id.articleImage);
articleSave = itemView.findViewById(R.id.articleSave);
articleWebView = itemView.findViewById(R.id.articleWebView);
articleShare = itemView.findViewById(R.id.articleShare);
articleHeadline = itemView.findViewById(R.id.articleHeadline);
articleDescription = itemView.findViewById(R.id.articleDescription);
articleTopic = itemView.findViewById(R.id.articleTopic);
articlePublisher = itemView.findViewById(R.id.articlePublisher);
goLeft = itemView.findViewById(R.id.goLeft);
goRight = itemView.findViewById(R.id.goRight);
}
void setArticle(Article article) {
articleHeadline.setText(article.getTitle());
articleDescription.setText(article.getDescription());
Glide.with(articleImage.getContext()).load(article.getUrlToImage()).into(articleImage);
String published = article.getSource().getName() + " | " + utils.getTimeDifference(utils.formatDate(article.getPublishedAt()));
articlePublisher.setText(published);
goLeft.setOnClickListener(view -> {
if (viewPager2.getCurrentItem() > 0) {
viewPager2.setCurrentItem(viewPager2.getCurrentItem() - 1);
}
});
goRight.setOnClickListener(view -> {
if (viewPager2.getCurrentItem() < getItemCount() - 1) {
viewPager2.setCurrentItem(viewPager2.getCurrentItem() + 1);
}
});
articleWebView.setOnClickListener(view -> {
Intent intent1 = new Intent(mContext, WebViewActivity.class);
intent1.putExtra("articleUrl", article.getUrl());
mContext.startActivity(intent1);
});
articleShare.setOnClickListener(view -> {
Intent sharingIntent = new Intent(Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
sharingIntent.putExtra(Intent.EXTRA_TEXT, article.getSource().getName() + " - " + article.getTitle() + " : " + article.getUrl());
mContext.startActivity(Intent.createChooser(sharingIntent, mContext.getString(R.string.share_article)));
});
}
}
}
<file_sep>package com.example.roundedbutton.Activity;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.view.ViewCompat;
import androidx.viewpager.widget.ViewPager;
import android.Manifest;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.StateListDrawable;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import com.example.roundedbutton.Adapter.LoginAdapter;
import com.example.roundedbutton.R;
import com.google.android.material.tabs.TabLayout;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class LoginActivity extends AppCompatActivity {
TabLayout tabLayout;
ViewPager viewPager;
Button submitButton, agreeButton;
TextView skipButton, termsAndCondition;
Dialog dialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
tabLayout = findViewById(R.id.tabLayout);
viewPager = findViewById(R.id.viewPager);
submitButton = findViewById(R.id.submitButton);
skipButton = findViewById(R.id.skipButton);
agreeButton = findViewById(R.id.agreeButton);
termsAndCondition = findViewById(R.id.tvtermsandcondition);
dialog = new Dialog(LoginActivity.this);
dialog.setContentView(R.layout.termsandconditiondialog);
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
dialog.getWindow().setBackgroundDrawable(getDrawable(R.drawable.tab_bg_normal_white));
}
agreeButton = dialog.findViewById(R.id.agreeButton);
termsAndCondition.setOnClickListener(view -> dialog.show());
agreeButton.setOnClickListener(view -> dialog.dismiss());
tabLayout.addTab(tabLayout.newTab().setText("Login"));
tabLayout.addTab(tabLayout.newTab().setText("Signup"));
//tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
tabLayout.setTabTextColors(Color.WHITE, Color.BLACK);
//ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 44);
int tabCount = tabLayout.getTabCount();
for (int i = 0; i < tabCount; i++) {
View tabView = ((ViewGroup) tabLayout.getChildAt(0)).getChildAt(i);
tabView.requestLayout();
ViewCompat.setBackground(tabView, setImageButtonStateNew(this));
//ViewCompat.setPaddingRelative(tabView, tabView.getPaddingStart(), tabView.getPaddingTop(), tabView.getPaddingEnd(), tabView.getPaddingEnd());
}
//tabLayout.setupWithViewPager(viewPager);
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
final LoginAdapter loginAdapter = new LoginAdapter(getSupportFragmentManager(), this, tabLayout.getTabCount());
viewPager.setAdapter(loginAdapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
skipButton.setOnClickListener(view -> {
Intent intent = new Intent(LoginActivity.this, UserChoiceActivity.class);
startActivity(intent);
});
}
Drawable setImageButtonStateNew(Context mContext) {
StateListDrawable states = new StateListDrawable();
states.addState(new int[]{android.R.attr.state_selected}, ContextCompat.getDrawable(mContext, R.drawable.tab_bg_normal_white));
states.addState(new int[]{-android.R.attr.state_selected}, ContextCompat.getDrawable(mContext, R.drawable.tab_bg_normal));
return states;
}
}<file_sep>package com.example.roundedbutton.Fragment;
import androidx.fragment.app.Fragment;
public class UserChoiceBaseFragment extends Fragment {
/*public void loadSearch(String searchQuery, String type) {
mList = mOriginalList;
if (searchQuery.isEmpty()) {
renderData();
} else {
mList = Utils.search(searchQuery, mList, type);
if (mList != null) {
renderData();
}
}
}
*/
}
<file_sep>package com.example.roundedbutton.Fragment;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.roundedbutton.Adapter.NewsRecyclerViewAdapter;
import com.example.roundedbutton.R;
import com.example.roundedbutton.Widgets.NewsTopicWidget;
public class TopStoriesFragment extends Fragment {
NewsTopicWidget widgetLatestNews, widgetIndiaNews, widgetGeneralNews, widgetTechNews,
widgetScienceNews, widgetSportsNews, widgetEntertainmentNews, widgetHealthNews, widgetBusinessNews;
private NewsRecyclerViewAdapter latestNewsRVAdapter, indiaNewsRVAdapter,
techNewsRVAdapter, scienceNewsRVAdapter, sportsNewsRVAdapter, entertainmentNewsRVAdapter, healthNewsRVAdapter;
public TopStoriesFragment() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_top_stories, container, false);
/*widgetLatestNews = view.findViewById(R.id.widgetLatestNews);
widgetLatestNews.setText("Latest News");
widgetLatestNews.setTypeandTopic("query","indore");
widgetLatestNews.loadq("world");*/
widgetIndiaNews = view.findViewById(R.id.widgetIndiaNews);
widgetIndiaNews.setText("India");
widgetIndiaNews.setTypeandTopic("country", "in");
widgetIndiaNews.loadc("in");
widgetGeneralNews = view.findViewById(R.id.widgetGeneralNews);
widgetGeneralNews.setText("General");
widgetGeneralNews.setTypeandTopic("category", "general");
widgetGeneralNews.load("general");
/*widgetTechNews = view.findViewById(R.id.widgetTechNews);
widgetTechNews.setText("Tech");
widgetTechNews.setTypeandTopic("category", "technology");
widgetTechNews.load("technology");
widgetScienceNews = view.findViewById(R.id.widgetScienceNews);
widgetScienceNews.load("science");
widgetScienceNews.setTypeandTopic("category","science");
widgetScienceNews.setText("Science");
widgetSportsNews = view.findViewById(R.id.widgetSportsNews);
widgetSportsNews.setText("Sports");
widgetSportsNews.setTypeandTopic("category","sports");
widgetSportsNews.load("sports");
widgetEntertainmentNews = view.findViewById(R.id.widgetEntertainmentNews);
widgetEntertainmentNews.setText("Entertainment");
widgetEntertainmentNews.setTypeandTopic("category","entertainment");
widgetEntertainmentNews.load("entertainment");
widgetHealthNews = view.findViewById(R.id.widgetHealthNews);
widgetHealthNews.setText("Health");
widgetHealthNews.setTypeandTopic("category","health");
widgetHealthNews.load("health");
widgetBusinessNews = view.findViewById(R.id.widgetBusinessNews);
widgetBusinessNews.setText("Business");
widgetBusinessNews.setTypeandTopic("category","business");
widgetBusinessNews.load("business");
*/
return view;
}
} | 1b58f881665255adada11c17fd8184b50883f253 | [
"Java",
"Gradle"
]
| 11 | Java | Lakshya28/News-App | d0241f7c11cf401a4a58f2f1d012c06ee8cf75de | 25eb8192d9a926796a46a71101aa4d8b4833c3d6 |
refs/heads/master | <file_sep>const https = require('https');
const http = require('http');
const { getOptions, postOptions } = require('./options');
setInterval(async () => {
const jsonData = await run();
const { name, latitude, longitude } = jsonData;
const obj = { serial: 4, model: name.toUpperCase(), latitude, longitude };
data = JSON.stringify(obj);
options = {
...postOptions, headers: {
'Content-Type': 'application/json',
'Content-Length': data.length
}
}
const response = await post(options, data);
console.log(response)
}, 5000)
async function run() {
const result = await get(getOptions);
return result;
}
function get(options) {
return new Promise((resolve, reject) => {
let data;
https.get(options, (res) => {
res.on('data', chunk => {
data += chunk
});
res.on('end', () => {
if (res.statusCode === 200) {
const [, json] = data.split('undefined');
resolve(JSON.parse(json));
}
});
res.on('error', () => reject(res.headers));
})
})
}
function post(options, json) {
let data;
const req = http.request(options, (res) => {
res.on('error', () => reject(res.headers));
res.on('data', chunk => {
data += chunk
});
})
return new Promise((resolve, reject) => {
req.write(json);
req.end();
req.on('response', (res) => {
res.on('end', () => {
if (res.statusCode === 200) {
const [, json] = data.split('undefined');
resolve(JSON.parse(json));
}
});
});
})
} | 8ac2b42cfac97e46da80c55cf2d329dc4281822a | [
"JavaScript"
]
| 1 | JavaScript | FaradaySeki/anyWhere-FakeDevice | c0eb8f9ffbe14948119d9748db847d71908a2fc4 | 1760f862413f44594efe5b361cf2d0406e46a5ae |
refs/heads/main | <file_sep># !/bin/bash
rostopic pub -1 /robot_0/initialpose geometry_msgs/Pose2D -- 0.0 0.0 0.0
rostopic pub -1 /robot_1/initialpose geometry_msgs/Pose2D -- -6.0 6.0 0.0
rostopic pub -1 /robot_2/initialpose geometry_msgs/Pose2D -- 4.0 0.0 0.0
rostopic pub -1 /robot_3/initialpose geometry_msgs/Pose2D -- 6.0 6.0 0.0
rostopic pub -1 /robot_4/initialpose geometry_msgs/Pose2D -- -6.0 -2.0 0.0
rostopic pub -1 /robot_5/initialpose geometry_msgs/Pose2D -- 0.0 -6.0 0.0
rostopic pub -1 /robot_6/initialpose geometry_msgs/Pose2D -- 6.0 -4.0 0.0
rostopic pub -1 /robot_7/initialpose geometry_msgs/Pose2D -- 0.0 8.0 0.0
rosrun connectivity terminals
<file_sep>## For full information http://wiki.ros.org/catkin/CMakeLists.txt
#############################################################################
## Set minimum required version of cmake, project name and compile options ##
#############################################################################
cmake_minimum_required(VERSION 2.8.3)
project(connectivity)
###########################################################################
## Find catkin packages and libraries for catkin and system dependencies ##
###########################################################################
find_package(catkin REQUIRED COMPONENTS
rospy
geometry_msgs
nav_msgs
std_msgs
tf
actionlib
)
##########################################
## Setup for python modules and scripts ##
##########################################
################################################
## Declare ROS messages, services and actions ##
################################################
# No new message declared.
add_action_files(
DIRECTORY action
FILES
Task.action
)
add_service_files(
DIRECTORY srv
FILES
Registration.srv
)
generate_messages(
DEPENDENCIES
nav_msgs
actionlib_msgs
)
################################################
## Declare ROS dynamic reconfigure parameters ##
################################################
# No new parameters declared.
###################################
## catkin specific configuration ##
###################################
catkin_package(
CATKIN_DEPENDS
rospy
geometry_msgs
nav_msgs
std_msgs
tf
actionlib_msgs
)
###########
## Build ##
###########
include_directories(
include
${catkin_INCLUDE_DIRS}
)
#############
## Install ##
#############
# all install targets should use catkin DESTINATION variables
# See http://ros.org/doc/api/catkin/html/adv_user_guide/variables.html
catkin_install_python(PROGRAMS
nodes/follower
nodes/leader
nodes/broadcaster
nodes/random_waypoints
DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION}
)
install(DIRECTORY launch
DESTINATION ${CATKIN_PACKAGE_SHARE_DESTINATION}
)
#############
## Testing ##
#############
# No unit test performed.
<file_sep>#### Author: <NAME>
#### Date: May 1, 2021
<br >
# Connectivity Maintenance for Multirobot Systems
This package computes intermediate locations necessary for maintaining connectivity for a given set of target locations and moves robots to those intermediate locations.
For the demonstration purpose, 1 leader and 7 followers are deployed. The robot with the lowest ID is the leader; the other 7 are followers. They coordinate in a leader-follower fashion. The leader does the computing and sends waypoints to the followers. All robots, including the leader, can be assigned waypoints.
# Nodes
* `leader`:
* initiates coordination
* waits for terminal messages
* computes all waypoints that require robots in place to ensure connectivity
* assigns each waypoint to the closest robot so that the total distance traveled by all robots is minimized
* sends goals to corresponding robots
* `follower`: receives waypoints from the leader and moves to the waypoints
* `broadcaster`: sets a common reference frame for all robots. A static tf broadcaster that broadcasts the coordinate frame of each robot according to their initial poses.
* `terminal`: generates random target locations and publishes them as a terminal messages. For the demonstration purpose, the number of random terminal
locations is set to 4.
# Instructions for running simulation in stageros (with Docker)
1. In the first terminal:
* run `docker-compose up --build`
2. In the second terminal:
* run `docker-compose exec ros bash`, this will bring you to `catkin_ws`
* run `catkin_make` to generate message files for ROS services and actions
* run `roscore`
3. In the third terminal:
* run `docker-compose exec ros bash`, this will bring you to `catkin_ws`
* copy`emtpy.world` and `emptyfloor.bmp` from `connectivity/world` to `stage_ros/world`
* run `rosrun stage_ros stageros connectivity/world/empty.world` to start a empty world and spawn the robots
4. In the fourth terminal: navigate to the `vnc-ros` directory,
* run `docker-compose exec ros bash`, this will bring you to `catkin_ws`
* run `roslaunch connectivity connectivity.launch`
5. In the fourth terminal: navigate to the `vnc-ros` directory,
* run `docker-compose exec ros bash`, this will bring you to `catkin_ws`
* after the 4th terminal shows statements indicating that the leader and followers are initiated and are "waiting for terminals", run `./inputs.sh` to publish initial poses for all robots and publish 4 random terminals
* after the 4th terminal shows "waiting for new terminals" again, run `rosrun connectivty terminals` to give new random terminals to the leader.
# Demo
See `simulation_demo.mov` (An update about running the world file is included in step 3 of the Instructions Section)
<file_sep>#!/usr/bin/env python
"""
Author: <NAME>
Date: May 12, 2020
Generate random terminal locations and publishes them as
a single Path message under the "/terminals" topic (the number of random terminal
locations is set to 4 for demonstration purpose)
Assumption: the number of verticess are equal to the number of robots,
with the terminal vertices less than or equal to the number of robots available
Usage: rosrun pa5 terminals
"""
# import of python modules
import random
# import of relevant libraries
import tf # package for setting coordinate frames
import rospy # module for ROS APIs
from nav_msgs.msg import Path # message type for an list of terminals
from geometry_msgs.msg import PoseStamped # message type for each terminal
# Constants
DEFAULT_TERMINALS_TOPIC = '/terminals'
# Vertices of a communication graph
VERTICES = [(6, 4), (-2, 2), (2, 2), (-4, 4), (-4, -2), (-2, -6), (4, -4), (0, -2)]
NUM_TERMINALS = 4
def compose_terminals_msg(terminals):
"""Compose path message from calculated terminals"""
path_msg = Path()
poses = []
# compose the PoseStamped message for each terminal
for i in range(len(terminals)):
pose = PoseStamped()
pose.pose.position.x = terminals[i][0]
pose.pose.position.y = terminals[i][1]
pose.pose.position.z = 0
quarternion = tf.transformations.quaternion_from_euler(0, 0, 0)
pose.pose.orientation.x = quarternion[0]
pose.pose.orientation.y = quarternion[1]
pose.pose.orientation.z = quarternion[2]
pose.pose.orientation.w = quarternion[3]
pose.header.stamp = rospy.Time.now()
pose.header.frame_id = "world"
poses.append(pose)
path_msg.header.stamp = rospy.Time.now()
path_msg.header.frame_id = "world"
path_msg.poses = poses
return path_msg
if __name__ == "__main__":
# initialization of node.
rospy.init_node("terminals")
# Sleep for a few seconds to wait for the registration.
rospy.sleep(2)
# set up terminals publisher
terminals_pub = rospy.Publisher(DEFAULT_TERMINALS_TOPIC, Path, queue_size=1)
rospy.sleep(2)
# compute terminals, compose path message, and publish
random_terminals = []
for i in range(NUM_TERMINALS):
new_terminal = random.choice(VERTICES)
while new_terminal in random_terminals:
new_terminal = random.choice(VERTICES)
random_terminals.append(new_terminal)
terminals_msg = compose_terminals_msg(random_terminals)
while terminals_pub.get_num_connections() == 0:
rospy.loginfo("Waiting for subscriber to connect")
rospy.sleep(1)
terminals_pub.publish(terminals_msg)
rospy.loginfo(terminals_msg)
<file_sep>#!/usr/bin/env python
"""
Author: <NAME>
Date: May 12, 2020
A static tf broadcaster to broadcast the coordinate frame of each robot according to their initial poses.
Usage: rosrun pa5 broadcaster
"""
import tf2_ros # package that provides StaticTransformBroadcaster
import tf # package for setting coordinate frames
import rospy # module for ROS APIs
from geometry_msgs.msg import Pose2D # message type for initial poses
from geometry_msgs.msg import TransformStamped
DEFAULT_INITIAL_POSE_TOPIC = 'initialpose'
DEFAULT_ODOM_TOPIC = 'odom'
def initial_pose_callback(msg):
# get namespace from message connection header
ns = '/' + msg._connection_header["topic"].split("/")[1] + '/'
rospy.loginfo(ns + " initialpose received")
broadcaster = tf2_ros.StaticTransformBroadcaster() # set up static broadcaster
static_transformStamped = TransformStamped() # create transform message to be broadcasted
static_transformStamped.header.stamp = rospy.Time.now() # time stamp
static_transformStamped.header.frame_id = "world" # parent frame
static_transformStamped.child_frame_id = ns + DEFAULT_ODOM_TOPIC # child frame
static_transformStamped.transform.translation.x = msg.x
static_transformStamped.transform.translation.y = msg.y
static_transformStamped.transform.translation.z = 0
quarternion = tf.transformations.quaternion_from_euler(0, 0, msg.theta)
static_transformStamped.transform.rotation.x = quarternion[0]
static_transformStamped.transform.rotation.y = quarternion[1]
static_transformStamped.transform.rotation.z = quarternion[2]
static_transformStamped.transform.rotation.w = quarternion[3]
broadcaster.sendTransform(static_transformStamped) # send transform message
if __name__ == "__main__":
rospy.init_node('tf_broadcaster', anonymous = True)
rospy.sleep(2)
ns = rospy.get_namespace()
# subscribe to initialpose topic
rospy.Subscriber(ns + DEFAULT_INITIAL_POSE_TOPIC, Pose2D, initial_pose_callback, queue_size=1)
rospy.spin()
<file_sep>#!/usr/bin/env python
"""
Author: <NAME>
Date: May 12, 2021
Follower: receives waypoints from the leader and moves to the waypoints
Usage: rosrun pa5 follower
"""
# import of python modules
import math
# import of relevant libraries
import tf # package for setting coordinate frames
import rospy # module for ROS APIs
import actionlib # package for ROS action, for use of SimpleActionServer
from turtlebot3_gazebo.srv import Registration # service type for registration
from turtlebot3_gazebo.msg import TaskAction, TaskResult # action type and message type for action result
from std_msgs.msg import Bool # message type for init_co
from geometry_msgs.msg import Twist # message type for cmd_vel
# constants
DEFAULT_INITIATE_COORDINATION_TOPIC = '/init_co'
DEFAULT_ACTION_TOPIC = 'task'
DEFAULT_SERVICE_TOPIC = '/registration'
DEFAULT_CMD_VEL_TOPIC = 'cmd_vel'
DEFAULT_TASK_DONE_TOPIC = 'taskdone'
FREQUENCY = 10 #Hz
LINEAR_VELOCITY = 0.2 # m/s
ANGULAR_VELOCITY = math.pi/4 # rad/s
class Follower():
def __init__(self, ns, linear_velocity=LINEAR_VELOCITY, angular_velocity=ANGULAR_VELOCITY, frequency=FREQUENCY):
# namespace
self.ns = ns
# state
self.state = "stop"
# subscribe to the init_co topic
self.init_coordination_sub = rospy.Subscriber(DEFAULT_INITIATE_COORDINATION_TOPIC, Bool, self.initiate_coordination_callback, queue_size=1)
# set up Task action server
self._as = actionlib.SimpleActionServer(self.ns + DEFAULT_ACTION_TOPIC , TaskAction, execute_cb=self.execute_cb, auto_start = False)
self._taskdone_pub = rospy.Publisher(DEFAULT_TASK_DONE_TOPIC, Bool, queue_size=1)
# set up publisher
self._cmd_pub = rospy.Publisher(DEFAULT_CMD_VEL_TOPIC, Twist, queue_size=1)
# other variables
self.rotate_duration = None
self.rotate_start_time = None
self.move_start_time = None
self.move_duration = None
self.linear_velocity = linear_velocity
self.angular_velocity = angular_velocity
self.frequency = FREQUENCY
def initiate_coordination_callback(self, msg):
"""process init_co message:
call self.registration_client to initiate registration process"""
if msg.data == True:
self.registration_client()
def registration_client(self):
"""send registration request and process response"""
rospy.wait_for_service(DEFAULT_SERVICE_TOPIC)
srv = rospy.ServiceProxy(DEFAULT_SERVICE_TOPIC, Registration)
# send service request
srv_response = srv(1)
# process service response
if srv_response.registered == 1:
# start the action server
self._as.start()
def execute_cb(self, goal):
"""execute callback that will run whenever a new goal is received"""
rospy.loginfo(self.ns + " goal received")
quaternion = goal.pose.orientation
euler = tf.transformations.euler_from_quaternion([quaternion.x, quaternion.y, quaternion.z, quaternion.w])
rotation_angle = euler[2]
if rotation_angle < 0:
self.angular_velocity = - self.angular_velocity
# set rotation duration and move duration
self.rotate_duration = abs(rotation_angle / self.angular_velocity)
self.move_duration = goal.pose.position.x /self.linear_velocity
# start rotating
self.state = "rotate"
self.rotate_start_time = rospy.get_rostime()
# send to the action client the action result that the goal is executed
result = TaskResult()
result.success = 1
self._as.set_succeeded(result)
def move(self):
"""move (assuming the robot has rotated towards the goal direction.
After moving to the goal position, publish taskdone message"""
if self.move_duration > 0:
twist_msg = Twist()
twist_msg.linear.x = self.linear_velocity
self._cmd_pub.publish(twist_msg)
self.move_duration -= 1/float(self.frequency)
else:
self.stop()
self.state = "stop"
done_msg = Bool()
done_msg.data = True
self._taskdone_pub.publish(done_msg)
def stop(self):
"""Stop the robot."""
twist_msg = Twist()
self._cmd_pub.publish(twist_msg)
def rotate(self):
"""
Rotate in place based on fixed angular velocity.
After rotation start moving.
"""
if self.rotate_duration > 0:
twist_msg = Twist()
twist_msg.angular.z = self.angular_velocity
self._cmd_pub.publish(twist_msg)
self.rotate_duration -= 1/float(self.frequency)
else:
self.stop()
self.state = "move"
if __name__ == "__main__":
rospy.init_node("follower", anonymous=True)
rospy.sleep(2)
ns = rospy.get_namespace()
follower = Follower(ns)
rospy.loginfo(ns + " follower initiated")
rate = rospy.Rate(FREQUENCY)
while not rospy.is_shutdown():
if follower.state == "rotate":
follower.rotate()
if follower.state == "move":
follower.move()
rate.sleep()
<file_sep>#!/usr/bin/env python
"""
Author: <NAME>
Date: May 12, 2020
Leader:
- construct communication graph
- initiates coordination
- waits for terminal messages
- computes all waypoints that require robots in place to ensure connectivity
- assigns each waypoint to the closest robot so that the total distance traveled by all robots is minimized
- sends goals to corresponding robots
Assumption: the number of nodes are equal to the number of robots,
with the terminal nodes less than or equal to the number of robots available
This script: the ROS node for the leader
Usage: rosrun pa5 leader
"""
# import of python modules
import numpy as np
import math
import networkx as nx
from networkx.algorithms.approximation.steinertree import steiner_tree
# import relevant libraries
import tf # package for setting coordinate frames
import rospy # module for ROS APIs
import actionlib # package for ROS action, for use of SimpleActionServer
from turtlebot3_gazebo.srv import Registration, RegistrationResponse # service type for registration, message type for service responce
from turtlebot3_gazebo.msg import TaskAction, TaskGoal # action type and message type for action goal
from nav_msgs.msg import Path # message type for an list of waypoints
from std_msgs.msg import Bool # message type for /init_co
from geometry_msgs.msg import Pose # message type for goal
from geometry_msgs.msg import Twist # message type for cmd_vel
# Constants
DEFAULT_TERMINALS_TOPIC = '/terminals'
DEFAULT_INITIATE_COORDINATION_TOPIC = '/init_co'
DEFAULT_ACTION_TOPIC = 'task'
DEFAULT_TASK_DONE_TOPIC = 'taskdone'
DEFAULT_CMD_VEL_TOPIC = 'cmd_vel'
LINEAR_VELOCITY = 0.2 # m/s
ANGULAR_VELOCITY = math.pi/4 # rad/s
VERTICES = [(6, 4), (-2, 2), (2, 2), (-4, 4), (-4, -2), (-2, -6), (4, -4), (0, -2)] # nodes in the communication graph
MIN_D = 2 * math.sqrt(5) # minimum distance required to add an edge between two nodes
FREQUENCY = 10 #Hz
class Leader():
def __init__(self, ns, linear_velocity=LINEAR_VELOCITY, angular_velocity=ANGULAR_VELOCITY, frequency = FREQUENCY):
# total number of nodes/robots
self.num = len(VERTICES)
# leader's namespace
self.ns = ns
# namespace prefix
self.nsprefix = ns.split('_')[0]
# all robots' namespaces
self.nss = []
for i in range(self.num):
self.nss.append(self.nsprefix+ '_' + str(i) + '/')
# all robots' poses as a dictionary, key is robot's namespace, value is robot's [x, y, yaw]
self.poses = {}
# waypoints, a list of (x, y) coordinates
self.waypoints = []
# ternminals, a list of (x, y) coordinates
self.terminals = []
# communication graph
self.G = self.build_graph()
# state
self.state = "wait"
# number of task executed will be decremented once a task is sent and incremented once a task is done
self.taskexecuted = self.num
# subscribe to terminals topic
self._terminals_sub = rospy.Subscriber(DEFAULT_TERMINALS_TOPIC, Path, self._terminals_callback, queue_size=1)
# subscribe to taskdone topic
self._taskdone_subs = []
for ns in self.nss:
if ns != self.ns:
self._taskdone_subs.append(rospy.Subscriber(ns + DEFAULT_TASK_DONE_TOPIC, Bool, self._taskdone_callback, queue_size=1))
# set up publisher for initiate coodiantion messages
self._initiate_coordination_pub = rospy.Publisher(DEFAULT_INITIATE_COORDINATION_TOPIC, Bool, queue_size=1)
self._cmd_pub = rospy.Publisher(DEFAULT_CMD_VEL_TOPIC, Twist, queue_size=1)
# set up registration service
self._registration_srv = rospy.Service('/registration', Registration, self._process_request)
# set up tf listener
self._tf_listener = tf.TransformListener()
# set up task action server
self._send_goal_acs = {}
for ns in self.nss:
if ns != self.ns:
self._send_goal_acs[ns] = actionlib.SimpleActionClient(ns + DEFAULT_ACTION_TOPIC , TaskAction)
# other variables
self.linear_velocity = linear_velocity
self.angular_velocity = angular_velocity
self.frequency = frequency
def _taskdone_callback(self, msg):
"""process taskdone message"""
self.taskexecuted += 1
# when actions are done by all servers, clear waypoints and terminals and wait for new terminals message
if self.taskexecuted == self.num:
self.terminals = []
self.waypoints = []
self.state = "wait"
def action_clients(self):
"""get and send goal to each action server
decrement self.taskexecuted once a task is sent"""
# create the Task action client for each Task action server
# waits until each action server has started up
for ns in self._send_goal_acs:
self._send_goal_acs[ns].wait_for_server()
# calculates the transformations that need to be performed by each action server, expressed as poses
allocations = self.allocate_waypoints()
# creates and sends the goal to each action server
for ns in allocations:
if ns != self.ns:
goal = TaskGoal()
goal.pose = allocations[ns]
self._send_goal_acs[ns].send_goal(goal, done_cb=self.callback_done)
self.taskexecuted -= 1
# perform transformation according to the goal sent to the leader
if self.ns in allocations:
self.do_transformation(allocations[self.ns])
self.taskexecuted -= 1
def callback_done(self, state, result):
"""callback function for self.action_client.send_goal"""
if result.success != 1:
rospy.logerr("Task not completed")
def _listener(self):
"""tf listener: get the latest pose of each robot relative to the world frame"""
for i in range(len(self.nss)):
trans, quaternion = self._tf_listener.lookupTransform('world', self.nss[i][1:] + 'base_link', rospy.Time(0))
euler = tf.transformations.euler_from_quaternion([quaternion[0], quaternion[1], quaternion[2], quaternion[3]])
self.poses[self.nss[i]] = trans[:2] + [euler[2]]
def _process_request(self, request):
"""process registration request"""
if request.onezero == 1:
return RegistrationResponse(1)
else:
return RegistrationResponse(0)
def allocate_waypoints(self):
"""returns a dictionary of poses that will guide the transformation of each obot"""
# get the latest poses of all robots
self._listener()
# key: namespace, value: pose
allocations = {}
# list of assigned namespaces
assignednss = []
#list of assigned waypoint indices
assignedwaypoints = []
# assign a waypoint to a robot based on their distance
for i in range(len(self.waypoints)):
min_dist_ns, min_dist_waypoint = self.min_distance_pair(assignednss, assignedwaypoints)
assignednss.append(min_dist_ns)
assignedwaypoints.append(min_dist_waypoint)
pose = self.calculate_transformation(self.poses[min_dist_ns], self.waypoints[min_dist_waypoint])
allocations[min_dist_ns] = pose
return allocations
def min_distance_pair(self, assignednss, assignedwaypoints):
"""helper function for self.allocate_waypoints
calculate the pair of robot and waypoint that have the minimum distance to each other,
excluding assigned robots and waypoints
Args:
assignednss, list of assigned namespaces
assignedwaypoints, list of assigned waypoint indices
Returns: robot's namespace and waypoint index """
min_dist = float("inf")
min_dist_ns = None
min_dist_waypoint = None
for i in range(len(self.waypoints)):
if i not in assignedwaypoints:
for ns in self.poses:
if ns not in assignednss:
dist = np.linalg.norm(abs(np.array(self.waypoints[i]) - np.array(self.poses[ns][:2])))
# print(ns, self.poses[ns][:2], self.waypoints[i], dist)
if (dist < min_dist) :
min_dist = dist
min_dist_ns = ns
min_dist_waypoint = i
rospy.loginfo(min_dist_ns + "is assigned to" + str(self.waypoints[min_dist_waypoint]))
return min_dist_ns, min_dist_waypoint
def calculate_transformation(self, start, end):
"""calculate the transformation from starting position to ending position
Returns: transformation represented as a Pose message, in which orientation
guides the rotation, and position.x tells the euclidean distance to travel
after the rotation"""
dist_x = end[0] - start[0]
dist_y = end[1] - start[1]
dist = math.sqrt(dist_x**2 + dist_y**2)
new_angle = math.atan2(dist_y, dist_x)
turn_angle = new_angle - start[2]
# convert to minimal turn angle
if abs(turn_angle) > math.pi:
if turn_angle > 0:
turn_angle = turn_angle - 2 * math.pi
if turn_angle < 0:
turn_angle = turn_angle + 2 * math.pi
# create pose message
pose = Pose()
pose.position.x, pose.position.y, pose.position.z = dist, 0, 0
quaternion = tf.transformations.quaternion_from_euler(0, 0, turn_angle)
pose.orientation.x, pose.orientation.y, pose.orientation.z, pose.orientation.w = quaternion[0], quaternion[1], quaternion[2], quaternion[3]
return pose
def _terminals_callback(self, msg):
"""extract terminals from the received Path message and
compute all waypoints that require robots to ensure connection"""
for posestamped in msg.posesŽ
self.terminals.append((posestamped.pose.position.x, posestamped.pose.position.y))
rospy.loginfo("terminals received: " + str(self.terminals))
self.waypoints = list(steiner_tree(self.G, self.terminals, weight = 'distance'))
rospy.loginfo("waypoints: " + str(self.waypoints))
def initiate_coordination(self):
"""initiate coordination by sending /init_co messages"""
# create and publish init_co message
if self.terminals:
initiation_msg = Bool()
initiation_msg.data = True
self._initiate_coordination_pub.publish(initiation_msg)
self.state = "action"
def do_transformation(self, goal):
""""transform the leader according to the goal"""
quaternion = goal.orientation
euler = tf.transformations.euler_from_quaternion([quaternion.x, quaternion.y, quaternion.z, quaternion.w])
rotation_angle = euler[2]
if rotation_angle < 0:
self.angular_velocity = - self.angular_velocity
# compute rotation durationand move duration
self.rotate_duration = abs(rotation_angle / self.angular_velocity)
self.move_duration = goal.position.x /self.linear_velocity
# start rotating
self.state = "rotate"
def distance(self, pos1, pos2):
"""return the distance between two positions"""
squared_distance = (pos1[0] - pos2[0])**2 + (pos1[1] - pos2[1])**2
return math.sqrt(squared_distance)
def build_graph(self):
"""build the communication graph given the vertices and the minimum
distance required to add an edge between two nodes"""
G = nx.Graph()
for i in range(len(VERTICES)):
for j in range(i+1, len(VERTICES)):
d = self.distance(VERTICES[i], VERTICES[j])
if d <= MIN_D:
G.add_edge(VERTICES[i], VERTICES[j], distance = d)
return G
def stop(self):
"""Stop the robot."""
twist_msg = Twist()
self._cmd_pub.publish(twist_msg)
def rotate(self):
if self.rotate_duration > 0:
twist_msg = Twist()
twist_msg.angular.z = self.angular_velocity
self._cmd_pub.publish(twist_msg)
self.rotate_duration -= 1/float(self.frequency)
else:
self.stop()
self.state = "move"
def move(self):
if self.move_duration > 0:
twist_msg = Twist()
twist_msg.linear.x = self.linear_velocity
self._cmd_pub.publish(twist_msg)
self.move_duration -= 1/float(self.frequency)
else:
self.stop()
self.state = "stop"
self.taskexecuted += 1
def main():
"""Main function."""
# initialization of node
rospy.init_node("leader")
rospy.sleep(2)
# get this robot's namespace
ns = rospy.get_namespace()
# initialization of the class for the leader
leader = Leader(ns)
rospy.loginfo(ns + "leader initiated")
# if interrupted, send a stop command.
rospy.on_shutdown(leader.stop)
rate = rospy.Rate(FREQUENCY)
while not rospy.is_shutdown():
try:
if leader.state == "rotate":
leader.rotate()
if leader.state == "move":
leader.move()
if leader.state == "wait":
print("waiting for new terminals")
leader.state = "coordination"
if leader.state == "coordination" :
leader.initiate_coordination()
if leader.state == "action":
leader.action_clients()
except rospy.ROSInterruptException:
rospy.logerr("ROS node interrupted.")
rate.sleep()
if __name__ == "__main__":
"""Run the main function."""
main()
| 54bb82a0971e391d1f070667d2a17513184b9204 | [
"Markdown",
"Python",
"CMake",
"Shell"
]
| 7 | Shell | zitongwu/Connectivity_Maintenance_for_Multirobot_System | 1021e83ede9bb7ffe701b9c6a4a200f2d5daa2b2 | b7a9aeebeb4b1b02f42b6daa9a3e719058a77d8b |
refs/heads/master | <repo_name>jereln/deck_of_cards<file_sep>/lib/deck.rb
class Deck
attr_accessor :cards
def initialize
@cards = []
suits = %w[hearts diamonds clubs spades]
rank = %w[2 3 4 5 6 7 8 9 10 J Q K A]
suits.each do |suit|
rank.each do |rank|
puts "#{suit}, #{rank}"
@cards << Card.new(suit, rank)
end
end
end
end
class Card
attr_accessor :suit, :rank
def initialize(suit, rank)
@suit = suit
@rank = rank
end
end
<file_sep>/spec/card_spec.rb
require 'minitest/autorun'
require 'minitest/test'
require 'deck'
describe 'card' do
card = Card.new('hearts', 4)
it 'has a suit' do
card.suit.must_equal 'hearts'
end
it 'has a rank' do
card.rank.must_equal 4
end
end
<file_sep>/spec/deck_spec.rb
require 'minitest/autorun'
require 'minitest/test'
require 'deck'
describe 'a deck of cards' do
deck = Deck.new
it 'has 52 cards' do
deck.cards.length.must_equal 52
end
it 'does not have two identical cards' do
deck.cards.uniq!.must_be_nil
end
it 'has all four suits' do
assert_includes deck.cards.to_s, 'hearts'
assert_includes deck.cards.to_s, 'diamonds'
assert_includes deck.cards.to_s, 'clubs'
assert_includes deck.cards.to_s, 'spades'
end
end
<file_sep>/README.md
#Deck of Cards
##Approach
I started off figuring out what tests i needed for both deck and card. Once I finally figured out how to actually write the tests, I started defining my classes. I am a little rusty on my Ruby so this took a while and a lot of help from the Brook, Marco, and Kayla. Once all my tests passed, I did a little refactoring and tried adding a few more tests.
##Resources
http://mattsears.com/articles/2011/12/10/minitest-quick-reference
http://ruby-doc.org/core-2.1.1/
##Collaborators
<NAME>
<NAME>
<NAME>
| bf30e6731678c12d5696be6d768bcf1a27b73ed3 | [
"Markdown",
"Ruby"
]
| 4 | Ruby | jereln/deck_of_cards | 7f60e9002ff01e7a24d67d6989256428b0e1f81b | 678d5347ef220720efbab6ac74c7b399460e1bcd |
refs/heads/master | <file_sep>package guestbook;
public class RateLimiter {
public boolean isRateLimited(String ipAddress) {
return false;
}
}
<file_sep>package guestbook;
public class GuestbookService {
private SpamChecker spamChecker;
private RateLimiter rateLimiter;
private JpaRepository jpaRepository;
public GuestbookService() {
this.spamChecker = new SpamChecker();
this.rateLimiter = new RateLimiter();
this.jpaRepository = new JpaRepository();
}
public void create(GuestbookEntry guestbookEntry, String ipAddress){
if (spamChecker.isSpam(guestbookEntry.getContent())) {
throw new RuntimeException("Spam words in content");
}
if (rateLimiter.isRateLimited(ipAddress)) {
throw new RuntimeException("Ip Address is rate limited");
}
jpaRepository.save(guestbookEntry);
}
}
<file_sep>package guestbook;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
public class SpamChecker {
private Set<String> spamWords;
public SpamChecker() {
this.spamWords = new HashSet<>();
this.spamWords.addAll(Arrays.asList("acne", "adult", ""));
}
public boolean isSpam(String content) {
Set<String> words = new HashSet<>(Arrays.asList(content.split("\\s")));
if (!Collections.disjoint(spamWords, words)) {
return true;
}
return false;
}
}
| eece5b9660d924f8826efdf2820bd663614d68f9 | [
"Java"
]
| 3 | Java | fs-101/guestbook | 4275a66d5a76a6d61fd2c26a6def0296c1a848e3 | 6a118140d307e24c86624cb512069fc1e421e280 |
refs/heads/master | <repo_name>traveaston/basherk<file_sep>/pre-basherk.sh
# pre-basherk
# Things to define before basherk runs
# fix for mail before anything else
[[ $HOSTNAME != *"mail"* ]] && shopt -s nocasematch
<file_sep>/README.md
# basherk
[](https://github.com/traveaston/basherk/actions/workflows/action.yaml)
(Pronounced sort of how bashrc sounds phonetically)
Handy aliases and functions to make your life in the terminal easier. Essentially:

### Installing
The easiest way to start using basherk is to download and source the file
`curl https://raw.githubusercontent.com/traveaston/basherk/master/basherk.sh -o ~/.basherk && . ~/.basherk`
To source it each session automatically
`echo -e "\n. ~/.basherk # source basherk\n" >> ~/.bashrc`
To have root source basherk from the same file
`sudo echo -e "\n. $(_realpath ~/.basherk) # source basherk\n" >> /root/.bashrc`
___
Additionally, you can clone the repo for contributing, custom aliases, etc.
Clone the repo to wherever you would like to store it
`git clone https://github.com/traveaston/basherk.git`
Source it this session
`source basherk/basherk.sh`
Then either symlink basherk into your home folder and source it from there
```
ln -s "$(_realpath basherk/basherk.sh)" ~/.basherk
echo -e "\n. ~/.basherk # source basherk\n" >> ~/.bashrc
```
Or source it straight from the repo
`echo -e "\n. \"$(_realpath basherk/basherk.sh)\" # source basherk\n" >> ~/.bashrc`
### Updating
If you aren't using the repo, `basherk --update` or `ubash` will download the latest revision from the master branch and re-source itself.
## Contributing
* Lint basherk with shellcheck `shellcheck -s bash basherk.sh`
* 4 space indentation
* Double quotes
* Aliases use single quotes
* Regexes use single quotes
* Rare cases where single quotes make more sense
* Don't quote LHS of comparison (eg. `[[ $foo == "$bar" ]]`), except:
* Subshells should be quoted for readability `[[ "$(cat bar.log)" == "foo" ]]`
* Variables concatentated with strings should be quoted
* Quote RHS of comparison (eg. `[[ $foo == "$(cat bar.log)" ]]`), except:
* Regex or pattern (and vars containing) shouldn't be quoted `[[ $os =~ (mac|unix) ]]`
* String with wildcards shouldn't be quoted `[[ $dir == *.git* ]]`
* String with wildcards and spaces should be half-quoted `[[ $dir == *"git bar"* ]]`
* Integers shouldn't be quoted
* Variables for if switches (eg. `[[ -z $foo ]]`) shouldn't be quoted, except:
* Variables concatentated with strings should be quoted
* Variable assignment should be quoted (`foo="bar"`), except:
* When assigning subshell output, don't quote `foo=$(curl ifconfig.me)`
* When assigning subshell + strings, quote `foo="user@$(curl ifconfig.me)"`
* When assigning an integer, don't quote `bar=256`
* When assigning a boolean, don't quote `bar=false`
* Simple regexes can be inline if it is clean but more complex expressions should be passed by variable
* Also when containing special characters, especially `space`, should be passed by variable
* Headings
* Main and subheadings are prepended with 2 lines
* Main code blocks are surrounded with Start/End headings
* Main headings are surrounded with 20x#
* Subheadings are prepended with 10x#
* Subheadings with no blank lines before next subheading are placed immediately above the code (see `Git diff aliases`)
* Subheadings containing comments or blank lines before next subheading contain an additional newline with a single # (see `Redefine builtin commands`)
* Aliases, functions, etc, under headings are sorted alphabetically most of the time, but not always.
## Authors
* **<NAME>** - *Initial work & maintenance*
See also the list of [contributors](https://github.com/traveaston/basherk/graphs/contributors) who participated in this project.
## License
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details
## Acknowledgments
* <NAME> http://stevelosh.com/blog/2009/03/candy-colored-terminal/
* more credits peppered throughout [basherk.sh](basherk.sh)
<file_sep>/post-basherk.sh
# post-basherk
# Things that depend on definitions inside basherk to work
<file_sep>/basherk.sh
# shellcheck shell=bash
# shellcheck disable=SC1090 # ignore non-constant source location warning
# shellcheck disable=SC1091 # ignore sourced files
# shellcheck disable=SC2119 # not a regular script, function's $1 is never script's $1
# shellcheck disable=SC2120 # not a regular script, functions define arguments we won't use here
#
# basherk
# .bashrc replacement
#################### Start basherk setup code ####################
# If not running interactively, don't do anything
[[ -z $PS1 ]] && return
# if version is already set, we are re-sourcing basherk
[[ -n $basherk_ver ]] && basherk_re_sourcing=true
basherk_ver=135
basherk_date="12 May 2021"
basherk_src="${BASH_SOURCE[0]}"
basherk_dir=$(dirname "$basherk_src")
basherk_url="https://raw.githubusercontent.com/traveaston/basherk/master/basherk.sh"
# colours, credit: http://stevelosh.com/blog/2009/03/candy-colored-terminal/
D=$'\e[37;49m'
BLUE=$'\e[34;49m'
CYAN=$'\e[36;49m'
GREEN=$'\e[32;49m'
ORANGE=$'\e[33;49m'
PINK=$'\e[35;49m'
RED=$'\e[31;49m'
# show basherk version (including time since modified if bleeding-edge) on execution
if [[ $basherk_ver == *bleeding* ]]; then
if [[ "$(uname)" == "Darwin" ]]; then
echo "basherk $basherk_ver (modified $(stat -f "%Sm" -t "%a %e %b %r" "$basherk_src")," $(( $(date +%s) - $(stat -f%c "$basherk_src") )) "seconds ago)"
else
echo "basherk $basherk_ver (modified $(date "+%a %e %b %r" -r "$basherk_src")," $(( $(date +%s) - $(date +%s -r "$basherk_src") )) "seconds ago)"
fi
else
echo "basherk $basherk_ver ($basherk_date)"
fi
alias basherk='. "$basherk_src"'
[[ $1 =~ -(v|-version) ]] && return
[[ $1 == "--update" ]] && ubash && return
# this is not idempotent
[[ $1 == "--install" ]] && {
# add preceeding newline if bashrc already exists
[[ -f ~/.bashrc ]] && basherk_install_string="\n"
basherk_install_string+=". $basherk_src # source basherk\n"
echo -e "$basherk_install_string" >> ~/.bashrc
return
}
# source pre-basherk definitions
[[ -f "$basherk_dir/pre-basherk.sh" ]] && . "$basherk_dir/pre-basherk.sh"
# source custom basherk user definitions
[[ -f "$basherk_dir/custom-basherk.sh" ]] && . "$basherk_dir/custom-basherk.sh"
#################### End basherk setup code ####################
#################### History / terminal options ####################
export HISTCONTROL=ignoredups:erasedups # no duplicate entries
export HISTSIZE=100000 # 100k lines of history
export HISTFILESIZE=100000 # 100kb max history size
export HISTIGNORE=" *:* --version:changed*:clear:countsize:df:f:find:gd:gds:gl:gla:graph:graphall:gs:h:h *:history:la:ls:mc:open .:ps:pwd:staged*:stashes:suho:test:time *:ubash:ubashall:gitinfo*"
export HISTTIMEFORMAT="+%Y-%m-%d.%H:%M:%S "
shopt -s histappend # append to history, don't overwrite
shopt -s checkwinsize # check the window size after each command
shopt -s cdspell # autocorrect for cd
# Check for interactive shell (to avoid problems with scp/rsync)
# and disable XON/XOFF to enable Ctrl-s (forward search) in bash reverse search
[[ $- == *i* ]] && stty -ixon
#################### Aliases ####################
os=$(uname)
[[ $os == "Darwin" ]] && os="macOS"
[[ $HOSTNAME =~ (Zen|Obsidian) ]] && os="Windows"
[[ $BASH == *termux* ]] && os="Android"
########## Redefine builtin commands (interactive/verbose for file operations)
#
alias cp='cp -iv'
alias df='df -h' # human readable
alias mkdir='mkdir -pv' # Make parent directories as needed and be verbose
alias mv='mv -iv'
alias sudo='sudo ' # pass aliases through sudo https://serverfault.com/a/178956
# shellcheck disable=SC2032 # ignore warning that other functions in this script won't use this alias
alias rm='rm -iv'
########## General aliases
alias back='cd "$OLDPWD"'
alias fuck='sudo $(history -p \!\!)' # Redo last command as sudo
alias gitr='cd ~/dev/repos' # open main git repo directory
alias lessf='less +F'
alias now='date +"%c"'
alias openports='nmap -sT -O localhost'
# shellcheck disable=SC2262 # we don't use this in the same parsing unit
alias pwf='echo "${PWD##*/}"' # print working folder
alias weigh='du -sch'
########## Git aliases
alias branches='git branch -a'
alias discard='git checkout --'
alias discardpatch='git checkout -p'
alias gb='git branch -a'
alias gitback='git checkout -'
alias gitsquashlast='git rebase -i HEAD~2'
alias gnb='git checkout -b'
alias gs='git status'
alias localbranches='git branch'
alias stage='git add -p'
alias stashcontents='git stash show -p'
alias stashes='git stash list'
alias unstage='git reset -q HEAD --'
########## Git diff aliases
alias changed='git diff'
alias changedchars='git diff --color-words=.'
alias changedwords='git diff --color-words'
alias gd='git diff'
alias gdom='git diff origin/master'
alias staged='git diff --staged'
alias stagedchars='git diff --staged --color-words=.'
alias stagedwords='git diff --staged --color-words'
########## Git log aliases
alias gl='graph'
alias gla='graphall' # git 2.9.3 seems to truncate SHAs to 7, rather than 2.26.2's 9
alias graph='git log --graph -14 --format=format:"%Cgreen%h%Creset - %<(52,trunc)%s %C(bold blue)%<(14,trunc)%cr%Creset %C(yellow)%d"'
alias graphall='git log --graph -20 --format=format:"%Cgreen%h %Cblue<%an> %Creset%<(52,trunc)%s %C(bold blue)%<(14,trunc)%cr%Creset %C(yellow)%d" --branches --remotes --tags'
alias graphdates='git log --graph -20 --format=format:"%Cgreen%h %Cblue<%an> %Creset%<(52,trunc)%s %C(bold blue)%<(26,trunc)%ad%Creset %C(yellow)%d" --branches --remotes --tags'
alias latestcommits='git log --graph -20 --date-order --format=format:"%Cgreen%h %Cblue<%an> %Creset%<(52,trunc)%s %C(bold blue)%<(14,trunc)%cr%Creset %C(yellow)%d" --branches --remotes --tags'
alias limbs='git log --all --graph --decorate --oneline --simplify-by-decoration'
########## Git reminder aliases / instructions
alias gitdeleteremotebranch='echo "to delete remote branch, ${PINK}git push origin :<branchName>"'
alias gitprune='echo "git remote prune origin" will automatically prune all branches that no longer exist'
alias gitrebase='echo -e "usage: git checkout ${GREEN}develop${D}\n git rebase ${PINK}master${D}\n\nRebase ${GREEN}branch${D} onto ${PINK}base${D}, which can be any kind of commit reference:\nan ID, branch name, tag or relative reference to HEAD."'
alias gitundocommit='echo "git reset --soft HEAD^"'
alias nevermind='echo "You will have to ${RED}git reset --hard HEAD && git clean -d -f${D} but it removes untracked things like vendor"'
#################### Conditional aliases / functions ####################
function exists() { # hoisted
[[ -z $1 ]] || [[ $1 == "--help" ]] && {
echo "Check if a command exists"
echo "Usage:"
echo " if exists apt-get; then apt-get update; fi"
return
}
# return false if git is apple's xcode wrapper
[[ "$1" == "git" ]] && grep -q xcode "$(command which git 2>/dev/null)" 2>/dev/null && return 1
command -v "$1" &>/dev/null
}
if ! exists aspell; then alias aspell='hunspell'; fi
if ! exists tailf; then alias tailf='tail -f'; fi
if exists ip; then
alias ipas='ip addr show | hlp ".*inet [0-9.]*"'
else
alias ipas='ifconfig | hlp ".*inet [0-9.]*"'
fi
if echo x | grep --color=auto x &>/dev/null; then
alias grep='grep --color=auto'
fi
########## macOS OR Linux/WSL commands
if [[ $os == "macOS" ]]; then
alias _stat_inode='stat -f%i'
alias vwmod='stat -f "%OLp"'
########## macOS only commands
alias fcache='sudo dscacheutil -flushcache' # flush dns
# When Time Mahine is backing up extremely slowly, it's usually due to throttling
alias tmnothrottle='sudo sysctl debug.lowpri_throttle_enabled=0'
alias tmthrottle='sudo sysctl debug.lowpri_throttle_enabled=1'
else
alias _stat_inode='stat -c%i'
alias vwmod='stat --format "%a"'
fi
########## Aliasing functions
#
# setup aliases for ls, la, l
function alias_ls() {
# set appropriate ls color flag
if command ls --color -d . &>/dev/null; then
alias ls='ls --color=auto'
elif command ls -G -d . &>/dev/null; then
# FreeBSD/FreeNAS/legacy macOS versions
alias ls='ls -G'
fi
alias la='ls -Ahl'
alias ll='ls -ahl' # don't hide . and .. as above does
# set appropriate l alias (hide owner/group if possible)
if command ls -dgo . &>/dev/null; then
alias l='la -go'
else
# busybox ls
alias l='la -g'
fi
}
alias_ls
unset alias_ls # avoid pollution
# alias realpath for consistency
function alias_realpath() {
local utility="realpath"
local exists_flag="-e"
# overwrite default if non-existent
if ! exists realpath; then
utility="readlink"
fi
# unset flag if not accepted (use known path for compatibility check)
if [[ "$($utility $exists_flag "/dev" 2>&1)" != "/dev" ]]; then
exists_flag=""
fi
# if no combinations work, it's not installed so define our own function
# shellcheck disable=SC2086 # flag variable needs to be unquoted
if [[ "$($utility $exists_flag "/dev" 2>&1)" != "/dev" ]]; then
function _basherk_realpath() {
# https://stackoverflow.com/a/18443300
local OURPWD LINK REALPATH
OURPWD=$PWD
command cd "$(dirname "$1")" || return $?
LINK=$(readlink "$(basename "$1")")
while [ "$LINK" ]; do
command cd "$(dirname "$LINK")" || return $?
LINK=$(readlink "$(basename "$1")")
done
REALPATH="$PWD/$(basename "$1")"
command cd "$OURPWD" || return $?
echo "$REALPATH"
}
utility="_basherk_realpath"
fi
# shellcheck disable=SC2139 # unconventionally use double quotes to expand variables
alias _realpath="$utility $exists_flag"
}
alias_realpath
unset alias_realpath # avoid pollution
########## Other hoisted functions
#
# credit: https://stackoverflow.com/a/17841619
# this solution avoids appending/prepending delimiter to final string
function array_join() {
[[ -z $1 ]] || [[ $1 == "--help" ]] && {
echo "Join array elements with a (multi-character) delimiter"
echo "Usage:"
echo " array_join [--help]"
echo " array_join delimiter \${array[@]}"
return
}
# capture delimiter in variable and remove from arguments array
local delimiter="$1"
shift
# echo first array element to avoid prepending it with delimiter
echo -n "$1"
shift
# prepend each element with delimiter
printf "%s" "${@/#/$delimiter}"
}
# usage: if in_array "foo" "${bar[@]}"; then echo "array contains element"; fi
function in_array() {
[[ -z $1 ]] || [[ $1 == "--help" ]] && {
echo "Search array for matching element"
echo "Usage:"
echo " in_array [--help]"
echo " in_array element \${array[@]}"
return
}
local positional
# capture element/needle in variable and remove from arguments array
local element="$1"
shift
# loop positional parameters (array) and return true if present
for positional; do
[[ $positional == "$element" ]] && return 0
done
# return false
return 1
}
function define_wsl_commands() {
# open files directly from terminal using Windows' default program, like macOS
alias open='cmd.exe /C start'
# cdwsl "C:\Program Files" -> "/mnt/c/Program Files"
function cdwsl() {
cd "$(wslpath "$@")" || return $?
}
}
if exists wslpath; then
define_wsl_commands
fi
unset define_wsl_commands # avoid pollution
# hoisted for use in cd()
function iTermSH() {
[[ $TERM_PROGRAM != *iTerm* ]] && return
# Help iTerm2 Semantic History by echoing current dir
d=$'\e]1337;CurrentDir='
d+=$(pwd)
d+=$'\007'
echo "$d"
}
#################### Main functions ####################
function cd() {
local new_dir="$1"
# go home if directory not specified
[[ -z $new_dir ]] && new_dir=~
# escape cd to avoid calling itself or other alias, return exit status on failure
command cd "$new_dir" || return $?
# echo dir for iTerm2 Semantic History immediately after cd
iTermSH
# print working directory, and list contents (without owner/group)
pwd
l
# run gitinfo if .git directory exists
[[ -d .git ]] && gitinfo
}
function cdfile() {
# shellcheck disable=SC2164 # don't worry about cd failure
cd "$(dirname "$1")"
}
# check256 $file [$checksum]
# show file checksum OR compare against expected checksum
function check256() {
local actual expect file sha256
if exists sha256sum; then
sha256="sha256sum"
elif exists shasum; then
sha256="shasum -a 256"
fi
file="$1"
expect="$2"
actual=$($sha256 "$file" | awk '{print $1}')
if [[ -z $expect ]]; then
echo "$actual"
else
if [[ $expect == "$actual" ]]; then
echo "${GREEN}sha256 matches${D}"
else
echo "${RED}sha256 check failed${D}"
fi
fi
}
# remove annoying synology, windows, macos files
function cleanup_files() {
# shellcheck disable=SC2033 # ignore warning that xargs rm in this script won't use my rm function
find . \( -iname "@eadir" -o -iname "thumbs.db" -o -iname ".ds_store" \) -print0 | xargs -0 rm -ivrf
}
# wrapper for git commit
# counts characters, checks spelling and asks to commit
# requires aspell/hunspell
function commit() {
local len
local message="$1"
len=$(length -a "$message")
[[ $len -gt 50 ]] && {
echo "${RED}$len characters long${D}"
echo "truncated to 50: '${BLUE}${message:0:50}${D}'"
return
}
[[ $len == 0 ]] && {
# commit with editor and if command succeeds, check spelling
git commit -e && check_commit
return
}
echo "${GREEN}$len characters long${D}"
echo
echo "${BLUE}Spell check:${D}"
echo "$message" | aspell -a
echo "git commit -m ${PINK}\"$message\"${D}"
read -r -p "Commit using this message? [y/N] " commit
[[ $commit == "y" ]] && {
git commit -m "$message"
} || echo "Aborted"
}
function check_commit() {
local commit="$1"
local message
local linenum=0 summary=0 longestline=0
# shellcheck disable=SC2086 # $commit needs to be unquoted to implicitly refer
# to the last commit, if no argument is passed to check_commit
message=$(git log $commit -1 --pretty=%B)
while read -r line; do
if [[ $linenum -eq 0 ]]; then
summary=${#line}
else
[[ ${#line} -gt $longestline ]] && longestline=${#line}
fi
((linenum++))
done <<< "$message"
if [[ $summary -gt 50 ]]; then
echo -n "Summary is ${RED}$summary characters long${D}"
else
echo -n "Summary is ${GREEN}$summary characters long${D}"
fi
if [[ $longestline -gt 72 ]]; then
echo -n ", and longest line in body is ${RED}$longestline characters long${D}"
else
# only echo body length if non-zero
[[ $longestline -ne 0 ]] && echo -n ", and longest line in body is ${GREEN}$longestline characters long${D}"
fi
# echo newlines to compensate for their omission above
echo -e "\n\n${PINK}$message${D}\n"
echo "$message" | aspell -a
echo "If necessary, amend commit with: ${BLUE}git commit --amend${D}"
}
# compare "string1" "string2"
function compare() {
[[ -z $1 ]] && echo "compare 2 strings" && return
[[ $1 == "$2" ]] && echo "${GREEN}2 strings match${D}" ||
echo "${RED}Strings don't match${D}"
}
# comparefiles $file1 $file2
function comparefiles() {
[[ $(_stat_inode "$1") == $(_stat_inode "$2") ]] && echo "${ORANGE}Paths point to the same file (matching inode)${D}"
check256 "$1" "$(check256 "$2")"
ls -ahl "$1"
ls -ahl "$2"
}
# cpmod $file1 $file2
# copy file mode / permissions from one file to another
# in other words set file2 permissions identical to file1
function cpmod() {
chmod "$(vwmod "$1")" "$2"
}
# custom find command to handle searching files, commits, file/commit contents, or PATH
function f() {
[[ -z $1 ]] || [[ $1 == "--help" ]] && {
echo "search files, commits, file/commit contents, or PATH"
echo "usage: f location search [sudo]"
echo
echo "locations:"
echo " folders ( / . /usr )"
echo " path (will systematically search each folder in \$PATH)"
echo " in (find in file contents)"
echo " commit (find a commit with message matching string)"
echo " patch (find a patch containing change matching string/regexp)"
echo " patchfull (find a patch containing change matching string/regexp, and show function context)"
echo
echo "f in string"
echo "f in 'string with spaces'"
echo "f in '\$pecial'"
return
}
local count debug hl matches path sudo tool
local location="$1"
local search="$2"
[[ $3 =~ -(d|-debug) ]] && debug=true || sudo="$3"
# escape all periods (regex wildcards), strip leading/trailing bash wildcards,
# and convert all other bash wildcards to regex
# ideally, we would also prepend a negative lookahead for / to ensure hlp
# only highlights matches in the basename, but macos grep doesn't support it
hl="$(sed -e 's/\./\\./g' -e 's/^*//' -e 's/*$//' -e 's/*/.*/g' <<< "$2")"
[[ $debug ]] && echo "${CYAN}highlighting with '$hl'${D}"
# prefer ripgrep, then silver surfer, then grep if neither are installed
if exists rg; then
tool="rg"
elif exists ag; then
tool="ag"
else
tool="grep"
fi
if [[ $location == "path" ]]; then
# search each folder in PATH with a max depth of 1
[[ -e $search ]] && echo "${ORANGE}Warning: if you specified a wildcard (*), bash interpreted it as globbing${D}"
# add wildcards to file search if the user hasn't specified one
[[ ! $search == *'*'* ]] && search="*$search*"
echo "searching dirs in ${CYAN}\$PATH${D} for files matching ${CYAN}$search${D} (case insensitive)"
local IFS=":"
for path in $PATH; do
# ignore non-existent directories in $PATH
[[ ! -d $path ]] && continue
[[ $debug ]] && echo "${CYAN}$sudo find \"$path\" -maxdepth 1 -iname \"$search\" | hlp -i \"$hl\"${D}"
$sudo find "$path" -maxdepth 1 -iname "$search" | hlp -i "$hl"
done
elif [[ $location == "in" ]]; then
# search file contents
if [[ $tool != "grep" ]]; then
echo "searching ${CYAN}$(pwf)/${D} for '${CYAN}$search${D}' (using $tool)"
[[ $debug ]] && echo "${CYAN}$tool -C 2 \"$search\"${D}"
$tool -C 2 "$search"
else
echo "searching ${CYAN}$(pwf)/${D} for '${CYAN}$search${D}' (using $tool, ignores: case, binaries, .git/, vendor/)"
[[ $debug ]] && {
echo "${CYAN}$tool --color=always -C 2 -Iinr \"$search\" . --exclude-dir=\".git\" --exclude-dir=\"vendor\"${D}"
echo "${CYAN}count=\$([ABOVE COMMAND] | tee /dev/tty | wc -l) matches${D}"
}
# force color=always as piping to tee breaks the auto detection
count=$($tool --color=always -C 2 -Iinr "$search" . --exclude-dir=".git" --exclude-dir="vendor" | tee /dev/tty | wc -l)
echo "$count matches"
fi
elif [[ $location == "commit" ]]; then
# find a commit with message matching string
echo "searching commits in ${CYAN}$(git_repo_name) repo${D} for messages matching ${CYAN}$search${D} (case insensitive)"
[[ $debug ]] && echo "${CYAN}graphall --all --grep=\"$search\" -i${D}"
graphall --all --grep="$search" -i
elif [[ $location == patch* ]]; then
# find a patch containing change matching string/regexp
echo "searching commits in ${CYAN}$(git_repo_name) repo${D} for patches matching ${CYAN}$search${D} (case sensitive)"
[[ $location == "patchfull" ]] && local context="--function-context"
[[ $debug ]] && {
echo "${CYAN}for commit in \$(git log --pretty=format:\"%h\" -G \"$search\"); do"
echo " git log -1 \"$commit\" --format=\"[...]\""
echo " git grep --color=always -n $context \"$search\" \"$commit\""
echo "done${D} (simplified)"
}
for commit in $(git log --pretty=format:"%h" -G "$search"); do
echo
git log -1 "$commit" --format="%Cgreen%h %Cblue<%an> %Creset%<(52,trunc)%s %C(bold blue)%<(20,trunc)%cr%Creset %C(yellow)%d"
# git grep the commit for the search, remove hash from each line as we echo it pretty above
# shellcheck disable=SC2086 # context/flag must be unquoted else it will eval to an empty positional argument
matches=$(git grep --color=always -n $context "$search" "$commit")
echo "${matches//$commit:/}"
done
# display tip for patchfull
[[ $location == "patch" ]] && echo -e "\n${GREEN}f ${*/patch/patchfull}${D} to show context (containing function)"
elif [[ -d $location ]]; then
# find files within a folder
[[ -e $search ]] && echo "${ORANGE}Warning: if you specified a wildcard (*), bash interpreted it as globbing${D}"
# add wildcards to file search if the user hasn't specified one
[[ ! $search == *'*'* ]] && search="*$search*"
echo "searching ${CYAN}$(command cd "$location" && pwd)${D} for files matching ${CYAN}$search${D} (case insensitive)"
[[ $debug ]] && echo "${CYAN}$sudo find \"$location\" -iname \"$search\" | sed -e 's/^\.\///' | hlp -i \"$hl\"${D}"
# capture find errors in global var basherk_f_errors
# https://stackoverflow.com/a/56577569
{
basherk_f_errors="$( {
# find files matching case-ins. search, strip leading ./ and highlight
$sudo find "$location" -iname "$search" | sed -e 's/^\.\///' | hlp -i "$hl"
} 2>&1 1>&3 3>&- )"
} 3>&1
# tell user if there are hidden errors
[[ -n $basherk_f_errors ]] && \
echo "${CYAN}$(echo "$basherk_f_errors" | wc -l | awk '{print $1}')${D} find errors hidden (${CYAN}echo \"\$basherk_f_errors\"${D})"
elif [[ -f $location ]]; then
# find a string within a single file
echo "searching ${CYAN}$location${D} contents for '${CYAN}$search${D}' (using $tool)"
[[ $debug ]] && echo "${CYAN}$tool \"$search\" \"$location\"${D}"
$tool "$search" "$location"
fi
}
function get_repo_url() {
local url
url=$(git remote get-url origin)
# reformat url from ssh to https if necessary
[[ $url != http* ]] && url=$(echo "$url" | perl -pe 's/:/\//g;' -e 's/^git@/https:\/\//i;' -e 's/\.git$//i;')
echo "$url"
}
function gitinfo() {
local repourl
local stashcount
local unset_variables=()
[[ -z "$(git config user.name)" ]] && unset_variables+=("name")
[[ -z "$(git config user.email)" ]] && unset_variables+=("email")
# show 10 latest commits across all branches
graphall -10
# show total number of commits
totalcommits
repourl=$(get_repo_url)
if [[ -n "$repourl" ]]; then
echo "Repo URL: ${GREEN}$repourl${D}"
fi
if [[ ${#unset_variables[@]} -ne 0 ]]; then
echo "Unset git parameters: ${PINK}$(array_join "," "${unset_variables[@]}")${D}"
fi
gitstats
stashcount=$(stashes | wc -l | tr -d ' ')
[[ $stashcount != 0 ]] && echo -e "\nYou have ${CYAN}$stashcount${D} stashes"
echo
git status
}
function gitstats() {
# variables are titlecased to support bash version <4.0 lacking case manipulation
# shellcheck disable=SC2034 # dynamic variables
local Changed='git diff' Staged='git diff --staged'
for command in Staged Changed; do
if [[ -n "$(${!command} --stat)" ]]; then
echo
echo "$command:"
# run command again instead of capturing output above to preserve colour and stat output width
${!command} --stat
fi
done
}
function h() {
[[ -z $1 ]] && history && return
history | grep "$@"
}
# _have and have are required by some bash_completion scripts
if ! exists _have; then
# This function checks whether we have a given program on the system.
_have() {
PATH=$PATH:/usr/sbin:/sbin:/usr/local/sbin type "$1" &>/dev/null
}
fi
if ! exists have; then
# Backwards compatibility redirect to _have
have() {
unset -v have
# shellcheck disable=SC2034 # ignore "have appears unused" this is for compatibility
_have "$1" && have=yes
}
fi
# Highlight Pattern
# Works like grep but shows all lines
function hlp() {
local arg
local flags
local regex
if [[ -z $1 ]] || [[ $1 == "--help" ]]; then
echo "hlp - highlight pattern:"
echo " highlight a string or regex pattern from stdin"
echo " see grep for more options"
echo
echo "usage: <command> | hlp [options...] [pattern]"
echo " options:"
echo " -i case-insensitive matching"
echo
echo " patterns:"
echo " foo bar match either 'foo' or 'bar'"
echo " 'foo bar' match 'foo bar'"
echo " '\\\$foo bar' match '\$foo bar'"
echo " '[0-9]{1,3}' match 000 through 999"
return
elif [[ $1 == "-i" ]]; then
shift
flags="-iE"
else
flags="-E"
fi
# always grep for $ (end of line) to show all lines, by highlighting the newline character
regex="$"
# concatenate arguments with logical OR
for arg in "$@"; do
regex+="|$arg"
done
grep $flags "$regex"
}
function ipdrop() {
iptables -A INPUT -s "$1" -j DROP
}
function ipscan() {
[[ $1 == "--help" ]] && {
echo "Scan IP address or subnet with sudo passthrough for ICMP"
echo "Usage:"
echo " ipscan Scan current subnet based on local IP"
echo " ipscan [ip] Scan IP address e.g. ipscan 192.168.25.50"
echo " ipscan [ip/netmask] Scan IP with netmask e.g. ipscan 192.168.25.50/28"
echo " ipscan [subnet] Scan subnet e.g. ipscan 25"
echo " ipscan [addr] [sudo] Scan address (IP or subnet) using sudo (ICMP rather than TCP pingscan)"
return
}
local ip="$1"
local sudo="$2"
# allow scanning local subnet with sudo without explitly passing ip
[[ $ip == "sudo" ]] && unset ip && sudo="sudo "
# by appending space to $sudo, we avoid displaying ` foo` as the executed command when sudo is unset
[[ -z $ip ]] && {
# scan subnet using local ip address with /24 subnet mask
ip="$(ifconfig | sed -En 's/127.0.0.1//; s/.*inet (addr:)?(([0-9]*\.){3}[0-9]*).*/\2/p;' | head -1)/24"
}
# if only subnet was given, build a complete address
local re='^[0-9]{1,3}$'
[[ $ip =~ $re ]] && ip="192.168.$ip.1/24"
echo "${sudo}scanning ${CYAN}$ip${D}"
# shellcheck disable=SC2086 # sudo needs to be unquoted
${sudo}nmap -sn -PE "$ip"
}
function lastmod() {
if [[ $os == "macOS" ]]; then
echo "Last modified" $(( $(date +%s) - $(stat -f%c "$1") )) "seconds ago"
else
echo "Last modified" $(( $(date +%s) - $(date +%s -r "$1") )) "seconds ago"
fi
}
function length() {
[[ -z $1 ]] || [[ $1 == "--help" ]] && {
echo "Usage:"
echo " length \"string\" Display the length of a given string (character count)"
echo " length -a \"string\" Show length of string only (int)"
return
}
# -a: just return string length
[[ $1 == "-a" ]] && echo "${#2}" && return
echo "string \"$1\" is ${CYAN}${#1}${D} characters long"
}
function listening() {
[[ -z $1 ]] || [[ $1 == "--help" ]] && {
echo "Find port or process in list of listening ports"
echo "Usage:"
echo " listening [--help] Show this screen"
echo " listening $ Show all ports/process (grep regex for newline char)"
echo " listening p1 [p2, etc] Show ports/processes matching p#"
return
}
local -a args=( "$@" )
local pattern
# regex for int with 1-5 characters
local int_regex='^[0-9]{1,5}$'
for (( i = 0; i < ${#args[@]}; i++ )); do
# prepend colon to integer(port) to avoid searching PID, etc
[[ ${args[$i]} =~ $int_regex ]] && args[i]=":${args[$i]}"
done
pattern=$(array_join "|" "${args[@]}")
if [[ $os == "macOS" ]]; then
# show full info with ps and grep for ports (and COMMAND to show header)
sudo lsof -iTCP -sTCP:LISTEN -nP | grep -E "COMMAND|$pattern"
else
# show full info with ps and grep for ports (and UID to show header)
# -tu show both tcp and udp
# -l display listening sockets
# -p display PID/Program name
# -n don't resolve ports to names (80 => http, can't grep for port number)
netstat -tulpn | grep -E "Active|Proto|$pattern"
fi
}
# mkdir and cd into it
function mkcd() {
[[ -z $1 ]] && echo "make a directory and cd into it, must provide an argument" && return
mkdir -pv "$@"
# shellcheck disable=SC2164 # don't worry about cd failure
cd "$@"
}
# movelink (move & link)
# move a file to another location, and symbolic link it back to the original location
function mvln() {
[[ -z $1 ]] && echo "usage like native mv: mvln oldfile newfile" && return
[[ -z $2 ]] && echo "Error: Must specify new location" && return
local old_location="$1"
local new_location="$2"
if ! new_location=$(mv -iv "$old_location" "$new_location"); then
# return before symlinking if move fails
echo "failed: $new_location"
return
fi
# capture actual final move location from first line of output, and remove quotes
new_location=$(echo "$new_location" | head -n1 | tr -d "\"‘’'")
# remove everything before "-> "
new_location="${new_location##*-> }"
ln -s "$new_location" "$old_location"
# show results, and for directories, show name(with trailing slash) instead of contents
la -dp "$old_location"
la -dp "$new_location"
}
function notify() {
notification=$'\e]9;'
notification+="$1"
notification+=$'\007'
echo "$notification"
}
function osver() {
if [[ $os == "macOS" ]]; then
sw_vers
else
cat /etc/*-release
fi
}
function pause() {
read -r -p "$*"
}
# sanitize history by removing -f from rm command
# this prevents you from rerunning an old command and force removing something unintended
# shellcheck disable=SC2032 # we don't aspire to invoke this via xargs
function rm() {
local HISTIGNORE="$HISTIGNORE:command rm *"
local arg process
local -a sanitized
command rm "$@"
process=true
for arg in "$@"; do
if [[ $process && $arg == "-f" ]]; then
# do nothing; don't add `-f` to the command in history
:
elif [[ $process && $arg == -*f* ]]; then
# remove the `f` from `-rf` or similar
sanitized+=("${arg//f/}")
elif [[ $process && $arg == "-iv" ]]; then
# do nothing; don't add `-iv` to the command in history
:
elif [[ $arg == -- ]]; then
process=
else
sanitized+=("$arg")
fi
done
# add sanitized command to history
history -s rm "${sanitized[@]}"
}
function rtfm() {
[[ -z $1 ]] || [[ $1 == "--help" ]] && {
echo "Search manual or --help for command & arguments"
echo " Accepts options/text without requiring escaping"
echo " Actual rtfm options are prepended with --rtfm-"
echo
echo "Usage: rtfm <command> [options...] [arguments...] [raw text...] [--rtfm-options...]"
echo " options:"
echo " --help show this page"
echo " --rtfm-# show # lines of context after match (0-9, default: 2)"
echo " --rtfm-debug show debugging info"
echo " --rtfm-strict ignore options scattered through descriptions of other options by explicitly matching start of line"
return
}
local -a long_opts
local -a raw
local context=2
local debug
local opts
local regex
local rtfm_opt
local strict_mode
# extract command from argument list
local command_name="$1"
shift
# loop through arguments
while (( $# > 0 )); do
case "$1" in
--rtfm-*)
# strip prepended --rtfm-
rtfm_opt="${1:7:99}"
if [[ $rtfm_opt =~ [0-9] ]]; then
context=$rtfm_opt
elif [[ $rtfm_opt == "debug" ]]; then
debug=true
elif [[ $rtfm_opt == "strict" ]]; then
strict_mode=true
fi
shift
;;
--*)
# strip prepended --
long_opts+=("${1:2:99}")
shift
;;
-*)
# strip prepended -
opts+="${1:1:99}"
shift
;;
*)
raw+=("$1")
shift
;;
esac
done
[[ $debug ]] && echo "${CYAN}rtfm is case-sensitive${D}"
if [[ $strict_mode ]]; then
[[ $debug ]] && echo "${CYAN}Strict mode: ignore options scattered through descriptions of other options${D}"
regex+="^ *-[$opts]|"
elif [[ -n $opts ]]; then
# match '[-x' or ' -x' or ',-x'
regex+="[[ ,]-[$opts]|"
fi
# add long_opts to regex if specified
[[ ${#long_opts[@]} -gt 0 ]] && regex+="--($(array_join "|" "${long_opts[@]}"))|"
# add raw text to regex if specified
[[ ${#raw[@]} -gt 0 ]] && regex+="($(array_join "|" "${raw[@]}"))|"
# strip trailing |
regex=${regex%?}
if ! man "$command_name" >/dev/null 2>&1; then
[[ $debug ]] && {
echo "No man found for $command_name"
echo "\"$command_name\" --help | grep -E \"$regex\""
}
"$command_name" --help | grep -E "$regex"
return
fi
# open manual if no search specified
[[ -z $regex ]] && {
man "$command_name"
return
}
# pipe man through col to fix backspaces and tabs, and grep the output for our regex
[[ $debug ]] && echo "man \"$command_name\" | col -bx | grep -E -A \"$context\" -e \"$regex\""
man "$command_name" | col -bx | grep -E -A "$context" -e "$regex"
}
# set_title $title
# set window title to $title, or "user at host in folder" if blank
# ensures prompt command is not overwritten
function set_title() {
# shellcheck disable=SC2016 # use single quotes for prompt command, variable expansion must happen at runtime
local pcmd='echo -ne "\033]0;$USER at ${HOSTNAME%%.*} in ${PWD##*/}\007";'
# hostname is truncated before first period
# folder is truncated after last slash
[[ -n $1 ]] && {
pcmd='echo -ne "\033]0;TITLE_HERE\007";'
pcmd=${pcmd/TITLE_HERE/$1}
}
# Save and reload the history after each command finishes
pcmd="history -a; history -c; history -r; $pcmd"
export PROMPT_COMMAND=$pcmd
}
# show host fingerprints in both formats
# don't show errors for "foo is not a public key file"
function show_fingerprints() {
echo
for file in /etc/ssh/*.pub; do
echo "$file"
ssh-keygen -E md5 -lf "$file" 2>/dev/null && \
ssh-keygen -E sha256 -lf "$file" 2>/dev/null && \
echo
done
}
function _source_bash_completions() {
[[ $1 == "--help" ]] && {
echo "Source all completion files from valid paths"
echo "Usage:"
echo " _source_bash_completions [options]"
echo " --help Show this screen"
echo " -f, --force Don't skip paths containing >250 files"
return
}
local -a absolutes paths
local absolute_path file filecount limit=250 path
[[ $1 =~ -(f|-force) ]] && limit=10000
paths=(
/etc/bash_completion.d
/usr/local/etc/bash_completion.d
/usr/share/bash-completion/bash_completion.d
/usr/share/bash-completion/completions
)
for path in "${paths[@]}"; do
# ignore non-existent directories
[[ ! -d $path ]] && continue
# uniquify via absolute paths
absolute_path=$(_realpath "$path")
if ! in_array "$absolute_path" "${absolutes[@]}"; then
absolutes+=("$absolute_path");
fi
done
for path in "${absolutes[@]}"; do
# shellcheck disable=SC2012 # ls (over find) is adequate for a quick file count
filecount=$(ls -1 "$path" | wc -l)
[[ $filecount -gt $limit ]] && {
echo "Skipping $filecount completions in $path"
continue
}
for file in "$path"/*; do
[[ -f $file ]] && {
source "$file" || echo "_source_bash_completions error sourcing $file"
}
done
done
# source other scripts if exist
[[ -f ~/.git-completion.bash ]] && source ~/.git-completion.bash
}
_source_bash_completions
function sshl() {
local default_key i inherit keys_found output
local key="$1"
local list_keys=true
if [[ -n $key ]]; then
# standardise user specified key or ~/.ssh/key to absolute pathname
for i in $key ~/.ssh/$key; do
# shellcheck disable=SC2086 # key path needs to be unquoted
[[ -f $i ]] && key="$(_realpath $i)" && break
done
else
# set a default key if none specified, in order of preference
for i in ed25519 rsa dsa ecdsa; do
[[ -f ~/.ssh/id_$i ]] && default_key="$(_realpath ~/.ssh/id_$i)" && break
done
fi
if exists keychain; then
# tell keychain to inherit forwarded or pre-existing local agent, but
# only if it contains "agent"; we ignore the builtin macOS agent, and
# spawn a new, keychain-compatible agent which persists between shells
if [[ $SSH_AUTH_SOCK == *agent* ]]; then
inherit="--inherit any"
fi
# add a default key, if there is one
# we do this so that keychain always adds a key, and we can do this because
# keychain doesn't add keys again if they're already loaded, unlike ssh-add
[[ -z $key && -n $default_key ]] && key="$default_key"
# shellcheck disable=SC2086 # params need to be unquoted
eval "$(keychain --eval $inherit $key)"
keychain -l
else
output="keychain not available, "
if [[ -z $SSH_AUTH_SOCK ]]; then
keys_found="$(find ~/.ssh -type f \( -iname "*id*" ! -iname "*.pub" \) -print -quit 2>/dev/null)"
# only start ssh-agent if the user specified a key, or if ~/.ssh contains a key
if [[ -n $keys_found || -n $key ]]; then
output+="spawning new ssh-agent"
eval "$(ssh-agent -s)"
else
output+="no keys found, not spawning ssh-agent"
list_keys=false
fi
else
output+="using forwarded ssh-agent"
fi
# add a default key, but only if the user hasn't specified one, we find a default, and no keys are loaded
if [[ -z $key && -n $default_key && "$(ssh-add -ql 2>/dev/null)" == "The agent has no identities." ]]; then
key=$default_key
fi
# shellcheck disable=SC2086 # key needs to be unquoted
[[ -n $key ]] && ssh-add $key
echo -e "$output\n"
[[ -n $key || $list_keys == true ]] && ssh-add -l
fi
}
export -f sshl
function stash() {
[[ $1 == "--help" ]] && {
echo "stash:"
echo " Wrapper / logic function for either stashing changes via patch or stashing the current stage"
echo
echo "usage: stash [message]"
return
}
local default_message message="$1"
local patch_fail="
${D}Patch failed to complete (most likely overlapping patches preventing the stashed changes from being removed)
See: https://stackoverflow.com/questions/5047366/why-does-git-stash-p-sometimes-fail
Please review the resulting stash (${BLUE}stashcontents${D}) and remove from work tree manually (${BLUE}discardpatch${D})"
default_message="WIP on $(git_branch): $(git rev-parse --short HEAD) $(git log -1 --pretty=%s)"
[[ -z $message ]] && message="$default_message"
# ask the user for a stash message first, it's harder to add one later
echo "${CYAN}$message${D}"
read -r -p "Type stash message, or continue with the above? (default: continue) " choice
[[ -z $choice ]] || {
message="$choice"
}
if git diff --quiet --exit-code --cached; then
echo "${CYAN}Stage is empty, reverting to patch mode${D}"
if ! git stash push --patch -m "$message"; then
echo "$patch_fail"
fi
return
fi
read -r -p "[p]atch in changes to stash, or stash [s]taged changes? [p/s] " function
if [[ $function == "p" ]]; then
git stash push --patch
elif [[ $function == "s" ]]; then
_stashstage "$message"
else
echo "Aborted"
return
fi
}
# git stash only what is currently staged and leave everything else
# credit: https://stackoverflow.com/a/39644782
function _stashstage() {
local message="$1"
[[ -z $message ]] && echo "message is required, exiting" && return
# stash everything but only keep staged files
git stash --keep-index
# stash staged files with requested message
git stash push -m "$message"
# apply the original stash to get us back to where we started
git stash apply "stash@{1}"
# create a temporary patch to reverse the originally staged changes and apply it
git stash show -p | git apply -R
# delete the temporary stash
git stash drop "stash@{1}"
}
function strpos() {
[[ -z $1 ]] && echo "usage: strpos haystack needle" && return
x="${1%%"$2"*}"
[[ $x = "$1" ]] && echo -1 || echo "${#x}"
}
function suho() {
if [[ $os == "macOS" ]]; then
sudo sublime /etc/hosts
elif [[ $os == "Windows" ]]; then
sudo vi /mnt/c/Windows/System32/drivers/etc/hosts
fi
}
[[ $os == "macOS" ]] && {
# credit <NAME> - original (http://justinhileman.com)
# credit Vitaly (https://gist.github.com/vitalybe/021d2aecee68178f3c52)
function tab() {
[[ $1 == "--help" ]] && {
echo "Open new iTerm tabs from the command line"
echo "Usage:"
echo " tab Opens the current directory in a new tab"
echo " tab [PATH] Open PATH in a new tab (includes symlinks)"
echo " tab [CMD] Open a new tab and execute CMD (also sets tab title)"
echo " tab [PATH] [CMD] ... You can prob'ly guess"
return
}
local commands=()
local path="$PWD" path_test
local exec_set_title exec_commands user_command
# test if we can cd into $1, and capture as $path if so.
# this way we can handle cases where you're inside a symlinked folder,
# but [[ -d ../foo ]] actaully references the literal parent folder
path_test=$(if command cd "$1" &>/dev/null; then pwd; fi;)
if [[ -n $path_test ]]; then
path="$path_test"
shift
fi
user_command="$*"
# no need to cd if goal is home directory
[[ $path != "$HOME" ]] && {
commands+=("command cd '$path'")
}
commands+=("clear" "pwd")
[[ -n $user_command ]] && {
exec_set_title="set_title '$user_command'"
commands+=("$user_command")
commands+=("set_title")
}
exec_commands=$(array_join "; " "${commands[@]}")
# osascript 2-space indentation due to deep nesting
osascript &>/dev/null <<EOF
tell application "iTerm"
tell current window
set newTab to (create tab with default profile)
tell newTab
tell current session
write text " $exec_set_title"
write text " $exec_commands"
end tell
end tell
end tell
end tell
EOF
}
}
function tm() {
[[ $1 == "--help" ]] && {
echo "Find running processes by name (task manager)"
echo "Usage:"
echo " tm Show all processes"
echo " tm [foo bar...] Search for processes matching foo, bar"
return
}
# join params with logical OR for regex
local processes
processes=$(array_join "|" "$@")
# if no args passed, show all processes (match end of line)
[[ -z $1 ]] && processes="$"
# grep process list (and PID to show header), without matching itself
# shellcheck disable=SC2009 # prefer grep over pgrep
ps -aef | grep -Ev "grep.*PID" | grep -E "PID|$processes"
}
if exists tmux; then
function tmucks() {
local status
status=$(tmux attach 2>&1)
# when there's already a tmux session, $() doesn't capture output,
# it just attaches, so we only need to check if it doesn't work
if [[ $status == "no sessions" ]]; then
tmux
fi
}
fi
function totalcommits() {
local override="custom"
local ref
local -i commits
# allow overriding starting commit, if you inherit a project or similar
# set using: git config basherk.firstcommit <ref>
# ref is any git-readable reference (sha, tag, branch, etc)
ref=$(git config --local --get basherk.firstcommit)
# reference initial commit if override is absent
[[ -z $ref ]] && {
# TODO: find out why rev-list returns 2 hashes for SELinuxProject/selinux
# both the same # of commits away from HEAD
# pipe through head to provide a single commit for calculation, for now
ref=$(git rev-list --max-parents=0 --abbrev-commit HEAD | head -1)
override="initial"
}
commits=$(git rev-list "$ref".. --count)
# increment to also include ref commit in count
((commits++))
echo "${D}Commits for ${CYAN}$(git_repo_name)${D} starting $ref ($override): ${CYAN}$commits${D}"
}
# update basherk on another machine (or localhost if none specified)
function ubash() {
local actual_path
local dest="$1"
local src="$basherk_src"
[[ -z $dest ]] && {
# update localhost
[[ -n "$(command cd "$basherk_dir" && git_in_repo)" ]] && {
echo "you are running basherk from a repo, to update:"
echo "${BLUE}cd \"$basherk_dir\""
echo "git pull"
echo "basherk${D}"
return
}
[[ -L $src ]] && {
actual_path=$(_realpath "$src")
echo "basherk is a symlink, updating it"
la "$src"
# if actual file is writable, set it as the location for curl
[[ -w $actual_path ]] && src="$actual_path"
}
# download latest (HEAD) basherk
curl "$basherk_url" -o "$src"
clear
echo "re-sourcing basherk"
basherk
return
}
if rsync -az "$src" "$dest":~/.basherk; then
echo "$dest updated with $(basherk --version)"
else
echo "${RED}basherk update failed for $dest${D}"
fi
}
function vollist() {
# handle voldisplay --help => vollist -a --help
if [[ $1 == "--help" || $2 == "--help" ]]; then
echo "vollist"
echo " display summary or extended info for volumes and volume groups"
echo " wraps pvs/vgs/lvs (and *display), run as sudo"
echo
echo "usage: vollist [options]"
echo " options:"
echo " -a show all/extended information"
return
fi
local selection
local command
local extended=(pvdisplay vgdisplay lvdisplay)
local summary=(pvs vgs lvs)
if [[ $1 == "-a" ]]; then
selection=("${extended[@]}")
else
selection=("${summary[@]}")
fi
for command in "${selection[@]}"; do
echo
echo "${CYAN}$command${D}"
# shellcheck disable=SC2086 # leave $command unquoted
sudo $command
done
}
if exists pvs; then
alias voldisplay='vollist -a'
else
unset vollist
fi
# extend information provided by which
function which() {
local app="$1"
local location
location=$(command which "$app")
echo "$location" # lol, i'm a bat
# check if which returns anything, otherwise we just ls the current dir
[[ -n $location ]] && ls -ahl "$location"
}
# return working directory with gitroot path replaced with repo name (if necessary)
# ~/dev/repos/basherk/test => basherk repo/test
function echo_working_dir() {
local dir="$1"
local gitrepo subfolder
if ! exists git; then
# return input if git is not installed
echo "$1"
return 0
fi
gitrepo=$(git_repo_name 2>/dev/null) || {
# return input if not in a git repo
echo "$1"
return
}
subfolder=$(git rev-parse --show-prefix)
# manually build subfolder if inside .git since show-prefix returns blank
[[ $dir == *.git* ]] && subfolder=".git${dir##*.git}"
dir="$gitrepo repo/$subfolder"
# trim trailing slash (in case subfolder is blank, since we append a slash after gitrepo)
dir="${dir%/}"
echo "$dir"
}
function git_branch() {
git branch --no-color 2>/dev/null | sed '/^[^*]/d; s/* \(.*\)/\1/;'
}
function git_dirty() {
local dirty untracked modified staged line
# pass here-string to preserve variable assignment
while read -r line; do
# exit if no files
[[ -z $line ]] && break
# check for untracked files first, and skip loop if so
[[ ${line:0:1} == "?" ]] && untracked=true && continue
# trim prepended "1 " for staged/modified lines, keep only 2 chars
line="${line:2:2}"
# staged can be A/M/R/etc in first column, modified is M in second
# simply check if each is not . which means not added, modified, etc
[[ ${line:0:1} != "." ]] && staged=true
[[ ${line:1:1} != "." ]] && modified=true
done <<< "$(git status --porcelain=v2 2>/dev/null)"
[[ $untracked ]] && dirty+="?"
[[ $modified ]] && dirty+="!"
[[ $staged ]] && dirty+="+"
echo "$dirty"
}
function git_in_repo() {
[[ -n "$(git_branch)" ]] && echo "on"
}
function git_repo_name() {
local gitrepo gitroot
gitroot=$(git_root) || return # return if not in a git repo
gitrepo=$(git remote -v | head -n1 | awk '{print $2}' | sed 's/.*\///; s/\.git//;')
# return git root folder name if git remote is blank
[[ -z $gitrepo ]] && gitrepo="${gitroot##*/}"
echo "$gitrepo"
}
function git_root() {
git rev-parse --show-toplevel
}
# git bash requires double quotes for prompt
if [[ -f /git-bash.exe ]]; then
# user at host
prompt="\n${PINK}\u ${D}at ${ORANGE}\h "
# working dir or repo name substitute
prompt+="${D}in ${GREEN}$(echo_working_dir "\w") "
prompt+="${D}$(git_in_repo) ${PINK}$(git_branch)${GREEN}$(git_dirty) "
prompt+="${D}\n\$ "
else
# shellcheck disable=SC2016 # prompt command requires single quotes
# user at host
prompt='\n${PINK}\u ${D}at ${ORANGE}\h '
# shellcheck disable=SC2016
# working dir or repo name substitute
prompt+='${D}in ${GREEN}$(echo_working_dir "\w") '
# shellcheck disable=SC2016
if exists git; then prompt+='${D}$(git_in_repo) ${PINK}$(git_branch)${GREEN}$(git_dirty) '; fi
# shellcheck disable=SC2016
# manually set mark to align it with the prompt, ensure it doesn't break (e.g. after re-sourcing basherk)
[[ $TERM_PROGRAM == *iTerm* ]] && prompt+='${D}\n\[$(iterm2_prompt_mark)\]$ ' || prompt+='${D}\n$ '
fi
export PS1=$prompt
unset prompt
# Set window title to something readable
set_title
export DISABLE_AUTO_TITLE="true"
# source post-basherk definitions
[[ -f "$basherk_dir/post-basherk.sh" ]] && . "$basherk_dir/post-basherk.sh"
# run sshl last to avoid terminating basherk when cancelling ssh passkey prompt
# don't run sshl if ssh isn't installed, or if we're re-sourcing basherk
if ! exists ssh-add; then return; fi
[[ -z $basherk_re_sourcing ]] && sshl
<file_sep>/custom-basherk.example.sh
# custom user aliases & functions
# sourced by basherk directly after pre-basherk.sh (i.e. before most other code)
# usage: copy this example file to expected filename and modify
# cp custom-basherk.example.sh custom-basherk.sh
# export MY_VAR="foo"
# alias my_alias='my_func'
# my_func() {
# …
# }
| 96eb14184e5a6a8e64a1dc458cd5fe01830807d7 | [
"Markdown",
"Shell"
]
| 5 | Shell | traveaston/basherk | fb4625d9b1938f2565a92317c3993a5cc8bb37a6 | 07aae09804c92ec6cb940f14039f7abe18152127 |
refs/heads/master | <repo_name>marsmensch/vbox-sync<file_sep>/vbox-sync-helper/vbox-sync-admin
#!/usr/bin/env python
# vim:set ft=python et sw=4 encoding=utf-8:
#
# © 2009 <NAME> <<EMAIL>>
#
# Licensed under the EUPL, Version 1.0 or – as soon they
# will be approved by the European Commission - subsequent
# versions of the EUPL (the "Licence");
# you may not use this work except in compliance with the
# Licence.
# You may obtain a copy of the Licence at:
#
# http://ec.europa.eu/idabc/eupl
#
# Unless required by applicable law or agreed to in
# writing, software distributed under the Licence is
# distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
# express or implied.
# See the Licence for the specific language governing
# permissions and limitations under the Licence.
from itomig.vbox import VBoxImage, Config, OptionParser, Logger
from itomig.vbox_gui import VBoxSyncAdminGui
import sys
def main(argv):
# Parse command-line parameters.
usage = 'usage: %prog [options]'
parser = OptionParser(usage)
(options, args) = parser.parse_args(argv)
if len(args) != 1:
parser.error('incorrect number of arguments')
config = Config(options)
# Do it.
gui = VBoxSyncAdminGui(config)
gui.main()
if __name__ == '__main__':
main(sys.argv)
<file_sep>/vbox-sync-helper/setup.py
from distutils.core import setup
setup(name='vbox-sync-helper',
version='0.1',
author='<NAME>',
author_email='<EMAIL>',
classifiers=[
'License :: OSI Approved :: European Union Public License',
'Programming Language :: Python'
],
packages=['itomig'],
scripts=['vbox-sync', 'vbox-invoke', 'vbox-makecfg', 'vbox-dispose', 'vbox-sync-admin'],
data_files=[('share/man/man1', ['vbox-invoke.1', 'vbox-makecfg.1', 'vbox-sync-admin.1']),
('share/man/man8', ['vbox-sync.8', 'vbox-dispose.8'])],
package_data={'itomig': ['vbox-sync-admin.glade']},
)
<file_sep>/vbox-sync-helper/itomig/vbox.py
# vim:set et sw=4 encoding=utf-8:
#
# Module to handle the distribution of VBox VM images
#
# © 2009 <NAME> <<EMAIL>>
#
# Licensed under the EUPL, Version 1.0 or – as soon they
# will be approved by the European Commission - subsequent
# versions of the EUPL (the "Licence");
# you may not use this work except in compliance with the
# Licence.
# You may obtain a copy of the Licence at:
#
# http://ec.europa.eu/idabc/eupl
#
# Unless required by applicable law or agreed to in
# writing, software distributed under the Licence is
# distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
# express or implied.
# See the Licence for the specific language governing
# permissions and limitations under the Licence.
"""
This module fetches VirtualBox images from a rsync server specified
in a configuration file and handles its user-local registration and
invocation.
"""
__VERSION__ = "@VERSION@"
from ConfigParser import ConfigParser
import errno
import logging
import optparse
import os
import os.path
import subprocess
import shutil
import sys
import tempfile
import re
class ImageNotFoundError(Exception):
"""This exception is raised when the specified image cannot be found
with the given version on the rsync server (vbox-sync) or if the image
was expected on the local disk and not found (vbox-invoke).
"""
pass
class PackageNotFoundError(Exception):
"""This exception is raised when, for an image found on the disk, no
corresponding debian package can be found.
"""
pass
class RsyncError(Exception):
"""This exception is raised when the rsync invocation to fetch the
image or to list the directory on the server fails with a different
error than 'File Not Found'. For the latter, see ImageNotFoundError.
"""
pass
class TargetNotWriteableError(Exception):
"""This exception is raised when the target direction of the sync
operation is not writeable, which is commonly the case if the target
directory is only writeable as root and the script is invoked as a
normal, unprivileged user."""
pass
class VBoxImageSync(object):
def __init__(self, image):
self.image = image
self.config = image.config
self.image_name = image.image_name
self.image_version = image.image_version
self.logger = image.logger
def _check_presence(self):
self._check_rsync_file(self._construct_url(self.image.vdi_filename()))
self._check_rsync_file(self._construct_url(self.image.cfg_filename()))
def _check_rsync_file(self, filename):
"""Submits a list request to the rsync server and raises
ImageNotFoundError if rsync returns with a failure of 23
(which is caused by ENOENT, among others) or raises
RsyncError if rsync returns with any other error."""
retcode = subprocess.call(['rsync', '-q', filename])
if retcode == 0:
self.logger.debug('Image found on the server.')
return
elif retcode == 23:
raise ImageNotFoundError
else:
raise RsyncError, retcode
def _check_target_writeable(self):
if not os.path.exists(self.image.vdi_path()):
return
if not os.access(self.image.vdi_path(), os.W_OK):
raise TargetNotWriteableError
def _ensure_target_directory(self):
basedir = os.path.dirname(self.image.vdi_path())
if not os.path.exists(basedir):
os.makedirs(basedir, 0755)
def _construct_url(self, filename):
"""Constructs a URL to the image file we want to retrieve based
on the baseurl we got from the configuration object."""
# urlparse.urljoin is insufficient here because it recognizes
# rsync URLs as being non-relative and generally does not what
# we want here.
image_path = '/'.join([self.image_name, self.image_version, filename])
url = '/'.join([self.config.baseurl, image_path])
return url
def _sync_file(self, source, target):
retcode = subprocess.call(['rsync', '--progress', '--times',
source, target])
if retcode != 0:
raise RsyncError, retcode
# Make it publically readable, do not inherit the permission
# even if copied from the local disk.
os.chmod(target, 0644)
def sync(self):
self._check_presence()
self._ensure_target_directory()
self._check_target_writeable()
self.logger.info('Syncing image')
self._sync_file(self._construct_url(self.image.cfg_filename()),
self.image.cfg_path())
self._sync_file(self._construct_url(self.image.vdi_filename()),
self.image.vdi_path())
class VBoxInvocationError(Exception):
pass
def guarded_vboxmanage_call(args):
cmdline = ['VBoxManage', '-nologo', '-convertSettingsBackup'] + args
retcode = subprocess.call(cmdline)
if retcode != 0:
raise VBoxInvocationError, ' '.join(cmdline)
class VBoxImageFinder(object):
def __init__(self, config):
self.config = config
def find_images(self):
for image_name in os.listdir(self.config.target):
if os.path.exists( os.path.join(self.config.target, image_name, "%s.vdi" % image_name)):
# We need to find the version. This is getting slightly messy
for package_name in [ "%s-vbox" % image_name,
"vbox-%s" % image_name,
image_name ]:
if os.path.exists ( os.path.join("/usr/share/doc",package_name,"changelog.gz") ):
break
if not package_name:
raise PackageNotFoundError
yield VBoxImage(self.config, image_name, self._version_of( package_name ))
def _version_of(self, package_name):
dpkg_pipe = subprocess.Popen(["dpkg-query", "--showformat", "${Version}", "--show", package_name], stdout=subprocess.PIPE)
return dpkg_pipe.communicate()[0]
class VBoxImage(object):
def __init__(self, config, image_name, image_version):
self.config = config
self.image_name = image_name
self.image_version = image_version
self.logger = Logger()
self.disks = dict()
self.admin_mode = False
# For the purposes of the GUI, we also want to know the name of the
# Debian package that we were shipped in. We find out about that here,
# using some common sense
for package_name in [ "%s-vbox" % image_name,
"vbox-%s" % image_name,
image_name ]:
if os.path.exists ( os.path.join("/usr/share/doc",package_name,"changelog.gz") ):
self.package_name = package_name
break
def name(self):
""" A descripive name of the image, for display in GUIs etc. """
return "%s (Version %s)" % (self.image_name, self.image_version)
def cfg_filename(self):
return '%s.cfg' % self.image_name
def vdi_filename(self):
return '%s.vdi' % self.image_name
def _target_path(self, filename=None):
if self.admin_mode:
path = self._vbox_home()
else:
path = os.path.join(self.config.target, self.image_name)
if filename:
path = os.path.join(path, filename)
return path
def vdi_path(self):
return self._target_path(self.vdi_filename())
def cfg_path(self):
return self._target_path(self.cfg_filename())
def sync(self):
"""This method syncs the image from the rsync server. It delegates
this to a VBoxImageSync object."""
sync = VBoxImageSync(self)
sync.sync()
def register(self):
self.logger.info('Registering the image with VirtualBox')
self._make_vdi_immutable()
def _vbox_home(self):
if self.admin_mode:
path = '~/.VirtualBox-%s-admin' % self.image_name
else:
path = '~/.VirtualBox-%s' % self.image_name
return os.path.abspath(os.path.expanduser(path))
def _ensure_vbox_home(self):
vbox_home = self._vbox_home()
# Create VBox home directory.
if not os.path.exists(vbox_home):
self.logger.info('Creating VBox home for %s in %s',
self.image_name, vbox_home)
os.makedirs(vbox_home, 0700)
# Create data disk storage directory.
if not os.path.exists(os.path.join(vbox_home, 'VDI')):
os.makedirs(os.path.join(vbox_home, 'VDI'))
os.environ['VBOX_USER_HOME'] = vbox_home
def _ensure_data_disk(self):
"""Creates a data disk for use as the second harddrive in the
VM with the passed size in megabytes. The data disk will not be
resized in any way if the given size differs from the on-disk
image."""
# A temporary image we create.
data_disk_tmp = tempfile.NamedTemporaryFile()
data_disk = data_disk_tmp.name
# The real image which will be used with VBox.
data_disk_vdi = os.path.join(self._vbox_home(), 'VDI',
'%s-data.vdi' % self.image_name)
if os.path.exists(data_disk_vdi):
# Do nothing.
return
vmparameters = dict(self._read_cfg())
if not 'datadisksize' in vmparameters:
# No data disk size specified, do not create a data disk.
print vmparameters
return
size = int(vmparameters['datadisksize'])
self.logger.info('Creating data disk image for %s.', self.image_name)
# First create an empty image full of zeros. This needs some
# space in the temporary directory, but avoids that a template needs
# to be shipped separately. VirtualBox is compressing the image
# when converting from RAW to VDI anyway (32M to 1M in tests with
# fat16).
ret = subprocess.call(['dd', 'if=/dev/zero', 'of=%s' % data_disk,
'bs=1M', 'count=%d' % size])
# XXX: improve exceptions here
# XXX: catch stderr+stdout and only print it if something goes wrong
if ret != 0:
raise Exception, 'dd failed'
# Now create a DOS disk label.
# (The path to parted is explicitly specified, because /sbin is not
# always in the path. Maybe this should be replaced by an
# environment modification later on.)
ret = subprocess.call(['/sbin/parted', data_disk, 'mklabel', 'msdos'])
if ret != 0:
raise Exception, 'parted-mklabel failed'
# Create a fat16 or fat32 partition, depending on the size. parted
# complains if the partition is too tiny for fat32 but the minimum
# size is determined by a strange algorithm. In tests it already
# worked with 64M, but not with 32M. It's probably not advisable
# to use fat32 on such tiny images anyway.
if size >= 128:
fs_type = 'fat32'
else:
fs_type = 'fat16'
ret = subprocess.call(['/sbin/parted', data_disk, 'mkpartfs', 'primary',
fs_type, '1', str(size)])
if ret != 0:
raise Exception, 'parted-mkpartfs failed'
# Now convert it using VBoxManage.
guarded_vboxmanage_call(['convertfromraw', '-format', 'VDI',
data_disk, data_disk_vdi])
# This destroys the temporary image.
data_disk_tmp.close()
# data_disk_vdi is now a disk usable for D:
self.disks['data'] = data_disk_vdi
def _register_disks(self):
for disk in self.disks:
if disk == 'system' and not self.admin_mode:
disk_type = 'immutable'
elif disk == 'system' and self.admin_mode:
disk_type = 'writethrough'
elif disk == 'data':
# TODO: Do we want that? Causes it to be unaffected by
# snapshots.
disk_type = 'writethrough'
else:
disk_type = 'normal'
self.vbox_registry.register_hdd(self.disks[disk], disk_type)
def _read_cfg(self):
"""Read the supplied configuration file for VM parameters."""
parser = ConfigParser()
parser.read(self.cfg_path())
return parser.items('vmparameters')
def _register_vm(self):
# XXX: Maybe update settings only after upgrades? That's the only
# part that would require passing in the version on the command-line.
# TODO: We really need to change this, as the immutability of the
# system disk creates differential images that are assigned to the
# ide port instead
uuid = self.vbox_registry.create_vm(self.image_name)
# ConfigParser's items method gives us a list of tuples. The map
# will unquote the values (i.e. remove spaces and quotes) and prepend
# a dash to the keys to act as the parameters. In the end it's casted
# to a dict for later modification.
parameters = dict(map(lambda t: ('-%s' % t[0], t[1].strip(' "\'')),
self._read_cfg()))
if '-datadisksize' in parameters:
del parameters['-datadisksize']
self.vbox_registry.modify_vm(uuid, parameters)
for disk in self.disks:
# TODO: improve this
if disk == 'system':
ide_port = 'hda'
elif disk == 'data':
ide_port = 'hdb'
else:
raise NotImplementedError, 'disks other than system and data '\
'implemented'
self.vbox_registry.attach_hdd(uuid, ide_port, self.disks[disk])
def _ensure_system_disk(self):
if not os.path.exists(self.vdi_path()):
raise ImageNotFoundError
self.disks['system'] = self.vdi_path()
def invoke(self, use_exec=True):
"""
Invokes the virtual machine in this image. If the parameter exec is
true, the current process will be replaced.
"""
self._ensure_vbox_home()
self.vbox_registry = VBoxRegistry(self._vbox_home())
self._ensure_system_disk()
self._ensure_data_disk()
self._register_disks()
self._register_vm()
self.vbox_registry.garbage_collect_hdds(self.image_name)
# Using execlp to replace the current process image.
# XXX: do we want that? function does not return
if use_exec:
os.execlp('VBoxManage', 'VBoxManage', '-nologo', 'startvm', self.image_name)
else:
os.spawnlp('VBoxManage', 'VBoxManage', '-nologo', 'startvm', self.image_name)
# TODO: make this configurable to either use SDL or VBox proper
#os.execlp('vboxsdl', '-vm', self.image_name)
def dispose(self):
# NB: This does not clean up the data disks in the user home
# directories. OTOH there is no sane way to handle that,
# as user homes should not be touched.
if os.path.exists(self.vdi_path()):
os.unlink(self.vdi_path())
if os.path.exists(self.cfg_path()):
os.unlink(self.cfg_path())
# Remove the parent directory if empty.
if os.path.exists(self._target_path()):
try:
os.rmdir(self._target_path())
except OSError, e:
if not e.errno == errno.ENOTEMPTY:
raise
self.logger.warn('%s not empty, thus not removed.',
self._target_path())
def prepare_admin_mode(self):
assert not self.admin_mode
sys_vdi = self.vdi_path()
sys_cfg = self.cfg_path()
self.admin_mode = True
self._ensure_vbox_home()
admin_vdi = self.vdi_path()
admin_cfg = self.cfg_path()
shutil.copyfile(sys_vdi, admin_vdi)
shutil.copyfile(sys_cfg, admin_cfg)
def copy_image_files_to(self, target_directory):
shutil.copy(self.vdi_path(), target_directory)
shutil.copy(self.cfg_path(), target_directory)
def leave_admin_mode(self):
assert self.admin_mode
if os.path.exists(self.vdi_path()):
os.remove(self.vdi_path())
if os.path.exists(self.cfg_path()):
os.remove(self.cfg_path())
shutil.rmtree(self._vbox_home())
self.admin_mode = False
class VBoxRegistry(object):
# XXX: handle failures
def __init__(self, vbox_home):
self.vbox_home = vbox_home
self.logger = Logger()
# TODO: pass this through subprocess
if vbox_home:
os.environ['VBOX_USER_HOME'] = vbox_home
def _get_list_value(self, line):
return line.split(' ', 1)[1].strip()
def get_vms(self):
p = subprocess.Popen(['VBoxManage', '-nologo',
'-convertSettingsBackup',
'list', 'vms'],
stdout=subprocess.PIPE)
vms, current_name = {}, None
output = p.communicate()[0]
for line in output.splitlines():
# XXX: test if this is locale dependent
if line.startswith('Name:'):
current_name = self._get_list_value(line)
elif line.startswith('UUID:'):
uuid = self._get_list_value(line)
vms[uuid] = current_name
else:
m = re.match(r'"(.*)" {(.*)}', line)
if m:
vms[m.group(2)] = m.group(1)
return vms
def get_hdds(self):
p = subprocess.Popen(['VBoxManage', '-nologo',
'-convertSettingsBackup',
'list', 'hdds'],
stdout=subprocess.PIPE)
output = p.communicate()[0]
hdds = []
for line in output.splitlines():
if line.startswith('Location:'):
hdds.append(self._get_list_value(line))
return hdds
def create_vm(self, name):
"""Registers a new VM with VirtualBox and returns its UUID."""
vms = self.get_vms()
for uuid in vms:
if vms[uuid] == name:
return uuid
# VM does not exist already, create it in the registry.
p = subprocess.Popen(['VBoxManage', '-nologo',
'-convertSettingsBackup',
'createvm', '-name', name, '-register'],
stdout=subprocess.PIPE)
output = p.communicate()[0]
for line in output.splitlines():
if line.startswith('UUID:'):
return self._get_list_value(line)
# TODO: No UUID found, something went wrong inside vbox. We should
# raise an exception instead.
assert False
def modify_vm(self, identifier, parameters):
"""Takes the VM identifier (either name or UUID) and a dict of
parameters and adjusts the VM parameters accordingly through
VBoxManage."""
# XXX: We should interact with vbox more sanely. Sadly vbox's CLI
# interface is not machine-parseable, so that's hard.
arg_list = []
for key in parameters:
arg_list.extend([key, str(parameters[key])])
guarded_vboxmanage_call(['modifyvm', identifier] + arg_list)
def register_hdd(self, filename, disk_type='normal'):
"""Registers a VDI file with the VirtualBox media registry.
Supported disk types: normal, immutable and writethrough
Returns True if a change has been done to the registry and False
if the image was already registered.
"""
# VirtualBox always works with absolute paths. So we need to
# work with those too, unless everything will be messed up.
absolute_filename = os.path.abspath(filename)
if absolute_filename in self.get_hdds():
# Nothing to do, it's already registered.
return False
self.logger.debug('Registering new hard disk image %s with type %s.',
absolute_filename, disk_type)
guarded_vboxmanage_call(['openmedium', 'disk',
os.path.abspath(filename),
'-type', disk_type])
return True
def attach_hdd(self, identifier, ide_port, disk_identifier):
"""Attaches a hard disk image to a VM ide port by detaching the old
and attaching the new image. This works around failures by VirtualBox
if differential hard disks are already attached."""
# TODO: (IMPORTANT!) get rid of the differential disk leftover
# disconnect current HDD
guarded_vboxmanage_call(['modifyvm', identifier, '-%s' % ide_port,
'none'])
# attach the new one
guarded_vboxmanage_call(['modifyvm', identifier, '-%s' % ide_port,
disk_identifier])
def _uuid_from_filename(self, filename):
m = re.match(r'{(.+)}.vdi', os.path.basename(filename))
if not m:
raise RuntimeError, \
"Unknown filename type to convert to UUID: %s" % filename
return m.group(1)
def garbage_collect_hdds(self, image_name):
"""Checks if there are differential images leftovers from previous
attach/detach operations that are not currently associated to a VM."""
snapshot_directory = os.path.join(self.vbox_home, 'Machines',
image_name, 'Snapshots')
if not os.path.exists(snapshot_directory):
return
for filename in os.listdir(snapshot_directory):
full_hdd_path = os.path.abspath(os.path.join(snapshot_directory,
filename))
p = subprocess.Popen(['VBoxManage', '-nologo',
'-convertSettingsBackup',
'showhdinfo', full_hdd_path],
stdout=subprocess.PIPE)
output = p.communicate()[0]
if re.search(r'In use by VMs:', output):
continue
uuid = self._uuid_from_filename(filename)
Logger().info("Removing unused differential harddisk '%s'", uuid)
self.discard_hdd(uuid)
os.unlink(full_hdd_path)
def discard_hdd(self, identifier):
"""Unregisters a hard disk image from the VBox media registry."""
guarded_vboxmanage_call(['closemedium', 'disk', identifier])
# The machine-readable output of VBoxManage showvminfo needs severe fixups
# to be used as input for modifyvm's command-line interface. The following
# dict specified which keys to discard (by setting them to False) and which
# keys to fix up because they are named differently, by specifying a
# replacement name.
_transform_vminfo_keys = {
'name': False,
'UUID': False,
'CfgFile': False,
'VMState': False,
'VMStateChangeTime': False,
'GuestStatisticsUpdateInterval': False,
'bootmenu': 'biosbootmenu',
'hda': False,
'hdb': False,
'hdc': False,
'hdd': False,
}
def dump_vm_config(self, identifier, output_file=None, data_disk_size=None):
# XXX: We can get rid of this ad-hoc configuration file if we switch to
# the OVF format.
if output_file:
f = output_file
else:
f = sys.stdout
p = subprocess.Popen(['VBoxManage', '-nologo',
'-convertSettingsBackup',
'showvminfo', identifier, '-machinereadable'],
stdout=subprocess.PIPE)
output = p.communicate()[0]
f.write("[vmparameters]\n")
for line in output.splitlines():
for pattern in self._transform_vminfo_keys:
if line is None:
continue
if line.startswith(pattern):
if self._transform_vminfo_keys[pattern] is False:
line = None
else:
line = '%s%s' % (self._transform_vminfo_keys[pattern],
line[len(pattern):])
if not line:
continue
f.write(line)
f.write("\n")
if data_disk_size:
f.write("datadisksize=%s\n" % str(data_disk_size))
class Config(object):
"""Configuration object that reads ~/.config/vbox-sync.cfg
and /etc/vbox-sync.cfg iff they exist and overrides settings
based on the command-line options passed by the user."""
def __init__(self, options):
self._read_config_files()
if options:
self._read_cmdline_options(options)
logger = Logger()
logger.debug('Configuration:')
logger.debug(' Rsync Base URL: %s', self.baseurl)
logger.debug(' Target directory: %s', self.target)
def _read_config_files(self):
# Read configuration file.
file_config = ConfigParser()
file_config.read([os.path.expanduser('~/.config/vbox-sync.cfg'),
'/etc/vbox-sync.cfg'])
self.baseurl = file_config.get('rsync', 'baseurl')
self.target = file_config.get('images', 'target')
def _read_cmdline_options(self, options):
if getattr(options, 'baseurl', None):
self.baseurl = options.baseurl
if getattr(options, 'target', None):
self.target = options.target
class OptionParser(optparse.OptionParser):
"""An almost-normal OptionParser object, with the difference that it
sets logging to DEBUG if -d is passed. As this is wanted for all
callees of this module we implement it centrally.
"""
def __init__(self, usage):
optparse.OptionParser.__init__(self, usage,
version="%prog " + __VERSION__)
self.add_option('-d', '--debug', dest='debug',
help='enables debugging output',
action='callback', callback=self._enable_debug)
def _enable_debug(self, option, opt, value, parser):
Logger().setLevel(logging.DEBUG)
_logger = None
def Logger():
"""Logger singleton based on a named logger provided by the logging
module."""
global _logger
if _logger:
return _logger
_logger = logging.getLogger('itomig.vbox')
handler = logging.StreamHandler()
formatter = logging.Formatter('%(name)s: %(levelname)-8s %(message)s')
handler.setFormatter(formatter)
_logger.addHandler(handler)
_logger.setLevel(logging.INFO)
return _logger
<file_sep>/vbox-sync-helper/vbox-sync
#!/usr/bin/env python
# vim:set ft=python et sw=4 encoding=utf-8:
#
# © 2009 <NAME> <<EMAIL>>
#
# Licensed under the EUPL, Version 1.0 or – as soon they
# will be approved by the European Commission - subsequent
# versions of the EUPL (the "Licence");
# you may not use this work except in compliance with the
# Licence.
# You may obtain a copy of the Licence at:
#
# http://ec.europa.eu/idabc/eupl
#
# Unless required by applicable law or agreed to in
# writing, software distributed under the Licence is
# distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
# express or implied.
# See the Licence for the specific language governing
# permissions and limitations under the Licence.
from itomig.vbox import VBoxImage, Config, OptionParser, Logger, \
ImageNotFoundError, RsyncError
import sys
def main(argv):
# Parse command-line parameters.
usage = 'usage: %prog [options] image-name image-version'
parser = OptionParser(usage)
parser.add_option('-b', '--baseurl', dest='baseurl', metavar='URL',
help='the base URL of the host to sync from '\
'(e.g. rsync://host/module/)')
parser.add_option('-t', '--target-directory', dest='target',
metavar='DEST-DIR', help='the base directory to save '\
'the image in')
(options, args) = parser.parse_args(argv)
if len(args) != 3:
parser.error('incorrect number of arguments')
image_name, image_version = args[1:3]
config = Config(options)
# Do it.
img = VBoxImage(config, image_name, image_version)
try:
img.sync()
except ImageNotFoundError:
Logger().error('Specified image not found on the server!')
sys.exit(1)
except RsyncError:
Logger().error('Rsync error. Is /etc/vbox-sync.cfg set up correctly?')
sys.exit(1)
if __name__ == '__main__':
main(sys.argv)
<file_sep>/vbox-sync-helper/itomig/vbox_gui.py
# vim:set et sw=4 encoding=utf-8:
#
# Module to handle the distribution of VBox VM images
#
# © 2009 <NAME> <<EMAIL>>
#
# Licensed under the EUPL, Version 1.0 or – as soon they
# will be approved by the European Commission - subsequent
# versions of the EUPL (the "Licence");
# you may not use this work except in compliance with the
# Licence.
# You may obtain a copy of the Licence at:
#
# http://ec.europa.eu/idabc/eupl
#
# Unless required by applicable law or agreed to in
# writing, software distributed under the Licence is
# distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
# express or implied.
# See the Licence for the specific language governing
# permissions and limitations under the Licence.
from itomig.vbox import Logger, VBoxImageFinder
import os.path
import pygtk
pygtk.require("2.0")
import gtk
import gtk.glade
import gobject
import threading
import tempfile
import gzip
import subprocess
from glob import glob
import shutil
from time import localtime, strftime
import locale
import debian.changelog
class PackageBuildingError(Exception):
"""This exception is thrown when someting goes wrong in the automated
package building process."""
pass
def current_email_address():
# We abuse debchange to provide a proper username and email address
(handle,tmp) = tempfile.mkstemp('','vbox-admin-')
try:
os.unlink(tmp) # debchange wants to create the file
ret = subprocess.call(['debchange', '--create', '--newversion', '0.0',
'--package', 'dummy', '--changelog', tmp, 'blubb'])
if ret != 0:
raise Exception, 'debchange failed'
chlog = debian.changelog.Changelog(file=file(tmp))
for block in chlog:
return block.author
finally:
os.remove(tmp)
def bump_version_number(version):
# We again abuse debchange
(handle,tmp) = tempfile.mkstemp('','vbox-admin-')
try:
os.unlink(tmp) # debchange wants to create the file
ret = subprocess.call(['debchange', '--create', '--newversion', version,
'--package', 'dummy', '--changelog', tmp, 'blubb'])
if ret != 0:
raise Exception, 'debchange failed'
ret = subprocess.call(['debchange', '--increment', '--changelog', tmp, 'blubb'])
if ret != 0:
raise Exception, 'debchange failed'
chlog = debian.changelog.Changelog(file=file(tmp))
return(str(chlog.version))
finally:
os.remove(tmp)
def dialogued_action(text, action):
dlg = gtk.MessageDialog(flags = gtk.DIALOG_MODAL)
dlg.props.text = text
class Thread(threading.Thread):
def run(self):
action()
dlg.destroy()
thread = Thread()
dlg.show()
thread.start()
class VBoxSyncAdminGui(object):
def __init__(self, config):
self.config = config
self.logger = Logger()
self.target_directory = os.getcwd()
gladefile = os.path.join(os.path.dirname(__file__),"vbox-sync-admin.glade")
assert os.path.exists(gladefile)
self.wTree = gtk.glade.XML(gladefile)
self.imagestore = gtk.ListStore(gobject.TYPE_PYOBJECT, gobject.TYPE_STRING)
tv = self.wTree.get_widget("imagetreeview")
tv.set_model(self.imagestore)
tv.insert_column_with_attributes(-1,"Image",gtk.CellRendererText(),text=1)
tv.get_selection().connect("changed", self.update_sensitivity)
window = self.wTree.get_widget("vboxsyncadminwindow")
# TODO Check for unsaved data here?
window.connect("destroy", self.on_exit)
self.wTree.get_widget("cancelbutton").connect("clicked", self.on_exit)
self.wTree.get_widget("forwardbutton").connect("clicked", self.on_forward)
self.wTree.get_widget("backbutton").connect("clicked", self.on_backward)
self.wTree.get_widget("executebutton").connect("clicked", self.on_execute)
self.wTree.get_widget("okbutton").connect("clicked", self.on_upload)
self.switch_to(0)
self.update_sensitivity()
window.show()
def fill_list_of_images(self):
self.imagestore.clear()
for image in VBoxImageFinder(self.config).find_images():
self.imagestore.append(( image , image.name() ))
def current_state(self):
return self.wTree.get_widget("notebook").get_current_page()
def update_sensitivity(self, *args):
if self.current_state() == 0:
sel = self.wTree.get_widget("imagetreeview").get_selection()
(model,iter) = sel.get_selected()
if not iter:
self.wTree.get_widget("forwardbutton").set_sensitive(False)
else:
self.wTree.get_widget("forwardbutton").set_sensitive(True)
self.wTree.get_widget("backbutton").set_sensitive(False)
elif self.current_state() == 1:
self.wTree.get_widget("backbutton").set_sensitive(True)
self.wTree.get_widget("forwardbutton").set_sensitive(True)
elif self.current_state() == 2:
self.wTree.get_widget("backbutton").set_sensitive(True)
self.wTree.get_widget("forwardbutton").set_sensitive(True)
elif self.current_state() == 3:
self.wTree.get_widget("backbutton").set_sensitive(True)
self.wTree.get_widget("forwardbutton").set_sensitive(False)
def on_backward(self, button):
if self.current_state() == 1:
dialogued_action("Entferne Kopie des Systemimages.",
self.image.leave_admin_mode)
self.switch_to(0)
elif self.current_state() == 2:
self.switch_to(1)
elif self.current_state() == 3:
self.switch_to(2)
def on_forward(self, button):
if self.current_state() == 0:
# Advancing from the image selecting frame
sel = self.wTree.get_widget("imagetreeview").get_selection()
(model,iter) = sel.get_selected()
if not iter:
return
self.image = model.get(iter,0)[0]
dialogued_action( "Kopiere Orginal-Systemimage (Dies kann eine Weile dauern).",
self.image.prepare_admin_mode )
self.wTree.get_widget("packageentry").set_text(self.image.package_name)
self.wTree.get_widget("versionentry").set_text(bump_version_number(self.image.image_version))
self.wTree.get_widget("distributionentry").set_text("UNRELEASED")
self.switch_to(1)
elif self.current_state() == 1:
self.switch_to(2)
elif self.current_state() == 2:
self.switch_to(3)
def on_exit(self, widget):
dialogued_action("Räume temporäre Dateien auf.",
self.cleanup)
gtk.main_quit()
def cleanup(self):
# In case of abortion
if self.current_state() >= 1:
assert self.image
self.image.leave_admin_mode()
def switch_to(self, new_state):
if new_state == 0:
self.fill_list_of_images()
self.image = None
elif new_state == 1:
assert self.image
elif new_state == 2:
assert self.image
self.wTree.get_widget("notebook").set_current_page(new_state)
self.update_sensitivity()
def on_execute(self, widget):
assert self.current_state() == 1
dialogued_action("Starte VirtualBox",
lambda: self.image.invoke( use_exec=False ))
def on_upload(self, widget):
assert self.current_state() == 3
tmpdir = tempfile.mkdtemp('','vbox-admin-')
try:
os.chdir(tmpdir)
package_name = self.wTree.get_widget("packageentry").get_text()
package_version = self.wTree.get_widget("versionentry").get_text()
package_changes = self.wTree.get_widget("changesentry").get_text()
package_distribution = self.wTree.get_widget("distributionentry").get_text()
locale.setlocale(locale.LC_ALL, 'C')
date = strftime("%a, %d %b %Y %H:%M:%S %z", localtime())
locale.setlocale(locale.LC_ALL, '')
os.mkdir(package_name)
os.chdir(package_name)
os.mkdir("debian")
file("debian/control", "w").write(
"""Source: %(package_name)s
Section: misc
Priority: extra
Maintainer: %(maintainer)s
Build-Depends: debhelper (>= 7)
Standards-Version: 3.8.2
Package: %(package_name)s
Architecture: all
Depends: ${misc:Depends}, vbox-sync-helper
Description: ${misc:Image} for VirtualBox
Retrieves the ${misc:Image} image for VirtualBox from the central rsync
repository and offers you access through the `${misc:Image}' command.
""" % { 'package_name' : package_name,
'maintainer' : current_email_address() } )
file("debian/rules", "w").write(
"""#!/usr/bin/make -f
PACKAGE=$(shell dpkg-parsechangelog | sed -ne 's/Source: *\\(.*\\) *$$/\\1/p')
IMAGE=$(shell echo $(PACKAGE) | sed -ne 's/-vbox$$//p')
build: build-stamp
build-stamp:
dh_testdir
touch build-stamp
clean:
dh_testdir
dh_testroot
rm -f build-stamp
dh_clean
install: build
dh_testdir
dh_testroot
dh_prep
dh_installdirs
# Build architecture-independent files here.
binary-indep: build install
dh_testdir
dh_testroot
dh_installchangelogs
dh_installdocs
dh_installexamples
dh_installman
dh_link
dh_compress
dh_fixperms
dh_vbox_sync $(IMAGE)
dh_installdeb
dh_gencontrol
dh_md5sums
dh_builddeb
binary-arch: build install
binary: binary-indep binary-arch
.PHONY: build clean binary-indep binary-arch binary install
""")
file("debian/compat", "w").write("7")
file("debian/changelog","w").write(
"""%(package_name)s (%(package_version)s) %(package_distribution)s; urgency=low
* %(package_changes)s
-- %(maintainer)s %(date)s
""" % { 'package_name' : package_name,
'package_version' : package_version,
'package_changes' : package_changes,
'package_distribution' : package_distribution,
'maintainer' : current_email_address(),
'date': date
} )
file("debian/changelog","a").write(
gzip.GzipFile("/usr/share/doc/%s/changelog.gz" % self.image.package_name, "r").read())
retcode = subprocess.call(['dpkg-buildpackage','-uc','-us'])
if retcode != 0:
raise PackageBuildingError("dpkg-buildpackage call failed")
os.chdir("..")
# Now look for the produced files
generated_files = glob("*.changes") + glob("*.deb") + glob("*.dsc") + glob("*.tar.gz")
for gen_file in generated_files:
shutil.copy(gen_file, self.target_directory)
self.image.copy_image_files_to(self.target_directory)
finally:
os.chdir(self.target_directory)
shutil.rmtree(tmpdir)
dlg = gtk.MessageDialog(flags = gtk.DIALOG_MODAL, buttons = gtk.BUTTONS_OK)
dlg.props.text = \
"Paket erfolgreich gebaut. Die Dateien finden Sie im Verzeichnis %s." % \
self.target_directory
dlg.run()
self.cleanup()
gtk.main_quit()
def main(self):
gtk.gdk.threads_init()
gtk.main()
<file_sep>/vbox-sync-helper/vbox-makecfg
#!/usr/bin/env python
# vim:set ft=python et sw=4 encoding=utf-8:
#
# © 2009 <NAME> <<EMAIL>>
#
# Licensed under the EUPL, Version 1.0 or – as soon they
# will be approved by the European Commission - subsequent
# versions of the EUPL (the "Licence");
# you may not use this work except in compliance with the
# Licence.
# You may obtain a copy of the Licence at:
#
# http://ec.europa.eu/idabc/eupl
#
# Unless required by applicable law or agreed to in
# writing, software distributed under the Licence is
# distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
# express or implied.
# See the Licence for the specific language governing
# permissions and limitations under the Licence.
from itomig.vbox import VBoxRegistry, Config, OptionParser
import sys
def main(argv):
# Parse command-line parameters.
usage = 'usage: %prog [options] vm-identifier'
parser = OptionParser(usage)
parser.add_option('-o', '--output-file', dest='output_file',
metavar='FILE', help='the output file to write to')
parser.add_option('--vbox-home', dest='vbox_home',
metavar='DIR', help='VirtualBox home directory')
parser.add_option('-s', '--data-disk-size', dest='data_disk_size',
metavar='SIZE', help='size of data disk in MB')
(options, args) = parser.parse_args(argv)
if len(args) != 2:
parser.error('incorrect number of arguments')
vm_identifier = args[1]
config = Config(options)
registry = VBoxRegistry(options.vbox_home)
registry.dump_vm_config(vm_identifier, output_file=options.output_file,
data_disk_size=options.data_disk_size)
if __name__ == '__main__':
main(sys.argv)
<file_sep>/README.md
vbox-sync
=========
simpflyfied handling of debianized virtualbox images
<file_sep>/vbox-sync-helper/vbox-invoke
#!/usr/bin/env python
# vim:set ft=python et sw=4 encoding=utf-8:
#
# © 2009 <NAME> <<EMAIL>>
#
# Licensed under the EUPL, Version 1.0 or – as soon they
# will be approved by the European Commission - subsequent
# versions of the EUPL (the "Licence");
# you may not use this work except in compliance with the
# Licence.
# You may obtain a copy of the Licence at:
#
# http://ec.europa.eu/idabc/eupl
#
# Unless required by applicable law or agreed to in
# writing, software distributed under the Licence is
# distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
# express or implied.
# See the Licence for the specific language governing
# permissions and limitations under the Licence.
from itomig.vbox import VBoxImage, Config, OptionParser
import logging
import sys
def main(argv):
logging.basicConfig()
usage = 'usage: %prog [options] image-name image-version'
parser = OptionParser(usage)
(options, args) = parser.parse_args(argv)
if len(args) != 3:
parser.error('incorrect number of arguments')
image_name, image_version = args[1:3]
config = Config(options)
img = VBoxImage(config, image_name, image_version)
img.invoke()
if __name__ == '__main__':
main(sys.argv)
| 78b95f03f3f9ea1a603a6f1bb26691cc7229038f | [
"Markdown",
"Python"
]
| 8 | Python | marsmensch/vbox-sync | ea33c8bd065ccf358ba0258a631f23afe6ba9a56 | 986a7c227d121857fd51032264372621ad839b1a |
refs/heads/master | <repo_name>luapi82/HTML-PHP-MySQL-Game<file_sep>/main.php
<?php
$username = $_POST["username"];
$password = $_POST["<PASSWORD>"];
try {
require 'connectToDB.php';
$conn = Connect();
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
echo $e->getMessage();
die();
}
$query = $conn->query("SELECT * FROM users WHERE username='$username' and password='$<PASSWORD>'");
if($query->rowCount()){
if($query->rowCount() == 1){
echo "<html>
<head></head>
<body>
<h1>Warrior Wars</h1>
Welcome ".$username."!<p>
Soon you will be able to play this fantastic game! =)
</body>
</html>";
exit();
}
} else {
echo "<p>Could not sign in. <a href='index.html'>Try again</a> or <a href='createUser.html'>Create new account</a>";
}
$conn = null;
?><file_sep>/setup.php
<?php
$servername = "webroot";
$username = "root";
$password = "";
$databasename = "game";
try {
$conn = new PDO("mysql:host=$servername;", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "DROP DATABASE $databasename";
// use exec() because no results are returned
$conn->exec($sql);
echo "Database '$databasename' deleted successfully<p>";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage() . "<p>";
}
try {
$conn = new PDO("mysql:host=$servername;", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "CREATE DATABASE $databasename";
// use exec() because no results are returned
$conn->exec($sql);
echo "Database '$databasename' created successfully<p>";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage() . "<p>";
}
try {
$conn = new PDO("mysql:host=$servername;dbname=$databasename", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// sql to create table
$sql = "CREATE TABLE users (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(30) NOT NULL UNIQUE,
email VARCHAR(50) NOT NULL UNIQUE,
password VARCHAR(30) NOT NULL,
dateCreated datetime NOT NULL DEFAULT NOW()
);
CREATE TABLE characters (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
characterName VARCHAR(30) NOT NULL UNIQUE,
currentLevel INT DEFAULT 0,
hp INT DEFAULT 5,
gold INT DEFAULT 0,
experience INT DEFAULT 0)";
// use exec() because no results are returned
$conn->exec($sql);
echo "Table 'users' created successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
//header("Location: index.html");
echo "Return to <a href='../index.html'>main page</a><p>";
?><file_sep>/forgotPassword.php
<?php
$email = $_POST["email"];
try {
require 'connectToDB.php';
$conn = Connect();
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
echo $e->getMessage();
die();
}
$query = $conn->query("SELECT * FROM users WHERE email='$email'");
if($query->rowCount()){
if($query->rowCount() == 1){
$to = '$email';
$subject = 'Password Reset Request';
$message = 'Hello, someone has requested a password reset from the Warrior Wars website, if this was not you please ignore this message.';
$headers = 'From: <EMAIL>';
mail($to, $subject, $message, $headers);
}
} else {
echo "That email does not exist";
}
$conn = null;
?> | 111f87b780dfa4b036ce3a3a223c71313ce252dc | [
"PHP"
]
| 3 | PHP | luapi82/HTML-PHP-MySQL-Game | 72a42babf92802f66f5d11bccd4d2be39c6c5be9 | 9589b06bbe6d692830d2d0064591884e8416fa1a |
refs/heads/master | <file_sep># multi-pages
vue 多入口例子
<file_sep>// eslint-disable-next-line no-undef
const glob = require('glob')
const pages = glob.sync('./src/pages/**/main.js').reduce((obj, path) => {
const chunk = path.split('./src/pages/')[1].split('/main.js')[0]
obj[chunk] = {
entry: path,
template: 'public/index.html',
chunks: ['chunk-vendors', 'chunk-common', chunk]
}
return obj
}, {})
// eslint-disable-next-line no-undef
module.exports = {
pages
} | df8d8248cb5ebc89fd2f9c050958a2b40541f64e | [
"Markdown",
"JavaScript"
]
| 2 | Markdown | wuchaofan/multi-pages | cdeb740eb1d1f1b326c83b55adc51d285c44be4d | 63de56cc6326a4bab88a193360d4041fddc20cd1 |
refs/heads/master | <repo_name>hermitlt3/AI_Asn2<file_sep>/Base/Source/Node.h
#ifndef NODE_H_
#define NODE_H_
#include "Vector3.h"
#include "Grid.h"
static int nodeID = 0;
struct Grid;
// Node class for A* pathfinding
struct Node
{
// Constructor
Node() {
parent = nullptr;
visited = false;
ID = nodeID ++ ;
G = 0;
F = 0;
H = 0;
};
// Destructor
~Node() {};
// Parent node to trace back
Node *parent;
// The movement cost to move from the starting point A
// to a given node on the grid, following the path generated
// to get there
unsigned int G;
// The estimated movement cost to move from that given node
// to the final destination, point B. a.k.a the Heuristic
unsigned int H;
// F = G + H
unsigned int F;
// The grid it is at
Grid* grid;
// Whether it is visited
bool visited;
friend bool operator==(const Node& lhs, const Node& rhs);
int ID; // juz a lil smth for us to use operator ==
};
bool operator==(const Node& lhs, const Node& rhs)
{
return lhs.ID == rhs.ID;
}
#endif<file_sep>/Base/Source/AStarAlgorithm.h
#pragma once
#include "Vector3.h"
#include "Node.h"
#include "NodeManager.h"
#include <map>
#include <set>
#include <vector>
using namespace std;
bool leftFltrightF(Node* lhs, Node* rhs)
{
return lhs->F < rhs->F;
}
static vector<Vector3> AStarAlgorithm(Node* start, Node* goal)
{
/*
// The set of currently discovered nodes that are already evaluated
priority_queue<Node*, std::vector<Node*>, LessFcost>openList;
// Only start node is known
openList.push(start);
// The set of nodes already checked
map<Node*, int> cost_so_far;
map<Node*, Node*> came_from;
cost_so_far[start] = 0;
came_from[start] = nullptr;
int i = 0;
Node* current;
while (!openList.empty())
{
current = openList.top();
if (current == goal || i > 20){
break;
}
i++;
list<Node*>tempList = NodeManager::GetInstance()->returnNeighbours(current);
for (std::list<Node*>::iterator it = tempList.begin(); it != tempList.end(); ++it) {
Node* next = (*it);
next->visited = true;
int new_cost = cost_so_far[current] + NodeManager::GetInstance()->returnGcost(current, next);
// If node is an obstacle
if (next->grid->type == Grid::WALL) {
continue;
}
// Ignore neighbour
// If node is calculated
if (cost_so_far.find(next) == cost_so_far.end() || new_cost < cost_so_far[next]) {
cost_so_far[next] = new_cost;
//next->F = new_cost + heuristic(goal->grid->pos, next->grid->pos);
std::make_heap(const_cast<Node**>(&openList.top()), const_cast<Node**>(&openList.top()) + openList.size(), LessFcost());
openList.push(next);
came_from[next] = current;
}
}
}
while (current != start) {
}*///
bool(*compare)(Node*, Node*) = leftFltrightF;
set<Node*, bool(*)(Node*, Node*)>openList(compare);
set<Node*>closeList;
openList.insert(start);
// The set of nodes already checked
map<Node*, int> gScore;
map<Node*, int> fScore;
map<Node*, Node*> came_from;
gScore[start] = 0;
fScore[start] = heuristic(start->grid->pos, goal->grid->pos);
Node* current;
vector<Vector3> results;
results.push_back(goal->grid->pos);
while (!openList.empty())
{
current = *(openList.begin());
if (current == goal)
break;
openList.erase(current);
closeList.insert(current);
list<Node*>tempList = NodeManager::GetInstance()->returnNeighbours(current);
for (std::list<Node*>::iterator it = tempList.begin(); it != tempList.end(); ++it) {
Node* next = (*it);
if (closeList.find(next) != closeList.end()) {
continue;
}
next->visited = true;
int tentative_gScore = gScore[current] + heuristic(current->grid->pos, next->grid->pos);
if (openList.find(next) == openList.end()) {
openList.insert(next);
}
else if (tentative_gScore >= gScore[next])
continue;
came_from[next] = current;
gScore[next] = tentative_gScore;
fScore[next] = gScore[next] + heuristic(next->grid->pos, goal->grid->pos);
}
}
if (current != goal)
return results;
while (current != start)
{
current->parent = came_from[current];
if (results.back().x != came_from[current]->grid->pos.x && results.front().y != came_from[current]->grid->pos.y) {
results.push_back(current->grid->pos);
}
current = came_from[current];
}
results.push_back(start->grid->pos);
for (int i = 0; i < results.size(); ++i) {
cout << results[i] << endl;
}
return results;
}
<file_sep>/Base/Source/Priest.cpp
#include "Priest.h"
#include "GameObjectManager.h"
#include "Guardian.h"
#include <vector>
Priest::Priest() :
currState(IDLE),
innerProximity(25.f),
outerProximity(35.f),
nextHealth(health),
timer(0.0),
speed(5.f)
{
health = 100;
maxhealth = health;
mana = 50;
maxmana = mana;
}
Priest::~Priest()
{
}
void Priest::OnNotification(const std::string& msg)
{
if (msg == "INJURED")
{
timer = 0.0;
currState = HEAL;
resetPos = pos;
}
else if (msg == "UNINJURED")
{
currState = RETURN;
}
else if (msg == "GUARDIAN DOWN")
{
currState = RESURRECT;
//resetPos = pos;
}
}
void Priest::Update(double dt)
{
switch (currState) {
case HEAL:
{
HealsGuardian(dt);
break;
}
case RESURRECT:
{
RevivesGuardian(dt);
break;
}
case REPLENISH:
{
ReplenishMana(dt);
break;
}
case IDLE:
{
vel.SetZero();
break;
}
case RUN:
{
vel = IsEnemiesInOuterP() * speed;
break;
}
case DIE:
{
scale.x -= (float)dt * 3; scale.y -= (float)dt * 3; scale.z -= (float)dt * 3;
if (scale.x <= Math::EPSILON) {
active = false;
}
break;
}
case RETURN:
{
ReturnToIdle(dt);
break;
}
}
// Check if the health in this frame is not the same as the one in the next frame
nextHealth = health;
}
void Priest::FSM()
{
// Unless you "resurrect", or you die
if (health <= 0)
currState = DIE;
// If health decreases due to enemy
else
{
if (health != nextHealth) {
currState = RUN;
SendMessage("UNDER ATTACK");
}
switch (currState){
case IDLE:
{
if ((float)mana / (float)maxmana < 0.5f) {
currState = REPLENISH;
resetPos = pos;
}
break;
}
case RUN:
{
if (!IsEnemiesInInnerP())
{
currState = IDLE;
SendMessage("UNHARMED");
}
break;
}
case RESURRECT:
{
if (guardian->active == true)
currState = RETURN;
break;
}
case REPLENISH:
{
if (mana >= maxmana) {
mana = maxmana;
currState = RETURN;
}
break;
}
case RETURN:
{
if ((guardian->pos - pos).Length() > innerProximity - 1.f && (guardian->pos - pos).Length() < innerProximity + 1.f)
currState = IDLE;
break;
}
}
}
}
Vector3 Priest::IsEnemiesInOuterP()
{
Vector3 distance = 0.f;
for (std::vector<GameObject *>::iterator it = GameObjectManager::GetInstance()->m_goList.begin(); it != GameObjectManager::GetInstance()->m_goList.end(); ++it) {
GameObject *go = (GameObject *)*it;
if (go->type == GameObject::GO_PRIEST || go->type == GameObject::GO_GUARDIAN)
continue;
if ((go->pos + go->scale - pos - scale).Length() <= outerProximity) {
distance += go->pos - pos;
}
}
return -distance.Normalized();
}
bool Priest::IsEnemiesInInnerP()
{
for (std::vector<GameObject *>::iterator it = GameObjectManager::GetInstance()->m_goList.begin(); it != GameObjectManager::GetInstance()->m_goList.end(); ++it) {
GameObject *go = (GameObject *)*it;
if (go->type == GameObject::GO_PRIEST || go->type == GameObject::GO_GUARDIAN)
continue;
if ((go->pos + go->scale - pos - scale).Length() <= innerProximity) {
return true;
}
}
return false;
}
void Priest::HealsGuardian(double dt)
{
if (guardian->health < guardian->maxhealth) {
if ((guardian->pos - pos).Length() <= guardian->scale.x + scale.x) {
timer += dt;
vel.SetZero();
}
else
vel = (guardian->pos - pos).Normalized() * speed;
if (timer > 1.0) {
guardian->health += 10;
timer = 0.0;
mana -= 5;
}
}
else {
guardian->health = guardian->maxhealth;
}
}
void Priest::RevivesGuardian(double dt)
{
if ((guardian->pos - pos).Length() <= guardian->scale.x + scale.x) {
timer += dt;
vel.SetZero();
}
else
vel = (guardian->pos - pos).Normalized() * speed;
if (timer > 3.0) {
SendMessage("REVIVING");
mana -= 30;
timer = 0.0;
}
}
void Priest::ReplenishMana(double dt)
{
Vector3 offset;
offset.Set(3, 3, 0);
vel = (manaPos - pos).Normalized() * speed;
if (pos.x > manaPos.x - offset.x && pos.x < manaPos.x + offset.x &&
pos.y > manaPos.y - offset.y && pos.y < manaPos.y + offset.y) {
vel.SetZero();
timer += dt;
if (timer > 0.2) {
mana += 3;
timer = 0.0;
}
}
}
void Priest::ReturnToIdle(double dt)
{
if ((guardian->pos - pos).Length() < innerProximity + 1.f)
vel = (pos - guardian->pos).Normalized() * speed;
else if ((guardian->pos - pos).Length() > innerProximity - 1.f)
vel = (guardian->pos - pos).Normalized() * speed;
else
vel.SetZero();
}
<file_sep>/Base/Source/Grid.h
#pragma once
#include "Vector3.h"
#include "list"
using std::list;
struct Grid {
enum GRID_TYPE
{
EMPTY = 0,
WALL,
END,
START,
TOTAL_GRID_TYPES
};
Grid() {
pos = Vector3(0, 0, 0);
scale = Vector3(1, 1, 1);
type = EMPTY;
}
Grid(Vector3 pos, Vector3 scale, GRID_TYPE type) {
this->pos = pos;
this->scale = scale;
this->type = type;
}
~Grid() {
}
Vector3 pos;
Vector3 scale;
GRID_TYPE type;
};
<file_sep>/Base/Source/Messager.h
/// @brief
///
/// A messager class which will be in charged of sending messages
/// to the message board. Classes which wants to access the message
/// board will inherit from this class.
///
#ifndef MESSAGER_H_
#define MESSAGER_H_
#include <string>
class MessageBoard;
class Messager
{
public:
// constructor
Messager();
// destructor
~Messager();
// Sends a message to the message board
bool SendMessage(const std::string& msg);
// Function to do things from to msg received
virtual void OnNotification(const std::string& msg) = 0;
// Update
virtual void Update(double dt) = 0;
private:
// The message board
MessageBoard* mb;
};
#endif<file_sep>/Base/Source/GameObject.cpp
#include "GameObject.h"
#include "Mtx44.h"
GameObject::GameObject(GAMEOBJECT_TYPE typeValue)
: type(typeValue),
pos(0, 0, 0),
vel(0, 0, 0),
normal(0, 0, 0),
scale(1, 1, 1),
active(false),
mass(1.f)
{
}
GameObject::~GameObject()
{
}
void GameObject::SetGO(
GameObject::GAMEOBJECT_TYPE type,
Vector3 scale,
Vector3 rotate,
Vector3 pos,
bool _active)
{
Mtx44 ro;
ro.SetToRotation(rotate.y, 0, 1, 0);
ro.SetToRotation(rotate.x, 1, 0, 0);
ro.SetToRotation(rotate.z, 0, 0, 1);
this->scale = scale;
this->normal = ro * Vector3(1, 0, 0);
this->type = type;
this->pos = pos;
this->active = _active;
}
<file_sep>/Base/Source/Priest.h
#ifndef PRIEST_H_
#define PRIEST_H_
#include "GameObject.h"
#include "Messager.h"
class Guardian;
class Priest : public Messager, public GameObject
{
public:
// States
enum PRIEST_STATES
{
IDLE = 0,
HEAL,
RUN,
RESURRECT,
REPLENISH,
RETURN,
DIE
};
// Constructor
Priest();
// Destructor
~Priest();
// Update
virtual void Update(double dt);
// Finite State Machine
void FSM();
// Set guardian
inline void SetGuardian(Guardian* _guardian) { guardian = _guardian; }
std::string GetState() {
switch (currState) {
case 0:
return "IDLE";
case 1:
return "HEAL";
case 2:
return "RUN";
case 3:
return "RESURRECT";
case 4:
return "REPLENISH";
case 5:
return "RETURN";
case 6:
return "DIE";
}
return "";
}
Vector3 manaPos;
Vector3 resetPos;
private:
// Function to do things from to msg received
virtual void OnNotification(const std::string& msg);
// Current state of priest
PRIEST_STATES currState;
// Inner proximity
float innerProximity;
// Outer proximity
float outerProximity;
// Health to check if it is hit, always updated to the health in GameObject class
int nextHealth;
// Personal timer
double timer;
// float
float speed;
// Find if there are enemies within outer proximity, and return a Vector3 which is the flocking distance
Vector3 IsEnemiesInOuterP();
// Find if there are enemies within inner proximity, and return if there are enemies
bool IsEnemiesInInnerP();
// Finds and heals guardian
Guardian* guardian;
void HealsGuardian(double dt);
void RevivesGuardian(double dt);
void ReplenishMana(double dt);
// Returns to idle state
void ReturnToIdle(double dt);
};
#endif<file_sep>/Base/Source/Messager.cpp
#include "Messager.h"
#include "MessageBoard.h"
Messager::Messager()
{
mb = MessageBoard::GetInstance();
mb->AddMessager(this);
}
Messager::~Messager()
{
}
bool Messager::SendMessage(const std::string& msg)
{
mb->BroadcastMessage(msg);
return true;
}<file_sep>/Base/Source/SceneAI2.h
#ifndef SCENE_AI1_H
#define SCENE_AI1_H
#include "GameObject.h"
#include <vector>
#include "SceneBase.h"
#include <string>
using std::string;
class Priest;
class Guardian;
class Enemy;
struct Node;
class NodeManager;
class SceneAI2 : public SceneBase
{
public:
SceneAI2();
~SceneAI2();
virtual void Init();
virtual void Update(double dt);
virtual void Render();
virtual void Exit();
/************* GO ****************/
void InitGO();
void RenderGO(GameObject *go);
GameObject* FetchGO();
/*********************************/
void UpdateMouse(double dt);
void UpdateKeys(double dt);
void UpdatePhysics(double dt);
void UpdateFSM(double dt);
protected:
float m_worldWidth;
float m_worldHeight;
float textureOffset[2];
int m_objectCount;
Priest* priest;
Guardian* guardian;
Enemy* bossEnemy;
Vector3 rdmPos[5];
GameObject* npc;
Vector3 manaPos;
Vector3 manaArea;
NodeManager* nodemanager;
int AIIndex;
std::vector<Vector3> waypoints;
bool reverse;
};
#endif<file_sep>/Base/Source/SceneAI2.cpp
#include "SceneAI2.h"
// Managers
#include "Application.h"
#include "MeshBuilder.h"
#include "KeyboardController.h"
#include "GameObjectManager.h"
#include "MessageBoard.h"
// Libs
#include "GL\glew.h"
#include <fstream>
#include <iostream>
#include <math.h>
#include <sstream>
#include "Priest.h"
#include "Guardian.h"
#include "Enemy.h"
#include "Grid.h"
#include "NodeManager.h"
#include "Node.h"
#include "AStarAlgorithm.h"
using std::ifstream;
SceneAI2::SceneAI2()
{
}
SceneAI2::~SceneAI2()
{
}
void SceneAI2::Init()
{
SceneBase::Init();
//Physics code here
Math::InitRNG();
m_worldHeight = 100.f;
m_worldWidth = m_worldHeight * (float)Application::GetWindowWidth() / Application::GetWindowHeight();
m_objectCount = 0;
nodemanager = NodeManager::GetInstance();
priest = new Priest();
priest->SetGO(GameObject::GO_PRIEST, Vector3(5, 5, 5), Vector3(0, 0, 0), Vector3(100, 50, 0)); // TYPE, SCALE, ROTATION, POSITION
GameObjectManager::GetInstance()->m_goList.push_back(priest);
guardian = new Guardian();
guardian->SetGO(GameObject::GO_GUARDIAN, Vector3(5, 5, 5), Vector3(0, 0, 0), Vector3(80, 40, 0)); // TYPE, SCALE, ROTATION, POSITION
guardian->SetOriginalPosition(Vector3(80, 40, 0));
guardian->health = 100;
guardian->maxhealth = 100;
GameObjectManager::GetInstance()->m_goList.push_back(guardian);
guardian->SetPriest(priest);
priest->SetGuardian(guardian);
bossEnemy = new Enemy();
bossEnemy->SetGO(GameObject::GO_ENEMY, Vector3(5, 5, 5), Vector3(0, 0, 0), Vector3(100, 35, 0)); // TYPE, SCALE, ROTATION, POSITION
bossEnemy->health = 50;
bossEnemy->SetIsLeader(true);
GameObjectManager::GetInstance()->m_goList.push_back(bossEnemy);
manaArea.Set(20, 20, 1);
manaPos.Set(m_worldWidth / 2, 80, 0);
priest->manaPos = manaPos;
int rdm = Math::RandIntMinMax(0, GRID_COLS - 1);
Node *start; Node *goal;
for (int i = 0; i < GRID_COLS; ++i) {
for (int j = 0; j < GRID_ROWS; ++j) {
Node* node = new Node();
if (i == rdm && j == 0) {
node->grid = new Grid(Vector3((float)((GRID_SIZE >> 1) + GRID_SIZE * i), (float)((GRID_SIZE >> 1) + GRID_SIZE * j), 0), Vector3(GRID_SIZE, GRID_SIZE, -1), Grid::START);
start = node;
}
else if (i == GRID_COLS - 1 && j == ((GRID_ROWS + 1) >> 1)) {
node->grid = new Grid(Vector3((float)((GRID_SIZE >> 1) + GRID_SIZE * i), (float)((GRID_SIZE >> 1) + GRID_SIZE * j), 0), Vector3(GRID_SIZE, GRID_SIZE, -1), Grid::END);
goal = node;
}
else {
int rdm2 = Math::RandIntMinMax(0, 10);
if (rdm2 < 8)
node->grid = new Grid(Vector3((float)((GRID_SIZE >> 1) + GRID_SIZE * i), (float)((GRID_SIZE >> 1) + GRID_SIZE * j), 0), Vector3(GRID_SIZE, GRID_SIZE, -1), Grid::EMPTY);
else
node->grid = new Grid(Vector3((float)((GRID_SIZE >> 1) + GRID_SIZE * i), (float)((GRID_SIZE >> 1) + GRID_SIZE * j), 0), Vector3(GRID_SIZE, GRID_SIZE, -1), Grid::WALL);
}
nodemanager->Init(i, j, node);
}
}
if (start && goal) {
NodeManager::GetInstance()->CalculateFGHCost(start, goal);
}
waypoints = AStarAlgorithm(start, goal);
npc = new GameObject();
if (waypoints.size() > 0)
AIIndex = waypoints.size() - 1;
reverse = false;
npc->SetGO(GameObject::GO_NPC, Vector3(5, 5, 5), Vector3(0, 0, 0), Vector3(waypoints[AIIndex].x, waypoints[AIIndex].y, 1));
GameObjectManager::GetInstance()->m_goList.push_back(npc);
}
GameObject* SceneAI2::FetchGO()
{
for (std::vector<GameObject *>::iterator it = GameObjectManager::GetInstance()->m_goList.begin(); it != GameObjectManager::GetInstance()->m_goList.end(); ++it)
{
GameObject *go = *it;
if (go->active == false)
{
go->active = true;
++m_objectCount;
return go;
}
}
for (size_t count = 0; count < 10; ++count)
{
GameObjectManager::GetInstance()->m_goList.push_back(new GameObject(GameObject::GO_NONE));
}
GameObject *go = *(GameObjectManager::GetInstance()->m_goList.end() - 1);
go->active = true;
++m_objectCount;
return go;
}
void SceneAI2::UpdateMouse(double dt)
{
//Mouse Section
static bool bLButtonState = false;
if (!bLButtonState && Application::IsMousePressed(0))
{
bLButtonState = true;
std::cout << "LBUTTON DOWN" << std::endl;
}
else if (bLButtonState && !Application::IsMousePressed(0))
{
bLButtonState = false;
std::cout << "LBUTTON UP" << std::endl;
}
}
void SceneAI2::UpdateKeys(double dt)
{
if (KeyboardController::GetInstance()->IsKeyDown('W')) {
guardian->health = 0;
}
if (KeyboardController::GetInstance()->IsKeyDown('S')) {
priest->health = 0;
}
if (KeyboardController::GetInstance()->IsKeyDown('A')) {
}
if (KeyboardController::GetInstance()->IsKeyDown('D')) {
}
//
double x, y;
Application::GetCursorPos(&x, &y);
int w = Application::GetWindowWidth();
int h = Application::GetWindowHeight();
float mouseX = (float)x * m_worldWidth / w;
float mouseY = (float)(h - y) * m_worldHeight / h;
}
void SceneAI2::UpdatePhysics(double dt)
{
//Physics Simulation Section
for (std::vector<GameObject *>::iterator it = GameObjectManager::GetInstance()->m_goList.begin(); it != GameObjectManager::GetInstance()->m_goList.end(); ++it)
{
GameObject *go = (GameObject *)*it;
if (!go->active)
continue;
go->pos += go->vel * (float)dt;
float radius = go->scale.x;
if (go->pos.x < -go->scale.x)
go->pos.x = m_worldWidth + go->scale.x;
else if (go->pos.x > m_worldWidth + go->scale.x)
go->pos.x = 0;
if (go->pos.y < -go->scale.y)
go->pos.y = m_worldHeight + go->scale.y;
else if (go->pos.y > m_worldHeight + go->scale.y)
go->pos.y = 0;
//Exercise 8a: handle collision between GO_BALL and GO_BALL using velocity swap
for (std::vector<GameObject *>::iterator ho = it + 1; ho != GameObjectManager::GetInstance()->m_goList.end(); ++ho)
{
GameObject* other = (GameObject*)*ho;
if (!other->active)
continue;
GameObject* goA = go, *goB = other;
if (go->type != GameObject::GO_PLAYER)
{
if (other->type != GameObject::GO_PLAYER)
continue;
goA = other;
goB = go;
}
if (CheckCollision(goA, goB, dt)) {
CollisionResponse(goA, goB, dt);
break;
}
}
}
}
void SceneAI2::Update(double dt)
{
MessageBoard::GetInstance()->Update(dt);
fps = 1.f / (float)dt;
priest->Update(dt);
bossEnemy->Update(dt);
guardian->Update(dt);
UpdateKeys(dt);
UpdateMouse(dt);
UpdatePhysics(dt);
priest->FSM();
guardian->FSM();
bossEnemy->FSM();
if (!waypoints.empty()){
if ((npc->pos.x > waypoints[AIIndex].x - 0.2f && npc->pos.x < waypoints[AIIndex].x + 0.2f) &&
(npc->pos.y > waypoints[AIIndex].y - 0.2f && npc->pos.y < waypoints[AIIndex].y + 0.2f))
{
npc->pos = waypoints[AIIndex];
if (!reverse) {
if (AIIndex > 0) {
AIIndex--;
}
else
reverse = true;
}
else {
if (AIIndex < waypoints.size() - 1)
AIIndex++;
else
reverse = false;
}
}
Vector3 direction;
Vector3 temp;
temp.Set(waypoints[AIIndex].x, waypoints[AIIndex].y, 1);
direction = (temp - npc->pos).Normalized();
npc->pos += direction * 5 * dt;
}
}
void SceneAI2::RenderGO(GameObject *go)
{
switch (go->type)
{
case GameObject::GO_PRIEST:
{
modelStack.PushMatrix();
modelStack.Translate(go->pos.x, go->pos.y, go->pos.z);
modelStack.Scale(go->scale.x, go->scale.y, go->scale.z);
RenderMesh(meshList[PRIEST], false);
modelStack.PopMatrix();
break;
}
case GameObject::GO_GUARDIAN:
{
modelStack.PushMatrix();
modelStack.Translate(go->pos.x, go->pos.y, go->pos.z);
modelStack.Scale(go->scale.x, go->scale.y, go->scale.z);
RenderMesh(meshList[GUARDIAN], false);
modelStack.PopMatrix();
break;
}
case GameObject::GO_ENEMY:
{
modelStack.PushMatrix();
modelStack.Translate(go->pos.x, go->pos.y, go->pos.z);
modelStack.Scale(go->scale.x, go->scale.y, go->scale.z);
RenderMesh(meshList[BOSS_ENEMY], false);
modelStack.PopMatrix();
break;
}
case GameObject::GO_NPC:
{
modelStack.PushMatrix();
modelStack.Translate(go->pos.x, go->pos.y, go->pos.z);
modelStack.Scale(go->scale.x, go->scale.y, go->scale.z);
RenderMesh(meshList[NPC], false);
modelStack.PopMatrix();
break;
}
}
}
void SceneAI2::Render()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
//Calculating aspect ratio
m_worldHeight = 100.f;
m_worldWidth = m_worldHeight * (float)Application::GetWindowWidth() / Application::GetWindowHeight();
// Projection matrix : Orthographic Projection
Mtx44 projection;
projection.SetToOrtho(0, m_worldWidth, 0, m_worldHeight, -10, 10);
projectionStack.LoadMatrix(projection);
// Camera matrix
viewStack.LoadIdentity();
viewStack.LookAt(
camera.position.x, camera.position.y, camera.position.z,
camera.target.x, camera.target.y, camera.target.z,
camera.up.x, camera.up.y, camera.up.z
);
// Model matrix : an identity matrix (model will be at the origin)
modelStack.LoadIdentity();
for (size_t i = 0; i < GRID_ROWS; ++i) {
for (size_t j = 0; j < GRID_COLS; ++j) {
modelStack.PushMatrix();
modelStack.Translate(nodemanager->theNode[j][i]->grid->pos.x, nodemanager->theNode[j][i]->grid->pos.y, nodemanager->theNode[j][i]->grid->pos.z);
modelStack.Scale(nodemanager->theNode[j][i]->grid->scale.x, nodemanager->theNode[j][i]->grid->scale.y, nodemanager->theNode[j][i]->grid->scale.z);
if (nodemanager->theNode[j][i]->grid->type == Grid::START)
RenderMesh(meshList[GRID_START], false);
else if (nodemanager->theNode[j][i]->grid->type == Grid::END)
RenderMesh(meshList[GRID_END], false);
else if (nodemanager->theNode[j][i]->parent)
RenderMesh(meshList[GRID_PATH], false);
else if (nodemanager->theNode[j][i]->grid->type == Grid::WALL)
RenderMesh(meshList[GRID_WALL], false);
else if (nodemanager->theNode[j][i]->visited)
RenderMesh(meshList[GRID_VISITED], false);
else if(nodemanager->theNode[j][i]->grid->type == Grid::EMPTY)
RenderMesh(meshList[GRID_EMPTY], false);
modelStack.PopMatrix();
modelStack.PushMatrix();
std::ostringstream op;
op.str("");
op << "F:" << nodemanager->theNode[j][i]->F;
modelStack.Translate(nodemanager->theNode[j][i]->grid->pos.x - 3, nodemanager->theNode[j][i]->grid->pos.y + 4, nodemanager->theNode[j][i]->grid->pos.z );
modelStack.Scale(nodemanager->theNode[j][i]->grid->scale.x, nodemanager->theNode[j][i]->grid->scale.y, nodemanager->theNode[j][i]->grid->scale.z);
modelStack.Scale(0.3f, 0.3f, 1);
RenderText(meshList[GEO_TEXT], op.str(), Color(0, 1, 1), 0.5f);
modelStack.PopMatrix();
modelStack.PushMatrix();
op.str("");
op << "G:" << nodemanager->theNode[j][i]->G;
modelStack.Translate(nodemanager->theNode[j][i]->grid->pos.x - 3, nodemanager->theNode[j][i]->grid->pos.y + 2, nodemanager->theNode[j][i]->grid->pos.z);
modelStack.Scale(nodemanager->theNode[j][i]->grid->scale.x, nodemanager->theNode[j][i]->grid->scale.y, nodemanager->theNode[j][i]->grid->scale.z);
modelStack.Scale(0.3f, 0.3f, 1);
RenderText(meshList[GEO_TEXT], op.str(), Color(1, 1, 0), 0.5f);
modelStack.PopMatrix();
modelStack.PushMatrix();
op.str("");
op << "H:" << nodemanager->theNode[j][i]->H;
modelStack.Translate(nodemanager->theNode[j][i]->grid->pos.x - 3, nodemanager->theNode[j][i]->grid->pos.y , nodemanager->theNode[j][i]->grid->pos.z);
modelStack.Scale(nodemanager->theNode[j][i]->grid->scale.x, nodemanager->theNode[j][i]->grid->scale.y, nodemanager->theNode[j][i]->grid->scale.z);
modelStack.Scale(0.3f, 0.3f, 1);
RenderText(meshList[GEO_TEXT], op.str(), Color(1, 0, 1), 0.5f);
modelStack.PopMatrix();
}
}
modelStack.PushMatrix();
modelStack.Translate(manaPos.x, manaPos.y, manaPos.z);
modelStack.Scale(manaArea.x, manaArea.y, manaArea.z);
RenderMesh(meshList[MANA_AREA], false);
modelStack.PopMatrix();
for (std::vector<GameObject *>::iterator it = GameObjectManager::GetInstance()->m_goList.begin(); it != GameObjectManager::GetInstance()->m_goList.end(); ++it)
{
GameObject *go = (GameObject *)*it;
if (go->active)
{
RenderGO(go);
}
}
float yCoordinates = 58.f;
std::ostringstream ss;
for (size_t i = 0; i < MessageBoard::GetInstance()->GetList().size(); ++i)
{
ss.str("");
ss << i << ": Message Board receives \"" << MessageBoard::GetInstance()->GetList()[i] << "\"";
RenderTextOnScreen(meshList[GEO_TEXT], ss.str(), Color(1, 1, 0), 1.6f, 20, yCoordinates - i * 1.5f);
}
//
//
// << " \tHealth: " << bossEnemy->health
std::ostringstream ss2;
ss2.str("");
ss2 << "Priest state: " << priest->GetState() ;
RenderTextOnScreen(meshList[GEO_TEXT], ss2.str(), Color(1, 1, 0), 1, 20, 16);
ss2.str("");
ss2 << "Guardian state: " << guardian->GetState();
RenderTextOnScreen(meshList[GEO_TEXT], ss2.str(), Color(1, 1, 0), 1, 20, 14);
ss2.str("");
ss2 << "Enemy state: " << bossEnemy->GetState();
RenderTextOnScreen(meshList[GEO_TEXT], ss2.str(), Color(1, 1, 0), 1, 20, 12);
ss2.str("");
ss2 << "Priest Health: " << priest->health << " \tMana: " << priest->mana;
RenderTextOnScreen(meshList[GEO_TEXT], ss2.str(), Color(1, 1, 0), 1, 50, 16);
ss2.str("");
ss2 << "Guardian Health " << guardian->health;
RenderTextOnScreen(meshList[GEO_TEXT], ss2.str(), Color(1, 1, 0), 1, 50, 14);
ss2.str("");
ss2 << "Enemy Health: " << bossEnemy->health;
RenderTextOnScreen(meshList[GEO_TEXT], ss2.str(), Color(1, 1, 0), 1, 50, 12);
}
void SceneAI2::Exit()
{
SceneBase::Exit();
//Cleanup GameObjects
while (GameObjectManager::GetInstance()->m_goList.size() > 0)
{
GameObject *go = GameObjectManager::GetInstance()->m_goList.back();
delete go;
GameObjectManager::GetInstance()->m_goList.pop_back();
}
}<file_sep>/Base/Source/NodeManager.h
#pragma once
#include <list>
#include "SingletonTemplate.h"
#include "Node.h"
#define GRID_ROWS 10
#define GRID_COLS 4
#define GRID_SIZE 10
using std::list;
static float heuristic(Vector3 a, Vector3 b)
{
return abs(a.x - b.x) + abs(a.y - b.y);
}
struct Node;
class NodeManager : public Singleton<NodeManager>
{
friend Singleton<NodeManager>;
public:
void Init(const int width, const int height, Node* node) {
theNode[width][height] = node;
}
list<Node*> returnNeighbours(Node* node) {
int widthIndex = returnWidthIndex(node);
int heightIndex = returnHeightIndex(node);
list<Node*> results;
// LEFT NEIGHBOUR
if (widthIndex > 0) {
if (theNode[widthIndex - 1][heightIndex]->grid->type != Grid::WALL)
results.push_back(theNode[widthIndex - 1][heightIndex]);
}
if (heightIndex < GRID_ROWS - 1) {
if (theNode[widthIndex][heightIndex + 1]->grid->type != Grid::WALL)
results.push_back(theNode[widthIndex][heightIndex + 1]);
}
if (widthIndex < GRID_COLS - 1) {
if (theNode[widthIndex + 1][heightIndex]->grid->type != Grid::WALL)
results.push_back(theNode[widthIndex + 1][heightIndex]);
}
if (heightIndex > 0) {
if (theNode[widthIndex ][heightIndex - 1]->grid->type != Grid::WALL)
results.push_back(theNode[widthIndex][heightIndex - 1]);
}
return results;
};
int returnWidthIndex(Node* node) {
return (int)((node->grid->pos.x - (GRID_SIZE >> 1)) / GRID_SIZE);
}
int returnHeightIndex(Node* node) {
return (int)((node->grid->pos.y - (GRID_SIZE >> 1)) / GRID_SIZE);
}
int returnGcost(Node* start, Node* curr) {
int startWIndex = returnWidthIndex(start);
int startHIndex = returnHeightIndex(start);
int currWIndex = returnWidthIndex(curr);
int currHIndex = returnHeightIndex(curr);
int a = abs(currWIndex - startWIndex) + abs(currHIndex - startHIndex);
return a;
}
int returnHcost(Node* curr, Node* end) {
return (int)heuristic(end->grid->pos, curr->grid->pos);
}
void CalculateFGHCost(Node* start, Node* goal) {
for (size_t i = 0; i < GRID_ROWS; ++i) {
for (size_t j = 0; j < GRID_COLS; ++j) {
if (theNode[j][i]->grid->type != Grid::START || theNode[j][i]->grid->type != Grid::END)
{
theNode[j][i]->G = returnGcost(start, theNode[j][i]);
theNode[j][i]->H = returnHcost(theNode[j][i], goal);
theNode[j][i]->F = theNode[j][i]->G + theNode[j][i]->H;
}
}
}
}
//private:
Node* theNode[GRID_COLS][GRID_ROWS];
};
<file_sep>/Base/Source/MessageBoard.cpp
#include "MessageBoard.h"
#include "Messager.h"
#include <iostream>
MessageBoard::MessageBoard()
{
// Clears the list
messagerList.clear();
timer = 0.0;
}
MessageBoard::~MessageBoard()
{
}
bool MessageBoard::AddMessager(Messager* msgr)
{
// Pushes back a messager into the list
messagerList.push_back(msgr);
return true;
}
void MessageBoard::BroadcastMessage(const std::string& msg)
{
// Add the message to the queue to display it
latestMessage.push_back(msg);
// Iterate through every element to notify them
for (std::list<Messager*>::iterator it = messagerList.begin();
it != messagerList.end(); ++it)
{
// Do things in their respective onNotification(string)
(*it)->OnNotification(msg);
}
}
void MessageBoard::Update(double dt)
{
// If there is still a message being sent
if (!latestMessage.empty())
{
// Timer start counting
timer += dt;
// If timer exceeds a certain limit
if (timer > 3.0)
{
// Resets timer and pops queue
latestMessage.pop_front();
timer = 0.0;
}
}
}<file_sep>/Base/Source/GameObjectManager.h
#pragma once
#include "SingletonTemplate.h"
#include "GameObject.h"
#include <vector>
using std::vector;
class GameObjectManager : public Singleton<GameObjectManager> {
friend Singleton<GameObjectManager>;
public:
vector<GameObject*> m_goList;
};
/*********** Physics *************/
static bool CheckCollision(GameObject *go, GameObject *other, double dt);
//float CheckCollision2(GameObject* go, GameObject* other);
static void CollisionResponse(GameObject *go, GameObject *other, double dt);
/*********************************/
bool CheckCollision(GameObject *go, GameObject *other, double dt)
{
switch (other->type)
{
case GameObject::GO_PLAYER:
case GameObject::GO_GUARDIAN:
case GameObject::GO_ENEMY:
{
float lengthSquared = ((go->pos + go->vel * (float)dt) - (other->pos - other->vel *(float)dt)).LengthSquared();
float combinedRadSq = (go->scale.x + other->scale.x) * (go->scale.x + other->scale.x);
Vector3 relativeVelocity = go->vel - other->vel;
Vector3 relativeDisplacement = other->pos - go->pos;
return ((lengthSquared < combinedRadSq) && (relativeVelocity.Dot(relativeDisplacement) > 0));
break;
}
}
return false;
}
void CollisionResponse(GameObject *go, GameObject *other, double dt)
{
switch (other->type)
{
case GameObject::GO_PLAYER:
case GameObject::GO_GUARDIAN:
case GameObject::GO_ENEMY:
{
//Exercise 8b: store values in auditing variables
float m1 = go->mass;
float m2 = other->mass;
Vector3 u1 = go->vel;
Vector3 u2 = other->vel;
Vector3 u1N, u2N, N;
N = (other->pos - go->pos).Normalized();
u1N = u1.Dot(N) * N;
u2N = u2.Dot(N) * N;
go->vel = u1 + (2 * m2) / (m1 + m2) * (u2N - u1N);
other->vel = u2 + (2 * m1) / (m1 + m2) * (u1N - u2N);
break;
}
}
}
<file_sep>/Base/Source/Guardian.h
#pragma once
#include "GameObject.h"
#include "Messager.h"
#include "Priest.h"
class Priest;
class Enemy;
class Guardian : public GameObject, public Messager
{
public:
// States
enum GUARDIAN_STATES
{
IDLE = 0,
CHASE,
RETURN,
ATTACK,
BEING_HEALED,
DIE
};
// Constructor
Guardian();
// Destructor
~Guardian();
// Update
virtual void Update(double dt);
// Finite State Machine
void FSM();
inline void SetPriest(Priest* Priest){ _Priest = Priest; };
inline void SetTarget(GameObject* thetarget){ _target = thetarget; };
void SetOriginalPosition(Vector3 position);
Vector3 GetOriginalPosition();
float gethealth();
std::string GetState() {
switch (currState) {
case 0:
return "IDLE";
case 1:
return "CHASE";
case 2:
return "RETURN";
case 3:
return "ATTACK";
case 4:
return "RECOVERING";
case 5:
return "DIE";
}
return "";
}
private:
// Function to do things from to msg received
virtual void OnNotification(const std::string& msg);
// Current state of priest
GUARDIAN_STATES currState;
// Personal timer
double timer;
//A value to store it's original position
Vector3 OriginalPosition;
//This is to Check if the priest is being attacked
Priest *_Priest;
GameObject *_target;
GameObject *nearestTarget;
//This is called when the Guardian is in Return State;
void Returnposition(double dt);
void GoToPriest(double dt);
void LocateTarget();
void ChaseTarget(GameObject *target);
void CheckHP();
bool InAggroRange();
float nexthealth;
float Speed;
Vector3 direction;
float Aggrorange;
float distancefromPriest;
float distancefromoriginalposition;
float originalScale;
};
static float DistBetween(const Vector3& posOne, const Vector3& posTwo)
{
return (posOne - posTwo).Length();
}<file_sep>/Base/Source/MessageBoard.h
#ifndef MESSAGE_BOARD_H
#define MESSAGE_BOARD_H
#include "SingletonTemplate.h"
#include <string>
#include <list>
#include <deque>
class Messager;
class MessageBoard : public Singleton<MessageBoard>
{
friend Singleton<MessageBoard>;
public:
// Constructor
MessageBoard();
// Destructor
~MessageBoard();
// Adds a new item into the list of Messagers
bool AddMessager(Messager* msgr);
// Broadcast message to all messagers
void BroadcastMessage(const std::string& msg);
// Update
void Update(double dt);
// Gets queue
std::deque<std::string> GetList() { return latestMessage; }
private:
// List of messagers
std::list<Messager*> messagerList;
// Queue of messages being passed in
std::deque<std::string> latestMessage;
// Timer for it to display
double timer;
};
#endif<file_sep>/Base/Source/Guardian.cpp
#include "Guardian.h"
#include "Enemy.h"
#include "GameObjectManager.h"
#include <vector>
#include <algorithm>
#include <iostream>
using std::cout;
using std::endl;
Guardian::Guardian() :
timer(0.0),
currState(IDLE), Speed(10.0f), Aggrorange(5.f)
{
health = 100;
maxhealth = health;
nexthealth = health;
originalScale = 5;
}
Guardian::~Guardian()
{
}
void Guardian::SetOriginalPosition(Vector3 position)
{
OriginalPosition = position;
}
Vector3 Guardian::GetOriginalPosition()
{
return OriginalPosition;
}
void Guardian::FSM()
{
if (_target == nullptr)
{
return;
}
if (health <= 0)
{
currState = DIE;
}
else
{
switch (currState)
{
case CHASE:
{
break;
}
case ATTACK:
{
if (!InAggroRange())
{
currState = RETURN;
}
break;
}
case RETURN:
{
if (InAggroRange())
{
LocateTarget();
}
break;
}
case BEING_HEALED:
{
if (health == maxhealth)
{
SendMessage("UNINJURED");
currState = IDLE;
}
}
case IDLE:
{
if (health != nexthealth)
{
LocateTarget();
}
}
}
}
}
void Guardian::Update(double dt)
{
//cout << health << endl;
if (_target == nullptr || _Priest == nullptr)
{
return;
}
switch (currState)
{
case IDLE:
{
break;
}
case CHASE:
{
GoToPriest(dt);
break;
}
case RETURN:
{
Returnposition(dt);
//cout << "Returning" << endl;
break;
}
case ATTACK:
{
this->vel.SetZero();
this->normal = (_target->pos - this->pos).Normalized();
timer += dt;
if (timer > 1.f)
{
_target->health -= (float)Math::RandFloatMinMax(10.f, 15.f);
timer = 0;
}
break;
}
case BEING_HEALED:
{
break;
}
case DIE:
{
if (active) {
scale.x -= dt * 3; scale.y -= dt * 3; scale.z -= dt * 3;
if (scale.x <= Math::EPSILON) {
SendMessage("GUARDIAN DOWN");
active = false;
scale.Set(originalScale, originalScale, originalScale);
}
}
}
}
nexthealth = health;
}
void Guardian::OnNotification(const std::string& msg)
{
if (msg == "UNDER ATTACK")
{
currState = CHASE;
}
if (msg == "UNHARMED")
{
currState = RETURN;
}
if (msg == "REVIVING")
{
currState = IDLE;
active = true;
health = 100;
}
}
void Guardian::Returnposition(double dt)
{
distancefromoriginalposition = DistBetween(OriginalPosition,this->pos);
if (distancefromoriginalposition > 0.1f)
{
vel = (this->OriginalPosition - this->pos).Normalize() * Speed;
direction = vel;
this->normal = direction.Normalized();
}
else
{
this->vel.SetZero();
currState = BEING_HEALED;
CheckHP();
}
}
void Guardian::CheckHP()
{
if (health == maxhealth)
{
SendMessage("UNINJURED");
}
if (health != maxhealth)
{
SendMessage("INJURED");
}
}
void Guardian::GoToPriest(double dt)
{
distancefromPriest = DistBetween(_Priest->pos, this->pos);
if (distancefromPriest > 20.f)
{
vel = (_Priest->pos - pos).Normalize() * Speed;
direction = vel;
this->normal = direction.Normalized();
}
else if (distancefromPriest < 20.f)
{
LocateTarget();
}
}
void Guardian::LocateTarget()
{
nearestTarget = nullptr;
float nearestdistance = 100.f;
for (vector<GameObject*>::iterator it = GameObjectManager::GetInstance()->m_goList.begin(); it != GameObjectManager::GetInstance()->m_goList.end(); ++it)
{
if ((*it)->type == GO_ENEMY) {
if (((*it)->pos - pos).Length() < nearestdistance) {
nearestTarget = (*it);
nearestdistance = (nearestTarget->pos - pos).Length();
}
}
}
if (nearestTarget)
{
_target = nearestTarget;
ChaseTarget(_target);
SetTarget(_target);
}
}
void Guardian::ChaseTarget(GameObject *target)
{
float distancefromtarget = DistBetween(target->pos, this->pos);
if (distancefromtarget > 4.0f)
{
vel = (target->pos - pos).Normalize() * Speed;
direction = vel;
this->normal = direction.Normalized();
}
else
{
currState = ATTACK;
}
}
bool Guardian::InAggroRange()
{
for (std::vector<GameObject *>::iterator it = GameObjectManager::GetInstance()->m_goList.begin(); it != GameObjectManager::GetInstance()->m_goList.end(); ++it)
{
GameObject *go = (GameObject *)*it;
if (go->type == GameObject::GO_PRIEST || go->type == GameObject::GO_GUARDIAN)
continue;
if ((go->pos - pos).Length() <= Aggrorange)
{
return true;
}
}
return false;
}
float Guardian::gethealth()
{
return health;
}<file_sep>/Base/Source/GameObject.h
#ifndef GAME_OBJECT_H
#define GAME_OBJECT_H
#include "Vector3.h"
#include "Vertex.h"
struct GameObject
{
enum GAMEOBJECT_TYPE
{
GO_NONE = 0,
GO_PLAYER,
GO_PRIEST,
GO_GUARDIAN,
GO_ENEMY,
GO_NPC,
GO_TOTAL, //must be last
};
GAMEOBJECT_TYPE type;
Vector3 pos;
Vector3 vel;
Vector3 scale;
Vector3 normal;
bool active;
float mass;
int health;
int maxhealth;
int mana;
int maxmana;
GameObject(GAMEOBJECT_TYPE typeValue = GO_NONE);
virtual ~GameObject();
void SetGO(GameObject::GAMEOBJECT_TYPE type = GameObject::GO_NONE,
Vector3 scale = (1.f, 1.f, 1.f),
Vector3 rotate = (0.f, 0.f, 0.f),
Vector3 pos = (0.f, 0.f, 0.f),
bool _active = true
);
};
#endif<file_sep>/Base/Source/Enemy.h
#pragma once
#include "GameObject.h"
#include "Messager.h"
// Enemy is to demostrate collab AI and
// the AI for the other two classes. There will be hiding
// enemies that will reveal when message is received.
class Enemy : public GameObject, public Messager
{
public:
enum ENEMY_STATES
{
IDLE,
CHASE,
ATTACK,
DIE
};
// Constructor
Enemy();
// Destructor
~Enemy();
// Update
virtual void Update(double dt);
// Set isLeader
inline void SetIsLeader(const bool& set) { isLeader = set; }
// Set speed
inline void SetSpeed(const float& spd) { speed = spd; }
// Function to do things from to msg received
virtual void OnNotification(const std::string& msg);
// Finite state machine
void FSM();
std::string GetState() {
switch (currState) {
case 0:
return "IDLE";
case 1:
return "CHASE";
case 2:
return "ATTACK";
case 3:
return "DIE";
}
return "";
}
private:
// Check if it is the main enemy
bool isLeader;
// Message sent once
bool isSent;
// Speed of enemy
float speed;
// Target
GameObject* target;
// Personal timer
double timer;
// Enemy states
ENEMY_STATES currState;
// Function to chase friendly
void ChaseFriendly();
// Function to attack target
void AttackTarget(double dt);
};<file_sep>/Base/Source/Enemy.cpp
#include "Enemy.h"
#include "GameObjectManager.h"
#include <vector>
Enemy::Enemy() :
isLeader(false),
isSent(false),
speed(3.f),
currState(CHASE),
timer(0.0)
{
health = 50;
}
Enemy::~Enemy()
{
}
void Enemy::Update(double dt)
{
switch (currState)
{
case IDLE:
{
break;
}
case CHASE:
{
ChaseFriendly();
break;
}
case ATTACK:
{
AttackTarget(dt);
break;
}
case DIE:
{
scale.x -= dt; scale.y -= dt; scale.z -= dt;
if (scale.x <= Math::EPSILON) {
active = false;
}
break;
}
}
if (health <= 20 && isLeader)
{
if (!isSent) {
//SendMessage("AMBUSH");
isSent = true;
health = 0;
}
}
if (health <= 0)
{
currState = DIE;
for (vector<GameObject*>::iterator it = GameObjectManager::GetInstance()->m_goList.begin(); it != GameObjectManager::GetInstance()->m_goList.end();) {
if (*it == this) {
it = GameObjectManager::GetInstance()->m_goList.erase(it);
break;
}
else
it++;
}
}
}
void Enemy::OnNotification(const std::string& str)
{
if (str == "AMBUSH" && !isLeader)
{
if (active == false)
active = true;
}
}
void Enemy::FSM()
{
switch (currState)
{
case IDLE:
{
break;
}
case CHASE:
{
if (!target)
break;
if ((target->pos - pos).Length() <= target->scale.x + scale.x) {
currState = ATTACK;
}
break;
}
case ATTACK:
{
if (!target)
break;
if ((target->pos - pos).Length() > target->scale.x + scale.x) {
currState = CHASE;
}
break;
}
case DIE:
{
break;
}
}
}
void Enemy::ChaseFriendly()
{
Vector3 getNearestFriendly(FLT_MAX, FLT_MAX, FLT_MAX);
for (std::vector<GameObject *>::iterator it = GameObjectManager::GetInstance()->m_goList.begin(); it != GameObjectManager::GetInstance()->m_goList.end(); ++it)
{
GameObject *go = (GameObject *)*it;
if (!go->active)
continue;
if (go->type == GameObject::GO_PRIEST || go->type == GameObject::GO_GUARDIAN) {
if ((pos - go->pos).Length() < getNearestFriendly.Length()) {
getNearestFriendly = pos - go->pos;
target = (*it);
}
}
}
if (!target)
return;
vel = (target->pos - pos).Normalized() * speed;
}
void Enemy::AttackTarget(double dt)
{
if (!target || !target->active)
return;
vel.SetZero();
timer += dt;
if (timer > 1.0) {
timer = 0.0;
target->health -= 5;
}
} | 3e8b64a29bbde30ad3b816b7082f167884bbee01 | [
"C",
"C++"
]
| 19 | C | hermitlt3/AI_Asn2 | 984a7b42c8d3fa48672b0b37763fe544f6c8df56 | 170aa2e29d68b8af45d979f867c462b85ac6e3a8 |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Palin
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(GetLongestPalindrome("ABCBAHELLOHOWRACECARAREYOUILOVEUEVOLIIAMAIDOINGGOOD"));
Console.WriteLine(Factorial(5));
var l = Console.ReadLine();
}
private static int Factorial(int v)
{
if (v == 1) return 1;
return v * Factorial(v-1);
}
private static string GetLongestPalindrome(string input)
{
var longestPal = string.Empty;
for (int i = 0; i < input.Length; i++)
{
for(int j = input.Length - i; j > 0; j--)
{
var str = input.Substring(i, j -1);
if (IsPalin(str) && str.Length > longestPal.Length)
longestPal = str;
}
}
return longestPal;
}
private static bool IsPalin(string input)
{
if (input.Length < 2) return false;
for (int i = 0; i < input.Length - i; i++)
{
if (input[i] != input[input.Length - i - 1])
return false;
}
return true;
}
}
}
| 0d29135c71495265299e3e7a6d9e8cf15ba829e5 | [
"C#"
]
| 1 | C# | panwarg/CSharpExamples | ebe48b09a115eb1ff0dc888e37f0862df7a30c57 | f1792ef7ca738578beaa7b3edbe9bb76ff47f03a |
refs/heads/master | <repo_name>avdheshgarodia/opengl-animation-cs418-mp1<file_sep>/source/Makefile
#Makefile for Mp1
CC=g++
exe=mp1
all:
$(CC) mp1.cpp -o $(exe) -framework OpenGL -framework GLUT
<file_sep>/README.md
# opengl-animation-cs418-mp1
Simple Animation done in OpenGL of a dancing letter I. Linear interpolation is used to transition between keyframes.
Mp Done on Mac OS X 10.9.4
Using C++ and GLUT and OpenGL
Xcode was not used.
Compilation instructions
1. Navigate to source folder in Terminal
2. Run the MakeFile by calling make
3. Run the generated executable by calling ./mp1
The p button on the keyboard will pause or play the animation
The o button on the keyboard will toggle wireframe mode ON/OFF
The Escape button will quit the program
The link to the video demo is:
http://youtu.be/w-ZI0KAJfNM
<file_sep>/source/mp1.cpp
#include <GLUT/GLUT.h>
#include <iostream>
#include <math.h>
/*
MP1-<NAME>
CS418-Fall 2014
*/
void render(void);
void keyboard(unsigned char key, int x, int y);
void tick(int m);
//Time variable used for the sin calculations
static float t = 0.0;
//The X and Y coordinates for the Vertices of the I
static float xCo[12] = {-0.37,-0.37,0.37,0.37,0.15,0.15,0.37,0.37,-0.37,-0.37,-0.15,-0.15};
static float yCo[12] = {0.5,0.8,0.8,0.5,0.5,-0.5,-0.5,-0.8,-0.8,-0.5,-0.5,0.5};
//The order in which the Vertices are to be called for a Triangle Strip
static int fillorder[16] = {0,11,1,4,2,3,4,11,5,10,9,10,8,5,7,6};
/*The X and Y offsets for the animation,
12 rows for the 12 vertices in the I and 10 columns
for the 10 dance keyframes/positions. Theese will
be linearly interpolated in the animation
*/
static float xKey[12][10]={
/*0*/ {0.0, -0.1, -0.2 ,-0.1,0.0 ,-0.1,-0.1 ,-0.1 ,-0.1,-0.1},
/*1*/ {0.0, 0.1 , 0.0 ,0.1 ,0.2 ,0.1 ,0.0 ,-0.1 ,0.1 ,0.1 },
/*2*/ {0.0, -0.1, -0.2 ,-0.1,0.0 ,-0.1,0.1 ,0.1 ,-0.1,-0.1},
/*3*/ {0.0, 0.1 , 0.0 ,0.1 ,0.2 ,0.1 ,-0.1 ,0.1 ,0.01,0.1 },
/*4*/ {0.0, 0.0 , -0.1 ,0.0 ,0.0 ,0.0 ,0.0 ,0.1 ,0.0 ,0.0 },
/*5*/ {0.0, 0.0 , 0.1 ,0.0 ,-0.1,0.0 ,0.1 ,-0.05 ,0.0 ,0.0 },
/*6*/ {0.0, 0.1 , 0.2 ,0.1 ,0.0 ,0.1 ,0.0 ,0.1 ,0.1 ,0.1 },
/*7*/ {0.0, -0.1, 0.0 ,-0.1,-0.2,-0.1,-0.1 ,0.2 ,-0.1,-0.1},
/*8*/ {0.0, 0.1 , 0.2 ,0.1 ,0.0 ,0.1 ,0.0 ,-0.1 ,0.1 ,0.1 },
/*9*/ {0.0, -0.1, 0.0 ,-0.1,-0.2,-0.1,0.1 ,-0.1 ,-0.1,-0.1},
/*10*/ {0.0, 0.0 , 0.1 ,0.0 ,-0.1,0.0 ,0.0 ,-0.05,0.1 ,0.0 },
/*11*/ {0.0, 0.0 , -0.1 ,0.0 ,0.0 ,0.0 ,-0.1 ,0.1 ,-0.1 ,0.0}};
static float yKey[12][10]={
/*0*/ {0.0,0.1,0.0 ,0.0,0.0 ,0.0, -0.2 ,-0.1,0.0,0.0 },
/*1*/ {0.0,0.0,0.0 ,0.0,-0.1,0.0, -0.2 ,0.0 ,0.0,0.0 },
/*2*/ {0.0,-0.1,0.0 ,0.0,-0.1,0.0, -0.2 ,0.1 ,0.0,0.0 },
/*3*/ {0.0,0.0,0.0 ,0.0,0.1 ,0.0, -0.2 ,0.0 ,0.0,0.0 },
/*4*/ {0.0,-0.1,-0.1,0.0,0.0 ,0.0, -0.1 ,0.0 ,0.0,-0.3},
/*5*/ {0.0,0.1,0.1 ,0.0,-0.1,0.0, 0.1 ,0.0 ,0.0,0.3 },
/*6*/ {0.0,0.1,0.0 ,0.1,0.0 ,0.0, 0.2 ,-0.1,0.0,0.0 },
/*7*/ {0.0,-0.2,0.0 ,0.1,0.1 ,0.0, 0.2 ,0.1 ,0.0,0.0 },
/*8*/ {0.0,-0.1,0.0 ,0.1,0.0 ,0.0, 0.2 ,0.1 ,0.0,0.0 },
/*9*/ {0.0,0.1,0.0 ,0.1,0.1 ,0.0, 0.2 ,-0.1,0.0,0.0 },
/*10*/ {0.0,0.0,0.1 ,0.0,0.0 ,0.0, 0.1 ,-0.1,0.0,0.3 },
/*11*/ {0.0,-0.1,-0.1,0.0,0.0 ,0.0, -0.1 ,0.0 ,0.0,-0.3}};
//Boolean that is true when animation is running. False when animation is paused
static bool running=true;
//Boolean for wireframe On/Off
static bool wireframe=false;
//current and previous frame of the animation
static int animstepprev = 0;
static int animstep = 1;
//The current frame
static int currframe = 0;
//The amount of frames each step will use. Dance will be slower in this is higher
static int framesinstep =11;
//Dimensions of window
const static int WIDTH = 640;
const static int HEIGHT = 480;
int main(int argc, char** argv){
//initialize the window
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA);
glutInitWindowPosition(200,200);
glutInitWindowSize(WIDTH,HEIGHT);
//set title of window
glutCreateWindow("MP1: Dancing I");
glutDisplayFunc(render);
glutKeyboardFunc(keyboard);
glutTimerFunc(33,tick,0);
//Enable line smoothing
glEnable( GL_LINE_SMOOTH );
glEnable( GL_POLYGON_SMOOTH );
glHint( GL_LINE_SMOOTH_HINT, GL_NICEST );
glHint( GL_POLYGON_SMOOTH_HINT, GL_NICEST );
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
//set the line width
glLineWidth(2.7);
//set the background color to WHITE
glClearColor(1.0,1.0,1.0,1.0);
//Start the main loop
glutMainLoop();
}
/*The Tick function called every
33 milliseconds
*/
void tick(int m){
//Redraw the display
glutPostRedisplay();
if(running){
//increment the time;
t=t+.2;
//if the current frame reaches the frame limit swicth to next position
if(currframe==framesinstep){
//reset current frame
currframe=0;
//set animstepprev to current animstep and increment animstep
animstepprev=animstep;
animstep=(animstep+1)%10;
}
//increment current frame
currframe=currframe+1;
}
/*recall timer func in 33 milliseconds
redraw every 33 milliseconds which is
approximatly=1000/33=30 frames per seconds
*/
glutTimerFunc(33,tick,0);
}
void keyboard(unsigned char key, int x, int y){
//if key is 27 esacpe is pressed
if(key==27){
//if escape is pressed exit the program
exit(0);
}
//p key toggles the pause
else if(key=='p'){
running=!running;
}
//o key toggles the wireframe
else if(key=='o'){
wireframe=!wireframe;
}else if(key=='w'){
framesinstep++;
}
else if(key=='s'){
framesinstep--;
}
}
void render(void){
//x and y offsets for the vertices causes oscillations
float x= 0.03 * sin(t-1.5);
float y = 0.03 * sin(t - 0.5);
//clears the sreen so that new stuff can be drawn
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
//if wireframe is on set Polygon mode to Lines
if(wireframe==true){
glPolygonMode(GL_FRONT_AND_BACK , GL_LINE);
}
//if wireframe is on set Polygon mode to FIll
if(wireframe==false){
glPolygonMode(GL_FRONT_AND_BACK , GL_FILL);
}
//Start the triangle strip
glBegin(GL_TRIANGLE_STRIP);
//Draw the first 6 vertices
for(int i=0;i<6;i++){
//Set colors of the vertices
if(fillorder[i]==0 || fillorder[i]==3){
glColor3f(0.31,0.01,0.01);
}
else{
glColor3f(0.64,0.01,0.01);
}
//compute to x and y offsets caused by linear interpolation
//xOff = (x2 - x1)* (currframe/framesneeded)
float xOff = ((xKey[fillorder[i]][animstep] - xKey[fillorder[i]][animstepprev]) * (float)(((float)currframe) / ((float)framesinstep))) + xKey[fillorder[i]][animstepprev];
float yOff = ((yKey[fillorder[i]][animstep] - yKey[fillorder[i]][animstepprev]) * (float)(((float)currframe) / ((float)framesinstep))) + yKey[fillorder[i]][animstepprev];
//The actual vertex calls
glVertex2f(xCo[fillorder[i]]+x+xOff,yCo[fillorder[i]]+y+yOff);
}
//end the gl call
glEnd();
glBegin(GL_TRIANGLE_STRIP);
//Draw the next 4 vertices
for(int i=6;i<10;i++){
glColor3f(0.64,0.01,0.01);
float xOff = ((xKey[fillorder[i]][animstep] - xKey[fillorder[i]][animstepprev]) * (float)(((float)currframe) / ((float)framesinstep))) + xKey[fillorder[i]][animstepprev];
float yOff = ((yKey[fillorder[i]][animstep] - yKey[fillorder[i]][animstepprev]) * (float)(((float)currframe) / ((float)framesinstep))) + yKey[fillorder[i]][animstepprev];
glVertex2f(xCo[fillorder[i]]+x+xOff,yCo[fillorder[i]]+y+yOff);
}
glEnd();
glBegin(GL_TRIANGLE_STRIP);
//Draw the next 6 vertices
for(int i=10;i<16;i++){
if(fillorder[i]==5 || fillorder[i]==10){
glColor3f(0.64,0.01,0.01);
}
else{
glColor3f(0.22,0.09,0.18);
}
float xOff = ((xKey[fillorder[i]][animstep] - xKey[fillorder[i]][animstepprev]) * (float)(((float)currframe) / ((float)framesinstep))) + xKey[fillorder[i]][animstepprev];
float yOff = ((yKey[fillorder[i]][animstep] - yKey[fillorder[i]][animstepprev]) * (float)(((float)currframe) / ((float)framesinstep))) + yKey[fillorder[i]][animstepprev];
glVertex2f(xCo[fillorder[i]]+x+xOff,yCo[fillorder[i]]+y+yOff);
}
glEnd();
/*if the wireframe is false draw in
a line loop around all the vertices
*/
if(wireframe==false){
glBegin(GL_LINE_LOOP);
//set line color to black
glColor3f(0.0,0.0,0.0);
//loop through all 12 vertices
for(int i=0;i<12;i++){
float xOff = ((xKey[i][animstep] - xKey[i][animstepprev]) * (float)(((float)currframe) / ((float)framesinstep))) + xKey[i][animstepprev];
float yOff = ((yKey[i][animstep] - yKey[i][animstepprev]) * (float)(((float)currframe) / ((float)framesinstep))) + yKey[i][animstepprev];
glVertex2f(xCo[i]+x+xOff,yCo[i]+y+yOff);
}
glEnd();
}
//swap the buffers so the animation does not flicker
glutSwapBuffers();
}
| 168923097ac222ad59ff175b2c197b26be82f956 | [
"Markdown",
"Makefile",
"C++"
]
| 3 | Makefile | avdheshgarodia/opengl-animation-cs418-mp1 | aaafcd1644c7faf62d4e80ad8e14d45bb91a64fb | 902c69a89847e67b2791d9db866659da753f0850 |
refs/heads/master | <repo_name>SummerWindL/imooc-security<file_sep>/imooc-security-core/src/main/java/com/imooc/security/core/validate/code/sms/SmsCodeSender.java
package com.imooc.security.core.validate.code.sms;
/**
*@date 2018年7月14日-下午5:06:20
*@author <NAME>
*@action(作用) :短信验证码发送接口
*@instruction
*/
public interface SmsCodeSender {
void send(String mobile,String code);
}
<file_sep>/imooc-security-demo/src/main/java/com/imooc/validator/MyConstraintValidator.java
package com.imooc.validator;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import org.springframework.beans.factory.annotation.Autowired;
import com.imooc.service.HelloService;
/**
*@date 2018年6月4日-下午11:06:33
*@author <NAME>
*@action(作用)
*@instruction
*/
public class MyConstraintValidator implements ConstraintValidator<MyConstraint, Object> {
@Autowired
private HelloService service;
@Override
public void initialize(MyConstraint constraintAnnotation) {
System.out.println("my validator init");
}
@Override
public boolean isValid(Object value, ConstraintValidatorContext context) {
service.greeting("tome");
System.out.println(value);
return false;
}
}
<file_sep>/README.md
# imooc-security
##spring-security学习</br>
`day06 拦截器`</br>
`day07 wiremock伪造REST服务`</br>
`day08 自定义用户认证逻辑`</br>
`day09 个性化用户认证流程(1)`</br>
`day10 个性化用户认证流程(2)`</br>
`day11 个性化定制图形验证码`</br>
`day12 记住我配置及原理`</br>
`day13 短信验证码发送`
### 使用wiremock伪造服务
服务端:[wiremock-standalone-2.18.0.jar](http://repo1.maven.org/maven2/com/github/tomakehurst/wiremock-standalone/2.18.0/wiremock-standalone-2.18.0.jar)</br>
**指定端口启动服务**:
$ java -jar wiremock-standalone-2.18.0.jar --port 8062</br>
客户端:
[MockServer](https://github.com/SummerWindL/imooc-security/blob/master/imooc-security-demo/src/main/java/com/imooc/wiremock/MockServer.java)
### 使用swagger2开发接口</br>
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.7.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.7.0</version>
</dependency>
集成这两个工具
#### 异步处理REST服务</br>
1、使用Runnable异步处理Rest服务</br>
2、使用DeferredResult异步处理Rest服务</br>
3、异步处理配置(过滤处理)</br>
#### 伪代码</br>
* 1、
Callable<String> result = new Callable<String>() {
@Override
public String call() throws Exception {
logger.info("副线程开始");
Thread.sleep(1000);
logger.info("副线程返回");
return "success";
}
};
* 2、
*
String orderNumber = RandomStringUtils.randomNumeric(8);//生成八位随机数订单号
mockQueue.setPlaceOrder(orderNumber);//模拟放入消息队列
DeferredResult<String> result = new DeferredResult<String>();
deferredResultHolder.getMap().put(orderNumber, result);
# 使用Spring Security开发基于表单的登录
## 自定义用户认证逻辑
spring security原理
* spring security过滤器链

***
处理用户信息获取逻辑 **实现UserDetailsService**
处理用户校验逻辑 UserDetails
处理密码加密解密 PasswordEncoder(使用crypto包中的)
## 个性化用户认证流程
>1.自定义登陆页面
>

>
>2.自定义登陆成功处理
>
>3.自定义登陆失败处理
* 封装读取用户自定义properties

@ConfigurationProperties(prefix ="imooc.security")
public class SecurityProperties {
BrowserProperties browser = new BrowserProperties();
public BrowserProperties getBrowser() {
return browser;
}
public void setBrowser(BrowserProperties browser) {
this.browser = browser;
}
}
public class BrowserProperties {
private String loginPage = "/imooc-signIn.html";
public String getLoginPage() {
return loginPage;
}
public void setLoginPage(String loginPage) {
this.loginPage = loginPage;
}
}
## 个性化用户认证流程(二)
>1、自定义登陆页面 http.formLogin().loginPage("/imooc-signIn.html")
>2、自定义登陆成功处理 AuthenticationSuccessHandler
>3、自定义登陆失败处理 AuthenticationFailureHandler
* spring security 默认成功跳转继承类 SavedRequestAwareAuthenticationSuccessHandler
* spring security 默认失败跳转继承类
SimpleUrlAuthenticationFailureHandler
## 个性化定制图形验证码基于配置方式(略)
## 记住我配置及原理


> ### 配置
>1、页面添加记住我checkbox,name必须是remember-me
>
<tr>
<td colspan="2"><input name ="remember-me" type="checkbox" value="true"/>记住我</td>
</tr>
>效果
<tr>
<td colspan="2"><input name ="remember-me" type="checkbox" value="true"/>记住我</td>
</tr>
>2、BrowserProperties.java新增过期时间
>private int rememberSeconds = 3600;</br>
BrowserSecurityConfig新增 persistentTokenRepository方法</br>
``` /**
* 记住我配置
* @return
*/
@Bean
public PersistentTokenRepository persistentTokenRepository() {
JdbcTokenRepositoryImpl tokenRepository = new JdbcTokenRepositoryImpl();
tokenRepository.setDataSource(dataSource);
tokenRepository.setCreateTableOnStartup(true);//启动时系统自动建立这张表
return tokenRepository;
}
```
需要引入<br>
@Autowired
private DataSource dataSource;
@Autowired
private UserDetailsService userDetailsService;
>3、BrowserSecurityConfig的configure方法配置登陆动作<br>
`` .and()
.rememberMe()
.tokenRepository(persistentTokenRepository())
.tokenValiditySeconds(securityProperties.getBrowser().getRememberSeconds())
.userDetailsService(userDetailsService)
``
## 短信验证码发送(层级架构)
<file_sep>/imooc-security-demo/src/main/java/com/imooc/web/controller/UserController.java
package com.imooc.web.controller;
import java.util.ArrayList;
import java.util.List;
import javax.validation.Valid;
import org.apache.commons.lang.builder.ReflectionToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.access.ExceptionTranslationFilter;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.fasterxml.jackson.annotation.JsonView;
import com.imooc.dto.User;
import com.imooc.dto.UserQueryCondition;
import com.imooc.exception.UserNotExistException;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
/**
*@date 2018年5月25日-下午10:25:33
*@author <NAME>
*@action(作用)
*@instruction
*/
@RestController
@RequestMapping("/user")
public class UserController{
@GetMapping("/me")
public Object getCurrentUser(@AuthenticationPrincipal UserDetails user) {
return user;
}
@PostMapping
public User create(@Valid @RequestBody User user) {
/*if(errors.hasErrors()) {
errors.getAllErrors().stream().forEach(error -> System.out.println(error.getDefaultMessage()));;
}*/
System.out.println(user.getId());
System.out.println(user.getUsername());
System.out.println(user.getPassword());
System.out.println(user.getBirthday());
user.setId("1");
return user;
}
@PutMapping("/{id:\\d+}")
public User update(@Valid @RequestBody User user,BindingResult errors) {
if(errors.hasErrors()) {
errors.getAllErrors().stream().forEach(error -> {
// FieldError fieldError = (FieldError)error;
// String message = fieldError.getField() +" "+ error.getDefaultMessage();
System.out.println(error.getDefaultMessage());
} );
}
System.out.println(user.getId());
System.out.println(user.getUsername());
System.out.println(user.getPassword());
System.out.println(user.getBirthday());
user.setId("1");
return user;
}
@DeleteMapping("/{id:\\d+}")
public void delete(@PathVariable String id) {
System.out.println(id);
}
@GetMapping
@JsonView(User.UserSimpleView.class)
@ApiOperation(value="用户查询服务")
public List<User> query(UserQueryCondition condiction/*@RequestParam(value ="username" ,required = false,defaultValue = "tom") String nickname,*/
,@PageableDefault(page = 2,size = 17,sort="username,asc") Pageable page){
// System.out.println(nickname);
System.out.println(ReflectionToStringBuilder.toString(condiction,ToStringStyle.MULTI_LINE_STYLE) );
System.out.println(page.getPageSize());
System.out.println(page.getPageNumber());
System.out.println(page.getSort());
List<User> user = new ArrayList<>();
user.add(new User());
user.add(new User());
user.add(new User());
return user;
}
@GetMapping("/{id:\\d+}")
@JsonView(User.UserDetailView.class)
public User getInfo(@ApiParam("用户id")@PathVariable ( name = "id") String idxxx) {
// throw new UserNotExistException(idxxx);
System.out.println("进入getInfo服务");
User user = new User();
user.setUsername("tom");
return user;
}
}
| 4897f788fb5713b3c5c9f1176402f1f707d3a408 | [
"Markdown",
"Java"
]
| 4 | Java | SummerWindL/imooc-security | af67ddff963edc299f8c47912c31c73aea82f3b7 | 8a57198726836f9511c8d912e3bfcc14e34d5af5 |
refs/heads/main | <repo_name>ColeCrase/Week-8Assignment<file_sep>/Project1-Crase.py
"""
Program: Project1
Author: <NAME>
This program is to allow the user to input a number and then returns an estimate
of its square root.
"""
import math
tolerance = 0.000001
def newton(x):
"""Returns the square root of x"""
estimate = 1.0
while True:
estimate = (estimate + x / estimate) / 2
difference = abs(x - estimate ** 2)
if difference <= tolerance:
break
return estimate
def main():
"""Allows the user to obtain square roots."""
while True:
x = input("Enter a positive number or press enter/return to quit: ")
if x == "":
break
x = float(x)
print("The estimate of the square root of ", x, "is ",
round(newton(x),2))
main()
<file_sep>/README.md
# Week-8Assignment
This is my repository for week 8 assignment
<file_sep>/Project2-Crase.py
"""
Program: Project2
Author: <NAME>
This program is modify from project 1 that uses a recursive function.
As well as using the estimate of the square roote as a second argument.
"""
import math
tolerance = 0.000001
def newton(x, estimate):
"""Returns the square root of x"""
while True:
estimate = (estimate + x / estimate) / 2
difference = abs(x - estimate ** 2)
if difference <= tolerance:
return estimate
else:
return newton(x,estimate)
def main():
"""Allows the user to obtain square roots."""
while True:
x = input("Enter a positive number or press enter/return to quit: ")
if x == "":
break
x = float(x)
estimate = 1.0
print("The estimate of the square root of ", x, "is ",
round(newton(x, estimate)))
main()
<file_sep>/Project3-Crase.py
"""
Program: Project3
Author: <NAME>
This program is modify from project 2 that uses keyword arguement with
appropriate default value.
"""
import math
tolerance = 0.000001
def newton(x, estimate):
"""Returns the square root of x"""
while True:
difference = abs(x - estimate ** 2)
if difference <= tolerance:
return estimate
else:
return newton(x, (estimate + x / estimate) / 2)
def main():
"""To allow the user to obtain the square roots."""
while True:
x = input("Enter a number or press enter/return to quit: ")
if x == "":
break
x = float(x)
estimate = 1.0
print("The estimate of the square root of ", x, "is ",
round(newton(x, estimate)))
main()
| 2dcc76713c382a236ecb4404279e9bdb7039dd8b | [
"Markdown",
"Python"
]
| 4 | Python | ColeCrase/Week-8Assignment | 6480948d49d05bacdc3353eb6af2b7cbbfac700a | c690e180f6e8f4a0e7be064172baf53e05327937 |
refs/heads/main | <file_sep>class Main {
companion object {
@JvmStatic
fun main(args: Array<String>) {
val a: Int? = 1000
val b: Int? = 1000
print(a === b)
}
}
} | 22c88d1da20737d8f10240da75c6e975f67c80e0 | [
"Kotlin"
]
| 1 | Kotlin | phamVu314/100days_kot | c954dcee9f1cc45737f7cb2d22ede39bd11a2c15 | 9bc3bcccc720f8fe0701b8e565fdddd110e2f29c |
refs/heads/master | <repo_name>damianSM1997/sumaNumerosPorParametros<file_sep>/codigo.js
const arr = [4, 5, 9, 12, 13, 1, 10, 2,12];
function findSum(nums, combineNum, sum){
const sums = [];
nums.map((num, i) => { //corresponde a el numero e i al indice
for (let index = i; index < nums.length; index++) { //ciclo que termina hasta la ultima posision del areglo
if(index + combineNum > nums.length)
return
const slicedArray = nums.slice(index + 1, index+combineNum); //recorre el areglo y lo guarda a la variable slicedArray
const tempSum = slicedArray.reduce((pre,current) => pre + current , num); //parte que hace las interaciones iterador acumulativo y ahí
//uso el numero actual como valor inicial y luego voy sumando
//todos los restantes del slice,
if(sum == tempSum){ // compara y guarda los valores
sums.push([
num,
...slicedArray
])
}
}
})
return sums; //retorna el resultado deseado
}
findSum(arr, 4 , 18)
console.log(findSum(arr, 2 , 17)) | d1b02353bc9978d7263c47d2ca166caee13a73fa | [
"JavaScript"
]
| 1 | JavaScript | damianSM1997/sumaNumerosPorParametros | 1c5b62c403aa96dfa0bfd0ec9a68c334677e851a | 84229240df176c2afa08b87dae5935f0ded98734 |
refs/heads/master | <file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyDestroy : MonoBehaviour
{
public GameObject EnemyDestroyEffect;
// public GameObject HealthFollowParticle;
void OnTriggerEnter2D(Collider2D col)
{
if (col.gameObject.tag == "SwordAttackPoint")
{
SoundEffect.PlaySound("enemydeath");
Instantiate(EnemyDestroyEffect, transform.position, Quaternion.identity);
Destroy(gameObject);
}
if(col.gameObject.tag == "Bullet" ) //|| col.gameObject.tag == "Player"
{
SoundEffect.PlaySound("enemydeath");
Instantiate(EnemyDestroyEffect, transform.position, Quaternion.identity);
// Instantiate(HealthFollowParticle, transform.position, Quaternion.identity);
Destroy(gameObject);
}
}
}
| 29b5a9d59666269abe26fbfc856bdd7217b36f3f | [
"C#"
]
| 1 | C# | Santhosh-N/SwordAttack | 0e041a4a789ed7d8c86abf85eec299e57603e673 | ac669e78528dbe96026de3c157982c7d70363ca7 |
refs/heads/master | <repo_name>space-w-alker/cultaku<file_sep>/MainWindow.xaml.cs
using culTAKU.Models;
using culTAKU.ViewsAndControllers;
using culTAKU.ViewsAndControllers.Extras;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace culTAKU
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window, INotifyPropertyChanged
{
public enum APP_STATE { HOME, PLAYING, DETAILS_VIEW, ANIME_HISTORY}
internal AnimeCollection MyAnimeCollection;
internal TopOptionsBar TopBar;
internal HomeView HomeViewObject;
internal StatusDisplay statusDisplay;
internal AnimePlayer Player;
internal ContinueWatchingView ContinueWatching;
internal bool isConnected;
private APP_STATE appState;
internal APP_STATE AppState {get { return appState; } set { appState = value; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("AppState")); } }
ICollectionView animeDisplayView;
public event PropertyChangedEventHandler PropertyChanged;
public bool IsConnected
{
get { return isConnected; }
set { isConnected = value; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("IsConnected")); }
}
public ICollectionView AnimeDisplayView { get => animeDisplayView; set => animeDisplayView = value; }
public MainWindow()
{
MyAnimeCollection = CollectionHandler.LoadMyCollectionFile();
statusDisplay = new StatusDisplay();
InitializeComponent();
if (MyAnimeCollection == null || MyAnimeCollection.AllAnimePaths.Count < 1)
{
MyAnimeCollection = new AnimeCollection();
}
Misc.Miscelleneous.MainWindow = this;
TopBar = new TopOptionsBar();
HomeViewObject = new HomeView(MyAnimeCollection);
mainGrid.Children.Insert(0, HomeViewObject);
Player = new AnimePlayer();
if(MyAnimeCollection.ContinueWatching.Count > 2)
{
ContinueWatching = new ContinueWatchingView();
//ContinueWatching.LoadContinueWatching();
HomeViewObject.HomeViewGrid.Children.Insert(0, ContinueWatching);
ContinueWatching.ExitButton.Click += ExitButton_Click1;
}
HomeViewObject.MainGrid.Children.Add(TopBar);
animeDisplayView = CollectionViewSource.GetDefaultView(HomeViewObject.DataContext);
animeDisplayView.SortDescriptions.Add(new SortDescription("Rating", ListSortDirection.Descending));
animeDisplayView.SortDescriptions.Add(new SortDescription("Name", ListSortDirection.Ascending));
PropertyChanged += MainWindow_PropertyChanged;
TopBar.SearchBar.TextChanged += SearchBar_TextChanged;
TopBar.SortOption.SelectionChanged += SortOption_SelectionChanged;
HomeViewObject.anime_list.MouseDoubleClick += Anime_list_MouseDoubleClick;
HomeViewObject.anime_list.KeyUp += Anime_list_KeyUp;
Player.ExitButton.Click += ExitButton_Click;
AppState = APP_STATE.HOME;
}
private void ExitButton_Click1(object sender, RoutedEventArgs e)
{
HomeViewObject.HomeViewGrid.Children.RemoveAt(0);
ContinueWatching.CloseAll();
ContinueWatching = null;
}
private void MainWindow_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
if(e.PropertyName == "AppState")
{
if (ContinueWatching == null) return;
if(AppState == APP_STATE.HOME)
{
ContinueWatching.LoadContinueWatching();
}
else { ContinueWatching.CloseAll(); }
}
}
private void Anime_list_KeyUp(object sender, KeyEventArgs e)
{
if(e.Key == Key.Return)
{
OpenDetails();
}
}
private void Anime_list_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
OpenDetails();
}
private void BackButton_Click(object sender, RoutedEventArgs e)
{
Button back_button = (Button)sender;
back_button.Click -= BackButton_Click;
mainGrid.Children.RemoveAt(0);
mainGrid.Children.Insert(0, HomeViewObject);
AppState = APP_STATE.HOME;
}
private void ExitButton_Click(object sender, RoutedEventArgs e)
{
Player.Closing();
mainGrid.Children[0].Visibility = Visibility.Visible;
if(mainGrid.Children[0].GetType() == typeof(HomeView)) { AppState = APP_STATE.HOME; }
else if(mainGrid.Children.GetType() == typeof(DetailsView)) { AppState = APP_STATE.DETAILS_VIEW; }
mainGrid.Children.RemoveAt(1);
}
private void SortOption_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
string selection = ((TextBlock)TopBar.SortOption.SelectedItem).Text;
switch (selection)
{
case "Name":
animeDisplayView.SortDescriptions.Clear();
animeDisplayView.SortDescriptions.Add(new SortDescription("Name", ListSortDirection.Ascending));
break;
case "Rating":
animeDisplayView.SortDescriptions.Clear();
animeDisplayView.SortDescriptions.Add(new SortDescription("Rating", ListSortDirection.Descending));
animeDisplayView.SortDescriptions.Add(new SortDescription("Name", ListSortDirection.Ascending));
break;
}
}
private void SearchBar_TextChanged(object sender, TextChangedEventArgs e)
{
if (TopBar.SearchBar.Text.Length == 0) AnimeDisplayView.Filter = null;
if (String.IsNullOrWhiteSpace(TopBar.SearchBar.Text) || TopBar.SearchBar.Text.Length < 3)
{
return;
}
else
{
AnimeDisplayView.Filter = obj => ((Anime)obj).Name.IndexOf(TopBar.SearchBar.Text, StringComparison.InvariantCultureIgnoreCase) > -1;
}
}
public void PlayAnime(long animeId, int EpisodeIndex = -1, bool isContinue = false)
{
foreach(Anime anime in MyAnimeCollection.ListOfAnime)
{
if (anime.Id == animeId)
{
Player.PlayAnime(anime, EpisodeIndex, isContinue);
//mainGrid.Children.RemoveAt(0);
mainGrid.Children[0].Visibility = Visibility.Collapsed;
mainGrid.Children.Insert(1, Player);
AppState = APP_STATE.PLAYING;
}
}
}
public void OpenDetails()
{
Anime selected = (Anime)HomeViewObject.anime_list.SelectedItem;
DetailsView details = new DetailsView();
details.BackButton.Click += BackButton_Click;
details.DataContext = selected;
details.EpisodesList.DataContext = selected.ListOfEpisodes;
details.EpisodesList.ItemsSource = selected.ListOfEpisodes;
mainGrid.Children.RemoveAt(0);
mainGrid.Children.Insert(0, details);
AppState = APP_STATE.DETAILS_VIEW;
}
public void CheckInternet()
{
statusDisplay.DisplayImagePath = StatusDisplay.StatusType.LOADING;
statusDisplay.DisplayText = "Checking Internet Connection...";
try
{
OverLayer.Children.Add(statusDisplay);
}
catch(ArgumentException e)
{
return;
}
ThreadPool.QueueUserWorkItem(_ =>
{
bool conn = Misc.Miscelleneous.IsConnectionActive();
Dispatcher.BeginInvoke(new Action(()=> {
IsConnected = conn;
}));
});
}
private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
if(AppState == APP_STATE.PLAYING)
{
Player.Closing();
}
CollectionHandler.SaveMyCollectionFile(MyAnimeCollection);
}
}
}
<file_sep>/Models/AnimeCollection.cs
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace culTAKU.Models
{
[Serializable()]
public class AnimeCollection
{
public List<string> AllAnimePaths;
private Random random;
public ObservableCollection<Anime> ListOfAnime;
public ObservableCollection<AnimeEpisode> ContinueWatching;
public AnimeCollection()
{
AllAnimePaths = new List<string>();
ListOfAnime = new ObservableCollection<Anime>();
ContinueWatching = new ObservableCollection<AnimeEpisode>();
random = new Random();
}
public void AddPath(string path)
{
DirectoryInfo dir = new DirectoryInfo(path);
if (!Directory.Exists(Path.GetFullPath("Image/")))
{
Directory.CreateDirectory(Path.GetFullPath("Image/"));
}
//Unit Test This Later
foreach(DirectoryInfo anime_dir in dir.GetDirectories("*", SearchOption.TopDirectoryOnly))
{
long anime_id = (long)(random.NextDouble() * 1000000000);
string anime_path;
try
{
anime_path = anime_dir.FullName;
}
catch (NotSupportedException e)
{
continue;
}
Anime anime = new Anime(anime_id, anime_path);
anime.ParseEpisodes();
ListOfAnime.Add(anime);
}
AllAnimePaths.Add(path);
}
public void AddToContinueWatching(AnimeEpisode episode)
{
RemoveFromContinueWatching(episode);
ContinueWatching.Insert(0, episode);
if (ContinueWatching.Count > 7) ContinueWatching.RemoveAt(ContinueWatching.Count - 1);
}
public void RemoveFromContinueWatching(AnimeEpisode episode)
{
for (int i = 0; i < ContinueWatching.Count; i++)
{
if (episode.ParentAnime.Name == ContinueWatching[i].ParentAnime.Name)
{
ContinueWatching.RemoveAt(i);
}
}
}
}
}
<file_sep>/App.xaml.cs
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Markup;
namespace culTAKU
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
private int keyDownTimeShift;
private int keyDownTimeCtrl;
public App()
{
//var si = GetContentStream(new Uri("./Styles/blue_skin.xaml",UriKind.Relative));
//var rd = (ResourceDictionary)XamlReader.Load(si.Stream);
//Current.Resources.MergedDictionaries.Add(rd);
EventManager.RegisterClassHandler(typeof(Control), Window.KeyUpEvent, new KeyEventHandler(keyUp), false);
EventManager.RegisterClassHandler(typeof(Control), Window.KeyDownEvent, new KeyEventHandler(KeyDown), false);
keyDownTimeCtrl = 0;
keyDownTimeShift = 0;
}
private void KeyDown(object sender, KeyEventArgs e)
{
if(Misc.Miscelleneous.MainWindow.Player.PlayerState == ViewsAndControllers.AnimePlayer.PLAYER_STATE.STOPPED)
{
return;
}
if(e.Key == Key.Right)
{
if(Keyboard.IsKeyDown(Key.RightShift) || Keyboard.IsKeyDown(Key.LeftShift))
{
if (e.Timestamp - keyDownTimeShift < 300)
{
return;
}
keyDownTimeShift = e.Timestamp;
Misc.Miscelleneous.MainWindow.Player.AnimeMediaPlayer.Position = Misc.Miscelleneous.MainWindow.Player.AnimeMediaPlayer.Position.Add(TimeSpan.FromSeconds(3));
}
}
if (e.Key == Key.Left)
{
if (Keyboard.IsKeyDown(Key.RightShift) || Keyboard.IsKeyDown(Key.LeftShift))
{
if (e.Timestamp - keyDownTimeShift < 300)
{
return;
}
keyDownTimeShift = e.Timestamp;
Misc.Miscelleneous.MainWindow.Player.AnimeMediaPlayer.Position = Misc.Miscelleneous.MainWindow.Player.AnimeMediaPlayer.Position.Subtract(TimeSpan.FromSeconds(3));
}
}
}
private void keyUp(object sender, KeyEventArgs e)
{
if(Misc.Miscelleneous.MainWindow.AppState == culTAKU.MainWindow.APP_STATE.PLAYING)
{
if (e.Key == Key.Space)
{
Misc.Miscelleneous.MainWindow.Player.Toggle_Play_Pause();
e.Handled = true;
}
}
}
}
}
<file_sep>/Models/Anime.cs
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using culTAKU.Misc;
using System.Net;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Threading;
namespace culTAKU.Models
{
[Serializable()]
public class Anime : ObservableObject
{
public ObservableCollection<AnimeEpisode> ListOfEpisodes;
public ObservableCollection<AnimeEpisode> ListOfUnOrderedEpisodes;
private string anime_path;
private const string base_html_string = "https://myanimelist.net/search/all?q=";
private long id;
private long animeListId;
private string name;
private string synopsis;
private int episodes;
private string image_path;
private float rating;
public bool ImageFetched { get; set; }
public bool DetailsFetched { get; set; }
private AnimeEpisode lastPlayed;
public long Id
{
get { return id; }
set
{
if (id != value)
{
id = value;
OnPropertyChanged("Id");
}
}
}
public long AnimeListId
{
get { return animeListId; }
set
{
if (animeListId != value)
{
animeListId = value;
OnPropertyChanged("AnimeListId");
}
}
}
public string Name { get { return name; } set
{
if(name != value)
{
name = value;
OnPropertyChanged("Name");
}
}
}
public string Synopsis
{
get { return synopsis; }
set
{
if (synopsis != value)
{
synopsis = value;
OnPropertyChanged("Synopsis");
}
}
}
public int Episodes
{
get { return episodes; }
set
{
if (episodes != value)
{
episodes = value;
OnPropertyChanged("Episodes");
}
}
}
public string ImagePath
{
get { return image_path; }
set
{
if (image_path != value)
{
image_path = value;
OnPropertyChanged("ImagePath");
}
}
}
public float Rating
{
get { return rating; }
set
{
if(rating != value)
{
rating = value;
OnPropertyChanged("Rating");
}
}
}
public AnimeEpisode LastPlayed
{
get { return lastPlayed; }
set { lastPlayed = value; OnPropertyChanged("LastPlayed"); }
}
public bool IsPathExists { get { return Directory.Exists(anime_path); } }
public bool IsImagePathExists { get { return File.Exists(ImagePath); } }
public bool IsKnownAnime { get; set; }
public Anime() { }
public Anime(long id, string path)
{
Id = id;
anime_path = path;
name = new DirectoryInfo(anime_path).Name;
rating = 0;
ListOfEpisodes = new ObservableCollection<AnimeEpisode>();
ListOfUnOrderedEpisodes = new ObservableCollection<AnimeEpisode>();
ImagePath = "Icons/unknown.png";
ImageFetched = false;
DetailsFetched = false;
}
public void ParseEpisodes()
{
List<Regex> checks = new List<Regex> {
new Regex(@"episode.*?(?<EpisodeNumber>\d+).*?((\.avi)|(\.mp4)|(\.flv)|(\.mkv))$", RegexOptions.IgnoreCase),
new Regex(@"((eps)|(ep))( |-|_)*(?<EpisodeNumber>\d+).*?((\.avi)|(\.mp4)|(\.flv)|(\.mkv))$", RegexOptions.IgnoreCase),
new Regex(@"(?<EpisodeNumber>\d+)((\.avi)|(\.mp4)|(\.flv)|(\.mkv))$",RegexOptions.IgnoreCase),
new Regex(@"(?<EpisodeNumber>\d+).*?((\.avi)|(\.mp4)|(\.flv)|(\.mkv))$",RegexOptions.IgnoreCase)
};
Regex SearchIsVideoFile = new Regex(@".*?((\.avi)|(\.mp4)|(\.flv)|(\.mkv))$", RegexOptions.IgnoreCase);
foreach (FileInfo file in new DirectoryInfo(anime_path).GetFiles("*", SearchOption.TopDirectoryOnly))
{
int num = -1;
foreach(Regex check in checks)
{
if (check.IsMatch(file.Name))
{
num = Convert.ToInt32(check.Match(file.Name).Groups["EpisodeNumber"].Value);
break;
}
}
if (num == -1) continue;
int index = 0;
foreach(AnimeEpisode episode in ListOfEpisodes)
{
if (num < episode.EpisodeNumber)
{
break;
}
index += 1;
}
ListOfEpisodes.Insert(index, new AnimeEpisode(this, num, file.FullName));
}
}
public void FetchDetails()
{
Regex get_target_anime_url = new Regex("information(.|\n)*?href=\"(?<link>.*?)\"", RegexOptions.IgnoreCase);
Regex get_anime_id = new Regex(@"\d+");
Regex get_anime_image_url = new Regex("js-scrollfix-bottom\"(.|\n)*?<img src=\"(?<image_link>.*?)\"", RegexOptions.IgnoreCase);
Regex get_anime_synopsis = new Regex("<span itemprop=\"description\">(?<synopsis>(.|\n)*?)</span>");
Regex get_anime_rating = new Regex(@"fl-l score(.|\n)*?(?<rating>\d[.]\d+)");
Regex get_anime_episodes_count = new Regex(@">Episodes:</span>(\s|\n)*?(?<episodes>\d+)");
string search_response = Miscelleneous.GetHtml(base_html_string + Name, 10);
if (search_response == null) { return; }
string anime_url = get_target_anime_url.Match(search_response).Groups["link"].Value;
int anime_id = Int32.Parse(get_anime_id.Match(anime_url).Value);
string anime_page = Miscelleneous.GetHtml(anime_url, 10);
if(String.IsNullOrWhiteSpace(anime_page)) { return; }
string _synopsis = get_anime_synopsis.Match(anime_page).Groups["synopsis"].Value;
float _rating = 0;
try
{
_rating = float.Parse(get_anime_rating.Match(anime_page).Groups["rating"].Value);
}
catch(Exception e)
{
_rating = 0;
}
string image_url = get_anime_image_url.Match(anime_page).Groups["image_link"].Value;
int _episodes = 0;
try
{
_episodes = int.Parse(get_anime_episodes_count.Match(anime_page).Groups["episodes"].Value);
}
catch(Exception e) {
}
AnimeListId = anime_id;
Synopsis = _synopsis;
Rating = _rating;
DetailsFetched = true;
ImagePath = Miscelleneous.GetImage(image_url, anime_id, 10, false);
ImageFetched = ImagePath != null;
}
public void FetchDetailsAsync()
{
ThreadPool.QueueUserWorkItem(_=> {
FetchDetails();
});
}
}
}
<file_sep>/Misc/Converters/ImageUriConverter.cs
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Data;
namespace culTAKU.Misc.Converters
{
public class ImageUriConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if((string)value == "Image/AnimeImage-387.jpg")
{
int j = 0;
}
if (value == null || !File.Exists((string)value))
{
return Path.GetFullPath("Icons/unknown.png");
}
return Path.GetFullPath((string)value);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
<file_sep>/ViewsAndControllers/AnimePlayer.xaml.cs
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;
namespace culTAKU.ViewsAndControllers
{
/// <summary>
/// Interaction logic for AnimePlayer.xaml
/// </summary>
public partial class AnimePlayer : UserControl, INotifyPropertyChanged
{
public enum PLAYER_STATE {PLAYING, FILE_NOT_FOUND, STOPPED, PAUSED }
//private Models.Anime CurrentlyPlayingAnime;
private int currentIndex;
private Storyboard Burst;
private DispatcherTimer Timer;
private DateTime SeekUpdateTimeStamp;
private long IdleTime;
private double secondsPosition;
private bool ignoreUpdate;
private object lockObject;
public PLAYER_STATE PlayerState;
public ObservableCollection<Models.AnimeEpisode> CombinedEpisodes;
public event PropertyChangedEventHandler PropertyChanged;
public int PlayIndex
{
get { return currentIndex; }
set { currentIndex = value; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("PlayIndex")); }
}
public AnimePlayer()
{
PlayerState = PLAYER_STATE.STOPPED;
InitializeComponent();
AnimeMediaPlayer.LoadedBehavior = MediaState.Manual;
AnimeMediaPlayer.UnloadedBehavior = MediaState.Manual;
Burst = Resources["Burst"] as Storyboard;
lockObject = new object();
ignoreUpdate = false;
secondsPosition = 0;
Timer = new DispatcherTimer();
Timer.Interval = TimeSpan.FromMilliseconds(750);
Timer.Tick += Timer_Tick;
AnimeMediaPlayer.MediaOpened += AnimeMediaPlayer_MediaOpened;
AnimeMediaPlayer.MediaEnded += AnimeMediaPlayer_MediaEnded;
AnimeMediaPlayer.PreviewMouseLeftButtonUp += AnimeMediaPlayer_PreviewMouseLeftButtonUp;
AnimeMediaPlayer.PreviewMouseMove += AnimeMediaPlayer_PreviewMouseMove;
AnimeMediaPlayer.SourceUpdated += AnimeMediaPlayer_SourceUpdated;
SeekBar.ValueChanged += SeekBar_ValueChanged;
EpisodesList.MouseDoubleClick += EpisodesList_MouseDoubleClick;
}
private void EpisodesList_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
PlayNextEpisode(EpisodesList.SelectedIndex);
}
private void AnimeMediaPlayer_PreviewMouseMove(object sender, MouseEventArgs e)
{
PlayerControls.Visibility = Visibility.Visible;
IdleTime = 0;
}
private void AnimeMediaPlayer_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
ShowHideControls();
}
private void AnimeMediaPlayer_SourceUpdated(object sender, DataTransferEventArgs e)
{
PlayerState = PLAYER_STATE.STOPPED;
}
private void AnimeMediaPlayer_MediaEnded(object sender, RoutedEventArgs e)
{
PlayNextEpisode();
}
private void SeekBar_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
if (PlayerState == PLAYER_STATE.STOPPED)
{
return;
}
if (DateTime.Now.Subtract(SeekUpdateTimeStamp).TotalMilliseconds > 300)
{
lock (lockObject)
{
if (ignoreUpdate)
{
ignoreUpdate = false;
return;
}
secondsPosition = SeekBar.Value;
SeekUpdateTimeStamp = DateTime.Now;
}
}
}
private void Timer_Tick(object sender, EventArgs e)
{
lock (lockObject)
{
ignoreUpdate = true;
if (secondsPosition > 0)
{
AnimeMediaPlayer.Position = TimeSpan.FromSeconds(secondsPosition);
secondsPosition = 0;
}
SeekBar.Value = AnimeMediaPlayer.Position.TotalSeconds;
}
TimeSpan pos = AnimeMediaPlayer.Position;
TimeSpan tot = AnimeMediaPlayer.NaturalDuration.TimeSpan;
DateTime date = DateTime.Now;
Regex formatTime = new Regex(@".*? (?<str>\d*:\d*):\d*? (?<tm>.*)");
var matched = formatTime.Match(date.AddSeconds(tot.TotalSeconds - pos.TotalSeconds).ToString());
EndsAtDisplay.Text = string.Format("Ends At {0} {1}", matched.Groups["str"], matched.Groups["tm"]);
PlayTime.Text = string.Format("{0}:{1}:{2} / {3}:{4}:{5}", pos.Hours, pos.Minutes, pos.Seconds, tot.Hours, tot.Minutes, tot.Seconds);
IdleTime += 300;
if (IdleTime > 5000)
{
PlayerControls.Visibility = Visibility.Hidden;
}
}
private void AnimeMediaPlayer_MediaOpened(object sender, RoutedEventArgs e)
{
SeekBar.Maximum = AnimeMediaPlayer.NaturalDuration.TimeSpan.TotalSeconds;
Timer.Start();
PlayerState = PLAYER_STATE.PLAYING;
SetEpisodeStatus(Models.AnimeEpisode.STATUS.WATCHING_NOW, CombinedEpisodes[PlayIndex]);
CurrentPlayingDisplay.Text = string.Format("{0} Episode {1}", CombinedEpisodes[PlayIndex].ParentAnime.Name, CombinedEpisodes[PlayIndex].EpisodeNumber);
IdleTime = 0;
}
private void PlayButton_Click(object sender, RoutedEventArgs e)
{
Toggle_Play_Pause();
}
public void PlayAnime(Models.Anime anime, int EpisodeIndex = -1, bool isContinue = false)
{
PlayerState = PLAYER_STATE.STOPPED;
CombinedEpisodes = new ObservableCollection<Models.AnimeEpisode>(anime.ListOfEpisodes.Concat(anime.ListOfUnOrderedEpisodes));
EpisodesList.DataContext = CombinedEpisodes;
if (EpisodeIndex == -1) PlayIndex = 0;
else PlayIndex = EpisodeIndex;
AnimeMediaPlayer.Source = new Uri(CombinedEpisodes[PlayIndex].EpisodePath, UriKind.Absolute);
AnimeMediaPlayer.Play();
if (isContinue)
{
AnimeMediaPlayer.Position = CombinedEpisodes[PlayIndex].StoppedAt.Subtract(TimeSpan.FromSeconds(3));
}
SeekUpdateTimeStamp = DateTime.Now;
}
public void PlayNextEpisode(int index = -1)
{
Timer.Stop();
if (PlayerState != PLAYER_STATE.STOPPED)
{
if (100.0 * AnimeMediaPlayer.Position.TotalSeconds / AnimeMediaPlayer.NaturalDuration.TimeSpan.TotalSeconds > 85)
{
SetEpisodeStatus(Models.AnimeEpisode.STATUS.WATCHED, CombinedEpisodes[PlayIndex]);
}
else
{
SetEpisodeStatus(Models.AnimeEpisode.STATUS.WATCHING, CombinedEpisodes[PlayIndex]);
}
CombinedEpisodes[PlayIndex].StoppedAt = AnimeMediaPlayer.Position;
}
AnimeMediaPlayer.Stop();
PlayerState = PLAYER_STATE.STOPPED;
if (index == -1)
{
PlayIndex = (PlayIndex + 1) % CombinedEpisodes.Count;
}
else
{
PlayIndex = index;
}
AnimeMediaPlayer.Source = new Uri(CombinedEpisodes[PlayIndex].EpisodePath, UriKind.Absolute);
AnimeMediaPlayer.Play();
}
public void PlayPreviousEpisode()
{
Timer.Stop();
if (PlayerState != PLAYER_STATE.STOPPED)
{
if (100.0 * AnimeMediaPlayer.Position.TotalSeconds / AnimeMediaPlayer.NaturalDuration.TimeSpan.TotalSeconds > 85)
{
SetEpisodeStatus(Models.AnimeEpisode.STATUS.WATCHED, CombinedEpisodes[PlayIndex]);
}
else
{
SetEpisodeStatus(Models.AnimeEpisode.STATUS.WATCHING, CombinedEpisodes[PlayIndex]);
}
CombinedEpisodes[PlayIndex].StoppedAt = AnimeMediaPlayer.Position;
}
AnimeMediaPlayer.Stop();
PlayerState = PLAYER_STATE.STOPPED;
PlayIndex = PlayIndex - 1;
if (PlayIndex == -1) PlayIndex = CombinedEpisodes.Count - 1;
AnimeMediaPlayer.Source = new Uri(CombinedEpisodes[PlayIndex].EpisodePath, UriKind.Absolute);
AnimeMediaPlayer.Play();
}
public void Play_Pressed()
{
AnimeMediaPlayer.Play();
Burst.Begin(PlayButtonPathScreen, true);
PlayerState = PLAYER_STATE.PLAYING;
}
public void Pause_Pressed()
{
Burst.Begin(PauseButtonPathScreen, true);
AnimeMediaPlayer.Pause();
PlayerState = PLAYER_STATE.PAUSED;
}
public void Toggle_Play_Pause()
{
if (PlayerState == PLAYER_STATE.PLAYING)
{
Pause_Pressed();
}
else if (PlayerState == PLAYER_STATE.PAUSED)
{
Play_Pressed();
}
}
public void ShowHideControls()
{
if (PlayerControls.Visibility == Visibility.Visible)
{
PlayerControls.Visibility = Visibility.Hidden;
}
else if (PlayerControls.Visibility == Visibility.Hidden)
{
PlayerControls.Visibility = Visibility.Visible;
}
}
private void SetEpisodeStatus(Models.AnimeEpisode.STATUS status, Models.AnimeEpisode episode)
{
if(episode.Status != Models.AnimeEpisode.STATUS.WATCHED)
{
episode.Status = status;
}
}
public void Closing()
{
Timer.Stop();
if (PlayerState != PLAYER_STATE.STOPPED)
{
if (100.0 * AnimeMediaPlayer.Position.TotalSeconds / AnimeMediaPlayer.NaturalDuration.TimeSpan.TotalSeconds > 85)
{
SetEpisodeStatus(Models.AnimeEpisode.STATUS.WATCHED, CombinedEpisodes[PlayIndex]);
}
else
{
SetEpisodeStatus(Models.AnimeEpisode.STATUS.WATCHING, CombinedEpisodes[PlayIndex]);
}
Misc.Miscelleneous.MainWindow.MyAnimeCollection.AddToContinueWatching(CombinedEpisodes[PlayIndex]);
CombinedEpisodes[PlayIndex].StoppedAt = AnimeMediaPlayer.Position;
CombinedEpisodes[PlayIndex].ParentAnime.LastPlayed = CombinedEpisodes[PlayIndex];
}
Models.CollectionHandler.SaveMyCollectionFile(Misc.Miscelleneous.MainWindow.MyAnimeCollection);
AnimeMediaPlayer.Close();
CombinedEpisodes = null;
}
private void NextButton_Click(object sender, RoutedEventArgs e)
{
PlayNextEpisode();
}
public void PreviousButton_Click(object sender, RoutedEventArgs e)
{
PlayPreviousEpisode();
}
}
}
<file_sep>/ViewsAndControllers/DetailsView.xaml.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace culTAKU.ViewsAndControllers
{
/// <summary>
/// Interaction logic for DetailsView.xaml
/// </summary>
public partial class DetailsView : UserControl
{
public DetailsView()
{
InitializeComponent();
EpisodesList.MouseDoubleClick += EpisodesList_MouseDoubleClick;
ContinueButton.Click += ContinueButton_Click;
}
private void ContinueButton_Click(object sender, RoutedEventArgs e)
{
if (EpisodesList.Items.Count < 1) return;
Models.Anime selected = ((Models.AnimeEpisode)EpisodesList.Items[0]).ParentAnime;
if (selected.LastPlayed == null) return;
Misc.Miscelleneous.MainWindow.PlayAnime(selected.Id, selected.ListOfEpisodes.IndexOf(selected.LastPlayed), true);
}
private void EpisodesList_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
if (EpisodesList.SelectedItem == null) return;
Models.Anime selected = ((Models.AnimeEpisode)EpisodesList.SelectedItem).ParentAnime;
Misc.Miscelleneous.MainWindow.PlayAnime(selected.Id, EpisodesList.SelectedIndex);
}
}
}
<file_sep>/ViewsAndControllers/Extras/StatusDisplay.xaml.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Animation;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace culTAKU.ViewsAndControllers.Extras
{
/// <summary>
/// Interaction logic for StatusDisplay.xaml
/// </summary>
public partial class StatusDisplay : UserControl, INotifyPropertyChanged
{
public enum StatusType { CAUTION, ERROR, LOADING}
private string displayText;
private Storyboard RotateLoadingImage;
public event PropertyChangedEventHandler PropertyChanged;
public string DisplayText
{
get { return displayText; }
set
{
displayText = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("DisplayText"));
}
}
public StatusType DisplayImagePath
{
set
{
string full = System.IO.Path.GetFullPath(String.Format("Icons/{0}.png",value.ToString().ToLower()));
if(full == System.IO.Path.GetFullPath("Icons/loading.png"))
{
RotateLoadingImage.Begin(image, true);
}
else
{
int m = 1;
RotateLoadingImage.Remove(image);
RotateLoadingImage.Stop(image);
}
image.Source = new BitmapImage(new Uri(full, UriKind.Absolute));
}
}
public StatusDisplay()
{
InitializeComponent();
RotateLoadingImage = (Storyboard)Resources["RotateLoadingImage"];
DisplayText = "Loading...";
DisplayImagePath = StatusType.LOADING;
}
}
}
<file_sep>/Misc/Miscelleneous.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
namespace culTAKU.Misc
{
public static class Miscelleneous
{
private const string AnimeListUrl = "https://myanimelist.net/";
public static culTAKU.MainWindow MainWindow;
public static string GetHtml(string url, int totalRetry)
{
string html = string.Empty;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Uri.EscapeUriString(url));
HttpWebResponse response = null;
request.AutomaticDecompression = DecompressionMethods.GZip;
StreamReader reader;
int retryCount = 0;
while (true)
{
try
{
response = (HttpWebResponse)request.GetResponse();
}
catch (WebException e)
{
if(retryCount == totalRetry)
{
return null;
}
Console.WriteLine(e.Status);
Thread.Sleep(1000 * retryCount + 1);
retryCount += 1;
continue;
}
Stream stream = response.GetResponseStream();
reader = new StreamReader(stream);
break;
}
html = reader.ReadToEnd();
return html;
}
public static bool IsConnectionActive()
{
string returnHtml = GetHtml(AnimeListUrl, 0);
if (returnHtml == null) return false;
else return true;
}
public static string GetImage(string url, int id, int totalRetry, bool IgnoreCurrentImage=true)
{
string image_location = string.Format("Image/AnimeImage-{0}.jpg", id);
if (!IgnoreCurrentImage && File.Exists(image_location))
{
return image_location;
}
using (WebClient client = new WebClient())
{
int RetryCount = 0;
while (true)
{
try
{
client.DownloadFile(new Uri(url), Path.GetFullPath(image_location));
return image_location;
}
catch (WebException e)
{
if (RetryCount == totalRetry)
{
return null;
}
Thread.Sleep(1000 * RetryCount + 1);
RetryCount += 1;
continue;
}
}
}
}
}
}
<file_sep>/Models/CollectionHandler.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading.Tasks;
namespace culTAKU.Models
{
public static class CollectionHandler
{
private static string filePath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"./MyCollection/SavedCollection.bin";
public static void SaveMyCollectionFile(AnimeCollection MyAnimeCollection)
{
Directory.CreateDirectory(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "//MyCollection");
Stream file;
try
{
file = File.Create(filePath);
}
catch (System.IO.IOException e)
{
return;
}
BinaryFormatter serializer = new BinaryFormatter();
serializer.Serialize(file, MyAnimeCollection);
}
public static AnimeCollection LoadMyCollectionFile()
{
if (File.Exists(filePath))
{
using (Stream file = File.OpenRead(filePath))
{
BinaryFormatter deserializer = new BinaryFormatter();
try
{
return (AnimeCollection)deserializer.Deserialize(file);
}
catch(SerializationException e)
{
return null;
}
}
}
return null;
}
}
}
<file_sep>/ViewsAndControllers/Extras/ContinueWatchingView.xaml.cs
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Windows.Threading;
using System.IO;
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;
namespace culTAKU.ViewsAndControllers.Extras
{
/// <summary>
/// Interaction logic for ContinueWatchingView.xaml
/// </summary>
public partial class ContinueWatchingView : UserControl
{
public ObservableCollection<Models.Anime> ContinueWatchingList;
DispatcherTimer Timer;
public ContinueWatchingView()
{
InitializeComponent();
PreviewContinuePlaying.LoadedBehavior = MediaState.Manual;
PreviewContinuePlaying.UnloadedBehavior = MediaState.Manual;
ContinueWatchingList = new ObservableCollection<Models.Anime>();
Timer = new DispatcherTimer();
Timer.Interval = TimeSpan.FromSeconds(10);
Timer.Tick += Timer_Tick;
ListContinue.DataContext = ContinueWatchingList;
ListContinue.ItemsSource = ContinueWatchingList;
ListContinue.SelectionChanged += ListContinue_SelectionChanged;
ContinueWatchingButton.Click += ContinueWatchingButton_Click;
}
private void ContinueWatchingButton_Click(object sender, RoutedEventArgs e)
{
if(ListContinue.SelectedItem != null)
{
Models.Anime anime = (Models.Anime)ListContinue.SelectedItem;
Misc.Miscelleneous.MainWindow.PlayAnime(anime.Id, anime.ListOfEpisodes.IndexOf(anime.LastPlayed), true);
}
}
private void Timer_Tick(object sender, EventArgs e)
{
ListContinue.SelectedIndex = (ListContinue.SelectedIndex + 1) % ContinueWatchingList.Count;
}
private void ListContinue_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
Timer.Stop();
PreviewContinuePlaying.Stop();
Models.AnimeEpisode lastPlayed = null;
try
{
lastPlayed = ((Models.Anime)ContinueWatchingList[ListContinue.SelectedIndex]).LastPlayed;
ContinueWatchingText.Text = string.Format("Continue Watching {0} Episode {1}", lastPlayed.ParentAnime.Name, lastPlayed.EpisodeNumber);
}
catch (ArgumentOutOfRangeException error)
{
return;
}
PreviewContinuePlaying.Source = new Uri(lastPlayed.EpisodePath, UriKind.Absolute);
PreviewContinuePlaying.Play();
PreviewContinuePlaying.Position = lastPlayed.StoppedAt.Subtract(TimeSpan.FromSeconds(12));
Timer.Start();
}
public void CloseAll()
{
Timer.Stop();
PreviewContinuePlaying.Stop();
}
public void LoadContinueWatching()
{
ContinueWatchingList.Clear();
Timer.Stop();
foreach(Models.AnimeEpisode episode in Misc.Miscelleneous.MainWindow.MyAnimeCollection.ContinueWatching)
{
ContinueWatchingList.Add(episode.ParentAnime);
}
ListContinue.SelectedIndex = 0;
Timer.Start();
}
}
}
<file_sep>/ViewsAndControllers/HomeView.xaml.cs
using culTAKU.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Forms;
using System.Threading;
using System.Windows.Shapes;
using System.ComponentModel;
namespace culTAKU.ViewsAndControllers
{
/// <summary>
/// Interaction logic for DefaultView.xaml
/// </summary>
public partial class HomeView : System.Windows.Controls.UserControl, INotifyPropertyChanged
{
private AnimeCollection MyAnimeCollection;
private int fetchedCount;
public int FetchedCount { get { return fetchedCount; } set { fetchedCount = value; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("FetchedCount")); } }
private object fetchCountLock;
private bool isFetching;
public HomeView()
{
InitializeComponent();
}
public HomeView(AnimeCollection animeCollection)
{
MyAnimeCollection = animeCollection;
InitializeComponent();
if(MyAnimeCollection == null || MyAnimeCollection.AllAnimePaths.Count < 1)
{
selectFolderView.Visibility = Visibility.Visible;
}
DataContext = MyAnimeCollection.ListOfAnime;
anime_list.ItemsSource = MyAnimeCollection.ListOfAnime;
fetchedCount = 0;
fetchCountLock = new object();
isFetching = false;
Misc.Miscelleneous.MainWindow.TopBar.FetchAllDetailsButton.Click += FetchAllDetailsButton_Click;
}
private void FetchAllDetailsButton_Click(object sender, RoutedEventArgs e)
{
FetchAllAnime();
}
public event PropertyChangedEventHandler PropertyChanged;
public void FetchAllAnime()
{
if (isFetching) return;
isFetching = true;
Misc.Miscelleneous.MainWindow.PropertyChanged += InternetStateChanged;
Misc.Miscelleneous.MainWindow.CheckInternet();
}
public void InternetStateChanged(object sender, PropertyChangedEventArgs e)
{
if(e.PropertyName == "IsConnected")
{
Misc.Miscelleneous.MainWindow.PropertyChanged -= InternetStateChanged;
if (Misc.Miscelleneous.MainWindow.IsConnected)
{
Misc.Miscelleneous.MainWindow.statusDisplay.DisplayText = "Fetching Anime Details...";
Misc.Miscelleneous.MainWindow.statusDisplay.DisplayImagePath = Extras.StatusDisplay.StatusType.LOADING;
PropertyChanged += HomeView_PropertyChanged;
foreach(Anime anime in MyAnimeCollection.ListOfAnime)
{
if (anime.DetailsFetched && anime.ImageFetched)
{
lock (fetchCountLock)
{
FetchedCount += 1;
continue;
}
}
ThreadPool.QueueUserWorkItem(_ =>
{
anime.FetchDetails();
Dispatcher.Invoke(new Action(() =>
{
lock (fetchCountLock)
{
FetchedCount += 1;
}
}));
});
}
}
else
{
Misc.Miscelleneous.MainWindow.statusDisplay.DisplayText = "Connection Error. Unable to fetch Anime details";
Misc.Miscelleneous.MainWindow.statusDisplay.DisplayImagePath = Extras.StatusDisplay.StatusType.ERROR;
isFetching = false;
Misc.Miscelleneous.MainWindow.OverLayer.Children.Remove(Misc.Miscelleneous.MainWindow.statusDisplay);
}
}
}
private void HomeView_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
if(e.PropertyName == "FetchedCount")
{
Misc.Miscelleneous.MainWindow.statusDisplay.DisplayText = string.Format("Fetching Anime Details... {0}/{1}", FetchedCount, Misc.Miscelleneous.MainWindow.MyAnimeCollection.ListOfAnime.Count);
if(FetchedCount == Misc.Miscelleneous.MainWindow.MyAnimeCollection.ListOfAnime.Count)
{
PropertyChanged -= HomeView_PropertyChanged;
FetchedCount = 0;
isFetching = false;
Misc.Miscelleneous.MainWindow.statusDisplay.DisplayText = "Done";
Misc.Miscelleneous.MainWindow.statusDisplay.DisplayImagePath = Extras.StatusDisplay.StatusType.CAUTION;
Misc.Miscelleneous.MainWindow.OverLayer.Children.Remove(Misc.Miscelleneous.MainWindow.statusDisplay);
}
}
}
private void SelectFolder_Click(object sender, RoutedEventArgs e)
{
using (var dialog = new FolderBrowserDialog())
{
if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
MyAnimeCollection.AddPath(dialog.SelectedPath);
FetchAllAnime();
selectFolderView.Visibility = Visibility.Collapsed;
}
}
}
}
}
<file_sep>/Styles/dark_skin.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
namespace culTAKU.Styles
{
partial class dark_skin : System.Windows.ResourceDictionary
{
public dark_skin()
{
InitializeComponent();
}
private void PlayButton_Click(object sender, System.Windows.RoutedEventArgs e)
{
FrameworkElement source = (FrameworkElement)e.Source;
Misc.Miscelleneous.MainWindow.PlayAnime((long)source.Tag);
}
}
}
<file_sep>/Models/AnimeEpisode.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using culTAKU.Models;
namespace culTAKU.Models
{
[Serializable()]
public class AnimeEpisode : INotifyPropertyChanged
{
[field:NonSerialized()]
public event PropertyChangedEventHandler PropertyChanged;
public enum STATUS { WATCHING_NOW, LAST_PLAYED, WATCHING, WATCHED, NEW, MISSING_LINK }
private readonly Anime parentAnime;
private TimeSpan stoppedAt;
private STATUS status;
public Anime ParentAnime { get { return parentAnime; } }
public int EpisodeNumber { get; }
public string EpisodePath { get; }
public TimeSpan StoppedAt { get { return stoppedAt; } set { stoppedAt = value; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("StoppedAt")); } }
public STATUS Status { get { return status; } set { status = value; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Status")); } }
public bool IsPathExists { get { return Directory.Exists(EpisodePath); } }
public AnimeEpisode(Anime parent_anime, int episodeNumber, string episodePath)
{
parentAnime = parent_anime;
EpisodeNumber = episodeNumber;
EpisodePath = episodePath;
stoppedAt = new TimeSpan();
status = STATUS.NEW;
}
}
}
<file_sep>/Misc/ObservableObject.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace culTAKU.Misc
{
[Serializable()]
public abstract class ObservableObject : INotifyPropertyChanged
{
[field:NonSerialized()]
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string PropName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(PropName));
}
}
}
| 1389fbb51f4c3e7ff8514d33fe4d3b26db42606c | [
"C#"
]
| 15 | C# | space-w-alker/cultaku | 837f720de24b6bfde5069bb87a3decbd00bc59c4 | a7b1d39969f5fa35efd1e3ca1cf164d5f77f4322 |
refs/heads/master | <repo_name>zdobrenen/BudWatch<file_sep>/arduino/lib/FlowMeter/FlowMeter.h
/**
* Flow Meter
*/
#ifndef FLOWMETER_H
#define FLOWMETER_H
#include "Arduino.h"
/**
* FlowSensorProperties
*/
typedef struct {
String name;
String type;
unsigned int power_pin;
unsigned int digital_pin;
double capacity; //!< capacity, upper limit of flow rate (in l/min)
double kFactor; //!< "k-factor" (in (pulses/s) / (l/min)), e.g.: 1 pulse/s = kFactor * l/min
double mFactor[10]; //!< multiplicative correction factor near unity, "meter factor" (per decile of flow)
double thresholdUp;
double thresholdDown;
} FlowSensorProperties;
extern FlowSensorProperties UncalibratedSensor;
/**
* FlowMeter
*/
class FlowMeter {
public:
FlowMeter(FlowSensorProperties prop = UncalibratedSensor);
void setup();
void start();
void stop();
String getName();
String getType();
int getState();
unsigned int getPowerPin();
unsigned int getDigitalPin();
double getThresholdUp();
double getThresholdDown();
double getCurrentFlowrate();
double getCurrentVolume();
double getTotalFlowrate();
double getTotalVolume();
void read(unsigned long duration = 1000);
void count();
void reset();
FlowMeter* setTotalDuration(unsigned long totalDuration);
FlowMeter* setTotalVolume(double totalVolume);
FlowMeter* setTotalCorrection(double totalCorrection);
unsigned long getCurrentDuration();
double getCurrentFrequency();
double getCurrentError();
unsigned long getTotalDuration();
double getTotalError();
protected:
byte _state;
FlowSensorProperties _properties;
unsigned long _currentDuration;
double _currentFrequency;
double _currentFlowrate = 0.0f;
double _currentVolume = 0.0f;
double _currentCorrection;
unsigned long _totalDuration = 0.0f;
double _totalVolume = 0.0f;
double _totalCorrection = 0.0f;
volatile unsigned long _currentPulses = 0;
};
#endif // FLOWMETER_H
<file_sep>/arduino/src/main.cpp
#include "Arduino.h"
#include "FlowMeter.h"
#include "LevelMeter.h"
#include "SoilMeter.h"
#include "WaterPump.h"
#include "WaterValve.h"
#ifndef LED_BUILTIN
#define LED_BUILTIN 13
#endif
// define digital pin variables
const int DIGITAL_1 = 2;
const int DIGITAL_2 = 4;
const int DIGITAL_3 = 7;
const int DIGITAL_4 = 8;
const int DIGITAL_5 = 12;
const int DIGITAL_6 = 13;
// define interrupt pin variables
const int INTERRUPT_1 = 0;
// define mosfet pin variables
const int MOSFET_1 = 3;
const int MOSFET_2 = 5;
const int MOSFET_3 = 6;
const int MOSFET_4 = 9;
const int MOSFET_5 = 10;
const int MOSFET_6 = 11;
// define analog pin variable
const int ANALOG_1 = A1;
const int ANALOG_2 = A2;
const int ANALOG_3 = A3;
const int ANALOG_4 = A4;
const int ANALOG_5 = A5;
// define device/power pin assignment
int PUMP_PWR_PIN = MOSFET_1; // Water pump power pin (12V)
int VLVE_PWR_PIN = MOSFET_2; // Water valve power pin (12V)
int FANS_PWR_PIN = MOSFET_3; // Fans power pin (12V)
int LEVL_PWR_PIN = MOSFET_4; // Level sensor power pin (5V)
int SOIL_PWR_PIN = MOSFET_4; // Soil sensor power pin (5V)
int FLOW_PWR_PIN = MOSFET_5; // Water flow sensor power pin (5V)
// define device/analog pin assignment
int LEVL_ANA_PIN = ANALOG_1;
int SOIL_ANA_PIN = ANALOG_2;
// define device/digital pin assignment
int FLOW_PWM_PIN = DIGITAL_1;
// define device/interrupt pin assignment
int FLOW_INT_PIN = INTERRUPT_1;
// define device properties
FlowSensorProperties flowSensorProps = {
"flow_meter",
"sensor",
FLOW_PWR_PIN,
FLOW_PWM_PIN,
3.0f,
3.846f,
{1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
3.00f,
1.50f
};
LevelSensorProperties levelSensorProps = {
"level_meter",
"sensor",
LEVL_PWR_PIN,
LEVL_ANA_PIN,
15.0f,
05.0f
};
SoilSensorProperties soilSensorProps = {
"soil_meter",
"sensor",
SOIL_PWR_PIN,
SOIL_ANA_PIN,
600,
200
};
WaterPumpProperties waterPumpProps = {
"water_pump",
"pump",
PUMP_PWR_PIN
};
WaterValveProperties waterValveProps = {
"water_valve",
"valve",
VLVE_PWR_PIN
};
// init device objects
FlowMeter flowMeter = FlowMeter(flowSensorProps);
LevelMeter levelMeter = LevelMeter(levelSensorProps);
SoilMeter soilMeter = SoilMeter(soilSensorProps);
WaterPump waterPump = WaterPump(waterPumpProps);
WaterValve waterValve = WaterValve(waterValveProps);
void WaterFlowISR() {
flowMeter.count();
}
void setup()
{
Serial.begin(9600);
flowMeter.setup();
levelMeter.setup();
soilMeter.setup();
waterPump.setup();
waterValve.setup();
attachInterrupt(FLOW_INT_PIN, WaterFlowISR, RISING);
flowMeter.start();
levelMeter.start();
soilMeter.start();
flowMeter.reset();
levelMeter.reset();
soilMeter.reset();
}
// define main loop global variables
long period = 1000;
long lastTime = 0;
void loop()
{
long currentTime = millis();
long duration = currentTime - lastTime;
flowMeter.read(duration);
delay(10);
levelMeter.read(duration);
delay(10);
soilMeter.read(duration);
delay(10);
Serial.println("soil meter: " + String(soilMeter.getCurrentValue()));
Serial.println("flow meter: " + String(flowMeter.getCurrentFlowrate()));
Serial.println("level meter: " + String(levelMeter.getCurrentHeight()));
if (soilMeter.getCurrentValue() >= soilMeter.getThresholdUp() &&
levelMeter.getCurrentHeight() >= levelMeter.getThresholdUp()) {
// Doesn't need water
if (waterPump.getState() != LOW) {
waterPump.stop();
}
delay(150000);
if (waterValve.getState() != HIGH) {
waterValve.start();
}
delay(100000);
}
else if (soilMeter.getCurrentValue() < soilMeter.getThresholdDown() &&
levelMeter.getCurrentHeight() < levelMeter.getThresholdDown()) {
// Needs water
if (waterPump.getState() != HIGH) {
waterPump.start();
}
if (waterValve.getState() != LOW) {
waterValve.stop();
}
}
else {
// something's running
if (waterPump.getState() == HIGH) {
if (levelMeter.getCurrentHeight() >= levelMeter.getThresholdUp()) {
waterPump.stop();
}
}
if (waterValve.getState() == HIGH) {
if (flowMeter.getCurrentFlowrate() <= flowMeter.getThresholdDown()) {
waterValve.stop();
}
}
}
lastTime = currentTime;
delay(period);
}
<file_sep>/arduino/lib/WaterValve/WaterValve.cpp
/*
* Water Valve
*/
#include "Arduino.h"
#include "WaterValve.h"
WaterValve::WaterValve(WaterValveProperties prop) :
_properties(prop)
{
}
void WaterValve::setup() {
pinMode(this->_properties.power_pin, OUTPUT);
this->_state = LOW;
}
void WaterValve::start() {
if (this->_state != HIGH) {
digitalWrite(this->_properties.power_pin, HIGH);
this->_state = HIGH;
}
}
void WaterValve::stop() {
if (this->_state != LOW) {
digitalWrite(this->_properties.power_pin, LOW);
this->_state = LOW;
}
}
String WaterValve::getName() {
return this->_properties.name;
}
String WaterValve::getType() {
return this->_properties.type;
}
int WaterValve::getState() {
return this->_state;
}
unsigned int WaterValve::getPowerPin() {
return this->_properties.power_pin;
}
WaterValveProperties DefaultValveProperties = {};
<file_sep>/arduino/lib/WaterPump/WaterPump.cpp
/*
* Water Pump
*/
#include "Arduino.h"
#include "WaterPump.h"
WaterPump::WaterPump(WaterPumpProperties prop) :
_properties(prop)
{
}
void WaterPump::setup() {
pinMode(this->_properties.power_pin, OUTPUT);
this->_state = LOW;
}
void WaterPump::start() {
if (this->_state != HIGH) {
digitalWrite(this->_properties.power_pin, HIGH);
this->_state = HIGH;
}
}
void WaterPump::stop() {
if (this->_state != LOW) {
digitalWrite(this->_properties.power_pin, LOW);
this->_state = LOW;
}
}
String WaterPump::getName() {
return this->_properties.name;
}
String WaterPump::getType() {
return this->_properties.type;
}
int WaterPump::getState() {
return this->_state;
}
unsigned int WaterPump::getPowerPin() {
return this->_properties.power_pin;
}
WaterPumpProperties DefaultPumpProperties = {};
<file_sep>/arduino/lib/WaterValve/WaterValve.h
/**
WaterValve
*/
#ifndef WATERVALVE_H
#define WATERVALVE_H
#include "Arduino.h"
typedef struct {
String name;
String type;
unsigned int power_pin;
} WaterValveProperties;
extern WaterValveProperties DefaultValveProperties;
class WaterValve {
public:
WaterValve(WaterValveProperties prop = DefaultValveProperties);
void setup();
void start();
void stop();
String getName();
String getType();
int getState();
unsigned int getPowerPin();
protected:
byte _state;
WaterValveProperties _properties;
};
#endif // WATERVALVE_H
<file_sep>/arduino/lib/LevelMeter/LevelMeter.h
/**
WaterLevel
*/
#ifndef LEVELMETER_H
#define LEVELMETER_H
#include "Arduino.h"
typedef struct {
String name;
String type;
unsigned int power_pin;
unsigned int analog_pin;
double thresholdUp;
double thresholdDown;
} LevelSensorProperties;
extern LevelSensorProperties DefaultLevelProperties;
class LevelMeter {
public:
LevelMeter(
LevelSensorProperties prop = DefaultLevelProperties
);
void setup();
void start();
void reset();
void stop();
void read(unsigned long duration);
String getName();
String getType();
int getState();
unsigned int getPowerPin();
unsigned int getAnalogPin();
double getThresholdUp();
double getThresholdDown();
unsigned int getCurrentValue();
unsigned int getCurrentHeight();
unsigned long getCurrentDuration();
unsigned long getTotalDuration();
protected:
byte _state;
unsigned int _currentValue;
unsigned int _currentHeight;
unsigned long _currentDuration;
unsigned long _totalDuration;
LevelSensorProperties _properties;
};
#endif // WATERLEVEL_H
<file_sep>/arduino/lib/FlowMeter/FlowMeter.cpp
/*
* Flow Meter
*/
#include "Arduino.h"
#include "FlowMeter.h"
#include <math.h>
FlowMeter::FlowMeter(FlowSensorProperties prop) :
_properties(prop)
{
}
void FlowMeter::setup() {
pinMode(this->_properties.power_pin, OUTPUT);
pinMode(this->_properties.digital_pin, INPUT_PULLUP);
this->_state = LOW;
}
void FlowMeter::start() {
if (this->_state != HIGH) {
digitalWrite(this->_properties.power_pin, HIGH);
this->_state = HIGH;
this->reset();
}
}
void FlowMeter::stop() {
if (this->_state != LOW) {
digitalWrite(this->_properties.power_pin, LOW);
this->_state = LOW;
this->reset();
}
}
String FlowMeter::getName() {
return this->_properties.name;
}
int FlowMeter::getState() {
return this->_state;
}
String FlowMeter::getType() {
return this->_properties.type;
}
double FlowMeter::getThresholdUp() {
return this->_properties.thresholdUp;
}
double FlowMeter::getThresholdDown() {
return this->_properties.thresholdDown;
}
double FlowMeter::getCurrentFlowrate() {
return this->_currentFlowrate;
}
double FlowMeter::getCurrentVolume() {
return this->_currentVolume;
}
double FlowMeter::getTotalFlowrate() {
return this->_totalVolume / (this->_totalDuration / 1000.0f) * 60.0f;
}
double FlowMeter::getTotalVolume() {
return this->_totalVolume;
}
void FlowMeter::read(unsigned long duration) {
/* sampling and normalisation */
double seconds = duration / 1000.0f;
cli();
double frequency = this->_currentPulses / seconds;
this->_currentPulses = 0;
sei();
/* determine current correction factor (from sensor properties) */
unsigned int decile = floor(10.0f * frequency / (this->_properties.capacity * this->_properties.kFactor));
unsigned int ceiling = 9;
this->_currentCorrection = this->_properties.kFactor / this->_properties.mFactor[min(decile, ceiling)];
/* update current calculations: */
this->_currentFlowrate = frequency / this->_currentCorrection;
this->_currentVolume = this->_currentFlowrate / (60.0f/seconds);
/* update statistics: */
this->_currentDuration = duration;
this->_currentFrequency = frequency;
this->_totalDuration += duration;
this->_totalVolume += this->_currentVolume;
this->_totalCorrection += this->_currentCorrection * duration;
}
void FlowMeter::count() {
this->_currentPulses++;
}
void FlowMeter::reset() {
cli();
this->_currentPulses = 0;
sei();
this->_currentFrequency = 0.0f;
this->_currentDuration = 0.0f;
this->_currentFlowrate = 0.0f;
this->_currentVolume = 0.0f;
this->_currentCorrection = 0.0f;
}
unsigned int FlowMeter::getPowerPin() {
return this->_properties.power_pin;
}
unsigned int FlowMeter::getDigitalPin() {
return this->_properties.digital_pin;
}
unsigned long FlowMeter::getCurrentDuration() {
return this->_currentDuration;
}
double FlowMeter::getCurrentFrequency() {
return this->_currentFrequency;
}
double FlowMeter::getCurrentError() {
return (this->_properties.kFactor / this->_currentCorrection - 1) * 100;
}
unsigned long FlowMeter::getTotalDuration() {
return this->_totalDuration;
}
double FlowMeter::getTotalError() {
return (this->_properties.kFactor / this->_totalCorrection * this->_totalDuration - 1) * 100;
}
FlowMeter* FlowMeter::setTotalDuration(unsigned long totalDuration) {
this->_totalDuration = totalDuration;
return this;
}
FlowMeter* FlowMeter::setTotalVolume(double totalVolume) {
this->_totalVolume = totalVolume;
return this;
}
FlowMeter* FlowMeter::setTotalCorrection(double totalCorrection) {
this->_totalCorrection = totalCorrection;
return this;
}
FlowSensorProperties UncalibratedSensor = {"flow_meter", "sensor", 3, 2, 60.0f, 5.0f, {1, 1, 1, 1, 1, 1, 1, 1, 1, 1}, 0.0f, 3.0f};
<file_sep>/arduino/lib/WaterPump/WaterPump.h
/**
WaterPump
*/
#ifndef WATERPUMP_H
#define WATERPUMP_H
#include "Arduino.h"
typedef struct {
String name;
String type;
unsigned int power_pin;
} WaterPumpProperties;
extern WaterPumpProperties DefaultPumpProperties;
class WaterPump {
public:
WaterPump(WaterPumpProperties prop = DefaultPumpProperties);
void setup();
void start();
void stop();
String getName();
String getType();
int getState();
unsigned int getPowerPin();
protected:
byte _state;
WaterPumpProperties _properties;
};
#endif // WATERPUMP_H
<file_sep>/arduino/lib/SoilMeter/SoilMeter.cpp
/*
* Soil Meter
*/
#include "Arduino.h"
#include "SoilMeter.h" // https://github.com/sekdiy/FlowMeter
SoilMeter::SoilMeter(SoilSensorProperties prop) :
_properties(prop)
{
}
void SoilMeter::setup() {
pinMode(this->_properties.power_pin, OUTPUT);
this->_state = LOW;
}
void SoilMeter::start() {
if (this->_state != HIGH) {
digitalWrite(this->_properties.power_pin, HIGH);
this->_state = HIGH;
}
}
void SoilMeter::stop() {
if (this->_state != LOW) {
digitalWrite(this->_properties.power_pin, LOW);
this->_state = LOW;
}
}
void SoilMeter::reset() {
}
void SoilMeter::read(unsigned long duration) {
/* sampling and normalization */
double seconds = duration / 1000.0f;
this->_currentValue= analogRead(this->_properties.analog_pin);
/* update statistics: */
this->_currentDuration = duration;
this->_totalDuration += duration;
}
String SoilMeter::getName() {
return this->_properties.name;
}
String SoilMeter::getType() {
return this->_properties.type;
}
int SoilMeter::getState() {
return this->_state;
}
unsigned int SoilMeter::getPowerPin() {
return this->_properties.power_pin;
}
unsigned int SoilMeter::getAnalogPin() {
return this->_properties.analog_pin;
}
double SoilMeter::getThresholdUp() {
return this->_properties.thresholdUp;
}
double SoilMeter::getThresholdDown() {
return this->_properties.thresholdDown;
}
unsigned int SoilMeter::getCurrentValue() {
return this->_currentValue;
}
SoilSensorProperties DefaultSoilProperties = {};
<file_sep>/arduino/lib/LevelMeter/LevelMeter.cpp
/*
* Water Level
*/
#include "Arduino.h"
#include "LevelMeter.h" // https://github.com/sekdiy/FlowMeter
LevelMeter::LevelMeter(LevelSensorProperties prop) :
_properties(prop)
{
}
void LevelMeter::setup() {
pinMode(this->_properties.power_pin, OUTPUT);
this->_state = LOW;
}
void LevelMeter::start() {
if (this->_state != HIGH) {
digitalWrite(this->_properties.power_pin, HIGH);
this->_state = HIGH;
}
}
void LevelMeter::reset() {
}
void LevelMeter::stop() {
if (this->_state != LOW) {
digitalWrite(this->_properties.power_pin, LOW);
this->_state = LOW;
}
}
void LevelMeter::read(unsigned long duration) {
/* sampling and normalization */
double seconds = duration / 1000.0f;
this->_currentValue = analogRead(this->_properties.analog_pin);
if (this->_currentValue <= 480) {
this->_currentHeight = 0.0f;
}
else if (this->_currentValue > 480 && this->_currentValue <= 530) {
this->_currentHeight = 5.0f;
}
else if (this->_currentValue > 530 && this->_currentValue <= 615) {
this->_currentHeight = 10.0f;
}
else if (this->_currentValue > 615 && this->_currentValue <= 660) {
this->_currentHeight = 15.0f;
}
else if (this->_currentValue > 660 && this->_currentValue <= 680) {
this->_currentHeight = 20.0f;
}
else if (this->_currentValue > 680 && this->_currentValue <= 690) {
this->_currentHeight = 25.0f;
}
else if (this->_currentValue > 690 && this->_currentValue <= 700) {
this->_currentHeight = 30.0f;
}
else if (this->_currentValue > 700 && this->_currentValue <= 705) {
this->_currentHeight = 35.0f;
}
else if (this->_currentValue > 705) {
this->_currentHeight = 40.0f;
}
/* update statistics: */
this->_currentDuration = duration;
this->_totalDuration += duration;
}
String LevelMeter::getName() {
return this->_properties.name;
}
int LevelMeter::getState() {
return this->_state;
}
String LevelMeter::getType() {
return this->_properties.type;
}
double LevelMeter::getThresholdUp() {
return this->_properties.thresholdUp;
}
double LevelMeter::getThresholdDown() {
return this->_properties.thresholdDown;
}
unsigned int LevelMeter::getPowerPin() {
return this->_properties.power_pin;
}
unsigned int LevelMeter::getAnalogPin() {
return this->_properties.analog_pin;
}
unsigned int LevelMeter::getCurrentValue() {
return this->_currentValue;
}
unsigned int LevelMeter::getCurrentHeight() {
return this->_currentHeight;
}
unsigned long LevelMeter::getCurrentDuration() {
return this->_currentDuration;
}
unsigned long LevelMeter::getTotalDuration() {
return this->_totalDuration;
}
LevelSensorProperties DefaultLevelProperties = {};
<file_sep>/README.md
# BudWatch
#Re-Imaging:
source: https://www.raspberrypi.org/documentation/installation/installing-images/mac.md
#IP-Locating
source: https://www.raspberrypi.org/documentation/remote-access/ip-address.md
<file_sep>/arduino/lib/SoilMeter/SoilMeter.h
/**
* Soil Meter
*/
#ifndef SOILMETER_H
#define SOILMETER_H
#include "Arduino.h"
typedef struct {
String name;
String type;
unsigned int power_pin;
unsigned int analog_pin;
double thresholdUp;
double thresholdDown;
} SoilSensorProperties;
extern SoilSensorProperties DefaultSoilProperties;
class SoilMeter {
public:
SoilMeter(
SoilSensorProperties prop = DefaultSoilProperties
);
void setup();
void start();
void reset();
void stop();
void read(unsigned long duration);
String getName();
String getType();
int getState();
unsigned int getPowerPin();
unsigned int getAnalogPin();
double getThresholdUp();
double getThresholdDown();
unsigned int getCurrentValue();
protected:
byte _state;
unsigned int _currentValue;
unsigned long _currentDuration;
unsigned long _totalDuration;
SoilSensorProperties _properties;
};
#endif // WATERLEVEL_H
| 562eebee1a785ce15431f2681703253d1601ece0 | [
"Markdown",
"C++"
]
| 12 | C++ | zdobrenen/BudWatch | 7ba1cb7df6a81d1c0ebee00f9ae1ad1060e27b93 | 2aea4a15285ded94c64cdb9fb1d342e6cbe0ca49 |
refs/heads/master | <file_sep>#include <stdio.h>
#include <stdlib.h>
void printMatrix(double ***mat, int n, int m) {
double **matrix = *mat;
printf("Matrix:\n");
int i, j;
for (i = 0; i < n; i ++) {
for (j = 0; j < m; j++){
printf("%lf\t", matrix[i][j]);
}
printf("\n");
}
return;
}
int main(int argc, char *argv[]){
if (argc < 2) {
printf("Need argument\n");
return -1;
}
char *filename = argv[1];
FILE *file = fopen(filename, "r");
int n, m;
fscanf(file, "%d\n", &n);
fscanf(file, "%d\n", &m);
double **matrix = (double**) malloc(sizeof(double*) * n);
int i, j;
for (i = 0; i < n; i++) {
matrix[i] = (double*) malloc(sizeof(double) * m);
}
for (i = 0; i < n; i++) {
for (j = 0; j < m; j++) {
matrix[i][j] = 0;
}
}
printf("matrix 0,0 = %lf\n", matrix[0][0]);
int x = sizeof(matrix[0][0]);
printMatrix(&matrix, n, m);
return 0;
}<file_sep>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// Node stores index of tag in the relevant set of cache and the next node in LL
typedef struct node {
long long int value;
struct node *next;
} Node;
// inserts node into LL of relevant set where the front holds the least-recently-used and the back holds most-recently-used
void insert(Node **lru, int set, long long int val) {
Node *ptr = lru[set];
while (ptr->next != NULL)
ptr = ptr->next;
Node *temp = (Node*) malloc(sizeof(Node));
temp->value = val;
temp->next = NULL;
ptr->next = temp;
return;
}
// updates node after a cache hit
void update(Node **lru, int set, long long int val) {
Node *ptr = lru[set], *prev = NULL;
if (ptr->next == NULL)
return;
while (ptr != NULL) {
if (ptr->value == val)
break;
prev = ptr;
ptr = ptr->next;
}
if (prev == NULL)
lru[set] = ptr->next;
else
prev->next = ptr->next;
free(ptr);
insert(lru, set, val);
return;
}
// log base 2 utility
int mlog2(int value) {
if (value < 1)
return 0;
int count = 0;
while (value != 1) {
value = value/2;
count++;
}
return count;
}
// checks if given tag value is in cache and return index of tag; also if value = 0, returns the next unused line in the cache if any remain
int contains(long long int **arr, int lines, int setNum, long long int value) {
int i;
for (i = 0; i < lines; i++) {
if (arr[setNum][i] == value)
return i;
}
return -1;
}
// free LRU nodes
void freeList(Node **lru, int sets) {
Node *ptr, *temp;
int i;
for (i = 0; i < sets; i++) {
ptr = lru[i];
while (ptr != NULL) {
temp = ptr;
ptr = ptr->next;
free(temp);
}
}
return;
}
int main(int argc, char *argv[]){
// store cache and block sizes
int cacheSize = atoi(argv[1]), blockSize = atoi(argv[2]), opt;
if (cacheSize < 1) {
printf("Invalid argument format(s) - A\n");
return 1;
}
if (blockSize < 1 || blockSize > cacheSize) {
printf("Invalid argument format(s) - B\n");
return 1;
}
char *policy = argv[3], *p1 = "fifo", *p2 = "lru";
// determine eviction policy
if (!strcmp(policy, p1)) {
opt = 1;
}
else {
if (strcmp(policy, p2)) {
printf("Invalid argument format(s) - C\n");
return 1;
}
else
opt = 2;
}
char *assoc = argv[4], *filename = argv[5];
int lines = cacheSize/blockSize, sets, i = 6, j;
// manual string parser to determine associativity
if (strlen(assoc) < 5) {
printf("Invalid argument format(s) - D\n");
return 1;
}
else if (strlen(assoc) == 6)
sets = lines;
else if (strlen(assoc) == 5)
sets = 1;
else {
while (assoc[i] != '\0') {
i++;
}
i -= 5;
char temp[i];
int t = 6;
for (j = 0; j < i; j++){
temp[j] = assoc[t++];
}
temp[j] = '\0';
sets = lines/atoi(temp);
}
int setlines = lines/sets;
// create 2D array of ints to store the tag of each address, where col = set and row = cache line
long long int **arr = (long long int**) malloc(sizeof(long long int*) * sets);
// create 1D array to track FIFO index for each set
int *fifo = (int*) malloc(sizeof(int) * sets);
// create array of Linked Lists where each index corresponds to each set's LL that holds the order of LRU addresses;
Node **lru = (Node**) malloc(sizeof(Node*) * sets);
// initialize relevant eviction policy
if (opt == 1) {
if (fifo == NULL || arr == NULL) {
printf("Out of memory - A1\n");
return 1;
}
for (i = 0; i < sets; i++) {
arr[i] = (long long int*) malloc(sizeof(long long int) * setlines);
if (arr[i] == NULL) {
printf("Out of memory - B1\n");
return 1;
}
for (j = 0; j < setlines; j++)
arr[i][j] = 0;
fifo[i] = 0;
}
}
else {
if (lru == NULL || arr == NULL) {
printf("Out of memory - A2\n");
return 1;
}
for (i = 0; i < sets; i++) {
arr[i] = (long long int*) malloc(sizeof(long long int) * setlines);
if (arr[i] == NULL) {
printf("Out of memory - B2\n");
return 1;
}
for (j = 0; j < setlines; j++)
arr[i][j] = 0;
lru[i] = (Node*) malloc(sizeof(Node));
if (lru[i] == NULL) {
printf("Out of memory - C\n");
return 1;
}
lru[i]->value = 0;
lru[i]->next = NULL;
}
}
// open file
FILE *file = fopen(filename, "r");
if (file == NULL) {
printf("Invalid argument format(s) - E\n");
return 1;
}
char c;
long long int value, tag, temptag;
int index, blockOffset, setOffset, set, hits = 0, misses = 0, reads = 0, writes = 0, t;
Node *temp;
blockOffset = mlog2(blockSize);
setOffset = mlog2(sets);
// scan through input file line by line
while (fscanf(file, "%c %llx\n", &c, &value) && c != '#') {
// get set value
set = (value >> blockOffset) & ((1 << (setOffset)) - 1);
// get tag value
tag = value >> (setOffset + blockOffset);
// switch based on eviction policy
switch (opt) {
case 1:
// switch on R or W
switch (c) {
case 'R':
// check if in cache
if (contains(arr, setlines, set, tag) != -1){
hits++;
}
else {
misses++;
reads++;
// if not in cache, check if any unused lines left
t = contains(arr, setlines, set, 0);
if (t != -1) {
// set next available unused line to missed address; address now in cache
arr[set][t] = tag;
}
else {
// if no unused lines left, need to evict; fifo[set] holds next index of set to evict
arr[set][fifo[set]] = tag;
// increment fifo[set] to next index for future eviction and check if at the last line of the set; if so, reset to index 0
fifo[set]++;
if (fifo[set] == setlines)
fifo[set] = 0;
}
}
break;
// repeat above steps for case W; increment writes
case 'W':
writes++;
if (contains(arr, setlines, set, tag) != -1){
hits++;
}
else {
misses++;
reads++;
t = contains(arr, setlines, set, 0);
if (t != -1) {
arr[set][t] = tag;
}
else {
arr[set][fifo[set]] = tag;
fifo[set]++;
if (fifo[set] == setlines)
fifo[set] = 0;
}
}
break;
}
break;
// case 2 = LRU policy
// I was off by a small amount for most LRU cases, I couldn't figure out why
case 2:
switch (c) {
case 'R':
// check if in cache
t = contains(arr, setlines, set, tag);
if (t != -1){
hits++;
// given address is in cache at arr[set][t], update set's corresponding LRU linked list so this index is moved to most-recently-used position of LL
update(lru, set, tag);
}
else {
misses++;
reads++;
// check if any unused lines; if so, insert this index into set's LRU LL at most-recently-used position
t = contains(arr, setlines, set, 0);
if (t != -1) {
arr[set][t] = tag;
insert(lru, set, tag);
}
else {
// given no unused lines, evict; LRU index of this set is at the front of LRU's LL for this set
temptag = lru[set]->value;
// overwrite cache line at LRU index
t = contains(arr, setlines, set, temptag);
arr[set][t] = tag;
// insert index into most-recently-used positon in LRU LL
insert(lru, set, tag);
// if only one node in LRU LL, no update needed
if (lru[set]->next != NULL) {
// save old front of LL
temp = lru[set];
// update LRU front to new least-recently-used index
lru[set] = lru[set]->next;
// free old front node
free(temp);
}
}
}
break;
// repeat above for case W
case 'W':
writes++;
t = contains(arr, setlines, set, tag);
if (t != -1){
hits++;
update(lru, set, tag);
}
else {
misses++;
reads++;
t = contains(arr, setlines, set, 0);
if (t != -1) {
arr[set][t] = tag;
insert(lru, set, tag);
}
else {
temptag = lru[set]->value;
t = contains(arr, setlines, set, temptag);
arr[set][t] = tag;
insert(lru, set, tag);
if (lru[set]->next != NULL) {
temp = lru[set];
lru[set] = lru[set]->next;
free(temp);
}
}
}
break;
}
break;
}
}
freeList(lru, sets);
free(arr);
free(fifo);
printf("Memory reads: %d\nMemory writes: %d\nCache hits: %d\nCache misses: %d\n", reads, writes, hits, misses);
return 0;
}
<file_sep>#include <stdio.h>
#include <stdlib.h>
void printMatrix(double ***mat, int n, int m) {
double **matrix = *mat;
printf("Matrix:\n");
int i, j;
for (i = 0; i < n; i ++) {
for (j = 0; j < m; j++){
printf("%lf\t", matrix[i][j]);
}
printf("\n");
}
return;
}
double** transpose (double ***mat, int n, int m) {
double **matrix = *mat;
double **tmat = (double**) malloc(sizeof(double*) * m);
if (tmat == NULL) {
printf("Out of memory A\n");
return NULL;
}
int i, j;
for (i = 0; i < m; i++) {
tmat[i] = (double*) malloc(sizeof(double) * n);
if (tmat[i] == NULL) {
printf("Out of memory B\n");
return NULL;
}
}
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
tmat[i][j] = matrix[j][i];
}
}
//double*** ret = tmat;
return tmat;
}
double** multiply(double ***mat1, int n1, int m1, double ***mat2, int n2, int m2) {
if (m1 != n2) {
printf("Invalid input matrices\n");
return NULL;
}
double **A = *mat1;
double **B = *mat2;
double **pmat = (double**) malloc(sizeof(double*) * n1);
if (pmat == NULL) {
printf("Out of memory C\n");
return NULL;
}
int h, i, j, k;
for (i = 0; i < n1; i++) {
pmat[i] = (double*) malloc(sizeof(double) * m2);
if (pmat[i] == NULL) {
printf("Out of memory D\n");
return NULL;
}
}
double sum = 0;
for (i = 0; i < n1; i++) {
for (j = 0; j < m2; j++) {
for (k = 0; k < n2; k++) {
sum += A[i][k] * B[k][j];
}
pmat[i][j] = sum;
sum = 0;
}
}
//printf("Matrix product: \n");
//printMatrix(&pmat, n1, m2);
//double ***temp = pmat;
return pmat;
}
double** rowReduce(double ***mat, int n, int m) {
double **matrix = *mat;
int i, j, k, a, b;
double c, temp;
for (i = 0; i < (n-1); i++) {
temp = matrix[i][i];
for (a = i; a < m; a++) {
matrix[i][a] = matrix[i][a]/temp;
}
for (j = i+1; j < n; j++) {
c = matrix[j][i]/matrix[i][i];
for (k = i; k < m; k++) {
matrix[j][k] = matrix[j][k] - (c*matrix[i][k]);
}
}
//printMatrix(&matrix, n, m);
}
//printf("rref step 1\n");
//printMatrix(&matrix, n, m);
for (a = (n-1); a >= 0; a--) {
temp = matrix[a][a];
for (b = a; b < m; b++) {
matrix[a][b] = matrix[a][b]/temp;
}
for (i = (n-1); i >= 0; i--) {
for (j = (i-1); j >= 0; j--) {
c = matrix[j][i]/matrix[i][i];
for (k = i; k < m; k++) {
matrix[j][k] = matrix[j][k] - (c*matrix[i][k]);
}
}
}
//printMatrix(&matrix, n, m);
}
// printf("rref final:\n");
// printMatrix(&matrix, n, m);
return matrix;
}
double** inverse(double ***mat, int n, int m){
double **matrix = *mat;
double **inv = (double**) malloc(sizeof(double*) * n);
if (inv == NULL){
printf("Out of memory\n");
return NULL;
}
int i, j;
for (i = 0; i < n; i++) {
inv[i] = (double*) malloc(sizeof(double) * m * 2);
if (inv[i] == NULL){
printf("Out of memory\n");
return NULL;
}
}
for (i = 0; i < n; i++){
for (j = 0; j < (2*m); j++){
if (i == j-m)
inv[i][j] = 1;
else if (j < m)
inv[i][j] = matrix[i][j];
else
inv[i][j] = 0;
}
}
// printf("Inv mat: \n");
// printMatrix(&inv, n, (2*m));
double **tmat = rowReduce(&inv, n, (2*m));
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++){
inv[i][j] = tmat[i][j+n];
}
}
return inv;
}
int main(int argc, char *argv[]){
if (argc < 2) {
printf("Need argument\n");
return -1;
}
char *filename = argv[1];
char *testfile = argv[2];
FILE *file = fopen(filename, "r");
FILE *tfile = fopen(testfile, "r");
int n, m;
fscanf(file, "%d\n", &m);
m++;
fscanf(file, "%d\n", &n);
double **matrix = (double**) malloc(sizeof(double*) * n);
double **y = (double**) malloc(sizeof(double*) * n);
if (matrix == NULL || y == NULL) {
printf("Out of memory E\n");
return -1;
}
int i, j;
for (i = 0; i < n; i++) {
matrix[i] = (double*) malloc(sizeof(double) * m);
if (matrix[i] == NULL) {
printf("Out of memory F\n");
return -1;
}
}
for (i = 0; i < n; i++) {
y[i] = (double*) malloc(sizeof(double));
if (y[i] == NULL) {
printf("Out of memory F\n");
return -1;
}
}
for (i = 0; i < n; i++) {
for (j = 0; j < m; j++) {
if (j == 0){
fscanf(file, "%lf,", &y[i][0]);
matrix[i][j] = 1;
continue;
}
else
fscanf(file, "%lf,", &matrix[i][j]);
}
fscanf(file, "\n");
}
printf("Y vector: \n");
printMatrix(&y, n, 1);
printf("Original: \n");
printMatrix(&matrix, n, m);
double **tmat = transpose(&matrix, n, m);
printf("Transpose: \n");
printMatrix(&tmat, m, n);
double **pmat = multiply(&tmat, m, n, &matrix, n, m);
printf("Transpose * Original: \n");
printMatrix(&pmat, m, m);
double **inv = inverse(&pmat, m, m);
printf("Inverse: \n");
printMatrix(&inv, m, m);
double **cmat = multiply(&tmat, m, n, &y, n, 1);
printf("Transpose * y\n");
printMatrix(&cmat, m, 1);
double **w = multiply(&inv, m, m, &cmat, m, 1);
printf("W:\n");
printMatrix(&w, m, 1);
int x;
fscanf(tfile, "%d\n", &x);
double **fmat = (double**) malloc(sizeof(double*) * x);
if (fmat == NULL) {
printf("Out of memory\n");
return -1;
}
for (i = 0; i < x; i++) {
fmat[i] = (double*) malloc(sizeof(double) * (m-1));
if (fmat[i] == NULL) {
printf("Out of memory\n");
return -1;
}
}
for (i = 0; i < x; i++) {
for (j = 0; j < (m-1); j++) {
fscanf(tfile, "%lf,", &fmat[i][j]);
}
}
printf("Test:\n");
printMatrix(&fmat, x, (m-1));
double **result = (double**) malloc(sizeof(double*) * x);
for (i = 0; i < x; i++) {
result[i] = (double*) malloc(sizeof(double));
result[i][0] = w[0][0];
}
for (i = 0; i < x; i++) {
for (j = 0; j < (m-1); j++) {
result[i][0] += w[j+1][0] * fmat[i][j];
}
}
printf("Result:\n");
printMatrix(&result, x, 1);
return 0;
}
<file_sep># CS211
CS211 course files
<file_sep>#include <stdio.h>
#include <stdlib.h>
#define SIZE 10000
typedef struct node {
int value;
struct node *next;
} node;
int hash(int num){
return num % 10000;
}
node* newNode(int num) {
node *temp = (node*) malloc(sizeof(node));
temp->value = num;
temp->next = NULL;
return temp;
}
int search (int num, node **tabl){
node **table = tabl;
int index = hash(num);
node *ptr = table[index];
while(ptr != NULL) {
if (ptr->value == num){
return 1;
}
ptr = ptr->next;
}
return 0;
}
int insert(int num, node **table){
int index = hash(num);
node *temp = newNode(num);
temp->next = table[index];
table[index] = temp;
return 0;
}
int main(int argc, char *argv[]) {
node **table = (node**) malloc(sizeof(node*) * SIZE);
int i;
for (i = 0; i < SIZE; i++) {
table[i] = NULL;
}
if (argc < 2) {
printf("Need argument\n");
return -1;
}
char *filename = argv[1];
FILE *file = fopen(filename, "r");
char *c;
int num, found;
while (fscanf(file, "%c\t%i\n", c, &num) != EOF){
found = search(num, table);
if (*c == 's') {
if (found == 1)
printf("present\n");
else
printf("absent\n");
}
else {
if (found == 1)
printf("duplicate\n");
else {
insert(num, table);
printf("inserted\n");
}
}
}
return 0;
}
<file_sep>#include <stdio.h>
#include <stdlib.h>
int sortOdds(int *array, int size){
int i, j, temp;
j = 0;
int *result = (int*) malloc(sizeof(int) * size);
for (i = 0; i < size; i++) {
if (array[i] % 2 == 1) {
// printf("%d\t", array[i]);
result[j] = array[i];
j++;
}
}
temp = j;
//printf("\n");
//printf("%d is temp in function\n", temp);
for (i = 0; i < size; i++){
if (array[i] % 2 == 0){
result[j] = array[i];
j++;
}
}
for (int i = 0; i < size; i ++){
array[i] = result[i];
}
/*
printf("\n");
for (int i = 0; i < size; i++){
printf("%d\t", array[i]);
}
printf("\n");
*/
return temp;
}
int * sort(int *array, int size) {
int i, j, min, temp;
for (i = 0; i < size-1; i++){
min = i;
for (j = i + 1; j < size; j++){
if (array[j] < array[min])
min = j;
}
temp = array[i];
array[i] = array[min];
array[min] = temp;
}
printf("in sorted function:\n");
for (int i = 0; i < size; i++){
printf("%d\t", array[i]);
}
printf("\n");
return array;
}
int * revsort(int *array, int size, int start) {
int i, j, max, temp;
for (i = start; i < size-1; i++){
max = i;
for (j = i + 1; j < size; j++){
if (array[j] > array[max])
max = j;
}
temp = array[i];
array[i] = array[max];
array[max] = temp;
}
return array;
}
int main(int argc, char *argv[]) {
if (argc < 2){
printf("Need an argument\n");
return -1;
}
/*
int arr[] = {5, 4, 3, 0, 1, 2};
sort(&arr, 3);
revsort(&arr, 6, 3);
printf("test sort:\n");
for (int i = 0; i < 6; i++){
printf("%d\t", arr[i]);
}
*/
char *filename = argv[1];
FILE *infile = fopen(filename, "r");
int arraySize;
fscanf(infile, "%d\n", &arraySize);
printf("Array size is %d\n", arraySize);
int *array = (int*) malloc(sizeof(int) * arraySize);
for (int i = 0; i < arraySize; i++) {
fscanf(infile, "%d", array + i);
}
int temp = sortOdds(array, arraySize);
printf("sortOdds array:\n");
for (int i = 0; i < arraySize; i++){
printf("%d\t", array[i]);
}
printf("\n");
printf("%d is temp in main\n", temp);
sort(array, temp);
revsort(array, arraySize, temp);
printf("final array w/o front sort:\n");
for (int i = 0; i < arraySize; i++){
printf("%d\n", array[i]);
}
fclose(infile);
free(array);
return 0;
}
<file_sep>#include <stdlib.h>
#include <stdio.h>
typedef struct node {
int value;
struct node *next;
} Node;
Node *head;
void insertLL(int value) {
Node *temp = (Node *) malloc(sizeof(Node));
temp->value = value;
temp->next = head;
head = temp;
}
void insertRear(int value){
if (head == NULL){
printf("NULL front\n");
return;
}
Node *ptr = head;
while (ptr->next != NULL){
ptr = ptr->next;
}
Node *temp = (Node*) malloc(sizeof(Node));
temp->value = value;
temp->next = NULL;
ptr->next = temp;
return;
}
int main(int argc, char *argv[]){
head = (Node*) malloc(sizeof(Node));
head->value = 5;
head->next = NULL;
insertLL(6);
insertRear(7);
printf("%d\n", head->value);
head = head->next;
printf("%d\n", head->value);
head = head->next;
printf("%d\n", head->value);
return 0;
}
<file_sep>all: first
first: first.c
gcc test.c -o test
clean:
rm -rf first
<file_sep>all: first
first: first.c
gcc -g -o first first.c -Wall -Werror -fsanitize=address
clean:
rm -rf first
| e37c93ed0d8dacad2763c8b8f70fc80e1cad6afc | [
"Markdown",
"C",
"Makefile"
]
| 9 | C | robertm745/CS211 | 77f21de0369e51262f6bf3a3fa2b84700500527e | 5ed795b05e3dfa4df18ff5991f98453ad08ec9f3 |
refs/heads/main | <repo_name>Terieyenike/jb-board-with-harperdb<file_sep>/config/db.js
const harperive = require('harperive');
// interesting choice, why did you decide to go with harperive for a local db?
const DB_CONFIG = {
harperHost: process.env.DB_HOST,
username: process.env.DB_USER,
password: process.env.DB_PASS,
};
const Client = harperive.Client;
const db = new Client(DB_CONFIG);
module.exports = db;<file_sep>/README.md
# Job board application
Built with HarperDB, NodeJs/Express, and Handlebars as the templating engine.
The job board application provides the opportunity to post job available in the job market where developers can apply to these jobs.


## Set Up and Installation
1. Create a directory and cd into the directory
`mkdir <project-name> && cd <project-name>`
2. Initialize the directory with
`npm init -y`
The flag -y simply state you accept the default changes into your directory.
3. Install the dependencies
`npm install harperive dotenv hbs express`
4. Install the dev depency, nodemon
`npm install --save-dev nodemon`
## Start the project
`npm run start:dev`
## Deployment
Heroku app
### Author
<NAME>
<file_sep>/app.js
const express = require('express');
const db = require('./config/db');
const path = require('path');
require('dotenv').config();
const app = express();
app.set('view engine', 'hbs');
app.set('views', path.join(__dirname, 'views')) // missing ; (the js engine will automatically add it but that's not necessarily a given on all browsers.)
app.use((req, res, next) => {
const start = Date.now();
next();
const delta = Date.now() - start;
console.log(`${req.method} ${req.baseUrl}${req.url} took ${delta}ms to run.`);
// well done.
});
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use('/', express.static(path.join(__dirname, 'public')));
// it's worth considering to move the port, and the listener to a separate file
// think server.js that starts the server and calls your app.
// the benefit with this approach is that, should the project grow, you can have different
// logic that can contain load balancers and such.
const PORT = process.env.PORT || 8000;
// have you considered separating the routes from your app.js?
// when the project starts to grow, it's best to think of app.js as a handler for the server and routes
// and have your routes in another directory
// https://stackoverflow.com/a/37309212
app.get('/', async (req, res) => {
try {
const jobs = await db.searchByValue({
table: 'jobs', // some people might want to have these hardcoded strings as variables but I don't have a strong opinion
operation: 'search_by_value',
schema: 'job',
searchValue: '*',
searchAttribute: 'job_id',
attributes: ['*'],
});
return res.render('index', {
details: jobs.data,
brand: 'All Dev Jobs',
});
} catch (error) {
return res.render('error', {
error: 'Connect to the internet',
});
}
});
app.get('/new', (req, res) => {
return res.render('new');
});
// did you consider creating an error handler middleware instead of using try/catch?
// this can help make your code more DRY (don't repeat yourself)
app.get(`/jobs/:job_id`, async (req, res) => {
let { job_id } = req.params; // underscore as variable names is typically frown upon in JS (https://github.com/felixge/node-style-guide#naming-conventions)
try {
const jobs = await db.searchByHash({
table: 'jobs',
operation: 'search_by_hash',
schema: 'job',
hashValues: [job_id],
attributes: ['*'],
});
return res.render('jobs', {
btn: "back to all jobs",
details: jobs.data
});
} catch (error) {
return res.render('error', {
error: 'Connect to the internet',
});
}
});
app.post('/new', async (req, res) => {
let { body } = req;
try {
await db.insert({
operation: 'insert',
schema: 'job',
table: 'jobs',
records: [body],
});
return res.status(200).redirect('/');
} catch (error) {
return res.render('error', {
error: 'Connect to the internet',
});
}
});
app.listen(PORT, () => {
console.log(`Server is running on port:${PORT}`);
});
| d1775520914131d773b10e7a7fcd68e2c6da800b | [
"JavaScript",
"Markdown"
]
| 3 | JavaScript | Terieyenike/jb-board-with-harperdb | 57dfc95dcbbd7350b909b614df90feed971ffca6 | 06707371c13ad3d1b21ce264cdf4a139d7e5d2a7 |
refs/heads/main | <repo_name>Foxall/gatsby_mui_redux-toolkit<file_sep>/src/state/fakelisteSlice.js
import { createSlice } from '@reduxjs/toolkit'
const initialState = {}
const FakeListSlice = createSlice({
name: 'fakeliste',
initialState,
reducers: {
setRedux(state, action) {
state.value = action.payload
},
},
})
export const { setRedux } = FakeListSlice.actions
export default FakeListSlice.reducer
<file_sep>/src/state/fakelist.js
import faker from 'faker'
import { setRedux } from './fakelisteSlice'
import { useDispatch } from 'react-redux'
const SetFakeList = () => {
const dispatch = useDispatch()
const createUser = () => ({ uuid: faker.random.uuid(), email: faker.internet.email(), address: faker.address.streetAddress(), bio: faker.lorem.sentence(), image: faker.image.avatar(), name: faker.name.findName() })
const createUsers = (numUsers = 5) => Array.from({ length: numUsers }, createUser)
const Users = createUsers()
dispatch(setRedux(Users))
return null
}
export default SetFakeList
<file_sep>/src/components/counter.js
import React from 'react'
import { Button } from 'gatsby-theme-material-ui'
import TextField from '@material-ui/core/TextField'
import { useSelector, useDispatch } from 'react-redux'
import { increment, decrement } from '../state/demoSlice'
import TextButton from './textbutton'
const Counter = () => {
const dispatch = useDispatch()
const name = useSelector((state) => state.counter.value)
return (
<div>
<Button variant='contained' onClick={() => dispatch(increment())}>
+
</Button>
<Button variant='contained' onClick={() => dispatch(decrement())}>
-
</Button>
<TextField value={name}/>
<TextButton />
</div>
)
}
export default Counter
<file_sep>/src/components/myliste.js
import React from 'react'
import List from '@material-ui/core/List'
import ListItem from '@material-ui/core/ListItem'
import ListItemText from '@material-ui/core/ListItemText'
import { useSelector } from 'react-redux'
const Myliste = () => {
const Users = useSelector((state) => state.fakelist.value)
const name = Users.map((user) => (
<ListItem key={user.uuid}>
<ListItemText>{user.name}</ListItemText>
</ListItem>
))
return (
<div>
<List>{name}</List>
</div>
)
}
export default Myliste
<file_sep>/src/pages/index.js
import React from 'react'
import Counter from '../components/counter'
import Myliste from '../components/myliste'
import { Button } from 'gatsby-theme-material-ui'
export default function Home() {
return (
<div>
<Button variant='outlined' to='/about'>
{' '}
about{' '}
</Button>
<Counter />
<Myliste />
</div>
)
}
| 5176ff25a518b8547e181fccb64877395cf728ae | [
"JavaScript"
]
| 5 | JavaScript | Foxall/gatsby_mui_redux-toolkit | c05aec39c2074e1746bea2d8747f11ef920e430c | 6466b11c756faf89734bbf784b68ebca102568b2 |
refs/heads/master | <repo_name>taneresme/te.android.practices<file_sep>/hw08/README.md
# Homework-10
Create a new Android project which consists of four classes as below. The classes will have the following features:
**1. MainActivity:**
The activity will take some information that should be passed to the BookProvider to be written to the table "Books"
There will be four EditText views, five TextViews, and one FloatingActionButton as seen below.
When the FloatingActionButton is clicked, the activity will get the texts of each EditText view;
**CHECKS** if such a book with the same name exists in the "Books" table;
if not insert it to the "Books" table via the ContentResolver methods.

**2. BookProvider**
This class will be based on the ContentProvider class.
It will create the DB with a single table called "Books" as explained below. Note that this is same
"Books" table you've written in Homework/Lab 6. You can use the DB helper you've written for Homework/Lab 6.
You are supposed to override the correct methods for inserting, and querying the DB similar to what we did
in lecture notes Part 9.
**3 - 4. Contract Class and DBHelper class**
This class will be based on the contract and DB helper classes we've built in Part 8 of the lectures.
Note that you can use the DB helper you've written for Homework/Lab 6.
**Table "Books":**
ID Name Author Genre Year
* ID is an auto-increment, primary key, integer column
* Name is a NOT NULL, text (or String) column
* Author is a NOT NULL, text (or String) column
* Genre is a text (or String) column
* Year is an integer column<file_sep>/hw08/app/src/main/java/tr/com/mskr/sunshine22/db/WeatherDbHelper.java
package tr.com.mskr.sunshine22.db;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class WeatherDbHelper extends SQLiteOpenHelper {
final String SQL_CREATE_WEATHER_TABLE = "CREATE TABLE " + WeatherContract.WeatherEntry.TABLE_NAME + " (" +
WeatherContract.WeatherEntry._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
WeatherContract.WeatherEntry.COLUMN_NAME_NAME + " TEXT NOT NULL, " +
WeatherContract.WeatherEntry.COLUMN_NAME_AUTHOR + " TEXT, " +
WeatherContract.WeatherEntry.COLUMN_NAME_GENDER + " TEXT, " +
WeatherContract.WeatherEntry.COLUMN_NAME_YEAR + " INTEGER " +
" );";
private static final int DATABASE_VERSION = 2;
public static final String DATABASE_NAME = "weather.db";
public WeatherDbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
sqLiteDatabase.execSQL(SQL_CREATE_WEATHER_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) {
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + WeatherContract.WeatherEntry.TABLE_NAME);
onCreate(sqLiteDatabase);
}
}
<file_sep>/README.md
# Android Application Development Practices
## Homework-01
Open up a new Android Project (API level 22, Empty Project).
Put 1 TextView view to the center of the screen and 2 floatingActionButton views at the bottom of the screen right next to the other in the project with different images.
Change the code of both of the floatingActionButtons so that,
- When the button to the left is clicked, the font of the TextView is changed to 24dp
- When the button to the right is clicked, the font of the TextView is changed to 12dp
**NOTE:** You need to go to the Android Developers web page and find the method for changing the font size of a TextView.
## Homework-02
Build up an UI consisting of one ImageView and three Switches as seen below

Make three versions of the same activity, each having the following layouts:
- ConstraintLayout
- LinearLayout
- RelativeLayout
**NOTE:** Use the following Star Trek Poster for the image of the ImageView.
## Homework-03
Open up a new Android Project (API level 22, Empty Project)
Using the UI you've built in Question 2 (ConstraintLayout version), change the functionality of the three switches as explained below:
- Switch 1 - (visibilitySwitch): If checked, the image should be visible; otherwise it should be invisible.
- Switch 2 - (tintSwitch): If checked, there should be a orange tint over the image (either screen or multiply mode); otherwise no tint.
- Switch 3 - (tintModeSwitch): If checked, the tint should be on screen mode; in unchecked it should be multiply mode.
You can find the details of ImageView views from the following link: ImageViews. Check the method setTintList and setTintMode.
## Homework-04
Open up a new Android Project (API level 22, Empty Project).
Build up an app with a single activity which in turn has a single horizontal RecyclerView element. Each item in the RecyclerView element should consist of three items (see Figure 1):
- One ImageView at the top
- Two TextViews below the ImageView, one below the other

The RecyclerView element should have the following features:
- There should be AT LEAST 10 items with different images in the RecyclerView.
- The layout of the RecyclerView should be a horizontal linear layout
- There should be a horizontal scroll bar in the RecyclerView
## Homework-05
Open up a new Android Project (API level 22, Empty Project).
Build up an app with a single activity which in turn has a single vertical staggered RecyclerView element. Each item in the RecyclerView element should consist of three items (see Figure 1):
- One ImageView at the top
- Two TextViews below the ImageView, one below the other
The RecyclerView element should have the following features:
- There should be AT LEAST 16 items with different images in the RecyclerView.
- The layout of the RecyclerView should be a vertical staggered grid layout.
- There should be 2 columns consisting of 8 items each.
- The horizontal sizes of each Image should be the same whereas the vertical sizes of each Image MUST be different from each other.
## Homework-06
Start from the project given in the file named "Sunshine22_Part5_END.zip" in Moodle.
Modify the FetchWeatherTask class so that the RecyclerView object should show the pressure and humidity information for each day instead of minimum temperature, maximum temperature and the weather information.
**Example:**
Each item in RecyclerView should say: "Sun Oct 22 Pr: 1018.6, Hum: 0%"
**HINT:** You have to change the part where you get the max, min, main items inside the JSON object.
## Homework-07
Start from the project given in the file named "Sunshine22_Part5_END.zip" in Moodle.
Modify the whole project so that when an item in the RecyclerView is touched, the DetailActivity is opened with the **following information of the touched item** is shown as in the image given below:
* Date
* Day (the big temperature), Min, and Max temperatures
* Description of the weather information (e.g., Sunny, Rainy...)
* The weather icon corresponding to the openweathermap icons

**NOTE:** You can find all the weather icons from [here](https://openweathermap.org/weather-conditions):
**NOTE:** For some strange reason, Android doesn't allow image files starting with numbers (i.e., if you try to use an image file called 10d.png, Android Studio will give you an error.). Instead you should use the weather icon files with some prefix (e.g., use 10d.png as owm_10d.png)
**NOTE:** If you do not like the openweathermap weather icons, you can use a different weather icon set available on the internet.
**HINT:** You should modify some parts of the the following classes:
* FetchWeatherTask.java
* ForecastViewHolder.java
* GreenAdapter.java
* DetailActivity.java
## Homework-08
Change the design of the MainActivity of the Sunshine project as seen below.
**HINT:** Start from Sunshinev22_Part8_END.zip

## Homework-09
Using the WeatherProvider class we've written in Part 9 of the lectures,
override the "bulkInsert" method of the WeatherProvider.
Also, modify the FetchWeatherTask's addWeather method so that if there are MORE THAN 5
weather entries to be inserted, the method uses the bulkInsert method of
the Content Resolver (CR) instead of insert method of the CR.
This bulkInsert method handles multiple inserts to the SQLite database in a fast way,
faster than individual insert method calls inside a loop.
In the bulkInsert method of the WeatherProvider (which is automatically called
if you use the bulkInsert method of the CR), you MUST add all of these rows
in a SINGLE DB TRANSACTION. You should use one of the following SQLiteDatabase commands
given below:
* beginTransaction()
* beginTransactionNonExclusive()
## Homework-10
Create a new Android project which consists of four classes as below. The classes will have the following features:
**1. MainActivity:**
The activity will take some information that should be passed to the BookProvider to be written to the table "Books"
There will be four EditText views, five TextViews, and one FloatingActionButton as seen below.
When the FloatingActionButton is clicked, the activity will get the texts of each EditText view;
**CHECKS** if such a book with the same name exists in the "Books" table;
if not insert it to the "Books" table via the ContentResolver methods.

**2. BookProvider**
This class will be based on the ContentProvider class.
It will create the DB with a single table called "Books" as explained below. Note that this is same
"Books" table you've written in Homework/Lab 6. You can use the DB helper you've written for Homework/Lab 6.
You are supposed to override the correct methods for inserting, and querying the DB similar to what we did
in lecture notes Part 9.
**3 - 4. Contract Class and DBHelper class**
This class will be based on the contract and DB helper classes we've built in Part 8 of the lectures.
Note that you can use the DB helper you've written for Homework/Lab 6.
**Table "Books":**
ID Name Author Genre Year
* ID is an auto-increment, primary key, integer column
* Name is a NOT NULL, text (or String) column
* Author is a NOT NULL, text (or String) column
* Genre is a text (or String) column
* Year is an integer column
## Homework-11
Rewrite the Hydration app with the same functionality using the JobScheduler API instead of
the Firebase JobDispatcher as the JobScheduling framework.<file_sep>/hw07/app/src/main/java/tr/com/mskr/sunshine22/ForecastViewHolder.java
package tr.com.mskr.sunshine22;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;
import com.squareup.moshi.JsonAdapter;
import com.squareup.moshi.Moshi;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import tr.com.mskr.sunshine22.weather.List;
import tr.com.mskr.sunshine22.weather.WeatherApiResult;
public class ForecastViewHolder extends RecyclerView.ViewHolder
implements View.OnClickListener{
private ListItemClickListener mListener;
public TextView listItemForecastView;
public ForecastViewHolder(View itemView, ListItemClickListener listener) {
super(itemView);
listItemForecastView = (TextView) itemView.findViewById(R.id.tv_item_forecast);
mListener = listener;
itemView.setOnClickListener(this);
}
void bind(String s) throws IOException {
Moshi moshi = new Moshi.Builder().build();
JsonAdapter<List> jsonAdapter = moshi.adapter(List.class);
List list = jsonAdapter.fromJson(s);
String pressureAndHumidity = formatPressureAndHumidity(list.getPressure(), list.getHumidity());
listItemForecastView.setText(list.getReadableDateString() + " " + pressureAndHumidity);
}
@Override
public void onClick(View view) {
int clickedPosition = getAdapterPosition();
mListener.onListItemClick(clickedPosition);
}
private String formatPressureAndHumidity(double pressure, double humidity) {
String roundedPressure = new DecimalFormat("#.#").format(pressure);
long roundedHumidity = Math.round(humidity);
String pressureAndHum = String.format("Pr: %s, Hum: %s%%", roundedPressure, roundedHumidity);
return pressureAndHum;
}
}<file_sep>/hw01/README.md
# Homework-01
Open up a new Android Project (API level 22, Empty Project).
Put 1 TextView view to the center of the screen and 2 floatingActionButton views at the bottom of the screen right next to the other in the project with different images.
Change the code of both of the floatingActionButtons so that,
- When the button to the left is clicked, the font of the TextView is changed to 24dp
- When the button to the right is clicked, the font of the TextView is changed to 12dp
**NOTE:** You need to go to the Android Developers web page and find the method for changing the font size of a TextView.<file_sep>/hw11/README.md
# Homework-11
Rewrite the Hydration app with the same functionality using the JobScheduler API instead of
the Firebase JobDispatcher as the JobScheduling framework.<file_sep>/hw07/app/src/main/java/tr/com/mskr/sunshine22/MainActivity.java
package tr.com.mskr.sunshine22;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
public class MainActivity extends AppCompatActivity
implements ListItemClickListener {
private GreenAdapter mAdapter;
private RecyclerView mNumbersList;
private DividerItemDecoration mDividerItemDecoration;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
mNumbersList = (RecyclerView) findViewById(R.id.rv_forecast);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
mNumbersList.setLayoutManager(layoutManager);
mNumbersList.setHasFixedSize(true);
mDividerItemDecoration = new DividerItemDecoration(mNumbersList.getContext(), layoutManager.getOrientation());
mNumbersList.addItemDecoration(mDividerItemDecoration);
mAdapter = new GreenAdapter(this);
mNumbersList.setAdapter(mAdapter);
String weatherAPIKey = "1b3a6d183e0681e26f960c86ee271000";
String weatherURLString = "http://api.openweathermap.org/data/2.5/forecast/" +
"daily?" +
"q=London" +
"&mode=JSON" +
"&units=metric" +
"&cnt=12" +
"&APPID="+weatherAPIKey;
FetchWeatherTask weatherTask = new FetchWeatherTask(mAdapter);
weatherTask.execute(weatherURLString);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onListItemClick(int clickedItemIndex) {
Intent detailActivityIntent;
Log.v("MainActivity.onCreate", "Item#"+Integer.toString(clickedItemIndex));
detailActivityIntent = new Intent(MainActivity.this, DetailActivity.class);
detailActivityIntent.putExtra(Intent.EXTRA_TEXT, mAdapter.getItem(clickedItemIndex));
startActivity(detailActivityIntent);
}
}<file_sep>/hw06/app/src/main/java/tr/com/mskr/sunshine22/MainActivity.java
package tr.com.mskr.sunshine22;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
public class MainActivity extends AppCompatActivity
implements ListItemClickListener {
private static final String DEGREE = "\u00b0";
private static final int FORECAST_LIST_ITEMS = 12;
private String[] FORECASTS = {
"Mon, Oct 9: 15"+DEGREE, "Tue, Oct 10: 17"+DEGREE, "Wed, Oct 11: 17"+DEGREE,
"Thu, Oct 12: 19"+DEGREE, "Fri, Oct 13: 19"+DEGREE, "Sat, Oct 14: 18"+DEGREE,
"Sun, Oct 15: 19"+DEGREE, "Mon, Oct 16: 22"+DEGREE, "Tue, Oct 17: 18"+DEGREE,
"Wed, Oct 18: 21"+DEGREE, "Thu, Oct 19: 12"+DEGREE, "Fri, Oct 20: 22"+DEGREE};
private GreenAdapter mAdapter;
private RecyclerView mNumbersList;
private DividerItemDecoration mDividerItemDecoration;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
mNumbersList = (RecyclerView) findViewById(R.id.rv_forecast);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
mNumbersList.setLayoutManager(layoutManager);
mNumbersList.setHasFixedSize(true);
mDividerItemDecoration = new DividerItemDecoration(mNumbersList.getContext(), layoutManager.getOrientation());
mNumbersList.addItemDecoration(mDividerItemDecoration);
mAdapter = new GreenAdapter(FORECAST_LIST_ITEMS, FORECASTS, this);
mNumbersList.setAdapter(mAdapter);
String weatherAPIKey = "1b3a6d183e0681e26f960c86ee271000";
String weatherURLString = "http://api.openweathermap.org/data/2.5/forecast/" +
"daily?" +
"q=London" +
"&mode=JSON" +
"&units=metric" +
"&cnt=12" +
"&APPID="+weatherAPIKey;
FetchWeatherTask weatherTask = new FetchWeatherTask(mAdapter);
weatherTask.execute(weatherURLString);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onListItemClick(int clickedItemIndex) {
Intent detailActivityIntent;
Log.v("MainActivity.onCreate", "Item#"+Integer.toString(clickedItemIndex));
detailActivityIntent = new Intent(MainActivity.this, DetailActivity.class);
detailActivityIntent.putExtra(Intent.EXTRA_TEXT, "Detailed Weather Info");
startActivity(detailActivityIntent);
}
}<file_sep>/hw04/README.md
# Homework-04
Open up a new Android Project (API level 22, Empty Project).
Build up an app with a single activity which in turn has a single horizontal RecyclerView element. Each item in the RecyclerView element should consist of three items (see Figure 1):
- One ImageView at the top
- Two TextViews below the ImageView, one below the other

The RecyclerView element should have the following features:
- There should be AT LEAST 10 items with different images in the RecyclerView.
- The layout of the RecyclerView should be a horizontal linear layout
- There should be a horizontal scroll bar in the RecyclerView<file_sep>/hw06/app/src/main/java/tr/com/mskr/sunshine22/FetchWeatherTask.java
package tr.com.mskr.sunshine22;
import android.os.AsyncTask;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
public class FetchWeatherTask extends AsyncTask<String, Void, String[]> {
GreenAdapter mWeatherAdapter;
public FetchWeatherTask(GreenAdapter weatherAdapter) {
mWeatherAdapter = weatherAdapter;
}
@Override
protected String[] doInBackground(String... urlStrings) {
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
String forecastJsonStr = null;
try {
URL weatherURL = new URL(urlStrings[0]);
urlConnection = (HttpURLConnection) weatherURL.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream != null) {
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line + "\n");
}
if (buffer.length() != 0) {
forecastJsonStr = buffer.toString();
}
}
} catch (IOException e) {
Log.e("MainActivity", "Error ", e);
} finally{
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e("MainActivity", "Error closing stream", e);
}
}
}
try {
return getWeatherDataFromJson(forecastJsonStr);
} catch (JSONException e) {
Log.e("FetchWeatherTask", e.getMessage(), e);
}
// This will only happen if there was an error getting or parsing the forecast.
return null;
}
@Override
protected void onPostExecute(String[] weatherInfo) {
super.onPostExecute(weatherInfo);
for(int i=0; i<weatherInfo.length; i++){
Log.v("FetchWeatherTask", weatherInfo[i]);
}
mWeatherAdapter.setWeatherData(weatherInfo);
}
public static double getMaxTempForDay(String wJsonStr, int dayIndex)
throws JSONException {
JSONObject mainObject = new JSONObject(wJsonStr);
JSONArray list = mainObject.getJSONArray("list");
String max_tmp = list.getJSONObject(dayIndex)
.getJSONObject("temp")
.getString("max");
return Double.parseDouble(max_tmp);
}
private String[] getWeatherDataFromJson(String forecastJsonStr)
throws JSONException {
final String OWM_LIST = "list";
final String OWM_WEATHER = "weather";
final String OWM_TEMPERATURE = "temp";
final String OWM_MAX = "max";
final String OWM_MIN = "min";
final String OWM_DESCRIPTION = "main";
final String OWM_DATETIME = "dt";
final String OWM_PRESSURE = "pressure";
final String OWM_HUMIDITY = "humidity";
final int SEC_TO_MILISEC = 1000;
JSONObject forecastJson = new JSONObject(forecastJsonStr);
JSONArray weatherArray = forecastJson.getJSONArray(OWM_LIST);
String[] resultStrs = new String[weatherArray.length()];
for(int i = 0; i < weatherArray.length(); i++) {
String day;
String pressureAndHumidity;
JSONObject dayForecast = weatherArray.getJSONObject(i);
double pressure = dayForecast.getDouble(OWM_PRESSURE);
double humidity = dayForecast.getDouble(OWM_HUMIDITY);
JSONObject weatherObject = dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0);
JSONObject temperatureObject = dayForecast.getJSONObject(OWM_TEMPERATURE);
long dateTime = dayForecast.getLong(OWM_DATETIME)*SEC_TO_MILISEC;
String desc = weatherObject.getString(OWM_DESCRIPTION);
pressureAndHumidity = formatPressureAndHumidity(pressure, humidity);
day = getReadableDateString(dateTime);
resultStrs[i] = day + " " + pressureAndHumidity;
}
return resultStrs;
}
private String formatPressureAndHumidity(double pressure, double humidity) {
String roundedPressure = new DecimalFormat("#.#").format(pressure);
long roundedHumidity = Math.round(humidity);
String pressureAndHum = String.format("Pr: %s, Hum: %s%%", roundedPressure, roundedHumidity);
return pressureAndHum;
}
private String getReadableDateString(long time){
SimpleDateFormat shortenedDateFormat = new SimpleDateFormat("EEE MMM dd");
return shortenedDateFormat.format(time);
}
}<file_sep>/hw05/README.md
# Homework-05
Open up a new Android Project (API level 22, Empty Project).
Build up an app with a single activity which in turn has a single vertical staggered RecyclerView element. Each item in the RecyclerView element should consist of three items (see Figure 1):
- One ImageView at the top
- Two TextViews below the ImageView, one below the other
The RecyclerView element should have the following features:
- There should be AT LEAST 16 items with different images in the RecyclerView.
- The layout of the RecyclerView should be a vertical staggered grid layout.
- There should be 2 columns consisting of 8 items each.
- The horizontal sizes of each Image should be the same whereas the vertical sizes of each Image MUST be different from each other.<file_sep>/hw08/app/src/main/java/tr/com/mskr/sunshine22/db/WeatherContract.java
package tr.com.mskr.sunshine22.db;
import android.provider.BaseColumns;
public class WeatherContract {
public static class WeatherEntry implements BaseColumns {
public static final String TABLE_NAME = "Books";
public static final String COLUMN_NAME_NAME = "Name";
public static final String COLUMN_NAME_AUTHOR = "Author";
public static final String COLUMN_NAME_GENDER= "Gender";
public static final String COLUMN_NAME_YEAR = "Year";
}
}
<file_sep>/hw11/app/src/main/java/com/example/android/background/sync/WaterReminderJobService.java
package com.example.android.background.sync;
import android.app.job.JobParameters;
import android.app.job.JobService;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.widget.Toast;
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public class WaterReminderJobService extends JobService {
private AsyncTask mBackgroundTask;
@Override
public boolean onStartJob(final JobParameters jobParameters) {
Toast.makeText(this, "Fired!", Toast.LENGTH_SHORT).show();
mBackgroundTask = new AsyncTask() {
@Override
protected Object doInBackground(Object[] params) {
Context context = WaterReminderJobService.this;
ReminderTasks.executeTask(context, ReminderTasks.ACTION_CHARGING_REMINDER);
return null;
}
@Override
protected void onPostExecute(Object o) {
jobFinished(jobParameters, false);
}
};
mBackgroundTask.execute();
return true;
}
@Override
public boolean onStopJob(JobParameters jobParameters) {
if (mBackgroundTask != null) {
mBackgroundTask.cancel(true);
}
return true;
}
}<file_sep>/hw08/app/src/main/java/tr/com/mskr/sunshine22/ForecastViewHolder.java
package tr.com.mskr.sunshine22;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.moshi.JsonAdapter;
import com.squareup.moshi.Moshi;
import java.io.IOException;
import tr.com.mskr.sunshine22.task.DownloadImageTask;
import tr.com.mskr.sunshine22.weather.List;
public class ForecastViewHolder extends RecyclerView.ViewHolder
implements View.OnClickListener {
private static final String DEGREE = "\u00b0";
private static final String IMAGE_URL = "http://openweathermap.org/img/w/";
private ListItemClickListener mListener;
public TextView forecast;
public TextView forecastDetail;
public ImageView forecastImage;
public TextView highDegree;
public TextView lowDegree;
public ForecastViewHolder(View itemView, ListItemClickListener listener) {
super(itemView);
forecast = (TextView) itemView.findViewById(R.id.tv_item_forecast);
forecastDetail = (TextView) itemView.findViewById(R.id.tv_item_forecast_detail);
forecastImage = (ImageView) itemView.findViewById(R.id.tv_item_image);
highDegree = (TextView) itemView.findViewById(R.id.tv_item_high_degree_txt);
lowDegree = (TextView) itemView.findViewById(R.id.tv_item_low_degree_txt);
mListener = listener;
itemView.setOnClickListener(this);
}
void bind(String s) {
Moshi moshi = new Moshi.Builder().build();
JsonAdapter<List> jsonAdapter = moshi.adapter(List.class);
try {
List list = jsonAdapter.fromJson(s);
String date = list.getReadableDateString();
long min = Math.round(list.getTemp().getMin());
long max = Math.round(list.getTemp().getMax());
long day = Math.round(list.getTemp().getDay());
String desc = list.getWeather().get(0).getDescription();
String image = list.getWeather().get(0).getIcon();
new DownloadImageTask(forecastImage).execute(IMAGE_URL + image + ".png");
forecast.setText(date);
forecastDetail.setText(desc);
highDegree.setText(String.format("%s%s", max, DEGREE));
lowDegree.setText(String.format("%s%s", min, DEGREE));
} catch (IOException e) {
Log.v("DetailActivity.onCreate", e.toString());
forecast.setText("EXCEPTION OCCURRED");
}
}
@Override
public void onClick(View view) {
int clickedPosition = getAdapterPosition();
mListener.onListItemClick(clickedPosition);
}
}<file_sep>/hw08/app/src/main/java/tr/com/mskr/sunshine22/MainActivity.java
package tr.com.mskr.sunshine22;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
public class MainActivity extends AppCompatActivity
implements ListItemClickListener {
private static final String DEGREE = "\u00b0";
private static final int FORECAST_LIST_ITEMS = 12;
private String[] FORECASTS = {
"Mon, Oct 9: 15" + DEGREE, "Tue, Oct 10: 17" + DEGREE, "Wed, Oct 11: 17" + DEGREE,
"Thu, Oct 12: 19" + DEGREE, "Fri, Oct 13: 19" + DEGREE, "Sat, Oct 14: 18" + DEGREE,
"Sun, Oct 15: 19" + DEGREE, "Mon, Oct 16: 22" + DEGREE, "Tue, Oct 17: 18" + DEGREE,
"Wed, Oct 18: 21" + DEGREE, "Thu, Oct 19: 12" + DEGREE, "Fri, Oct 20: 22" + DEGREE};
private String mWeatherAPIKey = "1b3a6d183e0681e26f960c86ee271000";
private GreenAdapter mAdapter;
private RecyclerView mNumbersList;
private DividerItemDecoration mDividerItemDecoration;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
mNumbersList = (RecyclerView) findViewById(R.id.rv_forecast);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
mNumbersList.setLayoutManager(layoutManager);
mNumbersList.setHasFixedSize(true);
mDividerItemDecoration = new DividerItemDecoration(mNumbersList.getContext(), layoutManager.getOrientation());
mNumbersList.addItemDecoration(mDividerItemDecoration);
mAdapter = new GreenAdapter(this);
mNumbersList.setAdapter(mAdapter);
String weatherURLString = "http://api.openweathermap.org/data/2.5/forecast/" +
"daily?" +
"q=London" +
"&mode=JSON" +
"&units=metric" +
"&cnt=12" +
"&APPID=" + mWeatherAPIKey;
FetchWeatherTask weatherTask = new FetchWeatherTask(mAdapter, this.getApplicationContext());
weatherTask.execute(weatherURLString);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
Context context = getApplicationContext();
int duration = Toast.LENGTH_SHORT;
if (id == R.id.action_settings) {
Intent intent = new Intent(MainActivity.this, SettingsActivity.class);
startActivity(intent);
} else if (id == R.id.action_help) {
Toast toast = Toast.makeText(context, "Help is clicked", duration);
toast.show();
} else if (id == R.id.action_refresh) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
String location = prefs.getString("location", "94043");
String weatherURLString = "http://api.openweathermap.org/data/2.5/forecast/" +
"daily?" +
"q=" + location +
"&mode=JSON" +
"&units=metric" +
"&cnt=12" +
"&APPID=" + mWeatherAPIKey;
FetchWeatherTask weatherTask = new FetchWeatherTask(mAdapter, this.getApplicationContext());
weatherTask.execute(weatherURLString);
}
return super.onOptionsItemSelected(item);
}
@Override
public void onListItemClick(int clickedItemIndex) {
Intent detailActivityIntent;
Log.v("MainActivity.onCreate", "Item#" + Integer.toString(clickedItemIndex));
detailActivityIntent = new Intent(MainActivity.this, DetailActivity.class);
detailActivityIntent.putExtra(Intent.EXTRA_TEXT, "Detailed Weather Info");
startActivity(detailActivityIntent);
}
}<file_sep>/hw09/README.md
# Homework-09
Using the WeatherProvider class we've written in Part 9 of the lectures,
override the "bulkInsert" method of the WeatherProvider.
Also, modify the FetchWeatherTask's addWeather method so that if there are MORE THAN 5
weather entries to be inserted, the method uses the bulkInsert method of
the Content Resolver (CR) instead of insert method of the CR.
This bulkInsert method handles multiple inserts to the SQLite database in a fast way,
faster than individual insert method calls inside a loop.
In the bulkInsert method of the WeatherProvider (which is automatically called
if you use the bulkInsert method of the CR), you MUST add all of these rows
in a SINGLE DB TRANSACTION. You should use one of the following SQLiteDatabase commands
given below:
* beginTransaction()
* beginTransactionNonExclusive()<file_sep>/hw06/README.md
# Homework-06
Start from the project given in the file named "Sunshine22_Part5_END.zip" in Moodle.
Modify the FetchWeatherTask class so that the RecyclerView object should show the pressure and humidity information for each day instead of minimum temperature, maximum temperature and the weather information.
**Example:**
Each item in RecyclerView should say: "Sun Oct 22 Pr: 1018.6, Hum: 0%"
**HINT:** You have to change the part where you get the max, min, main items inside the JSON object.<file_sep>/hw06/app/src/main/java/tr/com/mskr/sunshine22/GreenAdapter.java
package tr.com.mskr.sunshine22;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class GreenAdapter extends RecyclerView.Adapter<ForecastViewHolder> {
private int mNumberItems;
private String[] items;
private ListItemClickListener mOnClickListener;
public GreenAdapter(int numberOfItems, String[] itemList, ListItemClickListener listener) {
mNumberItems = numberOfItems;
items = itemList;
mOnClickListener = listener;
}
@Override
public ForecastViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Context context = parent.getContext();
int layoutIdForListItem = R.layout.forecast_list_item;
LayoutInflater inflater = LayoutInflater.from(context);
boolean shouldAttachToParentImmediately = false;
View view = inflater.inflate(layoutIdForListItem, parent, shouldAttachToParentImmediately);
ForecastViewHolder viewHolder = new ForecastViewHolder(view, mOnClickListener);
return viewHolder;
}
@Override
public void onBindViewHolder(ForecastViewHolder holder, int position) {
holder.bind(items[position]);
}
@Override
public int getItemCount() {
return mNumberItems;
}
public void setWeatherData(String[] weatherData) {
items = weatherData;
mNumberItems = weatherData.length;
notifyDataSetChanged();
}
}
<file_sep>/hw02/README.md
# Homework-02
Build up an UI consisting of one ImageView and three Switches as seen below

Make three versions of the same activity, each having the following layouts:
- ConstraintLayout
- LinearLayout
- RelativeLayout
**NOTE:** Use the following Star Trek Poster for the image of the ImageView.<file_sep>/hw07/app/src/main/java/tr/com/mskr/sunshine22/FetchWeatherTask.java
package tr.com.mskr.sunshine22;
import android.os.AsyncTask;
import android.util.Log;
import com.squareup.moshi.JsonAdapter;
import com.squareup.moshi.Moshi;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import tr.com.mskr.sunshine22.weather.List;
import tr.com.mskr.sunshine22.weather.WeatherApiResult;
public class FetchWeatherTask extends AsyncTask<String, Void, String[]> {
GreenAdapter mWeatherAdapter;
public FetchWeatherTask(GreenAdapter weatherAdapter) {
mWeatherAdapter = weatherAdapter;
}
@Override
protected String[] doInBackground(String... urlStrings) {
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
String forecastJsonStr = null;
try {
URL weatherURL = new URL(urlStrings[0]);
urlConnection = (HttpURLConnection) weatherURL.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream != null) {
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line + "\n");
}
if (buffer.length() != 0) {
forecastJsonStr = buffer.toString();
}
}
} catch (IOException e) {
Log.e("MainActivity", "Error ", e);
} finally{
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e("MainActivity", "Error closing stream", e);
}
}
}
try {
return getWeatherDataFromJson(forecastJsonStr);
} catch (Exception e) {
Log.e("FetchWeatherTask", e.getMessage(), e);
}
// This will only happen if there was an error getting or parsing the forecast.
return null;
}
@Override
protected void onPostExecute(String[] weatherInfo) {
super.onPostExecute(weatherInfo);
for(int i=0; i < weatherInfo.length; i++){
Log.v("FetchWeatherTask", weatherInfo[i]);
}
mWeatherAdapter.setWeatherData(weatherInfo);
}
private String[] getWeatherDataFromJson(String forecastJsonStr)
throws IOException, JSONException {
final String OWM_LIST = "list";
JSONObject forecastJson = new JSONObject(forecastJsonStr);
JSONArray weatherArray = forecastJson.getJSONArray(OWM_LIST);
String[] resultStrs = new String[weatherArray.length()];
for(int i = 0; i < weatherArray.length(); i++) {
JSONObject dayForecast = weatherArray.getJSONObject(i);
resultStrs[i] = dayForecast.toString();
}
return resultStrs;
}
}<file_sep>/hw07/README.md
# Homework-07
Start from the project given in the file named "Sunshine22_Part5_END.zip" in Moodle.
Modify the whole project so that when an item in the RecyclerView is touched, the DetailActivity is opened with the **following information of the touched item** is shown as in the image given below:
* Date
* Day (the big temperature), Min, and Max temperatures
* Description of the weather information (e.g., Sunny, Rainy...)
* The weather icon corresponding to the openweathermap icons

**NOTE:** You can find all the weather icons from [here](https://openweathermap.org/weather-conditions):
**NOTE:** For some strange reason, Android doesn't allow image files starting with numbers (i.e., if you try to use an image file called 10d.png, Android Studio will give you an error.). Instead you should use the weather icon files with some prefix (e.g., use 10d.png as owm_10d.png)
**NOTE:** If you do not like the openweathermap weather icons, you can use a different weather icon set available on the internet.
**HINT:** You should modify some parts of the the following classes:
* FetchWeatherTask.java
* ForecastViewHolder.java
* GreenAdapter.java
* DetailActivity.java<file_sep>/hw03/README.md
# Homework-03
Open up a new Android Project (API level 22, Empty Project)
Using the UI you've built in Question 2 (ConstraintLayout version), change the functionality of the three switches as explained below:
- Switch 1 - (visibilitySwitch): If checked, the image should be visible; otherwise it should be invisible.
- Switch 2 - (tintSwitch): If checked, there should be a orange tint over the image (either screen or multiply mode); otherwise no tint.
- Switch 3 - (tintModeSwitch): If checked, the tint should be on screen mode; in unchecked it should be multiply mode.
You can find the details of ImageView views from the following link: ImageViews. Check the method setTintList and setTintMode.
<file_sep>/hw10/app/src/main/java/com/android/taner/hw10/data/BookDbHelper.java
package com.android.taner.hw10.data;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import com.android.taner.hw10.data.BookContract.BookEntry;
public class BookDbHelper extends SQLiteOpenHelper {
// If you change the database schema, you must increment the database version.
private static final int DATABASE_VERSION = 2;
public static final String DATABASE_NAME = "book.db";
public BookDbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
final String SQL_CREATE_LOCATION_TABLE = "CREATE TABLE " + BookEntry.TABLE_NAME + " (" +
BookEntry._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
BookEntry.COLUMN_NAME + " TEXT NOT NULL, " +
BookEntry.COLUMN_AUTHOR + " TEXT NOT NULL, " +
BookEntry.COLUMN_GENRE + " TEXT, " +
BookEntry.COLUMN_YEAR + " INTEGER " +
" );";
sqLiteDatabase.execSQL(SQL_CREATE_LOCATION_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) {
// This database is only a cache for online data, so its upgrade policy is
// to simply to discard the data and start over
// Note that this only fires if you change the version number for your database.
// It does NOT depend on the version number for your application.
// If you want to update the schema without wiping data, commenting out the next 2 lines
// should be your top priority before modifying this method.
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + BookEntry.TABLE_NAME);
onCreate(sqLiteDatabase);
}
}
| 732eb1e4a18008296112cf92f2a11a44a31954fb | [
"Markdown",
"Java"
]
| 23 | Markdown | taneresme/te.android.practices | d1cb8b9c65c182bcfae540bc944e993a8ae185e8 | 9e5f94a487c1eaa97ec8dbcb136a2030f9d3b3cf |
refs/heads/master | <repo_name>PROB8/javascriptPython<file_sep>/app.js
const addBtn = `<button class='btn add_link'>ADD</button>`
const newLink = `
<a id='new_link' class='nav-link active new_link' href='#newAppointment'>
<button class='btn'>NEW</button>
</a>`
$(function(){
const $root = $("#root")
const $search = $('#search')
const $cancel = $('.cancel')
const $new = $('.new_link')
const $add = $('.add_link')
const $li = $('li')
const $noAppts = $('.no-appts')
const $tbody = $('tbody')
const $form = $('div.form-box')
const $divNtable =$('div.table-div')
let getAppointments = (term = '') => {
if (term.length === 0) {
return $.get('/getallappts').then(res=> {
if(!res) return
let data = JSON.parse(res)
if(data.length === 0) {
$tbody.empty()
$noAppts.removeClass('hidden')
return
}
else {
$tbody.empty()
$noAppts.addClass('hidden')
data.forEach((list) => {
let newRow = `<td>${list[0]}</td><td>${list[2]}</td><td>${list[1]}</td>`
$tbody.append(`<tr>${newRow}</tr>`)
})
}
}).catch(err => {
console.error(err)
})
}else {
$.post(`/getOne`,{search:term}).then(res => {
if(!res) return
if(res.length === 0) {
$tbody.empty()
$noAppts.removeClass('hidden')
}
else {
$tbody.empty()
$noAppts.addClass('hidden')
res.forEach((list) => {
let newRow = `<td>${list[0]}</td><td>${list[2]}</td><td>${list[1]}</td>`
$tbody.append(`<tr>${newRow}</tr>`)
})
}
}).catch(err => {
console.error(err)
})
}
}
$('.bn1').on('click',function(e){
e.preventDefault()
let value = $search.val().trim()
if ($form.hasClass('hidden')){
$divNtable.removeClass('hidden')
}
else{
$form.addClass('hidden')
$divNtable.removeClass('hidden')
}
if (value.length === 0){
getAppointments()
}
else {
getAppointments(value)
}
$search.val('');
})
$search.on('keydown', function(e){
let value = $search.val().trim()
if (e.keyCode === 13) {
if ( !$form.hasClass('hidden')) {
$form.addClass('hidden')
}
if($('.table-div').hasClass('hidden')) {
$('.table-div').removeClass('hidden')
}
if (value.length === 0) {
console.log('rockin')
getAppointments()
}
else {
getAppointments(value)
}
$search.val('');
}
})
$li.on('click', '.new_link', function(){
if ($divNtable.hasClass('hidden')){
$form.removeClass('hidden')
}
else {
$divNtable.addClass('hidden')
$form.removeClass('hidden')
}
$('li.add').html(addBtn)
})
$('body').on('click', '.add_link', function() {
const newAppt = {
date:$('#date_input').val(),
time:$('#time_input').val(),
description:$('#description').val().trim()
}
if (newAppt.date === '' ){
$('.date').removeClass('not-visible')
setTimeout(function(){
$('.date').addClass('not-visible')},3000)
return
}
if(newAppt.time === '') {
$('.time').removeClass('not-visible')
setTimeout(function(){
$('.time').addClass('not-visible')},3000)
return
}
if(newAppt.description === '') {
$('.description').removeClass('not-visible')
setTimeout(function(){
$('.description').addClass('not-visible')},3000)
return
}
$.post('/send',newAppt,function(data){
$tbody.empty()
let obj = JSON.parse(data)
$noAppts.addClass('hidden')
obj.forEach((list) => {
let newRow = `<td>${list[0]}</td><td>${list[2]}</td><td>${list[1]}</td>`
$tbody.append(`<tr>${newRow}</tr>`)
})
})
$('#date_input').val('')
$('#time_input').val('')
$('#description').val('')
$('li.add').html(newLink)
$('.form-box').addClass('hidden')
$('.table-div').removeClass('hidden')
})
$cancel.on('click', function() {
$('#date_input').val('')
$('#time_input').val('')
$('#description').val('')
$('.form-box').addClass('hidden')
$('li.add').html(newLink)
})
})
<file_sep>/file.py
# from flask import Flask
# from flask import request
# app = Flask(__name__)
# @app.route('/postjson', methods = ['POST'])
# def postJsonHandler():
# print (request.is_json)
# content = request.get_json()
# print (content)
# return 'JSON posted'
# @app.route('/postjson', methods = ['GET'])
# def getHandler():
# print (request.is_json)
# content = request.get_json()
# print (content)
# return 'JSON posted'
# app.run(host='0.0.0.0', port= 8090)
<file_sep>/requirements.txt
astroid==1.6.1
backports.functools-lru-cache==1.5
backports.shutil-get-terminal-size==1.0.0
certifi==2018.1.18
chardet==3.0.4
click==6.7
colorama==0.3.9
configparser==3.5.0
decorators==0.1.1
Django==1.11.10
endpoints==1.1.24
enum34==1.1.6
flake8==3.5.0
Flask==0.12.2
futures==3.2.0
idna==2.6
isort==4.3.4
itsdangerous==0.24
Jinja2==2.10
lazy-object-proxy==1.3.1
MarkupSafe==1.0
mccabe==0.6.1
pathlib==1.0.1
pew==1.1.2
pipenv==9.0.3
psutil==5.3.1
pycodestyle==2.3.1
pyflakes==1.6.0
pylint==1.8.2
pytz==2018.3
requests==2.18.4
shutilwhich==1.1.0
singledispatch==3.4.0.3
six==1.11.0
urllib3==1.22
virtualenv==15.1.0
virtualenv-clone==0.2.6
Werkzeug==0.14.1
wrapt==1.10.11
<file_sep>/README.md
# Make A Date
## What is it?
Small appointment app using JavaScript and Python 3. This is my first time using Python 👨🏽! I had fun and learned a lot about the language in this exercise. I went from knowing nothing about Python to getting a Python back end app running that serves HTML and has a SQLite DB that stores and searches for your appointments--in less than two days. Looking forward to learning and doing more with Python.
### Technologies
1. Python 3
2. Bootstrap
3. SQLite
4. Jquery
5. HTML
6. Javascript
### Getting Started
** Make sure you have Python installed on your local machine
1. clone this repo to your local machine.
3. `$ python server.py`
4. in your browser go to `http://localhost:8080`
<file_sep>/server.py
from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer
from os import curdir, sep
import cgi
import sqlite3
conn = sqlite3.connect('appointments.db')
c = conn.cursor()
import json
import urlparse
PORT = 8080
class myServer(BaseHTTPRequestHandler):
def _get_all_appts(self):
c.execute('select * from appointments')
res = c.fetchall()
_json = json.dumps(res)
self.wfile.write(_json)
print 'records sent'
return
def do_GET(self):
if self.path=="/":
self.path="/index.html"
c.executescript('drop table if exists appointments;')
c.execute('''create table if not exists appointments (date text,description text, time text )''')
if self.path=="/getallappts":
print 'getting all records'
c.execute('select * from appointments')
res = c.fetchall()
_json = json.dumps(res)
self.send_response(200)
self.end_headers()
self.wfile.write(_json)
print 'records sent'
return
try:
sendReply = False
if self.path.endswith(".html"):
mimetype='text/html'
sendReply = True
if self.path.endswith(".jpg"):
mimetype='image/jpg'
sendReply = True
if self.path.endswith(".ico"):
mimetype='image/x-icon'
sendReply = True
if self.path.endswith(".js"):
mimetype='application/javascript'
sendReply = True
if self.path.endswith(".css"):
mimetype='text/css'
sendReply = True
if sendReply == True:
f = open(curdir + sep + self.path)
self.send_response(200)
self.send_header('Content-type',mimetype)
self.end_headers()
self.wfile.write(f.read())
f.close()
return
except IOError:
self.send_error(404,'File Not Found: %s' % self.path)
def do_POST(self):
if self.path=="/send":
form = cgi.FieldStorage(
fp=self.rfile,
headers=self.headers,
environ={'REQUEST_METHOD':'POST',
'CONTENT_TYPE':self.headers['Content-Type'],
})
value = []
for key in form.keys():
value.append( form.getvalue(key))
c.execute("insert into appointments values (?,?,?)", (value))
self.send_response(200)
self.end_headers()
self._get_all_appts()
if self.path=='/getOne':
form = cgi.FieldStorage(
fp=self.rfile,
headers=self.headers,
environ={'REQUEST_METHOD':'POST',
'CONTENT_TYPE':self.headers['Content-Type'],
})
for key in form.keys():
value = str(form.getvalue(key))
t = ('%' + value + '%')
c.execute('select * from appointments where description like ?' , (t,))
res = c.fetchall()
_json = json.dumps(res)
self.send_response(200)
self.send_header("Content-type", "application/json")
self.end_headers()
self.wfile.write(_json)
print "I'm ya huckleberry", res
return
try:
server = HTTPServer(('', PORT), myServer)
print 'Server running on port' , PORT
server.serve_forever()
except KeyboardInterrupt:
print 'Server stopped, goodbye!'
server.socket.close()
| 9ea7ed2703e3c69c0e2ffffb1731b0e02f6db891 | [
"JavaScript",
"Python",
"Text",
"Markdown"
]
| 5 | JavaScript | PROB8/javascriptPython | d2f6690fb181da705bf99d0e520d477a034d788f | 0e07448fed1b98a9df12e99105a5a3e7818d0d06 |
refs/heads/main | <repo_name>KevalShetta20/Buddiesgram.github.io<file_sep>/app/src/main/java/com/kevalshetta/shetta/Friends/FindFriendsActivity.java
package com.kevalshetta.shetta.Friends;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.SearchView;
import android.widget.TextView;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.kevalshetta.shetta.Post.MainActivity;
import com.kevalshetta.shetta.R;
import com.kevalshetta.shetta.Utils.Users;
import com.squareup.picasso.Picasso;
import org.jetbrains.annotations.NotNull;
import de.hdodenhof.circleimageview.CircleImageView;
public class FindFriendsActivity extends AppCompatActivity {
private Toolbar toolbar;
private DatabaseReference UserRef;
private FirebaseAuth mAuth;
private String currentUserId;
private RecyclerView findFriendsRv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_find_friends);
toolbar = findViewById(R.id.app_bar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setTitle("Find Friends");
mAuth = FirebaseAuth.getInstance();
currentUserId = mAuth.getCurrentUser().getUid();
UserRef = FirebaseDatabase.getInstance().getReference().child("Users");
findFriendsRv = findViewById(R.id.findFriendsRv);
findFriendsRv.setHasFixedSize(true);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
linearLayoutManager.setReverseLayout(true);
linearLayoutManager.setStackFromEnd(true);
findFriendsRv.setLayoutManager(linearLayoutManager);
LoadUsers("");
}
private void LoadUsers(String s) {
Query searchFriends = UserRef.orderByChild("username").startAt(s).endAt(s + "\uf8ff");
FirebaseRecyclerOptions<Users> options =
new FirebaseRecyclerOptions.Builder<Users>()
.setQuery(searchFriends, Users.class)
.build();
FirebaseRecyclerAdapter<Users,FindFriendViewHolder> adapter = new FirebaseRecyclerAdapter<Users, FindFriendViewHolder>(options) {
@Override
protected void onBindViewHolder(@NonNull @NotNull FindFriendViewHolder holder, int position, @NonNull @NotNull Users model) {
if (!currentUserId.equals(getRef(position).getKey().toString())){
holder.find_friend_username.setText(model.getUsername());
holder.find_friend_fullname.setText(model.getFullname());
Picasso.get().load(model.getProfileimage()).placeholder(R.drawable.profile).into(holder.find_friend_profile_image);
}else{
holder.itemView.setVisibility(View.GONE);
holder.itemView.setLayoutParams(new RecyclerView.LayoutParams(0,0));
}
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String visit_user_id = getRef(position).getKey();
Intent profileIntent = new Intent(FindFriendsActivity.this, FriendsProfileActivity.class);
profileIntent.putExtra("user", visit_user_id);
startActivity(profileIntent);
}
});
}
@NonNull
@NotNull
@Override
public FindFriendViewHolder onCreateViewHolder(@NonNull @NotNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.single_view_friends, parent, false);
return new FindFriendViewHolder(view);
}
};
findFriendsRv.setAdapter(adapter);
adapter.startListening();
}
public static class FindFriendViewHolder extends RecyclerView.ViewHolder{
private CircleImageView find_friend_profile_image;
private TextView find_friend_username, find_friend_fullname;
public FindFriendViewHolder(@NonNull @NotNull View itemView) {
super(itemView);
find_friend_profile_image = itemView.findViewById(R.id.find_friend_profile_image);
find_friend_username = itemView.findViewById(R.id.find_friend_username);
find_friend_fullname = itemView.findViewById(R.id.find_friend_fullname);
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if(id == android.R.id.home)
{
SendUserToMainActivity();
}
return super.onOptionsItemSelected(item);
}
private void SendUserToMainActivity() {
Intent mainIntent = new Intent(FindFriendsActivity.this, MainActivity.class);
startActivity(mainIntent);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.search_menu, menu);
MenuItem menuItem = menu.findItem(R.id.search_friend);
SearchView searchView = (SearchView) menuItem.getActionView();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
return false;
}
@Override
public boolean onQueryTextChange(String s) {
LoadUsers(s);
return false;
}
});
return true;
}
}<file_sep>/settings.gradle
include ':app'
rootProject.name = "Shetta"<file_sep>/app/src/main/java/com/kevalshetta/shetta/Utils/Comments.java
package com.kevalshetta.shetta.Utils;
public class Comments {
private String date, comment, profileimage, username;
public Comments() {
}
public Comments(String date, String comment, String profileimage, String username) {
this.date = date;
this.comment = comment;
this.profileimage = profileimage;
this.username = username;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
public String getProfileimage() {
return profileimage;
}
public void setProfileimage(String profileimage) {
this.profileimage = profileimage;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
}
<file_sep>/app/src/main/java/com/kevalshetta/shetta/Friends/FriendsListActivity.java
package com.kevalshetta.shetta.Friends;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.kevalshetta.shetta.Chat.ChatActivity;
import com.kevalshetta.shetta.Post.MainActivity;
import com.kevalshetta.shetta.R;
import com.squareup.picasso.Picasso;
import org.jetbrains.annotations.NotNull;
import de.hdodenhof.circleimageview.CircleImageView;
public class FriendsListActivity extends AppCompatActivity {
private Toolbar toolbar;
private RecyclerView friends_list;
private DatabaseReference FriendsRef, UsersRef;
private FirebaseAuth mAuth;
private String currentUserID;
private TextView totalFriends;
private int countFriends = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_friends_list);
toolbar = findViewById(R.id.app_bar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setTitle("My Friend");
friends_list = (RecyclerView) findViewById(R.id.friends_list);
friends_list.setHasFixedSize(true);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
linearLayoutManager.setReverseLayout(true);
linearLayoutManager.setStackFromEnd(true);
friends_list.setLayoutManager(linearLayoutManager);
mAuth = FirebaseAuth.getInstance();
currentUserID = mAuth.getCurrentUser().getUid();
FriendsRef = FirebaseDatabase.getInstance().getReference().child("Friends").child(currentUserID);
UsersRef = FirebaseDatabase.getInstance().getReference().child("Users");
totalFriends = findViewById(R.id.totalFriends);
}
@Override
protected void onStart() {
super.onStart();
FirebaseRecyclerOptions options =
new FirebaseRecyclerOptions.Builder<Friends>()
.setQuery(FriendsRef, Friends.class)
.build();
final FirebaseRecyclerAdapter<Friends,FriendsListHolder> adapter = new FirebaseRecyclerAdapter<Friends, FriendsListHolder>(options) {
@Override
protected void onBindViewHolder(@NonNull @NotNull FriendsListHolder holder, int position, @NonNull @NotNull Friends model) {
final String userIDs = getRef(position).getKey();
final String[] userImage = {"default_image"};
UsersRef.child(userIDs).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull @NotNull DataSnapshot snapshot) {
if (snapshot.exists()){
if (snapshot.hasChild("profileimage"))
{
userImage[0] = snapshot.child("profileimage").getValue().toString();
Picasso.get().load(userImage[0]).placeholder(R.drawable.profile).into(holder.friends_profile_image);
}
String profileName = snapshot.child("username").getValue().toString();
String profilefName = snapshot.child("fullname").getValue().toString();
String profileStatus = snapshot.child("description").getValue().toString();
holder.friend_user_name.setText(profileName);
holder.friend_full_name.setText(profilefName);
holder.friend_caption.setText(profileStatus);
holder.friend_send_message.setVisibility(View.VISIBLE);
holder.friend_send_message.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent chatIntent = new Intent(FriendsListActivity.this, ChatActivity.class);
chatIntent.putExtra("visit_user_id",userIDs);
chatIntent.putExtra("visit_user_name",profileName);
chatIntent.putExtra("visit_image", userImage[0]);
startActivity(chatIntent);
}
});
}
}
@Override
public void onCancelled(@NonNull @NotNull DatabaseError error) {
}
});
FriendsRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull @NotNull DataSnapshot snapshot) {
if (snapshot.exists()){
countFriends = (int) snapshot.getChildrenCount();
totalFriends.setText(Integer.toString(countFriends) + " Friend");
}
else{
totalFriends.setText("0 Friends");
}
}
@Override
public void onCancelled(@NonNull @NotNull DatabaseError error) {
}
});
}
@NonNull
@NotNull
@Override
public FriendsListHolder onCreateViewHolder(@NonNull @NotNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.friends_display_layout, parent, false);
return new FriendsListHolder(view);
}
};
friends_list.setAdapter(adapter);
adapter.startListening();
}
public static class FriendsListHolder extends RecyclerView.ViewHolder{
TextView friend_user_name, friend_caption, friend_full_name;
CircleImageView friends_profile_image;
ImageView friend_send_message;
public FriendsListHolder(@NonNull View itemView) {
super(itemView);
friend_user_name = itemView.findViewById(R.id.friend_user_name);
friend_caption = itemView.findViewById(R.id.friend_caption);
friend_full_name = itemView.findViewById(R.id.friend_full_name);
friends_profile_image = itemView.findViewById(R.id.friends_profile_image);
friend_send_message = itemView.findViewById(R.id.friend_send_message);
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if(id == android.R.id.home)
{
SendUserToMainActivity();
}
return super.onOptionsItemSelected(item);
}
private void SendUserToMainActivity() {
Intent mainIntent = new Intent(FriendsListActivity.this, MainActivity.class);
startActivity(mainIntent);
}
}<file_sep>/app/src/main/java/com/kevalshetta/shetta/Post/EditPost.java
package com.kevalshetta.shetta.Post;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.kevalshetta.shetta.R;
import com.squareup.picasso.Picasso;
import org.jetbrains.annotations.NotNull;
public class EditPost extends AppCompatActivity {
private ImageView postImage;
private TextView postDescription;
private Button deletePost, editPost;
private DatabaseReference ClickPostRef;
private String PostKey, currentUserId, databaseUserId, age;
private FirebaseAuth mAuth;
private Toolbar toolbar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_post);
toolbar = findViewById(R.id.app_bar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setTitle("Edit Post");
mAuth = FirebaseAuth.getInstance();
currentUserId = mAuth.getCurrentUser().getUid();
PostKey = getIntent().getExtras().get("PostKey").toString();
age = getIntent().getExtras().get("age").toString();
ClickPostRef = FirebaseDatabase.getInstance().getReference().child("Posts").child(PostKey);
postImage = findViewById(R.id.edit_post);
postDescription = findViewById(R.id.editPostDesc);
deletePost = findViewById(R.id.deletePost);
editPost = findViewById(R.id.editPost);
ClickPostRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull @NotNull DataSnapshot snapshot) {
if (snapshot.exists()){
String des = snapshot.child("description").getValue().toString();
String image = snapshot.child("postimage").getValue().toString();
String uid = snapshot.child("uid").getValue().toString();
postDescription.setText(des);
Picasso.get().load(image).into(postImage);
if (currentUserId.equals(uid)){
deletePost.setVisibility(View.VISIBLE);
editPost.setVisibility(View.VISIBLE);
}else{
deletePost.setVisibility(View.INVISIBLE);
editPost.setVisibility(View.INVISIBLE);
}
editPost.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
EditCurrentPost(des);
}
});
}
}
@Override
public void onCancelled(@NonNull @NotNull DatabaseError error) {
}
});
deletePost.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
DeleteCurrentPost();
}
});
}
private void EditCurrentPost(String des) {
AlertDialog.Builder builder = new AlertDialog.Builder(EditPost.this, R.style.AlertDialogTheme);
builder.setTitle("Edit Post:");
final EditText inputField = new EditText(EditPost.this);
inputField.setText(des);
builder.setView(inputField);
builder.setPositiveButton("Update", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
ClickPostRef.child("description").setValue(inputField.getText().toString());
Toast.makeText(EditPost.this, "Post updated successfully...", Toast.LENGTH_SHORT).show();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
Dialog dialog = builder.create();
dialog.show();
dialog.getWindow().setBackgroundDrawableResource(android.R.color.darker_gray);
}
private void DeleteCurrentPost() {
ClickPostRef.removeValue().addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull @NotNull Task<Void> task) {
SendUserToMainActivity();
Toast.makeText(EditPost.this, "New Post is updated successfully.", Toast.LENGTH_SHORT).show();
}
});
FirebaseStorage firebaseStorage = FirebaseStorage.getInstance();
StorageReference storageReference = firebaseStorage.getReferenceFromUrl(age);
storageReference.delete().addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
Log.e("Picture","#deleted");
}
});
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if(id == android.R.id.home)
{
SendUserToMainActivity();
}
return super.onOptionsItemSelected(item);
}
private void SendUserToMainActivity() {
Intent mainIntent = new Intent(EditPost.this, MainActivity.class);
startActivity(mainIntent);
finish();
}
}<file_sep>/app/src/main/java/com/kevalshetta/shetta/Post/CommentsActivity.java
package com.kevalshetta.shetta.Post;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;
import com.kevalshetta.shetta.R;
import com.kevalshetta.shetta.Utils.Comments;
import com.squareup.picasso.Picasso;
import org.jetbrains.annotations.NotNull;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import de.hdodenhof.circleimageview.CircleImageView;
public class CommentsActivity extends AppCompatActivity {
private RecyclerView commRV;
private EditText commInputComments;
private ImageView commentSend;
private DatabaseReference UsersRef, commRef;
private FirebaseAuth mAuth;
private String postKey, currentUserID, saveCurrentDate;
private long countComments = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_comments);
postKey = getIntent().getExtras().get("PostKey").toString();
mAuth = FirebaseAuth.getInstance();
currentUserID = FirebaseAuth.getInstance().getCurrentUser().getUid();
UsersRef = FirebaseDatabase.getInstance().getReference().child("Users");
commRef = FirebaseDatabase.getInstance().getReference().child("Posts").child(postKey).child("Comment");
commRV = findViewById(R.id.commRV);
commRV.setHasFixedSize(true);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
linearLayoutManager.setReverseLayout(true);
linearLayoutManager.setStackFromEnd(true);
commRV.setLayoutManager(linearLayoutManager);
commInputComments = findViewById(R.id.commInputComments);
commentSend = findViewById(R.id.commentSend);
Date date = new Date();
SimpleDateFormat currentDate = new SimpleDateFormat("dd-MMMM-yyyy HH:mm:ss");
saveCurrentDate = currentDate.format(date);
commentSend.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
UsersRef.child(currentUserID).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull @NotNull DataSnapshot snapshot) {
if ((snapshot.exists()) && (snapshot.hasChild("profileimage")) && (snapshot.hasChild("fullname"))) {
String userName = snapshot.child("fullname").getValue().toString();
String userProfileImage = snapshot.child("profileimage").getValue().toString();
ValidateComment(userName, userProfileImage);
commInputComments.setText("");
}
}
@Override
public void onCancelled(@NonNull @NotNull DatabaseError error) {
}
});
}
});
}
private void ValidateComment(String userName, String userProfileImage) {
commRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull @NotNull DataSnapshot snapshot) {
if (snapshot.exists()){
countComments = snapshot.getChildrenCount();
}else{
countComments = 0;
}
}
@Override
public void onCancelled(@NonNull @NotNull DatabaseError error) {
}
});
String comment = commInputComments.getText().toString();
if (comment.isEmpty()){
Toast.makeText(CommentsActivity.this, "Please write comment...", Toast.LENGTH_SHORT).show();
}else{
final String randomkey = currentUserID + saveCurrentDate;
HashMap hashMap = new HashMap();
hashMap.put("username", userName);
hashMap.put("profileimage", userProfileImage);
hashMap.put("comment", comment);
hashMap.put("date", saveCurrentDate);
hashMap.put("counter", countComments);
commRef.child(randomkey).updateChildren(hashMap).addOnCompleteListener(new OnCompleteListener() {
@Override
public void onComplete(@NonNull @NotNull Task task) {
if (task.isSuccessful()){
Toast.makeText(CommentsActivity.this, "Comment send", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(CommentsActivity.this, ""+task.getException().toString(),Toast.LENGTH_SHORT).show();
}
}
});
}
}
@Override
protected void onStart() {
super.onStart();
Query sortComment = commRef.orderByChild("counter");
FirebaseRecyclerOptions options = new FirebaseRecyclerOptions.Builder<Comments>()
.setQuery(sortComment,Comments.class).build();
FirebaseRecyclerAdapter<Comments, CommentsViewHolder> adapter = new FirebaseRecyclerAdapter<Comments, CommentsViewHolder>(options) {
@Override
protected void onBindViewHolder(@NonNull @NotNull CommentsViewHolder holder, int position, @NonNull @NotNull Comments model) {
holder.comment_username.setText(model.getUsername());
holder.commentsTv.setText(model.getComment());
Picasso.get().load(model.getProfileimage()).into(holder.profileImage_comment);
}
@NonNull
@NotNull
@Override
public CommentsViewHolder onCreateViewHolder(@NonNull @NotNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.single_view_comment, parent, false);
return new CommentsViewHolder(view);
}
};
commRV.setAdapter(adapter);
adapter.startListening();
}
public class CommentsViewHolder extends RecyclerView.ViewHolder{
CircleImageView profileImage_comment;
TextView comment_username, commentsTv, time;
public CommentsViewHolder(@NonNull @NotNull View itemView) {
super(itemView);
profileImage_comment = itemView.findViewById(R.id.profileImagecomment);
comment_username = itemView.findViewById(R.id.comment_username);
commentsTv = itemView.findViewById(R.id.commentsTv);
time = itemView.findViewById(R.id.commentTime);
}
}
} | d647926c83e726e2533c0c73e6df66926d37690b | [
"Java",
"Gradle"
]
| 6 | Java | KevalShetta20/Buddiesgram.github.io | 910c006045f874778eec08d3eb7c5b45e596d394 | 1f35a0c82f31900124dc8f47ba30ce06a9427b9d |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.