branch_name
stringclasses 149
values | text
stringlengths 23
89.3M
| directory_id
stringlengths 40
40
| languages
listlengths 1
19
| num_files
int64 1
11.8k
| repo_language
stringclasses 38
values | repo_name
stringlengths 6
114
| revision_id
stringlengths 40
40
| snapshot_id
stringlengths 40
40
|
|---|---|---|---|---|---|---|---|---|
refs/heads/master
|
<file_sep>/// \file ExG4ActionInitialization01.hh
/// \brief Definition of the ExG4ActionInitialization01 class
#ifndef ExG4ActionInitialization01_h
#define ExG4ActionInitialization01_h 1
#include "G4VUserActionInitialization.hh"
/// Обязательный класс, который должен быть объявлен в проекте Geant4
/// Имя класса может быть другим, и он должен наследоваться от
/// класса G4VUserActionInitialization
class ExG4ActionInitialization01 : public G4VUserActionInitialization
{
public:
ExG4ActionInitialization01();//Конструктор
virtual ~ExG4ActionInitialization01();//Деструктор
virtual void Build() const;//Создание источника первичных частиц
};
#endif
<file_sep>// Подключаем заголовочные файлы
#include "G4RunManager.hh" // RunManager, класс из ядра Geant4,
//должен быть включен обязательно
#include "G4UImanager.hh" // Менеджер взаимодействия с пользователем
#include "ExG4DetectorConstruction01.hh" // Структура детектора,
//должна определяться пользователем
#include "FTFP_BERT.hh" // Подключается физика и используемые частицы
//в проекте, готовый физический лист из Geant4
#include "ExG4ActionInitialization01.hh" // Пользовательский класс
//для задания начального источника частиц
#include "G4VisExecutive.hh"//Визуализация
#include "G4UIExecutive.hh"//Выбор соответствующего интерфейса пользователя
#include "G4UIterminal.hh"
//#ifdef G4UI_USE //Если используется интерфейс пользователя то включаем визуализацию
//#include "G4VisExecutive.hh"//Визуализация
//#endif
int main(int argc,char** argv)
{
// Создание класса G4RunManager, он контролирует выполнение программы и
// управляет событиями при запуске проекта
G4RunManager* runManager = new G4RunManager;
// Установка обязательных инициализирующих классов
// Создание и объявление геометрии, материала детектора и мишени
// т.е. моделируемой установки
runManager->SetUserInitialization(new ExG4DetectorConstruction01);
// Создание физического листа - набора моделируемых частиц и физических процессов
// которые используются в данном моделировании.
// Используется готовый из Geant4
runManager->SetUserInitialization(new FTFP_BERT);
// Объявление начальных частиц (параметры пучка) и
// подключение прочих классов, используемых
// для получения данных о частицах в процессе моделирования
runManager->SetUserInitialization(new ExG4ActionInitialization01);
// Инициализация ядра Geant4
runManager->Initialize();
// Объявления менеджера визуализации
G4VisManager* visManager = new G4VisExecutive;
// Инициализация менеджера визуализации
visManager->Initialize();
// Получение указателя на менеджера взаимодействия с пользователем
// нужен, что бы можно было отправлять команды в проект
G4UImanager* UImanager = G4UImanager::GetUIpointer();
// Проверяем или были переданы через командную сроку параметры
if ( argc == 1 ) {//Если через командную строку ничего не передавалось
// То устанавливаем интерактивный режим
// Если используется визуализация
G4UIExecutive* ui = new G4UIExecutive(argc, argv);//Создание интерфейса пользователя
UImanager->ApplyCommand("/control/execute vis.mac");//Отрисовываем по заранее подготовленному
// файлу vis.mac
ui->SessionStart();//Запуск интерфейса пользователя
delete ui;//Удаление интерфейса пользователя
}
else {
// Если были переданы параметры, по включаем пакетный режим
G4String command = "/control/execute ";//Записываем в строковую переменную
// команду выполнить
G4String fileName = argv[1];//Имя файла из командной строки при запуске проекта
// Мы считаем, что первым параметром было передано имя файла с командами для запуска
// проекта в пакетном режиме
UImanager->ApplyCommand(command+fileName);//Выполнение команды
}
// Окончание работы, вызов деструктора (удаление) G4RunManager
delete runManager;
return 0;
}
<file_sep>#include<G4VSensitiveDetector.hh>
#ifndef ExG4DetectorSD_h
#define ExG4DetectorSD_h 1
class G4Step;
class G4TouchableHistory;
/// Класс определения чувствительной области детектора
class ExG4DetectorSD: public G4VSensitiveDetector
{
private:
//Создадим гистограмму в которую запишем распределение
//энергии протонов
//Число бинов (интервалов в гистограмме)
static const int NOBINS = 1000;
//Максимальная энергия в гистограмме
const double HIST_MAX;
//Минимальная энергия в гистограмме
const double HIST_MIN;
//Объявляем саму гистограмму
int histogram[NOBINS];
//Постоим также угол, на который рассеялся протон
int histogram_angle[NOBINS];
public:
//Контструктора, в нем обнуляем гистограммы
ExG4DetectorSD(G4String name);
//Декструктор, в нем выведем гистограммы в файл
//Вывод данных в файл лучше делать здесь чем в ProcessHits, так как
//вызов деструктора происходит в конце работы программы,
//а если записывать в процессе моделирования, то значительное
//время будет тратится на ожидание записи в файл. А это относительно
//медленная процедура и занимает много времени и в результате
//моделирование будет занимать больше времени чем нужно.
~ExG4DetectorSD();
//Когда частица попадает в этот чувствительный объем, тогда на каждом
//её шаге моделирования вызывается эта функция.
//В ней мы можем получить и передать информацию о состоянии
//частицы, и ее треке
G4bool ProcessHits(G4Step* step, G4TouchableHistory* history);
};
#endif /* SENSITIVEDETECTOR */
<file_sep>/// \file ExG4DetectorConstruction01.cpp
/// \brief Implementation of the ExG4DetectorConstruction01 class
#include "ExG4DetectorConstruction01.hh"
#include "ExG4DetectorSD.hh"
#include "G4RunManager.hh"
#include "G4SDManager.hh"
#include "G4NistManager.hh"
#include "G4Box.hh"
#include "G4LogicalVolume.hh"
#include "G4PVPlacement.hh"
#include "G4SystemOfUnits.hh"
// Конструктор класса объявления материалов и геометрии всей моделируемой системы
ExG4DetectorConstruction01::ExG4DetectorConstruction01()
: G4VUserDetectorConstruction()
{ }
// Деструктор
ExG4DetectorConstruction01::~ExG4DetectorConstruction01()
{ }
// Функция определения материалов и геометрии всей системы,
// должна возвращать физический объем - ссылку на экземпляр класса G4VPhysicalVolume
// Геометрию проектировать будем следующую: пучок протонов попадает на мишень
// вольфрамовый лист толщиной около 1 мм, а за мишень поставим детектор
// таких же размеров, он будет регистрировать что в него попало.
G4VPhysicalVolume* ExG4DetectorConstruction01::Construct()
{
// Для простоты используем предопределенные в Geant4 материалы
// Так объявляется менеджер, из которого можно извлечь
// ранее предопределенные материалы
G4NistManager* nist = G4NistManager::Instance();
// Параметры детектора
G4double det_sizeXY = 25*cm, det_sizeZ = 0.15*cm;
// Материал детектора, здесь выбираем вольфрам
G4Material* det_mat = nist->FindOrBuildMaterial("G4_W");
// Опция для включения/выключения проверки перекрытия объемов
G4bool checkOverlaps = true;
// World
// Объем мира, самый большой объем, включающий остальные, аналог экспериментального
// зала
G4double world_sizeXY = 30*cm;//Размер по x и y здесь будут одинаковы - ширина и высота
G4double world_sizeZ = 20*cm;//Размер по z - толщина
// Выбор материала для мира из предопределенных в Geant4, для зала берем воздух
G4Material* world_mat = nist->FindOrBuildMaterial("G4_AIR");
// Создание объема для мира (экспериментального зала), определяется сама форма объема,
// берем параллелепипед, это просто геометрическая фигура
G4Box* solidWorld =
new G4Box("World", //its name, название объема
0.5*world_sizeXY, 0.5*world_sizeXY, 0.5*world_sizeZ); //its size, его размеры
// указываются половины размеров высоты, ширины и глубины
// Логический объем, здесь подключается материал, из которого сделан объем
G4LogicalVolume* logicWorld =
new G4LogicalVolume(solidWorld, //its solid, геометрический объем, объявлен выше
world_mat, //its material, материал объема
"World"); //its name, название логического объема
//совпадает с названием объема, но
//для Geant4 это разные объекты
//геометрический объем и логический объем
//Физический объем, а теперь наш логический объем помещаем в "реальный" мир
G4VPhysicalVolume* physWorld =
new G4PVPlacement(0, //no rotation, нет вращения
G4ThreeVector(), //at (0,0,0), расположение в центре (0,0,0)
logicWorld, //its logical volume, логический объем этого физического
"World", //its name, название физического объема
0, //its mother volume, материнский объем, этот самый первый, поэтому 0
false, //no boolean operation, без логических (булевых) операций
0, //copy number, номер копии
checkOverlaps); //overlaps checking, флаг проверки перекрытия объемов
// Детектор, для него также используем параллелепипед
G4Box* solidDet =
new G4Box("Detector", //its name, имя
0.5*det_sizeXY, 0.5*det_sizeXY, 0.5*det_sizeZ); //its size, размеры
//Логический объем
G4LogicalVolume* logicDet =
new G4LogicalVolume(solidDet, //its solid, объем
det_mat, //its material, указываем материал детектора
"Detector"); //its name, его имя
//Физический объем детектора
new G4PVPlacement(0, //no rotation, так же без вращения
G4ThreeVector(0,0,5*cm), //at (0,0,5 см) положение центра детектора, он смещен на 5 см от центра объема World
logicDet, //its logical volume, подключаем логический объем
"Detector", //its name, имя физического объема
logicWorld, //its mother volume, родительский логический объем, помещаем в world!
false, //no boolean operation, без булевых операций
0, //copy number, номер копии
checkOverlaps); //overlaps checking, флаг проверки перекрытия объемов
// Для мишени, на которую будет падать пучек, возьмем геометрические размеры как
// у детектора, параллелепипед - лист вольфрама.
//Логический объем
G4LogicalVolume* logicTar =
new G4LogicalVolume(solidDet, //its solid, объем
det_mat, //its material, указываем материал мишени
"Target"); //its name, его имя
//Физический объем мишени
new G4PVPlacement(0, //no rotation, так же без вращения
G4ThreeVector(0,0,-5*cm),//at (0,0,-5 см) положение центра мишени в другую сторону от детектора, смещена на 5 см от центра объема World
logicTar, //its logical volume, подключаем логический объем
"Target", //its name, имя физического объема
logicWorld, //its mother volume, родительский логический объем!
false, //no boolean operation, без булевых операций
0, //copy number, номер копии
checkOverlaps);
//Всегда возвращает физический объем
return physWorld;
}
void ExG4DetectorConstruction01::ConstructSDandField()
{
// Объявление чувствительной области детектора, в которой можно получить подробную
// информацию о состоянии и движении частицы
// Назовем чувствительную область DetectorSD
G4String trackerChamberSDname = "DetectorSD";
// Создаем экземпляр чувствительной области
ExG4DetectorSD* aTrackerSD = new ExG4DetectorSD(trackerChamberSDname);
// Передаем указатель менеджеру
G4SDManager::GetSDMpointer()->AddNewDetector(aTrackerSD);
// Добавляем чувствительный объем ко всем логическим областям с
// именем Detector
SetSensitiveDetector("Detector", aTrackerSD, true);
}
<file_sep>#include<G4Step.hh>
#include<fstream>
#include<iostream>
#include "G4SystemOfUnits.hh"
#include "G4ThreeVector.hh"
#include "ExG4DetectorSD.hh"
// Используем пространство имен std, что бы не писать много где std::
using namespace std;
// Конструктор чувствительной области, по умолчанию инициализируем нижнюю и верхнюю
// границы гистограммы в 0 и 50 МэВ
ExG4DetectorSD::ExG4DetectorSD(G4String name): G4VSensitiveDetector(name),
HIST_MAX(50*MeV),// Инициализация верхней границы
HIST_MIN(0 *MeV)// Инициализация нижней границы
{
// Обнуляем гистограммы
for(int i = 0; i<NOBINS; i++){
histogram[i] = 0;
histogram_angle[i] = 0;
}
}
//Вызывается на каждом шаге моделирования частицы, когда она попадает в этот чувствительный объем
G4bool ExG4DetectorSD::ProcessHits(G4Step* step, G4TouchableHistory* history)
{
// Получаем кинетическую энергии частицы с предыдущего шага, т.е. начальную
// кинетическую энегрию перед текущим шагом
double energy = step->GetPreStepPoint()->GetKineticEnergy();
// Вычисляем ширину бина (интерва) гистограммы
double bin_width = (HIST_MAX - HIST_MIN) / NOBINS;
// Если имя частицы протон (proton), тогда заполняем гистограммы
if(step->GetTrack()->GetDefinition()->GetParticleName() == "proton" ){
// Определяем индекс (номер) бина гистограммы энергии
int index = int(floor((energy-HIST_MIN)/bin_width));
// Добавляем +1 в соответствующий бин
if(index >= 0 && index < NOBINS)
histogram[index]++;
// Далее заполняем гистограмму углового распределения
// Получаем вектор направления частицы
G4ThreeVector ang = step->GetPreStepPoint()->GetMomentumDirection();
// Задаем единичный вектор в направлении оси OZ
G4ThreeVector *centerVector = new G4ThreeVector(0, 0, 1);
// Применяем фунцию класса G4ThreeVector - находим угол относительно
// вектора centerVector
double angle=ang.angle(*centerVector);
// Определяем ширину бина в гистограмме углового распределения.
// Так как у нас измеряются углы между векторами, то максимальный
// угол равен пи 3.14, минимальный 0
double bin_width_ang = (3.14) / NOBINS;
// Получаем номер бина
index = int(floor((angle)/bin_width_ang));
// Заполняем гистограмму
if(index >= 0 && index < NOBINS)
histogram_angle[index]++;
}
// Так как мы хотим только измерить параметры частиц после прохождения
// мишени и не интересуемся дальнейшей их судьбой в детекторе, то их убиваем -
// устанавливаем статус остановлено и уничтожено (fStopAndKill)
step->GetTrack()->SetTrackStatus(fStopAndKill);
return true;
}
ExG4DetectorSD::~ExG4DetectorSD()
{
// В деструкторе выводим гистограммы в файлы
// Открываем файл (существующий файл полностью перезаписывается)
std::ofstream file("spectrum.dat");
// Вычисляем ширину бина
double bin_width = (HIST_MAX - HIST_MIN) / NOBINS;
// Выводим гистограмму
for(int i = 0; i<NOBINS; i++)
{
// Вычисляем энергию
double energy = i*bin_width + HIST_MIN;
// Выводим в файл
file << std::setw(15) << energy/MeV << " "
<< std::setw(15) << histogram[i] << std::endl;
}
// Закрываем файл
file.close();
// Открываем файл для вывода гистограммы углового распределения
file.open("angle.dat");
// Вычисляем ширину бина
bin_width = (3.14) / NOBINS;
// Выводим гистограмму
for(int i = 0; i<NOBINS; i++)
{
// Вычисляем угол
double angle = i*bin_width;
// Выводим в файл
file << std::setw(15) << angle << " "
<< std::setw(15) << histogram_angle[i] << std::endl;
}
// Закрываем файл
file.close();
}
<file_sep>#include "ExG4ActionInitialization01.hh"
#include "ExG4PrimaryGeneratorAction01.hh"//Подключаем обязательный класс
//в котором описываются источник начальных частиц
/// Обязательный класс, который должен быть объявлен в проекте Geant4
/// Имя класса может быть другим, и он должен наследоваться от
/// класса G4VUserActionInitialization
/// Конструктор
ExG4ActionInitialization01::ExG4ActionInitialization01()
: G4VUserActionInitialization()
{}
//Деструктор, ничего не объявляли, поэтому оставим пустым
ExG4ActionInitialization01::~ExG4ActionInitialization01()
{}
//Создание источника первичных частиц
void ExG4ActionInitialization01::Build() const
{
SetUserAction(new ExG4PrimaryGeneratorAction01);//Задается источник первичных частиц
// через обязательный класс ExG4PrimaryGeneratorAction01
}
<file_sep>#ifndef ExG4DetectorConstruction01_h
#define ExG4DetectorConstruction01_h 1
#include "G4VUserDetectorConstruction.hh"
#include "globals.hh"
class G4VPhysicalVolume;
class G4LogicalVolume;
/// \brief The ExG4DetectorConstruction01 class Класс геометрии установки,
/// объявление материалов и детекторов
class ExG4DetectorConstruction01 : public G4VUserDetectorConstruction
{
public:
//Конструктор, вызывается при создании экземпляра класса
//Обычно используется для задания начальных значений и значений по умолчанию
//при создании геометрии и материалов
ExG4DetectorConstruction01();
//Деструктор, вызывается при удалении экземпляра класса
//Обычно используется для освобождения памяти инициализированных массивов внутри класса
virtual ~ExG4DetectorConstruction01();
//Объявление и создание детекторов и среды
virtual G4VPhysicalVolume* Construct();
//Установка чувствительного объема. Когда частица в нем, то в нем извлекается
//вся информация о треке и параметрах частицы на каждом шаге моделирования
virtual void ConstructSDandField();
protected:
};
#endif
<file_sep>
/// \file ExG4PrimaryGeneratorAction01.cpp
/// \brief Implementation of the ExG4PrimaryGeneratorAction01 class
#include "ExG4PrimaryGeneratorAction01.hh"
// Подключаем необходимы заголовочные файлы
#include "G4LogicalVolumeStore.hh"
#include "G4LogicalVolume.hh"
#include "G4Box.hh"
#include "G4RunManager.hh"
#include "G4ParticleGun.hh"
#include "G4ParticleTable.hh"
#include "G4ParticleDefinition.hh"
#include "G4SystemOfUnits.hh"
#include "Randomize.hh"
// Класс, в котором описывается положение, тип, энергия, направление вылета
// и распределение начальных частиц
ExG4PrimaryGeneratorAction01::ExG4PrimaryGeneratorAction01()
: G4VUserPrimaryGeneratorAction(),
fParticleGun(0),
fEnvelopeBox(0)
{
// По умолчанию поставим 1 частицу
G4int n_particle = 1;
fParticleGun = new G4ParticleGun(n_particle);
// Получаем встроеную в Geant4 таблицу частиц
G4ParticleTable* particleTable = G4ParticleTable::GetParticleTable();
G4String particleName;
// Ищем частицу, в нашем случае протон
G4ParticleDefinition* particle
= particleTable->FindParticle(particleName="proton");
// Устанавливаем полученную частицу в качестве испускаемого типа начальных частиц в источнике
fParticleGun->SetParticleDefinition(particle);
// Устанавливаем направление движение частицы по (x,y,z)
// Здесь устанавливается направление вдоль оси Z
fParticleGun->SetParticleMomentumDirection(G4ThreeVector(0.,0.,1.));
// Установка начальной энергии испускаемых частиц, 50 МэВ
fParticleGun->SetParticleEnergy(50*MeV);
}
// Деструктор
ExG4PrimaryGeneratorAction01::~ExG4PrimaryGeneratorAction01()
{
// удаляем созданный в конструкторе экземпляр класса источника G4ParticleGun
delete fParticleGun;
}
void ExG4PrimaryGeneratorAction01::GeneratePrimaries(G4Event* anEvent)
{
//Эта функция вызывается в начале каждого первичного события запуска частицы
// Для избежания зависимости этого класса от класса DetectorConstruction,
// мы получаем ссылку на объем детектора через класс G4LogicalVolumeStore
G4double envSizeXY = 0;
G4double envSizeZ = 0;
// Проверяем или ссылка на fEnvelopeBox пустая
if (!fEnvelopeBox)
{
// Если пустая, то получаем ссылку на объем детектора
G4LogicalVolume* envLV
= G4LogicalVolumeStore::GetInstance()->GetVolume("Detector");
if ( envLV ) fEnvelopeBox = dynamic_cast<G4Box*>(envLV->GetSolid());
}
// Получаем размеры объема, стороны по x и y предполагается что одинаковы
if ( fEnvelopeBox ) {
envSizeXY = fEnvelopeBox->GetXHalfLength()*2.;
envSizeZ = fEnvelopeBox->GetZHalfLength()*2.;
}
else {//Если ссылка на fEnvelopeBox пустая, выдаем предупреждение
G4ExceptionDescription msg;
msg << "Envelope volume of box shape not found.\n";
msg << "Perhaps you have changed geometry.\n";
msg << "The gun will be place at the center.";
G4Exception("B1PrimaryGeneratorAction::GeneratePrimaries()",
"MyCode0002",JustWarning,msg);
}
// Объявляем переменные положения пушки частиц
G4double x0 = 0;
G4double y0 = 0;
G4double z0 = -0.5 * 20*cm;
// Устанавливаем положение
fParticleGun->SetParticlePosition(G4ThreeVector(x0,y0,z0));
// Генерируем первичное событие
fParticleGun->GeneratePrimaryVertex(anEvent);
}
<file_sep>/// \file ExG4PrimaryGeneratorAction01.hh
/// \brief Definition of the ExG4PrimaryGeneratorAction01 class
#ifndef B1PrimaryGeneratorAction_h
#define B1PrimaryGeneratorAction_h 1
#include "G4VUserPrimaryGeneratorAction.hh"
#include "G4ParticleGun.hh"
#include "globals.hh"
class G4ParticleGun;
class G4Event;
class G4Box;
/// Класс определения источника первичных частиц
class ExG4PrimaryGeneratorAction01 : public G4VUserPrimaryGeneratorAction
{
public:
ExG4PrimaryGeneratorAction01();
virtual ~ExG4PrimaryGeneratorAction01();
// Метод из базового класса, задает параметры источника начальных частиц
virtual void GeneratePrimaries(G4Event*);
// Метод для доступа к источнику частиц (пушке частиц ;) )
const G4ParticleGun* GetParticleGun() const { return fParticleGun; }
private:
G4ParticleGun* fParticleGun; // указатель на источник частиц
// Временная переменная объема
G4Box* fEnvelopeBox;
};
#endif
|
3bc2e95a172d99b5d0d90434e27793461ae2565e
|
[
"C++"
] | 9
|
C++
|
Vlad-Orlov/Basic-Simulation
|
230232d3b4e0fcc7b9bcee6cc2e76b5bf7550e46
|
5561e1a5a81835cb3c0719a1d5fc9d1ea0f9f499
|
refs/heads/master
|
<file_sep>#include "vmcsolver.h"
#include "lib.h"
#include "WaveFunction.h"
#include "hamiltonian.h"
#include "slaterdeterminant.h"
#include "correlation.h"
#include "minimise.h"
#include <armadillo>
#include <fstream>
#include <iostream>
#include <mpi.h>
using namespace arma;
using namespace std;
VMCSolver::VMCSolver():
nDimensions(3), //No of dimensions (1D, 2D, 3D, ...)
charge(10), //Charge of atomic nucleus
nParticles(10), //No of electrons in atom
h(0.001), //Constants used in numeric derivatives
h2(1000000),
nCycles(1000000), //No of MC cycles
timestep(0.01), //Timestep in importance sampling
D(0.5), //Constant in importance sampling
stepLength(1), //Steplength in brute force Monte Carlo
minimise_var(false), //Use optimizer to find best values for alpha and beta
min_steps(50000),//Number of MC cycles for optimizer to run
alpha(11),
beta(0.2)
{
}
void VMCSolver::runMonteCarloIntegration(int argc, char *argv[])
{
bool printToFile = true; //Print blocking files
slaterDeterminant *slater = new slaterDeterminant(nParticles, nDimensions);
Hamiltonian *hamiltonian = new Hamiltonian(nParticles, nDimensions, h, h2, charge);
correlation *corr = new correlation(nParticles, nDimensions);
double energies = 0;
double energySquareds = 0;
long idum = -1; //Random generator seed
int id, np;
//Start parallel threads
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &id);
MPI_Comm_size(MPI_COMM_WORLD, &np);
//Start timing
double myTime,mintime, maxtime,avgtime;
myTime = MPI_Wtime();
//No of steps per thread
int mpi_steps = nCycles/np;
idum = idum-id;
double* allEnergies = new double[mpi_steps+1];
double pEnergies = 0;
double pEnergySquareds = 0;
vec energySums = zeros<vec>(2);
cout << "ID: " << id << endl;
if(minimise_var) { //If optimization of alpha and beta
double gtol = 1e-4;
int iter;
double fret;
vec p = zeros<vec>(2,1);
p(0) = alpha;
p(1) = beta;
int n = 2;
vec ans = steepest_descent(idum, p, n, gtol, min_steps, &iter, &fret, slater,corr, hamiltonian);
cout <<ans<<endl;
double alpha_new = ans(0);
double beta_new = ans(1);
MPI_Barrier(MPI_COMM_WORLD);
//Get average results, alpha, beta
MPI_Allreduce(&alpha_new, &alpha, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(&beta_new, &beta, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
alpha = alpha/np;
beta = beta/np;
cout << "Final alpha, beta: "<< alpha<<" "<<beta<<endl;
}
//Call to importance sampling MC or brute force MC:
energySums = MCImportance(idum, alpha, beta, mpi_steps, slater, hamiltonian, corr, allEnergies);
//energySums = MCSampling(idum, alpha, beta, mpi_steps, slater, hamiltonian, corr, allEnergies);
if(printToFile) { //If blocking, write to files
cout<<"Print to block file"<<endl;
ostringstream ost;
ost << "/home/anette/helium/examples/vmc-simple/DATA/data" << id << ".mat" ;
ofstream blockofile;
blockofile.open( ost.str( ).c_str( ),ios::out | ios::binary );
if (blockofile.is_open())
{
blockofile.write((char*)(allEnergies+1) , mpi_steps*sizeof(double)) ;
blockofile.close();
}
else cout << "Unable to open data file for process " << id << endl;
}
//Get average energy data
pEnergies = energySums(0)/(nCycles * nParticles);
pEnergySquareds = energySums(1)/(nCycles * nParticles);
cout << "--------------------------" << endl;
MPI_Barrier(MPI_COMM_WORLD);
//Gather energy data from threads
MPI_Allreduce(&pEnergies, &energies, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(&pEnergySquareds, &energySquareds, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
myTime = MPI_Wtime() - myTime;
MPI_Reduce(&myTime, &maxtime, 1, MPI_DOUBLE, MPI_MAX, 0, MPI_COMM_WORLD);
MPI_Reduce(&myTime, &mintime, 1, MPI_DOUBLE, MPI_MIN, 0,MPI_COMM_WORLD);
MPI_Reduce(&myTime, &avgtime, 1, MPI_DOUBLE, MPI_SUM, 0,MPI_COMM_WORLD);
MPI_Finalize();
//End of parallel threads
if (id == 0) {
cout << "Energies: " << energies << endl; //*2*13.6
cout << "Energy squareds: " << energySquareds << endl; //*2*13.6*2*13.6
avgtime /= np;
cout << "Min time: " << mintime << ", max time: " << maxtime << ", avg time: " << avgtime << endl;
}
delete[] allEnergies;
}
//Importance sampling MC:
vec VMCSolver::MCImportance(long idum, double alpha, double beta, int mpi_steps,
slaterDeterminant *slater, Hamiltonian *hamiltonian, correlation *corr,
double *allEnergies) {
vec qForceOld = zeros<vec>(nDimensions,1);
vec qForceNew = zeros<vec>(nDimensions,1);
mat rOld = zeros<mat>(nParticles, nDimensions);
mat rNew = zeros<mat>(nParticles, nDimensions);
double accepted_steps = 0;
double count_total = 0;
double deltaE = 0;
vec deltaPsi = zeros<vec>(2);
vec deltaPsiE = zeros<vec>(2);
double cycleE = 0;
double ratio = 1;
double ratioCorr = 1;
vec energySums = zeros<vec>(6);
//Get initial positions
for(int i = 0; i < nParticles; i++) {
for(int j = 0; j < nDimensions; j++) {
rOld(i,j) = gaussianDeviate(&idum)*sqrt(timestep);
}
}
//Build the full Slater matrix and invert (done only once):
slater->buildDeterminant(rOld, alpha, beta);
for(int cycle = 0; cycle < mpi_steps; cycle++) { // loop over Monte Carlo cycles
for(int i = 0; i < nParticles; i++) { //Particle loop (electrons)
ratio = 1.0;
qForceOld = slater->gradientWaveFunction(rOld, i, ratio, alpha, beta); //Quatum force
// New position, current particle
for(int d = 0; d < nDimensions; d++) {
rNew(i,d) = rOld(i,d) + gaussianDeviate(&idum)*sqrt(timestep) + qForceOld(d)*timestep*D;
}
//Move only one particle (i).
for (int g=0; g<nParticles; g++) {
if(g != i) {
for(int d=0; d<nDimensions; d++) {
rNew(g,d) = rOld(g,d);
}
}
}
//Get the ratio of the new to the old determinant (wavefunction), slater determinant and correlation
ratio = slater->getRatioDeterminant(i, rNew, alpha, beta);
ratioCorr = corr->getRatioJastrow(i, rOld, rNew, beta);
//Get new quantum force
qForceNew = slater->gradientWaveFunction(rNew, i, ratio, alpha, beta);
//Greens function
double greensFunction = 0;
for(int d=0; d<nDimensions; d++) {
greensFunction += 0.5*(qForceOld(d) + qForceNew(d)) * (0.5*D*timestep*(qForceOld(d) - qForceNew(d)) - rNew(i,d) + rOld(i,d));
}
greensFunction = exp(greensFunction);
++count_total;
// Check for step acceptance (if yes, update position and determinant, if no, reset position)
if(ran2(&idum) <= greensFunction * ratio*ratio * ratioCorr*ratioCorr) {
++accepted_steps;
slater->updateDeterminant(rNew, rOld, i, alpha, beta, ratio);
for(int j = 0; j < nDimensions; j++) {
rOld(i,j) = rNew(i,j);
}
}
else {
for(int j = 0; j < nDimensions; j++) {
rNew(i,j) = rOld(i,j);
}
}
// update energies
deltaE = hamiltonian->localEnergy(rNew, alpha, beta, slater,corr);
energySums(0) += deltaE;
energySums(1) += deltaE*deltaE;
allEnergies[cycle] += deltaE;
cycleE += deltaE;
if(minimise_var) { //If optimization of alpha, beta: Get derivatives of wavefunction
deltaPsi = hamiltonian->dPsi(rNew,alpha,beta,slater,corr);
deltaPsiE(0) = deltaE*deltaPsi(0);
deltaPsiE(1) = deltaE*deltaPsi(1);
energySums(2) += deltaPsi(0);
energySums(3) += deltaPsi(1);
energySums(4) += deltaPsiE(0);
energySums(5) += deltaPsiE(1);
}
} //End particle loop
allEnergies[cycle] = cycleE; //Save data for blocking
cycleE = 0;
} //End Monte Carlo loop
cout << "accepted steps: " << 100*accepted_steps/count_total << "%" << endl;
return energySums;
}
//Brute force MC
vec VMCSolver::MCSampling(long idum, double alpha, double beta, int mpi_steps,
slaterDeterminant *slater, Hamiltonian *hamiltonian,
correlation *corr, double *allEnergies) {
rOld = zeros<mat>(nParticles, nDimensions);
rNew = zeros<mat>(nParticles, nDimensions);
int accepted_steps = 0;
int count_total = 0;
double deltaE = 0;
double cycleE = 0;
vec energySums = zeros<vec>(2);
//Get initial trial positions
for(int i = 0; i < nParticles; i++) {
for(int j = 0; j < nDimensions; j++) {
rOld(i,j) = stepLength * (ran2(&idum) - 0.5);
}
}
rNew = rOld;
//Build the full Slater matrix and invert (done only once):
slater->buildDeterminant(rOld, alpha, beta);
for(int cycle = 0; cycle < mpi_steps; cycle++) { // loop over Monte Carlo cycles
for(int i = 0; i < nParticles; i++) { //Loop over particles
// New position current particle
for(int d = 0; d < nDimensions; d++) {
rNew(i,d) = rOld(i,d) + stepLength*(ran2(&idum) - 0.5);
}
++count_total;
//Get the ratio of the new to the old determinant (wavefunction), slater determinant and correlation
double ratioSlater = slater->getRatioDeterminant(i, rNew, alpha, beta);
double ratioCorr = corr->getRatioJastrow(i, rOld, rNew, beta);
// Check for step acceptance (if yes, update position, if no, reset position)
if(ran2(&idum) <= ratioSlater*ratioSlater*ratioCorr*ratioCorr) {
++accepted_steps;
slater->updateDeterminant(rNew, rOld, i, alpha, beta, ratioSlater);
for(int d = 0; d < nDimensions; d++) {
rOld(i,d) = rNew(i,d);
}
}
else {
for(int d = 0; d < nDimensions; d++) {
rNew(i,d) = rOld(i,d);
}
}
// update energies
deltaE = hamiltonian->localEnergy(rNew, alpha, beta, slater,corr);
//deltaE = hamiltonian->analyticEnergyH(rNew, alpha, beta);
energySums(0) += deltaE;
energySums(1) += deltaE*deltaE;
cycleE += deltaE;
} //Particles
allEnergies[cycle] += cycleE; //Save data for MC cycle, blocking
cycleE = 0;
} //Monte Carlo cycles
cout << "accepted steps: " << 100*accepted_steps/count_total << "%" << endl;
return energySums;
}
//Get randum numbers, Gaussian pdf
double VMCSolver::gaussianDeviate(long *idum) {
static int iset = 0;
static double gset;
double fac, rsq, v1, v2;
if ( idum < 0) iset =0;
if (iset == 0) {
do {
v1 = 2.*ran2(idum) -1.0;
v2 = 2.*ran2(idum) -1.0;
rsq = v1*v1+v2*v2;
} while (rsq >= 1.0 || rsq == 0.);
fac = sqrt(-2.*log(rsq)/rsq);
gset = v1*fac;
iset = 1;
return v2*fac;
} else {
iset =0;
return gset;
}
}
//Optimization of alpha, beta
vec VMCSolver::steepest_descent(long idum, vec &p, int n, double gtol, int min_steps, int *iter, double *fret,
slaterDeterminant *slater, correlation *corr, Hamiltonian *hamiltonian)
{
vec dPsi = zeros<vec>(2,1);
vec dPsi_Elocal = zeros<vec>(2,1);
double* allEnergies = new double[min_steps+1];
double alpha = p(0);
double beta = p(1);
double alpha_new = alpha;
double beta_new = beta;
vec dE = zeros<vec>(n);
vec dEold = zeros<vec>(n);
int maxIter = 20;
vec answers = zeros<vec>(n+2);
double E = 0;
double Enew = 0;
double alpha_step = 0.5;
double beta_step = 0.1;
int i = 0;
double test;
double step_reduce = 2;
//Get E for current alpha and beta, do MC sample
vec Es = MCImportance(idum, alpha,beta,min_steps, slater, hamiltonian, corr, allEnergies);
E = Es(0)/(min_steps * nParticles);
dPsi(0) = Es(2)/(min_steps * nParticles);
dPsi(1) = Es(3)/(min_steps * nParticles);
dPsi_Elocal(0) = Es(4)/(min_steps * nParticles);
dPsi_Elocal(1) = Es(5)/(min_steps * nParticles);
dE = gradE(dPsi, E, dPsi_Elocal); //Get derivatives of E wrt alpha and beta
cout <<"E: "<<E<<endl;
while(i<maxIter) { //Loop until enough iterations
alpha_new = alpha - alpha_step*dE(0); //Get new value of alpha
if(alpha_new < 0) { //If the new alpha is negative,
while(alpha_new < 0) { //Reduce step length until new alpha is positive
alpha_step = alpha_step/step_reduce;
alpha_new = alpha - alpha_step*dE(0);
}
}
cout<<"dE alpha: "<<dE(0)<<endl;
dEold = dE;
//Get E for current alpha and beta, do MC sample
Es = MCImportance(idum, alpha_new,beta,min_steps, slater, hamiltonian, corr, allEnergies);
Enew = Es(0)/(min_steps * nParticles);
dPsi(0) = Es(2)/(min_steps * nParticles);
dPsi(1) = Es(3)/(min_steps * nParticles);
dPsi_Elocal(0) = Es(4)/(min_steps * nParticles);
dPsi_Elocal(1) = Es(5)/(min_steps * nParticles);
dE = gradE(dPsi, E, dPsi_Elocal); //Get derivatives of E wrt alpha and beta
//If derivatives have changed sign, reduce step length
if(dE(0)*dEold(0) < 0) alpha_step = alpha_step/step_reduce;
if(dE(1)*dEold(1) < 0) beta_step = beta_step/step_reduce;
//cout <<"Enew: "<<Enew<<endl;
// test = abs(Enew-E);
// if(test < gtol) break;
// E = Enew;
cout <<"Alpha new: "<< alpha_new <<endl;
cout <<"dE, Step: "<< dEold(0)<<" "<<alpha_step << endl;
cout<<"Enew: "<<Enew<<endl;
beta_new = beta - beta_step*dE(1); //Get new value of alpha
if(beta_new < 0) { //If the new beta is negative,
while(beta_new < 0) { //Reduce step length until new beta is positive
beta_step = beta_step/step_reduce;
beta_new = beta - beta_step*dE(0);
}
}
dEold = dE;
//Get E for current alpha and beta, do MC sample
Es = MCImportance(idum, alpha_new,beta_new,min_steps, slater, hamiltonian, corr, allEnergies);
Enew = Es(0)/(min_steps * nParticles);
dPsi(0) = Es(2)/(min_steps * nParticles);
dPsi(1) = Es(3)/(min_steps * nParticles);
dPsi_Elocal(0) = Es(4)/(min_steps * nParticles);
dPsi_Elocal(1) = Es(5)/(min_steps * nParticles);
dE = gradE(dPsi, E, dPsi_Elocal); //Get derivatives of E wrt alpha and beta
//If derivatives have changed sign, reduce step length
if(dE(0)*dEold(0) < 0) alpha_step = alpha_step/step_reduce;
if(dE(1)*dEold(1) < 0) beta_step = beta_step/step_reduce;
cout <<"beta new: "<< beta_new<<" "<<endl;
cout <<"dE, Step: "<< dEold(1)<<" "<<beta_step<<" "<<endl;
cout<<"Enew: "<<Enew<<endl;
cout <<"----------"<<endl;
test = abs(Enew-E);
if(test < gtol) break; //If change in energy is smaller than tolerance, break out of loop
E = Enew; //Else: Update E, alpha and beta
alpha = alpha_new;
beta = beta_new;
i++;
}
answers(0) = alpha_new;
answers(1) = beta_new;
answers(2) = Enew;
answers(3) = i;
return answers;
}
//Get derivatives of energy E wrt alpha, beta
vec VMCSolver::gradE(vec dPsi, double Elocal, vec dPsi_Elocal) {
vec dE = zeros<vec>(2);
dE(0) = 2*(dPsi_Elocal(0) - dPsi(0)*Elocal);
dE(1) = 2*(dPsi_Elocal(1) - dPsi(1)*Elocal);
return dE;
}
<file_sep>#ifndef VMCSOLVER_H
#define VMCSOLVER_H
#include <armadillo>
#include "WaveFunction.h"
#include "hamiltonian.h"
#include "slaterdeterminant.h"
#include "correlation.h"
#include "minimise.h"
using namespace arma;
using namespace std;
class VMCSolver
{
public:
VMCSolver();
void runMonteCarloIntegration(int argc, char* argv[]);
private:
vec MCSampling(long idum, double alpha, double beta, int mpi_steps,
slaterDeterminant *slater, Hamiltonian *hamiltonian, correlation *corr,
double *allEnergies);
mat quantumForce(const mat &r, double alpha_, double beta_, double wf, WaveFunction *function);
double gaussianDeviate(long *idum);
vec MCImportance(long idum, double alpha, double beta, int mpi_steps,
slaterDeterminant *slater, Hamiltonian *hamiltonian, correlation *corr,
double *allEnergies);
vec gradE(vec dPsi, double Elocal, vec dPsi_Elocal);
vec steepest_descent(long idum, vec &pnew, int n, double gtol, int min_steps, int *iter, double *fret,
slaterDeterminant *slater, correlation *corr, Hamiltonian *hamiltonian);
mat rOld;
mat rNew;
int nDimensions;
double h;
double h2;
double timestep;
double D;
double stepLength;
int nCycles;
int charge;
int nParticles;
double alpha;
double beta;
bool minimise_var;
int min_steps;
};
#endif // VMCSOLVER_H
<file_sep>#ifndef WAVEFUNCTION_H
#define WAVEFUNCTION_H
#include <armadillo>
using namespace arma;
using namespace std;
class WaveFunction {
public:
WaveFunction(int &nParticles_, int &nDimensions_);
double waveFunction(const mat &r, double alpha, double beta);
vec gradientWaveFunction(const mat &r, int i, double alpha, double beta);
double laPlaceWaveFunction(const mat &r, int i, double alpha, double beta);
double psi1s(double rtot, double alpha);
double psi2s(double rtot, double alpha);
double psi2p0(double rtot, int i, const mat &r, double alpha);
double psi2p1(double rtot, int i, const mat &r, double alpha);
double psi2p_1(double rtot, int i, const mat &r, double alpha);
vec dPsi1s(double rtot, int i, const mat &r, double alpha);
vec dPsi2s(double rtot, int i, const mat &r, double alpha);
vec dPsi2p0(double rtot, int i, const mat &r, double alpha);
vec dPsi2p_1(double rtot, int i, const mat &r, double alpha);
vec dPsi2p1(double rtot, int i, const mat &r, double alpha);
double d2Psi1s(double rtot, double alpha);
double d2Psi2s(double rtot, double alpha);
double d2Psi2p0(double rtot, int i, const mat &r, double alpha);
double d2Psi2p_1(double rtot, int i, const mat &r, double alpha);
double d2Psi2p1(double rtot, int i, const mat &r, double alpha);
double dPsi1s_dalpha(double rtot, double alpha);
double dPsi2s_dalpha(double rtot, double alpha);
double dPsi2p0_dalpha(double rtot, int i, const mat &r, double alpha);
double dPsi2p_1_dalpha(double rtot, int i, const mat &r, double alpha);
double dPsi2p1_dalpha(double rtot, int i, const mat &r, double alpha);
private:
int nDimensions;
int nParticles;
double alpha;
double beta;
};
#endif // WAVEFUNCTION_H
<file_sep>#include "vmcsolver.h"
#include "lib.h"
#include "WaveFunction.h"
#include "hamiltonian.h"
#include <armadillo>
#include <fstream>
#include <iostream>
#include <mpi.h>
using namespace arma;
using namespace std;
VMCSolver::VMCSolver():
nDimensions(3), //No of dimensions (1D, 2D, 3D, ...)
charge(2), //Charge of atomic nucleus
nParticles(2), //No of electrons in atom
h(0.001), //Constants used in numeric derivatives
h2(1000000),
idum(-1), //Random generator seed
nCycles(1000000), //No of MC cycles
alpha_min(1.8), //Alpha, minimum value (loop over alpha values)
alpha_max(1.8), //Alpha, max value
alpha_steps(1), //No of steps in alpha loop
beta_min(0.6), //Beta, min value
beta_max(0.6), //Beta, max value
beta_steps(1), //No of steps in beta loop
timestep(0.01), //Timestep in importance sampling
D(0.5), //Constant in importance sampling
stepLength(1), //Steplength in brute force Monte Carlo
minimise_var(false), //Use optimizer to find best values for alpha and beta
min_steps(50000)//Number of MC cycles for optimizer to run
{
}
//Start the MC method
void VMCSolver::runMonteCarloIntegration(int argc, char *argv[])
{
bool print_blockdata = false; //Print data to file for blocking (standard deviation)
char file_energies[] = "../../../output/energy.txt"; //Print data to file (alpha/beta loops)
char file_energySquareds[] = "../../../output/squareds.txt";
char file_alpha[] = "../../../output/alpha_beta.txt";
//Make WaveFunction and Hamiltonian-objects
WaveFunction *function = new WaveFunction(nParticles, nDimensions);
Hamiltonian *hamiltonian = new Hamiltonian(nParticles, nDimensions, h, h2, charge);
double energySum = 0;
double energySquaredSum = 0;
double alpha = 0;
double beta = 0;
//Compute the steps sizes for the alpha and beta loops
double alpha_step = (alpha_max - alpha_min)/(alpha_steps-1);
double beta_step = (beta_max - beta_min)/(beta_steps-1);
if(alpha_max == alpha_min) alpha_step = 1;
if(beta_max == beta_min) beta_step = 1;
vec alphas = zeros(alpha_steps);
vec betas = zeros(beta_steps);
mat energies = zeros(alpha_steps,beta_steps);
mat energySquareds = zeros(alpha_steps,beta_steps);
int id, np;
//Start parallel threads
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &id);
MPI_Comm_size(MPI_COMM_WORLD, &np);
double myTime,mintime, maxtime,avgtime;
myTime = MPI_Wtime(); //Timing of threads
int mpi_steps = nCycles/np; //Numver of MC cycles per thread
idum = idum-id; //Different seed for each thread
double* allEnergies = new double[mpi_steps+1];
//Matrices to store results
mat pEnergies = zeros(alpha_steps,beta_steps);
mat pEnergySquareds = zeros(alpha_steps,beta_steps);
for (int k=0; k<alpha_steps; k++) { //Loop over alpha values
alpha = alpha_min + k*alpha_step;
alphas(k) = alpha;
for (int l=0; l<beta_steps; l++) { //Loop over beta values
beta = beta_min + l*beta_step;
betas(l) = beta;
cout << "ID, k,l,alpha,beta: " << id << " "<< k << " " << l <<" "<< alpha << " " << beta <<endl;
if(minimise_var) { //If optimization of alpha and beta
double gtol = 1e-4;
int iter;
double fret;
vec p = zeros<vec>(2,1);
p(0) = alpha;
p(1) = beta;
int n = 2;
vec ans = steepest_descent(idum, p, n, gtol, min_steps, &iter, &fret, hamiltonian, function);
double alpha_new = ans(0);
double beta_new = ans(1);
MPI_Barrier(MPI_COMM_WORLD);
//Find average values of alpha and beta over threads
MPI_Allreduce(&alpha_new, &alpha, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(&beta_new, &beta, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
alpha = alpha/np;
beta = beta/np;
cout << "Final alpha, beta: "<< alpha<<" "<<beta<<endl;
}
//Importance sampling or brute force MC:
vec energyVec = MCImportance(idum, alpha, beta, mpi_steps, function, hamiltonian, allEnergies);
energySum = energyVec(0);
energySquaredSum = energyVec(1);
//MCSampling(alpha, beta, mpi_steps, function, hamiltonian, energySum, energySquaredSum, allEnergies);
if(print_blockdata) {
ostringstream ost;
//ost << "/mn/korona/rp-s1/alborg/4411/helium/examples/vmc-simple/DATA/data" << id << ".mat" ;
ost << "/home/anette/helium/examples/helium/DATA/data" << id << ".mat" ;
ofstream blockofile;
blockofile.open( ost.str( ).c_str( ),ios::out | ios::binary );
if (blockofile.is_open())
{
blockofile.write((char*)(allEnergies+1) , mpi_steps*sizeof(double)) ;
blockofile.close();
}
else cout << "Unable to open data file for process " << id << endl;
}
//Find average values of energies:
pEnergies(k,l) = energySum/(nCycles * nParticles);
pEnergySquareds(k,l) = energySquaredSum/(nCycles * nParticles);
cout << "--------------------------" << endl;
energySum = 0;
energySquaredSum = 0;
} //End beta loop
} //End alpha loop
MPI_Barrier(MPI_COMM_WORLD);
//Gather data from all threads:
MPI_Allreduce(pEnergies.memptr(), energies.memptr(), alpha_steps*beta_steps, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(pEnergySquareds.memptr(), energySquareds.memptr(), alpha_steps*beta_steps, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
myTime = MPI_Wtime() - myTime;
MPI_Reduce(&myTime, &maxtime, 1, MPI_DOUBLE, MPI_MAX, 0, MPI_COMM_WORLD);
MPI_Reduce(&myTime, &mintime, 1, MPI_DOUBLE, MPI_MIN, 0,MPI_COMM_WORLD);
MPI_Reduce(&myTime, &avgtime, 1, MPI_DOUBLE, MPI_SUM, 0,MPI_COMM_WORLD);
MPI_Finalize();
//End of parallel threads
if (id == 0) { //Thread no 0:
cout << "Energies: "<<energies << endl; //*2*13.6
cout<< "Squareds: "<< energySquareds<<endl;
cout << "Var: "<< (energySquareds - square(energies))/nCycles << endl;
cout << "Std: "<< sqrt((energySquareds - square(energies))/nCycles) << endl;
//Print data to file:
// printFile(*file_energies, *file_energySquareds, *file_alpha, energies, energySquareds, alphas, betas);
avgtime /= np;
cout << "Min time: " << mintime << ", max time: " << maxtime << ", avg time: " << avgtime << endl;
}
delete[] allEnergies;
}
//Do importance sampling MC:
vec VMCSolver::MCImportance(long idum, double alpha, double beta, int mpi_steps, WaveFunction *function, Hamiltonian *hamiltonian, double *allEnergies) {
mat qForceOld = zeros(alpha_steps,beta_steps);
mat qForceNew = zeros(alpha_steps,beta_steps);
rOld = zeros<mat>(nParticles, nDimensions);
rNew = zeros<mat>(nParticles, nDimensions);
int accepted_steps = 0;
int count_total = 0;
double deltaE = 0;
double waveFunctionOld = 0;
double waveFunctionNew = 0;
double cycleE = 0;
vec deltaPsi = zeros<vec>(2);
vec deltaPsiE = zeros<vec>(2);
vec energySums = zeros<vec>(6);
//Find initial positions for all electrons
for(int i = 0; i < nParticles; i++) {
for(int j = 0; j < nDimensions; j++) {
rOld(i,j) = gaussianDeviate(&idum)*sqrt(timestep);
}
}
//Compute the wavefunction and quantum force
waveFunctionOld = function->waveFunction(rOld, alpha, beta);
qForceOld = quantumForce(rOld, alpha, beta, waveFunctionOld,function);
for(int cycle = 0; cycle < mpi_steps; cycle++) { // loop over Monte Carlo cycles
for(int i = 0; i < nParticles; i++) { //Loop over particles (electrons)
// New position for current electron:
for(int j = 0; j < nDimensions; j++) {
rNew(i,j) = rOld(i,j) + gaussianDeviate(&idum)*sqrt(timestep) + qForceOld(i,j)*timestep*D;
}
//Move only one particle.
for (int g=0; g<nParticles; g++) {
if(g != i) {
for(int j=0; j<nDimensions; j++) {
rNew(g,j) = rOld(g,j);
}
}
}
// Recalculate the wave function and quantum force
waveFunctionNew = function->waveFunction(rNew, alpha, beta);
qForceNew = quantumForce(rNew, alpha, beta, waveFunctionNew,function);
//Greens function
double greensFunction = 0;
for(int j=0; j<nDimensions; j++) {
greensFunction += 0.5*(qForceOld(i,j) + qForceNew(i,j)) * (0.5*D*timestep*(qForceOld(i,j) - qForceNew(i,j)) - rNew(i,j) + rOld(i,j));
}
greensFunction = exp(greensFunction);
++count_total;
// Check for step acceptance (if yes, update position, if no, reset position)
if(ran2(&idum) <= greensFunction * (waveFunctionNew*waveFunctionNew) / (waveFunctionOld*waveFunctionOld)) {
++accepted_steps;
for(int j = 0; j < nDimensions; j++) {
rOld(i,j) = rNew(i,j);
qForceOld(i,j) = qForceNew(i,j);
}
waveFunctionOld = waveFunctionNew;
}
else {
for(int j = 0; j < nDimensions; j++) {
rNew(i,j) = rOld(i,j);
qForceNew(i,j) = qForceOld(i,j);
}
}
//Get contribution to energy
deltaE = hamiltonian->localEnergy(rNew, alpha, beta, function);
//deltaE = hamiltonian->analyticEnergyHe(rNew, alpha, beta); //Get analytic energy of He
energySums(0) += deltaE;
energySums(1) += deltaE*deltaE;
cycleE +=deltaE;
if(minimise_var) { //If optimizer is in use, get expectance value of dPsi/dalpha and dPsi/dbeta
deltaPsi = hamiltonian->dPsi(rNew,alpha,beta,function);
deltaPsiE(0) = deltaE*deltaPsi(0);
deltaPsiE(1) = deltaE*deltaPsi(1);
energySums(2) += deltaPsi(0);
energySums(3) += deltaPsi(1);
energySums(4) += deltaPsiE(0);
energySums(5) += deltaPsiE(1);
}
} //End particle loop
allEnergies[cycle] = cycleE/nParticles; //Store energy for this MC cycle (for blocking method)
cycleE = 0;
} //End Monte Carlo loop
cout << "accepted steps: " << 100*accepted_steps/count_total <<"%"<< endl;
return energySums;
}
//Do brute force MC
void VMCSolver::MCSampling(double alpha, double beta, int mpi_steps, WaveFunction *function, Hamiltonian *hamiltonian, double &energySum, double &energySquaredSum, double *allEnergies) {
rOld = zeros<mat>(nParticles, nDimensions);
rNew = zeros<mat>(nParticles, nDimensions);
int accepted_steps = 0;
int count_total = 0;
double deltaE = 0;
double waveFunctionOld = 0;
double waveFunctionNew = 0;
vec average_dist = zeros(3);
double cycleE = 0;
//Adjust step length, depending on alpha:
if(alpha==1) stepLength = 2.5;
if(alpha>1) stepLength = 2.25;
if(alpha>=1.2) stepLength = 2;
if(alpha>=1.4) stepLength = 1.75;
if(alpha>=1.6) stepLength = 1.5;
if(alpha>=2) stepLength = 1.25;
if(alpha>=2.3) stepLength = 1;
//Get initial trial positions
for(int i = 0; i < nParticles; i++) {
for(int j = 0; j < nDimensions; j++) {
rOld(i,j) = stepLength * (ran2(&idum) - 0.5);
}
}
rNew = rOld;
for(int cycle = 0; cycle < mpi_steps; cycle++) { // loop over Monte Carlo cycles
// Store the current value of the wave function
waveFunctionOld = function->waveFunction(rOld, alpha, beta);
for(int i = 0; i < nParticles; i++) { //Loop over particles
// New position for current particle:
for(int j = 0; j < nDimensions; j++) {
rNew(i,j) = rOld(i,j) + stepLength*(ran2(&idum) - 0.5);
}
// Recalculate the value of the wave function
waveFunctionNew = function->waveFunction(rNew, alpha, beta);
++count_total;
// Check for step acceptance (if yes, update position, if no, reset position)
if(ran2(&idum) <= (waveFunctionNew*waveFunctionNew) / (waveFunctionOld*waveFunctionOld)) {
++accepted_steps;
for(int j = 0; j < nDimensions; j++) {
rOld(i,j) = rNew(i,j);
waveFunctionOld = waveFunctionNew;
rowvec r12 = rOld.row(1) - rOld.row(0);
double r12norm = 0;
double r1norm = 0;
double r2norm = 0;
for(int d= 0;d<nDimensions;d++) {
r12norm += pow(r12(d),2);
r1norm += pow(rOld(0,d),2);
r2norm += pow(rOld(1,d),2);
}
average_dist(0) += sqrt(r12norm);
average_dist(1) += sqrt(r1norm);
average_dist(2) += sqrt(r2norm);
}
} else {
for(int j = 0; j < nDimensions; j++) {
rNew(i,j) = rOld(i,j);
}
}
// Get contribution to energy
deltaE = hamiltonian->localEnergy(rNew, alpha, beta, function);
cycleE +=deltaE;
//deltaE = hamiltonian->analyticEnergyHe(rNew, alpha, beta); //Analytic energy He
energySum += deltaE;
energySquaredSum += deltaE*deltaE;
} //End particle loop
allEnergies[cycle] = cycleE/nParticles; //Store energy for this MC cycle (for blocking method)
cycleE = 0;
} //End MC loop
cout << "average distance r1: "<<average_dist(1)/(mpi_steps*nParticles) <<endl;
cout << "average distance r2: "<<average_dist(2)/(mpi_steps*nParticles) <<endl;
cout << "average distance r12: "<<average_dist(0)/(mpi_steps*nParticles) <<endl;
cout << "accepted steps: " << 100*accepted_steps/count_total <<"%"<< endl;
}
//Optimization of alpha and beta:
vec VMCSolver::steepest_descent(long idum, vec &p, int n, double gtol, int min_steps, int *iter, double *fret,
Hamiltonian *hamiltonian, WaveFunction *function)
{
vec dPsi = zeros<vec>(2,1);
vec dPsi_Elocal = zeros<vec>(2,1);
double* allEnergies = new double[min_steps+1];
double alpha = p(0);
double beta = p(1);
double alpha_new = alpha;
double beta_new = beta;
vec dE = zeros<vec>(n);
vec dEold = zeros<vec>(n);
int maxIter = 50;
vec answers = zeros<vec>(n+2);
double E = 0;
double Enew = 0;
double alpha_step = 1;
double beta_step = 1;
int i = 0;
double test = 0;
double step_reduce = 2;
//Get E for current alpha and beta, do MC sample
vec Es = MCImportance(idum, alpha, beta, min_steps,function,hamiltonian,allEnergies);
E = Es(0)/(min_steps * nParticles);
dPsi(0) = Es(2)/(min_steps * nParticles);
dPsi(1) = Es(3)/(min_steps * nParticles);
dPsi_Elocal(0) = Es(4)/(min_steps * nParticles);
dPsi_Elocal(1) = Es(5)/(min_steps * nParticles);
dE = gradE(dPsi, E, dPsi_Elocal); //Get derivatives of E wrt alpha and beta
cout <<"E: "<<E<<endl;
while(i<maxIter) { //Loop until enough iterations
alpha_new = alpha - alpha_step*dE(0); //Get new value of alpha
if(alpha_new < 0) { //If the new alpha is negative,
while(alpha_new < 0) { //Reduce step length until new alpha is positive
alpha_step = alpha_step/step_reduce;
alpha_new = alpha - alpha_step*dE(0);
}
}
cout<<"dE alpha, step: "<<dE(0)<<" "<<alpha_step<<endl;
dEold = dE;
//Get E for new alpha and current beta, do MC sample
Es = MCImportance(idum, alpha_new,beta_new,min_steps, function,hamiltonian, allEnergies);
Enew = Es(0)/(min_steps * nParticles);
dPsi(0) = Es(2)/(min_steps * nParticles);
dPsi(1) = Es(3)/(min_steps * nParticles);
dPsi_Elocal(0) = Es(4)/(min_steps * nParticles);
dPsi_Elocal(1) = Es(5)/(min_steps * nParticles);
dE = gradE(dPsi, E, dPsi_Elocal); //Get derivatives of E wrt alpha and beta
//If derivatives have changed sign, reduce step length
if(dE(0)*dEold(0) < 0) alpha_step = alpha_step/step_reduce;
if(dE(1)*dEold(1) < 0) beta_step = beta_step/step_reduce;
beta_new = beta - beta_step*dE(1); //Get new value of beta
if(beta_new < 0) { //If the new beta is negative,
while(beta_new < 0) { //Reduce step length until new beta is positive
beta_step = beta_step/step_reduce;
beta_new = beta - beta_step*dE(1);
}
}
cout<<"dE beta, step: "<<dE(1)<<beta_step<<endl;
dEold = dE;
//Get E for new alpha and beta, do MC sample
Es = MCImportance(idum, alpha_new,beta_new,min_steps, function,hamiltonian, allEnergies);
Enew = Es(0)/(min_steps * nParticles);
dPsi(0) = Es(2)/(min_steps * nParticles);
dPsi(1) = Es(3)/(min_steps * nParticles);
dPsi_Elocal(0) = Es(4)/(min_steps * nParticles);
dPsi_Elocal(1) = Es(5)/(min_steps * nParticles);
dE = gradE(dPsi, E, dPsi_Elocal);//Get derivatives of E wrt alpha and beta
//If derivatives have changed sign, reduce step length
if(dE(0)*dEold(0) < 0) alpha_step = alpha_step/step_reduce;
if(dE(1)*dEold(1) < 0) beta_step = beta_step/step_reduce;
cout<<"alpha new: "<< alpha_new<<endl;
cout <<"beta new: "<< beta_new<<" "<<endl;
cout<<"Enew: "<<Enew<<endl;
cout <<"----------"<<endl;
test = abs(Enew-E);
if(test < gtol) break; //If change in energy is smaller than tolerance, break out of loop
E = Enew; //Else: Update E, alpha and beta
beta = beta_new;
alpha = alpha_new;
i++;
}
answers(0) = alpha_new;
answers(1) = beta_new;
answers(2) = Enew;
answers(3) = i;
return answers;
}
//Get derivatives of energy E wrt alpha, beta
vec VMCSolver::gradE(vec dPsi, double Elocal, vec dPsi_Elocal) {
vec dE = zeros<vec>(2);
dE(0) = 2*(dPsi_Elocal(0) - dPsi(0)*Elocal);
dE(1) = 2*(dPsi_Elocal(1) - dPsi(1)*Elocal);
return dE;
}
//Get quantum force (first derivative of wave function)
mat VMCSolver::quantumForce(const mat &r, double alpha_, double beta_, double wf, WaveFunction *function) {
mat qforce = zeros(nParticles, nDimensions);
mat rPlus = zeros<mat>(nParticles, nDimensions);
mat rMinus = zeros<mat>(nParticles, nDimensions);
rPlus = rMinus = r;
double waveFunctionMinus = 0;
double waveFunctionPlus = 0;
//First derivative, numerical approach
for(int i = 0; i < nParticles; i++) {
for(int j = 0; j < nDimensions; j++) {
rPlus(i,j) = r(i,j)+h;
rMinus(i,j) = r(i,j)-h;
waveFunctionMinus = function->waveFunction(rMinus, alpha_, beta_);
waveFunctionPlus = function->waveFunction(rPlus, alpha_, beta_);
qforce(i,j) = (waveFunctionPlus - waveFunctionMinus)/(wf*h);
rPlus(i,j) = r(i,j);
rMinus(i,j) = r(i,j);
}
}
return qforce;
}
//Get random numbers with a Gaussian pdf
double VMCSolver::gaussianDeviate(long *idum) {
static int iset = 0;
static double gset;
double fac, rsq, v1, v2;
if ( idum < 0) iset =0;
if (iset == 0) {
do {
v1 = 2.*ran2(idum) -1.0;
v2 = 2.*ran2(idum) -1.0;
rsq = v1*v1+v2*v2;
} while (rsq >= 1.0 || rsq == 0.);
fac = sqrt(-2.*log(rsq)/rsq);
gset = v1*fac;
iset = 1;
return v2*fac;
} else {
iset =0;
return gset;
}
}
//Print energy data to file
void VMCSolver::printFile(const char &file_energies, const char &file_energySquareds, const char &file_alpha, const mat &energies, const mat &energiesSquared, const vec alphas, const vec betas)
{
ofstream myfile(&file_energies);
if (myfile.is_open())
{
for (unsigned int f=0; f<energies.n_rows; f++)
{
for (unsigned int l=0; l<energies.n_cols; l++) {
myfile << energies(f,l) << " ";
}
myfile << endl;
}
myfile.close();
}
else cout << "Unable to open file" << endl;
ofstream myfile2 (&file_alpha);
if (myfile2.is_open())
{
myfile2 << alphas << endl;
myfile2 << betas << endl;
myfile2.close();
}
else cout << "Unable to open file" << endl;
ofstream myfile3(&file_energySquareds);
if (myfile3.is_open())
{
for (unsigned int f=0; f<energiesSquared.n_rows; f++)
{
for (unsigned int l=0; l<energiesSquared.n_cols; l++) {
myfile3 << energiesSquared(f,l) << " ";
}
myfile3 << endl;
}
myfile3.close();
}
else cout << "Unable to open file" << endl;
}
<file_sep>#include "hamiltonian.h"
#include "WaveFunction.h"
Hamiltonian::Hamiltonian(int nProtons_, int nElectrons_, int nDimensions_, double h_, double h2_, int charge_) :
nDimensions(nDimensions_),
nProtons(nProtons_),
nElectrons(nElectrons_),
nParticles(nProtons*nElectrons),
h(h_),
h2(h2_),
charge(charge_)
{
}
//Find the local energy (expectation value of the energy) numerically
double Hamiltonian::localEnergy(double R, const mat &r, const mat &rProtons, const double &alpha, const double &beta, WaveFunction *function)
{
double kinEnergy = kineticEnergy(r, rProtons, alpha, beta, function);
double potEnergy = potentialEnergy(R, r, rProtons);
//cout<<"kinetic, potential: "<<kinEnergy<<" "<<potEnergy<<endl;
return kinEnergy + potEnergy;
}
vec Hamiltonian::dPsi(const mat &r, const mat &rProtons, double alpha, double beta, WaveFunction *function) {
vec dPsi = zeros<vec>(2,1);
double wf = function->waveFunction(r, rProtons, alpha, beta); //Find wavefunction for r
//First derivative of wavefunction wrt alpha
double alphaPlus, alphaMinus;
alphaPlus = alphaMinus = alpha;
double waveFunctionMinus = 0;
double waveFunctionPlus = 0;
alphaPlus = alpha+h;
alphaMinus = alpha-h;
waveFunctionMinus = function->waveFunction(r, rProtons, alphaMinus, beta);
waveFunctionPlus = function->waveFunction(r, rProtons, alphaPlus, beta);
dPsi(0) = (waveFunctionPlus - waveFunctionMinus)/(2*wf*h);
//First derivative of wavefunction wrt beta
double betaPlus, betaMinus;
betaPlus = betaMinus = beta;
betaPlus = beta+h;
betaMinus = beta-h;
waveFunctionMinus = function->waveFunction(r, rProtons, alpha, betaMinus);
waveFunctionPlus = function->waveFunction(r, rProtons, alpha, betaPlus);
dPsi(1) = (waveFunctionPlus - waveFunctionMinus)/(2*wf*h);
return dPsi;
}
//Find the kinetic energy part of the local energy
double Hamiltonian::kineticEnergy(const mat &r, const mat rProtons, const double &alpha, const double &beta, WaveFunction *function)
{
mat rPlus = zeros<mat>(nParticles, nDimensions);
mat rMinus = zeros<mat>(nParticles, nDimensions);
rPlus = rMinus = r;
double waveFunctionMinus = 0;
double waveFunctionPlus = 0;
double waveFunctionCurrent = function->waveFunction(r, rProtons, alpha, beta); //Find wavefunction for r
//Second derivative (del^2):
double kineticEnergy = 0;
for(int i = 0; i < nParticles; i++) {
for(int j = 0; j < nDimensions; j++) {
rPlus(i,j) += h;
rMinus(i,j) -= h;
waveFunctionMinus = function->waveFunction(rMinus, rProtons, alpha, beta);
waveFunctionPlus = function->waveFunction(rPlus, rProtons, alpha, beta);
kineticEnergy -= (waveFunctionMinus + waveFunctionPlus - 2 * waveFunctionCurrent);
rPlus(i,j) = r(i,j);
rMinus(i,j) = r(i,j);
}
}
kineticEnergy = 0.5 * h2 * kineticEnergy / waveFunctionCurrent;
return kineticEnergy;
}
double Hamiltonian::potentialEnergy(double R, const mat &r, const mat &rProtons)
{
double potentialE = 0;
//Contribution from electron - proton potential (1/rep)
double rp = 0;
for(int e=0; e<nParticles; e++) {
for(int p=0; p<nProtons; p++) {
rp = 0;
for(int d=0; d<nDimensions; d++) rp += (r(e,d) - rProtons(p,d))*(r(e,d) - rProtons(p,d));
potentialE -= charge/sqrt(rp);
}
}
// Contribution from electron-electron potential (1/rij part)
double r12 = 0;
for(int i = 1; i < nParticles; i++) {
for(int j = 0; j < i; j++) {
r12 = 0;
for(int k = 0; k < nDimensions; k++) r12 += pow((r(i,k) - r(j,k)),2);
potentialE += 1/ sqrt(r12);
}
}
//Contribution from proton-proton potential 1/R
potentialE += abs(1/R);
return potentialE;
}
<file_sep>#include "WaveFunction.h"
#include "lib.h"
#include <armadillo>
using namespace arma;
using namespace std;
WaveFunction::WaveFunction(int &nParticles_, int &nDimensions_) :
nDimensions(nDimensions_),
nParticles(nParticles_)
{
}
//Wavefunction, 1s state
double WaveFunction::psi1s(double rtot, double alpha) {
double psi = exp(-alpha*rtot);
return psi;
}
//First derivative of wavefunction, 1s state
vec WaveFunction::dPsi1s(double rtot, int i, const mat &r, double alpha) {
vec der = zeros<vec>(3,1);
der(0) = -alpha*r(i,0)*exp(-alpha*rtot)/rtot;
der(1) = -alpha*r(i,1)*exp(-alpha*rtot)/rtot;
der(2) = -alpha*r(i,2)*exp(-alpha*rtot)/rtot;
return der;
}
//Second derivative of wavefunction, 1s state
double WaveFunction::d2Psi1s(double rtot, double alpha) {
double der = alpha*(alpha*rtot - 2)*exp(-alpha*rtot)/rtot;
return der;
}
//Wavefunction, 2s state
double WaveFunction::psi2s(double rtot, double alpha) {
double psi = (1-(alpha*rtot)/2)*exp(-alpha*rtot/2);
return psi;
}
//First derivative of wavefunction, 2s state
vec WaveFunction::dPsi2s(double rtot, int i, const mat &r, double alpha) {
vec der = zeros<vec>(3,1);
der(0) = alpha*r(i,0)*(alpha*rtot - 4)*exp(-alpha*rtot/2)/(4*rtot);
der(1) = alpha*r(i,1)*(alpha*rtot - 4)*exp(-alpha*rtot/2)/(4*rtot);
der(2) = alpha*r(i,2)*(alpha*rtot - 4)*exp(-alpha*rtot/2)/(4*rtot);
return der;
}
//Second derivative of wavefunction, 2s state
double WaveFunction::d2Psi2s(double rtot, double alpha) {
double der = -(alpha/(8*rtot))*(alpha*rtot-8)*(alpha*rtot-2)*exp(-alpha*rtot/2);
return der;
}
<file_sep>#include "vmcsolver.h"
#include <armadillo>
using namespace arma;
using namespace std;
int main(int argc, char* argv[])
{
//Start solver
VMCSolver *solver = new VMCSolver();
solver->runMonteCarloIntegration(argc, argv);
return 0;
}
<file_sep>#include <unittest++/UnitTest++.h>
//#include "../../molecules/WaveFunction.h"
//#include "../../molecules/lib.h"
//#include "../../molecules/hamiltonian.h"
//#include "../../vmc-simple/vmcsolver.h"
//#include "../../vmc-simple/slaterdeterminant.h"
//#include "../../vmc-simple/correlation.h"
//#include "../../vmc-simple/hamiltonian.h"
#include "../../moleculeBe/vmcsolver.h"
#include "../../moleculeBe/slaterdeterminant.h"
#include "../../moleculeBe/correlation.h"
#include "../../moleculeBe/hamiltonian.h"
#include "../../moleculeBe/lib.h"
#include <armadillo>
using namespace arma;
using namespace std;
TEST(Wave) {
int nParticles = 2;
int charge = 8;
int nDimensions = 3;
double alpha = 3.7;
double beta = 0.23;
int stepLength = 1;
long idum = -1;
double h = 0.001;
double h2 = 1000000;
double nProtons = 2;
double nElectrons = 4;
double R = 4.63;
nParticles = 8;
mat rOld = zeros<mat>(nParticles, nDimensions);
mat rNew = zeros<mat>(nParticles,nDimensions);
mat rProtons = zeros<mat>(nProtons, nDimensions);
rProtons(0,2) = -R/2;
rProtons(1,2) = R/2;
for(int i = 0; i < nParticles; i++) {
for(int j = 0; j < nDimensions; j++) {
rOld(i,j) = stepLength * (ran2(&idum) - 0.5);
}
}
rNew = rOld;
WaveFunction *function = new WaveFunction(nParticles,nDimensions);
slaterDeterminant *slater = new slaterDeterminant(nDimensions, nProtons, nElectrons);
correlation *corr = new correlation(nDimensions, nProtons, nElectrons);
Hamiltonian *hamiltonian = new Hamiltonian(nDimensions,h,h2,charge, nProtons, nElectrons, R, rProtons);
slater -> buildDeterminant(rOld,alpha);
// double test = slater->getDeterminant();
cout<<"Determinants: "<< slater->getDeterminant()<<" "<<slater->beryllium(rOld,alpha)<<endl;
//CHECK(slater->getDeterminant() == slater->beryllium(rOld,alpha));
//// CHECK(slater->getInvDeterminant() == slater->beryllium(rOld,alpha));
// double EnSum=0;
// double EHeSum=0;
int nCycles = 5;
for(int j=0; j<nCycles; j++) { //Cycles
for(int i = 0; i < nParticles; i++) { //Particles
// double En = hamiltonian->localEnergy(rOld,alpha,beta,slater,corr);
// EnSum +=En;
// double EHe = hamiltonian->analyticEnergyHe(rOld,alpha,beta);
// EHeSum += EHe;
//// cout<<"En, EHe: "<<En<<" "<<EHe<<endl;
cout<<"cycle, particle: "<<j<<" "<<i<<endl;
//cout<<"Jastrow: "<<corr->jastrow(rOld,beta)<<" "<<corr->jastrowNum(rOld,beta)<<endl;
vec gradCorr = corr->gradientWaveFunction(rOld,i,beta);
vec gradCorrNum = corr->gradientWaveFunctionNum(rOld,i,beta);
// // cout <<"Grad Jastrow: "<< gradCorr<<" "<<gradCorrNum <<endl;
double g_x = abs(gradCorr(0) - gradCorrNum(0));
double g_y = abs(gradCorr(1) - gradCorrNum(1));
double g_z = abs(gradCorr(2) - gradCorrNum(2));
CHECK(g_x < 1e-2);
CHECK(g_y < 1e-2);
CHECK(g_z < 1e-2);
double laplaceNum = corr->laPlaceWaveFunctionNum(rOld, beta);
double laplace = corr->laPlaceWaveFunction(rOld, beta);
double deltaLaP = abs(laplace - laplaceNum);
CHECK(laplaceNum < 1e-2);
vec a1 = slater->gradientWaveFunction(rOld,i,1,alpha);
vec b1 = slater->gradientWaveFunctionNum(rOld,i,alpha);
cout<<"Gradient, slater: "<<a1<<" "<<b1<<endl;
double error0 = 1e-2;
double gradient_x1 = abs(a1(0) - b1(0));
CHECK(gradient_x1 < error0);
double lpN = slater->laPlaceWaveFunctionNum(rOld,alpha);
double lp = slater->laPlaceWaveFunction(rOld,alpha);
double lap_diff = abs(lpN + 0.5*lp);
double error1 = 1e-2;
cout <<"Laplace, slater: "<< -0.5*lp<<" "<<lpN<<endl;
CHECK(lap_diff<error1);
//New position:
for(int d = 0; d < nDimensions; d++) {
rNew(i,d) = rOld(i,d) + stepLength*(ran2(&idum) - 0.5);
}
// //Accept new step
double ratio1 = slater->getRatioDeterminantNum(i,rOld,rNew,alpha);
double ratio2 = slater->getRatioDeterminant(i,rNew,alpha);
cout<<"Ratio: "<<ratio2<<" "<<ratio1<<endl;
double error3 = 1e-3;
double getRatioDeterminant = abs(ratio2 - ratio1);
CHECK(getRatioDeterminant < error3);
// // vec a = slater->gradientWaveFunction(rNew,i,ratio1,4,0.2);
// // vec b = slater->gradientWaveFunctionNum(rNew,i,4,0.2);
// double error2 = 1e-2;
// // double gradient_x = abs(a(0) - b(0));
// // CHECK(gradient_x < error2);
// // double gradient_y = abs(a(1) - b(1));
// // double gradient_z = abs(a(2) - b(2));
// // CHECK(gradient_y < error2);
// // CHECK(gradient_z < error2);
slater->updateDeterminant(rNew, rOld, i, alpha, ratio1);
double error4 = 1e-3;
double test1 = slater->beryllium(rNew,alpha);
cout<<"New r: "<<slater->getInvDeterminant()<<" "<<test1<<endl;
double getDeterminant = abs(slater->getInvDeterminant() - test1);
CHECK(getDeterminant < error4);
for(int d = 0; d < nDimensions; d++) {
rOld(i,d) = rNew(i,d);
}
}
}
// EnSum = EnSum/(nCycles*nParticles);
// EHeSum = EHeSum/(nCycles*nParticles);
// cout << "Analytic, num: "<<EHeSum<<" "<<EnSum<<endl;
}
//TEST(molecule) {
// int stepLength = 1;
// long idum = -1;
// int nDimensions = 2;
// int nProtons = 2;
// int nElectrons = 4;
// int nParticles = nElectrons*nProtons;
// double R = 4.63;
// double alpha = 3.5;
// double beta = 0.3;
// mat r = zeros<mat>(nParticles,nDimensions);
// for(int i = 0; i < nParticles; i++) {
// for(int j = 0; j < nDimensions; j++) {
// r(i,j) = stepLength * (ran2(&idum) - 0.5);
// }
// }
// mat rProtons = zeros<mat>(nProtons,nDimensions);
// rProtons(0,2) = -R/2;
// rProtons(1,2) = R/2;
// WaveFunction *function = new WaveFunction(nDimensions,nProtons,nElectrons);
// double wf = function->waveFunction(r,rProtons,alpha,beta);
// rowvec r1p1 = r.row(0) - rProtons.row(0);
// rowvec r1p2 = r.row(0) - rProtons.row(1);
// rowvec r2p1 = r.row(1) - rProtons.row(0);
// rowvec r2p2 = r.row(1) - rProtons.row(1);
// rowvec r3p1 = r.row(2) - rProtons.row(0);
// rowvec r3p2 = r.row(2) - rProtons.row(1);
// rowvec r4p1 = r.row(3) - rProtons.row(0);
// rowvec r4p2 = r.row(3) - rProtons.row(1);
// rowvec r5p1 = r.row(4) - rProtons.row(0);
// rowvec r5p2 = r.row(4) - rProtons.row(1);
// rowvec r6p1 = r.row(5) - rProtons.row(0);
// rowvec r6p2 = r.row(5) - rProtons.row(1);
// rowvec r7p1 = r.row(6) - rProtons.row(0);
// rowvec r7p2 = r.row(6) - rProtons.row(1);
// rowvec r8p1 = r.row(7) - rProtons.row(0);
// rowvec r8p2 = r.row(7) - rProtons.row(1);
// double R1p1 = sqrt(pow(r1p1(0),2) + pow(r1p1(1),2) + pow(r1p1(2),2));
// double R1p2 = sqrt(pow(r1p2(0),2) + pow(r1p2(1),2) + pow(r1p2(2),2));
// double R2p1 = sqrt(pow(r2p1(0),2) + pow(r2p1(1),2) + pow(r2p1(2),2));
// double R2p2 = sqrt(pow(r2p2(0),2) + pow(r2p2(1),2) + pow(r2p2(2),2));
// double R3p1 = sqrt(pow(r3p1(0),2) + pow(r3p1(1),2) + pow(r3p1(2),2));
// double R3p2 = sqrt(pow(r3p2(0),2) + pow(r3p2(1),2) + pow(r3p2(2),2));
// double R4p1 = sqrt(pow(r4p1(0),2) + pow(r4p1(1),2) + pow(r4p1(2),2));
// double R4p2 = sqrt(pow(r4p2(0),2) + pow(r4p2(1),2) + pow(r4p2(2),2));
// double R5p1 = sqrt(pow(r5p1(0),2) + pow(r5p1(1),2) + pow(r5p1(2),2));
// double R5p2 = sqrt(pow(r5p2(0),2) + pow(r5p2(1),2) + pow(r5p2(2),2));
// double R6p1 = sqrt(pow(r6p1(0),2) + pow(r6p1(1),2) + pow(r6p1(2),2));
// double R6p2 = sqrt(pow(r6p2(0),2) + pow(r6p2(1),2) + pow(r6p2(2),2));
// double R7p1 = sqrt(pow(r7p1(0),2) + pow(r7p1(1),2) + pow(r7p1(2),2));
// double R7p2 = sqrt(pow(r7p2(0),2) + pow(r7p2(1),2) + pow(r7p2(2),2));
// double R8p1 = sqrt(pow(r8p1(0),2) + pow(r8p1(1),2) + pow(r8p1(2),2));
// double R8p2 = sqrt(pow(r8p2(0),2) + pow(r8p2(1),2) + pow(r8p2(2),2));
// double wfnum = (exp(-alpha*R1p1) + exp(-alpha*R1p2)) * (exp(-alpha*R2p1) + exp(-alpha*R2p2)) * (exp(-alpha*R3p1) + exp(-alpha*R3p2)) * (exp(-alpha*R4p1) + exp(-alpha*R4p2)) * (exp(-alpha*R5p1) + exp(-alpha*R5p2)) * (exp(-alpha*R6p1) + exp(-alpha*R6p2)) * (exp(-alpha*R7p1) + exp(-alpha*R7p2)) * (exp(-alpha*R8p1) + exp(-alpha*R8p2));
// cout<<"num wave: "<<wfnum<<endl;
// double jastrow = 0;
// double a = 0.5;
// rowvec r12;
// double R12 = 0;
// for(int i=1; i<nParticles; i++) {
// for(int j=0; j<i; j++) {
// r12 = r.row(i) - r.row(j);
// R12 = sqrt(pow(r12(0),2) + pow(r12(1),2) + pow(r12(2),2));
// if((i==1 && j==0) || (i==3 && j==2) || (i==4 && (j==0 || j==1)) || (i==5 && (j==0 || j==1 || j==4)) || (i==6 && (j==2 || j==3)) || (i==7 && (j==2 || j==3 || j==6))) {
// a=0.25;
// }
// else a=0.5;
// jastrow += a*R12/(1+beta*R12)/2;
// }
// }
// jastrow = exp(jastrow);
// wfnum = wfnum * jastrow;
// cout <<"num jastrow: "<<jastrow<<endl;
// double delta = abs(wfnum - wf);
// cout <<"wavwfunc, num: "<<wf<<" "<<wfnum<<endl;
// CHECK(delta < 1e-3);
//}
//TEST(dEdP) {
// int nParticles = 4;
// int charge = 4;
// int nDimensions = 3;
// long idum = -1;
// double alpha_min = 3;
// double alpha_max = 4;
// double alpha_steps = 11;
// double beta_min = 0.2;
// double beta_max = 0.3;
// double beta_steps = 11;
// int steps = 10000;
// double h = 0.001;
// double h2 = 1000000;
// double* allEnergies = new double[steps+1];
// vec dE = zeros<vec>(2);
// vec dPsi = zeros<vec>(2,1);
// vec dPsi_Elocal = zeros<vec>(2,1);
// double da = 0.2;
// double db = 0.05;
// slaterDeterminant *slater = new slaterDeterminant(nParticles, nDimensions);
// correlation *corr = new correlation(nParticles,nDimensions);
// Hamiltonian *hamiltonian = new Hamiltonian(nParticles,nDimensions,h,h2,charge);
// VMCSolver *solver = new VMCSolver();
// mat Emat = zeros<mat>(alpha_steps,beta_steps);
// mat dEmat_alpha = zeros<mat>(alpha_steps,beta_steps);
// mat dEmat_beta = zeros<mat>(alpha_steps,beta_steps);
// vec alphas = zeros<vec>(alpha_steps);
// vec betas = zeros<vec>(beta_steps);
// double alpha = 0;
// double beta = 0;
// double alpha_step = (alpha_max - alpha_min)/(alpha_steps-1);
// double beta_step = (beta_max - beta_min)/(beta_steps-1);
// if(alpha_max == alpha_min) alpha_step = 1;
// if(beta_max == beta_min) beta_step = 1;
// for(int i=0; i<alpha_steps; i++) {
// alpha = alpha_min + i*alpha_step;
// alphas(i) = alpha;
// for(int j=0; j<beta_steps; j++) {
// beta = beta_min + j*beta_step;
// betas(j) = beta;
// vec Es = solver->MCImportance(idum, alpha,beta,steps, slater, hamiltonian, corr, allEnergies);
// double E = Es(0)/(steps * nParticles);
// Emat(i,j) = E;
// dPsi(0) = Es(2)/(steps * nParticles);
// dPsi(1) = Es(3)/(steps * nParticles);
// dPsi_Elocal(0) = Es(4)/(steps * nParticles);
// dPsi_Elocal(1) = Es(5)/(steps * nParticles);
// dE = solver->gradE(dPsi, E, dPsi_Elocal);
// dEmat_alpha(i,j) = dE(0);
// dEmat_beta(i,j) = dE(1);
// cout <<"Alpha, beta, E, dE: "<<alpha<<" "<< beta<<" "<<E<<" "<<dE(0)<<" "<<dE(1) <<endl;
// }
// }
// cout <<alphas<<endl;
// cout<<betas<<endl;
// cout <<Emat<<endl;
// cout <<dEmat_alpha + dEmat_beta<<endl;
// cout <<dEmat_alpha<<endl;
// cout <<dEmat_beta<<endl;
//}
int main()
{
return UnitTest::RunAllTests();
}
<file_sep>#include "slaterdeterminant.h"
#include "WaveFunction.h"
#include <armadillo>
using namespace arma;
using namespace std;
slaterDeterminant::slaterDeterminant(int nDimensions_, int nProtons_, int nElectrons_):
nDimensions(nDimensions_),
nProtons(nProtons_),
nElectrons(nElectrons_),
nParticles(nElectrons*nProtons),
slaterMatrixUp1(zeros(nElectrons/2,nElectrons/2)),
slaterMatrixDown1(zeros(nElectrons/2,nElectrons/2)),
slaterMatrixUp2(zeros(nElectrons/2,nElectrons/2)),
slaterMatrixDown2(zeros(nElectrons/2,nElectrons/2)),
invSlaterMatrixUp1(zeros(nElectrons/2,nElectrons/2)),
invSlaterMatrixDown1(zeros(nElectrons/2,nElectrons/2)),
invSlaterMatrixUp2(zeros(nElectrons/2,nElectrons/2)),
invSlaterMatrixDown2(zeros(nElectrons/2,nElectrons/2)),
function(new WaveFunction(nParticles,nDimensions))
{
}
//Build and invert Slater determinant once
void slaterDeterminant::buildDeterminant(const mat &r, double &alpha_) {
vec rs = zeros<vec>(nParticles,1);
double alpha = alpha_;
//Find |r| for each electron:
double rSingleParticle = 0;
for(int i = 0; i < nParticles; i++) {
rSingleParticle = 0;
for(int g = 0; g < nDimensions; g++) {
rSingleParticle += r(i,g) * r(i,g);
}
rs(i) = sqrt(rSingleParticle);
}
//Make Slater determinants (spin up and spin down)
//State 1s
slaterMatrixUp1(0,0) = function->psi1s(rs[0], alpha);
slaterMatrixUp1(1,0) = function->psi1s(rs[1], alpha);
slaterMatrixDown1(0,0) = function->psi1s(rs[2], alpha);
slaterMatrixDown1(1,0) = function->psi1s(rs[3], alpha);
slaterMatrixUp2(0,0) = function->psi1s(rs[4], alpha);
slaterMatrixUp2(1,0) = function->psi1s(rs[5], alpha);
slaterMatrixDown2(0,0) = function->psi1s(rs[6], alpha);
slaterMatrixDown2(1,0) = function->psi1s(rs[7], alpha);
//State 2s
slaterMatrixUp1(0,1) = function->psi2s(rs[0], alpha);
slaterMatrixUp1(1,1) = function->psi2s(rs[1], alpha);
slaterMatrixDown1(0,1) = function->psi2s(rs[2], alpha);
slaterMatrixDown1(1,1) = function->psi2s(rs[3], alpha);
slaterMatrixUp2(0,1) = function->psi2s(rs[4], alpha);
slaterMatrixUp2(1,1) = function->psi2s(rs[5], alpha);
slaterMatrixDown2(0,1) = function->psi2s(rs[6], alpha);
slaterMatrixDown2(1,1) = function->psi2s(rs[7], alpha);
//cout<<rs<<endl;
invSlaterMatrixUp1 = inv(slaterMatrixUp1);
invSlaterMatrixDown1 = inv(slaterMatrixDown1);
invSlaterMatrixUp2 = inv(slaterMatrixUp2);
invSlaterMatrixDown2 = inv(slaterMatrixDown2);
}
//Testing
double slaterDeterminant::getDeterminant() {
return det(slaterMatrixUp1)*det(slaterMatrixDown1)*det(slaterMatrixUp2)*det(slaterMatrixDown2);
}
//Testing
double slaterDeterminant::getInvDeterminant() {
return 1/(det(invSlaterMatrixUp1)*det(invSlaterMatrixDown1)) * 1/(det(invSlaterMatrixUp2)*det(invSlaterMatrixDown2));
}
//Get ration of new to old determinant, after rNew generation
double slaterDeterminant::getRatioDeterminant(int i, const mat &r, double alpha) {
double ratio = 0;
double rSingleParticle = 0;
//Get rtot for particle i's new position:
for(int d = 0; d < nDimensions; d++) {
rSingleParticle += r(i,d) * r(i,d);
}
double rtot = sqrt(rSingleParticle);
vec updatedStates = getStates(rtot, alpha); //Get states with new r for particle i
if(i==0 || i==1) { //Atom 1, particle spin up
for(int j=0; j<nElectrons/2; j++) { //States
ratio += updatedStates(j) * invSlaterMatrixUp1(j,i);
}
}
if(i==2 || i==3) { //Atom 1, particle spin down
for(int j=0; j<nElectrons/2; j++) { //States
ratio += updatedStates(j) * invSlaterMatrixDown1(j,i-2);
}
}
if(i==4 || i==5) { //Atom 2, particle spin up
for(int j=0; j<nElectrons/2; j++) { //States
ratio += updatedStates(j) * invSlaterMatrixUp2(j,i-4);
}
}
if(i==6 || i==7) { //Atom 2, particle spin down
for(int j=0; j<nElectrons/2; j++) { //States
ratio += updatedStates(j) * invSlaterMatrixDown2(j,i-6);
}
}
return ratio;
}
//Testing, analytical ratio
double slaterDeterminant::getRatioDeterminantNum(int i, const mat &rOld, const mat &rNew, double alpha) {
return beryllium(rNew, alpha) / beryllium(rOld, alpha);
}
//Get all electron states
vec slaterDeterminant::getStates(double rtot, double alpha) {
vec updatedStates = zeros<vec>(nElectrons/2,1);
updatedStates(0) = function->psi1s(rtot, alpha); //n=1,l=0,ml=0
updatedStates(1) = function->psi2s(rtot, alpha); //n=2,l=0,ml=0
return updatedStates;
}
//Update the inverse Slater determinant
void slaterDeterminant::updateDeterminant(const mat &rNew, const mat &rOld, int i, double &alpha_, double ratio) {
double rtot = 0;
int particle = 0;
//Get rtot for particles' position:
for(int d = 0; d < nDimensions; d++) {
rtot += rNew(i,d) * rNew(i,d);
}
rtot = sqrt(rtot);
vec newStates = getStates(rtot, alpha_); //Get all electron states
vec sumSj = zeros<vec>(nElectrons/2); //Sum over states(l)*d_lj for particles j
if(i<nElectrons) { //Atom1, electrons 0-3
particle = i;
if(i>1) particle = i - nElectrons/2;
if(i==0 || i==1) { //Spin up
for(int j=0; j<nElectrons/2; j++) { //Cols
for(int l=0; l<nElectrons/2; l++) { //Rows
sumSj(j) += newStates(l) * invSlaterMatrixUp1(l,j);
}
}
//Update all columns except column corresponding to particle i:
for (int j=0; j<nElectrons/2; j++) {
for(int k=0; k<nElectrons/2; k++) {
if(j != i) invSlaterMatrixUp1(k,j) = invSlaterMatrixUp1(k,j) - (sumSj(j)/ratio)*invSlaterMatrixUp1(k,i);
}
}
}
else { //If particle i has spin down
for(int j=0; j<nElectrons/2; j++) { //Cols
for(int l=0; l<nElectrons/2; l++) { //Rows
sumSj(j) += newStates(l) * invSlaterMatrixDown1(l,j);
}
}
for (int j=0; j<nElectrons/2; j++) { //Cols, inv matrix
for(int k=0; k<nElectrons/2; k++) { //Rows, inv matrix
if(j != particle) invSlaterMatrixDown1(k,j) = invSlaterMatrixDown1(k,j) - (sumSj(j)/ratio)*invSlaterMatrixDown1(k,particle);
}
}
}
//Update column corresponding to particle i:
for(int k=0; k<nElectrons/2; k++) { //States (rows)
if(i<nElectrons/2) { invSlaterMatrixUp1(k,particle) = (1/ratio)*invSlaterMatrixUp1(k,particle); }
else {invSlaterMatrixDown1(k,particle) = (1/ratio)*invSlaterMatrixDown1(k,particle); }
}
}
else { //Atom2, electrons 4-7
i -= 4;
particle = i;
if(i>1) particle = i - nElectrons/2;
if(i==0 || i==1) { //Spin up
for(int j=0; j<nElectrons/2; j++) { //Cols
for(int l=0; l<nElectrons/2; l++) { //Rows
sumSj(j) += newStates(l) * invSlaterMatrixUp2(l,j);
}
}
//Update all columns except column corresponding to particle i:
for (int j=0; j<nElectrons/2; j++) {
for(int k=0; k<nElectrons/2; k++) {
if(j != i) invSlaterMatrixUp2(k,j) = invSlaterMatrixUp2(k,j) - (sumSj(j)/ratio)*invSlaterMatrixUp2(k,i);
}
}
}
else { //If particle i has spin down
for(int j=0; j<nElectrons/2; j++) { //Cols
for(int l=0; l<nElectrons/2; l++) { //Rows
sumSj(j) += newStates(l) * invSlaterMatrixDown2(l,j);
}
}
for (int j=0; j<nElectrons/2; j++) { //Cols, inv matrix
for(int k=0; k<nElectrons/2; k++) { //Rows, inv matrix
if(j != particle) invSlaterMatrixDown2(k,j) = invSlaterMatrixDown2(k,j) - (sumSj(j)/ratio)*invSlaterMatrixDown2(k,particle);
}
}
}
//Update column corresponding to particle i:
for(int k=0; k<nElectrons/2; k++) { //States (rows)
if(i<nElectrons/2) { invSlaterMatrixUp2(k,particle) = (1/ratio)*invSlaterMatrixUp2(k,particle); }
else {invSlaterMatrixDown2(k,particle) = (1/ratio)*invSlaterMatrixDown2(k,particle); }
}
}
}
//Get the gradient of the Slater determinant
vec slaterDeterminant::gradientWaveFunction(const mat &r, int i, double ratio, double alpha) {
vec gradient = zeros<vec>(nDimensions,1);
vec invMatrix = zeros<vec>(nElectrons/2,1);
for(int j=0; j<nElectrons/2; j++) {
if(i==0 || i==1) { invMatrix(j) = invSlaterMatrixUp1(j,i); }
if(i==2 || i==3) { invMatrix(j) = invSlaterMatrixDown1(j,i-2); }
if(i==4 || i==5) { invMatrix(j) = invSlaterMatrixUp2(j,i-4); }
if(i==6 || i==7) { invMatrix(j) = invSlaterMatrixDown2(j,i-6); }
}
double rtot = 0;
for (int d=0; d<nDimensions; d++) { rtot += r(i,d)*r(i,d); }
rtot = sqrt(rtot);
gradient = function->dPsi1s(rtot, i, r, alpha)*(1/ratio)*invMatrix(0); //n=1,l=0,ml=0
gradient += function->dPsi2s(rtot, i, r, alpha)*(1/ratio)*invMatrix(1); //n=2,l=0,ml=0
return gradient;
}
//Numerical gradient
vec slaterDeterminant::gradientWaveFunctionNum(const mat &r, int i, double alpha_) {
vec grad = zeros(nDimensions);
mat rPlus = zeros<mat>(nDimensions);
mat rMinus = zeros<mat>(nDimensions);
double wf = beryllium(r,alpha_);
double h = 0.001;
rPlus = rMinus = r;
double waveFunctionMinus = 0;
double waveFunctionPlus = 0;
//First derivative
for(int j = 0; j < nDimensions; j++) {
rPlus(i,j) = r(i,j)+h;
rMinus(i,j) = r(i,j)-h;
waveFunctionMinus = beryllium(rMinus,alpha_);
waveFunctionPlus = beryllium(rPlus,alpha_);
grad(j) = (waveFunctionPlus - waveFunctionMinus)/(2*wf*h);
rPlus(i,j) = r(i,j);
rMinus(i,j) = r(i,j);
}
//cout <<"Numerical: "<< grad << endl;
return grad;
}
//Get second derivative, for kinetic energy
double slaterDeterminant::laPlaceWaveFunction(const mat &r, int i, double alpha) {
double rtot = 0;
double laplace = 0;
vec invMatrix = zeros<vec>(nElectrons/2,1);
rtot = 0;
for (int d=0; d<nDimensions; d++) { rtot += r(i,d)*r(i,d); } //Get r for particle
rtot = sqrt(rtot);
invMatrix.fill(0);
for(int j=0; j<nElectrons/2; j++) {
if(i==0 || i==1) { invMatrix(j) = invSlaterMatrixUp1(j,i); }
if(i==2 || i==3) { invMatrix(j) = invSlaterMatrixDown1(j,i-2); }
if(i==4 || i==5) { invMatrix(j) = invSlaterMatrixUp2(j,i-4); }
if(i==6 || i==7) { invMatrix(j) = invSlaterMatrixDown2(j,i-6); }
}
//Get laplacian for each state:
laplace += function->d2Psi1s(rtot, alpha)*invMatrix(0); //n=1,l=0,ml=0
laplace += function->d2Psi2s(rtot, alpha)*invMatrix(1);//n=2,l=0,ml=0
//cout <<"Analytical: "<<laplace<<endl;
return laplace;
}
//Second derivative, numerical method
double slaterDeterminant::laPlaceWaveFunctionNum(const mat &r, double alpha) {
double h2 = 1000000;
double h = 0.001;
mat rPlus = zeros<mat>(nParticles, nDimensions);
mat rMinus = zeros<mat>(nParticles, nDimensions);
rPlus = rMinus = r;
double waveFunctionMinus = 0;
double waveFunctionPlus = 0;
double waveFunctionCurrent = beryllium(r, alpha); //Find wavefunction for r
//Second derivative (del^2):
double kineticEnergy = 0;
for(int i = 0; i < nParticles; i++) {
for(int j = 0; j < nDimensions; j++) {
rPlus(i,j) += h;
rMinus(i,j) -= h;
waveFunctionMinus = beryllium(rMinus, alpha);
waveFunctionPlus = beryllium(rPlus, alpha);
kineticEnergy -= (waveFunctionMinus + waveFunctionPlus - 2 * waveFunctionCurrent);
rPlus(i,j) = r(i,j);
rMinus(i,j) = r(i,j);
}
}
kineticEnergy = 0.5 * h2 * kineticEnergy / waveFunctionCurrent;
//cout <<"Numerical: "<<kineticEnergy<<endl;
return kineticEnergy;
}
//Beryllium, for testing
double slaterDeterminant::beryllium(const mat &r, double &alpha_) {
double rs[nParticles];
double sum = 0;
//Find |r| for each electron:
double rSingleParticle = 0;
for(int i = 0; i < nParticles; i++) {
rSingleParticle = 0;
for(int j = 0; j < nDimensions; j++) {
rSingleParticle += r(i,j) * r(i,j);
}
rs[i] = sqrt(rSingleParticle);
sum += rs[i];
}
//Slater determinant, Be
double waveFunction1 = (function->psi1s(rs[0], alpha_)*function->psi2s(rs[1], alpha_) - function->psi1s(rs[1], alpha_)*function->psi2s(rs[0], alpha_))*
(function->psi1s(rs[2], alpha_)*function->psi2s(rs[3], alpha_) - function->psi1s(rs[3], alpha_)*function->psi2s(rs[2], alpha_));
double waveFunction2 = (function->psi1s(rs[4], alpha_)*function->psi2s(rs[5], alpha_) - function->psi1s(rs[5], alpha_)*function->psi2s(rs[4], alpha_))*
(function->psi1s(rs[6], alpha_)*function->psi2s(rs[7], alpha_) - function->psi1s(rs[7], alpha_)*function->psi2s(rs[6], alpha_));
return waveFunction1*waveFunction2;
}
<file_sep>#ifndef CORRELATION_H
#define CORRELATION_H
#include <armadillo>
using namespace arma;
using namespace std;
class correlation
{
public:
correlation(int nParticles_, int nDimensions_);
double jastrow(const mat &r, double beta);
double jastrowNum(const mat &r, double beta);
double getRatioJastrow(int i, const mat &rOld, const mat &rNew, double beta);
vec gradientWaveFunction(const mat &r, int i, double beta);
vec gradientWaveFunctionNum(const mat &r, int i, double beta);
double laPlaceWaveFunction(const mat &r, double beta);
double laPlaceWaveFunctionNum(const mat &r, double beta);
private:
int nParticles;
int nDimensions;
};
#endif // CORRELATION_H
<file_sep>#ifndef HAMILTONIAN_H
#define HAMILTONIAN_H
#include "slaterdeterminant.h"
#include "correlation.h"
class Hamiltonian
{
public:
Hamiltonian(int nParticles_, int nDimensions_, double h_, double h2_, int charge_);
double localEnergy(const mat &r, const double &alpha, const double &beta, slaterDeterminant *slater, correlation *corr);
vec dPsi(const mat &r, double alpha, double beta, slaterDeterminant *slater, correlation *corr);
private:
double kineticEnergy(const mat &r, const double &alpha, const double &beta, slaterDeterminant *slater, correlation *corr);
double potentialEnergy(const mat &r);
int nDimensions;
int nParticles;
double h;
double h2;
int charge;
};
#endif // HAMILTONIAN_H
<file_sep>#include "WaveFunction.h"
#include "lib.h"
#include <armadillo>
using namespace arma;
using namespace std;
WaveFunction::WaveFunction(int &nParticles_, int &nDimensions_) :
nDimensions(nDimensions_),
nParticles(nParticles_)
{
}
//Wavefunction, 1s state
double WaveFunction::psi1s(double rtot, double alpha) {
double psi = exp(-alpha*rtot);
return psi;
}
//First derivative of wavefunction, 1s state
vec WaveFunction::dPsi1s(double rtot, int i, const mat &r, double alpha) {
vec der = zeros<vec>(3,1);
der(0) = -alpha*r(i,0)*exp(-alpha*rtot)/rtot;
der(1) = -alpha*r(i,1)*exp(-alpha*rtot)/rtot;
der(2) = -alpha*r(i,2)*exp(-alpha*rtot)/rtot;
return der;
}
///First derivative of wavefunction wrt alpha, 1s state
double WaveFunction::dPsi1s_dalpha(double rtot, double alpha) {
return -rtot*exp(-alpha*rtot);
}
//Second derivative of wavefunction, 1s state
double WaveFunction::d2Psi1s(double rtot, double alpha) {
double der = alpha*(alpha*rtot - 2)*exp(-alpha*rtot)/rtot;
return der;
}
//Wavefunction, 2s state
double WaveFunction::psi2s(double rtot, double alpha) {
double psi = (1-(alpha*rtot)/2)*exp(-alpha*rtot/2);
return psi;
}
//First derivative of wavefunction, 2s state
vec WaveFunction::dPsi2s(double rtot, int i, const mat &r, double alpha) {
vec der = zeros<vec>(3,1);
der(0) = alpha*r(i,0)*(alpha*rtot - 4)*exp(-alpha*rtot/2)/(4*rtot);
der(1) = alpha*r(i,1)*(alpha*rtot - 4)*exp(-alpha*rtot/2)/(4*rtot);
der(2) = alpha*r(i,2)*(alpha*rtot - 4)*exp(-alpha*rtot/2)/(4*rtot);
return der;
}
//First derivative of wavefunction wrt alpha, 2s state
double WaveFunction::dPsi2s_dalpha(double rtot, double alpha) {
double psi = rtot*(alpha*rtot/4 - 1)*exp(-alpha*rtot/2);
return psi;
}
//Second derivative of wavefunction, 2s state
double WaveFunction::d2Psi2s(double rtot, double alpha) {
double der = -(alpha/(8*rtot))*(alpha*rtot-8)*(alpha*rtot-2)*exp(-alpha*rtot/2);
return der;
}
//Wavefunction, 2p ml=0 state
double WaveFunction::psi2p0(double rtot, int i, const mat &r, double alpha) {
double psi = r(i,0)*alpha*rtot*exp(-alpha*rtot/2);
return psi;
}
//First derivative of wavefunction wrt alpha, 2p ml=0 state
double WaveFunction::dPsi2p0_dalpha(double rtot, int i, const mat &r, double alpha) {
double psi = r(i,0)*rtot*(1-alpha*rtot/2)*exp(-alpha*rtot/2);
return psi;
}
//Wavefunction, 2p ml=-1 state
double WaveFunction::psi2p_1(double rtot, int i, const mat &r, double alpha) {
double psi = r(i,1)*alpha*rtot*exp(-alpha*rtot/2);
return psi;
}
//First derivative of wavefunction wrt alpha, 2p ml=-1 state
double WaveFunction::dPsi2p_1_dalpha(double rtot, int i, const mat &r, double alpha) {
double psi = r(i,1)*rtot*(1-alpha*rtot/2)*exp(-alpha*rtot/2);
return psi;
}
//Wavefunction, 2p ml=1 state
double WaveFunction::psi2p1(double rtot, int i, const mat &r, double alpha) {
double psi = r(i,2)*alpha*rtot*exp(-alpha*rtot/2);
return psi;
}
//First derivative of wavefunction wrt alpha, 2p ml=1 state
double WaveFunction::dPsi2p1_dalpha(double rtot, int i, const mat &r, double alpha) {
double psi = r(i,2)*rtot*(1-alpha*rtot/2)*exp(-alpha*rtot/2);
return psi;
}
//First derivative of wavefunction, 2p ml=0 state
vec WaveFunction::dPsi2p0(double rtot, int i, const mat &r, double alpha) {
double x=r(i,0);
double y=r(i,1);
double z=r(i,2);
vec der = zeros<vec>(3,1);
der(0) = -alpha*(alpha*rtot*pow(x, 2) - 2*pow(rtot, 2) - 2*pow(x, 2))*exp(-alpha*rtot/2)/(2*rtot);
der(1) = -alpha*x*y*(alpha*rtot - 2)*exp(-alpha*rtot/2)/(2*rtot);
der(2) = -alpha*x*z*(alpha*rtot - 2)*exp(-alpha*rtot/2)/(2*rtot);
return der;
}
//First derivative of wavefunction, 2p ml=-1 state
vec WaveFunction::dPsi2p_1(double rtot, int i, const mat &r, double alpha) {
double x=r(i,0);
double y=r(i,1);
double z=r(i,2);
vec der = zeros<vec>(3,1);
der(0) = -alpha*x*y*(alpha*rtot - 2)*exp(-alpha*rtot/2)/(2*rtot);
der(1) = -alpha*(alpha*rtot*pow(y, 2) - 2*pow(rtot, 2) - 2*pow(y, 2))*exp(-alpha*rtot/2)/(2*rtot);
der(2) = -alpha*y*z*(alpha*rtot - 2)*exp(-alpha*rtot/2)/(2*rtot);
return der;
}
//First derivative of wavefunction, 2p ml=1 state
vec WaveFunction::dPsi2p1(double rtot, int i, const mat &r, double alpha) {
double x=r(i,0);
double y=r(i,1);
double z=r(i,2);
vec der = zeros<vec>(3,1);
der(0) = -alpha*x*z*(alpha*rtot - 2)*exp(-alpha*rtot/2)/(2*rtot);
der(1) = -alpha*y*z*(alpha*rtot - 2)*exp(-alpha*rtot/2)/(2*rtot);
der(2) = -alpha*(alpha*rtot*pow(z, 2) - 2*pow(rtot, 2) - 2*pow(z, 2))*exp(-alpha*rtot/2)/(2*rtot);
return der;
}
//Second derivative of wavefunction, 2p ml=0 state
double WaveFunction::d2Psi2p0(double rtot, int i, const mat &r, double alpha) {
double x=r(i,0);
double y=r(i,1);
double z=r(i,2);
vec der2 = zeros<vec>(3,1);
der2(0) = alpha*x*(pow(alpha, 2)*pow(rtot, 2)*pow(x, 2) - 6*alpha*pow(rtot, 3) - 2*alpha*rtot*pow(x, 2) + 12*pow(rtot, 2) - 4*pow(x, 2))*exp(-alpha*rtot/2)/(4*pow(rtot, 3));
der2(1) = alpha*x*(pow(alpha, 2)*pow(rtot, 2)*pow(y, 2) - 2*alpha*pow(rtot, 3) - 2*alpha*rtot*pow(y, 2) + 4*pow(rtot, 2) - 4*pow(y, 2))*exp(-alpha*rtot/2)/(4*pow(rtot, 3));
der2(2) = alpha*x*(pow(alpha, 2)*pow(rtot, 2)*pow(z, 2) - 2*alpha*pow(rtot, 3) - 2*alpha*rtot*pow(z, 2) + 4*pow(rtot, 2) - 4*pow(z, 2))*exp(-alpha*rtot/2)/(4*pow(rtot, 3));
return sum(der2);
}
//Second derivative of wavefunction, 2p ml=-1 state
double WaveFunction::d2Psi2p_1(double rtot, int i, const mat &r, double alpha) {
double x=r(i,0);
double y=r(i,1);
double z=r(i,2);
vec der = zeros<vec>(3,1);
der(0) = alpha*y*(pow(alpha, 2)*pow(rtot, 2)*pow(x, 2) - 2*alpha*pow(rtot, 3) - 2*alpha*rtot*pow(x, 2) + 4*pow(rtot, 2) - 4*pow(x, 2))*exp(-alpha*rtot/2)/(4*pow(rtot, 3));
der(1) = alpha*y*(pow(alpha, 2)*pow(rtot, 2)*pow(y, 2) - 6*alpha*pow(rtot, 3) - 2*alpha*rtot*pow(y, 2) + 12*pow(rtot, 2) - 4*pow(y, 2))*exp(-alpha*rtot/2)/(4*pow(rtot, 3));
der(2) = alpha*y*(pow(alpha, 2)*pow(rtot, 2)*pow(z, 2) - 2*alpha*pow(rtot, 3) - 2*alpha*rtot*pow(z, 2) + 4*pow(rtot, 2) - 4*pow(z, 2))*exp(-alpha*rtot/2)/(4*pow(rtot, 3));
return sum(der);
}
//Second derivative of wavefunction, 2p ml=1 state
double WaveFunction::d2Psi2p1(double rtot, int i, const mat &r, double alpha) {
double x=r(i,0);
double y=r(i,1);
double z=r(i,2);
vec der = zeros<vec>(3,1);
der(0) = alpha*z*(pow(alpha, 2)*pow(rtot, 2)*pow(x, 2) - 2*alpha*pow(rtot, 3) - 2*alpha*rtot*pow(x, 2) + 4*pow(rtot, 2) - 4*pow(x, 2))*exp(-alpha*rtot/2)/(4*pow(rtot, 3));
der(1) = alpha*z*(pow(alpha, 2)*pow(rtot, 2)*pow(y, 2) - 2*alpha*pow(rtot, 3) - 2*alpha*rtot*pow(y, 2) + 4*pow(rtot, 2) - 4*pow(y, 2))*exp(-alpha*rtot/2)/(4*pow(rtot, 3));
der(2) = alpha*z*(pow(alpha, 2)*pow(rtot, 2)*pow(z, 2) - 6*alpha*pow(rtot, 3) - 2*alpha*rtot*pow(z, 2) + 12*pow(rtot, 2) - 4*pow(z, 2))*exp(-alpha*rtot/2)/(4*pow(rtot, 3));
return sum(der);
}
<file_sep>#include "hamiltonian.h"
#include "WaveFunction.h"
Hamiltonian::Hamiltonian(int nParticles_, int nDimensions_, double h_, double h2_, int charge_) :
nDimensions(nDimensions_),
nParticles(nParticles_),
h(h_),
h2(h2_),
charge(charge_)
{
}
//Find the local energy (expectation value of the energy) numerically
double Hamiltonian::localEnergy(const mat &r, const double &alpha, const double &beta, WaveFunction *function)
{
double kinEnergy = kineticEnergy(r, alpha, beta, function);
double potEnergy = potentialEnergy(r);
return kinEnergy + potEnergy;
}
//Find the kinetic energy part of the local energy
double Hamiltonian::kineticEnergy(const mat &r, const double &alpha, const double &beta, WaveFunction *function)
{
mat rPlus = zeros<mat>(nParticles, nDimensions);
mat rMinus = zeros<mat>(nParticles, nDimensions);
rPlus = rMinus = r;
double waveFunctionMinus = 0;
double waveFunctionPlus = 0;
double waveFunctionCurrent = function->waveFunction(r, alpha, beta); //Find wavefunction for r
//Second derivative (del^2):
double kineticEnergy = 0;
for(int i = 0; i < nParticles; i++) {
for(int j = 0; j < nDimensions; j++) {
rPlus(i,j) += h;
rMinus(i,j) -= h;
waveFunctionMinus = function->waveFunction(rMinus, alpha, beta);
waveFunctionPlus = function->waveFunction(rPlus, alpha, beta);
kineticEnergy -= (waveFunctionMinus + waveFunctionPlus - 2 * waveFunctionCurrent);
rPlus(i,j) = r(i,j);
rMinus(i,j) = r(i,j);
}
}
kineticEnergy = 0.5 * h2 * kineticEnergy / waveFunctionCurrent;
return kineticEnergy;
}
double Hamiltonian::potentialEnergy(const mat &r)
{
// Potential energy (1/r part)
double potentialEnergy = 0;
double rSingleParticle = 0;
for(int i = 0; i < nParticles; i++) {
rSingleParticle = 0;
for(int j = 0; j < nDimensions; j++) {
rSingleParticle += r(i,j)*r(i,j);
}
potentialEnergy -= charge / sqrt(rSingleParticle);
}
// Contribution from electron-electron potential (1/rij part)
double r12 = 0;
for(int i = 0; i < nParticles; i++) {
for(int j = i + 1; j < nParticles; j++) {
r12 = 0;
for(int k = 0; k < nDimensions; k++) {
r12 += (r(i,k) - r(j,k)) * (r(i,k) - r(j,k));
}
potentialEnergy += 1 / sqrt(r12);
}
}
return potentialEnergy;
}
//Find derivative of wavefunction wrt alpha, beta
vec Hamiltonian::dPsi(const mat &r, double alpha, double beta, WaveFunction *function) {
vec dPsi = zeros<vec>(2,1);
double wf = function->waveFunction(r, alpha, beta); //Find wavefunction for r
//First derivative of wavefunction wrt alpha
double alphaPlus, alphaMinus;
alphaPlus = alphaMinus = alpha;
double waveFunctionMinus = 0;
double waveFunctionPlus = 0;
alphaPlus = alpha+h;
alphaMinus = alpha-h;
waveFunctionMinus = function->waveFunction(r, alphaMinus, beta);
waveFunctionPlus = function->waveFunction(r, alphaPlus, beta);
dPsi(0) = (waveFunctionPlus - waveFunctionMinus)/(2*wf*h);
//First derivative of wavefunction wrt beta
double betaPlus, betaMinus;
betaPlus = betaMinus = beta;
betaPlus = beta+h;
betaMinus = beta-h;
waveFunctionMinus = function->waveFunction(r,alpha, betaMinus);
waveFunctionPlus = function->waveFunction(r,alpha, betaPlus);
dPsi(1) = (waveFunctionPlus - waveFunctionMinus)/(2*wf*h);
return dPsi;
}
//The analytic energy of He
double Hamiltonian::analyticEnergyHe(const mat &r, const double &alpha, const double &beta)
{
double r1 = 0;
double r2 = 0;
double r12 = 0;
double dot_r12 = 0;
for(int d=0; d<nDimensions; d++) {
r1 += pow(r(0,d),2);
r2 += pow(r(1,d),2);
r12 += pow(r(0,d) - r(1,d),2);
dot_r12 += r(0,d)*r(1,d);
}
r1 = sqrt(r1);
r2 = sqrt(r2);
r12 = sqrt(r12);
double energy_l1 = (alpha-charge)*(1/r1 + 1/r2) + 1/r12 - pow(alpha,2);
double energy_part = ((alpha*(r1+r2))/r12)*(1-dot_r12/(r1*r2)) - 1/(2*pow((1+beta*r12),2)) - 2/r12 + (2*beta)/(1+beta*r12);
double energy_l2 = energy_l1 + 1/(2*pow((1+beta*r12),2))*energy_part;
return energy_l2;
}
<file_sep>#include "hamiltonian.h"
#include "slaterdeterminant.h"
#include "correlation.h"
Hamiltonian::Hamiltonian(int nDimensions_, double h_, double h2_, int nProtons_, int nElectrons_, double R_, const mat &rProtons_) :
nDimensions(nDimensions_),
nProtons(nProtons_),
nElectrons(nElectrons_),
nParticles(nProtons*nElectrons),
h(h_),
h2(h2_),
R(R_),
rProtons(rProtons_)
{
}
//Find the local energy (expectation value of the energy) numerically
double Hamiltonian::localEnergy(const mat &r, const double &alpha, const double &beta, slaterDeterminant *slater, correlation *corr)
{
double kinEnergy = kineticEnergy(r, alpha, beta, slater,corr);
double potEnergy = potentialEnergy(r);
return kinEnergy + potEnergy;
}
//dPsi/dalpha/Psi and dPsi/dbeta/Psi
vec Hamiltonian::dPsi(const mat &r, double alpha, double beta, slaterDeterminant *slater, correlation *corr) {
vec dPsi = zeros<vec>(2,1);
//First derivative of wavefunction wrt alpha
//slater->buildDeterminant(r,alpha);
double wf = slater->getDeterminant();
double alphaPlus, alphaMinus;
alphaPlus = alphaMinus = alpha;
double waveFunctionMinus = 0;
double waveFunctionPlus = 0;
alphaPlus = alpha+h;
alphaMinus = alpha-h;
slater->buildDeterminant(r,alphaMinus);
waveFunctionMinus = slater->getDeterminant();
slater->buildDeterminant(r,alphaPlus);
waveFunctionPlus = slater->getDeterminant();
dPsi(0) = (waveFunctionPlus - waveFunctionMinus)/(2*wf*h);
slater->buildDeterminant(r,alpha);
//First derivative of wavefunction wrt beta
wf = corr->jastrow(r,beta);
double betaPlus, betaMinus;
betaPlus = betaMinus = beta;
betaPlus = beta+h;
betaMinus = beta-h;
waveFunctionMinus = corr->jastrow(r,betaMinus);
waveFunctionPlus = corr->jastrow(r,betaPlus);
dPsi(1) = (waveFunctionPlus - waveFunctionMinus)/(2*wf*h);
return dPsi;
}
//Find the kinetic energy part of the local energy
double Hamiltonian::kineticEnergy(const mat &r, const double &alpha, const double &beta, slaterDeterminant *slater, correlation *corr)
{
vec gradSlater1 = zeros<vec>(nDimensions,1);
vec gradSlater2 = zeros<vec>(nDimensions,1);
vec gradCorr = zeros<vec>(nDimensions,1);
double laPlaceSlater1 = 0;
double laPlaceSlater2 = 0;
double gradProduct = 0;
double laPlaceCorr = corr->laPlaceWaveFunction(r,beta);
for(int i=0;i<nParticles;i++) gradCorr = corr->gradientWaveFunction(r,i,beta);
for(int i=0;i<nElectrons;i++) { //Atom1
laPlaceSlater1 += slater->laPlaceWaveFunction(r, i, alpha);
gradSlater1 += slater->gradientWaveFunction(r,i,1,alpha);
}
for(int j=nElectrons;j<nParticles;j++) { //Atom2
laPlaceSlater2 += slater->laPlaceWaveFunction(r, j, alpha);
gradSlater2 += slater->gradientWaveFunction(r,j,1,alpha);
}
gradProduct = dot(gradSlater1, gradCorr) + dot(gradSlater2, gradCorr) + dot(gradSlater1, gradSlater2);
double kineticEnergy = -0.5*(laPlaceSlater1+laPlaceSlater2+laPlaceCorr+2*gradProduct);
return kineticEnergy;
}
double Hamiltonian::potentialEnergy(const mat &r)
{
double potentialE = 0;
//Contribution from electron - proton potential (Z/rep)
double rp = 0;
for(int e=0; e<nParticles; e++) {
for(int p=0; p<nProtons; p++) {
rp = 0;
for(int d=0; d<nDimensions; d++) rp += (r(e,d) - rProtons(p,d))*(r(e,d) - rProtons(p,d));
potentialE -= 4/sqrt(rp);
}
}
// Contribution from electron-electron potential (1/rij part)
double r12 = 0;
for(int i = 1; i < nParticles; i++) {
for(int j = 0; j < i; j++) {
r12 = 0;
for(int k = 0; k < nDimensions; k++) r12 += pow((r(i,k) - r(j,k)),2);
potentialE += 1 / sqrt(r12);
}
}
//Contribution from proton-proton potential Z*Z/R
potentialE += abs(16/R);
return potentialE;
}
<file_sep>#include "WaveFunction.h"
#include "lib.h"
#include <armadillo>
using namespace arma;
using namespace std;
WaveFunction::WaveFunction(int &nParticles_, int &nDimensions_) :
nDimensions(nDimensions_),
nParticles(nParticles_),
slater(new slaterDeterminant(nParticles,nDimensions))
{
}
//Compute wavefunction of He:
double WaveFunction::waveFunction(const mat &r, double alpha_, double beta_) {
alpha = alpha_;
beta = beta_;
double argument = 0;
double waveFunc = 0;
for(int i = 0; i < nParticles; i++) {
double rSingleParticle = 0;
for(int j = 0; j < nDimensions; j++) {
rSingleParticle += r(i,j) * r(i,j);
}
argument += sqrt(rSingleParticle);
}
waveFunc = exp(-argument * alpha) * jastrowFactor(r); //Both parts of wavefunction
return waveFunc;
}
//Correlation part of wavefunction:
double WaveFunction::jastrowFactor(const mat &r) {
rowvec r12;
double r12norm = 0;
double jastrow = 0;
for(int k=0;k<nParticles;k++) {
for(int l=0;l<nParticles;l++) {
if(k<l) {
r12 = r.row(k) - r.row(l);
r12norm = 0;
for(int j = 0; j < nDimensions; j++) {
r12norm += r12(j)*r12(j);
}
r12norm = sqrt(r12norm);
jastrow += r12norm / (2 * (1 + beta * r12norm));
}
}
}
return exp(jastrow);
}
<file_sep>#ifndef SLATERDETERMINANT_H
#define SLATERDETERMINANT_H
#include <armadillo>
#include "WaveFunction.h"
using namespace arma;
using namespace std;
class slaterDeterminant
{
public:
slaterDeterminant(int nParticles_, int nDimensions_);
void buildDeterminant(const mat &r, double &alpha_, double &beta_);
double getRatioDeterminant(int i, const mat &r, double alpha, double beta);
vec gradientWaveFunction(const mat &r, int i, double ratio, double alpha, double beta);
double laPlaceWaveFunction(const mat &r, double alpha, double beta);
double laPlaceWaveFunctionNum(const mat &r, double alpha, double beta);
double getDeterminant();
double getInvDeterminant();
vec getStates(const mat &r, int i, double rtot, double alpha, double beta);
void updateDeterminant(const mat &rNew, const mat &rOld, int i, double &alpha_, double &beta_, double ratio);
double beryllium(const mat &r, double &alpha);
vec gradientWaveFunctionNum(const mat &r, int i, double alpha_, double beta_);
double getRatioDeterminantNum(int i, const mat &rOld, const mat &rNew, double alpha, double beta);
private:
WaveFunction *function;
int nDimensions;
int nParticles;
mat slaterMatrixUp;
mat slaterMatrixDown;
mat invSlaterMatrixUp;
mat invSlaterMatrixDown;
};
#endif // SLATERDETERMINANT_H
<file_sep>#ifndef WAVEFUNCTION_H
#define WAVEFUNCTION_H
#include <armadillo>
using namespace arma;
using namespace std;
class WaveFunction {
public:
WaveFunction(int &nDimensions_, int &nProtons_, int &nElectrons_);
double waveFunction(const mat &r, const mat &rProtons, double alpha, double beta);
private:
double jastrowFactor(const mat &r, double beta);
int nDimensions;
int nProtons;
int nElectrons;
int nParticles;
double alpha;
double beta;
};
#endif // WAVEFUNCTION_H
<file_sep>#include "hamiltonian.h"
#include "slaterdeterminant.h"
#include "correlation.h"
Hamiltonian::Hamiltonian(int nParticles_, int nDimensions_, double h_, double h2_, int charge_) :
nDimensions(nDimensions_),
nParticles(nParticles_),
h(h_),
h2(h2_),
charge(charge_)
{
}
//Find the local energy (expectation value of the energy)
double Hamiltonian::localEnergy(const mat &r, const double &alpha, const double &beta, slaterDeterminant *slater, correlation *corr)
{
double kinEnergy = kineticEnergy(r, alpha, beta, slater,corr);
double potEnergy = potentialEnergy(r);
return kinEnergy + potEnergy;
}
//dPsi/dalpha/Psi and dPsi/dbeta/Psi
vec Hamiltonian::dPsi(const mat &r, double alpha, double beta, slaterDeterminant *slater, correlation *corr) {
vec dPsi = zeros<vec>(2,1);
//First derivative of wavefunction wrt alpha
slater->buildDeterminant(r,alpha,beta);
double wf = slater->getDeterminant();
double alphaPlus, alphaMinus;
alphaPlus = alphaMinus = alpha;
double waveFunctionMinus = 0;
double waveFunctionPlus = 0;
alphaPlus = alpha+h;
alphaMinus = alpha-h;
slater->buildDeterminant(r,alphaMinus,beta);
waveFunctionMinus = slater->getDeterminant();
slater->buildDeterminant(r,alphaPlus,beta);
waveFunctionPlus = slater->getDeterminant();
dPsi(0) = (waveFunctionPlus - waveFunctionMinus)/(2*wf*h);
slater->buildDeterminant(r,alpha,beta);
//First derivative of wavefunction wrt beta
wf = corr->jastrow(r,beta);
double betaPlus, betaMinus;
betaPlus = betaMinus = beta;
betaPlus = beta+h;
betaMinus = beta-h;
waveFunctionMinus = corr->jastrow(r,betaMinus);
waveFunctionPlus = corr->jastrow(r,betaPlus);
dPsi(1) = (waveFunctionPlus - waveFunctionMinus)/(2*wf*h);
return dPsi;
}
//Find the kinetic energy part of the local energy
double Hamiltonian::kineticEnergy(const mat &r, const double &alpha, const double &beta, slaterDeterminant *slater, correlation *corr)
{
vec gradSlater = zeros<vec>(nDimensions,1);
vec gradCorr = zeros<vec>(nDimensions,1);
double gradProduct = 0;
double laPlaceSlater = slater->laPlaceWaveFunction(r, alpha, beta);
double laPlaceCorr = corr->laPlaceWaveFunction(r,beta);
for(int i=0;i<nParticles;i++) {
gradSlater = slater->gradientWaveFunction(r,i,1,alpha,beta);
gradCorr = corr->gradientWaveFunction(r,i,beta);
gradProduct += dot(gradSlater, gradCorr);
}
double kineticEnergy = -0.5*(laPlaceSlater+laPlaceCorr+2*gradProduct);
return kineticEnergy;
}
double Hamiltonian::potentialEnergy(const mat &r)
{
// Potential energy (1/r part)
double potentialEnergy = 0;
double rSingleParticle = 0;
for(int i = 0; i < nParticles; i++) {
rSingleParticle = 0;
for(int j = 0; j < nDimensions; j++) {
rSingleParticle += r(i,j)*r(i,j);
}
potentialEnergy -= charge / sqrt(rSingleParticle);
}
// Contribution from electron-electron potential (1/rij part)
double r12 = 0;
for(int i = 0; i < nParticles; i++) {
for(int j = 0; j < i; j++) {
r12 = 0;
for(int k = 0; k < nDimensions; k++) {
r12 += pow((r(i,k) - r(j,k)),2);
}
potentialEnergy += 1 / sqrt(r12);
}
}
return potentialEnergy;
}
<file_sep>#include "vmcsolver.h"
#include "lib.h"
#include "WaveFunction.h"
#include "hamiltonian.h"
#include <armadillo>
#include <fstream>
#include <iostream>
#include <mpi.h>
using namespace arma;
using namespace std;
VMCSolver::VMCSolver():
nDimensions(3), //No of dimensions (1D, 2D, 3D, ...)
charge(1), //Charge of atomic nucleus
h(0.001), //Constants used in numeric derivatives
h2(1000000),
nCycles(1000000), //No of MC cycles
timestep(0.01), //Timestep in importance sampling
D(0.5), //Constant in importance sampling
stepLength(1), //Steplength in brute force Monte Carlo
minimise_var(false), //Use optimizer to find best values for alpha and beta
min_steps(50000),//Number of MC cycles for optimizer to run
alpha(1.3),
beta(0.3),
R(1.4), //Distance between protons (nucleii)
nProtons(2), //Total number of nuclei
nElectrons(1), //No of electron per atom
nParticles(nProtons*nElectrons), //Total number of electrons
printToFile(false) //Blocking
{
}
void VMCSolver::runMonteCarloIntegration(int argc, char *argv[])
{
WaveFunction *function = new WaveFunction(nDimensions,nProtons,nElectrons);
Hamiltonian *hamiltonian = new Hamiltonian(nProtons, nElectrons,nDimensions,h,h2,charge);
double energies = 0;
double energySquareds = 0;
long idum = -1;
mat Rs = zeros<vec>(20,4);
int id, np;
rProtons = zeros<mat>(nProtons, nDimensions);
//Start parallel threads
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &id);
MPI_Comm_size(MPI_COMM_WORLD, &np);
//Start timing
double myTime,mintime, maxtime,avgtime;
myTime = MPI_Wtime();
//No of MC cycles per thread
int mpi_steps = nCycles/np;
idum = idum-id; //Random seed for each thread
double* allEnergies = new double[mpi_steps+1];
double pEnergies = 0;
double pEnergySquareds = 0;
vec energySums = zeros<vec>(2);
cout << "ID: " << id << endl;
for(int b=0;b<1;b++) { //Loop over R values, invalidated
R += 0.2;
cout<<"R: "<<R<<endl;
//Set position of protons
rProtons(0,2) = -R/2;
rProtons(1,2) = R/2;
double alpha_new = alpha;
double beta_new = beta;
if(minimise_var) { //Optimize alpha and beta
double gtol = 1e-4;
int iter;
double fret;
vec p = zeros<vec>(2,1);
p(0) = alpha;
p(1) = beta;
int n = 2;
vec ans = steepest_descent(idum, p, n, gtol, min_steps, &iter, &fret, hamiltonian,function);
cout <<ans<<endl;
alpha_new = ans(0);
beta_new = ans(1);
MPI_Barrier(MPI_COMM_WORLD);
//Gather new alpha, beta
MPI_Allreduce(&alpha_new, &alpha, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(&beta_new, &beta, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
alpha = alpha/np;
beta = beta/np;
cout << "Final alpha, beta: "<< alpha<<" "<<beta<<endl;
}
//Run importance sampling MC
energySums = MCImportance(idum, alpha_new, beta_new, mpi_steps, hamiltonian, function, allEnergies);
if(printToFile) { //Blocking
cout<<"Printing to blocking file"<<endl;
ostringstream ost;
ost << "/home/anette/helium/examples/molecules/DATA/data" << id << ".mat" ;
ofstream blockofile;
blockofile.open( ost.str( ).c_str( ),ios::out | ios::binary );
if (blockofile.is_open())
{
blockofile.write((char*)(allEnergies+1) , mpi_steps*sizeof(double)) ;
blockofile.close();
}
else cout << "Unable to open data file for process " << id << endl;
}
//Find average values of energies:
pEnergies = energySums(0)/(nCycles * nParticles);
pEnergySquareds = energySums(1)/(nCycles * nParticles);
Rs(b,0) = R;
Rs(b,1) = alpha_new;
Rs(b,2) = beta_new;
Rs(b,3) = pEnergies;
cout << "--------------------------" << endl;
}
cout<<Rs<<endl;
MPI_Barrier(MPI_COMM_WORLD);
//Gather energy data from threads
MPI_Allreduce(&pEnergies, &energies, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(&pEnergySquareds, &energySquareds, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
myTime = MPI_Wtime() - myTime;
MPI_Reduce(&myTime, &maxtime, 1, MPI_DOUBLE, MPI_MAX, 0, MPI_COMM_WORLD);
MPI_Reduce(&myTime, &mintime, 1, MPI_DOUBLE, MPI_MIN, 0,MPI_COMM_WORLD);
MPI_Reduce(&myTime, &avgtime, 1, MPI_DOUBLE, MPI_SUM, 0,MPI_COMM_WORLD);
MPI_Finalize();
//Parallel threads ended
if (id == 0) {
cout << "Energies: " << energies << endl; //*2*13.6
cout << "Energy squareds: " << energySquareds << endl; //*2*13.6*2*13.6
avgtime /= np;
cout << "Min time: " << mintime << ", max time: " << maxtime << ", avg time: " << avgtime << endl;
}
delete[] allEnergies;
}
//Importance sampling MC
vec VMCSolver::MCImportance(long idum, double alpha, double beta, int mpi_steps, Hamiltonian *hamiltonian,
WaveFunction *function, double *allEnergies) {
mat rOld = zeros<mat>(nParticles, nDimensions);
mat rNew = zeros<mat>(nParticles, nDimensions);
double accepted_steps = 0;
double count_total = 0;
double deltaE = 0;
vec deltaPsi = zeros<vec>(2);
vec deltaPsiE = zeros<vec>(2);
double cycleE = 0;
vec energySums = zeros<vec>(6);
double r12 = 0;
double r1tot = 0;
double r2tot = 0;
mat qForceOld = zeros(nParticles,nDimensions);
mat qForceNew = zeros(nParticles,nDimensions);
double waveFunctionOld = 0;
double waveFunctionNew = 0;
//Get initial positions
for(int i = 0; i < nParticles; i++) {
for(int j = 0; j < nDimensions; j++) {
rOld(i,j) = gaussianDeviate(&idum)*sqrt(timestep);
}
}
//Compute the wavefunction and quantum force
waveFunctionOld = function->waveFunction(rOld, rProtons, alpha, beta);
qForceOld = quantumForce(rOld, rProtons, alpha, beta, waveFunctionOld,function);
for(int cycle = 0; cycle < mpi_steps; cycle++) { // loop over Monte Carlo cycles
for(int i = 0; i < nParticles; i++) { //Loop over particles
// New position current particle
for(int d = 0; d < nDimensions; d++) {
rNew(i,d) = rOld(i,d) + gaussianDeviate(&idum)*sqrt(timestep) + qForceOld(i,d)*timestep*D;
}
//Move only one particle (i).
for (int g=0; g<nParticles; g++) {
if(g != i) {
for(int d=0; d<nDimensions; d++) {
rNew(g,d) = rOld(g,d);
}
}
}
// Recalculate the wave function and quantum force
waveFunctionNew = function->waveFunction(rNew, rProtons, alpha, beta);
qForceNew = quantumForce(rNew, rProtons, alpha, beta, waveFunctionNew,function);
//Greens function
double greensFunction = 0;
for(int d=0; d<nDimensions; d++) {
greensFunction += 0.5*(qForceOld(i,d) + qForceNew(i,d)) * (0.5*D*timestep*(qForceOld(i,d) - qForceNew(i,d)) - rNew(i,d) + rOld(i,d));
}
greensFunction = exp(greensFunction);
++count_total;
// Check for step acceptance (if yes, update position and determinant, if no, reset position)
if(ran2(&idum) <= greensFunction * (waveFunctionNew*waveFunctionNew) / (waveFunctionOld*waveFunctionOld)) {
++accepted_steps;
for(int j = 0; j < nDimensions; j++) {
rOld(i,j) = rNew(i,j);
qForceOld(i,j) = qForceNew(i,j);
}
waveFunctionOld = waveFunctionNew;
r12 += sqrt(pow(rOld(0,0)-rOld(1,0),2)+pow(rOld(0,1)-rOld(1,1),2)+pow(rOld(0,2)-rOld(1,2),2));
r1tot += sqrt(pow(rOld(0,0),2) + pow(rOld(0,1),2) + pow(rOld(0,2),2));
r2tot += sqrt(pow(rOld(1,0),2) + pow(rOld(1,1),2) + pow(rOld(1,2),2));
}
else {
for(int j = 0; j < nDimensions; j++) {
rNew(i,j) = rOld(i,j);
qForceNew(i,j) = qForceOld(i,j);
}
}
//Get contribution to energy
deltaE = hamiltonian->localEnergy(R, rNew, rProtons, alpha, beta, function);
energySums(0) += deltaE;
energySums(1) += deltaE*deltaE;
allEnergies[cycle] += deltaE;
cycleE += deltaE;
if(minimise_var) { //If optimizer is in use, get expectance value of dPsi/dalpha and dPsi/dbeta
deltaPsi = hamiltonian->dPsi(rNew,rProtons,alpha,beta,function);
deltaPsiE(0) = deltaE*deltaPsi(0);
deltaPsiE(1) = deltaE*deltaPsi(1);
energySums(2) += deltaPsi(0);
energySums(3) += deltaPsi(1);
energySums(4) += deltaPsiE(0);
energySums(5) += deltaPsiE(1);
}
} //End particle loop
allEnergies[cycle] += cycleE; //Store energy for this MC cycle (for blocking method)
cycleE = 0;
} //End Monte Carlo loop
cout << "r1: "<<r1tot/(mpi_steps*nParticles)<<endl;
cout << "r2: "<<r2tot/(mpi_steps*nParticles)<<endl;
cout << "r12: "<<r12/(mpi_steps*nParticles)<<endl;
cout << "accepted steps: " << 100*accepted_steps/count_total << "%" << endl;
return energySums;
}
//Get random numbers with a Gaussian pdf
double VMCSolver::gaussianDeviate(long *idum) {
static int iset = 0;
static double gset;
double fac, rsq, v1, v2;
if ( idum < 0) iset =0;
if (iset == 0) {
do {
v1 = 2.*ran2(idum) -1.0;
v2 = 2.*ran2(idum) -1.0;
rsq = v1*v1+v2*v2;
} while (rsq >= 1.0 || rsq == 0.);
fac = sqrt(-2.*log(rsq)/rsq);
gset = v1*fac;
iset = 1;
return v2*fac;
} else {
iset =0;
return gset;
}
}
//Get quantum force (first derivative of wave function)
mat VMCSolver::quantumForce(const mat &r, const mat &rProtons, double alpha_, double beta_, double wf, WaveFunction *function) {
mat qforce = zeros(nParticles, nDimensions);
mat rPlus = zeros<mat>(nParticles, nDimensions);
mat rMinus = zeros<mat>(nParticles, nDimensions);
rPlus = rMinus = r;
double waveFunctionMinus = 0;
double waveFunctionPlus = 0;
//First derivative
for(int i = 0; i < nParticles; i++) {
for(int j = 0; j < nDimensions; j++) {
rPlus(i,j) = r(i,j)+h;
rMinus(i,j) = r(i,j)-h;
waveFunctionMinus = function->waveFunction(rMinus, rProtons, alpha_, beta_);
waveFunctionPlus = function->waveFunction(rPlus, rProtons, alpha_, beta_);
qforce(i,j) = (waveFunctionPlus - waveFunctionMinus)/(wf*h);
rPlus(i,j) = r(i,j);
rMinus(i,j) = r(i,j);
}
}
return qforce;
}
//Optimization of alpha and beta:
vec VMCSolver::steepest_descent(long idum, vec &p, int n, double gtol, int min_steps, int *iter, double *fret,
Hamiltonian *hamiltonian, WaveFunction *function)
{
vec dPsi = zeros<vec>(2,1);
vec dPsi_Elocal = zeros<vec>(2,1);
double* allEnergies = new double[min_steps+1];
double alpha = p(0);
double beta = p(1);
double alpha_new = alpha;
double beta_new = beta;
vec dE = zeros<vec>(n);
vec dEold = zeros<vec>(n);
int maxIter = 50;
vec answers = zeros<vec>(n+2);
double E = 0;
double Enew = 0;
double alpha_step = 0.1;
double beta_step = 1;
int i = 0;
int j = 0;
double test;
double step_reduce = 2;
double a = 1 + exp(-R/alpha);
double delta = a - alpha;
//Optimize alpha using relation alpha = 1 + exp(-R/alpha)
while(abs(delta) > gtol && j<maxIter) {
if(delta > 0) alpha_new = alpha + alpha_step;
else alpha_new = alpha - alpha_step;
alpha_step = alpha_step/1.2;
a = 1 + exp(-R/alpha_new);
cout<<"Alpha, da: "<<alpha_new<<" "<<a<<endl;
delta = a - alpha_new;
alpha = alpha_new;
j++;
}
cout <<"Alpha: "<<alpha_new<<endl;
//Optimize beta:
//Get E for current alpha and beta, do MC sample
vec Es = MCImportance(idum, alpha, beta, min_steps,hamiltonian,function,allEnergies);
E = Es(0)/(min_steps * nParticles);
dPsi(0) = Es(2)/(min_steps * nParticles);
dPsi(1) = Es(3)/(min_steps * nParticles);
dPsi_Elocal(0) = Es(4)/(min_steps * nParticles);
dPsi_Elocal(1) = Es(5)/(min_steps * nParticles);
dE = gradE(dPsi, E, dPsi_Elocal); //Get derivatives of E wrt alpha and beta
cout <<"E: "<<E<<endl;
while(i<maxIter) { //Loop until enough iterations
beta_new = beta - beta_step*dE(1); //Get new value of beta
if(beta_new < 0) { //If the new beta is negative,
while(beta_new < 0) { //Reduce step length until new beta is positive
beta_step = beta_step/step_reduce;
beta_new = beta - beta_step*dE(1);
}
}
cout<<"dE beta: "<<dE(1)<<endl;
dEold = dE;
//Get E for current alpha and beta, do MC sample
Es = MCImportance(idum, alpha_new,beta_new,min_steps,hamiltonian, function, allEnergies);
Enew = Es(0)/(min_steps * nParticles);
dPsi(0) = Es(2)/(min_steps * nParticles);
dPsi(1) = Es(3)/(min_steps * nParticles);
dPsi_Elocal(0) = Es(4)/(min_steps * nParticles);
dPsi_Elocal(1) = Es(5)/(min_steps * nParticles);
dE = gradE(dPsi, E, dPsi_Elocal); //Get derivatives of E wrt alpha and beta
//If derivatives have changed sign, reduce step length
if(dE(0)*dEold(0) < 0) alpha_step = alpha_step/step_reduce;
if(dE(1)*dEold(1) < 0) beta_step = beta_step/step_reduce;
cout <<"beta new: "<< beta_new<<" "<<endl;
cout <<"dE, Step: "<< dEold(1)<<" "<<beta_step<<" "<<endl;
cout<<"Enew: "<<Enew<<endl;
cout <<"----------"<<endl;
test = abs(Enew-E);
if(test < gtol) break; //If change in energy is smaller than tolerance, break out of loop
E = Enew; //Else: Update E, alpha and beta
beta = beta_new;
i++;
}
answers(0) = alpha_new;
answers(1) = beta_new;
answers(2) = Enew;
answers(3) = i;
return answers;
}
//Get derivatives of energy E wrt alpha, beta
vec VMCSolver::gradE(vec dPsi, double Elocal, vec dPsi_Elocal) {
vec dE = zeros<vec>(2);
dE(0) = 2*(dPsi_Elocal(0) - dPsi(0)*Elocal);
dE(1) = 2*(dPsi_Elocal(1) - dPsi(1)*Elocal);
return dE;
}
<file_sep>#ifndef HAMILTONIAN_H
#define HAMILTONIAN_H
#include <armadillo>
#include "WaveFunction.h"
using namespace arma;
class Hamiltonian
{
public:
Hamiltonian(int nProtons_, int nElectrons_, int nDimensions_, double h_, double h2_, int charge_);
double localEnergy(double R, const mat &r, const mat &rProtons, const double &alpha, const double &beta, WaveFunction *function);
vec dPsi(const mat &r, const mat &rProtons, double alpha, double beta, WaveFunction *function);
private:
double kineticEnergy(const mat &r, const mat rProtons, const double &alpha, const double &beta, WaveFunction *function);
double potentialEnergy(double R, const mat &r, const mat &rProtons);
int nDimensions;
int nProtons;
int nElectrons;
int nParticles;
double h;
double h2;
int charge;
};
#endif // HAMILTONIAN_H
<file_sep>#include "slaterdeterminant.h"
#include "WaveFunction.h"
#include <armadillo>
using namespace arma;
using namespace std;
slaterDeterminant::slaterDeterminant(int nParticles_, int nDimensions_):
nDimensions(nDimensions_),
nParticles(nParticles_),
slaterMatrixUp(zeros(nParticles/2,nParticles/2)),
slaterMatrixDown(zeros(nParticles/2,nParticles/2)),
invSlaterMatrixUp(zeros(nParticles/2,nParticles/2)),
invSlaterMatrixDown(zeros(nParticles/2,nParticles/2)),
function(new WaveFunction(nParticles,nDimensions))
{
}
//Build the original Slater determinant, the invert. Done only once.
void slaterDeterminant::buildDeterminant(const mat &r, double &alpha_, double &beta_) {
vec rs = zeros<vec>(nParticles,1);
double alpha = alpha_;
//Find |r| for each electron:
double rSingleParticle = 0;
for(int i = 0; i < nParticles; i++) {
rSingleParticle = 0;
for(int g = 0; g < nDimensions; g++) {
rSingleParticle += r(i,g) * r(i,g);
}
rs(i) = sqrt(rSingleParticle);
}
//Make Slater determinants (spin up and spin down)
for(int i=0; i<nParticles/2; i++) { //Rows: Particle (position)
for(int j=0; j<nParticles/2; j++) { //Cols: State
if (j == 0) { //n=1,l=0,ml=0
slaterMatrixUp(i,j) = function->psi1s(rs[i], alpha);
slaterMatrixDown(i,j) = function->psi1s(rs[nParticles/2+i], alpha);
}
if (j == 1) {//n=2,l=0,ml=0
slaterMatrixUp(i,j) = function->psi2s(rs[i], alpha);
slaterMatrixDown(i,j) = function->psi2s(rs[nParticles/2+i], alpha);
}
if (j == 2) { //n=2,l=1,ml=-1
slaterMatrixUp(i,j) = function->psi2p_1(rs[i], i, r, alpha);
slaterMatrixDown(i,j) = function->psi2p_1(rs[nParticles/2+i], nParticles/2+i, r, alpha);
}
if (j == 3) { //n=2,l=1,ml=0
slaterMatrixUp(i,j) = function->psi2p0(rs[i], i, r, alpha);
slaterMatrixDown(i,j) = function->psi2p0(rs[nParticles/2+i], nParticles/2+i, r, alpha);
}
if (j == 4) { //n=2,l=1,ml=1
slaterMatrixUp(i,j) = function->psi2p1(rs[i], i, r, alpha);
slaterMatrixDown(i,j) = function->psi2p1(rs[nParticles/2+i], nParticles/2+i, r, alpha);
}
}
}
invSlaterMatrixUp = inv(slaterMatrixUp);
invSlaterMatrixDown = inv(slaterMatrixDown);
}
//For testing
double slaterDeterminant::getDeterminant() {
return det(slaterMatrixUp)*det(slaterMatrixDown);
}
//For testing
double slaterDeterminant::getInvDeterminant() {
return 1/(det(invSlaterMatrixUp)*det(invSlaterMatrixDown));
}
//Return the ratio of new to old determinant
double slaterDeterminant::getRatioDeterminant(int i, const mat &r, double alpha, double beta) {
double ratio = 0;
double rSingleParticle = 0;
//Get rtot for particle i's new position:
for(int d = 0; d < nDimensions; d++) {
rSingleParticle += r(i,d) * r(i,d);
}
double rtot = sqrt(rSingleParticle);
vec updatedStates = getStates(r, i, rtot, alpha, beta); //Get states with new r for particle i
if(i<nParticles/2) { //Particle spin up
for(int j=0; j<nParticles/2; j++) { //States
ratio += updatedStates(j) * invSlaterMatrixUp(j,i);
}
}
else { //Particle spin down
for(int j=0; j<nParticles/2; j++) { //States
ratio += updatedStates(j) * invSlaterMatrixDown(j,i-nParticles/2);
}
}
return ratio;
}
//Testing, for Beryllium atom
double slaterDeterminant::getRatioDeterminantNum(int i, const mat &rOld, const mat &rNew, double alpha, double beta) {
return beryllium(rNew, alpha) / beryllium(rOld, alpha);
}
//Get all electron states for position r
vec slaterDeterminant::getStates(const mat &r, int i, double rtot, double alpha, double beta) {
vec updatedStates = zeros<vec>(nParticles/2,1);
updatedStates(0) = function->psi1s(rtot, alpha); //n=1,l=0,ml=0
if(nParticles/2>1) updatedStates(1) = function->psi2s(rtot, alpha); //n=2,l=0,ml=0
if(nParticles/2>2) updatedStates(2) = function->psi2p_1(rtot, i, r, alpha); //n=2,l=1,ml=-1
if(nParticles/2>3) updatedStates(3) = function->psi2p0(rtot, i, r, alpha); //n=2,l=1,ml=0
if(nParticles/2>4) updatedStates(4) = function->psi2p1(rtot, i, r, alpha); //n=2,l=1,ml=1
return updatedStates;
}
//Update the determinant with rNew
void slaterDeterminant::updateDeterminant(const mat &rNew, const mat &rOld, int i, double &alpha_, double &beta_, double ratio) {
double rtot = 0;
//Get rtot for particles' position:
for(int d = 0; d < nDimensions; d++) {
rtot += rNew(i,d) * rNew(i,d);
}
rtot = sqrt(rtot);
vec newStates = getStates(rNew, i, rtot, alpha_, beta_); //Get all the states
vec sumSjUp = zeros<vec>(nParticles/2); //Sum over states(l)*d_lj for particles j
vec sumSjDown = zeros<vec>(nParticles/2); //Sum over states(l)*d_lj for particles j
int particle = i;
if(i>=nParticles/2) particle = i-nParticles/2;
for(int j=0; j<nParticles/2; j++) { //Cols
for(int l=0; l<nParticles/2; l++) { //Rows
sumSjUp(j) += newStates(l) * invSlaterMatrixUp(l,j);
sumSjDown(j) += newStates(l) * invSlaterMatrixDown(l,j);
}
}
//Update inverse matrices:
//All columns except column corresponding to particle i:
if(i<nParticles/2) { //If particle i has spin up
for (int j=0; j<nParticles/2; j++) {
for(int k=0; k<nParticles/2; k++) {
if(j != particle) invSlaterMatrixUp(k,j) = invSlaterMatrixUp(k,j) - (sumSjUp(j)/ratio)*invSlaterMatrixUp(k,particle);
}
}
}
else { //If particle i has spin down
for (int j=0; j<nParticles/2; j++) { //Cols, inv matrix
for(int k=0; k<nParticles/2; k++) { //Rows, inv matrix
if(j != particle) invSlaterMatrixDown(k,j) = invSlaterMatrixDown(k,j) - (sumSjDown(j)/ratio)*invSlaterMatrixDown(k,particle);
}
}
}
//Update column corresponding to particle i:
for(int k=0; k<nParticles/2; k++) { //States (rows)
if(i<nParticles/2) { invSlaterMatrixUp(k,particle) = (1/ratio)*invSlaterMatrixUp(k,particle); }
else {invSlaterMatrixDown(k,particle) = (1/ratio)*invSlaterMatrixDown(k,particle); }
}
}
//Get the gradient of the wavwfunction (Slater determinant)
vec slaterDeterminant::gradientWaveFunction(const mat &r, int i, double ratio, double alpha, double beta) {
double rtot = 0;
vec gradient = zeros<vec>(nDimensions,1);
vec invMatrix = zeros<vec>(nParticles/2,1);
//Get the correct column of the determinant
for(int j=0; j<nParticles/2; j++) {
if(i<nParticles/2) { invMatrix(j) = invSlaterMatrixUp(j,i); }
else { invMatrix(j) = invSlaterMatrixDown(j,i-nParticles/2); }
}
for (int d=0; d<nDimensions; d++) { rtot += r(i,d)*r(i,d); }
rtot = sqrt(rtot);
//Get the gradient
gradient = function->dPsi1s(rtot, i, r, alpha)*(1/ratio)*invMatrix(0); //n=1,l=0,ml=0
if(nParticles/2 > 1) gradient += function->dPsi2s(rtot, i, r, alpha)*(1/ratio)*invMatrix(1); //n=2,l=0,ml=0
if(nParticles/2 > 2) gradient += function->dPsi2p_1(rtot, i, r, alpha)*(1/ratio)*invMatrix(2); //n=2,l=1,ml=-1
if(nParticles/2 > 3) gradient += function->dPsi2p0(rtot, i, r, alpha)*(1/ratio)*invMatrix(3); //n=2,l=1,ml=0
if(nParticles/2 > 4) gradient += function->dPsi2p1(rtot, i, r, alpha)*(1/ratio)*invMatrix(4); //n=2,l=1,ml=1
return gradient;
}
//Testing: Get the gradient of the wavwfunction for Be, numerical method
vec slaterDeterminant::gradientWaveFunctionNum(const mat &r, int i, double alpha_, double beta_) {
vec grad = zeros(nDimensions);
mat rPlus = zeros<mat>(nDimensions);
mat rMinus = zeros<mat>(nDimensions);
double wf = beryllium(r,alpha_);
double h = 0.001;
rPlus = rMinus = r;
double waveFunctionMinus = 0;
double waveFunctionPlus = 0;
//First derivative
for(int j = 0; j < nDimensions; j++) {
rPlus(i,j) = r(i,j)+h;
rMinus(i,j) = r(i,j)-h;
waveFunctionMinus = beryllium(rMinus,alpha_);
waveFunctionPlus = beryllium(rPlus,alpha_);
grad(j) = (waveFunctionPlus - waveFunctionMinus)/(2*wf*h);
rPlus(i,j) = r(i,j);
rMinus(i,j) = r(i,j);
}
return grad;
}
//Get the second derivative of the wavefunction (Slater determinant) for kinetic energy in Hamiltonian
double slaterDeterminant::laPlaceWaveFunction(const mat &r, double alpha, double beta) {
double rtot = 0;
double laplace = 0;
vec invMatrix = zeros<vec>(nParticles/2,1);
for(int i = 0; i < nParticles; i++) { //Loop over all particles
rtot = 0;
for (int d=0; d<nDimensions; d++) { rtot += r(i,d)*r(i,d); } //Get r for particle
rtot = sqrt(rtot);
//Get the correct column of determinant
invMatrix.fill(0);
for(int j=0; j<nParticles/2; j++) {
if(i<nParticles/2) { invMatrix(j) = invSlaterMatrixUp(j,i); }
else { invMatrix(j) = invSlaterMatrixDown(j,i-nParticles/2); }
}
//Get laplacian for each state:
laplace += function->d2Psi1s(rtot, alpha)*invMatrix(0); //n=1,l=0,ml=0
if(nParticles/2 > 1) laplace += function->d2Psi2s(rtot, alpha)*invMatrix(1);//n=2,l=0,ml=0
if(nParticles/2 > 2) laplace += function->d2Psi2p_1(rtot, i, r, alpha)*invMatrix(2);//n=2,l=1,ml=-1
if(nParticles/2 > 3) laplace += function->d2Psi2p0(rtot, i, r, alpha)*invMatrix(3);//n=2,l=1,ml=0
if(nParticles/2 > 4) laplace += function->d2Psi2p1(rtot, i, r, alpha)*invMatrix(4);//n=2,l=1,ml=1
}
return laplace;
}
//Testing: Get the second derivative of the wavefunction Be for kinetic energy in Hamiltonian
double slaterDeterminant::laPlaceWaveFunctionNum(const mat &r, double alpha, double beta) {
double h2 = 1000000;
double h = 0.001;
mat rPlus = zeros<mat>(nParticles, nDimensions);
mat rMinus = zeros<mat>(nParticles, nDimensions);
rPlus = rMinus = r;
double waveFunctionMinus = 0;
double waveFunctionPlus = 0;
double waveFunctionCurrent = beryllium(r, alpha); //Find wavefunction for r
//Second derivative (del^2):
double kineticEnergy = 0;
for(int i = 0; i < nParticles; i++) {
for(int j = 0; j < nDimensions; j++) {
rPlus(i,j) += h;
rMinus(i,j) -= h;
waveFunctionMinus = beryllium(rMinus, alpha);
waveFunctionPlus = beryllium(rPlus, alpha);
kineticEnergy -= (waveFunctionMinus + waveFunctionPlus - 2 * waveFunctionCurrent);
rPlus(i,j) = r(i,j);
rMinus(i,j) = r(i,j);
}
}
kineticEnergy = 0.5 * h2 * kineticEnergy / waveFunctionCurrent;
//cout <<"Numerical: "<<kineticEnergy<<endl;
return kineticEnergy;
}
//Testing: Slater determinant for Be
double slaterDeterminant::beryllium(const mat &r, double &alpha_) {
double rs[nParticles];
double sum = 0;
//Find |r| for each electron:
double rSingleParticle = 0;
for(int i = 0; i < nParticles; i++) {
rSingleParticle = 0;
for(int j = 0; j < nDimensions; j++) {
rSingleParticle += r(i,j) * r(i,j);
}
rs[i] = sqrt(rSingleParticle);
sum += rs[i];
}
//Slater determinant, Be
double waveFunction = (function->psi1s(rs[0], alpha_)*function->psi2s(rs[1], alpha_) - function->psi1s(rs[1], alpha_)*function->psi2s(rs[0], alpha_))*
(function->psi1s(rs[2], alpha_)*function->psi2s(rs[3], alpha_) - function->psi1s(rs[3], alpha_)*function->psi2s(rs[2], alpha_));
return waveFunction;
}
<file_sep>#ifndef WAVEFUNCTION_H
#define WAVEFUNCTION_H
#include <armadillo>
using namespace arma;
using namespace std;
class WaveFunction {
public:
WaveFunction(int &nParticles_, int &nDimensions_);
double waveFunction(const mat &r, double alpha, double beta);
private:
double jastrowFactor(const mat &r);
int nDimensions;
int nParticles;
double alpha;
double beta;
slaterDeterminant *slater;
};
#endif // WAVEFUNCTION_H
<file_sep>#include "correlation.h"
#include <armadillo>
using namespace arma;
using namespace std;
correlation::correlation(int nParticles_, int nDimensions_):
nDimensions(nDimensions_),
nParticles(nParticles_)
{
}
//Get the correlation factor (Jastrow factor)
double correlation::jastrow(const mat &r, double beta) {
double exponent=0;
double a = 0.25;
double rij = 0;
for(int j=1;j<nParticles;j++) {
for(int i=0;i<j;i++) {
int test1 = i-nParticles/2;
int test2 = j-nParticles/2;
if(test1*test2>0) a=0.25; //If the electrons have parallel spins
else a=0.5;
rij = 0;
for(int d=0;d<nDimensions;d++) rij += (r(i,d)-r(j,d))*(r(i,d)-r(j,d));
rij = sqrt(rij);
exponent += (a*rij)/(1.0+beta*rij);
}
}
return exp(exponent);
}
//Numerical Jastrow
double correlation::jastrowNum(const mat &r, double beta) {
double r12 = 0;
double wf = 0;
for(int i=0; i<nParticles; i++) {
for(int p=0; p<i; p++) {
r12 = 0;
for(int d=0;d<nDimensions;d++) r12 += pow(r(i,d)-r(p,d),2);
r12 = sqrt(r12);
wf += r12/(2*(1+beta*r12));
}
}
return exp(wf);
}
//Get the ration of new to old Jastrow factor (rNew and rOld)
double correlation::getRatioJastrow(int i, const mat &rOld, const mat &rNew, double beta) {
double exponent=0;
double a=0;
double rijOld = 0;
double rijNew = 0;
int test1 = i-nParticles/2;
for(int j=0;j<nParticles;j++) {
if(j != i) {
int test2 = j-nParticles/2;
if(test1*test2>0) a=0.25; //If the electrons have parallel spins
else a=0.5;
rijNew = 0; rijOld = 0;
for(int d=0;d<nDimensions;d++) {
rijNew += pow((rNew(i,d)-rNew(j,d)),2);
rijOld += pow((rOld(i,d)-rOld(j,d)),2);
}
rijNew = sqrt(rijNew);
rijOld = sqrt(rijOld);
exponent += (a*rijNew)/(1+beta*rijNew) - (a*rijOld)/(1+beta*rijOld);
}
}
return exp(exponent);
}
//Get the gradient of the correlation factor
vec correlation::gradientWaveFunction(const mat &r, int i, double beta) {
vec grad = zeros<vec>(nDimensions);
double a = 0.25;
int test1 = i-nParticles/2;
double rij = 0;
for(int j=0; j<nParticles; j++) {
if(j!=i) {
int test2 = j-nParticles/2;
if(test1*test2>0) a=0.25; //If the electrons have parallel spins
else a=0.5;
rij = 0;
for (int d=0; d<nDimensions; d++) { rij += pow((r(i,d)-r(j,d)),2); } //Get r for particle
rij = sqrt(rij);
grad(0) += ((r(i,0)-r(j,0))/rij)*(a/pow((1+beta*rij),2));
grad(1) += ((r(i,1)-r(j,1))/rij)*(a/pow((1+beta*rij),2));
grad(2) += ((r(i,2)-r(j,2))/rij)*(a/pow((1+beta*rij),2));
}
}
return grad;
}
//Get the gradient of the correlation factor, numerical method
vec correlation::gradientWaveFunctionNum(const mat &r, int i, double beta) {
vec grad = zeros(nDimensions);
mat rPlus = zeros<mat>(nDimensions);
mat rMinus = zeros<mat>(nDimensions);
double h = 0.001;
double wf = jastrowNum(r,beta);
rPlus = rMinus = r;
double waveFunctionMinus = 0;
double waveFunctionPlus = 0;
//First derivative
for(int p=0; p<nParticles; p++) {
if(p != i) {
for(int j = 0; j < nDimensions; j++) {
rPlus(i,j) = r(i,j)+h;
rMinus(i,j) = r(i,j)-h;
waveFunctionMinus = jastrowNum(rMinus,beta);
waveFunctionPlus = jastrowNum(rPlus,beta);
grad(j) = (waveFunctionPlus - waveFunctionMinus)/(2*wf*h);
rPlus(i,j) = r(i,j);
rMinus(i,j) = r(i,j);
}
}
}
//cout <<"Numerical: "<< grad << endl;
return grad;
}
//Get the second derivative of the correlation factor
double correlation::laPlaceWaveFunction(const mat &r, double beta) {
double rik = 0;
double rjk = 0;
double laplace = 0;
double a1 = 0.25;
double a2 = 0.25;
int test1;
int test2;
int test3;
vec rik_vec = zeros<vec>(nDimensions,1);
vec rjk_vec = zeros<vec>(nDimensions,1);
for(int k=0; k<nParticles; k++) {
test1 = k-nParticles/2;
for(int i = 0; i < nParticles; i++) {
test2 = i-nParticles/2;
if(test1*test2>0) a1=0.25; //If the electrons have parallel spins
else a1=0.5;
for(int j=0; j<nParticles; j++) {
if(i != k && j != k) {
test3 = j-nParticles/2;
if(test1*test3>0) a2=0.25; //If the electrons have parallel spins
else a2=0.5;
rik = 0; rjk = 0;
for(int d=0;d<nDimensions;d++) {
rik += pow((r(i,d)-r(k,d)),2);
rjk += pow((r(j,d)-r(k,d)),2);
rik_vec(d) = r(k,d) - r(i,d);
rjk_vec(d) = r(k,d) - r(j,d);
}
rik = sqrt(rik);
rjk = sqrt(rjk);
laplace += (dot(rik_vec,rjk_vec)/(rik*rjk))*(a1/pow((1+beta*rik),2)*(a2/pow((1+beta*rjk),2)));
}
}
}
}
for(int k=0; k<nParticles; k++) {
test1 = k-nParticles/2;
for(int j=0; j<nParticles; j++) {
if(j != k) {
int test3 = j-nParticles/2;
if(test1*test3>0) a2=0.25; //If the electrons have parallel spins
else a2=0.5;
rjk = 0;
for(int d=0;d<nDimensions;d++) {
rjk += pow((r(j,d)-r(k,d)),2);
rjk_vec(d) = r(k,d) - r(j,d);
}
rjk = sqrt(rjk);
laplace += (2*a2)/(rjk*pow((1+beta*rjk),2)) - (2*a2*beta)/pow((1+beta*rjk),3);
}
}
}
return laplace;
}
//Get the second derivative of the correlation factor, numerical method
double correlation::laPlaceWaveFunctionNum(const mat &r, double beta) {
double h2 = 1000000;
double h = 0.001;
mat rPlus = zeros<mat>(nParticles, nDimensions);
mat rMinus = zeros<mat>(nParticles, nDimensions);
rPlus = rMinus = r;
double waveFunctionMinus = 0;
double waveFunctionPlus = 0;
double waveFunctionCurrent = jastrowNum(r,beta);
//Second derivative (del^2):
double kineticEnergy = 0;
for(int i = 0; i < nParticles; i++) {
for(int j = 0; j < nDimensions; j++) {
rPlus(i,j) += h;
rMinus(i,j) -= h;
waveFunctionMinus = jastrowNum(rMinus,beta);
waveFunctionPlus = jastrowNum(rPlus,beta);
kineticEnergy -= (waveFunctionMinus + waveFunctionPlus - 2 * waveFunctionCurrent);
rPlus(i,j) = r(i,j);
rMinus(i,j) = r(i,j);
}
}
kineticEnergy = h2 * kineticEnergy / waveFunctionCurrent;
//cout <<"Numerical: "<<kineticEnergy<<endl;
return kineticEnergy;
}
<file_sep>#ifndef HAMILTONIAN_H
#define HAMILTONIAN_H
#include "slaterdeterminant.h"
#include "correlation.h"
class Hamiltonian
{
public:
Hamiltonian(int nDimensions_, double h_, double h2_, int nProtons_, int nElectrons_, double R_, const mat &rProtons_);
double localEnergy(const mat &r, const double &alpha, const double &beta, slaterDeterminant *slater, correlation *corr);
vec dPsi(const mat &r, double alpha, double beta, slaterDeterminant *slater, correlation *corr);
double analyticEnergyHe(const mat &r, const double &alpha, const double &beta);
double analyticdEnergyHe(const mat &r, const double &alpha, const double &beta);
private:
double kineticEnergy(const mat &r, const double &alpha, const double &beta, slaterDeterminant *slater, correlation *corr);
double potentialEnergy(const mat &r);
int nDimensions;
int nProtons;
int nElectrons;
int nParticles;
double h;
double h2;
double R;
mat rProtons;
};
#endif // HAMILTONIAN_H
<file_sep>#include "WaveFunction.h"
#include "lib.h"
#include <armadillo>
using namespace arma;
using namespace std;
WaveFunction::WaveFunction(int &nDimensions_, int &nProtons_, int &nElectrons_) :
nDimensions(nDimensions_),
nProtons(nProtons_),
nElectrons(nElectrons_),
nParticles(nProtons*nElectrons)
{
}
double WaveFunction::waveFunction(const mat &r, const mat &rProtons, double alpha, double beta) {
double rp;
double rp1 = 0;
double rp2 = 0;
double rp3 = 0;
double rp4 = 0;
double expP = 0;
double wave = 1;
for(int d=0; d<nDimensions; d++) {
rp1 += pow(r(0,d) - rProtons(0,d),2);
rp2 += pow(r(0,d) - rProtons(1,d),2);
rp3 += pow(r(1,d) - rProtons(0,d),2);
rp4 += pow(r(1,d) - rProtons(1,d),2);
}
wave = (exp(-alpha*sqrt(rp1)) - exp(-alpha*sqrt(rp2))) * (exp(-alpha*sqrt(rp3)) - exp(-alpha*sqrt(rp4)));
//wave = 1;
// for(int e=0; e<nParticles; e++) {
// expP = 0;
// rp = 0;
// for(int p=0; p<nProtons; p++) {
// rp = 0;
// for(int d=0; d<nDimensions; d++) rp += (r(e,d) - rProtons(p,d))*(r(e,d) - rProtons(p,d));
// expP += exp(-alpha*sqrt(rp));
// }
// wave = wave * expP;
// }
//cout <<"wave: "<<wave<<endl;
double jastrow = jastrowFactor(r,beta);
//cout<<"jastrow: "<<jastrow<<endl;
return wave*jastrow;
}
double WaveFunction::jastrowFactor(const mat &r, double beta) {
rowvec r12;
double r12norm = 0;
double jastrow = 0;
for(int k=1;k<nParticles;k++) {
for(int l=0;l<k;l++) {
r12 = r.row(k) - r.row(l);
r12norm = 0;
for(int d = 0; d < nDimensions; d++) r12norm += r12(d)*r12(d);
jastrow += sqrt(r12norm) / (2 * (1 + beta * sqrt(r12norm)));
}
}
return exp(jastrow);
}
<file_sep>#ifndef SLATERDETERMINANT_H
#define SLATERDETERMINANT_H
#include <armadillo>
#include "WaveFunction.h"
using namespace arma;
using namespace std;
class slaterDeterminant
{
public:
slaterDeterminant(int nDimensions_, int nProtons_, int nElectrons_);
void buildDeterminant(const mat &r, double &alpha_);
double getRatioDeterminant(int i, const mat &r, double alpha);
vec gradientWaveFunction(const mat &r, int i, double ratio, double alpha);
double laPlaceWaveFunction(const mat &r, int i, double alpha);
double laPlaceWaveFunctionNum(const mat &r, double alpha);
double getDeterminant();
double getInvDeterminant();
vec getStates(double rtot, double alpha);
void updateDeterminant(const mat &rNew, const mat &rOld, int i, double &alpha_, double ratio);
double beryllium(const mat &r, double &alpha);
vec gradientWaveFunctionNum(const mat &r, int i, double alpha_);
double getRatioDeterminantNum(int i, const mat &rOld, const mat &rNew, double alpha);
double dWaveFunction_dalpha(const mat &r, double alpha);
private:
WaveFunction *function;
int nDimensions;
int nElectrons;
int nProtons;
int nParticles;
mat slaterMatrixUp1;
mat slaterMatrixDown1;
mat slaterMatrixUp2;
mat slaterMatrixDown2;
mat invSlaterMatrixUp1;
mat invSlaterMatrixDown1;
mat invSlaterMatrixUp2;
mat invSlaterMatrixDown2;
};
#endif // SLATERDETERMINANT_H
<file_sep>#ifndef LIB_H
#define LIB_H
double ran2(long *);
#endif // LIB_H
|
87b376a2fb1cbe80a0e5357695155efbc5b15c09
|
[
"C",
"C++"
] | 27
|
C++
|
alborg/helium
|
0f054f1f05500d7b51cb1a3e5b70e3bfebb0cfc1
|
e050b454709482ed76a2478b6ced181f0a5c387b
|
refs/heads/master
|
<file_sep>kubeabc
=======
A toolkit for k8s developers
## Usage
### To begin with
Some convenient commands are in `bin` directory. So you should add that directory to `$PATH` at first.
```bash
export PATH="$PWD/bin:$PATH"
```
### For CLI
- kube
- kubectx (extended of [ahmetb/kubectx](https://github.com/ahmetb/kubectx))
- kubens (ditto)
### For tmux
- kube-context
- gcp-context
```config
set-option -g status-left 'tmux:[#P] #[fg=colour33](K) #(kube-context)#[default] #[fg=colour1](G) #(gcp-context)#[default]'
```
## License
MIT
## Auther
b4b4r07
<file_sep>kubectx
=======
```console
$ curl https://raw.githubusercontent.com/b4b4r07/kubeabc/master/install.sh | bash -s kubectx
```
<file_sep>kube
====
kubectl wrapper
## Usage
```
$ kube get pods
```
## Installation
```console
$ go get github.com/b4b4r07/kubeabc/cli/kube
```
## Features
- Fuzzy match (correct the typo and execute it)
- Can find and execute user-defined commands
- the executable command beginning with `kube`, `kube-` and `kubectl-`
- Can confirm with Yes/No before executing `apply`, `delete` and so on
## License
MIT
## Auther
b4b4r07
<file_sep>#!/bin/bash
kube--ctx $(kube--ctx | fzf --height 30 --reverse --ansi) >/dev/null
<file_sep>#!/bin/bash
if ! type jq &>/dev/null; then
echo "jq: not found" >&2
exit 1
fi
if ! type gcloud &>/dev/null; then
echo "gloud: not found" >&2
exit 1
fi
gcloud config configurations list --format='json' \
| jq -r '.[] | select(.is_active==true) | .properties.core.project'
<file_sep>#!/bin/bash
set -ex
install_dir=~/bin
install_kubectx() {
cmd=kubectx
download_file=/tmp/$cmd
{
echo "#!/bin/bash"
curl "https://raw.githubusercontent.com/ahmetb/kubectx/master/utils.bash"
curl "https://raw.githubusercontent.com/ahmetb/kubectx/master/$cmd" | sed -e 's/source/: source/g'
} >$download_file 2>/dev/null
chmod 755 $download_file
install -m 755 $download_file $install_dir/kube--ctx
install -m 755 $cmd/$cmd $install_dir
}
install_kubens() {
cmd=kubens
download_file=/tmp/$cmd
{
echo "#!/bin/bash"
curl "https://raw.githubusercontent.com/ahmetb/kubectx/master/utils.bash"
curl "https://raw.githubusercontent.com/ahmetb/kubectx/master/$cmd" | sed -e 's/source/: source/g'
} >$download_file 2>/dev/null
chmod 755 $download_file
install -m 755 $download_file $install_dir/kube--ns
install -m 755 $cmd/$cmd $install_dir
}
case $1 in
"kubectx")
install_kubectx
;;
"kubens")
install_kubens
;;
"")
install_kubectx
install_kubens
;;
*)
echo "nothing"
;;
esac
<file_sep>package main
import (
"bufio"
"fmt"
"log"
"math"
"os"
"os/exec"
"path/filepath"
"k8s.io/client-go/tools/clientcmd"
"github.com/agext/levenshtein"
"github.com/b4b4r07/kubeabc/cli/kube/command"
)
var subcommands = []string{
"create",
"expose",
"run",
"run-container",
"set",
"get",
"explain",
"edit",
"delete",
"rollout",
"rolling-update",
"rollingupdate",
"scale",
"resize",
"autoscale",
"certificate",
"cluster-info",
"clusterinfo",
"top",
"cordon",
"uncordon",
"drain",
"taint",
"describe",
"logs",
"attach",
"exec",
"port-forward",
"proxy",
"cp",
"auth",
"apply",
"patch",
"replace",
"update",
"convert",
"label",
"annotate",
"completion",
"api-versions",
"config",
"help",
"plugin",
"version",
}
var resources = []string{
"all",
"certificatesigningrequests", "certificatesigningrequest", "csr",
"clusterrolebindings", "clusterrolebinding",
"clusterroles", "clusterroles",
"clusters", "cluster",
"componentstatuses", "componentstatus", "cs",
"configmaps", "configmap", "cm",
"controllerrevisions", "controllerrevision",
"cronjobs", "cronjob",
"daemonsets", "daemonset", "ds",
"deployments", "deployment", "deploy",
"endpoints", "endpoint", "ep",
"events", "event", "ev",
"horizontalpodautoscalers", "horizontalpodautoscalers", "hpa",
"ingresses", "ingress", "ing",
"jobs", "job",
"limitranges", "limitrange", "limits",
"namespaces", "namespace", "ns",
"networkpolicies", "networkpolicy", "netpol",
"nodes", "node", "no",
"persistentvolumeclaims", "persistentvolumeclaim", "pvc",
"persistentvolumes", "persistentvolume", "pv",
"poddisruptionbudgets", "poddisruptionbudget", "pdb",
"podpreset",
"pods", "pod", "po",
"podsecuritypolicies", "podsecuritypolicy", "psp",
"podtemplates", "podtemplate",
"replicasets", "replicaset", "rs",
"replicationcontrollers", "replicationcontroller", "rc",
"resourcequotas", "resourcequotas", "quota",
"rolebindings", "rolebinding",
"roles", "role",
"secrets", "secret",
"serviceaccounts", "serviceaccount", "sa",
"services", "service", "svc",
"statefulsets", "statefulset",
"storageclasses", "storageclass",
"thirdpartyresources", "thirdpartyresource",
}
func main() {
os.Exit(_main(os.Args[1:]))
}
func _main(args []string) int {
if len(args) == 0 {
return run("kubectl", []string{"help"})
}
if len(args) > 1 {
results := similarResources(args[1])
if !contains(results, args[1]) {
switch len(results) {
case 0:
// through
case 1:
fmt.Fprintf(os.Stdout,
"You called a k8s resource named '%s', which does not exist.\nContinuing under the assumption that you meant '%s'\n",
args[1], results[0])
args[1] = results[0]
default:
fmt.Fprintf(os.Stderr,
"%s: no such resource\nThe most similar resources are %q\n",
args[0], results)
}
}
}
if args[0] == "kubectl" {
return run("kubectl", args[1:])
}
if contains(subcommands, args[0]) {
return run("kubectl", args)
}
cmds := searchCommands(args[0])
switch len(cmds) {
case 0:
// through
case 1:
return runWithTTY(cmds[0], args[1:])
default:
fmt.Fprintf(os.Stderr,
"Some commands are found: %q\n",
cmds)
return 1
}
subs := similarCommands(args[0])
switch len(subs) {
case 0:
// through
case 1:
fmt.Fprintf(os.Stdout,
"You called a kubectl command named '%s', which does not exist.\nContinuing under the assumption that you meant '%s'\n",
args[0], subs[0])
args[0] = subs[0]
return run("kubectl", args)
default:
fmt.Fprintf(os.Stderr,
"%s: no such command\nThe most similar commands are %q\n",
args[0], subs)
return 1
}
fmt.Fprintf(os.Stderr, "%s: no such command in kubectl\n", args[0])
return 1
}
func contains(s []string, e string) bool {
for _, v := range s {
if e == v {
return true
}
}
return false
}
func run(arg string, args []string) int {
switch args[0] {
case "apply", "delete":
prompt()
default:
}
c := command.New(command.Join(arg, args))
if err := c.Run(); err != nil {
// Unexpected error
log.Fatal(err)
}
res := c.Result()
if res.Failed {
fmt.Fprintf(os.Stderr, "Error: %v\n", res.StderrString())
return res.ExitCode
}
out := res.StdoutString()
if len(out) > 0 {
fmt.Fprintln(os.Stdout, out)
}
return res.ExitCode
}
func runWithTTY(arg string, args []string) int {
c := command.New(command.Join(arg, args))
if err := c.RunWithTTY(); err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err.Error())
return 1
}
return 0
}
func searchCommands(arg string) (results []string) {
prefixes := []string{
"kube", "kube-", "kubectl-",
}
for _, prefix := range prefixes {
cmd := prefix + arg
if _, err := exec.LookPath(cmd); err != nil {
continue
}
results = append(results, cmd)
}
return
}
func similarCommands(arg string) (results []string) {
var max float64
for _, cmd := range subcommands {
score := round(levenshtein.Similarity(cmd, arg, nil) * 100)
if score >= max {
max = score
if score > 65 {
results = append(results, cmd)
}
}
}
return
}
func similarResources(arg string) (results []string) {
var max float64
for _, resource := range resources {
score := round(levenshtein.Similarity(resource, arg, nil) * 100)
if score >= max {
max = score
if score > 65 {
results = append(results, resource)
}
}
}
return
}
func round(f float64) float64 {
return math.Floor(f + .5)
}
func prompt() {
file := filepath.Join(os.Getenv("HOME"), ".kube", "config")
config, err := clientcmd.LoadFromFile(file)
if err != nil {
panic(err)
}
fmt.Printf("Press Return key to continue\n-> current context %q", config.CurrentContext)
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
break
}
if err := scanner.Err(); err != nil {
panic(err)
}
}
<file_sep>#!/bin/bash
pod="$1"
if [[ -z $pod ]]; then
echo "pod name is required" >&2
exit 1
fi
res="$(kubectl exec -it "$pod" bash 2>&1)"
if [[ $? -eq 0 ]]; then
echo "$res"
exit 0
fi
# in case of no bash command
echo "sh"
kubectl exec -it "$pod" sh
exit $?
<file_sep>#!/bin/bash
if ! type kubectl &>/dev/null; then
echo "kubectl command not found" >&2
exit 1
fi
if ! context="$(kubectl config current-context 2>/dev/null)"; then
echo "NaN"
exit 0
fi
namespace="$(kubectl config view -o "jsonpath={.contexts[?(@.name==\"$context\")].context.namespace}")"
if [[ -z "$namespace" ]]; then
namespace="default"
fi
regions=(
"us-west1-a" "us-west1-b"
"us-central1-a" "us-central1-b" "us-central1-c" "us-central1-f"
"us-east1-b" "us-east1-c" "us-east1-d"
"europe-west1-b" "europe-west1-c" "europe-west1-d"
"asia-southeast1-a" "asia-southeast1-b"
"asia-east1-a" "asia-east1-b" "asia-east1-c"
"asia-northeast1-a" "asia-northeast1-b" "asia-northeast1-c"
)
for region in "${regions[@]}"
do
context=${context%_${region}*}
done
echo "${context}/${namespace}"
<file_sep>#!/bin/bash
kube--ns $(kube--ns | fzf --height 30 --reverse --ansi) >/dev/null
<file_sep># List and select pod name with fzf (https://github.com/junegunn/fzf)
# e.g.
# kubectl exec -it P sh
# kubectl delete pod P
alias fzfkubernetesalias="fzf --height 25 --header-lines=1 --reverse --multi --cycle"
alias -g P='$(kubectl get pods | fzfkubernetesalias | awk "{print \$1}")'
# Like P, global aliases about kubernetes resources
alias -g PO='$(kubectl get pods | fzfkubernetesalias | awk "{print \$1}")'
alias -g NS='$(kubectl get ns | fzfkubernetesalias | awk "{print \$1}")'
alias -g RS='$(kubectl get rs | fzfkubernetesalias | awk "{print \$1}")'
alias -g SVC='$(kubectl get svc | fzfkubernetesalias | awk "{print \$1}")'
alias -g ING='$(kubectl get ing | fzfkubernetesalias | awk "{print \$1}")'
# References
# - https://github.com/c-bata/kube-prompt
# - https://github.com/cloudnativelabs/kube-shell
<file_sep>package command
import (
"bytes"
"errors"
"os"
"os/exec"
"os/user"
"runtime"
"strconv"
"strings"
"syscall"
"time"
"github.com/gobs/args"
shellquote "github.com/kballard/go-shellquote"
)
var errorTimeout = errors.New("error: execution timeout")
type Result struct {
RealTime time.Duration
UserTime time.Duration
SysTime time.Duration
Stdout *bytes.Buffer
Stderr *bytes.Buffer
Pid int
ExitCode int
Failed bool
User string
Rusage *syscall.Rusage
}
type Command struct {
Stdout *bytes.Buffer
Stderr *bytes.Buffer
Pid int
result *Result
cmd *exec.Cmd
command string
startTime time.Time
endTime time.Time
failed bool
exitCode int
params struct {
user string
timeout time.Duration
workingDir string
environment []string
}
}
func Escape(command string, args ...string) string {
for _, arg := range args {
command = shellquote.Join(command, arg)
}
return command
}
// New returns the Command struct to execute the named program with
// the given arguments.
func New(command string) *Command {
return &Command{
Stdout: bytes.NewBuffer(nil),
Stderr: bytes.NewBuffer(nil),
command: command,
}
}
func (c *Command) SetTimeout(timeout time.Duration) {
c.params.timeout = timeout
}
func (c *Command) SetUser(username string) {
c.params.user = username
}
func (c *Command) SetWorkingDir(workingDir string) {
c.params.workingDir = workingDir
}
func (c *Command) SetEnvironment(environment []string) {
c.params.environment = environment
}
func (c *Command) Start() error {
c.buildExecCmd()
c.setOutput()
if err := c.setCredentials(); err != nil {
return err
}
if err := c.cmd.Start(); err != nil {
return err
}
c.startTime = time.Now()
c.Pid = c.cmd.Process.Pid
return nil
}
func (c *Command) buildExecCmd() {
arguments := args.GetArgs(c.command)
aname, err := exec.LookPath(arguments[0])
if err != nil {
aname = arguments[0]
}
c.cmd = &exec.Cmd{
Path: aname,
Args: arguments,
}
if c.params.workingDir != "" {
c.cmd.Dir = c.params.workingDir
}
if c.params.environment != nil {
c.cmd.Env = c.params.environment
}
}
func (c *Command) setOutput() {
c.cmd.Stdout = c.Stdout
c.cmd.Stderr = c.Stderr
}
func (c *Command) setCredentials() error {
if c.params.user == "" {
return nil
}
uid, gid, err := c.getUIDAndGIDInfo(c.params.user)
if err != nil {
return err
}
c.cmd.SysProcAttr = &syscall.SysProcAttr{}
c.cmd.SysProcAttr.Credential = &syscall.Credential{Uid: uid, Gid: gid}
return nil
}
func (c *Command) getUIDAndGIDInfo(username string) (uint32, uint32, error) {
user, err := user.Lookup(username)
if err != nil {
return 0, 0, err
}
uid, _ := strconv.Atoi(user.Uid)
gid, _ := strconv.Atoi(user.Gid)
return uint32(uid), uint32(gid), nil
}
func (c *Command) Wait() error {
if err := c.doWait(); err != nil {
c.failed = true
if exiterr, ok := err.(*exec.ExitError); ok {
if status, ok := exiterr.Sys().(syscall.WaitStatus); ok {
c.exitCode = status.ExitStatus()
}
} else {
if err != errorTimeout {
return err
}
c.Kill()
}
}
c.endTime = time.Now()
c.buildResponse()
return nil
}
func (c *Command) Kill() error {
c.failed = true
c.exitCode = -1
return c.cmd.Process.Kill()
}
func (c *Command) doWait() error {
if c.params.timeout != 0 {
return c.doWaitWithTimeout()
}
return c.doWaitWithoutTimeout()
}
func (c *Command) doWaitWithoutTimeout() error {
return c.cmd.Wait()
}
func (c *Command) doWaitWithTimeout() error {
go func() {
time.Sleep(c.params.timeout)
c.Kill()
}()
return c.cmd.Wait()
}
func (c *Command) buildResponse() {
result := &Result{
RealTime: c.endTime.Sub(c.startTime),
UserTime: c.cmd.ProcessState.UserTime(),
SysTime: c.cmd.ProcessState.UserTime(),
Rusage: c.cmd.ProcessState.SysUsage().(*syscall.Rusage),
Stdout: c.Stdout,
Stderr: c.Stderr,
Pid: c.cmd.Process.Pid,
Failed: c.failed,
ExitCode: c.exitCode,
User: c.params.user,
}
c.result = result
}
func (c *Command) Result() *Result {
return c.result
}
func (c *Command) Run() error {
if err := c.Start(); err != nil {
return err
}
return c.Wait()
}
func (r *Result) StdoutString() string {
return strings.TrimSuffix(string(r.Stdout.Bytes()), "\n")
}
func (r *Result) StderrString() string {
return strings.TrimSuffix(string(r.Stderr.Bytes()), "\n")
}
func (c *Command) RunWithTTY() error {
var cmd *exec.Cmd
if runtime.GOOS == "windows" {
cmd = exec.Command("cmd", "/c", c.command)
} else {
cmd = exec.Command("sh", "-c", c.command)
}
cmd.Stderr = os.Stderr
cmd.Stdout = os.Stdout
cmd.Stdin = os.Stdin
return cmd.Run()
}
func Join(c string, args []string) string {
for _, arg := range args {
c = c + " " + arg
}
return c
}
|
bc9e7fe7c05c01f7fb86e29095f201a8188ddfe0
|
[
"Markdown",
"Go",
"Shell"
] | 12
|
Markdown
|
b4b4r07/kubeabc
|
0c1b5c56d6b5fdc3db2ce6a6ea360b4437c1ca1a
|
a06709629df6ee2c8e9a203d15633403e32c15b5
|
refs/heads/master
|
<repo_name>panagiotis3600/WeatherStationRpi<file_sep>/animationtest.py
import time
import datetime as dt
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import dht11
import RPi.GPIO as GPIO
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
# Create figur for plotting
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
xs = []
ys = []
#zs = []
#read data using pin 14
instance = dht11.DHT11(pin=17)
result = instance.read()
# This function is called periodically from FuncAnimation
def animate(zs, xs, ys):
result = instance.read()
if result.is_valid():
temp_c = result.temperature
humid = result.humidity
# Add x and y to lists
xs.append(dt.datetime.now().strftime('%H:%M:%S'))
ys.append(temp_c)
#zs.append(humid)
# Draw x and y lists
ax.clear()
ax.plot(xs, ys)
# Format plot
plt.xticks(rotation=40, ha='right')
plt.subplots_adjust(bottom=0.30)
plt.title('DHT11 Temperature over Time')
plt.ylabel('Temperature (deg C)')
if xs == 5:
xs.clear
#Set up plot to call animate() function periodically
ani = animation.FuncAnimation(fig, animate, fargs=(xs, ys), interval=500)
plt.show()
|
feb5d0ec7252328d2a412e291d0de5e0d0acdcef
|
[
"Python"
] | 1
|
Python
|
panagiotis3600/WeatherStationRpi
|
b9f942dfa7d1ef4fe7c98d8283270091554317d1
|
32bd3cd69278a63fdfd16cc5e4388160edcdc955
|
refs/heads/master
|
<file_sep>from flask import Flask,make_response, jsonify,request
from flask_cors import CORS
from result_lookup import Results
from send_sms import SendSms
import os
app = Flask(__name__)
CORS(app,expose_headers=["Content-Disposition"])
@app.route('/')
def root():
CallSid=request.args.get('CallSid')
CallFrom=request.args.get('CallFrom')
CallTo=request.args.get('CallTo')
CallType=request.args.get('CallType')
From=request.args.get('From')
To=request.args.get('To')
result = Results()
marks = result.getResult(CallFrom)
msg = ' CallFrom:'+str(CallFrom)+' Result:'+str(marks)
print(msg)
send_sms = SendSms()
data = send_sms.send_my_sms(msg,CallFrom)
print(msg)
return make_response(data,200)
if __name__ =='__main__':
#application = Application()
#application.run()
port= int(os.getenv('PORT',8080))
app.run(port=port, host="0.0.0.0",debug=True)
<file_sep>#<KEY> API Key
#<KEY> secret key
import requests
import json
class SMSSender():
# get request
def sendPostRequest(self, reqUrl, apiKey, secretKey, useType, phoneNo, senderId, textMessage):
req_params = {
'apikey':apiKey,
'secret':secretKey,
'usetype':useType,
'phone': phoneNo,
'message':textMessage,
'senderid':senderId
}
return requests.post(reqUrl, req_params)
# myDict = {'text':'Hello from sendPostRequest'}
# return myDict
if __name__ =='__main__':
URL = 'https://www.sms4india.com/api/v1/sendCampaign'
smsSender = SMSSender()
# get response
response = smsSender.sendPostRequest(URL, 'Z26N1SVHHEL3CMGLFZTO1LAZQRR9ZVJM', 'W8XGKT0M20A5JTXI', 'stage', '8892472497', 'ABC123', 'Hello World' )
"""
Note:-
you must provide apikey, secretkey, usetype, mobile, senderid and message values and then requst to api
"""
# print response if you want
print(response.text)
<file_sep>PyMySQL==0.9.3
requests==2.22.0
Flask==1.1.1
Flask_Cors==3.0.8
<file_sep>import pymysql
class Results:
db = None
def __init__(self):
try:
self.db = pymysql.connect("remotemysql.com", "GSaXLUNgo4", "GSaXLUNgo4", "D4eS0fGmMk", 3306)
print("db connected")
except:
print("Failed in DB connection")
self.db.close()
def getResult(self,phone_num):
try:
cursor = self.db.cursor()
query = "select * from student_result where contactno = \'" + phone_num + "\'"
print(query)
cursor.execute(query)
record = cursor.fetchone()
print(record)
cursor.close()
total = record[3]+record[4]+record[5]+record[6]+record[7]
marks = 'Name:'+str(record[0])+' Rollno:'+str(record[1])+' DS:'+str(record[3])+' CS:'+str(record[4])+\
' DBMS:'+str(record[5])+' JAVA:'+str(record[6])+' OS:'+str(record[7])+' Total:'+str(total)
# marks = get result from executing query
if marks is not None:
return marks
else:
return 'not found'
except Exception as ex:
print(ex)
print("Failed to read data from table")
self.db.close()
if __name__ == "__main__":
result = Results()
print(result.getResult('09877177020'))<file_sep>import http.client
import urllib
import urllib.request
import requests
class SendSms:
def send_my_sms(self,msg,number):
if len(number)==11:
number = number[1:]
params = urllib.parse.urlencode({'message': msg, 'msisdn': number})
print(params)
url = 'https://global.datagenit.com/API/sms-api.php?auth=D!~<PASSWORD>&senderid=Infsms&'+params
resp = requests.get(url, verify=False)
print(resp)
return resp.content
if __name__ == '__main__':
send_sms = SendSms()
send_sms.send_my_sms('hello world', '08566975356')
|
ed13a8d88bccdf88a83118e38b2a14da87b50be1
|
[
"Python",
"Text"
] | 5
|
Python
|
cooljaya2016/telecaller
|
46628279c821d0dc6d3e9193f26028b282d29033
|
24bddd0c9130e591ea5e4612b21e04ae3292bc77
|
refs/heads/master
|
<repo_name>aman-tiwari/ciri-term<file_sep>/README.md
Terminal for Wizardhacks.
To start, double click on `start-osx.command` or run in a terminal `./start-osx.command` (or `./node index.js`)
You have to be focused on the **Unity** window to type into the terminal.
The niceness of the colours in the terminal depends on your default terminal theme, try using one of the Solarized Dark themes or somesuch.<file_sep>/index.js
'use strict'
let WebSocketServer = require('ws').Server;
let blessed = require('blessed');
let contrib = require('blessed-contrib');
let ipc = require('node-ipc');
ipc.config.logger = () => {};
ipc.config.id = 'dash';
ipc.config.retry = 500;
ipc.config.sync = true;
ipc.config.silent = true;
let wss = new WebSocketServer({port: 10101});
console.log('waiting for connection...');
let opened = null;
const state = {
spells: [],
flashlight: false,
inventory: {opened: false, items: []},
health: 100,
steps: 50,
battery: 100,
wifi: 100,
discovered_enemies: [],
stats: {
health: {
title: 'health',
x: [],
y: [],
style: {line: 'red', text: 'red', baseline: 'black'}
},
velocity: {
title: 'steps',
x: [],
y: [],
style: {line: 'orange', text: 'orange', baseline: 'black'}
},
wifi: {
title: 'wi-fi',
x: [],
y: [],
style: {line: 'blue', text: 'blue', baseline: 'black'}
},
battery: {
title: 'battery',
x: [],
y: [],
style: {line: 'green', text: 'green', baseline: 'black'}
}
}
};
let chartVals = ['health'];
// how many values to show in the stats charts
const CHART_HISTORY = 10;
// update the chart every
const CHART_UPDATE_EVERY = 500;
const DATA_SENDING_FAIL_PROBABILITY = 0.4;
const SPELL_WAIT = 3 * 1000;
wss.on('connection', (ws) => {
ipc.serve(function() {
ws.onopen = () => { opened = true };
let terminal;
let forward = (msg) => {
ipc.server.on(msg, (data, sock) => {
// if (state.wifi >= 10 * Math.random()) {
ws.send(msg);
ipc.server.emit(sock, 'ack');
// ipc.server.emit(sock, 'wifi');
// } else {
// if (terminal != undefined) {
// ipc.server.emit(sock, 'no wifi', msg);
// if (Math.random() > DATA_SENDING_FAIL_PROBABILITY) {
// setTimeout(() => ws.send(msg), SPELL_WAIT);
// ipc.server.emit(sock, 'ack');
//} else {
// ipc.server.emit(sock, 'sending failed');
// }
// }
//}
});
};
forward('flashlight');
forward('fists');
ipc.server.on('learn', function(data, sock) {
forward(data);
ipc.server.emit(sock, 'ack');
})
ipc.server.on('camera', (kind, socket) => {
if (kind.data == 'front') {
ws.send('photo:frontCamera');
} else {
ws.send('photo:rearCamera');
}
});
ipc.server.on('download', function({kind, data}) {
switch (kind) {
case 'meme':
break;
case 'spell':
// TODO: download spell
break;
}
});
let screen = blessed.screen({
smartCSR: true,
fullUnicode: true,
dockBorders: true,
ignoreDockContrast: true,
title: 'cir interface'
});
/* let line = contrib.line({
width: '100%',
height: '30%',
left: 0,
top: 0,
label: 'Stats',
legend: {width: 12}
}); */
// screen.append(line);
var line = contrib.line({
xLabelPadding: 1,
height: '30%',
xPadding: 2,
showLegend: true,
border: 'line',
wholeNumbersOnly: false, // true=do not show fraction in y axis
label: 'Stats',
screen: screen
});
var bar_h = contrib.bar({
label: 'Health (%)',
width: '10%',
height: '70%',
border: 'line',
left: '70%',
top: '30%',
barWidth: 4,
barSpacing: 6,
xOffset: 0,
maxHeight: 80,
barBgColor: 'red',
screen: screen
});
var bar_w = contrib.bar({
label: 'Health (%)',
width: '10%',
height: '70%',
border: 'line',
left: '80%',
top: '30%',
barWidth: 4,
barSpacing: 6,
xOffset: 0,
maxHeight: 80,
barBgColor: 'blue',
screen: screen
});
var bar_b = contrib.bar({
label: 'Battery (%)',
width: '10%',
height: '70%',
border: 'line',
left: '90%',
top: '30%',
barWidth: 4,
barSpacing: 6,
xOffset: 0,
maxHeight: 80,
barBgColor: 'green',
screen: screen
});
screen.append(line);
screen.append(bar_h);
screen.append(bar_w);
screen.append(bar_b);
// must append before setting data
line.setData([state.stats.health, state.stats.wifi, state.stats.battery]);
bar_h.setData({titles: ['health'], data: [state.health]});
bar_w.setData({titles: ['wifi'], data: [state.wifi]});
bar_b.setData({titles: ['battery'], data: [state.battery]});
/*
for (let i = 0; i < 400; i++) {
let t = new Date().toTimeString().split(' ')[0];
state.stats.health.y.push(state.health);
state.stats.health.x.push(t);
state.stats.wifi.y.push(state.wifi);
state.stats.wifi.x.push(t);
state.stats.battery.y.push(state.battery);
state.stats.battery.x.push(t);
if (state.stats.health.y.length > 400) {
state.stats.health.y.shift();
state.stats.health.x.shift();
state.stats.wifi.y.shift();
state.stats.wifi.x.shift();
state.stats.battery.y.shift();
state.stats.battery.x.shift();
}
line.setData([state.stats.health, state.stats.wifi, state.stats.battery]);
bar_h.setData({titles: ['health'], data: [state.health]});
bar_w.setData({titles: ['wifi'], data: [state.wifi]});
bar_b.setData({titles: ['battery'], data: [state.battery]});
}
*/
function updateChart() {
let t = new Date().toTimeString().split(' ')[0];
state.stats.health.y.push(state.health);
state.stats.health.x.push(t);
state.stats.wifi.y.push(state.wifi);
state.stats.wifi.x.push(t);
state.stats.battery.y.push(state.battery);
state.stats.battery.x.push(t);
if (state.stats.health.y.length > 400) {
state.stats.health.y.shift();
state.stats.health.x.shift();
state.stats.wifi.y.shift();
state.stats.wifi.x.shift();
state.stats.battery.y.shift();
state.stats.battery.x.shift();
}
line.setData([state.stats.health, state.stats.wifi, state.stats.battery]);
bar_h.setData({titles: ['health'], data: [state.health]});
bar_w.setData({titles: ['wifi'], data: [state.wifi]});
bar_b.setData({titles: ['battery'], data: [state.battery]});
ipc.server.broadcast('sync', JSON.stringify(state));
return;
}
function randomizeStats() {
for (let kind of chartVals) {
if (Math.random() > 0.6) {
state[kind] += (Math.random() * 2) - 1;
}
}
}
// for (let i = 0; i < 100; i++) updateChart();
let chart_update = setInterval(updateChart, 300);
// chart_update.unref();
function make_terminal() {
let term = blessed.terminal({
parent: screen,
cursor: 'line',
cursorBlink: true,
screenKeys: false,
label: ' hacker terminal ',
left: 0,
top: '30%',
shell: '/bin/bash',
env: process.env,
width: '70%',
height: '70%',
border: 'line',
style: {fg: 'default', bg: 'default', focus: {border: {fg: 'green'}}},
screen: screen
});
return term;
}
function battery_dead() {
return blessed.box({
top: 'center',
left: 'center',
width: '50%',
height: '50%',
content:
'{red-fg} {bold}BATTERY DEAD PLEASE CHARGE ME{/bold} {/red-fg}',
border: {type: 'line'},
style: {fg: 'white', bg: 'red', border: {fg: 'red'}}
})
}
terminal = make_terminal();
terminal.pty.write('cd ' + __dirname + ' && ' + __dirname + '/node vorterm.js\n');
let batteryNotice = battery_dead();
let terminalClosed = false;
ws.on('message', (data) => {
// typing
if (data.length == 1) terminal.pty.write(data);
let [prefix, amt] = data.split(':');
// console.log(prefix, amt);
if (prefix in state && amt !== undefined) {
prefix = prefix.trim();
state[prefix] = parseFloat(amt);
} else if (prefix == 'learnSpell') {
ipc.server.broadcast('learnSpell', amt)
}
});
ws.on('close', (code, reason) => {
terminal.write(
'closed with code: ' + code.toString() + ' and reason: ' + reason);
});
screen.render();
screen.key('C-c', function() {
ws.close(1000, 'ctrl-c recived');
terminal.kill();
// clearInterval(chart_update);
return screen.destroy();
});
ws.onclose = () => {
opened = false;
terminal.kill();
screen.destroy();
ipc.server.stop();
};
});
ipc.server.start();
});
<file_sep>/vorterm.js
let _vorpal = require('vorpal');
let ipc = require('node-ipc');
ipc.config.id = 'terminal';
ipc.config.retry = 500;
ipc.config.sync = true;
ipc.config.silent = true;
ipc.config.logger = () => {};
let state = {spells: [], inventory: {opened: false, items: []}};
let jokes = ['abcd'];
// how long it should take for a spell to download, in ms
const SPELL_WAIT = 3 * 1000;
ipc.connectTo('dash', function() {
ipc.of.dash.on('connect', function() {
let vorpal = _vorpal();
let emit = (msg, data) => ipc.of.dash.emit(msg, data);
let on = (ev, fn) => ipc.of.dash.on(ev, fn);
let cancelDownload = false;
function loading_bar(args, wait, callback) {
let msg = '> ' + args + ' spell...';
let t = 0;
function draw() {
msg = '--' + msg;
vorpal.ui.redraw(msg);
setTimeout(() => {
if (t < wait && !cancelDownload) {
draw();
t = t + (wait / 30);
} else {
cancelDownload = false;
vorpal.ui.redraw.done();
callback();
}
}, wait / 30);
}
draw();
}
on('no wifi', function(msg) {
this.log(' no wifi, spells will be sent over cellular data...\n');
vorpal.delimiter('cir (no wifi) > ').show();
});
on('sending failed', function() {
cancelDownload = true;
this.log(' *** spell sending failed! please try again *** ')
});
on('wifi', function() { vorpal.delimiter('cir > ').show(); });
on('sync', function(data) {
let new_state = JSON.parse(data);
if (new_state.wifi < 10 && state.wifi > 10) {
vorpal.log(
' ** no wifi, spells will be sent over cellular data... ** \n');
vorpal.delimiter('ciri (no wifi) > ').show();
} else if (new_state.wifi > 10 & state.wifi < 10) {
vorpal.delimiter('ciri > ');
}
state = new_state;
});
on('spell', function({action, spell}) {
let {name, desc} = spell;
switch (action) {
case 'learn':
state.spells.append(spell);
vorpal.command('spell ' + name, desc)
.action(function(args, callback) {
let msg = '> Opening ' + name + ' spell...';
let t = 0;
function draw() {
msg = '--' + msg;
vorpal.ui.redraw(msg);
setTimeout(() => {
if (t < SPELL_WAIT) {
draw();
t = t + (SPELL_WAIT / 30);
} else {
vorpal.ui.redraw.done();
}
}, SPELL_WAIT / 30);
}
});
}
});
function checkWifi(spellEmit, callback) {
if (state.wifi >= 10 * Math.random() || Math.random() > 0.3) {
loading_bar('sending', SPELL_WAIT * Math.random(), () => {
spellEmit();
return callback();
});
} else {
loading_bar('sending', SPELL_WAIT * Math.random() * 3.0, () => {
vorpal.log(
' *** spell sending failed! please try again or connect to wifi *** ');
return callback();
});
}
}
// adds a spell command
function addSpell(spell, desc, log) {
desc = desc || 'Equip ' + spell;
log = log || '--> turning on ' + spell;
let v = vorpal.command(spell, desc)
.action(function(args, callback) {
this.log(log);
return checkWifi(() => emit(spell), () => callback());
})
.alias('spell ' + spell);
emit('learn', spell);
return v;
};
vorpal.command('health', 'Show info about your health')
.action(function(args, callback) {
this.log('Health: ' + state.health);
return callback();
});
let enemy_info = {
cable_snake:
'small speedy snake. easily scared off but finds confidence in packs',
hand_phone:
'big body-blocking hand. very strong, self reliant. doesn\'t back down in the face of adversary',
disk_drive:
'very angry, will spray you with diskettes and drives. no fear',
possessed_peripherals:
'annoying swarms. animated by the spirits of lost data and misplaced files',
ambient_ghost: 'ambient. mysterious...'
};
vorpal
.command(
'enemy info',
'Print info about all the enemies you\'ve seen so far')
.action(function(args, callback) {
if (state.discovered_enemies && state.discovered_enemies.length > 0) {
for (let enemy of state.discovered_enemies) {
this.log(enemy_info[discovered_enemies]);
}
} else {
this.log('no enemies seen');
}
return callback();
});
let learntSpells = {};
let learnSpell = {
heal: () => addSpell('health heal', 'Heal 20 HP'),
armour: () => addSpell('health armour', 'Get 20 armour'),
fists:
() => addSpell(
'fists',
'New workout improves hand strength by 100 with one simple trick'),
water: () => addSpell('water', 'make things wet (voids warranty)'),
fireball: () => addSpell(
'fireball', 'turn up the heat with this holiday favourite'),
landmine: () => addSpell('landmine', 'open for a surprise'),
firespray: () => addSpell('spray fire', 'warranty voided upon usage'),
waterspray: () => addSpell(
'spray water', 'a fine mist appears at your fingertips'),
jump: () => addSpell('jump', 'boing!'),
crouch: () => addSpell('crouch', '!goinb'),
armor: () => vorpal.command('health armour', 'Gain 20 armour points')
.action(function(args, callback) {
this.log('Health: ' + state.health);
return callback();
}),
shield: () => vorpal.command('health shields', 'Gain 20 armour points')
.action(function(args, callback) {
this.log('Health: ' + state.health);
return callback();
})
};
learnSpell.fists();
learnSpell.heal();
// addSpell('lightning', 'blow them away with this powerful spell');
addSpell(
'radar', 'connect to your nearby friends',
'radar has stopped due to an unexpected error');
on('learnSpell', (spell) => {
let alreadyKnown = false;
if (learntSpells[spell] != undefined) {
vorpal.log(
'updating ' + spell + ' to latest version v' + Math.random() + '.' +
Math.random());
alreadyKnown = true;
}
if (spell in learnSpell) {
vorpal.log('downloading ' + spell);
loading_bar('downloading', 4000 + 2000 * Math.random(), () => {
if (!alreadyKnown) learnSpell[spell]();
learntSpells[spell] = true;
vorpal.log(
spell + ' spell downloaded!\n\ttype: help ' + spell +
' for usage instructions and help');
})
}
})
addSpell('attack', 'use the current spell').alias('atk').alias('a');
vorpal
.command(
'__learnSpell <spell>',
function(args, callback) {
learnSpell[args.spell]();
learntSpells[spell] = true;
})
.hidden();
vorpal.command('spell', 'Equip the spell').action(function(args, callback) {
this.log('i\'m sorry, i don\'t understand what you mean');
return callback();
});
vorpal.catch('catch-all').action(function(args, callback) {
this.log('i\'m sorry, i don\'t understand what you mean');
return callback();
});
ipc.of.dash.on('ack', () => {});
let flashlightOn = false;
// informational commands that are always there
vorpal.command('flashlight', 'Turns on flashlight')
.action(function(args, callback) {
this.log(
'--> turning ' + flashlightOn ? 'on' :
'off' +
' flashlight');
emit('flashlight');
flashlightOn = true;
callback();
});
vorpal.command('inventory', 'Opens app drawer')
.action(function(args, callback) {
this.log('^ opening inventory');
state.inventory.opened = true;
// emit('inventory');
return callback();
});
vorpal.command('spells', ' Lists spells in my memory')
.action(function(args, callback) {
this.log(state.spells.join(' '));
return callback();
});
addSpell('scan', 'QR-code scanner');
vorpal.delimiter('cir > ').show();
});
})
|
a1f08675399bf91df0550878c4aeca0a23321788
|
[
"Markdown",
"JavaScript"
] | 3
|
Markdown
|
aman-tiwari/ciri-term
|
a8692acee40a5f4c9b720ac0bbcb21ef7e516083
|
1ec5d62723361ad51b95e323ef2150ea52ebc126
|
refs/heads/main
|
<file_sep>package org.inex.Parser;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
import org.inex.Model.Request;
public class ParseRequest {
/**
* Parse the content of the request file
*
* @param pathRequest Path to the file that contain the requests
* @param applyStemming Boolean to choose using stemming during parsing
* @return Parsed content as an array of Request
* @throws IOException
*/
public static ArrayList<Request> extractRequests(String pathRequest, boolean applyStemming) throws IOException {
ArrayList<Request> requestList = new ArrayList<>();
File q = new File(pathRequest);
Scanner reader = new Scanner(q);
while (reader.hasNextLine()) {
String query = reader.nextLine().trim();
String[] input = query.split(" ", 2);
String code = input[0];
String[] terms = input[1].split(" ");
requestList.add(new Request(code, terms, applyStemming));
}
reader.close();
return requestList;
}
}
<file_sep>package org.inex.Utils;
import java.util.ArrayList;
import org.inex.App.Weight;
import org.inex.Model.Doc;
import org.inex.Model.Score;
public class UtilWeightCompute {
/**
* @param K Adjust term frequency saturation for BM25
* @param B Adjust size normalization for BM25
*/
private static final double K = 0.6;
private static final double B = 0.3;
/**
* @param docList List containing all the documents in the file(s)
* @return Average size of the documents in the list
*/
public static double avg(ArrayList<Doc> docList) {
double total = 0;
for (Doc d : docList) {
total = total + d.getContentList().size();
}
return total / docList.size();
}
/**
* @param docList List containing all the documents in the file(s)
* @return Average size of the elements in the documents list
*/
public static double avgElements(ArrayList<Doc> docList) {
double total = 0;
for (Doc d : docList) {
for (String k : d.getElements().keySet()) {
total = total + d.getElements().get(k).size();
}
}
return total / docList.size();
}
/**
* @param score Score object of the document
* @param df Number of documents that contain the term
* @param tf Term frequency in the document
* @param docSize Size of the document
* @param docListSize Total size of the documents in the list
* @param avg Average size of the documents in the list
* @param weight Type of weighting (LTN, LTC, BM25)
* @param node Name of the node (XML tag)
* @return Computed weight following the selected type
*/
public static void weight(Score score, int df, int tf, int docSize, int docListSize, double avg, Weight weight,
String node) {
if (weight.equals(Weight.LTN) || weight.equals(Weight.LTC)) {
if (tf != 0 && df != 0) {
double tfd = 1 + Math.log10(tf);
double idf = Math.log10(docListSize / df);
double w = tfd * idf;
score.setValue(score.getValue() + w);
if (weight.equals(Weight.LTC)) {
score.setNorm(score.getNorm() + Math.pow(w, 2));
}
}
}
if (weight.equals(Weight.BM25)) {
double tfd1 = tf * (K + 1);
double tfd2 = K * ((1 - B) + B * docSize / avg) + tf;
double idf = Math.log10((docListSize - df + 0.5) / (df + 0.5));
double w = tfd1 / tfd2 * idf;
score.setValue(score.getValue() + w);
}
}
}
<file_sep>package org.inex;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.stream.Collectors;
import javax.xml.parsers.ParserConfigurationException;
import org.inex.Model.Doc;
import org.inex.Model.GraphLink;
import org.inex.Model.Request;
import org.inex.Model.Score;
import org.inex.Parser.ParseRequest;
import org.inex.Parser.ParseTxt;
import org.inex.Parser.ParseXML;
import org.inex.Utils.UtilFrequencyCompute;
import org.inex.Utils.UtilWeightCompute;
import org.xml.sax.SAXException;
public class App {
/**
* @param PATH_QUERY Path to the txt file of requests
* @param PATH_INPUT_TXT Path to the txt format collection of documents
* @param PATH_INPUT_XML Path to the xml format collection of documents
* @param PATH_OUTPUT Path to the output of the txt file run
* @param ALPHA_POPULAR Adjust the importance of the popularity bonus
*/
private static final String PATH_QUERY = "./files/request/topics_M2WI7Q_2020_21.txt";
private static final String PATH_INPUT_TXT = "./files/input/txt/Text_Only_Ascii_Coll_MWI_NoSem.gz";
private static final String PATH_INPUT_XML = "./files/input/xml/XML_Coll_MWI_withSem.tar.gz";
private static final String PATH_OUTPUT = "./files/output/EliasNicolas_05_01_BM25_articles_k0.6b0.3.txt";
private static final int ALPHA_POPULAR = 1;
/**
* Custom enum class to define weighting type
*
* @param LTN Weighting request terms using LTN
* @param LTC Weighting request terms using LTC
* @param BM25 Weighting request terms using BM25
*/
public enum Weight {
LTN, LTC, BM25;
}
/**
* Custom enum class to define input type
*
* @param TXT Return content of a text document
* @param XML_ARTICLES Return content of article tag in XML documents
* @param XML_ELEMENTS Return content of specific tags in XML documents
*/
public enum Input {
TXT, XML_ARTICLES, XML_ELEMENTS;
}
public static void main(String[] args) throws IOException, ParserConfigurationException, SAXException {
read(false, Weight.BM25, Input.XML_ARTICLES, false);
}
/**
* Main program to generate a run from the input documents
*
* @param applyStemming Boolean to choose using stemming during parsing or not
* @param weight Type of weighting
* @param input Type of the documents
* @param applyPopularity Boolean to choose using popularity of links or not
* @throws IOException
* @throws ParserConfigurationException
* @throws SAXException
*/
public static void read(boolean applyStemming, Weight weight, Input input, boolean applyPopularity)
throws IOException, ParserConfigurationException, SAXException {
ArrayList<Doc> docList = new ArrayList<>();
GraphLink linkList = null;
ArrayList<Request> requestList = ParseRequest.extractRequests(PATH_QUERY, applyStemming);
if (input.equals(Input.TXT)) {
docList = ParseTxt.extractTxt(PATH_INPUT_TXT, applyStemming);
createRun(docList, linkList, requestList, weight);
} else if (input.equals(Input.XML_ARTICLES) || input.equals(Input.XML_ELEMENTS)) {
ParseXML.extractTarGzXmlFiles(PATH_INPUT_XML);
List<String> files = ParseXML.getXmlPathList();
for (String path : files) {
Doc doc = ParseXML.parseXmlFile(path, input, applyStemming);
docList.add(doc);
}
if (input.equals(Input.XML_ARTICLES)) {
if (applyPopularity) {
linkList = new GraphLink(docList);
}
createRun(docList, linkList, requestList, weight);
} else if (input.equals(Input.XML_ELEMENTS)) {
createRunElements(docList, requestList, weight);
}
ParseXML.deleteTmpXmlFolder();
}
}
/**
* Compute the score (articles) of the documents for each request
*
* @param docList List containing all the documents in the input file
* @param linkList List containing the links pointed by all documents
* @param requestList List containing all the requests in the request file
* @param weight Type of weighting
*/
public static void createRun(ArrayList<Doc> docList, GraphLink linkList, ArrayList<Request> requestList,
Weight weight) {
String inex = "";
int docListSize = docList.size();
double avg = UtilWeightCompute.avg(docList);
for (int i = 0; i < requestList.size(); i++) {
String id = requestList.get(i).getId();
Map<String, Score> scores = new HashMap<>();
ArrayList<String> terms = requestList.get(i).getTermList();
ArrayList<Integer> dfs = UtilFrequencyCompute.docFreq(docList, terms);
for (Doc d : docList) {
Score score = new Score("/article[1]", 0, 0);
int docSize = d.getContentList().size();
ArrayList<Integer> tfs = UtilFrequencyCompute.termFreq(d, terms);
for (int j = 0; j < terms.size(); j++) {
int df = dfs.get(j);
int tf = tfs.get(j);
UtilWeightCompute.weight(score, df, tf, docSize, docListSize, avg, weight, "/article[1]");
}
if (weight.equals(Weight.LTC)) {
if (score.getNorm() != 0) {
score.setValue(score.getValue() / Math.sqrt(score.getNorm()));
}
}
if (linkList != null) {
double bonus = linkList.getArticleVertexList().stream().filter(doc -> doc.getId().equals(d.getId()))
.collect(Collectors.toList()).get(0).getPopularity();
if (bonus > 0) {
score.setValue(score.getValue() + bonus * ALPHA_POPULAR);
}
}
scores.put(d.getId(), score);
}
inex = inex + writeRequestResult(id, scores);
}
writeRunResult(inex);
}
/**
* Compute the score (elements) of the documents for each request
*
* @param docList List containing all the documents in the input file
* @param requestList List containing all the requests in the request file
* @param weight Type of weighting
*/
public static void createRunElements(ArrayList<Doc> docList, ArrayList<Request> requestList, Weight weight) {
String inex = "";
int docListSize = docList.size();
double avg = UtilWeightCompute.avgElements(docList);
for (int i = 0; i < requestList.size(); i++) {
String id = requestList.get(i).getId();
Map<String, ArrayList<Score>> scores = new HashMap<>();
ArrayList<String> terms = requestList.get(i).getTermList();
ArrayList<Map<String, Integer>> dfs = UtilFrequencyCompute.docFreqElements(docList, terms);
for (Doc d : docList) {
Map<String, Score> scoreByNode = new HashMap<>();
ArrayList<Map<String, Integer>> tfs = UtilFrequencyCompute.termFreqElements(d, terms);
for (int j = 0; j < terms.size(); j++) {
for (String node : tfs.get(j).keySet()) {
Score score = new Score(node, 0, 0);
int nodeSize = d.getElements().get(node).size();
int df = dfs.get(j).get(node);
int tf = tfs.get(j).get(node);
UtilWeightCompute.weight(score, df, tf, nodeSize, docListSize, avg, weight, node);
if (scoreByNode.containsKey(node)) {
score.setValue(score.getValue() + scoreByNode.get(node).getValue());
score.setNorm(score.getNorm() + scoreByNode.get(node).getNorm());
scoreByNode.put(node, score);
} else {
scoreByNode.put(node, score);
}
}
}
if (scoreByNode.size() > 0) {
ArrayList<Score> scoreByDoc = new ArrayList<>();
double total = 0;
for (String node : scoreByNode.keySet()) {
Score score = scoreByNode.get(node);
if (weight.equals(Weight.LTC)) {
if (score.getNorm() != 0) {
score.setValue(score.getValue() / Math.sqrt(score.getNorm()));
}
}
total = total + score.getValue();
}
double avgScore = total / scoreByNode.size();
/**
* Take elements with a score higher or equal to the average score of the
* elements in the document
*/
for (String node : scoreByNode.keySet()) {
Score score = scoreByNode.get(node);
if (score.getValue() >= avgScore) {
scoreByDoc.add(score);
}
}
Collections.sort(scoreByDoc, Collections.reverseOrder());
/**
* Remove overlapping elements
*/
for (int j = 0; j < scoreByDoc.size() - 1; j++) {
String node1 = scoreByDoc.get(j).getNode();
for (int k = j + 1; k < scoreByDoc.size(); k++) {
String node2 = scoreByDoc.get(k).getNode();
if (node1.contains(node2) || node2.contains(node1)) {
scoreByDoc.remove(k);
k = k - 1;
}
}
}
/**
* Uncomment the below code to take the top 50% of the elements above the
* average score
*/
// scoreByDoc.subList((scoreByDoc.size() - 1) / 2, scoreByDoc.size() - 1).clear();
/**
* Uncomment the below code to take the top 25% of the elements above the
* average score
*/
// scoreByDoc.subList(((scoreByDoc.size() - 1) / 2) / 2, scoreByDoc.size() - 1).clear();
scores.put(d.getId(), scoreByDoc);
}
}
inex = inex + writeRequestResultElements(id, scores);
}
writeRunResult(inex);
}
/**
* Save the ranking result for one request
*
* @param id Request identifier
* @param scores Score of the documents in the list for this request
* @return Ranking of the top 1500 documents with the best score
*/
private static String writeRequestResult(String id, Map<String, Score> scores) {
String result = "";
int rank = 1;
int limit = 1500;
Comparator<Entry<String, Score>> comparator = Collections.reverseOrder(Map.Entry.comparingByValue());
Map<String, Score> ranking = scores.entrySet().stream().sorted(comparator).collect(Collectors
.toMap(Map.Entry::getKey, Map.Entry::getValue, (oldValue, newValue) -> oldValue, LinkedHashMap::new));
for (String key : ranking.keySet()) {
Score score = ranking.get(key);
result = result + id;
result = result + " " + "Q0";
result = result + " " + key;
result = result + " " + rank;
result = result + " " + score.getValue();
result = result + " " + "EliasNicolas";
result = result + " " + score.getNode() + "\n";
rank++;
if (rank > limit) {
break;
}
}
return result;
}
/**
* Save the ranking result for one request
*
* @param id Request identifier
* @param scores Score of the elements in the documents for this request
* @return Ranking of the top 1500 documents with the best score
*/
private static String writeRequestResultElements(String id, Map<String, ArrayList<Score>> scores) {
String result = "";
int rank = 1;
int limit = 1500;
Map<String, Double> scoreByDoc = new HashMap<>();
Comparator<Entry<String, Double>> comparator = Collections.reverseOrder(Map.Entry.comparingByValue());
/**
* Uncomment the below code to rank documents using the element with the best
* score in each document
*/
for (String node : scores.keySet()) {
scoreByDoc.put(node, scores.get(node).get(0).getValue());
}
/**
* Uncomment the below code to rank documents using the best average score of
* elements in each document
*/
/*
for (String node : scores.keySet()) {
double total = 0;
for (int i = 0; i < scores.get(node).size(); i++) {
total = total + scores.get(node).get(i).getValue();
}
scoreByDoc.put(node, total / scores.get(node).size());
}
*/
Map<String, Double> ranking = scoreByDoc.entrySet().stream().sorted(comparator).collect(Collectors
.toMap(Map.Entry::getKey, Map.Entry::getValue, (oldValue, newValue) -> oldValue, LinkedHashMap::new));
for (String key : ranking.keySet()) {
for (int i = 0; i < scores.get(key).size(); i++) {
Score score = scores.get(key).get(i);
result = result + id;
result = result + " " + "Q0";
result = result + " " + key;
result = result + " " + rank;
result = result + " " + (limit - rank + 1);
result = result + " " + "EliasNicolas";
result = result + " " + score.getNode() + "\n";
rank++;
if (rank > limit) {
break;
}
}
if (rank > limit) {
break;
}
}
return result;
}
/**
* Save the ranking result for all the requests
*
* @param inex Ranking of the top 1500 documents for all the requests
*/
private static void writeRunResult(String inex) {
try {
FileWriter writer = new FileWriter(PATH_OUTPUT);
writer.write(inex);
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
<file_sep># INEX
## Members
* <NAME>
* <NAME>
## Launch Program
* Open the project in your favorite IDE
* Open src/main/java/org/inex/App.java
* Run main function and the result file will be created in files/output/
## External Sources
* standford, introduction to information retrieval: [here](https://web.stanford.edu/class/cs276/handouts/lecture7-vectorspace-1per.pdf)
* elastic, considerations for picking b and k1 in elasticsearch: [here](https://www.elastic.co/fr/blog/practical-bm25-part-3-considerations-for-picking-b-and-k1-in-elasticsearch)
* quora, how does bm25 work: [here](https://www.quora.com/How-does-BM25-work)
* oracle, normalzing text: [here](https://docs.oracle.com/javase/tutorial/i18n/text/normalizerapi.html)
* stackoverflow, replacement of special characters: [here](https://stackoverflow.com/questions/18623868/replace-any-non-ascii-character-in-a-string-in-java)
* codeflow, lucene analyzers: [here](https://www.codeflow.site/fr/article/lucene-analyzers)
* stackoverflow, how to get a token from a lucene token stream: [here](https://stackoverflow.com/questions/2638200/how-to-get-a-token-from-a-lucene-tokenstream)
* lucene apache, documentation: [here](https://lucene.apache.org/core/7_3_1/core/org/apache/lucene/analysis/package-summary.html)
* stanford, coreNLP: [here](https://stanfordnlp.github.io/CoreNLP/)
* usermanual, pre-processing stemming: [here](https://usermanual.wiki/Document/Instructions.1836733729/help)
* programcreek, java code examples for englishStemmer: [here](https://www.programcreek.com/java-api-examples/?api=org.tartarus.snowball.ext.EnglishStemmer)
* codota, how to use englishStemmer: [here](https://www.codota.com/code/java/classes/org.tartarus.snowball.ext.englishStemmer)
* jgrapht, documentation: [here](https://jgrapht.org/guide/UserOverview)
* baeldung, introduction to jgrapht: [here](https://www.baeldung.com/jgrapht)
* howtodoinjava, read xml dom parser: [here](https://howtodoinjava.com/java/xml/read-xml-dom-parser-example/)
|
aaa510e1a54c77d200907308cb5c67c16fceaf50
|
[
"Markdown",
"Java"
] | 4
|
Java
|
eclair11/inex
|
4d1563bd01e4eb15bdb36666e4f59eced949bc37
|
cce01fc6b1b4b69afacdac925413c425d0fce20d
|
refs/heads/master
|
<repo_name>Kevinvossen/S02Game<file_sep>/SE2 - S23 - SE2 Game/Entities/Player.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Drawing;
using SE2___S23___SE2_Game.Game;
using System.Windows.Forms;
namespace SE2___S23___SE2_Game.Entities
{
public class Player
{
public Size Size { get; private set; }
public Point Position { get; set; }
public bool PowerUp { get; set; }
public int HitPoints { get; set; }
Point newPosition;
public Player(Size size, Point position, int hitpoints)
{
this.Size = size;
this.Position = position;
this.HitPoints = hitpoints;
this.newPosition = new Point(0, 0);
}
public void Update()
{
}
public void Draw(Graphics g)
{
SolidBrush brush = new SolidBrush(Color.DeepSkyBlue);
g.FillEllipse(brush, GetRectForPlayer());
g.DrawEllipse(Pens.Black, GetRectForPlayer());
}
public Rectangle GetRectForPlayer()
{
Map map = World.Instance.Map;
Rectangle rect = new Rectangle((Position.X + (map.CellSize.Width - this.Size.Width) / 2),
(Position.Y + (map.CellSize.Height - this.Size.Height) / 2),
this.Size.Width,
this.Size.Height);
return rect;
}
public void Interaction(Keys keyCode)
{
switch (keyCode)
{
case Keys.Up:
this.newPosition.Y = this.Position.Y - World.Instance.Map.CellSize.Height;
break;
case Keys.Down:
this.newPosition.Y = this.Position.Y + World.Instance.Map.CellSize.Height;
break;
case Keys.Left:
this.newPosition.X = this.Position.X - World.Instance.Map.CellSize.Width;
break;
case Keys.Right:
this.newPosition.X = this.Position.X + World.Instance.Map.CellSize.Width;
break;
default:
this.newPosition = this.Position;
break;
}
if (IsWithinBoundaries(newPosition))
{
this.Position = newPosition;
}
}
public bool IsWithinBoundaries(Point position)
{
if (this.newPosition.X < (World.Instance.Map.CellCount.X * World.Instance.Map.CellSize.Width) &&
this.newPosition.Y < (World.Instance.Map.CellCount.Y * World.Instance.Map.CellSize.Height) &&
this.newPosition.X >= 0 && this.newPosition.Y >= 0)
{
return true;
}
else
{
return false;
}
}
}
}
<file_sep>/SE2 - S23 - SE2 Game/Entities/Cell.cs
using SE2___S23___SE2_Game.Game;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SE2___S23___SE2_Game.Entities
{
public class Cell
{
public Point Position { get; set; }
public Size Size { get; set; }
public Cell(Size size, Point position)
{
this.Size = size;
this.Position = position;
}
}
}
<file_sep>/SE2 - S23 - SE2 Game/Game/Map.cs
using SE2___S23___SE2_Game.Entities;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SE2___S23___SE2_Game.Game
{
public class Map
{
public Size MapSize { get; set; }
public Size CellSize { get; set; }
public Point CellCount { get; set; }
public Map(Size mapSize, Point cellCount)
{
this.MapSize = mapSize;
this.CellCount = cellCount;
this.CellSize = new Size(mapSize.Width / cellCount.X,
mapSize.Height / cellCount.Y);
}
public void Draw(Graphics g)
{
for (int x = 1; x < this.CellCount.X; x++)
{
g.DrawLine(Pens.LightGray, x * this.CellSize.Width, 0,
x * this.CellSize.Width, this.MapSize.Height);
}
for (int y = 1; y < this.CellCount.Y; y++)
{
g.DrawLine(Pens.LightGray, 0, y * this.CellSize.Width,
this.MapSize.Width, y * this.CellSize.Width);
}
}
}
}
<file_sep>/SE2 - S23 - SE2 Game/Form1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using SE2___S23___SE2_Game.Game;
using SE2___S23___SE2_Game.Entities;
namespace SE2___S23___SE2_Game
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Size size = new Size(30, 30);
Point position = new Point(0, 0);
World.Instance.Create(picGameWorld.Size, new Point(10, 10));
World.Instance.CreatePlayer(size, position, 100);
Focus();
}
private void timerUpdate_Tick(object sender, EventArgs e)
{
World.Instance.Update();
picGameWorld.Refresh();
}
private void picGameWorld_Paint(object sender, PaintEventArgs e)
{
World.Instance.Draw(e.Graphics);
}
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
World.Instance.Player.Interaction(e.KeyCode);
}
}
}
<file_sep>/SE2 - S23 - SE2 Game/Game/World.cs
using SE2___S23___SE2_Game.Entities;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SE2___S23___SE2_Game.Game
{
public class World
{
public Player Player { get; set; }
public Map Map { get; private set; }
public bool GameWon { get; private set; }
public bool GameOver { get; private set; }
public Cell Cell { get; set; }
public static World Instance
{
get
{
if (instance == null)
{
instance = new World();
}
return instance;
}
}
private static World instance;
private World()
{
}
public void Update()
{
}
public void Draw(Graphics g)
{
this.Map.Draw(g);
this.Player.Draw(g);
}
public void Create(Size mapSize, Point cellCount)
{
this.Map = new Map(mapSize, cellCount);
}
public void CreatePlayer(Size size, Point position, int hitpoints)
{
this.Player = new Player(size, position, hitpoints);
}
}
}
|
825d1e121886d1dfa7145d25cea0261d1a47be82
|
[
"C#"
] | 5
|
C#
|
Kevinvossen/S02Game
|
dad282f079ded3b19fd7c6ba21ffcc075427bbc1
|
163d2be24a6e7182f10206399b8953c2be190393
|
refs/heads/master
|
<repo_name>Vishal-shakaya/channel<file_sep>/chat/urls.py
from django.urls import path
from chat import views
app_name = 'chat'
urlpatterns = [
path('',views.HomeView, name='home'),
path('<str:room_name>/', views.ChatRoom, name='chat_room'),
]
<file_sep>/chat/models.py
from django.db import models
# Create your models here.
class Client(models.Model):
channel_name = models.TextField(null=True, blank=True)<file_sep>/chat/routing.py
from django.urls import path
from chat import consumers
websocket_urlpatterns=[
path('chat/<str:room_name>/',consumers.ChatConsumer.as_asgi()),
]
<file_sep>/chat/views.py
from django.shortcuts import render
# Create your views here.
def HomeView(request):
return render(request, 'chat/CreateRoom.html')
def ChatRoom(request , room_name):
context ={'room_name':room_name}
return render(request, 'chat/Room.html', context=context)
<file_sep>/chat/consumers.py
import json
from channels.generic.websocket import AsyncWebsocketConsumer,WebsocketConsumer
from asgiref.sync import async_to_sync
from channels.db import database_sync_to_async
from django.contrib.auth.models import User
from channels.layers import get_channel_layer
from . models import Client as Clients
class ChatConsumer(WebsocketConsumer):
def connect(self):
# Make a database row with our channel name
print(f'connected to : {self.channel_name}')
Clients.objects.create(channel_name=self.channel_name)
self.accept()
def disconnect(self, close_code):
# Note that in some rare cases (power loss, etc) disconnect may fail
# to run; this naive example would leave zombie channel names around.
Clients.objects.filter(channel_name=self.channel_name).delete()
def receive(self, text_data):
text_data_json = json.loads(text_data)
message = text_data_json['message']
channel_layer = get_channel_layer()
async_to_sync(channel_layer.send)(self.channel_name, {
"type": "chat.message",
"message": message,
})
def chat_message(self, event):
# Handles the "chat.message" event when it's sent to us.
self.send(text_data=json.dumps({
'message':event["message"]
}))
# class ChatConsumer(AsyncWebsocketConsumer):
# pass
# async def connect(self):
# self.room_name = self.scope['url_route']['kwargs']['room_name']
# self.room_group_name = f'chat_{self.room_name}'
# await self.channel_layer.group_add(
# self.room_group_name ,
# self.channel_name )
# # username= await self.get_username()
# # print(f'username : {type(username)} ')
# await self.accept()
# # Database manuculation :
# @database_sync_to_async
# def get_username(self):
# return User.objects.all()[0]
# async def disconnect(self):
# await self.channel_layer.group_discard(
# self.room_group_name ,
# self.channel_name)
# async def receive(self , text_data):
# pure_data = json.loads(text_data)
# channel_layer = get_channel_layer()
# await channel_layer.send("notify", {
# "type": "chat.message",
# "text": "Hello there!",
# })
# await self.channel_layer.group_send(
# self.room_group_name ,
# {
# 'type':'send_message',
# 'message':pure_data['message']
# }
# )
# async def send_message(self, event):
# message =event['message']
# await self.send(
# text_data = json.dumps(
# {
# 'message':message
# }
# ))
|
930068dbe899f9aaf7edea4a63642cf7f96fcf24
|
[
"Python"
] | 5
|
Python
|
Vishal-shakaya/channel
|
8c54afdd4a18a925f31fd445ec8fc4713125adc9
|
01745d201adb6fdad8477c3b4ba5e274499f3b7d
|
refs/heads/master
|
<repo_name>Toxu4/GraphQL-CSharp-Generator<file_sep>/src/cs/Toxu4.GraphQl.Client/GraphQlApiSettings.cs
namespace Toxu4.GraphQl.Client
{
public class GraphQlApiSettings
{
public string Endpoint { get; set; }
}
}
<file_sep>/src/cs/Toxu4.GraphQl.Client/RegistrationExtensions.cs
using System;
using Microsoft.Extensions.DependencyInjection;
namespace Toxu4.GraphQl.Client
{
public static class RegistrationExtensions
{
public static IServiceCollection AddGraphQlClient(this IServiceCollection serviceCollection, Action<GraphQlApiSettings> settings, Action<IHttpClientBuilder> httpClientBuilder = null)
{
serviceCollection.Configure(settings);
var builder = serviceCollection
.AddHttpClient<IGraphQlQueryExecutor, GraphQlQueryExecutor>();
httpClientBuilder?.Invoke(builder);
return serviceCollection;
}
}
}<file_sep>/sample/GraphQlServer/Schema/ComputerSchema.cs
using GraphQL;
namespace GraphQlServer.Schema
{
public class ComputerSchema :GraphQL.Types.Schema
{
public ComputerSchema(ComputerQuery query, IDependencyResolver resolver)
{
Query = query;
DependencyResolver = resolver;
}
}
}<file_sep>/sample/GraphQlServer/Startup.cs
using GraphQlServer.Schema;
using GraphQlServer.Schema.Types;
using GraphQL;
using GraphQL.Server;
using GraphQL.Server.Ui.Playground;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
namespace GraphQlServer
{
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services
.AddGraphQL(options =>
{
options.EnableMetrics = true;
options.ExposeExceptions = true;
})
.AddDataLoader();
services.AddSingleton<IDependencyResolver>(
c => new FuncDependencyResolver(c.GetService));
//
services.AddSingleton<ComputerSchema>();
services.AddSingleton<ComputerQuery>();
services.AddSingleton<DriveQuery>();
services.AddSingleton<DriveType>();
services.AddSingleton<FolderOrFileType>();
services.AddSingleton<FolderType>();
services.AddSingleton<FileType>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseWebSockets();
app.UseGraphQL<ComputerSchema>();
app.UseGraphQLPlayground(new GraphQLPlaygroundOptions());
}
}
}<file_sep>/sample/GraphQlServer/Schema/Types/DriveType.cs
using System.IO;
using System.Linq;
using GraphQL.Types;
namespace GraphQlServer.Schema.Types
{
public class DriveType : ObjectGraphType<DriveInfo>
{
public DriveType()
{
Field(_ => _.Name);
Field(_ => _.VolumeLabel);
Field(_ => _.DriveFormat);
Field(_ => _.IsReady);
Field(_ => _.TotalSize);
Field(_ => _.AvailableFreeSpace);
Field(_ => _.TotalFreeSpace);
Field<ListGraphType<FolderOrFileType>>()
.Name("content")
.Resolve(context =>
Directory
.GetDirectories(context.Source.Name)
.Select(d => new DirectoryInfo(d)).Cast<object>()
.Union(
Directory
.GetFiles(context.Source.Name)
.Select(f => new FileInfo(f))));
}
}
}
<file_sep>/src/cs/Toxu4.GraphQl.Client/AbstractClassConverter.cs
using System;
using System.Collections.Concurrent;
using System.Linq;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace Toxu4.GraphQl.Client
{
internal class AbstractClassConverter : JsonConverter
{
private static readonly ConcurrentDictionary<(Type type, string name), Type> Implementations = new ConcurrentDictionary<(Type type , string name), Type>();
public override bool CanWrite => false;
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Null)
{
return null;
}
var token = JToken.ReadFrom(reader);
var typeNameToken = token.Children<JProperty>().FirstOrDefault(p => p.Name == "__typename");
if (typeNameToken == null)
{
return null;
}
var implementationType = Implementations
.GetOrAdd(
(objectType, typeNameToken.Value.ToString()),
tuple =>
tuple.type
.Assembly.GetTypes()
.FirstOrDefault(t =>
t.IsSubclassOf(tuple.type)
&&
t.Name == $"{tuple.name}Result"));
return implementationType != null
? token.ToObject(implementationType, serializer)
: null;
}
public override bool CanConvert(Type objectType)
{
return objectType.IsAbstract;
}
}
}
<file_sep>/sample/GraphQlServer/Schema/Types/FileType.cs
using System.IO;
using GraphQL.Types;
namespace GraphQlServer.Schema.Types
{
public class FileType : ObjectGraphType<FileInfo>
{
public FileType()
{
Field(_ => _.Name);
Field(_ => _.Length);
Field(_ => _.IsReadOnly);
Field(_ => _.CreationTime);
}
}
}<file_sep>/src/cs/Toxu4.GraphQl.Client/ErrorResult.cs
namespace Toxu4.GraphQl.Client
{
public class ErrorResult
{
public class LocationResult
{
public int Line { get; set; }
public int Column { get; set; }
}
public class ExtensionsResult
{
public string Code { get; set;}
}
public string Message { get; set;}
public LocationResult[] Locations { get; set;}
public ExtensionsResult Extensions { get; set;}
}
}
<file_sep>/sample/GraphQlServer/Schema/Types/DriveQuery.cs
using GraphQL.Types;
namespace GraphQlServer.Schema.Types
{
public class DriveQuery : ObjectGraphType
{
public DriveQuery()
{
Field<ListGraphType<DriveType>>()
.Name("list")
.Resolve(context => System.IO.DriveInfo.GetDrives());
}
}
}<file_sep>/src/cs/Toxu4.GraphQl.Client/GraphQlQueryExecutor.cs
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
namespace Toxu4.GraphQl.Client
{
internal class GraphQlQueryExecutor : IGraphQlQueryExecutor
{
private static readonly JsonSerializerSettings JsonSerializerSettings = new JsonSerializerSettings
{
Converters = new List<JsonConverter>
{
new AbstractClassConverter()
}
};
private readonly HttpClient _httpClient;
private readonly string _endpoint;
public GraphQlQueryExecutor(IOptions<GraphQlApiSettings> settings, HttpClient httpClient)
{
_httpClient = httpClient;
_endpoint = settings.Value.Endpoint;
}
public async Task<TResult> Run<TQuery, TResult>(TQuery query) where TQuery : IGraphQlQuery
{
var queryParamsBuilder = new StringBuilder($"query={query.QueryText}");
if (query.Variables.Any())
{
queryParamsBuilder.Append($"&variables={JsonConvert.SerializeObject(query.Variables)}");
}
var str = await _httpClient
.GetStringAsync($"{_endpoint}?{queryParamsBuilder}")
.ConfigureAwait(false);
return JsonConvert.DeserializeObject<TResult>(str, JsonSerializerSettings);
}
}
}
<file_sep>/src/cs/Toxu4.GraphQl.Client/QueryResult.cs
namespace Toxu4.GraphQl.Client
{
public class QueryResult<TData>
{
public TData Data { get; set; }
public ErrorResult[] Errors { get; set; }
public void Deconstruct(out TData data, out ErrorResult[] errors)
{
data = Data;
errors = Errors;
}
}
}
<file_sep>/sample/GraphQlServer/Schema/Types/FolderType.cs
using System;
using System.IO;
using System.Linq;
using GraphQL.Types;
namespace GraphQlServer.Schema.Types
{
public class FolderType : ObjectGraphType<DirectoryInfo>
{
public FolderType()
{
Field(_ => _.Name);
Field(_ => _.FullName);
Field(_ => _.CreationTime);
Field<ListGraphType<FolderOrFileType>>()
.Name("content")
.Resolve(context => Directory
.GetDirectories(context.Source.FullName)
.Select(d => new DirectoryInfo(d)).Cast<object>()
.Union(
Directory
.GetFiles(context.Source.FullName)
.Select(f => new FileInfo(f))));
}
}
}<file_sep>/README.md
# GraphQL-CSharp-Generator
[](https://ci.appveyor.com/project/Toxu4/graphql-csharp-generator/branch/master)
[](https://www.nuget.org/packages/Toxu4.GraphQl.Client)
[](https://www.npmjs.com/package/graphql.csharp.generator)
## Getting started
To get started with sample you need:
- nodejs v11
- .net cli
In your .net projects folder execute following commands:
```
git clone https://github.com/Toxu4/GraphQL-CSharp-Generator.git
cd GraphQL-CSharp-Generator\sample\GraphQlServer
dotnet run
```
Sample GraphQl server will start. You can surf api using playground:
```
http://localhost:5000/ui/playground
```
In new console window switch to your projects directory and execute following commands:
```
dotnet new console -n MyCoolGraphqlApp
cd .\MyCoolGraphqlApp
npm i -g graphql.csharp.generator
dotnet add package Toxu4.GraphQl.Client
dotnet add package Microsoft.Extensions.DependencyInjection
```
create and place into MyCoolGraphqlApp directory file computerQueries.graphql with following content:
```
query getDrives{
drives{
list{
name
content{
__typename
... on FolderType{
fullName
}
... on FileType{
name
}
}
}
}
}
```
Generate code:
```
gql-gen-csharp -s http://localhost:5000/graphql -d ./*.graphql -o Generated.cs -n MyCoolGraphqlApp
```
Replace program.cs file content with:
```
using System;
using Microsoft.Extensions.DependencyInjection;
using Toxu4.GraphQl.Client;
using System.Threading.Tasks;
namespace MyCoolGraphqlApp
{
class Program
{
static void Main(string[] args)
{
var queries =
new ServiceCollection()
.AddGraphQlClient(settings => settings.Endpoint = "http://localhost:5000/graphql")
.AddGeneratedQueries()
.BuildServiceProvider()
.GetRequiredService<IComputerQueries>();
var (result, _) = queries.GetDrives(new GetDrivesQuery()).GetAwaiter().GetResult();
foreach (var drive in result.Drives.List)
{
Console.WriteLine($"Drive: {drive.Name}");
foreach(var content in drive.Content)
{
switch (content)
{
case GetDrivesQuery.Result.DrivesResult.ListResult.ContentResult.FolderTypeResult folder:
Console.WriteLine($"Folder: {folder.FullName}");
break;
case GetDrivesQuery.Result.DrivesResult.ListResult.ContentResult.FileTypeResult file:
Console.WriteLine($"File: {file.Name}");
break;
}
}
}
}
}
}
```
Run application
```
dotnet run
```
## limitations
There are some query limitations.
- does not support interfaces
- does not support mutations
<file_sep>/src/cs/Toxu4.GraphQl.Client/IGraphQlQuery.cs
using System.Collections.Generic;
namespace Toxu4.GraphQl.Client
{
public interface IGraphQlQuery
{
string QueryText { get; }
IDictionary<string, object> Variables { get; }
}
}
<file_sep>/sample/GraphQlServer/Schema/Types/FolderOrFileType.cs
using GraphQL.Types;
namespace GraphQlServer.Schema.Types
{
public class FolderOrFileType : UnionGraphType
{
public FolderOrFileType()
{
Type<FolderType>();
Type<FileType>();
}
}
}<file_sep>/src/cs/Toxu4.GraphQl.Client/IGraphQlQueryExecutor.cs
using System.Threading.Tasks;
namespace Toxu4.GraphQl.Client
{
public interface IGraphQlQueryExecutor
{
Task<TResult> Run<TQuery, TResult>(TQuery query) where TQuery : IGraphQlQuery;
}
}
<file_sep>/sample/GraphQlServer/Schema/ComputerQuery.cs
using System.IO;
using GraphQlServer.Schema.Types;
using GraphQL.Types;
namespace GraphQlServer.Schema
{
public class ComputerQuery : ObjectGraphType
{
public ComputerQuery()
{
Field<DriveQuery>("drives", resolve:context => new {});
Field<FolderType>()
.Name("folder")
.Argument<StringGraphType, string>("name", "название")
.Resolve(context => new DirectoryInfo(context.GetArgument<string>("name")));
}
}
}
|
ff2f6e92c191266732d75a3d7fd3c780191e3cc3
|
[
"Markdown",
"C#"
] | 17
|
C#
|
Toxu4/GraphQL-CSharp-Generator
|
7bb42bd2377315ed3ef88a9e41e84e36b159aaa8
|
c7d100f63ff79a47fc0e08ad856feb634ec1a888
|
refs/heads/master
|
<file_sep>print("This is a Tic Tac Toe game.\nPlayer 1 is x, player 2 is o.\nCorrect input looks like: x, y i.e. 1,2, where x is number of column and y is number of row.")
table = [" "]*9
def printtable(table=[]):
print("_______")
print("|{}-{}-{}|".format(table[0], table[1], table[2]))
print("|{}-{}-{}|".format(table[3], table[4], table[5]))
print("|{}-{}-{}|".format(table[6], table[7], table[8]))
print(u"\u203E"*7)
def inputchecker(move):
if not len(move) == 3:
print("Input incorrect. Make sure to put in in following form: 1,2 and try again.")
return False
if not move[1] == ",":
print("Input incorrect. Try again.")
return False
if not (move[0] == "1" or move[0] == "2" or move[0] == "3"):
print("Input incorrect. Try again.")
return False
if not (move[2] == "1" or move[2] == "2" or move[2] == "3"):
print("Input incorrect. Try again.")
return False
return True
def tableassignment(move, player):
move = move.split(",")
move = list(map(lambda number: int(number), move))
if not table[((move[0]-1)*3+move[1])-1] == " ":
print("This place on the table is already taken. Try again.")
return False
table[(move[0]-1)*3+move[1]-1] = player
return True
def checkwinner():
def whichplayer(symbol):
if symbol == "x":
return "1"
else:
return "2"
if table[0] == table[1] == table[2] and not table[0] == " ":
print("Player {} won.".format(whichplayer(table[0])))
return True
if table[3] == table[4] == table[5] and not table[3] == " ":
print("Player {} won.".format(whichplayer(table[3])))
return True
if table[6] == table[7] == table[8] and not table[6] == " ":
print("Player {} won.".format(whichplayer(table[6])))
return True
if table[0] == table[3] == table[6] and not table[0] == " ":
print("Player {} won.".format(whichplayer(table[0])))
return True
if table[1] == table[4] == table[7] and not table[1] == " ":
print("Player {} won.".format(whichplayer(table[1])))
return True
if table[2] == table[5] == table[8] and not table[2] == " ":
print("Player {} won.".format(whichplayer(table[2])))
return True
if table[0] == table[4] == table[8] and not table[0] == " ":
print("Player {} won.".format(whichplayer(table[0])))
return True
if table[2] == table[4] == table[6] and not table[2] == " ":
print("Player {} won.".format(whichplayer(table[2])))
return True
return False
def isfull():
for element in table:
if element == " ":
return False
return True
iswon = False
lastplayer = 2
while not iswon:
if lastplayer == 1:
move = input("Type input for player 2: ")
if not inputchecker(move):
continue
lastplayer = 2
if not tableassignment(move, "o"):
continue
if checkwinner() == True:
iswon = True
elif lastplayer == 2:
move = input("Type input for player 1: ")
if not inputchecker(move):
continue
lastplayer = 1
if not tableassignment(move, "x"):
continue
if checkwinner() == True:
iswon = True
printtable(table)
if isfull() and not iswon:
print("Draw!")
break
<file_sep># tictactoe
Easy Tic-Tac-Toe game, written in Python
|
ecd9ae531b8134d1a631b33973a75ba7fdfd0cd1
|
[
"Markdown",
"Python"
] | 2
|
Python
|
bartoszbenna/tictactoe
|
1ce88fbb0e3b27e6af8b90affdcb2f2271374a2c
|
b40570c6e73f12ba091ce2243a00e23892e66961
|
refs/heads/master
|
<repo_name>salviolorenzo/capstone<file_sep>/frontend/src/Components/Tiles/Calendar.js
import React, { Component } from 'react';
import BigCalendar from 'react-big-calendar';
import moment from 'moment';
import 'react-big-calendar/lib/css/react-big-calendar.css';
import Modal from 'react-modal';
moment.locale('en');
const localizer = BigCalendar.momentLocalizer(moment);
const allViews = Object.keys(BigCalendar.Views).map(k => BigCalendar.Views[k]);
class Calendar extends Component {
constructor(props) {
super(props);
this.state = {
view: 'day',
date: new Date(),
width: '100%',
header: `Today's Agenda`
};
}
componentDidMount() {
Modal.setAppElement('body');
}
isAllDay(allDay) {
if (allDay) {
return null;
} else {
return (
<>
<input
type="text"
name="start"
value={this.props.start}
onChange={this.props.handleStartTime}
/>
<input
type="text"
name="end"
value={this.props.end}
onChange={this.props.handleEndTime}
/>
</>
);
}
}
render() {
return (
<div className="tile calendarTile">
<h3>{this.state.header}</h3>
<div className="calendarHeader">
<button
className="calendarBtn"
onClick={() =>
this.setState({ view: 'day', header: "Today's Agenda" })
}
>
Day
</button>
<button
className="calendarBtn"
onClick={() => this.setState({ view: 'week', header: 'This Week' })}
>
Week
</button>
<button
className="calendarBtn"
onClick={() =>
this.setState({ view: 'month', header: 'This Month' })
}
>
Month
</button>
</div>
<Modal
isOpen={this.props.modalIsOpen}
onAfterOpen={this.afterOpenModal}
onRequestClose={this.closeModal}
contentLabel="Example Modal"
>
<button onClick={this.props.closeModal} className="closeBtn">
X
</button>
<div className="modalText">
<h2>{this.props.selectedEvent.title}</h2>
<p>{this.props.selectedEvent.start}</p>
<p>{this.props.selectedEvent.end}</p>
</div>
<form
className="modalForm"
onSubmit={event => {
this.props.handleNewEvent(event);
}}
>
<input
type="text"
name="title"
placeholder="Event Title"
value={this.props.term}
onChange={this.props.handleTitleChange}
/>
<label>
<input
type="checkbox"
name="allDay"
value={this.props.allDay}
checked={this.props.allDay}
onChange={this.props.changeBox}
/>
All Day
</label>
{this.isAllDay(this.props.allDay)}
<textarea
name="eventDesc"
placeholder="Event Description"
value={this.props.desc}
onChange={this.props.handleDescChange}
/>
<button type="submit" value="Save" className="saveBtn">
Save
</button>
</form>
<form onSubmit={this.props.handleDelete}>
<button className="modalDelete" type="submit" value="Delete Event">
Delete Event
</button>
</form>
</Modal>
<BigCalendar
selectable={true}
style={{ height: 500, width: this.state.width }}
toolbar={false}
// events={events}
step={60}
localizer={localizer}
events={this.props.events}
onSelectEvent={event => {
this.props.displayEvent(event);
}}
onSelectSlot={event => {
this.props.onSlotChange(event);
}}
view={this.state.view}
views={allViews}
onView={() => {}}
date={this.state.date}
scrollToTime={this.state.date}
onNavigate={date => this.setState({ date })}
timeslots={1}
/>
</div>
);
}
}
export default Calendar;
<file_sep>/frontend/src/Components/Tiles/Weather.js
import React, { Component } from 'react';
function Weather(props) {
if (props) {
return (
<div className="tile weatherTile">
<h3>Today's weather</h3>
<img src={props.icon} className="weatherIcon" alt="WeatherIcon" />
<ul className="weatherList">
{Object.values(props.weather).map((item, index) => {
return <li key={index}>{item}</li>;
})}
</ul>
</div>
);
} else {
return (
<div className="tile weatherTile">
<h3>Loading...</h3>
</div>
);
}
}
export default Weather;
<file_sep>/README.md
# DSHBRD

- An interactive, customizable virtual social assistant.
- The driving concept behind this project was that there is now an app for everything a person can think of, but a user needs to have so many different apps downloaded in order to get all the information he or she needs. DSHBRD is meant to save you time by keeping everything in one place.
- Utilities:
- Weather
- Full Calendar
- News, customized to the users selected news sources
- Events (concerts and sporting events) in the area, based on user location.
- Restaurants in the area
- A google map that plots all the events and restaurants near you
## Technologies Used:
- React.js
- React Router
- Node.js
- Express.js
- PostgreSQL
- PG-Promise(SQL queries)
- CSS3
## Libraries & Modules:
- React Google Maps
- React Big Calendar
- React Swipeable Routes
- Moment.js
## API Services
- OpenWeatherMap API
- News API
- TicketMaster API
- Zomato API
- Google Maps API
## Contributors:
- <NAME>: Full Stack Development
## Home Page


- Users login with a simple combination of the email associated with your account and a password.
- New users can sign up for a new account with just a name, email account and password.
## User Dashboard
### Daily Briefing


- The user is greeted with the weather based on location services, their fully customized calendar, and a stream of news headlines.
- Users can add, edit and remove events at will.
- Users can add their preferred news sources to the user preferences page, allowing them to build a personalized news stream.
### Events & Places



- Events and Places lists are populated by information from the area that a user is in.
- Each item in the events list contains a link to purchase tickets to that events, information on the venue, and a button to add the event to your calendar in the Daily Briefing section.
- Each item in the Places list contains a link to the menu online, as well as average review score and a pricing index.
### Map


- Markers are placed on the map based on coordinates of the events and restaurants.
- When the red markers are clicked, a pop-up info window displays the ratings, pricing and distance of restaurants.
- When the blue markers are clicked, a pop-up info window displays name and distance of the event.
## Settings
### User Information


- Users can easily modify any of the information that is associated with their account through this simple form.
### User Preferences


- A user can add keywords to a list to be random selected to generate the background dynamically. If no values are entered, the keyword "space" is used.
- A user can select from a long list of news sources to populate their news stream.
<file_sep>/frontend/src/Components/Boards/Boards.js
import React from 'react';
import { BrowserRouter as Router, Route, Link } from 'react-router-dom';
function BoardList(props) {
return (
<Router>
<div className='boardlist'>
<ul>
<li>
<Link to='/boards/1'>Board 1</Link>
</li>
<li>
<Link to='/boards/2'>Board 2</Link>
</li>
<li>
<Link to='/boards/3'>Board 3</Link>
</li>
</ul>
{/* <Route path='/boards/1' component={Board_1} />
<Route path='/boards/2' component={Board_2} />
<Route path='/boards/3' component={Board_3} /> */}
</div>
</Router>
);
}
export default BoardList;
<file_sep>/server/seed.sql
insert into users
(name, email, password)
values
('lorenzo', '<EMAIL>', '<PASSWORD>'),
('lore', '<EMAIL>', <PASSWORD>');
insert into boards
(name, isDefault, user_id)
values
('board 1', true, 2),
('board 2', false, 2),
('board 3', false, 2);
insert into tiles
(name)
values
('notes'),
('todos'),
('weather'),
('CurrentsNews'),
('NYT'),
('Zomato'),
('SoundCloud'),
('TicketMaster'),
('Spotify'),
('Scores');
insert into board_tiles
(index, board_id, tile_id)
values
(1, 1, 1),
(2, 1, 2),
(3, 1, 3),
(4, 1, 4),
(1, 2, 5),
(2, 2, 6),
(3, 2, 7),
(4, 2, 8),
(1, 3, 4),
(2, 3, 3),
(3, 3, 1);
insert into preferences
(type)
values
('background'),
('news_source');
insert into user_preferences
(user_id, pref_id, term)
values
(2, 1, 'sky');
insert into events
(title, allDay, eventStart, eventEnd, description, user_id)
values
('Lunch Meeting', false, 'January 8, 2019 11:30:00', 'January 8, 2019 13:30:00', 'Lunch with John', 2),
('Sales Meeting', false, 'January 8, 2019 9:30:00', 'January 8, 2019 10:30:00', 'Meeting with new clients', 2),
('Sales Meeting', false, 'January 8, 2019 14:30:00', 'January 8, 2019 15:30:00', 'Meeting with new clients', 2),
('Sales Meeting', false, 'January 8, 2019 15:30:00', 'January 8, 2019 16:30:00', 'Meeting with new clients', 2),
('Staff Meeting', false, 'January 9, 2019 8:30:00', 'January 9, 2019 10:30:00', '', 2),
('Team Building Exercise', false, 'January 10, 2019 5:30:00', 'January 10, 2019 7:30:00', 'Team Workout', 2),
('Sales Event', false, 'January 11, 2019 9:30:00', 'January 11, 2019 12:30:00', 'Pitch meeting', 2),
('Lunch Meeting', false, 'January 12, 2019 11:30:00', 'January 12, 2019 13:30:00', 'Lunch with Marissa', 2),
('Lunch Meeting', false, 'January 14, 2019 11:30:00', 'January 14, 2019 13:30:00', 'Lunch with Jack', 2),
('Lunch Meeting', false, 'January 15, 2019 11:30:00', 'January 15, 2019 13:30:00', 'Lunch with John', 2),
('Sales Meeting', false, 'January 15, 2019 9:30:00', 'January 15, 2019 10:30:00', 'Meeting with new clients', 2),
('Sales Meeting', false, 'January 15, 2019 14:30:00', 'January 15, 2019 15:30:00', 'Meeting with new clients', 2),
('Sales Meeting', false, 'January 15, 2019 15:30:00', 'January 15, 2019 16:30:00', 'Meeting with new clients', 2),
('Staff Meeting', false, 'January 16, 2019 8:30:00', 'January 16, 2019 10:30:00', '', 2),
('Team Building Exercise', false, 'January 17, 2019 5:30:00', 'January 17, 2019 7:30:00', 'Team Workout', 2),
('Sales Event', false, 'January 18, 2019 9:30:00', 'January 18, 2019 12:30:00', 'Pitch meeting', 2),
('Lunch Meeting', false, 'January 18, 2019 11:30:00', 'January 18, 2019 13:30:00', 'Lunch with Marissa', 2),
('Lunch Meeting', false, 'January 21, 2019 11:30:00', 'January 21, 2019 13:30:00', 'Lunch with Jack', 2),
('Lunch Meeting', false, 'January 22, 2019 11:30:00', 'January 22, 2019 13:30:00', 'Lunch with John', 2),
('Sales Meeting', false, 'January 22, 2019 9:30:00', 'January 22, 2019 10:30:00', 'Meeting with new clients', 2),
('Sales Meeting', false, 'January 22, 2019 14:30:00', 'January 22, 2019 15:30:00', 'Meeting with new clients', 2),
('Sales Meeting', false, 'January 22, 2019 15:30:00', 'January 22, 2019 16:30:00', 'Meeting with new clients', 2),
('Staff Meeting', false, 'January 23, 2019 8:30:00', 'January 23, 2019 10:30:00', '', 2),
('Team Building Exercise', false, 'January 24, 2019 5:30:00', 'January 24, 2019 7:30:00', 'Team Workout', 2),
('Sales Event', false, 'January 25, 2019 9:30:00', 'January 25, 2019 12:30:00', 'Pitch meeting', 2),
('Lunch Meeting', false, 'January 25, 2019 11:30:00', 'January 25, 2019 13:30:00', 'Lunch with Marissa', 2),
('Lunch Meeting', false, 'January 26, 2019 11:30:00', 'January 26, 2019 13:30:00', 'Lunch with Jack', 2);
<file_sep>/frontend/src/Components/Boards/Board_1.js
import React, { Component, Suspense } from 'react';
const Calendar = React.lazy(() => import('../Tiles/Calendar'));
const Weather = React.lazy(() => import('../Tiles/Weather'));
// import { BrowserRouter as Router, Route, Link } from 'react-router-dom';
const News = React.lazy(() => import('../Tiles/News'));
function Board_1(props) {
return (
<div className="board">
<Suspense fallback={<div>Loading...</div>}>
<Weather weather={props.weather} icon={props.icon} />
</Suspense>
<Suspense fallback={<div>Loading...</div>}>
<Calendar
events={props.events.map(item => {
return {
id: item.id,
title: item.title,
allDay: item.allday,
start: new Date(item.eventstart),
end: new Date(item.eventend),
desc: item.description
};
})}
selectedEvent={props.selectedEvent}
modalIsOpen={props.modalIsOpen}
allDay={props.allDay}
term={props.term}
desc={props.desc}
start={props.start}
end={props.end}
displayEvent={props.displayEvent}
openModal={props.openModal}
afterOpenModal={props.afterOpenModal}
closeModal={props.closeModal}
onSlotChange={props.onSlotChange}
handleNewEvent={props.handleNewEvent}
handleDelete={props.handleDelete}
handleTitleChange={props.handleTitleChange}
handleDescChange={props.handleDescChange}
handleStartTime={props.handleStartTime}
handleEndTime={props.handleEndTime}
changeBox={props.changeBox}
/>
</Suspense>
<Suspense fallback={<div>Loading...</div>}>
<News
news={props.news}
handleNewsSearch={props.handleNewsSearch}
queryTerm={props.queryTerm}
handleQueryTerm={props.handleQueryTerm}
/>
</Suspense>
{/* Adjust news topics based on preferences either chosen or through machine learning */}
{/* Compound multiple sources to list */}
{/* Truth-meter ??? */}
{/* Calendar through Google API */}
{/* When you have a free night, suggest X or Y event */}
</div>
);
}
export default Board_1;
<file_sep>/frontend/src/Components/Boards/Board_3.js
import React, { Suspense } from 'react';
import Map from '../Tiles/Map';
function Board_3(props) {
return (
<div className="board mapBoard">
<Suspense fallback={<div>Loading...</div>}>
<Map
coords={props.coords}
restaurants={props.markers}
events={props.events.filter(item => {
if (item.venue) {
return item;
} else {
return null;
}
})}
/>
</Suspense>
{/* Mapping and transportation based on the weather. Machine learning to predict traffic */}
{/* Map incorporates restaurants and places to go. "I don't want to go farther than this from where I am" */}
</div>
);
}
export default Board_3;
<file_sep>/server/models/Board.js
const db = require('./db');
class Board {
constructor(name, isDefault) {
this.name = name;
this.isDefault = isDefault;
}
static addBoard(name, isDefault, user_id) {
return db
.one(
`insert into boards
(name, isDefault, user_id)
values
($1,$2,$3)
returning id`,
[name, isDefault, user_id]
)
.then(result => {
return new Board(result.id, name, isDefault, user_id);
});
}
static getByUser(user_id) {
return db.any(`select * from boards where user_id=$1`, [user_id]);
}
static getById(id) {
return db.one(`select * from boards where id=$1`, [id]);
}
static getDefaultBoard(user_id) {
return db.any(`select * from boards where user_id=$1 AND isDefault=true`, [
user_id
]);
}
static setDefaultBoard(user_id, board_id) {
return db.result(
`update boards
set isDefault=true
where user_id=$1
AND board_id=$2`,
[user_id, board_id]
);
}
static removeDefaultBoard(user_id, board_id) {
return db.result(
`update boards
set isDefault=false
where user_id=$1
AND board_id=$2`,
[user_id, board_id]
);
}
}
module.exports = Board;
<file_sep>/frontend/build/precache-manifest.c2d77beac6fe263b31cfd64c855771d6.js
self.__precacheManifest = [
{
"revision": "a94448c123f1abe39176",
"url": "/static/css/main.e4fa53a5.chunk.css"
},
{
"revision": "a94448c123f1abe39176",
"url": "/static/js/main.a94448c1.chunk.js"
},
{
"revision": "bfea61d0800149f4ffc7",
"url": "/static/js/1.bfea61d0.chunk.js"
},
{
"revision": "95c905c17933861cf65d",
"url": "/static/js/2.95c905c1.chunk.js"
},
{
"revision": "32c3bb5307854103d489",
"url": "/static/js/3.32c3bb53.chunk.js"
},
{
"revision": "7815fdf381ed42ccfa7e",
"url": "/static/js/4.7815fdf3.chunk.js"
},
{
"revision": "f8a249e7b2fccbe55b10",
"url": "/static/js/5.f8a249e7.chunk.js"
},
{
"revision": "38b5dc932412ef637031",
"url": "/static/js/6.38b5dc93.chunk.js"
},
{
"revision": "561ebc5b9f598ce7aba4",
"url": "/static/js/7.561ebc5b.chunk.js"
},
{
"revision": "1d199619d86979d3f1b8",
"url": "/static/js/8.1d199619.chunk.js"
},
{
"revision": "3083c677576dcc599fd4",
"url": "/static/js/9.3083c677.chunk.js"
},
{
"revision": "23e4184bba0e693d783f",
"url": "/static/js/10.23e4184b.chunk.js"
},
{
"revision": "6508693d6276b7b8af2c",
"url": "/static/css/11.f8f34164.chunk.css"
},
{
"revision": "6508693d6276b7b8af2c",
"url": "/static/js/11.6508693d.chunk.js"
},
{
"revision": "c6bbbf9fd579d1662c52",
"url": "/static/js/12.c6bbbf9f.chunk.js"
},
{
"revision": "fff5e27976da6fb5ac23",
"url": "/static/js/13.fff5e279.chunk.js"
},
{
"revision": "3c0745a56b5701607c23",
"url": "/static/js/14.3c0745a5.chunk.js"
},
{
"revision": "5b349fbef69cce81ed1a",
"url": "/static/js/runtime~main.5b349fbe.js"
},
{
"revision": "f04fc58f10ee0555d6728cbac90ba3c2",
"url": "/static/media/DSH_LOGO.f04fc58f.png"
},
{
"revision": "908a0081015f4b791b69e4d90b4796bc",
"url": "/static/media/rootBg.908a0081.jpeg"
},
{
"revision": "aa274fe098da5acfd0971e9f7d1d0248",
"url": "/index.html"
}
];<file_sep>/frontend/src/Components/Tiles/Zomato.js
import React from 'react';
function Zomato(props) {
return (
<div className="tile restoTile">
<h3>Places to eat</h3>
<ul className="restoList">
{props.restaurants.map((item, index) => {
return (
<li key={index}>
<h4>{item.name}</h4>
<div>
{`${item.location.address}, ${item.location.city}`}
<br />
{`Rating: ${item.avg_rating}/5`}
<br />
{`Pricing: ${item.price}/4`}
</div>
<a href={item.menu} target="_blank" rel="noreferrer noopener">
<button className="menuLink">Menu</button>
</a>
</li>
);
})}
</ul>
</div>
);
}
export default Zomato;
<file_sep>/frontend/src/Components/Tiles/Tickets.js
import React, { Component } from 'react';
import { LazyLoadImage } from 'react-lazy-load-image-component';
const eventTypes = ['Music', 'Sports'];
function displayVenue(item) {
if (item.venue !== undefined) {
return item.venue.name;
} else {
return null;
}
}
function Tickets(props) {
return (
<div className="tile eventTile">
<h3>Events</h3>
<ul className="eventType">
{eventTypes.map((item, index) => {
return (
<li
key={index}
onClick={event => {
props.handleEventType(item, event);
}}
>
<button>{item}</button>
</li>
);
})}
</ul>
<ul className="eventList">
{props.events.map((item, index) => {
return (
<li key={index}>
<LazyLoadImage
alt={item.name}
effect="blur"
src={item.img}
height="90px"
width="30%"
/>
<div className="eventText">
<a href={item.url} target="_blank" rel="norefferer noopener">
<h4>{item.name}</h4>
</a>
<div>
{item.date}
<br />
{displayVenue(item)}
</div>
<button
onClick={() => {
props.addToCalendar(item);
}}
>
Add to my Calendar
</button>
</div>
</li>
);
})}
</ul>
</div>
);
}
export default Tickets;
<file_sep>/frontend/src/Components/Settings/UserInfo.js
import React, { Component } from 'react';
function UserInfo(props) {
return (
<div className='settingsDiv tile'>
<h4>Adjust your information.</h4>
<form
className='settingsForm userInfo'
onSubmit={event => {
props.handleInfoSubmit(event);
}}
>
<label>
Name:
<br />
<input
type='text'
value={props.user.name}
onChange={event => {
props.handleNewName(event);
}}
placeholder='Name'
name='name'
/>
</label>
<label>
Email:
<br />
<input
type='email'
value={props.user.email}
onChange={event => {
props.handleNewEmail(event);
}}
placeholder='Email'
name='email'
/>
</label>
<label>
Current Password
<br />
<input type='password' placeholder='<PASSWORD>!' name='curPass' />
</label>
<label>
New Password:
<br />
<input type='password' placeholder='<PASSWORD>!' name='newPass' />
</label>
<label>
Confirm New Password:
<br />
<input
type='password'
placeholder='<PASSWORD>!'
name='confirmNewPass'
/>
</label>
<input type='submit' value='Save' className='saveBtn' />
</form>
</div>
);
}
export default UserInfo;
<file_sep>/frontend/src/Components/Tiles/Map.js
import React, { Component } from 'react';
import { Map, GoogleApiWrapper, InfoWindow, Marker } from 'google-maps-react';
import keys from '../../config';
import yourLocImg from '../../images/yourLocation.png';
import restoIcon from '../../images/restoIcon.png';
import eventIcon from '../../images/eventIcon.png';
function createStyles() {
const mapStyles = {
width: '90%',
height: '50%'
};
return mapStyles;
}
class MapContainer extends Component {
constructor(props) {
super(props);
this.state = {
showingInfoWindow: false,
activeMarker: {},
selectedPlace: {}
};
}
onMarkerClick(props, marker, e) {
this.setState({
selectedPlace: props,
activeMarker: marker,
showingInfoWindow: true
});
}
onClose(props) {
if (this.state.showingInfoWindow) {
this.setState({
showingInfoWindow: false,
activeMarker: null
});
}
}
foodOrShow(criteria) {
if (criteria === undefined) {
return (
<>
<h4>{this.state.selectedPlace.categories}</h4>
<h4>{this.state.selectedPlace.distance}</h4>
</>
);
} else {
return (
<>
<h6>{this.state.selectedPlace.categories}</h6>
<h5>{`Avg. Rating: ${this.state.selectedPlace.rating}/5`}</h5>
<h5>{`Pricing: ${this.state.selectedPlace.pricing}/4`}</h5>
</>
);
}
}
render() {
return (
<>
<ul className="mapLegend">
<li>
<button id="restoLegend" />
Restaurants
</li>
<li>
<button id="eventLegend" />
Events
</li>
</ul>
<Map
google={this.props.google}
zoom={14}
style={createStyles()}
initialCenter={{
lat: parseFloat(this.props.coords.lat),
lng: parseFloat(this.props.coords.long)
}}
>
<Marker
onClick={this.onMarkerClick.bind(this)}
name={'Current location'}
icon={{
url: yourLocImg
}}
/>
{this.props.restaurants.map((item, index) => {
return (
<Marker
key={index}
name={item.name}
categories={item.category}
rating={item.avg_rating}
pricing={item.price}
url={item.menu}
position={{
lat: parseFloat(item.location.latitude),
lng: parseFloat(item.location.longitude)
}}
onClick={this.onMarkerClick.bind(this)}
icon={{
url: restoIcon
}}
/>
);
})}
{this.props.events.map((item, index) => {
return (
<Marker
key={index}
name={item.name}
categories={item.date}
distance={`${item.distance} miles`}
url={item.url}
position={{
lat: parseFloat(item.venue.location.latitude),
lng: parseFloat(item.venue.location.longitude)
}}
onClick={this.onMarkerClick.bind(this)}
icon={{
url: eventIcon
}}
/>
);
})}
<InfoWindow
marker={this.state.activeMarker}
visible={this.state.showingInfoWindow}
onClose={this.onClose.bind(this)}
>
<div className="infoWindow">
<a
href={this.state.selectedPlace.url}
target="_blank"
rel="noreferrer noopener"
>
<h4>{this.state.selectedPlace.name}</h4>
</a>
{this.foodOrShow(this.state.selectedPlace.rating)}
</div>
</InfoWindow>
</Map>
</>
);
}
}
export default GoogleApiWrapper({
apiKey: keys.GOKEY
})(MapContainer);
<file_sep>/frontend/src/Components/Settings/SettingComp.js
import React, { Component } from 'react';
import { Route, Link } from 'react-router-dom';
import UserInfo from './UserInfo';
import UserPref from './UserPref';
// USER SHOULD BE ABLE TO:
// -- Adjust their info
// -- Adjust background pictures
// -- Add preffered news sources
function Settings(props) {
return (
<div className='settings'>
<div className='settingsLinks'>
<Link to='/home/settings/info'>
<button>User Information</button>
</Link>
<Link to='/home/settings/preferences'>
<button>User Preferences</button>
</Link>
</div>
<Route
path='/home/settings/info'
exact
render={routeProps => {
return (
<UserInfo
user={props.userInfo}
handleNewName={props.handleNewName}
handleInfoSubmit={props.handleInfoSubmit}
handleNewEmail={props.handleNewEmail}
{...routeProps}
/>
);
}}
/>
<Route
path='/home/settings/preferences'
render={routeProps => {
return (
<UserPref
preferences={props.preferences}
bgTerm={props.bgTerm}
newsTerm={props.newsTerm}
handleBgTermChange={props.handleBgTermChange}
handleNewsTermChange={props.handleNewsTermChange}
handleNewBackground={props.handleNewBackground}
handleNewsSource={props.handleNewsSource}
handlePrefDelete={props.handlePrefDelete}
{...routeProps}
/>
);
}}
/>
</div>
);
}
export default Settings;
<file_sep>/server/models/Events.js
const db = require('./db');
class Events {
constructor(id, title, allDay, eventStart, eventEnd, description) {
this.id = id;
this.title = title;
this.allDay = allDay;
this.eventStart = eventStart;
this.eventEnd = eventEnd;
this.description = description;
}
static addEvent(title, allDay, eventStart, eventEnd, description, user_id) {
return db
.one(
`insert into events
(title, allDay, eventStart, eventEnd, description, user_id)
values
($1, $2, $3, $4, $5, $6)
returning id`,
[title, allDay, eventStart, eventEnd, description, user_id]
)
.then(result => {
return new Events(
result.id,
title,
allDay,
eventStart,
eventEnd,
description
);
});
}
static getAll(user_id) {
return db.any(`select * from events where user_id=$1`, [user_id]);
}
static getById(id) {
return db.any(`select * from events where id=$1`, [id]);
}
static editEvent(title, allDay, description, user_id) {
return db.result(
`update events
set title=$1,
allDay=$2,
description=$3
where user_id=$4
`,
[title, allDay, description, user_id]
);
}
static deleteEvent(id) {
return db.result(`delete from events where id=$1`, [id]);
}
}
module.exports = Events;
<file_sep>/frontend/src/Components/Header.js
import React from 'react';
import { Link } from 'react-router-dom';
function Header(props) {
return (
<header>
<nav>
<li>
<Link to="/home/settings/info">
<button>Settings</button>
</Link>
</li>
<Link to="/home/dash1">
<img src={require('../images/DSH_LOGO.png')} />
</Link>
{/* <li>
<Link to='/boards'>Boards</Link>
</li> */}
<form method="POST" action="/api/logout">
<button type="submit" value="Log Out">
Log Out
</button>
</form>
</nav>
</header>
);
}
export default Header;
<file_sep>/server/schema.sql
-- Users have:
-- Name, email, pssword, accounts
-- Accounts: Github, Twitter, Facebook, Linkedin, Instagram, gmail
create table users (
id serial primary key,
name varchar(50) not null ,
email varchar(50) not null unique,
password varchar(100) not null
);
create table boards(
id serial primary key,
name text,
isDefault boolean,
user_id integer references users(id)
);
create table tiles(
id serial primary key,
name text,
content text
);
create table board_tiles(
id serial primary key,
index integer,
board_id integer references boards(id),
tile_id integer references tiles(id)
);
create table preferences(
id serial primary key,
type text,
value text
);
create table events(
id serial primary key,
title text,
allDay boolean,
eventStart timestamp,
eventEnd timestamp,
description text,
user_id integer references users(id)
);
create table user_preferences(
id serial primary key,
term text,
user_id integer references users(id),
pref_id integer references preferences(id)
);
-- create table accounts(
-- id serial primary key,
-- name text
-- );
-- Linking Tables
-- create table user_tiles(
-- id serial primary key,
-- index integer,
-- login text,
-- user_id integer references users(id),
-- tile_id integer references tiles(id)
-- );
-- create table user_accounts(
-- id serial primary key,
-- user_id integer references users(id),
-- account_id integer references accounts(id)
-- );<file_sep>/frontend/src/Components/Landing/Login.js
import React from 'react';
function Login(props) {
return (
<form
onSubmit={item => {
props.handleLogin(item);
}}
className="landingForm"
>
<label>
Email:
<br />
<input
type="email"
placeholder="<EMAIL>"
name="email"
value={props.loginEmail}
onChange={event => {
props.handleLoginChange(event);
}}
/>
</label>
<label>
Password:
<br />
<input
type="<PASSWORD>"
placeholder="<PASSWORD>"
name="password"
value={props.loginPass}
onChange={event => {
props.handlePassChange(event);
}}
/>
</label>
<button type="submit" className="logRegBtn">
Log in
</button>
<p className="errorMsg">{props.error}</p>
</form>
);
}
export default Login;
<file_sep>/server/models/Tiles.js
const db = require('./db');
class Tile {
constructor(name) {
this.name = name;
}
static getByBoard(board_id) {
return db.any(
`select * from board_tiles b
inner join tiles t
on b.tile_id = t.id
where b.board_id=$1 `,
[board_id]
);
}
}
module.exports = Tile;
<file_sep>/frontend/src/Components/HomeComp/Home.js
import React, { Component, Suspense } from 'react';
import { Route, NavLink, Switch } from 'react-router-dom';
import SwipeableRoutes from 'react-swipeable-routes';
import moment from 'moment';
import keys from '../../config';
// import day from '../../images/weather_icons/animated/day.svg';
// import cloudy from '../../images/weather_icons/animated/cloudy.svg';
// import rainyDay from '../../images/weather_icons/animated/rainy-3.svg';
// import rainy from '../../images/weather_icons/animated/rainy-6.svg';
// import snow from '../../images/weather_icons/animated/snowy-6.svg';
// import thunder from '../../images/weather_icons/animated/thunder.svg';
const Settings = React.lazy(() => import('../Settings/SettingComp'));
const Header = React.lazy(() => import('../Header'));
const Board_1 = React.lazy(() => import('../Boards/Board_1'));
const Board_2 = React.lazy(() => import('../Boards/Board_2'));
const Board_3 = React.lazy(() => import('../Boards/Board_3'));
function createBackSplash(url) {
const style = {
backgroundImage: `url(${url})`,
backgroundSize: `cover`,
backgroundPosition: `center`,
backgroundAttachment: `fixed`
};
return style;
}
function weatherIcon(string) {
switch (string) {
case 'clear sky':
return '/images/weather_icons/animated/day.svg';
case 'few clouds':
return '/images/weather_icons/animated/cloudy.svg';
case 'scattered clouds':
return '/images/weather_icons/animated/cloudy.svg';
case 'broken clouds':
return '/images/weather_icons/animated/cloudy.svg';
case 'shower rain':
return '/images/weather_icons/animated/rainy-6.svg';
case 'rain':
return '/images/weather_icons/animated/rainy-3.svg';
case 'thunderstorm':
return '/images/weather_icons/animated/thunder.svg';
case 'snow':
return '/images/weather_icons/animated/snowy-6.svg';
case 'mist':
return '/images/weather_icons/animated/cloudy.svg';
default:
return '/images/weather_icons/animated/cloudy.svg';
}
}
function getWeather(object) {
let location = {
lat: object.coords.latitude.toFixed(4),
long: object.coords.longitude.toFixed(4)
};
console.log(location);
fetch(
`https://api.openweathermap.org/data/2.5/weather?lat=${location.lat}&lon=${
location.long
}&apikey=${keys.OWKEY}`
)
.then(r => r.json())
.then(result => {
let weather = {
temp: `Temperature: ${(
((result.main.temp - 273.15) * 9) / 5 +
32
).toFixed(2)} °F`,
high_low: `High: ${(
((result.main.temp_max - 273.15) * 9) / 5 +
32
).toFixed(2)} °F Low: ${(
((result.main.temp_min - 273.15) * 9) / 5 +
32
).toFixed(2)} °F`,
// low: `Low: ${(((result.main.temp_min - 273.15) * 9) / 5 + 32).toFixed(
// 2
// )} °F`,
hum: `Humidity: ${result.main.humidity} %`
};
this.setState({
coords: { lat: location.lat, long: location.long },
board1: {
...this.state.board1,
weather: weather,
weatherIcon: weatherIcon(result.weather[0].description)
}
});
});
return location;
}
function getRestInfo(object) {
let location = {
lat: object.coords.latitude.toFixed(4),
long: object.coords.longitude.toFixed(4)
};
fetch(
`https://developers.zomato.com/api/v2.1/geocode?lat=${location.lat}&lon=${
location.long
}&apikey=${keys.ZOMKEY}`
)
.then(r => r.json())
.then(result => {
let place = {
entity_id: result.location.entity_id,
entity_type: result.location.entity_type
};
let nearbyArray = result.nearby_restaurants.map(item => {
return {
id: item.restaurant.id,
name: item.restaurant.name,
location: item.restaurant.location,
category: item.restaurant.cuisines,
price: item.restaurant.price_range,
avg_rating: item.restaurant.user_rating.aggregate_rating,
menu: item.restaurant.menu_url
};
});
fetch(
`https://developers.zomato.com/api/v2.1/location_details?entity_id=${
place.entity_id
}&entity_type=${place.entity_type}&apikey=${keys.ZOMKEY}`
)
.then(r => r.json())
.then(result_2 => {
let bestArray = result_2.best_rated_restaurant.map(item => {
return {
id: item.restaurant.id,
name: item.restaurant.name,
location: item.restaurant.location,
category: item.restaurant.cuisines,
price: item.restaurant.price_range,
avg_rating: item.restaurant.user_rating.aggregate_rating,
menu: item.restaurant.menu_url
};
});
let filteredArray = nearbyArray.filter(val =>
bestArray.includes(val)
);
let restoArray = bestArray.concat(filteredArray);
console.log(restoArray);
this.setState({
board2: {
...this.state.board2,
restaurants: restoArray
}
});
});
});
}
function getEvents(object) {
let date = `${moment(new Date().toLocaleDateString('en-US')).format(
'YYYY-MM-DD'
)}T00:00:00Z`;
console.log(date);
let location = {
lat: object.coords.latitude.toFixed(4),
long: object.coords.longitude.toFixed(4)
};
fetch(
`https://app.ticketmaster.com/discovery/v2/events.json?&latlong=${
location.lat
},${
location.long
}&radius=20&unit=miles&size=50&startDateTime=${date}&includeTBD=no&classificationName=${
this.state.board2.category
}&sort=date,asc&apikey=${keys.TMKEY}`
)
.then(r => r.json())
.then(result => {
console.log(result);
let newArray = result._embedded.events.map(event => {
if (event.classifications[0].subGenre) {
return {
name: event.name,
img: event.images[8].url,
url: event.url,
date: event.dates.start.localDate,
time: event.dates.start.localTime,
distance: event.distance,
type: event.classifications[0].segment.name,
genre: event.classifications[0].subGenre.name,
venue: event._embedded.venues[0]
};
} else {
return {
name: event.name,
img: event.images[5].url,
url: event.url,
date: event.dates.start.localDate,
time: event.dates.start.localTime,
distance: event.distance,
type: event.classifications[0].segment.name,
venue: event._embedded.venues[0]
};
}
});
this.setState({
board2: { ...this.state.board2, events: newArray }
});
});
}
class Home extends Component {
constructor(props) {
super(props);
this.state = {
coords: {},
tiles: [],
userInfo: {},
userPreferences: {
bgTerm: '',
newsTerm: '',
array: []
},
bgQuery: '',
newsQuery: '',
bgUrl: '',
board1: {
tiles: [],
weather: {},
weatherIcon: '',
news: {
articles: [],
queryTerm: ''
},
calendar: {
selectedEvent: {},
modalIsOpen: false,
term: '',
desc: ' ',
start: '',
end: '',
allDay: false,
events: []
}
},
board2: {
tiles: [],
events: [],
category: 'music',
restaurants: []
},
board3: {
tiles: []
}
};
}
componentDidMount() {
fetch('/api/preferences')
.then(r => r.json())
.then(result => {
let prefArray = result.map(item => {
return { id: item.id, term: item.term, type: item.type };
});
this.setState(
{
userPreferences: {
...this.state.userPreferences,
array: prefArray
}
},
() => {
let bg_query;
let news_query;
if (this.state.userPreferences.array.length === 0) {
bg_query = 'space';
news_query = `country=us`;
} else {
let bgArray = this.state.userPreferences.array
.filter(item => {
return item.type === 'background';
})
.map(object => {
return object.term;
});
let newsArray = this.state.userPreferences.array
.filter(item => {
return item.type === 'news_source';
})
.map(object => {
return object.term;
});
if (bgArray.length === 1 && newsArray.length === 0) {
bg_query = bgArray[0];
news_query = `country=us`;
} else if (bgArray.length === 0 && newsArray.length === 1) {
bg_query = 'space';
news_query = `sources=${newsArray[0]}`;
} else if (bgArray.length === 0 && newsArray.length > 1) {
news_query = `sources=${newsArray.map(item => {
return `${item}`;
})}`;
bg_query = 'space';
} else if (bgArray.length === 1 && newsArray.length === 1) {
bg_query = bgArray[0];
news_query = `sources=${newsArray[0]}`;
} else if (bgArray.length === 1 && newsArray.length > 1) {
bg_query = bgArray[0];
news_query = `sources=${newsArray.map(item => {
return `${item}`;
})}`;
} else if (bgArray.length === 0 && newsArray.length > 1) {
bg_query = 'space';
news_query = `sources=${newsArray.map(item => {
return `${item}`;
})}`;
} else if (bgArray.length > 1 && newsArray.length === 0) {
let ranNum = Math.floor(Math.random() * bgArray.length);
bg_query = bgArray[ranNum];
news_query = 'country=us';
} else {
let ranNum = Math.floor(Math.random() * bgArray.length);
news_query = `sources=${newsArray.map(item => {
return `${item}`;
})}`;
bg_query = bgArray[ranNum];
}
}
this.setState(
{
bgQuery: bg_query,
newsQuery: news_query
},
() => {
fetch(
`https://api.unsplash.com/search/photos?query=${
this.state.bgQuery
}&client_id=${keys.USKEY}`
)
.then(r => r.json())
.then(object => {
console.log(object);
let ranNum = Math.floor(Math.random() * 9);
fetch(
`https://newsapi.org/v2/top-headlines?${
this.state.newsQuery
}&apiKey=${keys.NEWSKEY}`
)
.then(r => r.json())
.then(result => {
console.log(result);
let newArray = result.articles.map(item => {
return {
source: item.source.name,
title: item.title,
url: item.url,
description: item.description
};
});
this.setState({
board1: {
...this.state.board1,
news: {
...this.state.board1.news,
articles: newArray
}
},
bgUrl: object.results[ranNum].urls.regular
});
});
});
}
);
}
);
});
if ('geolocation' in navigator) {
navigator.geolocation.getCurrentPosition(getWeather.bind(this));
navigator.geolocation.getCurrentPosition(getRestInfo.bind(this));
navigator.geolocation.getCurrentPosition(getEvents.bind(this));
} else {
let object = {
coords: {
latitude: 34,
longitude: -84
}
};
getWeather(object);
getRestInfo(object);
getEvents(object);
}
// home component with boards and tiles
fetch('/api/events')
.then(result => result.json())
.then(array => {
this.setState({
board1: {
...this.state.board1,
calendar: {
...this.state.board1.calendar,
events: array
}
}
});
});
fetch('/api/settings')
.then(r => r.json())
.then(object => {
this.setState({
userInfo: object
});
});
}
handleEventType(item) {
let date = `${moment(new Date().toLocaleDateString('en-US')).format(
'YYYY-MM-DD'
)}T00:00:00Z`;
this.setState(
{
board2: {
...this.state.board2,
category: item
}
},
() => {
fetch(
`https://app.ticketmaster.com/discovery/v2/events.json?&latlong=${
this.state.coords.lat
},${
this.state.coords.long
}&radius=20&unit=miles&size=50&startDateTime=${date}&includeTBD=no&classificationName=${
this.state.board2.category
}&sort=date,asc&apikey=${keys.TMKEY}`
)
.then(r => r.json())
.then(result => {
let newArray = result._embedded.events.map(event => {
if (event._embedded.venues[0] && event.classifications[0].genre) {
return {
name: event.name,
img: event.images[8].url,
url: event.url,
date: event.dates.start.localDate,
time: event.dates.start.localTime,
type: event.classifications[0].segment.name,
genre: event.classifications[0].genre.name,
venue: event._embedded.venues[0]
};
} else if (
event._embedded.venues[0] &&
!event.classifications[0].genre
) {
return {
name: event.name,
img: event.images[8].url,
url: event.url,
date: event.dates.start.localDate,
time: event.dates.start.localTime,
type: event.classifications[0].segment.name,
venue: event._embedded.venues[0]
};
} else {
return {
name: event.name,
img: event.images[0].url,
url: event.url,
date: event.dates.start.localDate,
time: event.dates.start.localTime,
type: event.classifications[0].segment.name
};
}
});
this.setState({
board2: { ...this.state.board2, events: newArray }
});
});
}
);
}
displayEvent(event) {
console.log(event.id);
const newEvent = {
id: event.id,
title: event.title,
allDay: event.allDay,
start: moment(event.start.toLocaleString()).format('MM-DD-YYYY HH:mm:ss'),
end: moment(event.end.toLocaleString()).format('MM-DD-YYYY HH:mm:ss'),
desc: event.desc
};
console.log(newEvent);
this.setState(
{
board1: {
...this.state.board1,
calendar: {
...this.state.board1.calendar,
selectedEvent: newEvent,
term: newEvent.title,
desc: newEvent.desc,
start: newEvent.start,
end: newEvent.end
}
}
},
this.openModal
);
}
openModal() {
this.setState({
board1: {
...this.state.board1,
calendar: {
...this.state.board1.calendar,
modalIsOpen: true
}
}
});
}
afterOpenModal() {
console.log('opened');
}
closeModal() {
this.setState({
board1: {
...this.state.board1,
calendar: {
...this.state.board1.calendar,
modalIsOpen: false,
selectedEvent: {},
term: '',
desc: ''
}
}
});
}
onSlotChange(slotInfo) {
const startDate = moment(slotInfo.start.toLocaleString()).format(
'MM-DD-YYYY HH:mm:ss'
);
const endDate = moment(slotInfo.end.toLocaleString()).format(
'MM-DD-YYYY HH:mm:ss'
);
const newEvent = {
title: this.state.board1.calendar.term,
allDay: false,
start: startDate,
end: endDate,
description: this.state.board1.calendar.desc
};
this.setState({
board1: {
...this.state.board1,
calendar: {
...this.state.board1.calendar,
selectedEvent: newEvent,
start: newEvent.start,
end: newEvent.end
}
}
});
this.openModal();
}
handleNewEvent(event) {
event.preventDefault();
const newEvent = {
id: this.state.board1.calendar.selectedEvent.id,
title: this.state.board1.calendar.term,
allDay: this.state.board1.calendar.allDay,
start: this.state.board1.calendar.start,
end: this.state.board1.calendar.end,
description: this.state.board1.calendar.desc
};
console.log(newEvent);
fetch('/api/events/new', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(newEvent)
})
.then(r => r.json())
.then(result => {
console.log(result);
const addEvent = {
id: result.id,
title: result.title,
allday: result.allDay,
eventstart: result.eventStart,
eventend: result.eventEnd,
description: result.description
};
this.setState(
{
board1: {
...this.state.board1,
calendar: {
...this.state.board1.calendar,
events: [...this.state.board1.calendar.events, addEvent],
selectedEvent: {}
}
}
},
this.closeModal
);
});
}
handleDelete(e) {
e.preventDefault();
fetch(`/api/events/${this.state.board1.calendar.selectedEvent.id}/delete`, {
method: 'POST'
})
.then(r => r.json())
// .then(console.log);
.then(res => {
let newEvents = this.state.board1.calendar.events.filter(event => event.id !== res);
this.setState({
board1: {
...this.state.board1,
calendar: {
...this.state.board1.calendar,
events: newEvents,
selectedEvent: {}
}
}
});
});
this.closeModal();
}
handleTitleChange(event) {
this.setState({
board1: {
...this.state.board1,
calendar: {
...this.state.board1.calendar,
term: event.target.value
}
}
});
}
handleDescChange(event) {
this.setState({
board1: {
...this.state.board1,
calendar: {
...this.state.board1.calendar,
desc: event.target.value
}
}
});
}
handleStartTime(event) {
this.setState({
board1: {
...this.state.board1,
calendar: {
...this.state.board1.calendar,
start: event.target.value
}
}
});
}
handleEndTime(event) {
this.setState({
board1: {
...this.state.board1,
calendar: {
...this.state.board1.calendar,
end: event.target.value
}
}
});
}
changeBox(event) {
this.setState({
board1: {
...this.state.board1,
calendar: {
...this.state.board1.calendar,
allDay: event.target.checked
}
}
});
}
handleQueryTerm(event) {
this.setState({
board1: {
...this.state.board1,
news: {
...this.state.board1.news,
queryTerm: event.target.value
}
}
});
console.log(event.target.value);
}
// NEWS QUERY
handleNewsSearch(event) {
event.preventDefault();
if (this.state.board1.news.queryTerm) {
fetch(
`https://newsapi.org/v2/top-headlines?q=${
this.state.board1.news.queryTerm
}&apiKey=${keys.NEWSKEY}`
)
.then(r => r.json())
.then(result => {
console.log(result);
let newArray = result.articles.map(item => {
return {
source: item.source.name,
title: item.title,
url: item.url,
description: item.description
};
});
this.setState({
board1: {
...this.state.board1,
news: {
...this.state.board1.news,
articles: newArray
}
}
});
});
} else {
return null;
}
}
// SETTINGS COMPONENT
handleNewName(event) {
this.setState({
userInfo: {
...this.state.userInfo,
name: event.target.value
}
});
}
handleNewEmail(event) {
this.setState({
userInfo: {
...this.state.userInfo,
email: event.target.value
}
});
}
handleInfoSubmit(event) {
event.preventDefault();
if (
event.target.newPass.value.length >= 8 &&
event.target.newPass.value === event.target.confirmNewPass.value
) {
const infoObject = {
name: event.target.name.value,
email: event.target.email.value,
password: event.target.curPass.value,
newPass: event.target.newPass.value
};
fetch('/api/settings/info', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(infoObject)
})
.then(r => r.json())
.then(result => {
this.setState({
userInfo: result
});
});
} else {
const infoObject = {
name: event.target.name.value,
email: event.target.email.value,
password: <PASSWORD>.target.cur<PASSWORD>.value
};
fetch('/api/settings/info', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(infoObject)
})
.then(r => r.json())
.then(result => {
this.setState({
userInfo: result
});
});
}
}
handleBgTermChange(event) {
this.setState({
userPreferences: {
...this.state.userPreferences,
bgTerm: event.target.value
}
});
}
handleNewsTermChange(event) {
this.setState({
userPreferences: {
...this.state.userPreferences,
newsTerm: event.target.value
}
});
}
handleNewBackground(event) {
event.preventDefault();
if (this.state.userPreferences.bgTerm !== '') {
let object = {
id: 1,
value: this.state.userPreferences.bgTerm,
type: 'background'
};
fetch('/api/preferences', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(object)
})
.then(r => r.json())
.then(result => {
this.setState({
userPreferences: {
...this.state.userPreferences,
array: [...this.state.userPreferences.array, result]
}
});
});
}
}
handleNewsSource(event) {
event.preventDefault();
console.log(event.select);
if (this.state.userPreferences.newsTerm !== '') {
let object = {
id: 2,
value: this.state.userPreferences.newsTerm,
type: 'news_source'
};
fetch('/api/preferences', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(object)
})
.then(r => r.json())
.then(result => {
this.setState({
userPreferences: {
...this.state.userPreferences,
array: [...this.state.userPreferences.array, result]
}
});
});
}
}
handlePrefDelete(item) {
console.log(item);
let index = this.state.userPreferences.array.indexOf(item);
let array = this.state.userPreferences.array;
console.log(index);
array.splice(index, 1);
fetch(`/api/preferences/${item.id}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
}
}).then(result => {
console.log(result);
this.setState({
userPreferences: {
...this.state.userPreferences,
array: this.state.userPreferences.array.filter(
pref => pref.id !== item.id
)
}
});
});
}
addToCalendar(item) {
console.log(item);
const newEvent = {
title: item.name,
allDay: false,
start: `${item.date} ${item.time}`,
end: `${item.date} 23:59:00`,
description: `Genre: ${item.genre}, Venue: ${item.venue.name}`
};
console.log(newEvent);
fetch('/api/events/new', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(newEvent)
})
.then(r => r.json())
.then(result => {
console.log(result);
const addEvent = {
id: result.id,
title: result.title,
allday: result.allDay,
eventstart: result.eventStart,
eventend: result.eventEnd,
description: result.description
};
this.setState(
{
board1: {
...this.state.board1,
calendar: {
...this.state.board1.calendar,
events: [...this.state.board1.calendar.events, addEvent],
selectedEvent: {}
}
}
},
this.closeModal
);
});
}
render() {
return (
<>
<Suspense fallback={<div>Loading...</div>}>
<Header />
<div className="home" style={createBackSplash(this.state.bgUrl)}>
<ul className="navList">
<li>
<NavLink
activeStyle={{
borderBottom: '1px solid white',
paddingBottom: '3px'
}}
to="/home/dash1"
>
Daily Briefing
</NavLink>
</li>
<li>
<NavLink
activeStyle={{
borderBottom: '1px solid white',
paddingBottom: '3px'
}}
to="/home/dash2"
>
Events & Places
</NavLink>
</li>
<li>
<NavLink
activeStyle={{
borderBottom: '1px solid white',
paddingBottom: '3px'
}}
to="/home/dash3"
>
Map
</NavLink>
</li>
</ul>
<Switch>
<SwipeableRoutes>
<Route
path="/home/settings/info"
render={props => {
return (
<Settings
userInfo={this.state.userInfo}
preferences={this.state.userPreferences.array}
bgTerm={this.state.userPreferences.bgTerm}
newsTerm={this.state.userPreferences.newsTerm}
handleBgTermChange={this.handleBgTermChange.bind(this)}
handleNewsTermChange={this.handleNewsTermChange.bind(
this
)}
handleNewBackground={this.handleNewBackground.bind(
this
)}
handleNewsSource={this.handleNewsSource.bind(this)}
handleNewName={this.handleNewName.bind(this)}
handleNewEmail={this.handleNewEmail.bind(this)}
handleInfoSubmit={this.handleInfoSubmit.bind(this)}
handlePrefDelete={this.handlePrefDelete.bind(this)}
{...props}
/>
);
}}
/>
<Route
path="/home/dash1"
render={props => {
return (
<Suspense fallback={<div>Loading...</div>}>
<Board_1
weather={this.state.board1.weather}
icon={this.state.board1.weatherIcon}
news={this.state.board1.news.articles}
events={this.state.board1.calendar.events}
allDay={this.state.board1.calendar.allDay}
selectedEvent={
this.state.board1.calendar.selectedEvent
}
modalIsOpen={this.state.board1.calendar.modalIsOpen}
term={this.state.board1.calendar.term}
desc={this.state.board1.calendar.desc}
start={this.state.board1.calendar.start}
end={this.state.board1.calendar.end}
displayEvent={this.displayEvent.bind(this)}
openModal={this.openModal.bind(this)}
afterOpenModal={this.afterOpenModal.bind(this)}
closeModal={this.closeModal.bind(this)}
onSlotChange={this.onSlotChange.bind(this)}
handleNewEvent={this.handleNewEvent.bind(this)}
handleDelete={this.handleDelete.bind(this)}
handleTitleChange={this.handleTitleChange.bind(this)}
handleDescChange={this.handleDescChange.bind(this)}
handleStartTime={this.handleStartTime.bind(this)}
handleEndTime={this.handleEndTime.bind(this)}
changeBox={this.changeBox.bind(this)}
handleNewsSearch={this.handleNewsSearch.bind(this)}
queryTerm={this.state.board1.news.queryTerm}
handleQueryTerm={this.handleQueryTerm.bind(this)}
{...props}
/>
</Suspense>
);
}}
/>
<Route
path="/home/dash2"
render={props => {
return (
<Suspense fallback={<div>Loading...</div>}>
<Board_2
events={this.state.board2.events}
{...props}
addToCalendar={this.addToCalendar.bind(this)}
handleEventType={this.handleEventType.bind(this)}
restaurants={this.state.board2.restaurants}
/>
</Suspense>
);
}}
/>
<Route
path="/home/dash3"
render={props => {
return (
<Suspense fallback={<div>Loading...</div>}>
<Board_3
coords={this.state.coords}
markers={this.state.board2.restaurants}
events={this.state.board2.events}
{...props}
/>
</Suspense>
);
}}
/>
</SwipeableRoutes>
</Switch>
</div>
</Suspense>
</>
);
}
}
export default Home;
<file_sep>/server/models/Preferences.js
const db = require('./db');
class Preferences {
constructor(id, term, type) {
this.id = id;
this.term = term;
this.type = type;
}
// CRUD
static addPref(user_id, pref_id, term, type) {
return db
.one(
`insert into user_preferences
(user_id, pref_id, term)
values
($1, $2, $3)
returning id`,
[user_id, pref_id, term]
)
.then(data => {
return new Preferences(data.id, term, type);
});
}
static getPref(user_id) {
return db.any(
`select u.id, u.term, p.type from
user_preferences u
inner join preferences p
on u.pref_id = p.id
where u.user_id=$1`,
[user_id]
);
}
static removePref(id) {
return db.result(`delete from user_preferences where id=$1`, [id]);
}
}
module.exports = Preferences;
<file_sep>/frontend/src/Components/Landing/Register.js
import React from 'react';
function Register(props) {
return (
<form
onSubmit={item => {
props.handleRegister(item);
}}
className="landingForm"
>
<label>
Name:
<br />
<input
type="text"
placeholder="<NAME>"
name="name"
value={props.regName}
onChange={event => {
props.handleRegNameChange(event);
}}
/>
</label>
<label>
Email:
<br />
<input
type="email"
placeholder="<EMAIL>"
name="email"
value={props.regEmail}
onChange={event => {
props.handleRegEmailChange(event);
}}
/>
</label>
<label>
Password:
<br />
<input
type="<PASSWORD>"
placeholder="<PASSWORD>"
name="password"
value={props.regPass}
onChange={event => {
props.handleRegPassChange(event);
}}
/>
</label>
<label>
Confirm password:
<br />
<input
type="<PASSWORD>"
placeholder="<PASSWORD>"
name="confirmPassword"
value={props.regPassConf}
onChange={event => {
props.handleRegPassConfChange(event);
}}
/>
</label>
<button type="submit" className="logRegBtn">
Sign Up
</button>
<p className="errorMsg">{props.error}</p>
</form>
);
}
export default Register;
<file_sep>/server/models/User.js
const db = require('./db');
const bcrypt = require('bcrypt');
const saltRounds = 10;
class User {
constructor(id, name, email, password) {
this.id = id;
this.name = name;
this.email = email;
this.password = <PASSWORD>;
}
static addUser(name, email, password) {
const salt = bcrypt.genSaltSync(saltRounds);
const hash = bcrypt.hashSync(password, salt);
return db
.one(
`insert into users(name, email, password)
values
($1, $2, $3)
returning id`,
[name, email, hash]
)
.then(result => {
return new User(result.id, name, email, hash);
});
}
static getUserById(id) {
return db.one(`select * from users where id=$1`, [id]).then(result => {
return new User(result.id, result.name, result.email, result.password);
});
}
static getByEmail(email) {
return db
.one(`select * from users where email=$1`, [email])
.then(result => {
return new User(result.id, result.name, result.email, result.password);
});
}
checkPassword(password) {
return bcrypt.compareSync(password, this.password);
}
updateName(newName) {
return db.result(
`update users
set name=$1
where id=$2`,
[newName, this.id]
);
}
updateEmail(newEmail) {
return db.result(
`update users
set email=$1
where id=$2`,
[newEmail, this.id]
);
}
updatePass(newPass) {
const salt = bcrypt.genSaltSync(saltRounds);
const hash = bcrypt.hashSync(newPass, salt);
return db.result(
`update users
set password=$1
where id=$2`,
[hash, this.id]
);
}
}
module.exports = User;
<file_sep>/frontend/src/Components/Landing/Root.js
import React, { Component } from 'react';
import {
BrowserRouter as Router,
Route,
Link,
Redirect
} from 'react-router-dom';
import Login from './Login';
import Register from './Register';
class Root extends Component {
constructor(props) {
super(props);
this.state = {
loginEmail: '',
loginPass: '',
regName: '',
regEmail: '',
regPass: '',
regPassConf: '',
isLoggedIn: '',
loginError: '',
regError: ''
};
}
handleLoginChange(event) {
this.setState({
loginEmail: event.target.value
});
}
handlePassChange(event) {
this.setState({
loginPass: event.target.value
});
}
handleRegNameChange(event) {
this.setState({
regName: event.target.value
});
}
handleRegEmailChange(event) {
this.setState({
regEmail: event.target.value
});
}
handleRegPassChange(event) {
this.setState({
regPass: event.target.value
});
}
handleRegPassConfChange(event) {
this.setState({
regPassConf: event.target.value
});
}
handleRegister(item) {
console.log(item);
item.preventDefault();
const logObject = {
name: this.state.regName,
email: this.state.regEmail,
password: this.state.regPass
};
if (this.state.regPass === this.state.regPassConf) {
fetch('/api/register', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(logObject)
})
.then(r => r.json())
.then(result => {
if (result) {
this.setState({
isLoggedIn: true
});
}
});
} else {
this.setState({
regError: 'Passwords did not match.'
});
}
}
handleLogin(item) {
item.preventDefault();
const logObject = {
email: this.state.loginEmail,
password: this.state.loginPass
};
fetch('/api/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(logObject)
})
.then(r => r.json())
.then(result => {
if (result) {
this.setState({
isLoggedIn: result
});
} else {
this.setState({
loginError: 'Email address or password were incorrect.'
});
}
});
}
render() {
if (this.state.isLoggedIn) {
return <Redirect to="/home/dash1" />;
} else {
return (
<Router>
<div className="landing">
<div className="loginReg">
<img src={require('../../images/DSH_LOGO.png')} />
<ul>
<li>
<Link to="/login"> Log in </Link>
</li>
<li>
<Link to="/register"> Register </Link>
</li>
</ul>
<Route
path="/login"
render={routerProps => {
return (
<Login
handleLogin={this.handleLogin.bind(this)}
error={this.state.loginError}
loginEmail={this.state.loginEmail}
loginPass={<PASSWORD>}
handleLoginChange={this.handleLoginChange.bind(this)}
handlePassChange={this.handlePassChange.bind(this)}
{...routerProps}
/>
);
}}
/>
<Route
path="/register"
render={routerProps => {
return (
<Register
handleRegister={this.handleRegister.bind(this)}
error={this.state.regError}
regName={this.state.regName}
regEmail={this.state.regEmail}
regPass={this.state.regPass}
regPassConf={this.state.regPassConf}
handleRegNameChange={this.handleRegNameChange.bind(this)}
handleRegEmailChange={this.handleRegEmailChange.bind(
this
)}
handleRegPassChange={this.handleRegPassChange.bind(this)}
handleRegPassConfChange={this.handleRegPassConfChange.bind(
this
)}
{...routerProps}
/>
);
}}
/>
</div>
<footer>
<ul>
<li>
<a
title="Email"
href="mailto:<EMAIL>"
target="_blank"
rel="noopener noreferrer"
>
<img src={require('../../images/emailIcon.png')} />
</a>
</li>
<li>
<a
title="Portfolio"
href="https://www.lorenzosalvio.com"
target="_blank"
rel="noopener noreferrer"
>
<img src={require('../../images/websiteIcon.png')} />
</a>
</li>
<li>
<a
title="GitHub"
href="https://www.github.com/salviolorenzo"
target="_blank"
rel="noopener noreferrer"
>
<img src={require('../../images/gitIcon.png')} />
</a>
</li>
</ul>
<p> Built by <NAME> </p>
</footer>
</div>
</Router>
);
}
}
}
export default Root;
|
6e85d6722097a62a010dd06167b8e28460ee7c6e
|
[
"JavaScript",
"SQL",
"Markdown"
] | 24
|
JavaScript
|
salviolorenzo/capstone
|
39e425ced03e45153e48b076d973bbc4c42a4e5f
|
4c19cd0167bfaa7bf56b4fde0cffd4817d81605e
|
refs/heads/master
|
<file_sep># CHANGELOG.md
## (0.3.2)
Features:
- Fixes in injection process. Custom scope is processing properly now
## (0.3.1)
Features:
- Added FInject class which allow for inline injections if you really need it. In this case variants of same type has to be selected manually
- Added DiState class which extends State class for translarent injection inside state class
IMPORTANT You need do keep State class public. In that way fields can be accessed be generated code
## (0.3.0)
Features:
- Added disposability for
## (0.2.0)
Breaking Changes:
- Added new method of injecting class which are annotated with @immutable. Now you can use manualInjecting in context of buildMethod
## (0.1.4)
Breaking Changes:
- Use FinjectHost class instead of InjectHost class.
Features:
- Separation of scoping and injection
## (0.1.2)
Features:
- Injecting with constructor
- Injecting with fields
- Injecting with factory class
- Scoped Singleton
- Custom scopes
- Hierarchcal Search down the tree of widgets
- Named injections<file_sep># CHANGELOG.md
## (0.3.3)
- Some dependency changes
## (0.3.2)
Features:
- Added graph validation in code generation process
Other:
- Added some tests
## (0.3.1)
- If Injectable class has only one constructor there is no need for annotating it with Inject()
## (0.3.0)
- Performance improvements
- Version up
## (0.2.2)
Features:
- Added support for named constructors
## (0.2.1)
Bugfix:
- Impossible to generate Factory class on constructor with parameters
## (0.2.0)
Features:
- Generating profiles based on Annotations and declarated_profiles.dart info
## (0.1.8)
Features:
- New contract for profiles
## (0.1.8)
Features:
- Injecting super class members
Bugfixes:
- Injecting core dart classes
## (0.1.4)
Features:
- Example
## (0.1.0)
Features:
- Injecting with constructor
- Injecting with fields
- Injecting with factory class
- Scoped Singleton
- Custom scopes
- Hierarchcal Search down the tree of widgets
- Named injections<file_sep># Finject

[](https://travis-ci.com/TomMannson/Finject)
Tool that generates dependency injection Dart code.
Library was inspired by 3 other solution:
1. Spring Framework
2. Dagger 2
3. Angular DI builtin library
## Introduction
FInject provides:
- Easy and Flexible way of declarative DI approach (DI no service locator);
- Compile time code generation with single output (No need to create special part files every line is in one place);
- Easy scope management.
## Annotations and Contract classes for DI
[](https://pub.dev/packages/finject)
The core package providing the annotations which describes dependency graph.
No need to import in pubspec. Package finject_flutter using it
## Generator
[](https://pub.dev/packages/finject_generator)
The package providing the generator for DI code.
Import it into your pubspec `dev_dependencies:` section.
## Flutter glue code
[](https://pub.dev/packages/finject_flutter)
The package provides glue code which use injecting code under the hood.
Import it into your pubspec `dependencies:` section.
## Example
Example showing how to setup dependencies is available here:
[Source Code](https://github.com/TomMannson/Finject/tree/master/example)
## License
```
MIT License
Copyright (c) 2020 <NAME>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
```
<file_sep># CHANGELOG.md
## (0.1.0)
Features:
- Injecting with constructor
- Injecting with fields
- Injecting with factory class
- Scoped Singleton
- Custom scopes
- Hierarchcal Search down the tree of widgets
- Named injections<file_sep> - [Basic configuration usage](https://github.com/TomMannson/Finject/blob/master/example/lib/configuration.dart)<file_sep># CHANGELOG.md
## (0.3.2)
- Some tests added
## (0.3.0)
Features:
- ScopedObject and DisposableScopedObject interfaces added for Disposability feature
## (0.2.0)
Features:
- Added Profile Annotation for generating profile specific dependencies
## (0.1.4)
Features:
- Examples
## (0.1.0)
Features:
- Injecting with constructor
- Injecting with fields
- Injecting with factory class
- Scoped Singleton
- Custom scopes
- Hierarchcal Search down the tree of widgets
- Named injections<file_sep>#!/bin/bash --
# Copyright (c) 2016, Google Inc. Please see the AUTHORS file for details.
# All rights reserved. Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
set -e
directories="finject finject_generator finject_flutter"
parent_directory=$PWD
echo ""
echo "#####"
echo "##### CODE_FORMATTING"
echo "#####"
echo ""
for directory in $directories; do
echo "*** Formatting $directory..."
cd "$parent_directory/$directory"
dart format $(find bin lib test -name \*.dart 2>/dev/null)
done
echo ""
echo "#####"
echo "##### BUILD_RUNNER"
echo "#####"
echo ""
for directory in $directories; do
echo "*** Building $directory..."
cd "$parent_directory/$directory"
flutter pub get
flutter pub upgrade
# Clear any pre-existing build output so package:build doesn't get confused
# when we use built_value to build itself.
rm -rf .dart_tool/build/
grep -q build_runner pubspec.yaml && \
flutter pub run build_runner build \
--delete-conflicting-outputs \
--fail-on-severe
done
echo ""
echo "#####"
echo "##### DART ANALYZER"
echo "#####"
echo ""
for directory in $directories; do
echo "*** Analyzing $directory..."
cd "$parent_directory/$directory"
# --packages="$PWD/.packages" \
dart analyze \
--fatal-warnings \
--fatal-infos \
$(find bin lib test -name \*.dart 2>/dev/null)
done
echo ""
echo "#####"
echo "##### UNIT TESTS and COVERAGE"
echo "#####"
echo ""
dart_directories="finject finject_generator"
flutter_directories="finject_flutter"
for directory in $dart_directories; do
echo "*** Testing and coverage dart modules $directory..."
cd "$parent_directory/$directory"
dart test
# pub run test_coverage
done
for directory in $flutter_directories; do
echo "*** Testing and coverage flutter modules $directory..."
cd "$parent_directory/$directory"
# flutter test --coverage
flutter test
done
cd "$parent_directory"
|
36de2d77b9f775bd829e34b58ef439fbd65c7868
|
[
"Markdown",
"Shell"
] | 7
|
Markdown
|
TomMannson/Finject
|
043c72540170acf688b814e60b8eb056a0b63bbb
|
9f9428ee55eff057ad85fc19ff3e6f694b95fbb2
|
refs/heads/master
|
<file_sep><?php
session_start(); //สร้าง session สำหรับเก็บค่า username
//ตรวจสอบว่าทำการ Login เข้าสู่ระบบมารึยัง
$ses_userid =@$_SESSION['ses_userid']; //สร้าง session สำหรับเก็บค่า ID
$ses_username = @$_SESSION['ses_username'];
if(@$ses_userid <> session_id() or @$ses_username ==''){
}
//ตรวจสอบสถานะว่าใช่ admin รึเปล่า ถ้าไม่ใช่ให้หยุดอยู่แค่นี้
if(@$_SESSION['ses_status'] == 'user') {
}
elseif (@$_SESSION['ses_status'] == 'admin') {
# code...
}
else {
echo"<meta http-equiv='refresh' content='0;url=index.php'>";
echo '<script type="text/javascript">
function loadalert ()
{alert("กรุณา Login")
}
loadalert()
</script>';exit();
}
?>
<!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>Untitled Document</title><link rel="stylesheet" href="css/bootstrap.min.css" crossorigin="anonymous">
<link rel="stylesheet" href="css/bootstrap-theme.min.css" crossorigin="anonymous">
<link rel="stylesheet" href="css/style.css" crossorigin="anonymous">
<script src="js/bootstrap.min.js" crossorigin="anonymous"></script>
<script src="js/jquery.js"></script>
<script src="js/bootstrap.min.js"></script>
</head>
<body>
<?php
$q = intval($_GET['q']);
require("cn.php");
$sql="SELECT * FROM stock WHERE id = '".$q."'";
$result = mysqli_query($con,$sql);
?>
<table width="100%" class="table table-hover" id="tb1" >
<tr>
<th style="text-align: center;">รหัสวัสดุ</th>
<th style="text-align: center;">รายการ</th>
<th style="text-align: center;">ประเภทวัสดุ</th>
<th style="text-align: center;">เบิกจำนวน</th>
<th style="text-align: center;">คงเหลือ</th>
</tr>
<?php
while($row = mysqli_fetch_array($result)) {
?>
<tr>
<td><?php echo $row['code']; ?></td>
<td><?php echo $row['parts_name']; ?></td>
<td><?php echo $row['category']; ?></td>
<td width="30px;">
<input type="number" name="number1" style="width:50px;"></td>
<td><?php echo $row['number']; ?> <?php echo $row['unit']; ?></td>
<input type="hidden" name="num" value="<?php echo $row['number']; ?>"/>
<?php } ?>
</tr>
</table>
<?
mysqli_close($con);
?>
</body>
</html><file_sep><?php
session_start(); //เปิด session
$ses_userid =@$_SESSION['ses_userid']; //สร้าง session สำหรับเก็บค่า ID
$ses_username = @$_SESSION['ses_username'];
$ses_id = @$_SESSION['ses_id'];
$ses_status = @$_SESSION['ses_status']; //สร้าง session สำหรับเก็บค่า username
//ตรวจสอบว่าทำการ Login เข้าสู่ระบบมารึยัง
?>
<!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>Login</title>
<link rel="stylesheet" href="css/bootstrap.min.css" crossorigin="anonymous">
<link rel="stylesheet" href="css/bootstrap-theme.min.css" crossorigin="anonymous">
<link rel="stylesheet" href="css/style.css" crossorigin="anonymous">
<script src="js/bootstrap.min.js" crossorigin="anonymous"></script>
<script src="js/jquery.js"></script>
<script src="js/bootstrap.min.js"></script>
</head>
<style type="text/css">
.dd{
padding: 10px;
border: 2px solid #FFF;
}
.foot{
background-color:#e9e9e9;
width:100%;
height:20px;
bottom:0;
left:0;
position:fixed;
margin-bottom:5px;
}
.pagefooter
{
width:100%;
height:40px;
background-color:#282828;
position:fixed;
bottom:0;
left:0;
margin-top:500px;
color:#FFF;
padding:10px;
}
hr.so_sweethr001 {
border: 0;
height: 1px;
background: #333;
background-image: -webkit-linear-gradient(left, #ccc, #333, #ccc);
background-image: -moz-linear-gradient(left, #ccc, #333, #ccc);
background-image: -ms-linear-gradient(left, #ccc, #333, #ccc);
background-image: -o-linear-gradient(left, #ccc, #333, #ccc);
}
</style>
<body>
<br>
<div class="container">
<nav class="navbar navbar-default">
<div class="container-fluid">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<a class="navbar-brand" href="#">EQUIPMENT</a>
</div>
<?php
require("cn.php");
$strSQL = "SELECT * FROM user where id ='$ses_id'";
$objQuery = mysqli_query($con,$strSQL) or die ("Error Query [".$strSQL."]");
$objResult = mysqli_fetch_array($objQuery);
?>
<ul class="nav navbar-nav navbar-right">
<?php if($ses_id) { ?>
<li><?php if ($ses_status == 'user'){ ?><a href="treasury.php"><span class="badge">สวัสดีคุณ : <?php echo $objResult['name'];?></span></a><?php } else{?>
<a href="pageadmin.php"><span class="badge">สวัสดีคุณ : <?php echo $objResult['name'];?></span></a></li><li><a href="treasury.php"><span style="font-weight: bold; "><font color='EE0000' size="3">เบิกวัสดุ</font></span></a><?php }?></li>
<?php }
else{?>
<?php }?>
</ul>
</li>
</ul>
</div>
</div>
</nav>
<div class="container">
<div class="row">
<div class="col-xs-6 col-sm-4"></div>
<div class="col-xs-6 col-sm-4"><span style="font-weight: bold; font-size:30px;"><font color='#828282'>ระบบเบิกจ่ายอะไหล่ช่าง</font></span><br><br><br>
<form name="form1" class="form-horizontal" method="post" action="check_login.php" onSubmit="JavaScript:return fncSubmit();">
<div class="form-group">
<img src="img/preple.svg" width="15%" height="30" class="img-rounded" />
<div class="col-sm-10">
<input type="text" name="username" class="form-control" id="inputEmail3" placeholder="user">
</div>
</div>
<div class="form-group">
<img src="img/keys.svg" width="15%" height="30" class="img-rounded" />
<div class="col-sm-10">
<input type="<PASSWORD>" name="password" class="form-control" id="inputPassword3" placeholder="<PASSWORD>"><br>
<button type="submit" class="btn btn-primary btn-lg btn-block">Sign in</button>
</div>
</div>
</form></div>
<!-- Optional: clear the XS cols if their content doesn't match in height -->
<div class="clearfix visible-xs-block"></div>
<div class="col-xs-6 col-sm-4"></div>
</div>
</div>
<div class="pagefooter">2016 Copyright © All Rights Reserved.</div>
</body>
<script type="text/javascript">
function fncSubmit(strPage)
{
if(document.form1.username.value == "")
{
alert('กรุณาระบุชื่อผู้ใช้');
document.form1.username.focus();
return false;
}
if(document.form1.password.value == "")
{
alert('กรุณาระบุรหัสผ่าน');
document.form1.password.focus();
return false;
}
}
</script>
</html>
<file_sep> <!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" />
<Meta http-equiv="refresh"content="0;URL=treasury.php">
<title>Confirm</title>
</head>
<body>
</body>
</html>
<?php
session_start(); //สร้าง session สำหรับเก็บค่า username
//ตรวจสอบว่าทำการ Login เข้าสู่ระบบมารึยัง
$ses_userid =@$_SESSION['ses_userid']; //สร้าง session สำหรับเก็บค่า ID
$ses_username = @$_SESSION['ses_username'];
$ses_name = @$_SESSION['ses_name'];
if(@$ses_userid <> session_id() or @$ses_username ==''){
}
//ตรวจสอบสถานะว่าใช่ admin รึเปล่า ถ้าไม่ใช่ให้หยุดอยู่แค่นี้
if(@$_SESSION['ses_status'] == 'user') {
}
elseif (@$_SESSION['ses_status'] == 'admin') {
# code...
}
else {
echo"<meta http-equiv='refresh' content='0;url=index.php'>";
echo '<script type="text/javascript">
function loadalert ()
{alert("กรุณา Login")
}
loadalert()
</script>';exit();
}
?>
<?php
require("cn.php");
$idp = @$_POST['producte'];
$strSQL = "SELECT * FROM stock WHERE id = '".$idp."' ";
$objQuery = mysqli_query($con,$strSQL);
$objResult = mysqli_fetch_array($objQuery);
if($objResult['number'] < $_POST["number1"]) {
echo '<meta http-equiv="refresh" content="0;URL=treasury.php">';
echo '<script type="text/javascript">
function loadalert ()
{alert("สินค้าไม่พอ")
}
loadalert()
</script>';
exit();
}
$q1 = $objResult['number'];
$q2 =@$_POST['number1'];
$total = $q1 - $q2;
$total2 = $q1-($q2-($q2*0.03));
$total3 = $q2*0.03;
?>
<?php
require("cn.php"); /*
$number1 = $_POST['one2'];
$money1 = $_POST['select12']; */
mysqli_set_charset($con,"utf8");
$strSQL = "UPDATE stock SET number='$total' WHERE id = '".$idp."'";
$objQuery = mysqli_query($con,$strSQL);
?>
<?php
/*require("cn.php");
$cash1 = $_POST['cash'];
mysql_query("set names utf8");
mysqli_query($con,"UPDATE inform
SET monney='$cash1' WHERE telephone = '".$_GET["telephone"]."'");*/
?>
<?php /*
require("cn.php");
mysqli_query($con,"DELETE FROM inform WHERE telephone = '".$_GET["telephone"]."'");*/
?>
<?php
require("cn.php");
$select = "SELECT * FROM stock where id ='$idp'";
$se1 = mysqli_query($con,$select);
$resu = mysqli_fetch_array($se1);
?>
<?php
require("cn.php");
$product = $resu['parts_name'];
$num = @$_POST['number1'];
$depart = @$_POST['radio'];
$date01 = @$_POST['date01'];
$strSQL2 = "INSERT INTO order1(name_user,product,number1,department,credit,timer) VALUES('$ses_name','$product','$num','$depart','$total','$date01')";
$objQuery2 = mysqli_query($con,$strSQL2);
echo '<script type="text/javascript">
function loadalert ()
{alert("ดำเนินการเรียบร้อยแล้ว")
}
loadalert()
</script>';
?><file_sep>-- phpMyAdmin SQL Dump
-- version 4.4.14
-- http://www.phpmyadmin.net
--
-- Host: 127.0.0.1
-- Generation Time: Feb 15, 2016 at 05:47 PM
-- Server version: 5.6.26
-- PHP Version: 5.6.12
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `spares`
--
-- --------------------------------------------------------
--
-- Table structure for table `order1`
--
CREATE TABLE IF NOT EXISTS `order1` (
`id` int(11) NOT NULL,
`name_user` varchar(30) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
`product` varchar(30) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
`number1` int(30) NOT NULL,
`department` varchar(30) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
`credit` varchar(30) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
`timer` varchar(40) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=93 DEFAULT CHARSET=latin1;
--
-- Dumping data for table `order1`
--
INSERT INTO `order1` (`id`, `name_user`, `product`, `number1`, `department`, `credit`, `timer`) VALUES
(88, 'Stuart', 'กุญแจฝังเนื้อไม้ ALPHA No.4510', 10, 'ช่างไฟฟ้า', '15', '24-01-2016 20:22:45'),
(92, 'Kevin', 'กลอนโซฟา B.P.S.', 50, 'ช่างไฟฟ้า', '5', '27-01-2016 23:33:05');
-- --------------------------------------------------------
--
-- Table structure for table `stock`
--
CREATE TABLE IF NOT EXISTS `stock` (
`id` int(11) NOT NULL,
`parts_name` varchar(100) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
`type` varchar(30) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
`number` int(30) NOT NULL,
`category` varchar(30) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
`code` varchar(40) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
`unit` varchar(30) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=181 DEFAULT CHARSET=latin1;
--
-- Dumping data for table `stock`
--
INSERT INTO `stock` (`id`, `parts_name`, `type`, `number`, `category`, `code`, `unit`) VALUES
(8, 'สายไฟ VAF-GRD 2x2.5/1.5 ยี่ห้อ Thai Yazaki (100 เมตร)\r\n', '1', 4, 'ไฟฟ้า', '10102004116', 'ม้วน'),
(9, 'สายเสียบหัวหลักคอมเพรสเซอร์ # 4 ยาว 60 ซ.ม.', '1', 40, 'ไฟฟ้า', '10102004120', 'เส้น'),
(11, 'สายเสียบหัวหลักคอมเพรสเซอร์ # 4 ยาว 115 ซ.ม.', '1', 70, 'ไฟฟ้า', '10102004121', 'เส้น'),
(12, 'ปลั๊กตัวเมียเดี่ยว 2 สาย ', '1', 40, 'ไฟฟ้า', '10102005043', 'ตัว'),
(13, 'ปลั๊กตัวเมีย 3 สาย ดูเพล็ก ', '1', 100, 'ไฟฟ้า', '10102005044', 'ตัว'),
(14, 'สวิตช์ป้องกันไฟดูด Panasonic BJS 30308 YT 2P 30A ', '1', 30, 'ไฟฟ้า', '10102006020', 'ตัว'),
(15, 'สวิตซ์ออดลอย ยี่ห้อ Panasonic รุ่น WS4409H-8', '1', 60, 'ไฟฟ้า', '10102006044', 'ตัว'),
(16, 'หลอดไฟซุปเปอร์ลักซ์ 60w', '1', 50, 'ไฟฟ้า', '10102007059', 'หลอด'),
(17, 'หลอดไฟปิงปอง 25 W ', '1', 20, 'ไฟฟ้า', '10102007063', 'หลอด'),
(18, 'หลอดไฟจำปา 40 W ', '1', 50, 'ไฟฟ้า', '10102007112', 'หลอด'),
(19, 'หลอดไฟฟลูออเรสเซนต์ T5 28W D ยี่ห้อ EVE # 502864', '1', 360, 'ไฟฟ้า', '10102007126', 'หลอด'),
(20, 'หลอดประหยัดไฟ รุ่นมินิ 3 U 11 วัตต์ No. 500433 ( ชนิดหลอด เดย์ไลท์ E27 ยี่ห้อ EVE ทั้ง 3 ชนิด)', '1', 144, 'ไฟฟ้า', '10102007128', 'หลอด'),
(21, 'หลอดประหยัดไฟ รุ่นมินิ 3 U 14 วัตต์ No. 500457 ( ชนิดหลอด เดย์ไลท์ E27 ยี่ห้อ EVE ทั้ง 3 ชนิด)', '1', 60, 'ไฟฟ้า', '10102007129', 'หลอด'),
(22, 'หลอดประหยัดไฟ รุ่นมินิ 3 U 18 วัตต์ No. 500457 ( ชนิดหลอด เดย์ไลท์ E27 ยี่ห้อ EVE ทั้ง 3 ชนิด)', '1', 100, 'ไฟฟ้า', '10102007130', 'หลอด'),
(23, 'เบรคเกอร์ Square D รุ่น Qovs c20 3 ph 20a', '1', 5, 'ไฟฟ้า', '10102014042', 'ตัว'),
(24, 'ฝาครอบพลาสติกแบบ 1 ช่อง สีขาว ยี่ห้อ Panasonic รุ่น WEG 6801WK', '1', 30, 'ไฟฟ้า', '10102020030', 'อัน'),
(25, 'ฝาครอบพลาสติกแบบ 2 ช่อง สีขาว ยี่ห้อ Panasonic รุ่น WEG 6802WK', '1', 200, 'ไฟฟ้า', '10102020031', 'อัน'),
(26, 'ฝาครอบพลาสติกแบบ 3 ช่อง สีขาว ยี่ห้อ Panasonic รุ่น WEG 6803WK', '1', 50, 'ไฟฟ้า', '10102020032', 'อัน'),
(27, 'โคมดาวน์ไลน์ 6 นิ้ว ขอบขาว ลายเพชร ยี่ห้อ EVE # 505193 ', '1', 160, 'ไฟฟ้า', '10102029025', 'ชุด'),
(28, 'ฟิวส์หลอดแก้ว AUTO FUSES 30 MM 10A (1กล่อง=10 ตัว)', '1', 20, 'ไฟฟ้า', '10102222044', 'กล่อง'),
(29, 'สตาร์ทเตอร์ ยี่ห้อ Philips # S2 ', '1', 450, 'ไฟฟ้า', '10102222047', 'ตัว'),
(30, 'หลอดฟลูออเรสเซนต์ รุ่นมาตรฐาน 36 W/54 เดย์ไลท์ ยี่ห้อ อีฟ', '1', 100, 'ไฟฟ้า', '10102222106', 'หลอด'),
(31, 'หลอดฟลูออเรสเซนต์ รุ่นมาตรฐาน 18 W/54 เดย์ไลท์ ยี่ห้อ อีฟ', '1', 300, 'ไฟฟ้า', '10102222107', 'หลอด'),
(32, 'บัลลาสต์อิเล็กทรอนิกส์ T5 1x14 วัตต์ เบอร์ ยี่ห้อ อีฟ', '1', 50, 'ไฟฟ้า', '10102222194', 'ตัว'),
(33, 'บัลลาสต์อิเล็กทรอนิกส์ T5 1x28 วัตต์ เบอร์ ยี่ห้อ อีฟ', '1', 50, 'ไฟฟ้า', '10102222195', 'ตัว'),
(34, 'บัลลาสต์อิเล็กทรอนิกส์ T5 2x14 วัตต์ เบอร์ ยี่ห้อ อีฟ ', '1', 50, 'ไฟฟ้า', '10102222196', 'ตัว'),
(35, 'บัลลาสต์อิเล็กทรอนิกส์ T5 2x28 วัตต์ เบอร์ ยี่ห้อ อีฟ ', '1', 50, 'ไฟฟ้า', '10102222197', 'ตัว'),
(36, 'สายไฟฟ้า THW 1x1.5 สีดำ', '1', 2, 'ไฟฟ้า', '10102222348', 'ม้วน'),
(37, 'สายไฟฟ้า THW 1x1.5 สีขาว', '1', 5, 'ไฟฟ้า', '10102222349', 'ม้วน'),
(38, 'Honey well 2 WAY # VC4013AF1000', '1', 8, 'ไฟฟ้า', '10102222383', 'ตัว'),
(39, 'หลอดฟลูออเรสเซนต์ รุ่นมาตรฐาน 36 W/54 เดย์ไลท์ ยี่ห้อ อีฟ', '1', 100, 'ไฟฟ้า', '10102222106', 'หลอด'),
(40, 'หลอดฟลูออเรสเซนต์ รุ่นมาตรฐาน 18 W/54 เดย์ไลท์ ยี่ห้อ อีฟ', '1', 0, 'ไฟฟ้า', '10102222107', 'หลอด'),
(41, 'บัลลาสต์อิเล็กทรอนิกส์ T5 1x14 วัตต์ เบอร์ ยี่ห้อ อีฟ', '1', 50, 'ไฟฟ้า', '10102222194', 'ตัว'),
(42, 'บัลลาสต์อิเล็กทรอนิกส์ T5 1x28 วัตต์ เบอร์ ยี่ห้อ อีฟ', '1', 50, 'ไฟฟ้า', '10102222195', 'ตัว'),
(43, 'บัลลาสต์อิเล็กทรอนิกส์ T5 2x14 วัตต์ เบอร์ ยี่ห้อ อีฟ ', '1', 50, 'ไฟฟ้า', '10102222196', 'ตัว'),
(44, 'บัลลาสต์อิเล็กทรอนิกส์ T5 2x28 วัตต์ เบอร์ ยี่ห้อ อีฟ ', '1', 50, 'ไฟฟ้า', '10102222197', 'ตัว'),
(45, 'สายไฟฟ้า THW 1x1.5 สีดำ', '1', 2, 'ไฟฟ้า', '10102222348', 'ม้วน'),
(46, 'สายไฟฟ้า THW 1x1.5 สีขาว', '1', 5, 'ไฟฟ้า', '10102222349', 'ม้วน'),
(47, 'Honey well 2 WAY # VC4013AF1000', '1', 4, 'ไฟฟ้า', '10102222383', 'ตัว'),
(48, 'สตาร์ทคาปาซิเตอร์ 88-106 uF 220 AC', '1', 20, 'ไฟฟ้า', '10102222384', 'ตัว'),
(49, 'สายคอนโทรล แอร์ 7 Cores', '1', 100, 'ไฟฟ้า', '10102222386', 'เมตร'),
(50, 'ปลั๊ก 3 ขา วีเลค 13A 250V พร้อมฟิวส์กระเบื้อง', '1', 20, 'ไฟฟ้า', '10102222388', 'ตัว'),
(51, 'ปลั๊กตัวผู้(ยางดำ) 3ขา ยี่ห้อ COOPER รุ่น 1709-BOX', '1', 90, 'ไฟฟ้า', '10102222390', 'ตัว'),
(52, 'หลอดฟลูออเรสเซนต์กลม 32 W ยี่ห้อ Toshiba รุ่น FCL32D/30 BL32', '1', 100, 'ไฟฟ้า', '10102222391', 'หลอด'),
(53, 'หลอดไฟฟลูออเรสเซนต์ T5 14W D ยี่ห้อ EVE # 502840', '1', 400, 'ไฟฟ้า', '10102222393', 'หลอด'),
(54, 'หลอดฮาโลเจน ESS 50 W GU5.3 12V 36D OPEN # Philips', '1', 100, 'ไฟฟ้า', '10102222394', 'หลอด'),
(55, 'หลอดประหยัดไฟ รุ่นมินิ 3U 11 W WARMWHITE', '1', 48, 'ไฟฟ้า', '10102222395', 'หลอด'),
(56, 'หลอดประหยัดไฟ รุ่นมินิ 3U 14 W WARMWHITE', '1', 24, 'ไฟฟ้า', '10102222396', 'หลอด'),
(57, 'หลอดประหยัดไฟ รุ่นมินิ 3U 18 W WARMWHITE', '1', 48, 'ไฟฟ้า', '10102222397', 'หลอด'),
(58, 'ชุดโคมไฟสำเร็จรูป 36w', '1', 12, 'ไฟฟ้า', '10102222399', 'ชุด'),
(59, 'ชุดโคมไฟสำเร็จรูป 36w', '1', 12, 'ไฟฟ้า', '10102222399', 'ชุด'),
(60, 'สายไฟฟ้า THW 1x2.5 สีแดง', '1', 5, 'ไฟฟ้า', '10102222400', 'ม้วน'),
(61, 'สายไฟฟ้า THW 1x2.5 สีขาว', '1', 5, 'ไฟฟ้า', '10102222401', 'ม้วน'),
(62, 'สายไฟฟ้า THW 1x2.5 สีดำ', '1', 5, 'ไฟฟ้า', '10102222402', 'ม้วน'),
(63, 'สายไฟฟ้า THW 1x2.5 สีเขียว ', '1', 5, 'ไฟฟ้า', '10102222403', 'ม้วน'),
(64, 'สายไฟฟ้า VFF 2x2.5', '1', 0, 'ไฟฟ้า', '10102222404', 'เมตร'),
(65, 'เบรคเกอร์ Square D รุ่น Qovs c20 3 ph 32a', '1', 35, 'ไฟฟ้า', '10102222405', 'ตัว'),
(66, 'เบรคเกอร์ Square D รุ่น Qovs c20 1 ph 16a', '1', 12, 'ไฟฟ้า', '10102222407', 'ตัว'),
(67, 'เบรคเกอร์ Square D รุ่น Qovs c20 1 ph 32a', '1', 30, 'ไฟฟ้า', '10102222408', 'ตัว'),
(68, 'สวิตซ์ทางเดียวสีขาว ยี่ห้อ Panasonic รุ่น WEG 5001', '1', 200, 'ไฟฟ้า', '10102222410', 'ตัว'),
(69, 'สายไฟฟ้า THW 1x1.5 สีแดง', '1', 5, 'ไฟฟ้า', '10102222413', 'ม้วน'),
(70, 'SPILTER 1IN2 OUT', '1', 60, 'ไฟฟ้า', '10102222419', 'ชุด'),
(71, 'SPILTER 1IN3 OUT', '1', 80, 'ไฟฟ้า', '10102222420', 'ชุด'),
(72, 'SPILTER 1IN4 OUT', '1', 50, 'ไฟฟ้า', '10102222421', 'ชุด'),
(73, 'เต้ารับทีวี ยี่ห้อ Panasonic รุ่น WZ1201', '1', 200, 'ไฟฟ้า', '10102222429', 'ตัว'),
(74, 'บาลาส LOWLOSS BTA18L04LW ยี่ห้อ Philips', '1', 40, 'ไฟฟ้า', '10104054019', 'ตัว'),
(75, 'ใบพัดลม ยี่ห้อ มิตซูบิชิ', '1', 10, 'ไฟฟ้า', '10102222442', 'ใบ'),
(76, 'ฝาครอบพลาสติกแบบ 6 ช่อง สีขาว ยี่ห้อ Panasonic รุ่น WEG 6806WK', '1', 140, 'ไฟฟ้า', '10102222444', 'อัน'),
(77, 'FASCO Motor S2-1/4-C ( FCU )', '1', 6, 'ไฟฟ้า', '10202071004', 'ตัว'),
(78, 'HARTLAND 30 A 2P 220V', '1', 5, 'ไฟฟ้า', '10202222168', 'ตัว'),
(79, 'พัดลมดูดอากาศติดกระจกพานาโซนิค 8” รุ่น F-20 WUT', '1', 12, 'ไฟฟ้า', '10202221003', 'ตัว'),
(80, 'วาล์วลูกศร 1/4 นิ้ว มีหาง(มีไส้)', '1', 120, 'ไฟฟ้า', '10202222057', 'อัน'),
(81, 'TIMER WIP Air # W-2P', '1', 25, 'ไฟฟ้า', '10202222195', 'ตัว'),
(82, 'ขามอเตอร์คอล์ยเย็น (ขาตุ๊กตา) ', '1', 10, 'ไฟฟ้า', '10202222272', 'อัน'),
(83, 'Running SHIZUKI 45 MFd. 370/440V', '1', 25, 'ไฟฟ้า', '10202222306', 'ตัว'),
(84, 'หม้อแปลง อิเลคทริค ยี่ห้อ Philips ET-S60', '1', 15, 'ไฟฟ้า', '10202222353', 'ชุด'),
(85, 'Stage Resin Cartridge Filter 10” เรซินเหลือง', '3', 5, 'ทั่วไป', '10103322008', 'ชิ้น'),
(86, 'ไส้กรองโฟมหัวตัด ขนาด 5 ไมครอน', '2', 40, 'ประปา', '10103322166', 'อัน'),
(87, 'แปรงทาสีขนม้า ตรานกนางแอ่น ขนาด 4"', '3', 5, 'ทั่วไป', '10104005027', 'อัน'),
(88, 'ก๊อกสนามแบบบอลวาล์ว ยี่ห้อ SANWA ขนาด ½”', '2', 10, 'ประปา', '10104027009', 'ตัว'),
(89, 'ก๊อกซิ้งค์ติดเคาน์เตอร์ ยี่ห้อ Cotto รุ่น CT-130C10(HM)', '2', 10, 'ประปา', '10104027245', 'ตัว'),
(90, 'ก๊อก หางปลาติดอ่าง AE BN104', '2', 20, 'ประปา', '10104027251', 'ตัว'),
(91, 'ชุดท่อน้ำทิ้ง อเมริกัน# A-8100N', '2', 10, 'ประปา', '10104038010', 'ชุด'),
(92, 'ชุดก้านกระทุ้ง TOTO# S 342', '2', 60, 'ประปา', '10104054011', 'ชุด'),
(93, 'ท่อตรง TOTO# S321', '2', 25, 'ประปา', '10104054016', 'ชุด'),
(94, 'กลอนโซฟา B.P.S.', 'ทั่วไป', 60, 'ทั่วไป', '10104080025', 'อัน'),
(95, 'แกนใส่กระดาษชำระ TOTO # C975', '2', 40, 'ประปา', '10104086001', 'อัน'),
(96, 'บานพับแสตนเลส ยี่ห้อ LINK S-4420-2BR HD', '3', 70, 'ทั่วไป', '10104088060', 'ชุด'),
(97, 'ฝารองนั่ง American Standard No.48', '2', 7, 'ประปา', '10104092010', 'ชุด'),
(98, 'ฝารองนั่ง American Standard No.39', '2', 29, 'ประปา', '10104092011', 'ชุด'),
(99, 'ฝารองนั่ง American Standard No.39', '2', 29, 'ประปา', '10104092011', 'ชุด'),
(100, 'ฝารองนั่ง ยี่ห้อ ฟิกโซ รุ่น TR -02', '2', 20, 'ประปา', '10104092013', 'ชุด'),
(101, 'โช๊คอัพประตูยี่ห้อ YALE 2000 รุ่น 2022 (ไม่ค้าง) ', '3', 5, 'ทั่วไป', '10104101022', 'ชุด'),
(102, 'โช๊คอัพประตูยี่ห้อ YALE 2000 รุ่น 2012 (ค้าง)', '3', 5, 'ทั่วไป', '10104101023', 'ชุด'),
(103, 'ชุดวาล์วเปิด-ปิด TOTO รุ่น S-508 (1กล่อง = 30 ตัว)', '2', 30, 'ประปา', '10104182009', 'ชุด'),
(104, 'DOOR STOP ยี่ห้อ HAFELE (กันชนแม่เหล็ก)', '3', 10, 'ทั่วไป', '10104191001', 'อัน'),
(105, 'โช๊คอัพประตู ยี่ห้อ Newstar No.S-630', '3', 8, 'ทั่วไป', '10104229009', 'ชุด'),
(106, 'สายน้ำดี FIXO รุ่น SC-20 (กล่องละ 100 เส้น) สายยูเนียน', '2', 100, 'ประปา', '10104299130', 'ชุด'),
(107, 'ก๊อกน้ำเย็น รุ่น KCW-4000', '2', 20, 'ประปา', '10104299161', 'ตัว'),
(108, 'ก๊อกน้ำร้อน รุ่น KCW-4000', '2', 20, 'ประปา', '10104299162', 'ตัว'),
(109, 'ก๊อกบอล ยี่ห้อ SANWA ขนาด ½” ก๊อกลงบ่อ', '2', 10, 'ประปา', '10104299163', 'ตัว'),
(110, 'ก๊อกอ่างซิ้งติดผนัง COTTO # CT 134C10(HM)', '2', 26, 'ประปา', '10104299164', 'ตัว'),
(111, 'ข้องอ 90 1/2" PVC', '2', 100, 'ประปา', '10104299165', 'อัน'),
(112, 'ชุดฝักบัวสายอ่อน ยี่ห้อ Cotto รุ่น S-17 โครเมี่ยม', '2', 12, 'ประปา', '10104299166', 'ชุด'),
(113, 'ชุดฝักบัวสายอ่อน ยี่ห้อ Hang รุ่น HS-511 โครเมี่ยม', '2', 20, 'ประปา', '10104299168', 'ชุด'),
(114, 'ชุดวาล์วเปิด-ปิดน้ำ TOTO # S 498', '2', 34, 'ประปา', '10104299169', 'ชุด'),
(115, 'ท่อน้ำทิ้ง ยี่ห้อ TOTO รุ่น TS-612A (1กล่อง = 18 ตัว)', '2', 10, 'ประปา', '10104299171', 'ชุด'),
(127, 'ท่อน้ำทิ้ง สวีทโฮม รุ่น K-1200', '2', 35, 'ประปา', '10104299172', 'ชุด'),
(128, 'วาล์วเปิด-ปิด ฝักบัวอาบน้ำ เซรามิค หัวแก้ว RM', '2', 40, 'ประปา', '10104299176', 'ชุด'),
(129, 'สะดืออ่างล้างจาน ขนาด 1 1/4" (ทองเหลือง R.M.)', '2', 40, 'ประปา', '10104299177', 'อัน'),
(130, 'สายฉีดชำระ ยี่ห้อ Cotto รุ่น CT-667N#WH', '2', 60, 'ประปา', '10104299178', 'ชุด'),
(131, 'สายฉีดชำระ ยี่ห้อ Hang รุ่น SS02WHBR ยูเนี่ยนทองเหลือง', '2', 120, 'ประปา', '10104299179', 'ชุด'),
(132, 'สายฉีดชำระ ยี่ห้อ ฟิกโซ รุ่น ER-02', '2', 100, 'ประปา', '10104299180', 'ชุด'),
(133, 'อะไหล่ชักโครก อุปกรณ์จิงโจ้ รุ่น K-100-SPCH', '2', 12, 'ประปา', '10104299182', 'ชุด'),
(134, 'ก๊อกซิงค์ติดผนัง TS116B14', '2', 5, 'ประปา', '10104299184', 'ตัว'),
(135, 'สามทาง เอสล่อน 1/2" PVC', '2', 20, 'ประปา', '10104299187', 'อัน'),
(136, 'กลอนห้องน้ำแสตนเลส ขนาด 4 นิ้ว', '3', 60, 'ทั่วไป', '10104299247', 'ตัว'),
(137, 'กุญแจฝังเนื้อไม้ ALPHA No.4510', '3', 25, 'ทั่วไป', '10104299249', 'ชุด'),
(138, 'กุญแจลิ้นชัก ROYAL รุ่น 708 บรรจุ 12 ตัว / กล่อง', '3', 30, 'ทั่วไป', '10104299250', 'ชุด'),
(139, 'โช๊คอัพประตู VVP', '3', 8, 'ทั่วไป', '10104299251', 'ชุด'),
(140, 'โช๊คอัพประตู ยี่ห้อ WINMA', '3', 30, 'ทั่วไป', '10104299253', 'ชุด'),
(141, 'ท่อ PVC แข็ง แบบท่อปลายธรรมดา หนา 13.5 ขนาด 18 มม.(1/2"x4 เมตร) ', '2', 50, 'ประปา', '10104299256', 'ท่อน'),
(142, 'ท่อ PVC แข็ง แบบท่อปลายธรรมดา หนา 13.5 ขนาด 20 มม.(3/4"x4 เมตร) ', '2', 5, 'ประปา', '10104299257', 'ท่อน'),
(143, 'ท่อ PVC แข็ง แบบท่อปลายธรรมดา หนา 13.5 ขนาด 25 มม.(1"x4 เมตร)', '2', 10, 'ประปา', '10104299258', 'ท่อน'),
(144, 'บานพับ ขนาด 3นิ้ว ยี่ห้อ HINGE', '3', 20, 'ทั่วไป', '10104299262', 'ตัว'),
(145, 'บานพับ ยี่ห้อ HSK รุ่น LAVATORY HINGE( แสตนเลส ห้องน้ำ ภปร.)', '3', 60, 'ทั่วไป', '10104299264', 'ชุด'),
(146, 'บานพับแสตนเลส ยี่ห้อ LINK S-4420-4BR HD', '3', 15, 'ทั่วไป', '10104299265', 'ชุด'),
(147, 'บานสวิง ยี่ห้อ VVP ไขด้านเดียว V-39 รุ่น SW-1', '3', 50, 'ทั่วไป', '10104299266', 'ชุด'),
(148, 'ลูกบิดประตู MAXSTAR No.5130-SS', '3', 10, 'ทั่วไป', '10104299268', 'ชุด'),
(149, 'มือจับตัวรูปตัว C ขนาด 3 นิ้ว', '3', 150, 'ทั่วไป', '10104299269', 'อัน'),
(150, 'มือจับตัวรูปตัว C ขนาด 4 นิ้ว', '3', 150, 'ทั่วไป', '10104299270', 'อัน'),
(151, 'ลวดขึงราวม่าน', '3', 3, 'ทั่วไป', '10104299272', 'กล่อง'),
(152, 'สายยู พับได้ ขนาด 3 นิ้ว', '2', 24, 'ประปา', '10104299274', 'อัน'),
(153, 'ข้อต่อตรง ขนาด 1/2 " PVC', '2', 223, 'ประปา', '10104800024', 'อัน'),
(154, 'ข้อต่อตรง ขนาด 3/4 " PVC', '2', 35, 'ประปา', '10104800025', 'อัน'),
(155, 'ข้อต่อตรง ขนาด 1 1/4 ', '2', 50, 'ประปา', '10104800026', 'อัน'),
(156, 'ข้อต่อตรง ขนาด 2 " PVC', '2', 10, 'ประปา', '10104800027', 'อัน'),
(157, 'ข้องอ 90 1 1/4 " PVC', '2', 60, 'ประปา', '10104800038', 'อัน'),
(158, 'ข้องอ 90 2 " PVC', '2', 10, 'ประปา', '10104800078', 'อัน'),
(159, 'ข้องอ 90 1 " PVC', '2', 60, 'ประปา', '10204239102', 'อัน'),
(160, 'ข้องอ 90 1 1/2 " PVC', '2', 20, 'ประปา', '10204239109', 'อัน'),
(161, 'ก๊อกเดี่ยวอ่างล้างหน้า COTTO # CT 160C11', '2', 18, 'ประปา', '10204239374', 'ตัว'),
(162, 'ก๊อกอ่างล้างหน้า-ล้างมือ สวีทโฮม รุ่น K-475/2', '2', 36, 'ประปา', '10204239384', 'ตัว'),
(163, 'ก๊อกเดี่ยวก้านปัดติดผนัง TOTO#TS 131B14', '2', 60, 'ประปา', '10204239410', 'ตัว'),
(164, 'มินิบอลวาล์ว ยี่ห้อ Sanwa รุ่น BV15MF ผม. ?”', '2', 100, 'ประปา', '10204239412', 'ตัว'),
(165, 'บอลวาล์ว (รูเต็ม)1/2" ยี่ห้อ Sanwa รุ่น BV-15FB', '2', 10, 'ประปา', '10204239413', 'ตัว'),
(166, 'กุญแจคล้องเล็กทองเหลือง ยี่ห้อ FION', '3', 50, 'ทั่วไป', '10204239414', 'ชุด'),
(167, 'กุญแจลิ้นชัก MAXSTAR รุ่น 520-CP D19บรรจุ 12 ตัว/กล่องฝังเนื้อไม้', '3', 68, 'ทั่วไป', '10204239415', 'ชุด'),
(168, 'ปูนยาแนว ยี่ห้อ เวเบอร์ D01 สีขาว', '3', 96, 'ทั่วไป', '10204239418', 'ถุง'),
(169, 'ล้อ 5" ยางเทาแป้นตาย TENTE', '3', 30, 'ทั่วไป', '10105026182', 'ล้อ'),
(170, 'ล้อ 5" ยางเทาแป้นหมุน TENTE', '3', 30, 'ทั่วไป', '10105026183', 'ล้อ'),
(171, 'ล้อ 5" ยางเทาขาสกรู 16 mm. TENTE', '3', 10, 'ทั่วไป', '10105026184', 'ล้อ'),
(172, 'ล้อ 5" ยางเทาสกรูเบรค 16 mm. TENTE', '3', 10, 'ทั่วไป', '10105026207', 'ล้อ'),
(173, 'ล้อ 8" ยางดำแป้นตาย TENTE', '3', 10, 'ทั่วไป', '10105026208', 'ล้อ'),
(174, 'ล้อจิ๊บ ขนาด8 " พร้อมลูกปืนทั้งสองข้าง', '3', 20, 'ทั่วไป', '10105026210', 'ล้อ'),
(175, 'ล้อ 4" ยางเทาแป้นหมุน TENTE', '3', 30, 'ทั่วไป', '10105026212', 'ล้อ'),
(176, 'G.E.Relay # 3ARR3A4A3 2-5 HP (โพแทนเชี่ยนรีเลย์)', '3', 15, 'ทั่วไป', '10105101023', 'ตัว'),
(177, 'Honey well # T6373A Room Thermostat', '3', 6, 'ทั่วไป', '10105101026', 'ตัว'),
(178, 'มอเตอร์ส่ายพัดลมโคจรเพดานยี่ห้อ ฮาตาริ', '3', 10, 'ทั่วไป', '10216010032', 'ตัว'),
(180, 'ซิงล์ล้างจาน', '2', 5, 'ประปา', '10104299169', 'ชุด');
-- --------------------------------------------------------
--
-- Table structure for table `user`
--
CREATE TABLE IF NOT EXISTS `user` (
`id` int(11) NOT NULL,
`name` varchar(30) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
`status` varchar(10) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL DEFAULT 'user',
`group` varchar(20) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
`login_user` varchar(30) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
`login_pass` varchar(30) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1;
--
-- Dumping data for table `user`
--
INSERT INTO `user` (`id`, `name`, `status`, `group`, `login_user`, `login_pass`) VALUES
(1, 'Kevin', 'admin', 'admin', 'admin', '<PASSWORD>'),
(2, 'Stuart', 'user', 'teset', 'user', '1234');
--
-- Indexes for dumped tables
--
--
-- Indexes for table `order1`
--
ALTER TABLE `order1`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `stock`
--
ALTER TABLE `stock`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `user`
--
ALTER TABLE `user`
ADD PRIMARY KEY (`id`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `order1`
--
ALTER TABLE `order1`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=93;
--
-- AUTO_INCREMENT for table `stock`
--
ALTER TABLE `stock`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=181;
--
-- AUTO_INCREMENT for table `user`
--
ALTER TABLE `user`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=3;
/*!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
session_start(); //สร้าง session สำหรับเก็บค่า username
//ตรวจสอบว่าทำการ Login เข้าสู่ระบบมารึยัง
$ses_userid =@$_SESSION['ses_userid']; //สร้าง session สำหรับเก็บค่า ID
$ses_username = @$_SESSION['ses_username'];
$ses_id = @$_SESSION['ses_id'];
$ses_status = @$_SESSION['ses_status'];
if(@$ses_userid <> session_id() or @$ses_username ==''){
}
//ตรวจสอบสถานะว่าใช่ admin รึเปล่า ถ้าไม่ใช่ให้หยุดอยู่แค่นี้
if(@$_SESSION['ses_status'] == 'admin') {
}
else {
echo"<meta http-equiv='refresh' content='0;url=index.php'>";
echo '<script type="text/javascript">
function loadalert ()
{alert("กรุณา Login")
}
loadalert()
</script>';exit();
}
?>
<?php
require("cn.php");
$select = "DELETE FROM order1 WHERE id = '".$_GET["id"]."'";
$se1 = mysqli_query($con,$select);
?>
<!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" />
<Meta http-equiv="refresh"content="0;URL=pageadmin.php">
<title>Untitled Document</title>
</head>
<body>
</body>
</html>
<file_sep> <!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" />
<Meta http-equiv="refresh"content="0;URL=showall.php">
<title>Untitled Document</title>
</head>
<body>
</body>
</html>
<?php
session_start(); //สร้าง session สำหรับเก็บค่า username
//ตรวจสอบว่าทำการ Login เข้าสู่ระบบมารึยัง
$ses_userid =@$_SESSION['ses_userid']; //สร้าง session สำหรับเก็บค่า ID
$ses_username = @$_SESSION['ses_username'];
$ses_id = @$_SESSION['ses_id'];
$ses_status = @$_SESSION['ses_status'];
if(@$ses_userid <> session_id() or @$ses_username ==''){
}
//ตรวจสอบสถานะว่าใช่ admin รึเปล่า ถ้าไม่ใช่ให้หยุดอยู่แค่นี้
if(@$_SESSION['ses_status'] == 'admin') {
}
else {
echo"<meta http-equiv='refresh' content='0;url=index.php'>";
echo '<script type="text/javascript">
function loadalert ()
{alert("กรุณา Login")
}
loadalert()
</script>';exit();
}
?>
<?php
function a ($dd) {
if ($dd == 1)
return "ไฟฟ้า";
else if($dd == 2)
return "ประปา";
else
return "ทั่วไป";
}
?>
<?php
require("cn.php");
$type2 = a($_POST['category']);
$code = $_POST['code'];
$parts_name = $_POST['parts_name'];
$category = $_POST['category'];
$number = $_POST['number'];
$unit = $_POST['unit'];
mysqli_set_charset($con,"utf8");
$strSQL2 = "UPDATE stock SET code='$code',parts_name='$parts_name',category='$type2',type='$category',number='$number',unit='$unit' WHERE id = '".$_GET["id"]."'";
$objQuery2 = mysqli_query($con,$strSQL2);
?>
<file_sep><?php
session_start(); //สร้าง session สำหรับเก็บค่า username
//ตรวจสอบว่าทำการ Login เข้าสู่ระบบมารึยัง
$ses_userid =@$_SESSION['ses_userid']; //สร้าง session สำหรับเก็บค่า ID
$ses_username = @$_SESSION['ses_username'];
$ses_id = @$_SESSION['ses_id'];
$ses_status = @$_SESSION['ses_status'];
if(@$ses_userid <> session_id() or @$ses_username ==''){
}
//ตรวจสอบสถานะว่าใช่ admin รึเปล่า ถ้าไม่ใช่ให้หยุดอยู่แค่นี้
if(@$_SESSION['ses_status'] == 'user') {
}
elseif (@$_SESSION['ses_status'] == 'admin') {
# code...
}
else {
echo"<meta http-equiv='refresh' content='0;url=index.php'>";
echo '<script type="text/javascript">
function loadalert ()
{alert("กรุณา Login")
}
loadalert()
</script>';exit();
}
?>
<!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 rel="stylesheet" href="css/bootstrap.min.css" crossorigin="anonymous">
<link rel="stylesheet" href="css/bootstrap-theme.min.css" crossorigin="anonymous">
<link rel="stylesheet" href="css/style.css" crossorigin="anonymous">
<script src="js/bootstrap.min.js" crossorigin="anonymous"></script>
<script src="js/jquery.js"></script>
<script src="js/bootstrap.min.js"></script>
<style type="text/css">
.pagefooter
{
width:100%;
height:40px;
background-color:#282828;
position:fixed;
bottom:0;
left:0;
margin-top:500px;
color:#FFF;
padding:10px;
}
hr.so_sweethr001 {
border: 0;
height: 1px;
background: #333;
background-image: -webkit-linear-gradient(left, #ccc, #333, #ccc);
background-image: -moz-linear-gradient(left, #ccc, #333, #ccc);
background-image: -ms-linear-gradient(left, #ccc, #333, #ccc);
background-image: -o-linear-gradient(left, #ccc, #333, #ccc);
}
</style>
<script>
function showUser(str) {
var v = document.getElementById('seee').value;
if(v != 0)
{
document.getElementById('tbc').style.display = 'none';
}
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET","getuser.php?q="+str,true);
xmlhttp.send();
}
}
function showD(str) {
if (str == "") {
document.getElementById("textshow").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("textshow").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET","getdepart.php?q="+str,true);
xmlhttp.send();
}
}
</script>
</head>
<body>
<br>
<div class="container">
<nav class="navbar navbar-default">
<div class="container-fluid">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<a class="navbar-brand" href="index.php">Home</a>
</div>
<?php
require("cn.php");
$strSQL = "SELECT * FROM user where id ='$ses_id'";
$objQuery = mysqli_query($con,$strSQL) or die ("Error Query [".$strSQL."]");
$objResult = mysqli_fetch_array($objQuery);
?>
<ul class="nav navbar-nav navbar-right">
<?php if($ses_id) { ?>
<li><?php if ($ses_status == 'user'){ ?><a href="treasury.php"><span class="badge">สวัสดีคุณ : <?php echo $objResult['name'];?></span></a><?php } else{?>
<a href="pageadmin.php"><span class="badge">สวัสดีคุณ : <?php echo $objResult['name'];?></span></a><?php }?></li>
<?php }
else{?>
<?php }?>
<li><a href="logout.php">LOGOUT</a></li>
</ul>
</li>
</ul>
</div>
</div>
</nav>
<div class="container">
<form id="form1" name="form1" method="post" action="credit.php" onSubmit="JavaScript:return fncSubmit();">
<input type="hidden" name="date01" value="<?php echo date('d-m-Y H:i:s',strtotime('+ 6 hours')); ?>" />
<table width="100%" class="table table-condensed">
<tr>
<div class="radio"><td style="font-size: 20px; font-weight: bold;" >หน่วยงาน</td>
<td><label class="radio-inline">
<input type="radio" name="radio" id="radio1" value="ช่างไฟฟ้า" />
ช่างไฟฟ้า</label>
</td>
<td><label class="radio-inline">
<input type="radio" name="radio" id="radio2" value="ช่างประปา" />
ช่างประปา</label>
</td>
<td><label class="radio-inline">
<input type="radio" name="radio" id="radio3" value="ช่างทั่วไป" />
ช่างทั่วไป</label></td>
</tr>
</div>
</table>
<div class="row">
<div class="col-md-4">
<select class="form-control" id="select5" name="mo" onchange="showD(this.value)">
<option value="0">เลือกหมวด</option>
<option value="1">ไฟฟ้า</option>
<option value="2">ประปา</option>
<option value="3">ทั่วไป</option>
</select></div>
<div class="col-md-4" id="textshow">
</div>
<div class="col-md-4">
</div>
</div>
<br>
<?php
require("cn.php");
$strSQL1 = "select * from stock where type='e'";
$objQuery1 = mysqli_query($con,$strSQL1);
?>
<?php
require("cn.php");
$strSQL2 = "select * from stock where type='p'";
$objQuery2 = mysqli_query($con,$strSQL2);
?>
<table width="100%" class="table table-hover" id="tbc" >
<tr>
<th style="text-align: center;">รหัสวัสดุ</th>
<th style="text-align: center;">รายการ</th>
<th style="text-align: center;">ประเภทวัสดุ</th>
<th style="text-align: center;">เบิกจำนวน</th>
<th style="text-align: center;">คงเหลือ</th>
</tr>
</table>
<div id="txtHint"></div>
<input type="submit" class="btn btn-success" value="ตกลง">
</form>
</div>
<script type="text/javascript">
function a(){
var v = document.getElementById('select5').value;
if(v == 1)
{
document.getElementById('se22').style.display = '';
document.getElementById('se11').style.display = 'none';
document.getElementById('se33').style.display = 'none';
}
if(v == 2)
{
document.getElementById('se33').style.display = '';
document.getElementById('se11').style.display = 'none';
document.getElementById('se22').style.display = 'none';
}
if(v == 3)
{
document.getElementById('se11').style.display = '';
document.getElementById('se22').style.display = 'none';
document.getElementById('se33').style.display = 'none';
}
}
function fncSubmit(strPage)
{
var selected_index = form1.elements["mo"].selectedIndex;
if(selected_index > 0)
{
var selected_option_value = form1.elements["mo"].options[selected_index].value;
var selected_option_text = form1.elements["mo"].options[selected_index].text;
}
else
{
alert('กรุณาเลือกหมวด');
return false;
}var selected_index = form1.elements["producte"].selectedIndex;
if(selected_index > 0)
{
var selected_option_value = form1.elements["producte"].options[selected_index].value;
var selected_option_text = form1.elements["producte"].options[selected_index].text;
}
else
{
alert('กรุณาเลือกรายการ');
return false;
}
if(document.form1.radio1.checked == false && document.form1.radio2.checked == false && document.form1.radio3.checked == false)
{
alert('โปรดเลือกแผนก');
return false;
}
if(document.form1.number1.value == "")
{
alert('กรุณาระบุจำนวนเบิก');
document.form1.number1.focus();
return false;
}
if(document.form1.number1.value <= 0)
{
alert('ระบุจำนวนให้ถูกต้อง');
document.form1.number1.focus();
return false;
}
if(document.form1.number1.value > document.form1.num.value)
{
alert('วัสดุไม่เพียงพอ');
document.form1.number1.focus();
document.form1.num.focus();
return false;
}
document.form1.submit();
}
/*function b(id){
if(id == 1) { // ถ้าเลือก radio button 1 ให้โชว์ table 1 และ ซ่อน table 2
document.getElementById("tb1").style.display = "";
document.getElementById("tb2").style.display = "none";
document.getElementById('tb').style.display = 'none';
} else if(id == 2) { // ถ้าเลือก radio button 2 ให้โชว์ table 2 และ ซ่อน table 1
document.getElementById("tb2").style.display = "";
document.getElementById("tb1").style.display = "none";
document.getElementById('tb').style.display = 'none';
}
}
*/
</script>
<div class="pagefooter">2016 Copyright © All Rights Reserved.</div>
</body>
</html>
<file_sep><!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" />
<Meta http-equiv="refresh"content="0;URL=pageadmin.php">
<title>Untitled Document</title>
</head>
<body>
</body>
</html>
<?php
function a ($dd) {
if ($dd == 1)
return "ไฟฟ้า";
else if($dd == 2)
return "ประปา";
else
return "ทั่วไป";
}
?>
<?php
require("cn.php");
$type2 = a($_POST['type']);
$product = $_POST['product'];
$type = $_POST['type'];
$number = $_POST['number'];
$code = $_POST['code1'];
$unit = $_POST['unit'];
$strSQL2 = "INSERT INTO stock(parts_name,type,number,category,code,unit) values('$product','$type','$number','$type2','$code','$unit')";
$objQuery2 = mysqli_query($con,$strSQL2);
echo '<script type="text/javascript">
function loadalert ()
{alert("บันทึกข้อมูลเรียบร้อยแล้ว")
}
loadalert()
</script>';
exit();
?><file_sep><?php
session_start(); //สร้าง session สำหรับเก็บค่า username
//ตรวจสอบว่าทำการ Login เข้าสู่ระบบมารึยัง
$ses_userid =@$_SESSION['ses_userid']; //สร้าง session สำหรับเก็บค่า ID
$ses_username = @$_SESSION['ses_username'];
if(@$ses_userid <> session_id() or @$ses_username ==''){
}
//ตรวจสอบสถานะว่าใช่ admin รึเปล่า ถ้าไม่ใช่ให้หยุดอยู่แค่นี้
if(@$_SESSION['ses_status'] == 'user') {
}
elseif (@$_SESSION['ses_status'] == 'admin') {
# code...
}
else {
echo"<meta http-equiv='refresh' content='0;url=index.php'>";
echo '<script type="text/javascript">
function loadalert ()
{alert("กรุณา Login")
}
loadalert()
</script>';exit();
}
?>
<!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>Untitled Document</title><link rel="stylesheet" href="css/bootstrap.min.css" crossorigin="anonymous">
<link rel="stylesheet" href="css/bootstrap-theme.min.css" crossorigin="anonymous">
<link rel="stylesheet" href="css/style.css" crossorigin="anonymous">
<script src="js/bootstrap.min.js" crossorigin="anonymous"></script>
<script src="js/jquery.js"></script>
<script src="js/bootstrap.min.js"></script>
<script>
</script>
</head>
<body>
<select class="form-control" id="seee" name="producte" onchange="showUser(this.value)">
<option value="0">รายการ</option>
<?php
$q = intval($_GET['q']);
require("cn.php");
$sqla="SELECT * FROM stock WHERE type = '".$q."' order by parts_name asc" ;
$resulta = mysqli_query($con,$sqla);
while($dbarra=mysqli_fetch_array($resulta)){ ?>
<option value='<?php echo $dbarra['id']; ?>'><?php echo $dbarra['parts_name']; ?></option>
<?php
}?>
</select>
<script type="text/javascript">
function fncSubmit(strPage)
{
var d = document.getElementById('seee').value;
if(d ==0)
{
alert('โปรดเลือกรายการ');
return false;
}
</script>
</body>
</html><file_sep><?php
session_start(); //สร้าง session สำหรับเก็บค่า username
//ตรวจสอบว่าทำการ Login เข้าสู่ระบบมารึยัง
$ses_userid =@$_SESSION['ses_userid']; //สร้าง session สำหรับเก็บค่า ID
$ses_username = @$_SESSION['ses_username'];
$ses_id = @$_SESSION['ses_id'];
$ses_status = @$_SESSION['ses_status'];
if(@$ses_userid <> session_id() or @$ses_username ==''){
}
//ตรวจสอบสถานะว่าใช่ admin รึเปล่า ถ้าไม่ใช่ให้หยุดอยู่แค่นี้
if(@$_SESSION['ses_status'] == 'admin') {
}
else {
echo"<meta http-equiv='refresh' content='0;url=index.php'>";
echo '<script type="text/javascript">
function loadalert ()
{alert("กรุณา Login")
}
loadalert()
</script>';exit();
}
?>
<!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>Members</title><link rel="stylesheet" href="css/bootstrap.min.css" crossorigin="anonymous">
<link rel="stylesheet" href="css/bootstrap-theme.min.css" crossorigin="anonymous">
<link rel="stylesheet" href="css/style.css" crossorigin="anonymous">
<script src="js/bootstrap.min.js" crossorigin="anonymous"></script>
<script src="js/jquery.js"></script>
<script src="js/bootstrap.min.js"></script>
<body>
<br/>
<div class="container">
<div class="row">
<div class="col-md-6 col-md-offset-3">
<form action="edit2.php?id=<?php echo $_GET["id"];?>" name="frmEdit" method="post">
<?php
require("cn.php");
$strSQL = "SELECT * FROM stock WHERE id = '".$_GET["id"]."' ";
$objQuery = mysqli_query($con,$strSQL);
$objResult = mysqli_fetch_array($objQuery);
?>
<table width="100%" class="table">
<tr>
<td > <div align="center">รหัสวัสดุ </div></td>
<td ><div class="form-group" ><input type="text" name="code" size="20" class="form-control" value="<?php echo $objResult["code"];?>"></div></td>
</tr>
<tr>
<td > <div align="center">ชื่อวัสดุ </div></td>
<td ><div class="form-group"><input type="text" name="parts_name" size="20" class="form-control" value="<?php echo $objResult["parts_name"];?>"></div></td>
</tr>
<tr>
<td > <div align="center">ประเภทวัสดุ </div></td>
<td ><div class="form-group">
<select class="form-control" id="select5" name="category">
<option value="<?php echo $objResult["type"];?>"><?php echo $objResult["category"];?></option>
<option value="1">ไฟฟ้า</option>
<option value="2">ประปา</option>
<option value="3">ทั่วไป</option>
</select>
</div></td>
</tr>
<tr>
<td > <div align="center">จำนวนวัสดุ </div></td>
<td ><div class="form-group"><input type="number" name="number" size="20" class="form-control" value="<?php echo $objResult["number"];?>"></div></td>
</tr>
<tr>
<td > <div align="center">หน่วย </div></td>
<td ><div class="form-group"><input type="text" name="unit" size="20" class="form-control" value="<?php echo $objResult["unit"];?>"></div></td>
</tr>
</table>
<input type="submit" name="submit" value="submit" class="btn btn-default">
</form>
<br/>
<button class="btn btn-default" type="button" onClick='window.history.back()'>Back</button>
</div>
<!--
<div class="detail">
<table width="95%" border="0">
<tr>
<td> <img src="image/1.jpg" width="100%" height="99" style="margin-left: 15px;" /></td>
<td><img src="image/d.jpg" width="100%" height="99" style="margin-left: 15px;" /></td>
<td><img src="image/t.jpg" width="100%" height="99" style="margin-left: 15px;" /></td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
</tr>
</table>
</div>-->
</div>
<br/>
</body>
</html>
<file_sep><?php
session_start(); //สร้าง session สำหรับเก็บค่า username
//ตรวจสอบว่าทำการ Login เข้าสู่ระบบมารึยัง
$ses_userid =@$_SESSION['ses_userid']; //สร้าง session สำหรับเก็บค่า ID
$ses_username = @$_SESSION['ses_username'];
$ses_id = @$_SESSION['ses_id'];
$ses_status = @$_SESSION['ses_status'];
if(@$ses_userid <> session_id() or @$ses_username ==''){
}
//ตรวจสอบสถานะว่าใช่ admin รึเปล่า ถ้าไม่ใช่ให้หยุดอยู่แค่นี้
if(@$_SESSION['ses_status'] == 'admin') {
}
else {
echo"<meta http-equiv='refresh' content='0;url=index.php'>";
echo '<script type="text/javascript">
function loadalert ()
{alert("กรุณา Login")
}
loadalert()
</script>';exit();
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Document</title>
</head>
<link rel="stylesheet" href="css/bootstrap.min.css" crossorigin="anonymous">
<link rel="stylesheet" href="css/bootstrap-theme.min.css" crossorigin="anonymous">
<link rel="stylesheet" href="css/style.css" crossorigin="anonymous">
<script src="js/bootstrap.min.js" crossorigin="anonymous"></script>
<script src="js/jquery.js"></script>
<script src="js/bootstrap.min.js"></script>
<body><br>
<div class="container">
<form id="form1" name="form1" method="post" action="search2.php" class="form-inline" >
<div class="form-group">
<input type="text" name="name1" id="name" class="form-control" placeholder='ค้นหาวัสดุ' /> </div>
<input type="submit" name="bt" value="ค้นหา" class="btn btn-default"/>
<br><br>
<?php
require("cn.php");
$select = "SELECT * FROM stock order by category asc";
$se1 = mysqli_query($con,$select);
?>
<table width="100%" class="table table-hover">
<tr>
<th><center>รหัสวัสดุ</center></th>
<th><center>ชื่อวัสดุ</center></th>
<th><center>ประเภทวัสดุ</center></th>
<th><center>จำนวนคงเหลือ</center></th>
<th colspan='2'><center></center></th>
</tr>
<?php
while($resu = mysqli_fetch_array($se1))
{?>
<tr>
<td><?php echo $resu['code']; ?></td>
<td><?php echo $resu['parts_name']; ?></td>
<td><?php echo $resu['category']; ?></td>
<td><?php echo $resu['number']; ?> <?php echo $resu['unit']; ?></td>
<td><a href="edit.php?id=<?php echo $resu['id'];?>">แก้ไข</a></td>
<td><a href='delete2.php?id=<?php echo $resu['id']; ?>'><img src="img/close.svg" width="30" height="30" class="img-rounded" /></a></td>
</tr>
<?php } ?>
</table>
</form>
</div>
</body>
</html><file_sep><?php
session_start(); //สร้าง session สำหรับเก็บค่า username
//ตรวจสอบว่าทำการ Login เข้าสู่ระบบมารึยัง
$ses_userid =@$_SESSION['ses_userid']; //สร้าง session สำหรับเก็บค่า ID
$ses_username = @$_SESSION['ses_username'];
$ses_id = @$_SESSION['ses_id'];
$ses_status = @$_SESSION['ses_status'];
if(@$ses_userid <> session_id() or @$ses_username ==''){
}
//ตรวจสอบสถานะว่าใช่ admin รึเปล่า ถ้าไม่ใช่ให้หยุดอยู่แค่นี้
if(@$_SESSION['ses_status'] == 'admin') {
}
else {
echo"<meta http-equiv='refresh' content='0;url=index.php'>";
echo '<script type="text/javascript">
function loadalert ()
{alert("กรุณา Login")
}
loadalert()
</script>';exit();
}
?>
<!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>ADMIN</title>
</head>
<link rel="stylesheet" href="css/bootstrap.min.css" crossorigin="anonymous">
<link rel="stylesheet" href="css/bootstrap-theme.min.css" crossorigin="anonymous">
<link rel="stylesheet" href="css/style.css" crossorigin="anonymous">
<script src="js/bootstrap.min.js" crossorigin="anonymous"></script>
<script src="js/jquery.js"></script>
<script src="js/bootstrap.min.js"></script>
<script type="text/javascript">
function fncSubmit()
{
if(document.form1.code1.value == "")
{
alert('กรุณากรอกรหัสวัสดุ');
document.form1.code1.focus();
return false;
}
if(document.form1.product.value == "")
{
alert('กรุณากรอกชื่อวัสดุ');
document.form1.product.focus();
return false;
}
if(document.form1.type.value == "")
{
alert('กรุณาเลือกประเภท');
document.form1.type.focus();
return false;
}
if(document.form1.number.value == "")
{
alert('กรุณาใส่จำนวน');
document.form1.number.focus();
return false;
}
if(document.form1.unit.value == "")
{
alert('ระบุหน่วยของวัสดุ');
document.form1.unit.focus();
return false;
}
document.form1.submit();
}
</script>
<style type="text/css">
.pagefooter
{
width:100%;
height:40px;
background-color:#282828;
position:fixed;
bottom:0;
left:0;
margin-top:500px;
color:#FFF;
padding:10px;
}
hr.so_sweethr001 {
border: 0;
height: 1px;
background: #333;
background-image: -webkit-linear-gradient(left, #ccc, #333, #ccc);
background-image: -moz-linear-gradient(left, #ccc, #333, #ccc);
background-image: -ms-linear-gradient(left, #ccc, #333, #ccc);
background-image: -o-linear-gradient(left, #ccc, #333, #ccc);
}
</style>
<body>
</body>
<br>
<div class="container">
<nav class="navbar navbar-default">
<div class="container-fluid">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<a class="navbar-brand" href="index.php">Home</a>
</div>
<?php
require("cn.php");
$strSQL = "SELECT * FROM user where id ='$ses_id'";
$objQuery = mysqli_query($con,$strSQL) or die ("Error Query [".$strSQL."]");
$objResult = mysqli_fetch_array($objQuery);
?>
<ul class="nav navbar-nav navbar-right">
<?php if($ses_id) { ?>
<li><?php if ($ses_status == 'user'){ ?><a href="treasury.php"><span class="badge">สวัสดีคุณ : <?php echo $objResult['name'];?></span></a><?php } else{?>
<a href="pageadmin.php"><span class="badge">สวัสดีคุณ : <?php echo $objResult['name'];?></span></a><?php }?></li>
<?php }
else{?>
<?php }?>
<li><a href="logout.php">Logout</a></li>
</ul>
</li>
</ul>
</div>
</div>
</nav>
<div class="container">
<div class="row">
<div class="col-xs-12 col-md-8">
<?php
require("cn.php");
$select = "SELECT * FROM order1";
$se1 = mysqli_query($con,$select);
?>
<span style="font-weight: bold; "><font color='#8B8682' size="20">รายการเบิก</font></span><br><br>
<table width="100%" class="table table-hover">
<tr>
<th><center>เวลา</center></th>
<th><center>ชื่อผู้เบิก</center></th>
<th><center>แผนก</center></th>
<th><center>วิสดุ</center></th>
<th><center>เบิก</center></th>
<th><center>คงเหลือ</center></th>
<th></th>
</tr>
<?php
while($resu = mysqli_fetch_array($se1))
{?>
<tr>
<td ><?php echo $resu['timer']; ?></td>
<td><?php echo $resu['name_user']; ?></td>
<td><?php echo $resu['department']; ?></td>
<td><?php echo $resu['product']; ?></td>
<td><?php echo $resu['number1']; ?></td>
<td><?php echo $resu['credit']; ?></td>
<td><a href='delete.php?id=<?php echo $resu['id']; ?>'><img src="img/close.svg" width="50" height="30" class="img-rounded" /></a></td>
</tr>
<?php } ?>
</table></div>
<div class="col-xs-6 col-md-4">
<span style="font-weight: bold; "><font color='#8B8682' size="20">เพิ่มวัสดุ</font></span><br><br>
<form name='form1' method="post" action="adinsert.php" onSubmit="JavaScript:return fncSubmit();">
<input type="text" name="code1" id="name" class="form-control" placeholder='รหัสวัสดุ' />
<input type="text" name="product" id="name" class="form-control" placeholder='ชื่อวัสดุ' />
<select name="type" id="select" class="form-control">
<option>ประเภท</option>
<option value="1">ไฟฟ้า</option>
<option value="2">ประปา</option>
<option value="3">ทั่วไป</option>
</select>
<input type="number" name="number" id="name" class="form-control" placeholder='จำนวนของ' />
<select name="unit" id="select" class="form-control">
<option>หน่วย</option>
<option value="กล่อง">กล่อง</option>
<option value="เครื่อง">เครื่อง</option>
<option value="ชิ้น">ชิ้น</option>
<option value="ชุด">ชุด</option>
<option value="ตัว">ตัว</option>
<option value="ถุง">ถุง</option>
<option value="ท่อน">ท่อน</option>
<option value="ใบ">ใบ</option>
<option value="ม้วน">ม้วน</option>
<option value="เมตร">เมตร</option>
<option value="ล้อ">ล้อ</option>
<option value="เส้น">เส้น</option>
<option value="หลอด">หลอด</option>
<option value="อัน">อัน</option>
</select>
<br>
<input type="submit" name="mysubmit" class="btn btn-success" value="เพิ่มวัสดุ">
</form>
<br><br><br>
<a class="fancybox fancybox.iframe" href="showall.php"><button type="button" class="btn btn-primary">วัสดุทั้งหมด</button></a>
</div>
</div>
</div>
<script src="js/index.js"></script>
<script type="text/javascript" src="lib/jquery-1.8.2.min.js"></script>
<script type="text/javascript" src="lib/jquery.mousewheel-3.0.6.pack.js"></script>
<script type="text/javascript" src="source/jquery.fancybox.js?v=2.1.3"></script>
<link rel="stylesheet" type="text/css" href="source/jquery.fancybox.css?v=2.1.2" media="screen" />
<link rel="stylesheet" type="text/css" href="source/helpers/jquery.fancybox-buttons.css?v=1.0.5" />
<script type="text/javascript" src="source/helpers/jquery.fancybox-buttons.js?v=1.0.5"></script>
<link rel="stylesheet" type="text/css" href="source/helpers/jquery.fancybox-thumbs.css?v=1.0.7" />
<script type="text/javascript" src="source/helpers/jquery.fancybox-thumbs.js?v=1.0.7"></script>
<script type="text/javascript" src="source/helpers/jquery.fancybox-media.js?v=1.0.5"></script>
<script type="text/javascript">
$(document).ready(function() {
$('.fancybox').fancybox();
$(".fancybox-effects-popup").fancybox({
helpers: {
title : {
type : 'outside'
},
overlay : {
speedOut : 0
}
}
}).trigger('click'); <!--คำสั่ง .trigger('click') เป็นคำสั่งเด้ง popup โดยอัตโนมัติโดยไม่ต้องกด-->
});
</script>
<br/><br/>
<div class="pagefooter">2016 Copyright © All Rights Reserved.</div>
</body>
</html><file_sep><?php
$con = mysqli_connect('localhost','root','','spares');
mysqli_select_db($con,"spares");
mysqli_set_charset($con,"utf8");
?>
|
73227277d989026f2591d551ee6a5e04c642e17b
|
[
"SQL",
"PHP"
] | 13
|
PHP
|
itouwza1995/spares
|
c97f1880e1bdbcae17f236fc3541b08fd41042b3
|
a4e95c3b106ac068899a023cf1c6a0cbdc391799
|
refs/heads/master
|
<file_sep>using System.Collections.Generic;
using WinAPI;
namespace Wizard.Core {
class NetworkOper {
private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
public NetworkOper() {
}
public List<Network> getNetworkList() {
log.InfoFormat("=======开始获取网络======");
List<Network> networkList = new List<Network>();
List<XenRef<Network>> nwRefs = Network.get_all(ConnectManager.session);
foreach (XenRef<Network> nwRef in nwRefs) {
Network network = Network.get_record(ConnectManager.session, nwRef);
log.InfoFormat("uuid: {0}", network.uuid);
log.InfoFormat("name: {0}", network.name_label);
log.InfoFormat("name_description: {0}", network.name_description);
log.InfoFormat("bridge: {0}", network.bridge);
log.InfoFormat("MTU: {0}", network.MTU);
log.InfoFormat("PIFs Count: {0}", network.PIFs.Count);
//network.PIFs.Count > 0
if (!"xenapi".Equals(network.bridge)) {
networkList.Add(network);
}
}
log.InfoFormat("=======获取网络完成======");
return networkList;
}
public Network getNetworkByVif(VIF vif) {
XenRef<Network> nwRef = vif.network;
Network network = Network.get_record(ConnectManager.session, nwRef);
return network;
}
public XenRef<Network> getNetworkRef(Network network) {
XenRef<Network> nwRef = Network.get_by_uuid(ConnectManager.session, network.uuid);
return nwRef;
}
public void setVIF(VIF vif, Network network) {
vif.network = getNetworkRef(network);
ConnectManager.VIF = vif;
ConnectManager.NetworkName = network.name_label;
}
}
}
<file_sep>using System;
using System.IO;
using ICSharpCode.SharpZipLib.Tar;
namespace WizardLib.Archive
{
public class SharpZipTarArchiveIterator : ArchiveIterator
{
private TarInputStream tarStream;
private TarEntry tarEntry;
private bool disposed;
public SharpZipTarArchiveIterator()
{
tarStream = null;
disposed = true;
}
public SharpZipTarArchiveIterator(Stream tarFile)
{
tarStream = new TarInputStream(tarFile);
disposed = false;
}
public override void SetBaseStream(Stream stream)
{
tarStream = new TarInputStream(stream);
disposed = false;
}
~SharpZipTarArchiveIterator()
{
Dispose();
}
public override bool HasNext()
{
tarEntry = tarStream.GetNextEntry();
if (tarEntry == null)
return false;
return true;
}
public override string CurrentFileName()
{
if (tarEntry == null)
return String.Empty;
return tarEntry.Name;
}
public override long CurrentFileSize()
{
if (tarEntry == null)
return 0;
return tarEntry.Size;
}
public override DateTime CurrentFileModificationTime()
{
if (tarEntry == null)
return new DateTime();
return tarEntry.ModTime;
}
public override bool IsDirectory()
{
if (tarEntry == null)
return false;
return tarEntry.IsDirectory;
}
public override void ExtractCurrentFile(Stream extractedFileContents)
{
if (IsDirectory())
return;
tarStream.CopyEntryContents(extractedFileContents);
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
if(disposing)
{
if(!disposed)
{
if (tarStream != null)
tarStream.Dispose();
disposed = true;
}
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using WinAPI;
using System.Net;
namespace Wizard.Core {
class HTTPHelper {
private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
public static int progressPercent = 0;
private static int changePercent = 0;
public static string progressInfo;
public static string errorInfo = "";
public static String Put(int timeout, string path, string hostname, Delegate f, params object[] p) {
XenRef<Task> taskRef = Task.create(ConnectManager.session, "INSTALL WinCenter VM", hostname);
log.InfoFormat("创建Task:{0}", taskRef.opaque_ref);
try {
HTTP.UpdateProgressDelegate progressDelegate = delegate(int percent) {
Tick(percent);
};
return Put(progressDelegate, timeout, taskRef, ref ConnectManager.session, path, hostname, f, p);
}
finally {
Task.destroy(ConnectManager.session, taskRef);
log.InfoFormat("销毁Task:{0}", taskRef.opaque_ref);
}
}
public static String Put(HTTP.UpdateProgressDelegate progressDelegate, int timeout,
XenRef<Task> taskRef, ref Session session, string path, string hostname, Delegate f, params object[] p) {
HTTP.FuncBool cancellingDelegate = (HTTP.FuncBool)delegate() {
return false;
};
log.InfoFormat("HTTP导入文件从[{0}]到主机[{1}]", path, hostname);
try {
List<object> args = new List<object>();
args.Add(progressDelegate);
args.Add(cancellingDelegate);
args.Add(timeout);
args.Add(hostname);
args.Add(null); //IWebProxy
args.Add(path);
args.Add(taskRef.opaque_ref); // task_id
args.AddRange(p);
f.DynamicInvoke(args.ToArray());
} catch(Failure failure) {
log.InfoFormat("HTTP导入文件失败:{0}", failure.ErrorDescription.ToString());
}
catch (Exception ex) {
log.InfoFormat("HTTP导入文件失败:{0}", ex.Message);
}
return PollTaskForResult(ref ConnectManager.session, taskRef);
}
private static void Tick(int percent) {
if (percent < 0)
percent = 0;
if (percent > 100)
percent = 100;
progressPercent = percent * 90 / 100;
if (changePercent != percent) {
changePercent = percent;
log.InfoFormat("文件导入进度:{0}%,安装进度:{1}%", changePercent, progressPercent);
if (changePercent == 100) {
HTTPHelper.progressInfo = "导入完成";
}
}
}
private static String PollTaskForResult(ref Session session, XenRef<Task> taskRef) {
task_status_type status;
do {
System.Threading.Thread.Sleep(500);
status = Task.get_status(session, taskRef);
}
while (status == task_status_type.pending || status == task_status_type.cancelling);
if (status == task_status_type.failure) {
throw new Failure(Task.get_error_info(session, taskRef));
}
else {
return Task.get_result(session, taskRef);
}
}
}
}
<file_sep>WinCenterClient
=========
WinCenter-Appliance虚拟化管理系统安装程序。
WinCenterClient使用C#编写,目前版本号为6.5。
说明
------
* 兼容XenServer7.0/WinServer6.5及以下所有版本
* 也可以作为虚拟机导入工具,将虚拟机导入到XenServer/WinServer主机
版本变更
-------
V6.5
* 增加内存校验
* 优化API
* 优化性能
* 支持XenServer7.0/6.5/6.2/6.1
* 支持WinServer6.5/6.1/6.0/5.5/5.4/5.1/5.0
V5.5
* UI优化
* SSH使用Renci.SshNet
* 优化设置IP等网络信息
* .NET升级到4.0
* 支持XenServer6.5/6.2/6.1
* 支持WinServer6.1/6.0/5.5/5.4/5.1/5.0
V5.4
* 存储类型增加EXT
* 增加license许可
* 支持XenServer6.2/6.1
* 支持WinServer5.5/5.4/5.1/5.0
V5.1
* UI优化
* 支持XenServer6.2/6.1
* 支持WinServer5.1/5.0
V5.0
* 初始版本
* 使用AE设置IP等网络信息
* 支持XenServer6.2/6.1
WinCenterClient分析
---------------------
[WinCenterClient分析(一)](http://www.hl10502.com/2017/02/24/wincenterclient-1/)
[WinCenterClient分析(二)](http://www.hl10502.com/2017/02/24/wincenterclient-2/)
<file_sep>using System;
using WinAPI;
using System.Collections.Generic;
namespace Wizard.Core {
class SROper {
private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
private List<SR> sRList = new List<SR>();
public SROper() {
}
public List<Dictionary<string, string>> getStorageRepositories() {
List<Dictionary<string, string>> srList = new List<Dictionary<string, string>>();
List<XenRef<SR>> srRefs = SR.get_all(ConnectManager.session);
foreach (XenRef<SR> srRef in srRefs) {
SR sr = SR.get_record(ConnectManager.session, srRef);
log.InfoFormat("Name: {0}", sr.name_label);
log.InfoFormat("Description: {0}", sr.name_description);
log.InfoFormat("Usage: {0:0.00}GB / {1:0.0}GB", sr.physical_utilisation / Constants.UINT, sr.physical_size / Constants.UINT);
Dictionary<string, string> dict = new Dictionary<string, string>();
string value = sr.name_label + " 可用" + (sr.physical_utilisation / Constants.UINT) + "GB,总共" + sr.physical_size / Constants.UINT + "GB";
dict.Add(sr.uuid, value);
srList.Add(dict);
}
return srList;
}
public List<SRVo> getSRByTargetHost() {
HostOper hostOper = new HostOper();
Host targetHost = hostOper.getTargetHost();
log.InfoFormat("=======开始获取存储池======");
List<SRVo> srList = new List<SRVo>();
List<XenRef<SR>> srRefs = SR.get_all(ConnectManager.session);
foreach (XenRef<SR> srRef in srRefs) {
SR sr = SR.get_record(ConnectManager.session, srRef);
//五种类型 nfs ext lvm lvmhba lvmoiscsi
if ("nfs".Equals(sr.type) || "ext".Equals(sr.type) || (!String.IsNullOrEmpty(sr.type) && sr.type.IndexOf("lvm") >= 0)) {
if ("lvm".Equals(sr.type) || "ext".Equals(sr.type)) {
bool isLocalHost = false;
List<XenRef<PBD>> pbdRefs = sr.PBDs;
if (pbdRefs != null && pbdRefs.Count > 0) {
foreach (XenRef<PBD> pbdRef in pbdRefs) {
PBD pbd = PBD.get_record(ConnectManager.session, pbdRef);
if (pbd.currently_attached) {
Host host = Host.get_record(ConnectManager.session, pbd.host.opaque_ref);
if (targetHost.uuid.Equals(host.uuid)) {
isLocalHost = true;
break;
}
}
}
}
if (isLocalHost) {
string info = "";
if ((sr.physical_size - sr.physical_utilisation) < (long)ConnectManager.DiskCapacity) {
info = string.Format("本地存储池[{0}]可用容量不足", sr.name_label);
}
srList.Add(AddSRData(sr, info));
}
else {
log.InfoFormat("本地存储池未连接主机. sr=[uuid: {0}, Name: {1}, type: {2}, lave: {3:0.00}GB / {4:0.00}GB]", sr.uuid, sr.name_label, sr.type,
(sr.physical_size - sr.physical_utilisation) / Constants.UINT, sr.physical_size / Constants.UINT);
}
}
else {
string info = "";
if ((sr.physical_size - sr.physical_utilisation) < (long)ConnectManager.DiskCapacity) {
info = string.Format("共享存储池[{0}]可用容量不足", sr.name_label);
log.InfoFormat("{0}. sr=[uuid: {1}, Name: {2}, type: {3}, lave: {4:0.00}GB / {5:0.00}GB]", info, sr.uuid, sr.name_label, sr.type,
(sr.physical_size - sr.physical_utilisation) / Constants.UINT, sr.physical_size / Constants.UINT);
}
List<XenRef<PBD>> pbdRefs = sr.PBDs;
if (pbdRefs != null && pbdRefs.Count > 0) {
bool isCurrentlyAttached = true;
foreach (XenRef<PBD> pbdRef in pbdRefs) {
PBD pbd = PBD.get_record(ConnectManager.session, pbdRef);
if (!pbd.currently_attached) {
isCurrentlyAttached = false;
if (!string.IsNullOrEmpty(info)) {
info += ",连接主机PBD异常";
}
else {
info = string.Format("共享存储池[{0}]连接主机PBD异常", sr.name_label);
}
log.InfoFormat("{0}. pbd=[uuid:{1}], sr=[uuid: {2}, Name: {3}, type: {4}, lave: {5:0.00}GB / {6:0.00}GB]", info, pbd.uuid, sr.uuid, sr.name_label, sr.type,
(sr.physical_size - sr.physical_utilisation) / Constants.UINT, sr.physical_size / Constants.UINT);
}
}
if (isCurrentlyAttached) {
//srList.Add(AddSRData(sr));
//WriteLog(sr);
}
}
else {
if (!string.IsNullOrEmpty(info)) {
info += ",未连接主机";
}
else {
info = string.Format("共享存储池[{0}]未连接主机", sr.name_label);
}
log.InfoFormat("{0}. sr=[uuid: {1}, Name: {2}, type: {3}, lave: {4:0.00}GB / {5:0.00}GB]", info, sr.uuid, sr.name_label, sr.type,
(sr.physical_size - sr.physical_utilisation) / Constants.UINT, sr.physical_size / Constants.UINT);
}
srList.Add(AddSRData(sr, info));
}
}
else {
log.InfoFormat("存储池类型不是五种类型nfs/ext/lvm/lvmhba/lvmoiscsi中的一种. sr=[uuid: {0}, Name: {1}, type: {2}, lave: {3:0.00}GB / {4:0.00}GB]", sr.uuid, sr.name_label, sr.type,
(sr.physical_size - sr.physical_utilisation) / Constants.UINT, sr.physical_size / Constants.UINT);
}
//if ((sr.physical_size - sr.physical_utilisation) >= (long)ConnectManager.DiskCapacity) {
//}
//else {
// log.InfoFormat("存储池可用大小小于需要的存储容量. sr=[uuid: {0}, Name: {1}, type: {2}, lave: {3:0.00}GB / {4:0.00}GB]", sr.uuid, sr.name_label, sr.type,
// (sr.physical_size - sr.physical_utilisation) / Constants.UINT, sr.physical_size / Constants.UINT);
//}
}
log.InfoFormat("=======获取存储池结束======");
return srList;
}
private SRVo AddSRData(SR sr, string info) {
sRList.Add(sr);
SRVo sRVo = new SRVo();
sRVo.Uuid = sr.uuid;
sRVo.Name = sr.name_label;
sRVo.AvailableCapacity = sr.physical_size - sr.physical_utilisation;
sRVo.PhysicalSize = sr.physical_size;
sRVo.Type = sr.type;
if (!string.IsNullOrEmpty(info)) {
sRVo.Info = info;
}
else {
WriteLog(sr);
}
return sRVo;
}
private void WriteLog(SR sr) {
log.InfoFormat("****************存储池uuid={0}满足条件start", sr.uuid);
log.InfoFormat("uuid: {0}", sr.uuid);
log.InfoFormat("Name: {0}", sr.name_label);
log.InfoFormat("Description: {0}", sr.name_description);
log.InfoFormat("content_type: {0}", sr.content_type);
log.InfoFormat("type: {0}", sr.type);
log.InfoFormat("Usage: {0:0.00}GB / {1:0.0}GB", sr.physical_utilisation / Constants.UINT, sr.physical_size / Constants.UINT);
log.InfoFormat("lave: {0:0.00}GB", (sr.physical_size - sr.physical_utilisation) / Constants.UINT);
log.InfoFormat("****************存储池uuid={0}满足条件end", sr.uuid);
}
public string getAeISORepoUuid() {
string aeIsoRepoUuid = null;
List<XenRef<SR>> srRefs = SR.get_by_name_label(ConnectManager.session, Constants.AE_ISO_REPO_NAME);
foreach(XenRef<SR> srRef in srRefs) {
SR sr = SR.get_record(ConnectManager.session, srRef);
Dictionary<string, string> otherConfig = sr.other_config;
if (!otherConfig.ContainsKey(Constants.AE_ISO_REPO_HOST_KEY)
|| !otherConfig.ContainsKey(Constants.AE_ISO_REPO_OTHER_KEY)) {
continue;
}
string hostUuid = "";
otherConfig.TryGetValue(Constants.AE_ISO_REPO_HOST_KEY, out hostUuid);
string author = "";
otherConfig.TryGetValue(Constants.AE_ISO_REPO_OTHER_KEY, out author);
if (ConnectManager.TargetHost.uuid.Equals(hostUuid) && Constants.AE_ISO_REPO_OTHER_VALUE.Equals(author)) {
aeIsoRepoUuid = sr.uuid;
break;
}
}
if (string.IsNullOrEmpty(aeIsoRepoUuid)) {
//如果iso sr不存在需要新建ISO
aeIsoRepoUuid = createISOSr();
log.InfoFormat("AE ISO SR不存在,已创建新的ISO,srUuid={0}", aeIsoRepoUuid);
}
scanSr(aeIsoRepoUuid);
return aeIsoRepoUuid;
}
private string createISOSr() {
string aeIsoRepoUuid = null;
try {
string hostUuid = ConnectManager.TargetHost.uuid;
XenRef<Host> hostRef = Host.get_by_uuid(ConnectManager.session, hostUuid);
Dictionary<string, string> deviceConfig = new Dictionary<string, string>();
deviceConfig.Add("location", Constants.AE_ISO_REPO_LOCATION);
deviceConfig.Add("legacy_mode", "true");
Dictionary<string, string> smConfig = new Dictionary<string, string>();
XenRef<SR> srRef = SR.create(ConnectManager.session, hostRef, deviceConfig, 0, Constants.AE_ISO_REPO_NAME,
Constants.AE_ISO_REPO_LOCATION, "iso", "iso", false, smConfig);
Dictionary<string, string> otherConfig = new Dictionary<string, string>();
otherConfig.Add(Constants.AE_ISO_REPO_OTHER_KEY, Constants.AE_ISO_REPO_OTHER_VALUE);
otherConfig.Add(Constants.AE_ISO_REPO_HOST_KEY, hostUuid);
SR.set_other_config(ConnectManager.session, srRef, otherConfig);
aeIsoRepoUuid = SR.get_uuid(ConnectManager.session, srRef);
}
catch (Exception e) {
log.ErrorFormat("创建ISO失败: {0}" + e.Message);
}
return aeIsoRepoUuid;
}
public void scanSr(string srUuid) {
XenRef<SR> srRef = SR.get_by_uuid(ConnectManager.session, srUuid);
SR.scan(ConnectManager.session, srRef);
}
public XenRef<VDI> getVdiRef(string srUuid, string fileName) {
XenRef<SR> srRef = SR.get_by_uuid(ConnectManager.session, srUuid);
SR sr = SR.get_record(ConnectManager.session, srRef);
List<XenRef<VDI>> vdiRefs = sr.VDIs;
foreach (XenRef<VDI> vdiRef in vdiRefs) {
VDI vdi = VDI.get_record(ConnectManager.session, vdiRef);
string isoFileName = VDI.get_location(ConnectManager.session, vdiRef);
if (fileName.Equals(isoFileName)) {
return vdiRef;
}
}
return null;
}
public SR getSrByUuid(string uuid) {
foreach (SR sr in sRList) {
if (uuid.Equals(sr.uuid)) {
return sr;
}
}
return null;
}
public ulong DiskCapacity {
set {
ConnectManager.DiskCapacity = value;
}
get {
return ConnectManager.DiskCapacity;
}
}
public int VifCount {
set {
ConnectManager.VifCount = value;
}
get {
return ConnectManager.VifCount;
}
}
public int VcpuCount {
set {
ConnectManager.VcpuCount = value;
}
get {
return ConnectManager.VcpuCount;
}
}
public ulong Memory {
set {
ConnectManager.Memory = value;
}
get {
return ConnectManager.Memory;
}
}
public int MaxVIFsAllowed {
set {
ConnectManager.MaxVIFsAllowed = value;
}
}
public string vmNameLabel {
set {
ConnectManager.VMName = value;
}
}
}
}
<file_sep>using System;
using WinAPI;
using System.Collections.Generic;
namespace Wizard.Core {
class ConnectManager {
private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
public const int DEFAULT_XEN_PORT = 80;//默认80
public const int DEFAULT_NUM_VIFS_ALLOWED = 7;
public static Session session;//连接session
private static string filePath;//文件路径
private static Host targetHost;//目标主机
private static string targetHostName;//目标主机IP
private static string targetHostUserName;//目标主机用户名
private static string targetHostPassword;//目标主机密码
private static string masterHostName;//master主机IP
private static ulong diskCapacity;//ova.xml文件中的VDI总大小
private static int vifCount;//ova.xml文件中的VIF数量
private static int maxVIFsAllowed;//ova.xml文件中的最大允许的VIF数量
private static int vcpuCount;//ova.xml文件中的VCPU数量
private static ulong memory;//ova.xml文件中的内存大小
private static SR sr;
private static VIF vif;
private static string networkName;
private static Dictionary<string, string> iPMaskGatewayDict;
private static string vmname;
private static string WINSERVER_API_VERSION_2_0 = "WS-2.0";
private static int connectPort; //连接的端口
public static bool IsConn;
public static void Connect(String hostName, String userName, String password, bool isMaster)
{
log.InfoFormat("开始连接主机[{0}], 用户名{1}", hostName, userName);
try {
session = SessionFactory.CreateSession(hostName, DEFAULT_XEN_PORT);
//session.login_with_password(userName, password, API_Version.LATEST);
session.login_with_password(userName, password, WINSERVER_API_VERSION_2_0); //修改XAPI连接版本号
if (!isMaster) {
targetHostUserName = userName;
targetHostPassword = <PASSWORD>;
}
ConnectPort = DEFAULT_XEN_PORT; //使用默认的80端口
log.InfoFormat("连接主机[{0}]成功", hostName);
}
catch (Failure f) {
if (f.ErrorDescription.Count > 0) {
switch (f.ErrorDescription[0])
{
case "HOST_IS_SLAVE":
// we know it is a slave so there there is no need to try and connect again, we need to connect to the master
masterHostName = f.ErrorDescription[1];
log.InfoFormat("master主机是[{0}]", masterHostName);
//已连上目标主机,保存目标主机的用户名和密码(目标主机是从节点)
targetHostUserName = userName;
targetHostPassword = <PASSWORD>;
//需要去连接master
Connect(masterHostName, userName, password, true);
break;
case "SESSION_AUTHENTICATION_FAILED":
//用户名或密码错误Count=3
case "RBAC_PERMISSION_DENIED":
// No point retrying this, the user needs the read only role at least to log in
case "HOST_UNKNOWN_TO_MASTER":
// Will never succeed, CA-74718
throw;
}
}
}
catch (Exception ex) {
log.InfoFormat("连接主机[{0}]失败", hostName);
log.Error(ex.Message);
throw;
}
}
public static bool TryParseHostname(string s, int defaultPort, out string hostname, out int port)
{
try
{
int i = s.IndexOf(':');
if (i != -1)
{
hostname = s.Substring(0, i).Trim();
port = int.Parse(s.Substring(i + 1).Trim());
}
else
{
hostname = s;
port = defaultPort; // DEFAULT_XEN_PORT;
}
return true;
}
catch (Exception)
{
hostname = null;
port = 0;
return false;
}
}
public static void closeConnect() {
if (session != null) {
session.logout();
session = null;
}
}
public static Host TargetHost {
set {
targetHost = value;
}
get {
return targetHost;
}
}
public static string TargetHostName {
set {
targetHostName = value;
}
get {
return targetHostName;
}
}
public static string MasterHostName {
set {
masterHostName = value;
}
get {
return masterHostName;
}
}
public static ulong DiskCapacity {
set {
diskCapacity = value;
}
get {
return diskCapacity;
}
}
public static int VifCount {
set {
vifCount = value;
}
get {
return vifCount;
}
}
public static int VcpuCount {
set {
vcpuCount = value;
}
get {
return vcpuCount;
}
}
public static ulong Memory {
set {
memory = value;
}
get {
return memory;
}
}
public static int MaxVIFsAllowed {
set {
maxVIFsAllowed = value;
}
get {
if (maxVIFsAllowed == 0) {
return DEFAULT_NUM_VIFS_ALLOWED;
}
return maxVIFsAllowed;
}
}
public static SR SelectedSR {
set {
sr = value;
}
get {
return sr;
}
}
public static VIF VIF {
set {
vif = value;
}
get {
return vif;
}
}
public static string NetworkName {
set {
networkName = value;
}
get {
return networkName;
}
}
public static string FilePath {
set {
filePath = value;
}
get {
return filePath;
}
}
public static Dictionary<string, string> IPMaskGatewayDict {
set {
iPMaskGatewayDict = value;
}
get {
return iPMaskGatewayDict;
}
}
public static string VMName {
set {
vmname = value;
}
get {
return vmname;
}
}
public static string TargetHostUserName {
set {
targetHostUserName = value;
}
get {
return targetHostUserName;
}
}
public static string TargetHostPassword {
set {
targetHostPassword = value;
}
get {
return targetHostPassword;
}
}
public static int ConnectPort
{
set
{
connectPort = value;
}
get
{
return connectPort;
}
}
}
}
<file_sep>using System;
using System.Windows.Forms;
using System.IO;
using System.Reflection;
using Tamir.SharpSsh;
namespace Wizard {
static class Program {
private static log4net.ILog log = null;
static Program() {
log4net.Config.XmlConfigurator.ConfigureAndWatch(new FileInfo(Assembly.GetCallingAssembly().Location + ".config"));
log = log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
}
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main() {
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainForm());
}
}
}
<file_sep>using System;
using WizardLib;
using WinAPI;
using Wizard.Core;
using System.Threading;
using System.Windows.Forms;
namespace Wizard {
public partial class HostPage : InteriorWizardPage {
private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
//private bool isFirst = true;
private string hostName;
private string userName;
private string password;
private bool IsUserName = false;
private bool IsPassword = false;
private OpaqueCommand cmd;
private bool IsTestConn = false;
public HostPage() {
InitializeComponent();
cmd = new OpaqueCommand();
}
protected override bool OnSetActive() {
if (!base.OnSetActive())
return false;
log.InfoFormat("进入【主机配置】页面");
testConnectbutton.Enabled = true;
Wizard.SetWizardButtons(WizardButton.Back | WizardButton.Next);
//if (isFirst) {
// isFirst = false;
// testConnectbutton.Enabled = false;
// Wizard.SetWizardButtons(WizardButton.Back);
//}
//else {
// testConnectbutton.Enabled = true;
// Wizard.SetWizardButtons(WizardButton.Back | WizardButton.Next);
//}
return true;
}
protected override string OnWizardNext() {
if (!checkInput()) {
return null;
}
IsTestConn = false;
Wizard.SetWizardButtons(WizardButton.Back);
ThreadStart threadStart = new ThreadStart(DoConnect);
Thread thread = new Thread(threadStart);
thread.Start();
cmd.ShowOpaqueLayer(panel1, 125, true);
return null;
}
private bool checkInput() {
targetIPInfoLabel.Text = "*";
if (!this.ipBox1.IsValidate) {
targetIPInfoLabel.Text = "请输入IP地址!";
return false;
}
if (String.IsNullOrEmpty(usernameTextBox.Text)) {
userNameInfoLabel.Text = "请输入用户名!";
return false;
}
if (String.IsNullOrEmpty(passwordTextBox.Text)) {
passInfoLabel.Text = "请输入密码!";
return false;
}
return true;
}
private void testConnectbutton_Click(object sender, EventArgs e) {
if (!checkInput()) {
return;
}
testConnectbutton.Enabled = false;
IsTestConn = true;
Wizard.SetWizardButtons(WizardButton.Back);
ThreadStart threadStart = new ThreadStart(DoConnect);
Thread thread = new Thread(threadStart);
thread.Start();
cmd.ShowOpaqueLayer(panel1, 125, true);
}
private void DoConnect() {
string info = "";
ConnectManager.IsConn = false;
try {
bool isConn = setConnect();
if (isConn) {
info = "连接成功!";
ConnectManager.IsConn = true;
}
}
catch (Failure f) {
info = f.Message;
}
catch (Exception ex) {
info = ex.Message;
}
ConnFinished(info);
}
private bool setConnect() {
bool isMaster = false;
if (masterTextBox.Visible && !masterTextBox.Text.Equals(ipBox1.Value)) {
isMaster = true;
}
hostName = masterTextBox.Visible ? masterTextBox.Text : ipBox1.Value;
userName = usernameTextBox.Text;
password = <PASSWORD>;
try {
ConnectManager.MasterHostName = "";
ConnectManager.Connect(hostName, userName, password, isMaster);
ConnectManager.TargetHostName = ipBox1.Value;
}
catch (Exception) {
if (!String.IsNullOrEmpty(ConnectManager.MasterHostName)) {
return false;
}
else {
throw;
}
}
return true;
}
private delegate void changeText(string info);
public void ConnFinished(string info) {
if (this.InvokeRequired) {
this.BeginInvoke(new changeText(ConnFinished), info);
}
else {
cmd.HideOpaqueLayer();
if (Wizard != null) {
Wizard.SetWizardButtons(WizardButton.Back | WizardButton.Next);
if (!string.IsNullOrEmpty(info)) {
if (info.IndexOf("authenticate") > 0) {
testConnectLabel.Text = "用户名或密码错误";
}
else {
testConnectLabel.Text = info;
}
}
testConnectbutton.Enabled = true;
masterLabel.Visible = masterTextBox.Visible = false;
if(ConnectManager.IsConn) {
if (!IsTestConn) {
foreach (WizardPage page in Wizard.m_pages) {
if ("HostPage" == page.Name) {
Wizard.ActivatePage(Wizard.m_pages.IndexOf(page) + 1);
break;
}
}
}
} else {
string masterHostName = ConnectManager.MasterHostName;
if (!String.IsNullOrEmpty(masterHostName)) {
masterLabel.Visible = masterTextBox.Visible = true;
this.ipBox1.BindTextBox = masterTextBox;
masterTextBox.Text = masterHostName;
passwordTextBox.Text = "";
testConnectLabel.Text = "请输入管理节点用户密码!";
}
}
}
}
}
private void usernameTextBox_TextChanged(Object sender, EventArgs e) {
if (String.IsNullOrEmpty(usernameTextBox.Text)) {
userNameInfoLabel.Text = "请输入用户名!";
return;
}
else {
userNameInfoLabel.Text = "*";
IsUserName = true;
if (!this.ipBox1.IsValidate && IsPassword) {
//testConnectbutton.Enabled = true;
//Wizard.SetWizardButtons(WizardButton.Back | WizardButton.Next);
}
else {
//testConnectbutton.Enabled = false;
//Wizard.SetWizardButtons(WizardButton.Back);
}
}
}
private void passwordTextBox_TextChanged(Object sender, EventArgs e) {
if (String.IsNullOrEmpty(passwordTextBox.Text)) {
passInfoLabel.Text = "请输入密码!";
return;
}
else {
passInfoLabel.Text = "*";
IsPassword = true;
if (!this.ipBox1.IsValidate && IsUserName) {
//testConnectbutton.Enabled = true;
//Wizard.SetWizardButtons(WizardButton.Back | WizardButton.Next);
}
else {
//testConnectbutton.Enabled = false;
//Wizard.SetWizardButtons(WizardButton.Back);
}
}
}
}
}
<file_sep>using System;
using System.IO;
namespace WizardLib.Core {
public class PathValidator {
private static readonly char[] m_invalidFileCharList = Path.GetInvalidFileNameChars();
private static readonly string[] m_deviceNames = {
"CON", "PRN", "AUX", "NUL",
"COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9",
"LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9"
};
public static bool IsFileNameValid(string filename) {
if (filename.IndexOfAny(m_invalidFileCharList) > -1)
return false;
foreach (var name in m_deviceNames) {
if (name == filename.ToUpper())
return false;
}
return true;
}
public static bool IsPathValid(string path) {
if (string.IsNullOrEmpty(path))
return false;
try {
if (Path.IsPathRooted(path)) {
path = path[0] == '\\' && path.Length == 1
? path.Substring(1)
: path.Substring(2);
}
}
catch (ArgumentException) {
//path contains a character from Path.GetInvalidPathChars()
return false;
}
string[] parts = path.Split(new[] { '\\' });
if (parts.Length > 0) {
foreach (var part in parts) {
if (part.IndexOfAny(m_invalidFileCharList) > -1)
return false;
foreach (var name in m_deviceNames) {
if (name == part.ToUpper())
return false;
}
}
}
return true;
}
}
}
<file_sep>using System.Windows.Forms;
namespace WizardLib {
public partial class WizardPage : UserControl {
public WizardPage() {
InitializeComponent();
}
// ==================================================================
// Protected Properties
// ==================================================================
/// <summary>
/// Gets the <see cref="WizardForm">WizardForm</see>
/// to which this <see cref="WizardPage">WizardPage</see>
/// belongs.
/// </summary>
protected WizardForm Wizard {
get {
// Return the parent WizardForm
return (WizardForm)Parent;
}
}
// ==================================================================
// Protected Internal Methods
// ==================================================================
/// <summary>
/// Called when the page is no longer the active page.
/// </summary>
/// <returns>
/// <c>true</c> if the page was successfully deactivated; otherwise
/// <c>false</c>.
/// </returns>
/// <remarks>
/// Override this method to perform special data validation tasks.
/// </remarks>
protected internal virtual bool OnKillActive() {
// Deactivate if validation successful
return Validate();
}
/// <summary>
/// Called when the page becomes the active page.
/// </summary>
/// <returns>
/// <c>true</c> if the page was successfully set active; otherwise
/// <c>false</c>.
/// </returns>
/// <remarks>
/// Override this method to performs tasks when a page is activated.
/// Your override of this method should call the default version
/// before any other processing is done.
/// </remarks>
protected internal virtual bool OnSetActive() {
// Activate the page
return true;
}
/// <summary>
/// Called when the user clicks the Back button in a wizard.
/// </summary>
/// <returns>
/// <c>WizardForm.DefaultPage</c> to automatically advance to the
/// next page; <c>WizardForm.NoPageChange</c> to prevent the page
/// changing. To jump to a page other than the next one, return
/// the <c>Name</c> of the page to be displayed.
/// </returns>
/// <remarks>
/// Override this method to specify some action the user must take
/// when the Back button is pressed.
/// </remarks>
protected internal virtual string OnWizardBack() {
// Move to the default previous page in the wizard
return WizardForm.NextPage;
}
/// <summary>
/// Called when the user clicks the Finish button in a wizard.
/// </summary>
/// <returns>
/// <c>true</c> if the wizard finishes successfully; otherwise
/// <c>false</c>.
/// </returns>
/// <remarks>
/// Override this method to specify some action the user must take
/// when the Finish button is pressed. Return <c>false</c> to
/// prevent the wizard from finishing.
/// </remarks>
protected internal virtual bool OnWizardFinish() {
// Finish the wizard
return true;
}
/// <summary>
/// Called when the user clicks the Next button in a wizard.
/// </summary>
/// <returns>
/// <c>WizardForm.DefaultPage</c> to automatically advance to the
/// next page; <c>WizardForm.NoPageChange</c> to prevent the page
/// changing. To jump to a page other than the next one, return
/// the <c>Name</c> of the page to be displayed.
/// </returns>
/// <remarks>
/// Override this method to specify some action the user must take
/// when the Next button is pressed.
/// </remarks>
protected internal virtual string OnWizardNext() {
// Move to the default next page in the wizard
return WizardForm.NextPage;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.IO;
using Ionic.Zip;
namespace WizardLib.Archive
{
public class ExtractProgressChangedEventArgs : EventArgs
{
private readonly long bytesIn;
private readonly long totalBytes;
public ExtractProgressChangedEventArgs(long bytesTransferred, long totalBytesToTransfer)
{
bytesIn = bytesTransferred;
totalBytes = totalBytesToTransfer;
}
public long BytesTransferred
{
get { return bytesIn; }
}
public long TotalBytesToTransfer
{
get { return totalBytes; }
}
}
public class DotNetZipZipIterator : ArchiveIterator
{
private ZipFile zipFile = null;
private IEnumerator<ZipEntry> enumerator = null;
private ZipEntry zipEntry;
private bool disposed;
public event EventHandler<ExtractProgressChangedEventArgs> CurrentFileExtractProgressChanged;
public event EventHandler<EventArgs> CurrentFileExtractCompleted;
public DotNetZipZipIterator()
{
disposed = false;
}
void zipFile_ExtractProgress(object sender, ExtractProgressEventArgs e)
{
switch (e.EventType)
{
case ZipProgressEventType.Extracting_EntryBytesWritten:
{
EventHandler<ExtractProgressChangedEventArgs> handler = CurrentFileExtractProgressChanged;
if (handler != null)
handler(this, new ExtractProgressChangedEventArgs(e.BytesTransferred, e.TotalBytesToTransfer));
}
break;
case ZipProgressEventType.Extracting_AfterExtractEntry:
{
EventHandler<EventArgs> handler = CurrentFileExtractCompleted;
if (handler != null)
handler(this, e);
}
break;
}
}
public DotNetZipZipIterator(Stream inputStream) : this()
{
Initialise(inputStream);
}
private void Initialise(Stream zipStream)
{
try
{
zipFile = ZipFile.Read(zipStream);
}
catch (ZipException e)
{
throw new ArgumentException("Cannot read input as a ZipFile", "zipStream", e);
}
enumerator = zipFile.GetEnumerator();
zipFile.ExtractProgress += zipFile_ExtractProgress;
}
public override void SetBaseStream(Stream inputStream)
{
Initialise(inputStream);
disposed = false;
}
~DotNetZipZipIterator()
{
Dispose();
}
public override bool HasNext()
{
if (enumerator != null && enumerator.MoveNext())
{
zipEntry = enumerator.Current;
return true;
}
return false;
}
public override string CurrentFileName()
{
if (zipEntry == null)
return String.Empty;
return zipEntry.FileName;
}
public override long CurrentFileSize()
{
if (zipEntry == null)
return 0;
return zipEntry.UncompressedSize;
}
public override DateTime CurrentFileModificationTime()
{
if (zipEntry == null)
return new DateTime();
return zipEntry.LastModified;
}
public override bool IsDirectory()
{
if (zipEntry == null)
return false;
return zipEntry.IsDirectory;
}
public override void ExtractCurrentFile(Stream extractedFileContents)
{
if (IsDirectory())
return;
zipEntry.Extract(extractedFileContents);
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
if(disposing)
{
if(!disposed)
{
if (zipFile != null)
{
zipFile.ExtractProgress -= zipFile_ExtractProgress;
zipFile.Dispose();
}
disposed = true;
}
}
}
}
}
<file_sep>using System.Text;
using System.IO;
using Tamir.SharpSsh.jsch;
namespace Tamir.SharpSsh {
public class ShellHelp {
private MemoryStream outputstream = new MemoryStream();
private SshStream inputstream = null;
/// <summary>
/// 命令等待标识,用来标识命令是否执行完成的,执行完成就会在后面输出这个字符,有时也有可能是"]$"
/// </summary>
private string waitMark = "]#";
/// <summary>
/// 打开连接
/// </summary>
/// <param name="host"></param>
/// <param name="username"></param>
/// <param name="pwd"></param>
/// <param name="privateKeyPath"></param>
/// <returns></returns>
public bool OpenShell(string host, string username, string pwd, string privateKeyPath) {
try {
////Redirect standard I/O to the SSH channel
inputstream = new SshStream(host, username, pwd, privateKeyPath);
///我手动加进去的方法。。为了读取输出信息
inputstream.set_OutputStream(outputstream);
return inputstream != null;
}
catch { throw; }
}
/// <summary>
/// 执行命令
/// </summary>
/// <param name="cmd"></param>
public bool Shell(string cmd) {
if (inputstream == null) return false;
string initinfo = GetAllString();
inputstream.Write(cmd);
inputstream.Flush();
string currentinfo = GetAllString();
while (currentinfo == initinfo) {
System.Threading.Thread.Sleep(100);
currentinfo = GetAllString();
}
return true;
}
/// <summary>
/// 获取输出信息
/// </summary>
/// <returns></returns>
public string GetAllString() {
string outinfo = Encoding.UTF8.GetString(outputstream.ToArray());
//等待命令结束字符
while (!outinfo.Trim().EndsWith(waitMark)) {
System.Threading.Thread.Sleep(200);
outinfo = Encoding.UTF8.GetString(outputstream.ToArray());
}
outputstream.Flush();
return outinfo.ToString();
}
/// <summary>
/// 关闭连接
/// </summary>
public void Close() {
if (inputstream != null) inputstream.Close();
}
}
}
<file_sep>using WizardLib;
using Wizard.Core;
using System.Threading;
using System;
using System.Windows.Forms;
using WinAPI;
namespace Wizard {
public partial class ImportVMPage : InteriorWizardPage {
private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
public ImportVMPage() {
InitializeComponent();
}
protected override bool OnSetActive() {
if (!base.OnSetActive())
return false;
log.InfoFormat("进入【安装虚拟机】页面");
label1.Text = "";
ShowData();
Wizard.SetWizardButtons(WizardButton.Back);
return true;
}
protected override string OnWizardNext() {
return base.OnWizardNext();
}
private void ShowData() {
string memory = string.Format("{0:0.00}GB", ConnectManager.Memory / Constants.UINT);
log.InfoFormat("文件路径:{0}", ConnectManager.FilePath);
log.InfoFormat("目标主机:{0}", ConnectManager.TargetHostName);
log.InfoFormat("存储:{0}", ConnectManager.SelectedSR.name_label);
log.InfoFormat("虚拟机名称:{0}", ConnectManager.VMName);
log.InfoFormat("虚拟机配置:内存 {0},VCPU {1}个", memory, ConnectManager.VcpuCount);
this.filePathLabel.Text = string.Format("文件路径:{0}", ConnectManager.FilePath);
this.toolTip1.SetToolTip(this.filePathLabel, ConnectManager.FilePath);
this.targetHostLabel.Text = string.Format("目标主机:{0}", ConnectManager.TargetHostName);
this.storageLabel.Text = string.Format("存 储:{0}", ConnectManager.SelectedSR.name_label);
this.VMNameLabel.Text = string.Format("虚拟机名称:{0}", ConnectManager.VMName);
this.networkLabel.Text = string.Format("虚拟机配置:内存 {0},VCPU {1}个", memory, ConnectManager.VcpuCount);
string ip = "";
ConnectManager.IPMaskGatewayDict.TryGetValue("ip", out ip);
this.ipLabel.Text = string.Format("IP 地 址:{0}", ip);
string netmask = "";
ConnectManager.IPMaskGatewayDict.TryGetValue("netmask", out netmask);
this.maskLabel.Text = string.Format("掩 码:{0}", netmask);
string gateway = "";
ConnectManager.IPMaskGatewayDict.TryGetValue("gateway", out gateway);
this.gatewayLabel.Text = string.Format("网 关:{0}", gateway);
}
private void importButton_Click(object sender, System.EventArgs e) {
log.InfoFormat("开始安装WinCenter VM");
if (!checkMemory()) {
return;
}
importButton.Enabled = false;
Wizard.SetWizardButtons(WizardButton.DisabledAll);
//注册关闭按钮事件
Wizard.FormClosing += new FormClosingEventHandler(FormClosing);
HTTPHelper.errorInfo = "";
Thread workThread = new Thread(new ThreadStart(ProcessImp));
workThread.Start();
Thread uiThread = new Thread(new ThreadStart(ChangeProgress));
uiThread.Start();
}
private bool checkMemory() {
XenRef<Host> hostRef = Host.get_by_uuid(ConnectManager.session, ConnectManager.TargetHost.uuid);
ulong free_memory = (ulong)Host.compute_free_memory(ConnectManager.session, hostRef);
string hostFreeMemory = string.Format("{0:0.00}GB", free_memory / Constants.UINT);
string vmMemory = string.Format("{0:0.00}GB", ConnectManager.Memory / Constants.UINT);
log.InfoFormat("物理主机可用内存为{0},虚拟机需要的内存为{1}", hostFreeMemory, vmMemory);
if (ConnectManager.Memory > free_memory)
{
log.ErrorFormat("物理主机的可用内存不够!");
label1.Text = "物理主机的可用内存不够!";
return false;
}
return true;
}
private void FormClosing(object sender, FormClosingEventArgs e) {
e.Cancel = true;
log.InfoFormat("安装过程中,禁止关闭窗口");
}
private void ProcessImp() {
DateTime startTime = System.DateTime.Now;
try {
VMOper vmOper = new VMOper();
vmOper.ImpXvaFile();
DateTime endTime = System.DateTime.Now;
TimeSpan time = endTime - startTime;
log.InfoFormat("安装WinCenter VM总耗时: {0}小时{1}分钟{2}秒", time.Hours, time.Minutes, time.Seconds);
log.InfoFormat("安装WinCenter VM成功");
}
catch (Exception ex) {
HTTPHelper.errorInfo = ex.Message;
log.InfoFormat("安装WinCenter VM失败Message: {0}", ex.Message);
log.InfoFormat("安装WinCenter VM失败StackTrace: {0}", ex.StackTrace);
}
}
private void ChangeProgress() {
int i = 0;
while (true) {
while (!this.importButton.IsHandleCreated) {
//解决窗体关闭时出现“访问已释放句柄“的异常
if (this.importButton.Disposing || this.importButton.IsDisposed)
return;
}
int progressPercent = HTTPHelper.progressPercent;
this.Invoke(new Action<int>(this.UpdateProgress), progressPercent);
if (progressPercent == 100 || !string.IsNullOrEmpty(HTTPHelper.errorInfo)) {
if(i == 1) {
Wizard.FormClosing -= new FormClosingEventHandler(FormClosing);
break;
}
i++;
}
}
}
private void UpdateProgress(int progressPercent) {
if (string.IsNullOrEmpty(HTTPHelper.errorInfo)) {
progressBar1.Value = progressPercent;
label1.Text = "正在导入,进度:" + progressPercent + "%";
if (progressPercent >= 90) {
label1.Text = HTTPHelper.progressInfo + ",进度:" + progressPercent + "%";
}
label1.Refresh();
if (progressPercent == 100) {
label1.Text = "安装完成:" + progressPercent + "%";
label1.Refresh();
Wizard.SetWizardButtons(WizardButton.Next);
log.InfoFormat("WinCenter VM安装完成");
}
}
else {
//label1.Text = "安装失败:" + HTTPHelper.errorInfo;
label1.Text = "安装失败,详情请查看日志!";
label1.Refresh();
importButton.Enabled = true;
Wizard.SetWizardButtons(WizardButton.Back);
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using WizardLib;
namespace Wizard {
public partial class WelComePage : ExteriorWizardPage {
private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
public WelComePage() {
InitializeComponent();
}
protected override bool OnSetActive() {
if (!base.OnSetActive())
return false;
log.InfoFormat("WinCenter安装向导开始,进入【欢迎】页面");
Wizard.SetWizardButtons(WizardButton.Next);
return true;
}
}
}
<file_sep>
using System;
using System.Collections.Generic;
namespace Wizard {
class SRVo {
public SRVo() {
}
private string _uuid;
private string _name;
private long _availableCapacity;
private long _physicalSize;
private string _type;
private string _info;
public string Uuid {
set {
_uuid = value;
}
get {
return _uuid;
}
}
public string Name {
set {
_name = value;
}
get {
return _name;
}
}
public long AvailableCapacity {
set {
_availableCapacity = value;
}
get {
return _availableCapacity;
}
}
public long PhysicalSize {
set {
_physicalSize = value;
}
get {
return _physicalSize;
}
}
public string Type {
set {
_type = value;
}
get {
return _type;
}
}
public string Info {
set {
_info = value;
}
get {
return _info;
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
/*
* 按钮按下去时,还是去出现黑线框,这个黑线框通过属性设置时无法去掉的,需要自定义按钮,然后重绘。
* 自定义了一个Button。点击Button时不会出现黑色边框
*
*/
namespace WizardLib {
class MyButton : Button {
public MyButton() {
}
protected override bool ShowFocusCues {
get {
return false;
}
}
}
}
<file_sep>using System;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using WizardLib;
using WizardLib.Core;
using System.IO;
using System.Xml;
using System.Xml.XPath;
using WizardLib.Archive;
using Wizard.Core;
namespace Wizard {
public partial class ImportSourcePage : InteriorWizardPage {
private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
private readonly string supportedXvaTypes = ".xva";
private int VifCount = 0;
private int VcpuCount = 0;
private ulong memory = 0;
private string MaxVIFsAllowedValue = null;
private bool isFirst = true;
private string nameLabel;
public ImportSourcePage() {
InitializeComponent();
}
protected override bool OnSetActive() {
if (!base.OnSetActive())
return false;
log.InfoFormat("进入【安装来源】页面");
if (isFirst) {
isFirst = false;
string startupPath = System.Windows.Forms.Application.StartupPath;
string tmpPath = startupPath + Path.DirectorySeparatorChar + Constants.DEFAULT_TMP_FILE_NAME + supportedXvaTypes;
if (File.Exists(tmpPath)) {
textBoxFile.Text = tmpPath;
textBoxFile.Select(0, 0);
Wizard.SetWizardButtons(WizardButton.Back | WizardButton.Next);
}
else {
Wizard.SetWizardButtons(WizardButton.Back);
}
}
else {
Wizard.SetWizardButtons(WizardButton.Back | WizardButton.Next);
}
return true;
}
protected override string OnWizardNext() {
log.InfoFormat("开始校验文件");
string error = null;
if (!CheckIsSupportedType(out error)) {
ctrlErrorLabel.Text = error;
ctrlErrorLabel.Visible = true;
return null;
}
if (!CheckPathExists(out error)) {
ctrlErrorLabel.Text = error;
ctrlErrorLabel.Visible = true;
return null;
}
if (!GetDiskCapacityXva(out error)) {
ctrlErrorLabel.Text = error;
ctrlErrorLabel.Visible = true;
return null;
}
log.InfoFormat("文件校验完成");
ctrlErrorLabel.Text = "";
ctrlErrorLabel.Visible = false;
ConnectManager.FilePath = textBoxFile.Text;
return base.OnWizardNext();
}
private void buttonBrowse_Click(object sender, EventArgs e) {
using (FileDialog ofd = new OpenFileDialog {
CheckFileExists = true,
CheckPathExists = true,
DereferenceLinks = true,
Filter = "XVA files (*.xva)|*.xva",
RestoreDirectory = true,
Multiselect = false,
}) {
if (ofd.ShowDialog() == DialogResult.OK)
textBoxFile.Text = ofd.FileName;
}
}
private void textBoxFile_TextChanged(object sender, EventArgs e) {
string error = null;
bool flag = CheckPathValid(out error);
if (!flag) {
ctrlErrorLabel.Text = error;
ctrlErrorLabel.Visible = true;
Wizard.SetWizardButtons(WizardButton.Back);
return;
}
flag = CheckIsSupportedType(out error);
if (!flag) {
ctrlErrorLabel.Text = error;
ctrlErrorLabel.Visible = true;
Wizard.SetWizardButtons(WizardButton.Back);
return;
}
flag = CheckPathExists(out error);
if (!flag) {
ctrlErrorLabel.Text = error;
ctrlErrorLabel.Visible = true;
Wizard.SetWizardButtons(WizardButton.Back);
return;
}
ctrlErrorLabel.Text = "";
ctrlErrorLabel.Visible = true;
Wizard.SetWizardButtons(WizardButton.Back | WizardButton.Next);
}
private bool CheckPathValid(out string error) {
error = String.Empty;
string filepath = textBoxFile.Text;
if (String.IsNullOrEmpty(filepath.TrimEnd())) {
error = "模板路径不能为空";
return false;
}
//if it's URI ignore
if (IsUri())
return true;
if (!PathValidator.IsPathValid(filepath)) {
error = "模板路径中包含无效的字符";
return false;
}
return true;
}
private bool IsUri() {
string uriRegex = "^(http|https|file|ftp)://*";
Regex regex = new Regex(uriRegex, RegexOptions.IgnoreCase);
return regex.Match(textBoxFile.Text).Success;
}
private bool CheckIsSupportedType(out string error) {
error = string.Empty;
string filepath = textBoxFile.Text;
if (filepath.ToLower().EndsWith(supportedXvaTypes)) {
return true;
} else {
error = "文件格式不正确,应为*.xva格式!";
return false;
}
}
private bool CheckPathExists(out string error) {
error = string.Empty;
string filepath = textBoxFile.Text;
if (File.Exists(filepath))
return true;
error = "模板路径不存在!";
return false;
}
private bool GetDiskCapacityXva(out string error) {
error = string.Empty;
ulong ImageLength = 0;
try {
FileInfo info = new FileInfo(textBoxFile.Text);
ImageLength = info.Length > 0 ? (ulong)info.Length : 0;
SROper sROper = new SROper();
sROper.DiskCapacity = GetTotalSizeFromXmlXva(GetXmlStringFromTarXVA()); //xva style
sROper.VifCount = this.VifCount;
sROper.VcpuCount = this.VcpuCount;
sROper.Memory = this.memory;
sROper.vmNameLabel = this.nameLabel;
int MaxVIFsAllowed = 0;
try {
MaxVIFsAllowed = Convert.ToInt32(MaxVIFsAllowedValue);
}
catch {
MaxVIFsAllowed = 0;
}
sROper.MaxVIFsAllowed = MaxVIFsAllowed;
}
catch (Exception ex ) {
//error = ex.Message;
error = "模板文件内容不正确!";
log.ErrorFormat(error+ ":{0}", ex.Message);
return false;
}
return true;
}
private string GetXmlStringFromTarXVA() {
using (Stream stream = new FileStream(textBoxFile.Text, FileMode.Open, FileAccess.Read)) {
ArchiveIterator iterator = ArchiveFactory.Reader(ArchiveFactory.Type.Tar, stream);
if (iterator.HasNext()) {
Stream ofs = new MemoryStream();
iterator.ExtractCurrentFile(ofs);
ofs.Position = 0;
return new StreamReader(ofs).ReadToEnd();
}
return String.Empty;
}
}
private ulong GetTotalSizeFromXmlXva(string xmlString) {
log.InfoFormat("开始解析配置文件");
ulong totalSize = 0;
XmlDocument xmlMetadata = new XmlDocument();
xmlMetadata.LoadXml(xmlString);
XPathNavigator nav = xmlMetadata.CreateNavigator();
XPathNodeIterator nodeIteratorIsaTemplate = nav.Select(".//name[. = \"is_a_template\"]");
while (nodeIteratorIsaTemplate.MoveNext()) {
XPathNavigator vdiNavigator = nodeIteratorIsaTemplate.Current;
if (vdiNavigator.MoveToNext()) {
string is_a_template = vdiNavigator.Value;
if (is_a_template == "1") {
string error = "模板路径xva文件是虚拟机模板文件,请重新选择!";
log.InfoFormat("{0}", error);
throw new Exception(error);
}
}
}
XPathNodeIterator snapshotNodeIterator = nav.Select(".//name[. = \"snapshot\"]");
while (snapshotNodeIterator.MoveNext()) {
XPathNavigator snapshotNavigator = snapshotNodeIterator.Current;
if (snapshotNavigator.MoveToNext()) {
XPathNodeIterator powerStateIterator = snapshotNavigator.Select(".//name[. = \"power_state\"]");
bool flag = false;
while(powerStateIterator.MoveNext()) {
flag = true;
break;
}
if (flag) {
XPathNodeIterator nameLabelIterator = snapshotNavigator.Select(".//name[. = \"name_label\"]");
while (nameLabelIterator.MoveNext()) {
XPathNavigator vmNameNavigator = nameLabelIterator.Current;
if (vmNameNavigator.MoveToNext())
nameLabel = vmNameNavigator.Value;
break;
}
break;
}
}
}
log.InfoFormat("xva文件中的虚拟机名称为:{0}", nameLabel);
XPathNodeIterator nodeIterator = nav.Select(".//name[. = \"virtual_size\"]");
while (nodeIterator.MoveNext()) {
XPathNavigator vdiNavigator = nodeIterator.Current;
if (vdiNavigator.MoveToNext())
totalSize += UInt64.Parse(vdiNavigator.Value);
}
log.InfoFormat("xva文件VDI总大小: {0:0.00}GB", (totalSize / Constants.UINT));
//string vifs = "";
//XPathNodeIterator nodeIteratorVIFs = nav.Select(".//name[. = \"VIFs\"]");
//while (nodeIteratorVIFs.MoveNext()) {
// XPathNavigator vdiNavigator = nodeIteratorVIFs.Current;
// if (vdiNavigator.MoveToNext())
// if (vifs.IndexOf(vdiNavigator.Value) < 0) {
// vifs += vdiNavigator.Value;
// this.VifCount++;
// }
//}
//log.InfoFormat("xva文件中的VIF数量为:{0}", this.VifCount);
XPathNodeIterator nodeIteratorVCPUs = nav.Select(".//name[. = \"VCPUs_at_startup\"]");
while (nodeIteratorVCPUs.MoveNext()) {
XPathNavigator vdiNavigator = nodeIteratorVCPUs.Current;
if (vdiNavigator.MoveToNext()) {
this.VcpuCount = Convert.ToInt32(vdiNavigator.Value);
break;
}
}
log.InfoFormat("xva文件中的VCPU数量为:{0}", this.VcpuCount);
XPathNodeIterator nodeIteratorMem = nav.Select(".//name[. = \"memory_dynamic_max\"]"); //内存四个值设置同样大小,这里取动态最大值
while (nodeIteratorMem.MoveNext()) {
XPathNavigator vdiNavigator = nodeIteratorMem.Current;
if (vdiNavigator.MoveToNext()) {
this.memory = UInt64.Parse(vdiNavigator.Value);
break;
}
}
log.InfoFormat("xva文件中的memory为:{0:0.00}GB", this.memory / Constants.UINT);
//XmlNode xn = xmlMetadata.SelectSingleNode(@"restrictions/restriction[@property='number-of-vifs']");
//this.MaxVIFsAllowedValue = xn.Attributes["max"].Value;
//System.Console.WriteLine("xva文件中的最大允许的VIF数量为:{0}", this.MaxVIFsAllowedValue);
log.InfoFormat("配置文件解析完成");
return totalSize;
}
}
}
<file_sep>using System;
using System.IO;
namespace WizardLib
{
public class StreamUtilities
{
/// <summary>
/// Perform a copy of the contents of one stream class to another in a buffered fashion
///
/// Buffer size is a hard-coded 2Mb
/// </summary>
/// <param name="inputData">Source data</param>
/// <param name="outputData">Target stream</param>
public static void BufferedStreamCopy(Stream inputData, Stream outputData)
{
if( inputData == null)
throw new ArgumentNullException("inputData", "BufferedStreamCopy argument cannot be null");
if (outputData == null)
throw new ArgumentNullException("outputData", "BufferedStreamCopy argument cannot be null");
const long bufferSize = 2*1024*1024;
byte[] buffer = new byte[bufferSize];
int n;
while ((n = inputData.Read(buffer, 0, buffer.Length)) > 0)
{
outputData.Write(buffer, 0, n);
}
outputData.Flush();
}
}
}
<file_sep>using System;
using System.IO;
namespace WizardLib.Compression
{
/// <summary>
/// Abstract base class for the compression stream class
/// </summary>
public abstract class CompressionStream : Stream
{
private Stream storedStream = null;
protected Stream zipStream
{
set
{
disposed = false;
storedStream = value;
}
private get { return storedStream; }
}
public virtual void SetBaseStream(Stream baseStream)
{
throw new NotImplementedException();
}
private bool disposed = true;
protected CompressionStream()
{
zipStream = null;
disposed = true;
}
/// <summary>
/// Write *to* this stream *from* the source stream in a buffered manner analogous to Write()
/// </summary>
/// <param name="sourceStream">Stream get data from</param>
public void BufferedWrite(Stream sourceStream)
{
StreamUtilities.BufferedStreamCopy(sourceStream, this);
}
/// <summary>
/// Read *from* this stream and write to the targetStream in a buffered manner as per the Read()
/// </summary>
/// <param name="targetStream">Stream to put data into</param>
public void BufferedRead(Stream targetStream)
{
StreamUtilities.BufferedStreamCopy(this, targetStream);
}
public override int Read(byte[] buffer, int offset, int count)
{
return zipStream.Read(buffer, offset, count);
}
public override long Position
{
get { return zipStream.Position; }
set { zipStream.Position = value; }
}
protected override void Dispose(bool disposing)
{
if( disposing )
{
if (!disposed)
{
if (zipStream != null)
{
zipStream.Dispose();
zipStream = null;
}
disposed = true;
}
}
base.Dispose(disposing);
}
public override void Write(byte[] buffer, int offset, int count)
{
zipStream.Write(buffer, offset, count);
}
public override bool CanRead
{
get { return zipStream.CanRead; }
}
public override bool CanSeek
{
get { return zipStream.CanSeek; }
}
public override bool CanWrite
{
get { return zipStream.CanWrite; }
}
public override void Flush()
{
zipStream.Flush();
}
public override long Length
{
get { return zipStream.Length; }
}
public override long Seek(long offset, SeekOrigin origin)
{
return zipStream.Seek(offset, origin);
}
public override void SetLength(long value)
{
zipStream.SetLength(value);
}
}
}
<file_sep>using System;
using System.IO;
using System.Text;
using ICSharpCode.SharpZipLib.Tar;
namespace WizardLib.Archive
{
public class SharpZipTarArchiveWriter : ArchiveWriter
{
private TarOutputStream tar = null;
private const long bufferSize = 32*1024;
protected bool disposed;
public SharpZipTarArchiveWriter()
{
disposed = false;
}
public SharpZipTarArchiveWriter(Stream outputStream) : this()
{
tar = new TarOutputStream(outputStream);
}
public override void SetBaseStream(Stream outputStream)
{
tar = new TarOutputStream(outputStream);
disposed = false;
}
public override void AddDirectory(string directoryName, DateTime modificationTime)
{
StringBuilder sb = new StringBuilder(directoryName);
//Need to add a terminal front-slash to add a directory
if (!directoryName.EndsWith("/"))
sb.Append("/");
TarEntry entry = TarEntry.CreateTarEntry(sb.ToString());
entry.ModTime = modificationTime;
tar.PutNextEntry(entry);
tar.CloseEntry();
}
public override void Add(Stream filetoAdd, string fileName, DateTime modificationTime)
{
TarEntry entry = TarEntry.CreateTarEntry(fileName);
entry.Size = filetoAdd.Length;
entry.ModTime = modificationTime;
tar.PutNextEntry( entry );
byte[] buffer = new byte[bufferSize];
int n;
//You have to do this because if using a memory stream the pointer will be at the end it
//it's just been read and this will cause nothing to be written out
filetoAdd.Position = 0;
while ((n = filetoAdd.Read(buffer, 0, buffer.Length)) > 0)
{
tar.Write(buffer, 0, n);
}
tar.Flush();
tar.CloseEntry();
}
protected override void Dispose(bool disposing)
{
if( !disposed )
{
if( disposing )
{
if (tar != null)
{
tar.Dispose();
}
disposed = true;
}
}
base.Dispose(disposing);
}
}
}
<file_sep>using System;
using System.IO;
namespace WizardLib.Archive
{
public abstract class ArchiveWriter : IDisposable
{
public abstract void Add(Stream filetoAdd, string fileName, DateTime modificationTime);
public virtual void SetBaseStream(Stream outputStream)
{
throw new NotImplementedException();
}
public abstract void AddDirectory(string directoryName, DateTime modificationTime);
/// <summary>
/// Disposal hook
/// </summary>
/// <param name="disposing"></param>
protected virtual void Dispose(bool disposing){ }
public void CreateArchive( string pathToArchive )
{
if( !Directory.Exists(pathToArchive) )
throw new FileNotFoundException( "The path " + pathToArchive + " does not exist" );
foreach (string filePath in Directory.GetFiles(pathToArchive, "*.*", SearchOption.AllDirectories))
{
using (FileStream fs = File.OpenRead(filePath))
{
Add(fs, CleanRelativePathName(pathToArchive, filePath), File.GetCreationTime(filePath));
}
}
foreach (string dirPath in Directory.GetDirectories(pathToArchive, "*.*", SearchOption.AllDirectories))
{
AddDirectory(CleanRelativePathName(pathToArchive, dirPath), Directory.GetCreationTime(dirPath));
}
}
public void Add(Stream filetoAdd, string fileName)
{
Add( filetoAdd, fileName, DateTime.Now );
}
public void AddDirectory(string directoryName)
{
AddDirectory(directoryName, DateTime.Now);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private string CleanRelativePathName(string rootPath, string pathName)
{
return pathName.Replace(rootPath, "").Replace('\\', '/').TrimStart('/');
}
}
}
<file_sep>using System.Collections.Generic;
using WinAPI;
namespace Wizard.Core {
class VIFOper {
public List<VIF> getVIFList() {
List<VIF> vifList = new List<VIF>();
List<XenRef<VIF>> vifRefs = VIF.get_all(ConnectManager.session);
foreach (XenRef<VIF> vifRef in vifRefs) {
VIF vif = VIF.get_record(ConnectManager.session, vifRef);
vifList.Add(vif);
}
return vifList;
}
}
}
<file_sep>using System.Text.RegularExpressions;
namespace Wizard {
class Constants {
public const string DEFAULT_TMP_FILE_NAME = "CNware虚拟化管理系统镜像-CentOS";
public static readonly Regex MacRegex = new Regex(@"(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])");
public const double UINT = 1073741824D; //1024D * 1024D * 1024D,转换成GB
public const string AE_ISO_REPO_NAME = "WinCenter_Local_ISO";
public const string IDENTITY_FILENAME = "id_rsa";
public const string AE_ISO_REPO_LOCATION = "/var/opt/xen/Wincenter_ISO_Store";
// wce的AE库KEY
public const string AE_ISO_REPO_OTHER_KEY= "author";
// wce的AE库VALUE
public const string AE_ISO_REPO_OTHER_VALUE = "Wincenter";
// 主机UUID
public const string AE_ISO_REPO_HOST_KEY = "HOST-UUID";
public const string AE_XML_TMP_FILE = "/tmp/ovf-env.xml";
public const string WinServer = "WinServer";
public const string XenServer = "XenServer";
public const int WinServerPort = 4430;
public const int SSHPort = 22;
}
}
<file_sep>using System.Windows.Forms;
using WizardLib;
namespace Wizard {
public partial class MainForm : WizardForm {
private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
///**
// 禁止窗体关闭按钮
// */
//protected override void WndProc(ref System.Windows.Forms.Message m) {
// const int WM_SYSCOMMAND = 0x0112;
// const int SC_CLOSE = 0xF060;
// if (m.Msg == WM_SYSCOMMAND && (int)m.WParam == SC_CLOSE) {
// return;
// }
// base.WndProc(ref m);
//}
/**
窗体关闭提示
*/
protected override void WndProc(ref System.Windows.Forms.Message m) {
const int WM_SYSCOMMAND = 0x0112;
const int SC_CLOSE = 0xF060;
if (m.Msg == WM_SYSCOMMAND && (int)m.WParam == SC_CLOSE) {
WizardPage page = (WizardPage)this.m_pages[this.m_selectedIndex];
if ("ImportVMPage" == page.Name && !this.m_backButton.Enabled && !this.m_nextButton.Enabled) {
return;
} else if (MessageBox.Show("是否确定取消安装?", "", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK) {
base.WndProc(ref m);
return;
} else {
return;
}
}
base.WndProc(ref m);
}
public MainForm() {
InitializeComponent();
log.InfoFormat("WinCenter安装向导开始初始化....");
Controls.AddRange(new Control[] {
new WelComePage(),
new LicenseAgreement(),
new ImportSourcePage(),
new HostPage(),
new StoragePage(),
new NetWorkPage(),
new ImportVMPage(),
new FinishPage()
});
log.InfoFormat("WinCenter安装向导初始化完成....");
}
}
}
<file_sep>using System.Collections.Generic;
using WinAPI;
namespace Wizard.Core {
class PIFOper {
private Network network;
public Dictionary<string, string> getNetworkInfo(string hostUuid) {
Dictionary<string, string> dict = new Dictionary<string, string>();
List<XenRef<PIF>> vifRefs = PIF.get_all(ConnectManager.session);
foreach (XenRef<PIF> vifRef in vifRefs) {
PIF vif = PIF.get_record(ConnectManager.session, vifRef);
if (vif.management) {
XenRef<Host> hostRef = vif.host;
Host host = Host.get_record(ConnectManager.session, hostRef);
if (hostUuid.Equals(host.uuid)) {
string ip = vif.IP;
dict.Add("ip", ip);
string netmask = vif.netmask;
dict.Add("netmask", netmask);
string gateway = vif.gateway;
dict.Add("gateway", gateway);
XenRef<Network> networkRef = vif.network;
network = Network.get_record(ConnectManager.session, networkRef);
}
}
}
return dict;
}
public Network ManageNetwork {
get {
return network;
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
namespace WizardLib.Core {
public static class StringUtility {
/// <summary>
/// Parses strings of the form "hostname:port"
/// </summary>
/// <param name="s"></param>
/// <param name="hostname"></param>
/// <param name="port"></param>
/// <returns></returns>
public static bool TryParseHostname(string s, int defaultPort, out string hostname, out int port) {
try {
int i = s.IndexOf(':');
if (i != -1) {
hostname = s.Substring(0, i).Trim();
port = int.Parse(s.Substring(i + 1).Trim());
}
else {
hostname = s;
port = defaultPort; // Program.DEFAULT_XEN_PORT;
}
return true;
}
catch (Exception) {
hostname = null;
port = 0;
return false;
}
}
public static int NaturalCompare(string s1, string s2) {
if (string.Compare(s1, s2, StringComparison.CurrentCultureIgnoreCase) == 0) {
// Strings are identical
return 0;
}
if (s1 == null)
return -1;
if (s2 == null)
return 1;
char[] chars1 = s1.ToCharArray();
char[] chars2 = s2.ToCharArray();
// Compare strings char by char
int min = Math.Min(chars1.Length, chars2.Length);
for (int i = 0; i < min; i++) {
char c1 = chars1[i];
char c2 = chars2[i];
bool c1IsDigit = char.IsDigit(c1);
bool c2IsDigit = char.IsDigit(c2);
if (!c1IsDigit && !c2IsDigit) {
// Two non-digits. Do a string (i.e. alphabetical) comparison.
int tmp = String.Compare(s1.Substring(i, 1), s2.Substring(i, 1), StringComparison.CurrentCultureIgnoreCase);
if (tmp == 0)
continue; // Identical non-digits. Move onto next character.
else
return tmp;
}
else if (c1IsDigit && c2IsDigit) {
// See how many digits there are in a row in each string.
int j = 1;
while (i + j < chars1.Length && char.IsDigit(chars1[i + j]))
j++;
int k = 1;
while (i + k < chars2.Length && char.IsDigit(chars2[i + k]))
k++;
// A number that is shorter in decimal places must be smaller.
if (j < k) {
return -1;
}
else if (k < j) {
return 1;
}
// The two integers have the same number of digits. Compare them digit by digit.
for (int m = i; m < i + j; m++) {
if (chars1[m] != chars2[m])
return chars1[m] - chars2[m];
}
// Skip the characters we've already compared, so we don't have to do them again. (CA-50738)
// (It's only j-1, not j, because we get one more in the loop increment).
i += j - 1;
continue;
}
else {
// We're comparing a digit to a non-digit.
return String.Compare(s1.Substring(i, 1), s2.Substring(i, 1), StringComparison.CurrentCultureIgnoreCase);
}
}
// The shorter string comes first.
return chars1.Length - chars2.Length;
}
private static readonly Regex IPRegex = new Regex(@"^([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$");
private static readonly Regex IPRegex0 = new Regex(@"^([0]{1,3})\.([0]{1,3})\.([0]{1,3})\.([0]{1,3})$");
public static bool IsIPAddress(string s) {
if (string.IsNullOrEmpty(s))
return false;
// check the general form is ok
Match m = IPRegex.Match(s);
if (!m.Success)
return false;
// check the individual numbers are in range, easier to do this as a parse than with the regex
for (int i = 1; i < 3; i++) {
int v;
if (!int.TryParse(m.Groups[i].Value, out v))
return false;
if (v > 255)
return false;
}
Match m2 = IPRegex0.Match(s);
if (m2.Success)
return false;
return true;
}
}
}<file_sep>namespace WinAPI
{
using System;
using System.Collections;
using System.Collections.Generic;
public class PGPU : XenObject<PGPU>
{
private XenRef<WinAPI.GPU_group> _GPU_group;
private XenRef<Host> _host;
private Dictionary<string, string> _other_config;
private XenRef<WinAPI.PCI> _PCI;
private string _uuid;
public PGPU()
{
}
public PGPU(Hashtable table)
{
this.uuid = Marshalling.ParseString(table, "uuid");
this.PCI = Marshalling.ParseRef<WinAPI.PCI>(table, "PCI");
this.GPU_group = Marshalling.ParseRef<WinAPI.GPU_group>(table, "GPU_group");
this.host = Marshalling.ParseRef<Host>(table, "host");
this.other_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "other_config"));
}
public PGPU(Proxy_PGPU proxy)
{
this.UpdateFromProxy(proxy);
}
public PGPU(string uuid, XenRef<WinAPI.PCI> PCI, XenRef<WinAPI.GPU_group> GPU_group, XenRef<Host> host, Dictionary<string, string> other_config)
{
this.uuid = uuid;
this.PCI = PCI;
this.GPU_group = GPU_group;
this.host = host;
this.other_config = other_config;
}
public static void add_to_other_config(Session session, string _pgpu, string _key, string _value)
{
session.proxy.pgpu_add_to_other_config(session.uuid, (_pgpu != null) ? _pgpu : "", (_key != null) ? _key : "", (_value != null) ? _value : "").parse();
}
public bool DeepEquals(PGPU other)
{
if (object.ReferenceEquals(null, other))
{
return false;
}
return (object.ReferenceEquals(this, other) || (((Helper.AreEqual2<string>(this._uuid, other._uuid) && Helper.AreEqual2<XenRef<WinAPI.PCI>>(this._PCI, other._PCI)) && (Helper.AreEqual2<XenRef<WinAPI.GPU_group>>(this._GPU_group, other._GPU_group) && Helper.AreEqual2<XenRef<Host>>(this._host, other._host))) && Helper.AreEqual2<Dictionary<string, string>>(this._other_config, other._other_config)));
}
public static List<XenRef<PGPU>> get_all(Session session)
{
return XenRef<PGPU>.Create(session.proxy.pgpu_get_all(session.uuid).parse());
}
public static Dictionary<XenRef<PGPU>, PGPU> get_all_records(Session session)
{
return XenRef<PGPU>.Create<Proxy_PGPU>(session.proxy.pgpu_get_all_records(session.uuid).parse());
}
public static XenRef<PGPU> get_by_uuid(Session session, string _uuid)
{
return XenRef<PGPU>.Create(session.proxy.pgpu_get_by_uuid(session.uuid, (_uuid != null) ? _uuid : "").parse());
}
public static XenRef<WinAPI.GPU_group> get_GPU_group(Session session, string _pgpu)
{
return XenRef<WinAPI.GPU_group>.Create(session.proxy.pgpu_get_gpu_group(session.uuid, (_pgpu != null) ? _pgpu : "").parse());
}
public static XenRef<Host> get_host(Session session, string _pgpu)
{
return XenRef<Host>.Create(session.proxy.pgpu_get_host(session.uuid, (_pgpu != null) ? _pgpu : "").parse());
}
public static Dictionary<string, string> get_other_config(Session session, string _pgpu)
{
return Maps.convert_from_proxy_string_string(session.proxy.pgpu_get_other_config(session.uuid, (_pgpu != null) ? _pgpu : "").parse());
}
public static XenRef<WinAPI.PCI> get_PCI(Session session, string _pgpu)
{
return XenRef<WinAPI.PCI>.Create(session.proxy.pgpu_get_pci(session.uuid, (_pgpu != null) ? _pgpu : "").parse());
}
public static PGPU get_record(Session session, string _pgpu)
{
return new PGPU(session.proxy.pgpu_get_record(session.uuid, (_pgpu != null) ? _pgpu : "").parse());
}
public static string get_uuid(Session session, string _pgpu)
{
return session.proxy.pgpu_get_uuid(session.uuid, (_pgpu != null) ? _pgpu : "").parse();
}
public static void remove_from_other_config(Session session, string _pgpu, string _key)
{
session.proxy.pgpu_remove_from_other_config(session.uuid, (_pgpu != null) ? _pgpu : "", (_key != null) ? _key : "").parse();
}
public override string SaveChanges(Session session, string opaqueRef, PGPU server)
{
if (opaqueRef == null)
{
return "";
}
if (!Helper.AreEqual2<Dictionary<string, string>>(this._other_config, server._other_config))
{
set_other_config(session, opaqueRef, this._other_config);
}
return null;
}
public static void set_other_config(Session session, string _pgpu, Dictionary<string, string> _other_config)
{
session.proxy.pgpu_set_other_config(session.uuid, (_pgpu != null) ? _pgpu : "", Maps.convert_to_proxy_string_string(_other_config)).parse();
}
public Proxy_PGPU ToProxy()
{
return new Proxy_PGPU { uuid = (this.uuid != null) ? this.uuid : "", PCI = (this.PCI != null) ? ((string) this.PCI) : "", GPU_group = (this.GPU_group != null) ? ((string) this.GPU_group) : "", host = (this.host != null) ? ((string) this.host) : "", other_config = Maps.convert_to_proxy_string_string(this.other_config) };
}
public override void UpdateFrom(PGPU update)
{
this.uuid = update.uuid;
this.PCI = update.PCI;
this.GPU_group = update.GPU_group;
this.host = update.host;
this.other_config = update.other_config;
}
internal void UpdateFromProxy(Proxy_PGPU proxy)
{
this.uuid = (proxy.uuid == null) ? null : proxy.uuid;
this.PCI = (proxy.PCI == null) ? null : XenRef<WinAPI.PCI>.Create(proxy.PCI);
this.GPU_group = (proxy.GPU_group == null) ? null : XenRef<WinAPI.GPU_group>.Create(proxy.GPU_group);
this.host = (proxy.host == null) ? null : XenRef<Host>.Create(proxy.host);
this.other_config = (proxy.other_config == null) ? null : Maps.convert_from_proxy_string_string(proxy.other_config);
}
public virtual XenRef<WinAPI.GPU_group> GPU_group
{
get
{
return this._GPU_group;
}
set
{
if (!Helper.AreEqual(value, this._GPU_group))
{
this._GPU_group = value;
base.Changed = true;
base.NotifyPropertyChanged("GPU_group");
}
}
}
public virtual XenRef<Host> host
{
get
{
return this._host;
}
set
{
if (!Helper.AreEqual(value, this._host))
{
this._host = value;
base.Changed = true;
base.NotifyPropertyChanged("host");
}
}
}
public virtual Dictionary<string, string> other_config
{
get
{
return this._other_config;
}
set
{
if (!Helper.AreEqual(value, this._other_config))
{
this._other_config = value;
base.Changed = true;
base.NotifyPropertyChanged("other_config");
}
}
}
public virtual XenRef<WinAPI.PCI> PCI
{
get
{
return this._PCI;
}
set
{
if (!Helper.AreEqual(value, this._PCI))
{
this._PCI = value;
base.Changed = true;
base.NotifyPropertyChanged("PCI");
}
}
}
public virtual string uuid
{
get
{
return this._uuid;
}
set
{
if (!Helper.AreEqual(value, this._uuid))
{
this._uuid = value;
base.Changed = true;
base.NotifyPropertyChanged("uuid");
}
}
}
}
}
<file_sep>using System;
using System.IO;
using WizardLib.Compression;
namespace WizardLib.Archive
{
/// <summary>
/// A static factory to create an object that will allow the archiving of data
/// </summary>
public static class ArchiveFactory
{
/// <summary>
/// Supported types of archive
/// </summary>
public enum Type
{
Tar,
TarGz,
TarBz2,
Zip
}
/// <summary>
/// Instantiate a class that can read a archive type
/// </summary>
/// <param name="archiveType">Type of archive to read</param>
/// <param name="packagedData">The contents of packaged data</param>
/// <exception cref="NotSupportedException">if there is not a iterator for a specified archive type</exception>
/// <returns>ArchiveIterator to allow an archive to be traversed</returns>
public static ArchiveIterator Reader(Type archiveType, Stream packagedData)
{
if (archiveType == Type.Tar)
return new SharpZipTarArchiveIterator(packagedData);
if (archiveType == Type.TarGz)
return new SharpZipTarArchiveIterator(CompressionFactory.Reader(CompressionFactory.Type.Gz, packagedData));
if (archiveType == Type.TarBz2)
return new SharpZipTarArchiveIterator(CompressionFactory.Reader(CompressionFactory.Type.Bz2, packagedData));
if (archiveType == Type.Zip)
return new DotNetZipZipIterator(packagedData);
throw new NotSupportedException(String.Format("Type: {0} is not supported by ArchiveIterator", archiveType));
}
/// <summary>
/// Instantiate a class that can write a archive type
/// </summary>
/// <param name="archiveType">Type of archive to write</param>
/// <param name="targetPackage">The placed where the packaged data will be stored</param>
/// <exception cref="NotSupportedException">if there is not a writer for a specified archive type</exception>
/// <returns>ArchiveWriter to allow an archive to be written</returns>
public static ArchiveWriter Writer(Type archiveType, Stream targetPackage)
{
if (archiveType == Type.Tar)
return new SharpZipTarArchiveWriter(targetPackage);
if (archiveType == Type.Zip)
return new DotNetZipZipWriter(targetPackage);
throw new NotSupportedException( String.Format( "Type: {0} is not supported by ArchiveWriter", archiveType ) );
}
}
}
<file_sep>namespace WinAPI
{
using System;
public static class task_allowed_operations_helper
{
public static string ToString(task_allowed_operations x)
{
if (x == task_allowed_operations.cancel)
{
return "cancel";
}
return "unknown";
}
}
}
<file_sep>using Ionic.Zlib;
using System.IO;
namespace WizardLib.Compression
{
/// <summary>
/// A class that can compress a bzip2 data stream type
/// </summary>
class DotNetZipGZipOutputStream : CompressionStream
{
public DotNetZipGZipOutputStream()
{
}
public DotNetZipGZipOutputStream(Stream outputStream)
{
zipStream = new GZipStream(outputStream, CompressionMode.Compress);
}
public override void SetBaseStream(Stream outputStream)
{
zipStream = new GZipStream(outputStream, CompressionMode.Compress);
}
}
/// <summary>
/// A class that can decompress a bzip2 data stream type
/// </summary>
class DotNetZipGZipInputStream : CompressionStream
{
public DotNetZipGZipInputStream()
{
}
public DotNetZipGZipInputStream(Stream inputStream)
{
zipStream = new GZipStream(inputStream, CompressionMode.Decompress);
}
public override void SetBaseStream(Stream inputStream)
{
zipStream = new GZipStream(inputStream, CompressionMode.Decompress);
}
}
}
<file_sep>using WizardLib;
using Wizard.Core;
using System.Windows.Forms;
using System.Diagnostics;
namespace Wizard {
public partial class FinishPage : WizardLib.InteriorWizardPage {
private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
private string winCenterLinkAddr;
public FinishPage() {
InitializeComponent();
}
protected override bool OnSetActive() {
if (!base.OnSetActive())
return false;
string ip = "";
ConnectManager.IPMaskGatewayDict.TryGetValue("ip", out ip);
WinCenterLinkLabel.Text = winCenterLinkAddr = string.Format("https://{0}:8090/pc/index.jsp", ip);
log.InfoFormat("进入【完成】页面");
Wizard.SetWizardButtons(WizardButton.Finish);
return true;
}
private void WinCenterLinkLabel_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
Process.Start(winCenterLinkAddr);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using WinAPI;
using System.Xml;
using Tamir.SharpSsh;
using System.IO;
using Renci.SshNet;
using System.Threading;
namespace Wizard.Core {
class VMOper {
private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
private const int HTTP_PUT_TIMEOUT = 3 * 60 * 60 * 1000; //3 hours
private List<VM> VMs;
public VMOper() {
}
public void getVMs() {
VMs = new List<VM>();
List<XenRef<VM>> vmRefs = VM.get_all(ConnectManager.session);
foreach (XenRef<VM> vmRef in vmRefs) {
VM vm = VM.get_record(ConnectManager.session, vmRef);
VMs.Add(vm);
}
}
public void ImpXvaFile() {
log.InfoFormat("开始导入WinCenter xva文件:{0}", ConnectManager.FilePath);
string vmRef = GetVmRef(applyFile());
if (string.IsNullOrEmpty(vmRef)) {
return;
}
log.InfoFormat("WinCenter xva文件导入完成");
try {
log.InfoFormat("导入后的WinCenter VM:[{0}]", vmRef);
List<XenRef<VIF>> vifRefs = VM.get_VIFs(ConnectManager.session, vmRef);
foreach (XenRef<VIF> vifRef in vifRefs) {
log.InfoFormat("删除原有的VIF:[{0}]", vifRef.opaque_ref);
VIF.destroy(ConnectManager.session, vifRef);
}
HTTPHelper.progressInfo = "删除原有VIF";
HTTPHelper.progressPercent += 1;
bool isTemplate = VM.get_is_a_template(ConnectManager.session, vmRef);
if (isTemplate) {
log.InfoFormat("导入的xva是模板,删除VM:[{0}]", vmRef);
VM.destroy(ConnectManager.session, vmRef);
return;
}
VIF newVif = ConnectManager.VIF;
newVif.VM = new XenRef<VM>(vmRef);
XenRef<VIF> newVifRef = VIF.create(ConnectManager.session, newVif);
log.InfoFormat("重新创建VIF:[{0}]", newVifRef.opaque_ref);
string mac = VIF.get_MAC(ConnectManager.session, newVifRef);
log.InfoFormat("新的MAC地址为:[{0}]", mac);
string newVifUuid = VIF.get_uuid(ConnectManager.session, newVifRef);
log.InfoFormat("新的VIF UUID为:[{0}]", newVifUuid);
HTTPHelper.progressInfo = "创建新的VIF";
HTTPHelper.progressPercent += 1;
DefaultVMName(ConnectManager.VMName);
log.InfoFormat("检查WinCenter VM的名称,VM名称为:{0}", ConnectManager.VMName);
VM.set_name_label(ConnectManager.session, vmRef, ConnectManager.VMName);
HTTPHelper.progressInfo = "检查VM名称";
HTTPHelper.progressPercent += 1;
/**
* BUG:AE方式设置IP之后,由于ISO没有弹出,在控制台修改IP重启以后,AE会重新设置ISO配置中的IP
* 故不再使用AE这种方式,而是改成在VM启动后使用xenstore-write方式动态修改IP
*/
//初始化AE
//initVmByAe(vmRef, mac);
XenRef<Host> hostRef = Host.get_by_uuid(ConnectManager.session, ConnectManager.TargetHost.uuid);
log.InfoFormat("设置WinCenter VM的所属主机:[{0}]", ConnectManager.TargetHostName);
HTTPHelper.progressInfo = "设置主机";
VM.set_affinity(ConnectManager.session, vmRef, hostRef);
HTTPHelper.progressPercent += 1;
setAutoPoweron(vmRef);
HTTPHelper.progressInfo = "启动VM";
VM.start(ConnectManager.session, vmRef, false, false);
Thread.Sleep(2 * 60 * 1000); //休眠2分钟,等待虚拟机启动完成
HTTPHelper.progressPercent += 2;
log.InfoFormat("启动WinCenter VM:[{0}]成功", vmRef);
//去掉AE方式设置IP,VM启动后使用xenstore-write方式动态设置IP
HTTPHelper.progressInfo = "设置网络信息";
setActiveVifIp(newVifUuid);
HTTPHelper.progressPercent = 100;
log.InfoFormat("设置IP信息成功");
}
catch (Exception ex) {
log.ErrorFormat("安装失败: {0}", ex.Message);
log.ErrorFormat("开始删除WinCenter VM:[{0}]", vmRef);
try {
vm_power_state power_state = VM.get_power_state(ConnectManager.session, vmRef);
if (!vm_power_state.Halted.ToString().Equals(power_state.ToString())) {
VM.shutdown(ConnectManager.session, vmRef);
}
}
catch (Exception ex1) {
log.ErrorFormat("WinCenter VM关机失败:{0}", ex1.Message);
}
try {
VM.destroy(ConnectManager.session, vmRef);
}
catch (Exception ex1) {
log.ErrorFormat("删除WinCenter VM失败:{0}", ex1.Message);
throw ex1;
}
throw;
}
}
private string applyFile() {
log.InfoFormat("安装WinCenter VM从[{0}]到存储池{1}", ConnectManager.FilePath, ConnectManager.SelectedSR.name_label);
Host host = null;
if (!ConnectManager.SelectedSR.shared) {
host = ConnectManager.TargetHost;
}
string hostURL;
if (host == null) {
Uri uri = new Uri(ConnectManager.session.Url);
hostURL = uri.Host;
}
else {
log.InfoFormat("导存储池不是共享存储,直接导入到目标主机:[{0}]", host.address);
hostURL = host.address;
}
//添加port
int port = HTTP.DEFAULT_HTTP_PORT;
if (ConnectManager.ConnectPort != 0)
{
port = ConnectManager.ConnectPort;
}
hostURL = hostURL + ":" + port; //ip:port
log.InfoFormat("导入URL:{0}", hostURL);
XenRef<SR> srRef = SR.get_by_uuid(ConnectManager.session, ConnectManager.SelectedSR.uuid);
return HTTPHelper.Put(HTTP_PUT_TIMEOUT, ConnectManager.FilePath, hostURL,
(HTTP_actions.put_ssbbs)HTTP_actions.put_import,
ConnectManager.session.uuid, false, false, srRef.opaque_ref);
}
private string GetVmRef(string result) {
if (string.IsNullOrEmpty(result))
return null;
string head = "<value><array><data><value>";
string tail = "</value></data></array></value>";
if (!result.StartsWith(head) || !result.EndsWith(tail))
return null;
int start = head.Length;
int length = result.IndexOf(tail) - start;
return result.Substring(start, length);
}
public void DefaultVMName(string vmName) {
getVMs();
string name = vmName;
int i = 0;
while (VMsWithName(name) > 1) {
i++;
name = string.Format("{0} ({1})", vmName, i);
}
ConnectManager.VMName = name;
}
private int VMsWithName(string name) {
int i = 0;
foreach (VM v in VMs)
if (v.name_label == name)
i++;
return i;
}
private void initVmByAe(string vmRef, string mac) {
Dictionary<string, string> aeDict = new Dictionary<string, string>();
setDictValue(aeDict, mac);
string xmlString = GenerateXMLInfo(aeDict);
log.InfoFormat("组装AE配置文件,xml:{0}", xmlString);
HTTPHelper.progressInfo = "组装AE配置文件";
HTTPHelper.progressPercent += 1;
DateTime dt = System.DateTime.Now;
string dateTime = string.Format("{0:yyyyMMddHHmmssffff}", dt);
string aeFileName = "Sharp_AE_" + dateTime + ".iso";
mkisofsByRenciSshNet(xmlString, aeFileName);
//mkisofsBySharpSSH(xmlString, aeFileName);
insertAEISO(vmRef, aeFileName);
}
/**
SSH连接使用RenciSshNet,需要.net4.0
*/
private void mkisofsByRenciSshNet(string xmlString, string aeFileName) {
ConnectionInfo connectionInfo = new ConnectionInfo(ConnectManager.TargetHostName, Constants.SSHPort, ConnectManager.TargetHostUserName,
new AuthenticationMethod[]{
// Pasword based Authentication
new PasswordAuthenticationMethod(ConnectManager.TargetHostUserName, ConnectManager.TargetHostPassword),
// Key Based Authentication (using keys in OpenSSH Format)
/**
new PrivateKeyAuthenticationMethod("username",new PrivateKeyFile[]{
new PrivateKeyFile(@"..\openssh.key","passphrase")
}),
*/
}
);
SshClient sshclient = new SshClient(connectionInfo);
try {
sshclient.Connect();
//在winsever上新建xml文件
string cmdStr = "echo '" + xmlString + "' > " + Constants.AE_XML_TMP_FILE;
var cmd = sshclient.CreateCommand(cmdStr);
cmd.Execute();
log.InfoFormat("目标主机上新建AE文件,执行命令{0}", cmdStr);
string info = cmd.Result;//获取返回结果
string error = cmd.Error;//获取错误信息
log.InfoFormat("目标主机上新建AE文件,执行命令输出{0}", info + error);
HTTPHelper.progressInfo = "新建AE配置文件";
HTTPHelper.progressPercent += 1;
cmdStr = "ls " + Constants.AE_ISO_REPO_LOCATION;
cmd = sshclient.CreateCommand(cmdStr);
cmd.Execute();
log.InfoFormat("目标主机上校验AE ISO库目录,执行命令{0}", cmdStr);
info = cmd.Result;
error = cmd.Error;
log.InfoFormat("目标主机上校验AE ISO库目录,执行命令输出{0}", info + error);
if (!string.IsNullOrWhiteSpace(error) && error.IndexOf("No such file or directory") != -1) {
cmdStr = "mkdir -p " + Constants.AE_ISO_REPO_LOCATION;
cmd = sshclient.CreateCommand(cmdStr);
cmd.Execute();
log.InfoFormat("目标主机上创建AE ISO库目录,执行命令{0}", cmdStr);
info = cmd.Result;
error = cmd.Error;
log.InfoFormat("目标主机上创建AE ISO库目录,执行命令输出{0}", info + error);
}
//制作ISO文件
cmdStr = "mkisofs -r -o " + Constants.AE_ISO_REPO_LOCATION + "/" + aeFileName + " " + Constants.AE_XML_TMP_FILE;
cmd = sshclient.CreateCommand(cmdStr);
cmd.Execute();
log.InfoFormat("目标主机上根据AE文件制作ISO,执行命令{0}", cmdStr);
info = cmd.Result;
error = cmd.Error;
log.InfoFormat("目标主机上根据AE文件制作ISO,执行命令输出{0}", info + error);
HTTPHelper.progressInfo = "制作AE ISO文件";
HTTPHelper.progressPercent += 1;
}
catch (Exception ex) {
log.ErrorFormat("制作ISO失败:" + ex.Message);
throw;
}
finally {
//删除临时文件
if (sshclient != null) {
string cmdStr = "rm -f " + Constants.AE_XML_TMP_FILE;
sshclient.CreateCommand(cmdStr).Execute();
log.InfoFormat("删除AE临时文件,执行命令{0}", cmdStr);
log.InfoFormat("删除AE临时文件成功");
sshclient.Disconnect();
}
}
}
/**
* @deprecated
* SSH连接使用SharpSSH,需要.net2.0
* SharpSSH版本比较旧,一直未更新,does not support modern ciphers and KEX algorithms
* 就会报这个Algorithm negotiation fail错误
*/
private void mkisofsBySharpSSH(string xmlString, string aeFileName) {
////获取启动了应用程序的可执行文件的路径目录
//string startupPath = System.Windows.Forms.Application.StartupPath;
//string privateKeyPath = startupPath + Path.DirectorySeparatorChar + ".ssh" + Path.DirectorySeparatorChar + Constants.IDENTITY_FILENAME;
//if (!File.Exists(privateKeyPath)) {
// log.InfoFormat("SSH连接所需私钥文件[{0}]不存在", privateKeyPath);
//}
ShellHelp shell = new ShellHelp();
try {
if (shell.OpenShell(ConnectManager.TargetHostName, ConnectManager.TargetHostUserName, ConnectManager.TargetHostPassword, null)) {
//在winsever上新建xml文件
shell.Shell("echo '" + xmlString + "' > " + Constants.AE_XML_TMP_FILE);
string info = shell.GetAllString();//获取返回结果
log.InfoFormat("目标主机上新建AE文件,命令输出{0}", info);
HTTPHelper.progressInfo = "新建AE配置文件";
HTTPHelper.progressPercent += 1;
shell.Shell("ls " + Constants.AE_ISO_REPO_LOCATION);
info = shell.GetAllString();
log.InfoFormat("目标主机上执行ls命令输出{0}", info);
if (info.IndexOf("No such file or directory") != -1) {
shell.Shell("mkdir -p " + Constants.AE_ISO_REPO_LOCATION);
}
//制作ISO文件
shell.Shell("mkisofs -r -o " + Constants.AE_ISO_REPO_LOCATION + "/" + aeFileName + " " + Constants.AE_XML_TMP_FILE);
info = shell.GetAllString();
log.InfoFormat("目标主机上根据AE文件制作ISO,命令输出{0}", info);
HTTPHelper.progressInfo = "制作AE ISO文件";
HTTPHelper.progressPercent += 1;
}
}
catch (Exception ex) {
log.ErrorFormat("制作ISO失败:" + ex.Message);
throw;
}
finally {
//删除临时文件
shell.Shell("rm -f " + Constants.AE_XML_TMP_FILE);
log.InfoFormat("删除AE临时文件成功");
shell.Close();
}
}
private void insertAEISO(string vmRef, string aeFileName) {
HTTPHelper.progressInfo = "获取AE ISO库";
HTTPHelper.progressPercent += 1;
SROper srOper = new SROper();
string aeIsoRepoUuid = srOper.getAeISORepoUuid();
XenRef<VBD> cdVBDRef = null;
VM vm = VM.get_record(ConnectManager.session, vmRef);
List<XenRef<VBD>> vbdRefs = vm.VBDs;
foreach (XenRef<VBD> vbdRef in vbdRefs) {
VBD vbd = VBD.get_record(ConnectManager.session, vbdRef);
if (vbd_type.CD.Equals(vbd.type)) {
cdVBDRef = vbdRef;
try {
VBD.eject(ConnectManager.session, vbdRef);
}
catch (Exception ex) {
log.InfoFormat("设置VBD eject, error=[{0}]", ex.Message);
}
break;
}
}
if (cdVBDRef == null) {
string[] userdevices = VM.get_allowed_VBD_devices(ConnectManager.session, vmRef);
if (userdevices != null && userdevices.Length > 0) {
VBD vbd = new VBD();
vbd.VM = new XenRef<VM>(vmRef);
vbd.type = vbd_type.CD;
vbd.mode = vbd_mode.RO;
vbd.userdevice = userdevices[0];
vbd.empty = true;
cdVBDRef = VBD.create(ConnectManager.session, vbd);
log.InfoFormat("WinCenter VM没有虚拟光驱,新建一个VBD成功");
}
else {
log.InfoFormat("可供使用的VBD标识符列表数为0,不能创建VBD");
}
}
XenRef<VDI> vdiRef = srOper.getVdiRef(aeIsoRepoUuid, aeFileName);
VBD cdVBD = VBD.get_record(ConnectManager.session, cdVBDRef);
bool isInsert = VBD.get_allowed_operations(ConnectManager.session, cdVBDRef).Contains(vbd_operations.insert);
if (isInsert) {
log.InfoFormat("加载AE ISO文件");
VBD.insert(ConnectManager.session, cdVBDRef, vdiRef);
HTTPHelper.progressInfo = "加载AE ISO文件";
HTTPHelper.progressPercent += 1;
}
else {
XenRef<VDI> cdVDIRef = cdVBD.VDI;
string name = VDI.get_name_label(ConnectManager.session, cdVDIRef);
log.InfoFormat("WinCenter VM已插入镜像[{0}],不能插入AE镜像", name);
}
}
private void setDictValue(Dictionary<string, string> aeDict, string mac) {
foreach (KeyValuePair<string, string> net in ConnectManager.IPMaskGatewayDict) {
if (net.Key.Equals("ip")) {
aeDict.Add("com.huadi.ovf.wce.adapter.networking.ipv4addresses.1", net.Value);
}
else if (net.Key.Equals("netmask")) {
aeDict.Add("com.huadi.ovf.wce.adapter.networking.ipv4netmasks.1", net.Value);
}
else if (net.Key.Equals("gateway")) {
aeDict.Add("com.huadi.ovf.wce.system.networking.ipv4defaultgateway", net.Value);
}
}
aeDict.Add("com.huadi.ovf.wce.system.networking.hostname", "wincenter"); //wincenter VM hostname
aeDict.Add("com.huadi.ovf.wce.adapter.networking.mac.1", mac);
aeDict.Add("com.huadi.ovf.wce.system.timezone", "");
aeDict.Add("com.huadi.ovf.wce.adapter.networking.order.1", "");
aeDict.Add("com.huadi.ovf.wce.system.networking.domainname", "");
aeDict.Add("com.huadi.ovf.wce.adapter.networking.usedhcpv4.1", "false");
aeDict.Add("com.huadi.ovf.wce.adapter.networking.useipv6autoconf.1", "false");
aeDict.Add("com.huadi.ovf.wce.adapter.networking.ipv4hosttableentries.0", "");
aeDict.Add("com.huadi.ovf.wce.adapter.networking.ipv6gateways.1", "");
aeDict.Add("com.huadi.ovf.wce.adapter.networking.ipv6addresses.1", "");
aeDict.Add("com.huadi.ovf.wce.adapter.networking.ipv6hosttableentries.1", "");
aeDict.Add("com.huadi.ovf.wce.system.networking.dnsIPaddresses", "");
aeDict.Add("com.huadi.ovf.wce.system.license", "");
}
private string GenerateXMLInfo(Dictionary<string, string> aeDict) {
XmlDocument doc = new XmlDocument();
XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "UTF-8", null);
doc.AppendChild(dec);
XmlElement root = doc.CreateElement("Environment");
doc.AppendChild(root);
XmlElement platformSection = doc.CreateElement("PlatformSection");
XmlElement locale = doc.CreateElement("Locale");
locale.InnerText = "en_US";
platformSection.AppendChild(locale);
root.AppendChild(platformSection);
XmlElement propertySection = doc.CreateElement("PropertySection");
root.AppendChild(propertySection);
foreach (KeyValuePair<string, string> ae in aeDict) {
XmlElement property = doc.CreateElement("Property");
property.SetAttribute("key", ae.Key);
property.SetAttribute("value", ae.Value);
propertySection.AppendChild(property);
}
return doc.OuterXml;
}
/**
* 设置虚拟机开机启动(需要在资源池和虚拟机上设置)
* 1、设置池开机启动 xe pool-param-set uuid=f0171d28-44e7-4444-0777-06f3b3805714 other-config:auto_poweron=true
* 2、设置虚拟机开启启动 xe vm-param-set uuid=af9e0b9b-b0e8-385c-eb8e-f9c2f3cbc5c5 other-config:auto_poweron=true
*
*/
private void setAutoPoweron(String vmRef) {
List<XenRef<Pool>> poolRefs = Pool.get_all(ConnectManager.session);
foreach (XenRef<Pool> poolRef in poolRefs) {
Dictionary<string, string> poolOtherConfig = Pool.get_other_config(ConnectManager.session, poolRef);
//先判断是否含有auto_poweron,如果有的话先remove,再add(直接add会报错提示已含有相同的key)
if (poolOtherConfig.ContainsKey("auto_poweron")) {
poolOtherConfig.Remove("auto_poweron");
}
poolOtherConfig.Add("auto_poweron", "true");
Pool.set_other_config(ConnectManager.session, poolRef, poolOtherConfig); //设置资源池开机启动
}
Dictionary<string, string> otherConfig = VM.get_other_config(ConnectManager.session, vmRef);
//先判断是否含有auto_poweron,如果有的话先remove,再add(直接add会报错提示已含有相同的key)
if (otherConfig.ContainsKey("auto_poweron")) {
otherConfig.Remove("auto_poweron");
}
otherConfig.Add("auto_poweron", "true");
VM.set_other_config(ConnectManager.session, vmRef, otherConfig); //设置虚拟机开机启动
}
/**
* 根据物理主机的product_brand、product_version来确定开放的https端口号,默认443
*/
private string getHostPort() {
string productVersion = null;
string productBrand = null;
try {
XenRef<Host> hostRef = Host.get_by_uuid(ConnectManager.session, ConnectManager.TargetHost.uuid);
Dictionary<string, string> softwareVersion = Host.get_software_version(ConnectManager.session, hostRef);
foreach (KeyValuePair<string, string> kv in softwareVersion) {
if ("product_version".Equals(kv.Key)) {
productVersion = kv.Value;
}
else if ("product_brand".Equals(kv.Key)) {
productBrand = kv.Value;
}
}
log.InfoFormat("目标主机产品信息: productVersion={0}, productBrand={1}", productVersion, productBrand);
if (Constants.WinServer.Equals(productBrand) && !string.IsNullOrEmpty(productVersion)) {
if (productVersion.IndexOf(".") > 0) {
string[] productVersionArr = productVersion.Split(new char[] { '.' }, StringSplitOptions.RemoveEmptyEntries);
if (productVersionArr.Length > 0) {
string version = productVersionArr[0].Trim();
if (!string.IsNullOrEmpty(version)) {
int productVersionNum = Int32.Parse(version);
if (productVersionNum >= 2) {
return "" + Constants.WinServerPort; //主版本号在2及以上的物理主机
}
}
}
}
}
}
catch (Exception e) {
log.ErrorFormat("获取目标主机产品版本号错误: {0}", e.Message);
}
return null;
}
/**
* 动态设置VM的IP信息
* SSH连接使用RenciSshNet,需要.net4.0
*/
private void setActiveVifIp(string newVifUuid) {
ConnectionInfo connectionInfo = new ConnectionInfo(ConnectManager.TargetHostName, Constants.SSHPort, ConnectManager.TargetHostUserName,
new AuthenticationMethod[]{
// Pasword based Authentication
new PasswordAuthenticationMethod(ConnectManager.TargetHostUserName, ConnectManager.TargetHostPassword),
// Key Based Authentication (using keys in OpenSSH Format)
/**
new PrivateKeyAuthenticationMethod("username",new PrivateKeyFile[]{
new PrivateKeyFile(@"..\openssh.key","passphrase")
}),
*/
}
);
SshClient sshclient = new SshClient(connectionInfo);
try {
sshclient.Connect();
//动态设置IP
/**
* /opt/xensource/libexec/set-active-vif-ip --vifuuid <vifuuid> [--ip <ip>] [--gateway <gateway>] [--netmask <netmask>] [--hostname <hostname>] [--ipv6 <ipv6>] [--gatewayv6 <ipv6 gateway>] [--dns <dns>]
* 其中 --vifuuid <vifuuid>是必须的,其余参数可选
*/
string cmdStr = "/opt/xensource/libexec/set-active-vif-ip --vifuuid " + newVifUuid;
foreach (KeyValuePair<string, string> net in ConnectManager.IPMaskGatewayDict) {
cmdStr += " --" + net.Key + " " + net.Value; //key有三个,分别为ip,netmask,gateway
//if (net.Key.Equals("ip")) {
// cmdStr= " --ip " + net.Value;
//}
//else if (net.Key.Equals("netmask")) {
// cmdStr = " --netmask " + net.Value;
//}
//else if (net.Key.Equals("gateway")) {
// cmdStr = " --gateway " + net.Value;
//}
}
cmdStr += " --hostname wincenter"; //wincenter VM hostname
var cmd = sshclient.CreateCommand(cmdStr);
cmd.Execute();
log.InfoFormat("设置IP信息,执行命令{0}", cmdStr);
string info = cmd.Result;//获取返回结果
string error = cmd.Error;//获取错误信息
log.InfoFormat("设置IP信息,执行命令输出{0}", info + error);
if ((!String.IsNullOrEmpty(info) && info.IndexOf("ERROR") >= 0) || !String.IsNullOrEmpty(error)) {
//设置IP信息输出错误信息,抛出异常
throw new Exception(info + error);
}
HTTPHelper.progressInfo = "设置IP信息";
HTTPHelper.progressPercent += 2;
}
catch (Exception ex) {
log.ErrorFormat("设置IP信息失败:" + ex.Message);
throw;
}
finally {
if (sshclient != null) {
sshclient.Disconnect();
}
}
}
}
}
<file_sep>using WinAPI;
namespace Wizard.Core {
public static class SessionFactory {
public static Session CreateSession(string hostname, int port) {
return new Session(Session.STANDARD_TIMEOUT, hostname, port);
}
public static Session CreateSession(Session session, int timeout) {
return new Session(session, timeout);
}
}
}
<file_sep>using System.Collections.Generic;
using WizardLib;
using Wizard.Core;
using System;
using WinAPI;
using System.Windows.Forms;
using System.ComponentModel;
using Wizard.Common;
using System.Threading;
namespace Wizard {
public partial class StoragePage : InteriorWizardPage {
private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
private SROper sROper;
public StoragePage() {
InitializeComponent();
}
protected override bool OnSetActive() {
if (!base.OnSetActive())
return false;
log.InfoFormat("进入【存储配置】页面");
SelectSRInfoLabel.Text = "";
//ThreadStart threadStart = new ThreadStart(setVmName);
//Thread thread = new Thread(threadStart);
//thread.Start();
string vdiSize = string.Format("{0:0.00}GB", ConnectManager.DiskCapacity / Constants.UINT);
label1.Text = string.Format("所需磁盘容量为{0}, 请选择可用容量大于{1}的存储池", vdiSize, vdiSize);
sROper = new SROper();
List<SRVo> srList = sROper.getSRByTargetHost();
////排序:降序
//Reverser<SRVo> reverser = new Reverser<SRVo>(new SRVo().GetType(), "AvailableCapacity", ReverserInfo.Direction.DESC);
//srList.Sort(reverser);
////排序
//srList.Sort(delegate(SRVo x, SRVo y) { return x.AvailableCapacity.CompareTo(y.AvailableCapacity);});
////排序,使用Lambda表达式,升序
//srList.Sort((x, y) => x.AvailableCapacity.CompareTo(y.AvailableCapacity));
//排序,使用Lambda表达式,降序
srList.Sort((x, y) => y.AvailableCapacity.CompareTo(x.AvailableCapacity));
if (srList.Count > 0) {
storageDataGridView.RowCount = srList.Count;
storageDataGridView.Rows[0].Selected = true;//每次默认选中第一行
for (int i = 0; i < srList.Count; i++) {
storageDataGridView.Rows[i].Cells["uuidColumn"].Value = srList[i].Uuid;
//int index = storageDataGridView.CurrentRow == null ? 0 : storageDataGridView.CurrentRow.Index;
int index = 0;
if (i == index) {
storageDataGridView.Rows[i].Cells["checkBoxColumn"].Value = SelectedStatus.Selected;
}
else {
storageDataGridView.Rows[i].Cells["checkBoxColumn"].Value = SelectedStatus.NoSelected;
}
storageDataGridView.Rows[i].Cells["nameLabelColumn"].Value = srList[i].Name;
storageDataGridView.Rows[i].Cells["AvailableCapacityColumn"].Value = string.Format("{0:0.00}GB", srList[i].AvailableCapacity / Constants.UINT);
storageDataGridView.Rows[i].Cells["physicalSizeColumn"].Value = string.Format("{0:0.00}GB", srList[i].PhysicalSize / Constants.UINT);
storageDataGridView.Rows[i].Cells["TypeColumn"].Value = srList[i].Type;
storageDataGridView.Rows[i].Cells["infoColumn"].Value = srList[i].Info;
}
//storageDataGridView.Sort(storageDataGridView.Columns["AvailableCapacityColumn"], ListSortDirection.Descending);
Wizard.SetWizardButtons(WizardButton.Back | WizardButton.Next);
} else {
Wizard.SetWizardButtons(WizardButton.Back);
}
return true;
}
protected override string OnWizardNext() {
SelectSRInfoLabel.Text = "";
Object o = this.storageDataGridView.CurrentRow.Cells["infoColumn"].Value;
if (o != null) {
SelectSRInfoLabel.Text = o.ToString();
return null;
}
string uuid = this.storageDataGridView.CurrentRow.Cells["uuidColumn"].Value.ToString();
string name = this.storageDataGridView.CurrentRow.Cells["nameLabelColumn"].Value.ToString();
ConnectManager.SelectedSR = sROper.getSrByUuid(uuid);
log.InfoFormat("已选择存储池,sr=[uuid:{0}, name:{1}]", uuid, name);
return base.OnWizardNext();
}
private void storageDataGridView_CellClick(object sender, DataGridViewCellEventArgs e) {
if (e.RowIndex >= 0) {
//Cells[1]为checkBoxColumn列
DataGridViewDisableCheckBoxCell cell = storageDataGridView.Rows[e.RowIndex].Cells["checkBoxColumn"] as DataGridViewDisableCheckBoxCell;
if (!cell.Enabled) {
return;
}
string isSelected = cell.Value == null ? "NoSelected" : cell.Value.ToString();
if (SelectedStatus.NoSelected.ToString().Equals(isSelected)) {
cell.Value = SelectedStatus.Selected;
SetRadioButtonValue(cell);
}
}
}
private void SetRadioButtonValue(DataGridViewDisableCheckBoxCell cell) {
SelectedStatus status = (SelectedStatus)cell.Value;
if (status == SelectedStatus.Selected) {
status = SelectedStatus.NoSelected;
}
else {
status = SelectedStatus.Selected;
}
for (int i = 0; i < storageDataGridView.Rows.Count; i++) {
DataGridViewDisableCheckBoxCell cel = storageDataGridView.Rows[i].Cells["checkBoxColumn"] as DataGridViewDisableCheckBoxCell;
if (!cel.Equals(cell)) {
cel.Value = status;
}
}
}
private void setVmName() {
VMOper vmOper = new VMOper();
vmOper.DefaultVMName(ConnectManager.VMName);
}
}
}
<file_sep>using System;
using WinAPI;
using System.Collections.Generic;
namespace Wizard.Core {
class HostOper {
public HostOper() {
}
public Host getTargetHost() {
Host targetHost = null;
List<XenRef<Host>> hostRefs = Host.get_all(ConnectManager.session);
if (hostRefs != null && hostRefs.Count > 0) {
foreach (XenRef<Host> hostRef in hostRefs) {
Host host = Host.get_record(ConnectManager.session, hostRef);
if (host.address.Equals(ConnectManager.TargetHostName)) {
targetHost = ConnectManager.TargetHost = host;
break;
}
}
}
return targetHost;
}
public Boolean IsConnect() {
List<XenRef<Host>> hostList = Host.get_all(ConnectManager.session);
if (hostList != null && hostList.Count > 0) {
return true;
}
return false;
}
}
}
<file_sep>using WizardLib;
using System.IO;
using System;
using System.Windows.Forms;
using System.Resources;
using Wizard.Properties;
using System.Diagnostics;
namespace Wizard {
public partial class LicenseAgreement : ExteriorWizardPage {
private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
public LicenseAgreement() {
InitializeComponent();
}
protected override bool OnSetActive() {
if (!base.OnSetActive())
return false;
log.InfoFormat("进入【许可协议】页面");
readRtfToRichTextBox();
if (radioButton1.Checked) {
Wizard.SetWizardButtons(WizardButton.Back | WizardButton.Next);
}
else {
Wizard.SetWizardButtons(WizardButton.Back);
}
return true;
}
private void readRtfToRichTextBox() {
try {
string startupPath = System.Windows.Forms.Application.StartupPath;
string filePath = startupPath + Path.DirectorySeparatorChar + "LicenseAgreement.rtf";
this.richTextBox1.LoadFile(filePath, RichTextBoxStreamType.RichText); //加载rtf文件
//this.richTextBox1.LoadFile(filePath, RichTextBoxStreamType.PlainText);//加载txt文件
}
catch (Exception e) {
log.ErrorFormat("打开许可协议文件错误: {0}", e.Message);
}
}
//打开rtf文件中的email超链接
private void richTextBox1_LinkedClick(object sender, LinkClickedEventArgs e) {
try {
Process.Start(e.LinkText);
}
catch (Exception ex) {
log.ErrorFormat("未找到邮箱应用程序,打开邮箱地址错误:{0}", ex.Message);
}
}
private void radioButton1_CheckedChanged(object sender, System.EventArgs e) {
Wizard.SetWizardButtons(WizardButton.Back | WizardButton.Next);
}
private void radioButton2_CheckedChanged(object sender, System.EventArgs e) {
Wizard.SetWizardButtons(WizardButton.Back);
}
}
}
<file_sep>using System;
using System.IO;
namespace WizardLib.Archive
{
/// <summary>
/// A base abstract class to iterate over an archived file type
/// </summary>
public abstract class ArchiveIterator : IDisposable
{
/// <summary>
/// Helper function to extract all contents of this iterating class to a path
/// </summary>
/// <param name="pathToExtractTo">The path to extract the archive to</param>
/// <exception cref="ArgumentNullException">If null path is passed in</exception>
/// <exception cref="NullReferenceException">If while combining path and current file name a null arises</exception>
public void ExtractAllContents( string pathToExtractTo )
{
if( String.IsNullOrEmpty(pathToExtractTo) )
throw new ArgumentNullException();
while( HasNext() )
{
//Make the file path from the details in the archive making the path windows friendly
string conflatedPath = Path.Combine(pathToExtractTo, CurrentFileName()).Replace('/', Path.DirectorySeparatorChar);
//Create directories - empty ones will be made too
Directory.CreateDirectory( Path.GetDirectoryName(conflatedPath) );
//If we have a file extract the contents
if( !IsDirectory() )
{
using (FileStream fs = File.Create(conflatedPath))
{
ExtractCurrentFile(fs);
}
}
}
}
/// <summary>
/// Hook to allow the base stream to be wrapped by this classes archive mechanism
/// </summary>
/// <param name="stream">base stream</param>
public virtual void SetBaseStream(Stream stream)
{
throw new NotImplementedException();
}
public abstract bool HasNext();
public abstract void ExtractCurrentFile(Stream extractedFileContents);
public abstract string CurrentFileName();
public abstract long CurrentFileSize();
public abstract DateTime CurrentFileModificationTime();
public abstract bool IsDirectory();
/// <summary>
/// Dispose hook - overload and clean up IO
/// </summary>
/// <param name="disposing"></param>
protected virtual void Dispose(bool disposing){}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}
}
<file_sep>using System.IO;
using System;
namespace WizardLib.Compression
{
/// <summary>
/// A static factory to create an object that will allow the archiving of data
/// </summary>
public static class CompressionFactory
{
/// <summary>
/// Type of compressed stream
/// </summary>
public enum Type
{
Gz,
Bz2
}
/// <summary>
/// Instantiate a class that can decompress a data stream type
/// </summary>
/// <param name="compressionType">Type of compressed stream to read</param>
/// <param name="compressedDataSource">The contents of compressed data</param>
/// <exception cref="NotSupportedException">If there is not a compressor for a specified archive type</exception>
/// <returns>CompressionStream to allow an read as a stream</returns>
public static CompressionStream Reader(Type compressionType, Stream compressedDataSource)
{
if (compressionType == Type.Gz)
return new DotNetZipGZipInputStream(compressedDataSource);
if (compressionType == Type.Bz2)
return new DotNetZipBZip2InputStream(compressedDataSource);
throw new NotSupportedException(String.Format("Type: {0} is not supported by CompressionStream Reader", compressionType));
}
/// <summary>
/// Instantiate a class that can compress a data stream type
/// </summary>
/// <param name="compressionType">Type of compressed stream to write</param>
/// <param name="compressedDataTarget">The place where the compressed data will be put</param>
/// <exception cref="NotSupportedException"> if there is not a compressor for a specified archive type</exception>
/// <returns>CompressionStream to allow an write as a stream</returns>
public static CompressionStream Writer(Type compressionType, Stream compressedDataTarget)
{
if (compressionType == Type.Gz)
return new DotNetZipGZipOutputStream(compressedDataTarget);
if (compressionType == Type.Bz2)
return new DotNetZipBZip2OutputStream(compressedDataTarget);
throw new NotSupportedException(String.Format("Type: {0} is not supported by CompressionStream Writer", compressionType));
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace WizardLib {
public partial class InteriorWizardPage : WizardPage {
// ==================================================================
// Protected Fields
// ==================================================================
// ==================================================================
// Public Constructors
// ==================================================================
/// <summary>
/// Initializes a new instance of the <see cref="InteriorWizardPage">InteriorWizardPage</see>
/// class.
/// </summary>
public InteriorWizardPage() {
// This call is required by the Windows Form Designer
InitializeComponent();
}
}
}
<file_sep>using System;
using System.Collections;
using System.Drawing;
using System.Windows.Forms;
namespace WizardLib {
/// <summary>
/// Used to identify the various buttons that may appear within a wizard
/// dialog.
/// </summary>
[Flags]
public enum WizardButton {
/// <summary>
/// Identifies the <b>Back</b> button.
/// </summary>
Back = 0x00000001,
/// <summary>
/// Identifies the <b>Next</b> button.
/// </summary>
Next = 0x00000002,
/// <summary>
/// Identifies the <b>Finish</b> button.
/// </summary>
Finish = 0x00000004,
/// <summary>
/// Identifies the disabled <b>Finish</b> button.
/// </summary>
DisabledFinish = 0x00000008,
/// <summary>
/// Identifies the <b>DisabledAll</b> button.
/// </summary>
DisabledAll = 0x000000016,
}
public partial class WizardForm : Form {
// ==================================================================
// Public Constants
// ==================================================================
/// <summary>
/// Used by a page to indicate to this wizard that the next page
/// should be activated when either the Back or Next buttons are
/// pressed.
/// </summary>
public const string NextPage = "";
/// <summary>
/// Used by a page to indicate to this wizard that the selected page
/// should remain active when either the Back or Next buttons are
/// pressed.
/// </summary>
public const string NoPageChange = null;
// ==================================================================
// Private Fields
// ==================================================================
/// <summary>
/// Array of wizard pages.
/// </summary>
public ArrayList m_pages = new ArrayList();
/// <summary>
/// Index of the selected page; -1 if no page selected.
/// </summary>
public int m_selectedIndex = -1;
// ==================================================================
// Protected Fields
// ==================================================================
/// <summary>
/// The Back button.
/// </summary>
protected Button m_backButton;
/// <summary>
/// The Next button.
/// </summary>
protected Button m_nextButton;
/// <summary>
/// The Cancel button.
/// </summary>
protected Button m_cancelButton;
/// <summary>
/// The Finish button.
/// </summary>
protected Button m_finishButton;
public WizardForm() {
InitializeComponent();
// Ensure Finish and Next buttons are positioned similarly
m_finishButton.Location = m_nextButton.Location;
}
/// <summary>
/// Activates the page at the specified index in the page array.
/// </summary>
/// <param name="newIndex">
/// Index of new page to be selected.
/// </param>
public void ActivatePage(int newIndex) {
// Ensure the index is valid
if (newIndex < 0 || newIndex >= m_pages.Count)
throw new ArgumentOutOfRangeException();
// Deactivate the current page if applicable
WizardPage currentPage = null;
if (m_selectedIndex != -1) {
currentPage = (WizardPage)m_pages[m_selectedIndex];
if (!currentPage.OnKillActive())
return;
}
//if (newIndex != m_selectedIndex + 1) {
// return;
//}
// Activate the new page
WizardPage newPage = (WizardPage)m_pages[newIndex];
if (!newPage.OnSetActive())
return;
// Update state
m_selectedIndex = newIndex;
if (currentPage != null)
currentPage.Visible = false;
newPage.Visible = true;
newPage.Focus();
}
/// <summary>
/// Handles the Click event for the Back button.
/// </summary>
private void OnClickBack(object sender, EventArgs e) {
// Ensure a page is currently selected
if (m_selectedIndex != -1) {
// Inform selected page that the Back button was clicked
string pageName = ((WizardPage)m_pages[
m_selectedIndex]).OnWizardBack();
switch (pageName) {
// Do nothing
case NoPageChange:
break;
// Activate the next appropriate page
case NextPage:
if (m_selectedIndex - 1 >= 0)
ActivatePage(m_selectedIndex - 1);
break;
// Activate the specified page if it exists
default:
foreach (WizardPage page in m_pages) {
if (page.Name == pageName)
ActivatePage(m_pages.IndexOf(page));
}
break;
}
}
}
/// <summary>
/// Handles the Click event for the Cancel button.
/// </summary>
private void OnClickCancel(object sender, EventArgs e) {
// Close wizard
//DialogResult = DialogResult.Cancel;
if (MessageBox.Show("是否确定取消安装?", "", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK) {
Application.Exit();
}
}
/// <summary>
/// Handles the Click event for the Finish button.
/// </summary>
private void OnClickFinish(object sender, EventArgs e) {
// Ensure a page is currently selected
if (m_selectedIndex != -1) {
// Inform selected page that the Finish button was clicked
WizardPage page = (WizardPage)m_pages[m_selectedIndex];
if (page.OnWizardFinish()) {
// Deactivate page and close wizard
if (page.OnKillActive())
//DialogResult = DialogResult.OK;
Application.Exit();
}
}
}
/// <summary>
/// Handles the Click event for the Next button.
/// </summary>
private void OnClickNext(object sender, EventArgs e) {
// Ensure a page is currently selected
if (m_selectedIndex != -1) {
// Inform selected page that the Next button was clicked
string pageName = ((WizardPage)m_pages[
m_selectedIndex]).OnWizardNext();
switch (pageName) {
// Do nothing
case NoPageChange:
break;
// Activate the next appropriate page
case NextPage:
if (m_selectedIndex + 1 < m_pages.Count)
ActivatePage(m_selectedIndex + 1);
break;
// Activate the specified page if it exists
default:
foreach (WizardPage page in m_pages) {
if (page.Name == pageName)
ActivatePage(m_pages.IndexOf(page));
}
break;
}
}
}
// ==================================================================
// Protected Methods
// ==================================================================
/// <seealso cref="System.Windows.Forms.Control.OnControlAdded">
/// System.Windows.Forms.Control.OnControlAdded
/// </seealso>
protected override void OnControlAdded(ControlEventArgs e) {
// Invoke base class implementation
base.OnControlAdded(e);
// Set default properties for all WizardPage instances added to
// this form
WizardPage page = e.Control as WizardPage;
if (page != null) {
page.Visible = false;
page.Location = new Point(0, 0);
page.Size = new Size(Width, 390);
m_pages.Add(page);
if (m_selectedIndex == -1)
m_selectedIndex = 0;
}
}
/// <seealso cref="System.Windows.Forms.Form.OnLoad">
/// System.Windows.Forms.Form.OnLoad
/// </seealso>
protected override void OnLoad(EventArgs e) {
// Invoke base class implementation
base.OnLoad(e);
// Activate the first page in the wizard
if (m_pages.Count > 0)
ActivatePage(0);
}
// ==================================================================
// Public Methods
// ==================================================================
/// <summary>
/// Sets the text in the Finish button.
/// </summary>
/// <param name="text">
/// Text to be displayed on the Finish button.
/// </param>
public void SetFinishText(string text) {
// Set the Finish button text
m_finishButton.Text = text;
}
/// <summary>
/// Enables or disables the Back, Next, or Finish buttons in the
/// wizard.
/// </summary>
/// <param name="flags">
/// A set of flags that customize the function and appearance of the
/// wizard buttons. This parameter can be a combination of any
/// value in the <c>WizardButton</c> enumeration.
/// </param>
/// <remarks>
/// Typically, you should call <c>SetWizardButtons</c> from
/// <c>WizardPage.OnSetActive</c>. You can display a Finish or a
/// Next button at one time, but not both.
/// </remarks>
public void SetWizardButtons(WizardButton flags) {
// Enable/disable and show/hide buttons appropriately
m_backButton.Enabled =
(flags & WizardButton.Back) == WizardButton.Back;
m_backButton.Visible =
(flags & WizardButton.Back) == WizardButton.Back;
m_nextButton.Enabled =
(flags & WizardButton.Next) == WizardButton.Next;
m_nextButton.Visible =
(flags & WizardButton.Finish) == 0 &&
(flags & WizardButton.DisabledFinish) == 0;
m_finishButton.Enabled =
(flags & WizardButton.DisabledFinish) == 0;
m_finishButton.Visible =
(flags & WizardButton.Finish) == WizardButton.Finish ||
(flags & WizardButton.DisabledFinish) == WizardButton.DisabledFinish;
m_cancelButton.Enabled = (m_backButton.Enabled || m_nextButton.Enabled);
m_cancelButton.Visible = (!m_finishButton.Visible || !m_finishButton.Enabled);
if (flags == WizardButton.DisabledAll) {
m_backButton.Visible = m_nextButton.Visible = m_cancelButton.Visible = true;
m_backButton.Enabled = m_nextButton.Enabled = m_cancelButton.Enabled = false;
m_finishButton.Visible = m_finishButton.Enabled = false;
}
// Set the AcceptButton depending on whether or not the Finish
// button is visible or not
//AcceptButton = m_finishButton.Visible ? m_finishButton : m_nextButton;
}
}
}
<file_sep>using WizardLib;
using System.Windows.Forms;
using Wizard.Core;
using System.Collections.Generic;
using WizardLib.Core;
using WinAPI;
using System.ComponentModel;
using System;
using System.Text.RegularExpressions;
using System.Net.NetworkInformation;
using System.Threading;
namespace Wizard {
public partial class NetWorkPage : InteriorWizardPage {
private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
private readonly Regex MacRegex = new Regex(@"^([0-9a-fA-F]{2}:){5}[0-9a-fA-F]{2}$");
private PIFOper pifOper = new PIFOper();
private bool IsTestPing = false;
private OpaqueCommand cmd;
private bool isFirst = true;
public NetWorkPage() {
InitializeComponent();
cmd = new OpaqueCommand();
}
protected override bool OnSetActive() {
if (!base.OnSetActive())
return false;
log.InfoFormat("进入【网络配置】页面");
InfoLabel.Text = "";
getNetwork();
Wizard.SetWizardButtons(WizardButton.Back | WizardButton.Next);
return true;
}
protected override string OnWizardNext() {
if (!pingButton.Enabled) {
InfoLabel.Text = "正在测试Ping连接,请稍候!";
return null;
}
InfoLabel.Text = "";
if (ipBox1.textBox4.Text == "") {
ipBox1.textBox4.Focus();
InfoLabel.Text = "请输入IP地址最后一位!";
return null;
}
string ip = ipBox1.Value;
if (ip.Equals(ConnectManager.TargetHostName)) {
InfoLabel.Text = "IP地址不能与目标主机相同!";
return null;
}
IsTestPing = false;
doPingConnect();
return null;
}
private void getNetwork() {
pifOper = new PIFOper();
Dictionary<string, string> dict = pifOper.getNetworkInfo(ConnectManager.TargetHost.uuid);
string ip = "";
dict.TryGetValue("ip", out ip);
ipBox1.Value = ip;
ipBox1.textBox1.Enabled = false;
ipBox1.textBox2.Enabled = false;
ipBox1.textBox3.Enabled = false;
//ipBox1.textBox4.Select(0, 0); //取消选中所有文本
string netmask = "";
dict.TryGetValue("netmask", out netmask);
ipBox2.Value = netmask;
ipBox2.Enabled = false;
string gateway = "";
dict.TryGetValue("gateway", out gateway);
ipBox3.Value = gateway;
ipBox3.Enabled = false;
if (ConnectManager.IPMaskGatewayDict != null && ConnectManager.IPMaskGatewayDict.ContainsKey("ip")) {
string manIp = "";
ConnectManager.IPMaskGatewayDict.TryGetValue("ip", out manIp);
if (ip.Substring(0, ip.LastIndexOf(".")).Equals(manIp.Substring(0, manIp.LastIndexOf(".")))) {
ipBox1.Value = manIp;
}
}
Dictionary<string, string> IPMaskGatewayDict = new Dictionary<string, string>();
IPMaskGatewayDict.Add("ip", ipBox1.Value);
IPMaskGatewayDict.Add("netmask", ipBox2.Value);
IPMaskGatewayDict.Add("gateway", ipBox3.Value);
ConnectManager.IPMaskGatewayDict = IPMaskGatewayDict;
}
private void pingButton_Click(object sender, EventArgs e) {
IsTestPing = true;
if (ipBox1.textBox4.Text == "") {
ipBox1.textBox4.Focus();
InfoLabel.Text = "请输入IP地址最后一位!";
return;
}
InfoLabel.Text = "";
doPingConnect();
}
private void doPingConnect() {
pingButton.Enabled = false;
ThreadStart threadStart = new ThreadStart(pingConnect);
Thread thread = new Thread(threadStart);
thread.Start();
cmd.ShowOpaqueLayer(groupBox1, 125, true);
}
private void pingConnect() {
string ip = ipBox1.Value;
Ping p = new Ping();
PingReply reply = p.Send(ip);
ConnFinished(reply.Status.ToString());
}
private delegate void changeText(string status);
public void ConnFinished(string status) {
if (this.InvokeRequired) {
this.BeginInvoke(new changeText(ConnFinished), status);
}
else {
pingButton.Enabled = true;
cmd.HideOpaqueLayer();
if (IPStatus.Success.ToString().Equals(status)) {
InfoLabel.Text = "IP地址已被使用,请输入其他IP!";
}
else {
InfoLabel.Text = "此IP地址可以使用!";
if (Wizard != null) {
if (!IsTestPing) {
foreach (WizardPage page in Wizard.m_pages) {
if ("NetWorkPage" == page.Name) {
setNetwork();
Wizard.ActivatePage(Wizard.m_pages.IndexOf(page) + 1);
break;
}
}
}
}
}
}
}
private void setNetwork() {
NetworkOper networkOper = new NetworkOper();
VIF vif = new VIF();
vif.device = "0";
vif.MAC = "";
vif.MAC_autogenerated = true;
networkOper.setVIF(vif, pifOper.ManageNetwork);
string ip = ipBox1.Value;
string netmask = ipBox2.Value;
string gateway = ipBox3.Value;
Dictionary<string, string> IPMaskGatewayDict = new Dictionary<string, string>();
IPMaskGatewayDict.Add("ip", ip);
IPMaskGatewayDict.Add("netmask", netmask);
IPMaskGatewayDict.Add("gateway", gateway);
ConnectManager.IPMaskGatewayDict = IPMaskGatewayDict;
log.InfoFormat("=======已设置网络start======");
log.InfoFormat("ip: {0}", ip);
log.InfoFormat("netmask: {0}", netmask);
log.InfoFormat("gateway: {0}", gateway);
log.InfoFormat("=======已设置网络end======");
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
namespace WizardLib.Controls.Common {
public delegate bool CheckDelegate(out string error);
public partial class CheckFailure : UserControl {
public CheckFailure() {
InitializeComponent();
}
[Localizable(true)]
public string Error {
get {
return errorLabel.Text;
}
set {
errorLabel.Text = value;
}
}
protected override void OnResize(EventArgs e) {
base.OnResize(e);
errorLabel.MaximumSize = new Size(Width - errorLabel.Margin.Left - errorLabel.Margin.Right -
errorPictureBox.Width - errorPictureBox.Margin.Left - errorPictureBox.Margin.Right, 0);
}
public void ShowError(string errorMsg) {
Visible = true;
Error = errorMsg;
}
public void HideError() {
Visible = false;
}
/// <summary>
/// Performs certain checks on the pages's input data and shows/hides itself accordingly
/// </summary>
/// <param name="checks">The checks to perform</param>
/// <returns></returns>
public bool PerformCheck(params CheckDelegate[] checks) {
foreach (var check in checks) {
string errorMsg;
if (!check.Invoke(out errorMsg)) {
if (string.IsNullOrEmpty(errorMsg))
HideError();
else
ShowError(errorMsg);
return false;
}
}
HideError();
return true;
}
}
}
|
7105d918ff1021296dc17607f236b107f01f0dc2
|
[
"Markdown",
"C#"
] | 42
|
C#
|
radtek/WinCenterClient
|
0855899952efd8a473a3c66019055634bce6d53f
|
08f3260cf16f1abe1f49762554b30d09f4757d75
|
refs/heads/master
|
<repo_name>louiemay/ARAP-surface-modeling<file_sep>/ARAP_3D/ARAP_3D/LocalGlobal.cpp
#include "LocalGlobal.h"
bool LocalGlobal::ReadFromFile(string InputFile)
{
if (!OpenMesh::IO::read_mesh(mesh, InputFile))
return false;
else
return true;
}
bool LocalGlobal::ExportToFile(string OutputFile)
{
if (!OpenMesh::IO::write_mesh(mesh, OutputFile))
return false;
else
return true;
}
void LocalGlobal::Preprocessing()
{
n = static_cast<int>(mesh.n_vertices());
m = static_cast<int>(mesh.n_faces());
this->V.resize(n, 3); // original model
this->F.resize(m, 3); // Remember that row numbers of F is the number of faces in the model
this->V_.resize(n, 3); // current model
for (TriMesh::VertexIter v_it = mesh.vertices_begin(); v_it != mesh.vertices_end(); v_it++){
V((*v_it).idx(), 0) = mesh.point(*v_it)[0];
V((*v_it).idx(), 1) = mesh.point(*v_it)[1];
V((*v_it).idx(), 2) = mesh.point(*v_it)[2];
}
for (TriMesh::FaceIter f_it = mesh.faces_begin(); f_it != mesh.faces_end(); ++f_it){
int index = 0;
for (TriMesh::FaceVertexIter fv_it = mesh.fv_iter(*f_it); fv_it.is_valid(); ++fv_it){
F((*f_it).idx(), index) = (*fv_it).idx();
index++;
}
}
// Construct adjacency list and omega list
construct_adj();
// Initialize R(rotation matrices for all vertices) as identity matrices
R.clear();
R.resize(n, Eigen::Matrix3d::Identity());
}
void LocalGlobal::construct_adj()
{
// Clear and preallocate adjacency list & omega information
// Structures of adj, omega and eij are identical
adj.clear();
omega.clear();
eij.clear();
omega.resize(n, vector<double>());
// Temporary vector containing the adjacent vertex indices of the current vertex
vector<int> temp_adj;
vector<Eigen::Vector3d, aligned_allocator<Eigen::Vector3d>> temp_eij;
for (TriMesh::VertexIter v_it = mesh.vertices_begin(); v_it != mesh.vertices_end(); ++v_it){
temp_adj.clear();
temp_eij.clear();
for (TriMesh::VertexVertexIter vv_it = mesh.vv_iter(*v_it); vv_it.is_valid(); ++vv_it)
{
temp_adj.push_back((*vv_it).idx());
// Calculate edges
Eigen::Vector3d vedge = V.row((*v_it).idx()) - V.row((*vv_it).idx()); // transformed to column vectors
// Column vectors
temp_eij.push_back(vedge); // push back all eij edges into temp_eij
}
adj.push_back(temp_adj);
eij.push_back(temp_eij);
omega[(*v_it).idx()].resize(temp_adj.size(), 0.0); // resize with double(0.0)
}
// Calculate omega list for the mesh
calculate_omega();
}
// Iterate over all halfedges, each halfedge is related to one angle, so there is no need to determine whether
// the edge is boundary or not.
void LocalGlobal::calculate_omega()
{
// Each Halfedge corresponds to only one angle
for (TriMesh::HalfedgeIter he_it = mesh.halfedges_begin(); he_it != mesh.halfedges_end(); ++he_it)
{
// Indices at from_vertex and to_vertex should both be added in 'omega'
TriMesh::VertexHandle from_vertex_handle = mesh.from_vertex_handle(*he_it);
TriMesh::VertexHandle to_vertex_handle = mesh.to_vertex_handle(*he_it);
// Face current halfedge belongs to
TriMesh::FaceHandle face_handle = mesh.face_handle(*he_it);
Vector3i v = F.row(face_handle.idx());
int ThirdVertex;
if (((from_vertex_handle.idx() == v(0)) && (to_vertex_handle.idx() == v(1))) ||
((from_vertex_handle.idx() == v(1)) && (to_vertex_handle.idx() == v(0))))
ThirdVertex = v(2);
else if (((from_vertex_handle.idx() == v(2)) && (to_vertex_handle.idx() == v(1))) ||
((from_vertex_handle.idx() == v(1)) && (to_vertex_handle.idx() == v(2))))
ThirdVertex = v(0);
else if (((from_vertex_handle.idx() == v(2)) && (to_vertex_handle.idx() == v(0))) ||
((from_vertex_handle.idx() == v(0)) && (to_vertex_handle.idx() == v(2))))
ThirdVertex = v(1);
// Pass vertex handles and vertex index to the function
// Calculate value of cotangent theta
//////// ThirdVertex is used without being initialized //////////
double CosTheta = calculate_costheta(from_vertex_handle, to_vertex_handle, ThirdVertex);
double CotTheta = CosTheta / sqrt(1 - pow(CosTheta, 2)); // sin(0~PI) is always positive
// Find location of from_vertex and to_vertex in each other's adjacency list
vector<int>::iterator it;
it = find(adj[to_vertex_handle.idx()].begin(), adj[to_vertex_handle.idx()].end(), from_vertex_handle.idx());
// Location of from_vertex in to_vertex list
int location_from = static_cast<int>(distance(adj[to_vertex_handle.idx()].begin(), it));
it = find(adj[from_vertex_handle.idx()].begin(), adj[from_vertex_handle.idx()].end(), to_vertex_handle.idx());
// Location of to_vertex in from_vertex list
int location_to = static_cast<int>(distance(adj[from_vertex_handle.idx()].begin(), it));
// Since we iterate over all halfedges, and each halfedge corresponds to one angle,
// so we need to include cotangent values in both i-j and j-i
omega[to_vertex_handle.idx()][location_from] += 0.5 * CotTheta;
omega[from_vertex_handle.idx()][location_to] += 0.5 * CotTheta;
}
//std::cout << "Omega calculation successful!\n";
}
double LocalGlobal::calculate_costheta(TriMesh::VertexHandle from_vertex, TriMesh::VertexHandle to_vertex, int third_vertex)
{
// Obtain coordinates of the 3 points using vertex handles and vertex index
TriMesh::Point FromVertex = mesh.point(from_vertex);
TriMesh::Point ToVertex = mesh.point(to_vertex);
TriMesh::VertexHandle third_vertex_handle = mesh.vertex_handle(third_vertex);
TriMesh::Point ThirdVertex = mesh.point(third_vertex_handle);
OpenMesh::Vec3d edge1 = FromVertex - ThirdVertex;
OpenMesh::Vec3d edge2 = ToVertex - ThirdVertex;
// Dot product: a.dotProduct(b)=a*b*cos(<a,b>)
double CosineTheta = (edge1 | edge2) / (edge1.length() * edge2.length());
return CosineTheta;
}
void LocalGlobal::set_handles_static(vector<int> vhandles, Eigen::MatrixXd vHandles, vector<int> vstatic)
{
this->vHandle = vhandles;
this->vHandleCoordinates = vHandles;
this->vStatic = vstatic;
vFixed.clear();
vFixed.resize(n, false);
for (auto x : vhandles)
vFixed[x] = true;
for (auto x : vstatic)
vFixed[x] = true;
//std::cout << "Handles' selection and Fixed initialization successful!\n";
}
// Update rotation matrices R for the iteration process
// Calculated using V, V_ and omega
// update_R() is called after V_ is initialized
void LocalGlobal::update_R()
{
// Given V and V_
// omega contains the weights
//cout << "Length of the adj vector is: " << adj.size() << endl;
for (TriMesh::VertexIter v_it = mesh.vertices_begin(); v_it != mesh.vertices_end(); ++v_it)
{
Eigen::Matrix3d temp_R = Eigen::Matrix3d::Zero();
int i = 0;
for (TriMesh::VertexVertexIter vv_it = mesh.vv_iter(*v_it); vv_it.is_valid(); ++vv_it)
{
Eigen::Vector3d eij_ = V_.row((*v_it).idx()) - V_.row((*vv_it).idx()); // pi_ - pj_
// Equation (5) in 'As-rigid-as-possible surface modeling'
temp_R += omega[(*v_it).idx()][i] * eij[(*v_it).idx()][i] * eij_.transpose(); // pi - pj has been calculated
i++;
}
R[(*v_it).idx()] = temp_R;
}
// By now, R represent the transformation matrix, not the rotation matrix
// The following code execute the SVD computation and calculate Ri
for (int i = 0; i < R.size(); ++i)
{
Eigen::Matrix3d Si = R[i], Ri;
JacobiSVD<Matrix3d> svd(Si, ComputeFullU | ComputeFullV);
Ri = svd.matrixV()*svd.matrixU().transpose();
R[i] = Ri;
}
//std::cout << "R updated successful!\n";
}
// Left side of Equation (9)
// Sort vConstraints in ascending order
// Calculate vShifts
void LocalGlobal::calculate_L()
{
vector<Eigen::Triplet<double>> T;
// vHandles and vStatic must be already placed in ascending order
// No need to rearrange them after combined together
vConstraints.clear();
vConstraints.resize(vHandle.size() + vStatic.size());
std::merge(vHandle.begin(), vHandle.end(), vStatic.begin(), vStatic.end(), vConstraints.begin());
// Set the size of the sparse matrix: excluding number of constraints
this->SpMat.conservativeResize(n - vConstraints.size(), n - vConstraints.size());
this->SpMat.setZero();
auto vcopy = vConstraints; // Get a copy of constraints' information
// Stores the number of delete rows(columns)
int number = static_cast<int>(vcopy.size());
vcopy.emplace(vcopy.begin(), -1);
vcopy.emplace(vcopy.end(), n);
// Initialize value of vShift with 0
// Number of shifts needed to obtain an erased version of L
vShifts.clear();
vShifts.resize(n, 0);
int count = 0;
vector<int>::iterator it = vShifts.begin();
for (int i = 0; i < vcopy.size() - 1; ++i){
vector<int> temp;
temp.clear();
temp.resize(vcopy[i + 1] - vcopy[i] - 1, count);
std::copy(temp.begin(), temp.end(), it);
if (count == number)
break;
it += temp.size() + 1;
count++;
}
// By now elements of vShifts are the number of shifts needed to erase rows and columns
////////// May need to change //////////
// Erasing respective rows and columns from L
for (int i = 0; i < adj.size(); ++i) {
for (int j = 0; j < adj[i].size(); ++j) {
if (!vFixed[i]) {
T.push_back(Eigen::Triplet<double>(i - vShifts[i], i - vShifts[i], omega[i][j]));
if (!vFixed[adj[i][j]])
T.push_back(Eigen::Triplet<double>(i - vShifts[i], adj[i][j] - vShifts[adj[i][j]], -omega[i][j]));
}
}
}
///////////////////////////////////////
this->SpMat.setFromTriplets(T.begin(), T.end());
this->SpMat.makeCompressed();
//std::cout << "Sparse Matrix L initialized successful!\n";
}
// Right side of Equation (9)
void LocalGlobal::calculate_b()
{
// Initialize b to be a zero matrix
// Number of columns is (n - number of constaints)
b = MatrixXd::Zero(n - vConstraints.size(), 3);
Eigen::Vector3d temp_b;
for (int i = 0; i < adj.size(); ++i)
{
temp_b = Eigen::Vector3d::Zero();
if (!vFixed[i]) {
for (int j = 0; j < adj[i].size(); ++j)
{
temp_b += 0.5 * omega[i][j] * (R[i] + R[adj[i][j]]) * eij[i][j];
if (vFixed[adj[i][j]]) {
Eigen::Vector3d pj;
vector<int>::iterator it_j;
it_j = find(vHandle.begin(), vHandle.end(), adj[i][j]);
if (it_j != vHandle.end()) { // Handle vertices
int location = static_cast<int>(distance(vHandle.begin(), it_j));
pj = vHandleCoordinates.row(location);
}
else // Static vertices
pj = this->V.row(adj[i][j]);
// Move item from left of equation (8) to the right
temp_b += omega[i][j] * pj.transpose();
}
}
// Only the insertion of temp_b alters
// Only calculate elements of b whose rows and columns are not deleted
b.row(i - vShifts[i]) = temp_b;
}
}
////////////////// Delete respective rows from b
//std::cout << "b initialization successful!\n";
}
// Prefactor the sparse matrix L
void LocalGlobal::prefactor()
{
//Cholesky.compute(this->SpMat);
LDLT.compute(this->SpMat);
//std::cout << "Prefactor successful!\n";
}
// This function solves the sparse system using calculated L and b
// and update V_(current configuration)
void LocalGlobal::solve_sparse()
{
// x,y,z coordinates for the solution
// Solve for vertices in the free region
// Initialized with zero vector
Eigen::VectorXd x = Eigen::VectorXd::Zero(n - vConstraints.size());
Eigen::VectorXd y = x, z = x;
//x = Cholesky.solve(b.col(0)); // Size: (n - vConstraints.size())*1
//y = Cholesky.solve(b.col(1));
//z = Cholesky.solve(b.col(2));
x = LDLT.solve(b.col(0));
y = LDLT.solve(b.col(1));
z = LDLT.solve(b.col(2));
Eigen::MatrixXd V_sol;
// Resize before initialization
V_sol.resize(n - vConstraints.size(), 3);
// Horizontal sum
V_sol << x, y, z;
// V_temp-----insert rows-----V_mat
Eigen::MatrixXd V_mat = Eigen::MatrixXd::Zero(n, 3);
int it = 0;
// Tested already!!! No error
for (int i = 0; i < interval_pair.size(); ++i){
V_mat.block(interval_pair[i].first, 0, interval_pair[i].second - interval_pair[i].first + 1, V_mat.cols()) =
V_sol.block(it, 0, interval_pair[i].second - interval_pair[i].first + 1, V_mat.cols());
it += interval_pair[i].second - interval_pair[i].first + 1;
}
// Update static+fixed vertices with constraints
for (int i = 0; i < vHandle.size(); ++i)
V_mat.row(vHandle[i]) = vHandleCoordinates.row(i);
for (auto j : vStatic)
V_mat.row(j) = V.row(j);
// Do all assignment operation with V_mat
// update current model coordinates with V_mat finally
V_ = V_mat;
//std::cout << "Sparse solving and coordinates' update successful!\n";
}
void LocalGlobal::calculate_energy()
{
// Use default setting, wi = 1 in equation (7)
// When calculating deformation energy, the V_ has already been updated
double temp_energy = 0.0;
Eigen::Vector3d temp_v = Eigen::Vector3d::Zero();
for (int i = 0; i < adj.size(); ++i)
{
for (int j = 0; j < adj[i].size(); ++j)
{
// All components of temp_v must be 3*1
temp_v = (V_.row(i) - V_.row(adj[i][j])).transpose() - R[i] * eij[i][j];
temp_v.squaredNorm();
temp_energy += omega[i][j] * temp_v.squaredNorm();
}
}
this->energy = temp_energy;
std::cout << "Deformation energy:" << this->energy << endl;
}
void LocalGlobal::iteration()
{
// Since handles+static are specified, the L matrix is definite,thus we can prefactor it.
calculate_L();
prefactor();
// Given constraint vertices(handle+static)
calculate_interval_pair();
// V_initial is the initial guess for the coordinates of vertices
// same dimension as V and V_
Eigen::MatrixXd V_initial = Eigen::MatrixXd::Zero(n, 3);
if (attribute.initial == Attribute::Default)
{
if (V_initial.rows() == V.rows() && V_initial.cols() == V.cols())
V_initial = V;
else
cerr << "Dimensions of V_initial and V are not equal!\n";
for (int i = 0; i < vHandle.size(); ++i)
V_initial.row(vHandle[i]) = vHandleCoordinates.row(i);
}
else if (1){}
V_ = V_initial;
calculate_energy();
int index = 10;
//display_V_(n);
// e_previous first stores the initial deformation energy
double e_previous = this->energy;
int i = 0;
while (1)
{
update_R();
calculate_b();
solve_sparse();
calculate_energy();
///// For test purposes
//display_R(index);
//display_b(index);
//display_V_(n);
//display_vConstraints();
//display_vHandlesStatic();
//display_SparseNonzero();
//break;
double e_latter = this->energy;
double eps = abs((e_previous - e_latter) / e_previous);
e_previous = e_latter;
cout << "eps: " << eps << endl;
i++;
std::cout << i << "'s iteration\n";
if (eps < this->epsilon)
break;
}
std::cout << "Iteration completed!\n" << i << " iterations in total.\n";
std::cout << "Deformation energy is: " << this->energy << endl;
UpdateMesh();
std::cout << "New vertices' positions updated.\n";
std::cout << "Coordinates of new vertex positions are stored in V_.\n";
}
// Select handle vertices and static vertices for the model to be deformed
// Default settings: zmin vertices as static, zmax vertices as handles
bool LocalGlobal::SelectHandlesStatic(int NumberOfHandles, int NumberOfStatic, Eigen::MatrixXd& vHandleCoordinates,
vector<int>& vHandles, vector<int>& vStatic, int indicator)
{
std::cout << "Select " << NumberOfHandles << " handle vertices and " << NumberOfStatic << " static vertices.\n";
vHandles.clear(); vStatic.clear();
string dir;
(indicator == 0) ? dir = "x" : ((indicator == 1) ? dir = "y" : ((indicator == 2) ? dir = "z" : dir = "NULL"));
std::cout << "Current configuration selects vertices\n" << dir << "_max as handles\n" << dir << "_min as static.\n";
Eigen::VectorXd vec = V.col(indicator);
Eigen::VectorXd translation;
auto vec_temp = vec;
int index;
vHandleCoordinates.resize(NumberOfHandles, 3);
translation = (indicator == 0) ? 0.5*(V.col(0).maxCoeff() - V.col(0).minCoeff())*Vector3d(1, 0, 0) :
((indicator == 1) ? 0.5*(V.col(1).maxCoeff() - V.col(1).minCoeff())*Vector3d(0, 1, 0) :
((indicator == 2) ? 0.5*(V.col(2).maxCoeff() - V.col(2).minCoeff())*Vector3d(0, 0, 1) : Vector3d(0, 0, 0)));
// Select max_coordinates for the model
for (int i = 0; i < NumberOfHandles; ++i)
{
vec_temp.maxCoeff(&index);
vHandles.push_back(index);
// Move chosen coordinates from original positions
vHandleCoordinates.row(i) = V.row(index) + translation.transpose();
vec_temp[index] = DBL_MIN;
}
// Select min_coordinates for the model
vec_temp = vec;
for (int i = 0; i < NumberOfStatic; ++i)
{
vec_temp.minCoeff(&index);
vStatic.push_back(index);
vec_temp[index] = DBL_MAX;
}
// Sort vHandles and vStatic in ascending order
std::sort(vHandles.begin(), vHandles.end(), myobject);
std::sort(vStatic.begin(), vStatic.end(), myobject);
std::cout << vHandles.size() << " handle vertices selected.\n" << vStatic.size() << " static vertices selected.\n";
return true;
}
void LocalGlobal::display_R(int i)
{
std::cout << "Rotation matrix display:\n";
for (int index = 0; index < i; ++index)
{
std::cout << "R" << index + 1 << endl;
cout << R[index] << endl;
}
}
void LocalGlobal::display_b(int i)
{
cout << "b display:\n";
//cout << b.topRows(i) << endl;
//cout << b.row(48) << endl;
cout << b << endl;
}
void LocalGlobal::display_V_(int i)
{
cout << "V_:\n";
cout << V_.topRows(i) << endl;
}
void LocalGlobal::display_vHandlesStatic()
{
cout << "Original handle positions:\n";
for (auto x : vHandle)
{
cout << x << "# ";
cout << V.row(x) << endl;
}
cout << "New handle positions:\n";
cout << vHandleCoordinates << endl;
cout << "Static vertices:\n";
for (auto x : vStatic)
{
cout << x << "# ";
cout << V.row(x) << endl;
}
}
void LocalGlobal::display_SparseNonzero()
{
for (SparseMatrix<double>::InnerIterator it(SpMat, 2); it; ++it)
{
cout << "Value: " << it.value() << endl;
cout << "row: " << it.row() << endl;
cout << "col: " << it.col() << endl;
cout << "index: " << it.index() << endl;
}
}
int LocalGlobal::calculate_deleted_elements(int serial)
{
return 0;
}
void LocalGlobal::calculate_interval_pair()
{
// interval_pair: contains intervals of vertex list [0~n-1] separated by vertices in vConstraints(static+handle)
// It is used to reconstruct complete V_ from calculated b (length = n - vConstraints)
interval_pair.clear();
auto vConstraints_copy = vConstraints; // Get a copy of vConstraints
vConstraints_copy.emplace(vConstraints_copy.begin(), -1);
vConstraints_copy.emplace(vConstraints_copy.end(), n); // n: number of vertices in total
for (int i = 0; i < vConstraints_copy.size() - 1; ++i){
if ((vConstraints_copy[i + 1] - vConstraints_copy[i]) == 1)
continue;
else
interval_pair.push_back(make_pair(vConstraints_copy[i] + 1, vConstraints_copy[i + 1] - 1));
}
cout << "interval_pair calculation completed!\n";
}
void LocalGlobal::UpdateMesh()
{
for (TriMesh::VertexIter v_it = mesh.vertices_begin(); v_it != mesh.vertices_end(); ++v_it){
mesh.point(*v_it)[0] = V_((*v_it).idx(), 0);
mesh.point(*v_it)[1] = V_((*v_it).idx(), 1);
mesh.point(*v_it)[2] = V_((*v_it).idx(), 2);
}
cout << "Update mesh successful!\n";
}
<file_sep>/README.md
# ARAP-surface-modeling
Implementation of ARAP surface modeling method in the paper "<NAME> and <NAME>, As-Rigid-As-Possible Surface modeling, 2007, Eurographics Symposium on Geometry Processing".
Developed in Visual Studio 2015(x64), on a Window 8(x64) operating system.
External libraries include:
1. OpenMesh 6.2 (data structure for 3d triangular meshes)
2. Eigen 3.3.4 (matrix computation and sparse linear solvers)
<file_sep>/ARAP_3D/ARAP_3D/main.cpp
#include "mesh.h"
#include "LocalGlobal.h"
#include <Windows.h>
#include <fstream>
#include <istream>
#include <iomanip>
int main()
{
cout.precision(5);
// initiate timer
clock_t start, finish;
double totaltime;
start = clock();
// Indices of handles and static vertices
vector<int> vHandles, vStatic;
// New coordinates of handles after deformation
Eigen::MatrixXd vHandleCoordinates;
vector<string> filenames = { "sphere.obj","sphere_out.obj" };
LocalGlobal lg;
lg.ReadFromFile(filenames[0]);
lg.set_attribute(LocalGlobal::Attribute::OneRingNeighbor, LocalGlobal::Attribute::ContangentWeights,
LocalGlobal::Attribute::Default, 1e-3);
int NumberOfHandles, NumberOfStatic;
NumberOfHandles = 3;
NumberOfStatic = 3;
// Default settings: xyz_min vertices as static, xyz_max vertices as handles
int indicator = 0; // 0:x; 1:y; 2:z
lg.Preprocessing();
lg.SelectHandlesStatic(NumberOfHandles, NumberOfStatic, vHandleCoordinates, vHandles, vStatic, indicator);
// We put 'SelectHandlesStatic' and 'set_handles_static' in sequence explicitly since we may have the need to specify
// handle and static vertices in the main function
// Set handles through direct assignment, specify data in the main function
lg.set_handles_static(vHandles, vHandleCoordinates, vStatic);
// Set handle vertices and static vertices before the prefactorization of sparse system matrix
// Since the incorporation of constraints alter L
lg.iteration();
// Export new mesh to file
lg.ExportToFile(filenames[1]);
finish = clock();
totaltime = (double)(finish - start) / CLOCKS_PER_SEC;
cout << "Running time:\n" << setprecision(5) << totaltime << " s" << endl;
return 0;
}
<file_sep>/ARAP_3D/ARAP_3D/LocalGlobal.h
#pragma once
#ifndef LOCALGLOBAL_H
#define LOCALGLOBAL_H
#define NDEBUG
#include "mesh.h"
#include <iostream>
#include <algorithm>
#include <vector>
#include <set>
#include <string>
#include <iterator>
#include <iomanip>
#include <sstream>
#include <fstream>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <math.h>
#include <cassert>
#include <stdlib.h>
#include <utility>
#include <Eigen/Sparse>
#include <Eigen/SparseCore>
#include <Eigen/Cholesky>
#include <Eigen/Dense>
#include <Eigen/SVD>
#include <Eigen/StdVector>
#include <Eigen/IterativeLinearSolvers>
#include <Eigen/SparseCholesky>
#include <Eigen/SparseLU>
#include <Eigen/SparseQR>
#include <Eigen/OrderingMethods>
using namespace std;
using namespace Eigen;
class LocalGlobal
{
public:
struct Attribute{
enum RingNeighbor { OneRingNeighbor, TwoRingNeighbor, VariantNeighbor };
enum Weights { ContangentWeights };
enum Initial { Default, Laplacian };
RingNeighbor ringneighbor;
Weights weights;
Initial initial;
};
LocalGlobal() {
attribute.ringneighbor = Attribute::RingNeighbor::OneRingNeighbor;
attribute.weights = Attribute::Weights::ContangentWeights;
attribute.initial = Attribute::Initial::Default;
this->epsilon = 1e-3;
};
~LocalGlobal() {};
// Read data from InputFile, save the mesh information in 'mesh'
bool ReadFromFile(string InputFile);
bool ExportToFile(string OutputFile);
// Preprocessing of the ARAP modeling, including construction of V and F,
void Preprocessing();
void set_attribute(Attribute::RingNeighbor r, Attribute::Weights w, Attribute::Initial i, double eps){
attribute.ringneighbor = r;
attribute.weights = w;
attribute.initial = i;
this->epsilon = eps;
};
void set_handles_static(vector<int>, Eigen::MatrixXd, vector<int>);
// Start the iteration process: core of the local-global process
void iteration();
bool SelectHandlesStatic(int NumberOfHandles, int NumberOfStatic, Eigen::MatrixXd& vHandleCoordinates,
vector<int>& vHandles, vector<int>& vStatic, int indicator);
private:
void construct_adj();
void calculate_omega();
// Pass the from_vertex, to_vertex handles and third_vertex indices to the function to calculate the
// cotangent value of theta
double calculate_costheta(TriMesh::VertexHandle from_vertex, TriMesh::VertexHandle to_vertex, int third_vertex);
void update_R();
// Calculate sparse matrix L in advance, no need to change L during iteration.
void calculate_L();
// Calculate b on-line during iteration, change from time to time
void calculate_b();
// Solve the sparse linear system
void solve_sparse();
// Calculate deformation energy
void calculate_energy();
// Prefactor the L matrix
void prefactor();
// Calculate number of deleted rows(columns)
// Input is the serial number of current row or column
int calculate_deleted_elements(int serial);
// Calculate interval_pair
void calculate_interval_pair();
// Update vertex coordinates for output purposes
void UpdateMesh();
// Display first i matrices
void display_R(int i);
// Display first i rows of b
void display_b(int i);
// Display first i rows of current coordinates matrix
void display_V_(int i);
void display_vHandlesStatic();
void display_SparseNonzero();
void display_vConstraints() { for (auto x : vConstraints) { cout << x << " "; } };
// Declare private object of class LocalGlobal
struct myclass{
bool operator()(int i, int j) { return (i < j); }
}myobject;
TriMesh mesh;
Eigen::MatrixXd V; // Rows are coordinates of the original model
Eigen::MatrixXi F; // Rows are the face-vertex indices of the model, Corner
// Also include the initial guess
// Updated after each sparse matrix solving
Eigen::MatrixXd V_; // Rows are the coordinates of the current model
// Structures of 'omega','eij' and 'adj' are identical
vector <vector<double>> omega; // weights for omega_ij
vector <vector<int>> adj; // adjacent list information of vertices in the mesh
// edges of the original mesh (precomputed)
vector <vector<Eigen::Vector3d, aligned_allocator<Eigen::Vector3d>>> eij;
// Attribute information for LocalGlobal iteration
Attribute attribute;
// List of all ROTATION matrices for each vertex-centered cell
// Need to be computed using Singular Value Decomposition (SVD)
// Same order as in V
vector<Matrix3d, aligned_allocator<Matrix3d>> R;
// List of indices for all handles
vector<int> vHandle;
// Coordinates of NEW COORDINATES for all handles
Eigen::MatrixXd vHandleCoordinates;
// List of static vertices. No need to store the coordinates of static vertices
vector<int> vStatic;
// Combination of vHandle and vStatic
vector<int> vConstraints;
// Number of shifts for each row and column in L
// Length n:
vector<int> vShifts;
// Length n: indicates whether vertex is fixed(handle+static) or not
vector<bool> vFixed;
// Sparse matrix of discrete Laplace-Beltrami operator (modified to meet the constraints requirements)
Eigen::SparseMatrix<double> SpMat;
// Default use Cholesky decomposition
Eigen::SimplicialCholesky<Eigen::SparseMatrix<double>> Cholesky;
Eigen::SimplicialLDLT<Eigen::SparseMatrix<double>> LDLT;
// Right side of equation (9), 'b' is a n*3 matrix, including x-y-z coordinates
Eigen::MatrixXd b;
// Interval pair: includes the start and end of rows separated by erased rows
vector<pair<int, int>> interval_pair;
// Number of vertices
int n;
// Number of faces
int m;
// Deformation energy
double energy;
// Epsilon that defines the stopping criteria of the Local-Global iteration process
double epsilon = 1e-3;
};
#endif <file_sep>/ARAP_3D/ARAP_3D/mesh.h
#pragma once
#ifndef MESH_H
#define MESH_H
#include <OpenMesh/Core/IO/MeshIO.hh>
#include <OpenMesh/Core/Mesh/TriMesh_ArrayKernelT.hh>
#include <OpenMesh/Core/Geometry/VectorT.hh>
#include <OpenMesh/Core/Mesh/AttribKernelT.hh>
struct MyTraits : OpenMesh::DefaultTraits
{
// Let Point and Normal be a vector of doubles
typedef OpenMesh::Vec3d Point;
typedef OpenMesh::Vec3d Normal;
// The default 2D texture coordinate type is OpenMesh::Vec2f.
typedef OpenMesh::Vec2d TexCoord2D;
VertexAttributes(OpenMesh::Attributes::Status | OpenMesh::Attributes::Normal | OpenMesh::Attributes::Color
| OpenMesh::Attributes::TexCoord2D);
HalfedgeAttributes(OpenMesh::Attributes::Status | OpenMesh::Attributes::PrevHalfedge);
FaceAttributes(OpenMesh::Attributes::Status | OpenMesh::Attributes::Normal | OpenMesh::Attributes::Color);
EdgeAttributes(OpenMesh::Attributes::Status | OpenMesh::Attributes::Color);
};
typedef OpenMesh::TriMesh_ArrayKernelT<MyTraits> TriMesh;
#endif // MESH_H
|
499229763e12761f1447d686b92f423e5d47444b
|
[
"Markdown",
"C",
"C++"
] | 5
|
C++
|
louiemay/ARAP-surface-modeling
|
686faf76e21b0353a4f1fd9aeb9632b0ab01d832
|
cd129d6cd0648775e2fa16e21000f91593405561
|
refs/heads/main
|
<file_sep>const path = require('path');
const webpack = require('webpack');
const {CleanWebpackPlugin} = require('clean-webpack-plugin');
const CopyPlugin = require("copy-webpack-plugin");
const HtmlWebpackPlugin = require("html-webpack-plugin");
module.exports = {
mode: 'development',
entry: {
background: './src/background.js',
options: './src/options.js',
popup: './src/popup.js',
inject: './src/inject.js'
},
devtool: 'inline-source-map',
plugins: [
new CopyPlugin({
patterns: [
{ from: "./src/*.json", to: "./[name].json"},
{from: "./node_modules/sql.js/dist/sql-wasm.wasm", to: "./"}
],
}),
new HtmlWebpackPlugin({
filename: "options.html",
template: "./src/options.html",
chunks: ["options"]
}),
new HtmlWebpackPlugin({
filename: "popup.html",
template: "./src/popup.html",
chunks: ["popup"]
}),
new webpack.ProvidePlugin({
Buffer: ['buffer', 'Buffer'],
process: 'process'
}),
new CleanWebpackPlugin()
],
output: {
filename: '[name].js',
path: path.resolve(__dirname, 'dist'),
},
resolve: {
fallback: {
"zlib": require.resolve("browserify-zlib"),
"assert": require.resolve("assert/"),
"stream": require.resolve("stream-browserify"),
"util": require.resolve("util/"),
"path": require.resolve("path-browserify"),
"fs": require.resolve("browserify-fs")
}
},
module: {
rules: [
{
test: /\.css$/,
loader: "css-loader",
options: {
esModule: false
}
},
],
}
};<file_sep># KeepLearning
Web extension that helps limit spend on websites using anki flashcards
<file_sep>document.getElementById("test-btn").addEventListener("click",displayCard);
function displayCard(){
chrome.runtime.sendMessage("displayCard");
//chrome.tabs.executeScript({file: "./inject.js"});
}<file_sep>const unzip = require("unzip-js");
const initSql = require("sql.js");
/**
* @typedef {Object} Note
* @property {Number} id - id of the note
* @property {Number} mid - id of the model
* @property {String[]} fld - fields of the note
*/
/**
* @typedef {Object} Card
* @property {Number} id - id of the card
* @property {Number} nid - id of the note
* @property {Number} ord - position of template in model array of templates
*/
/**
* @typedef {Object} Template
* @property {String} front - front HTML of the card
* @property {String} back - back HTML of the card
*/
/**
* @typedef {Object} Field
* @property {String} name - name of field
* @property {Number} ord - position of field in fld array of note
*/
/**
* @typedef {Object} Model
* @property {Number} id - id of the model
* @property {Field[]} flds - fields of the model
* @property {Template[]} tmpls - templates of the model
* @property {String} css - css to be used in model
*/
/**
* @typedef {Object} Deck
* @property {Number} id - id of the deck
* @property {String} name - name of the deck
* @property {Card[]} cards - cards in this deck
*/
/**
* @typedef {Object} DecksStore
* @property {Deck[]} decks - all decks
* @property {Model[]} models - all models
* @property {Note[]} notes - all notes
*/
/**
* @param {File} file
* @returns {Promise<DecksStore>}
*/
function getDeck(file){
return new Promise((resolve, reject) => {
unzip(file,(err,zipFile) => {
zipFile.readEntries(/**@param {Entry[]} entries */(err,entries)=>{
for (let entry of entries){
if (entry.name == 'collection.anki2'){
zipFile.readEntryData(entry,false,(err, readStream) => {
databaseCreate(err, readStream).then(parseDatabase).then(resolve);
});
break;
}
}
})
})
});
}
/**
*
* @param {import('sql.js/module').SqlJs.Database} db
*/
function parseDatabase(db){
const col = db.exec("SELECT models,decks FROM col")[0];
const decksJSON = JSON.parse(col.values[0][1]);
const modelsJSON = JSON.parse(col.values[0][0]);
const cards = db.exec("SELECT id,nid,did,ord FROM cards")[0].values;
const notes = db.exec("SELECT id,mid,flds FROM notes")[0].values;
db.close();
/**@type {Deck[]} */
var decks = [];
for(let deck in decksJSON){
let id = Number.parseInt(deck);
let deckCards = cards.filter(e => e[2] === id).map(e =>{
return {
id: e[0],
nid: e[1],
ord: e[3]
}
});
if(deckCards.length) decks.push({id: id, name: decksJSON[deck].name, cards: deckCards});
}
/**@type {Model[]} */
var models = [];
for(let model in modelsJSON){
let id = Number.parseInt(model);
/**@type {Field[]} */
let flds = modelsJSON[model].flds;
flds.forEach(fld =>
["media","sticky","rtl","font","size"].forEach(e=>{delete fld[e];})
);
/**@type {Template[]} */
let tmpls = modelsJSON[model].tmpls.map(tmpl =>{
return {front: tmpl.qfmt, back: tmpl.afmt};
});
models.push({id: id, flds: flds, tmpls: tmpls, css: modelsJSON[model].css});
}
var notesArr = notes.map(e => {
return {id: Number.parseInt(e[0]), mid: Number.parseInt(e[1]), fld: e[2].split('')}
});
return new Promise((resolve,reject)=>resolve({decks: decks, models: models, notes: notesArr}));
}
/**
*
* @param {Error} err
* @param {ReadStream} readStream
*/
function databaseCreate(err, readStream){
return new Promise((resolve, reject) => {
var bufs = [];
readStream.on('data', (chunk) => {
bufs.push(chunk);
});
readStream.on('end', () => {
console.log('Data read, init sql.');
var buf = Buffer.concat(bufs);
initSql().then(function(SQL){
var db = new SQL.Database(new Uint8Array(buf));
resolve(db);
});
});
}
)
}
module.exports = {getDeck};<file_sep>const {getDeck} = require("./anki");
const emptyDecksStore = {
decks: [],
models: [],
notes: []
}
var selectedDeckId = 0;
const decksList = document.getElementById("decks-list");
document.getElementById("test-url").textContent = chrome.runtime.getURL("popup.html");
decksList.childNodes.forEach(c => c.addEventListener("click",onDeckSelect));
loadOptions();
loadDeckEntries();
const cardNumInput = document.getElementById("card-num-input");
const timeInput = document.getElementById("time-input");
cardNumInput.addEventListener("change",updateOptions);
timeInput.addEventListener("change",updateOptions);
const fileImport = document.getElementById("import-btn"),
fileElem = document.getElementById("file-elem");
fileImport.addEventListener(
"click",
function (e) {
e.preventDefault();
if (fileElem) {
fileElem.click();
}
},
false
);
fileElem.addEventListener("change",handleFile, false);
async function handleFile(){
const deck = await getDeck(this.files[0]);
chrome.storage.local.get({decksStore:emptyDecksStore}, ds =>{
deck.decks.forEach(newDeck => {
if(!ds.decksStore.decks.find(e=>e.id === newDeck.id)) ds.decksStore.decks.push(newDeck);
});
deck.models.forEach(newModel => {
if(!ds.decksStore.models.find(e=>e.id === newModel.id)) ds.decksStore.models.push(newModel);
});
deck.notes.forEach(newNote => {
if(!ds.decksStore.notes.find(e=>e.id === newNote.id)) ds.decksStore.notes.push(newNote);
});
console.log("inserting");
console.log(ds);
chrome.storage.local.set(ds);
loadDeckEntries();
});
}
function onDeckSelect(event){
var element = event.target;
console.log("click");
selectDeck(element);
updateSelectedDeck(Number.parseInt(element.id.split('.')[1]));
}
function selectDeck(element){
Array.prototype.slice.call(decksList.children).forEach(c => c.classList.remove("selected"));
element.classList.add("selected");
}
function updateSelectedDeck(id){
selectedDeckId = id;
chrome.storage.local.set({selected: selectedDeckId});
}
function loadSelectedDeck(){
chrome.storage.local.get("selected", e => {
if(e.selected) {
selectedDeckId = e.selected;
let selectedElem = document.getElementById("deck." + selectedDeckId);
if(selectedElem) selectDeck(selectedElem);
}
if(!selectedDeckId){
let child = decksList.firstElementChild;
if(child){
selectDeck(child);
updateSelectedDeck(Number.parseInt(child.id.split('.')[1]));
}
}
});
}
function updateOptions(){
console.log("update options");
if(this.value < 1) this.value = 1;
chrome.storage.local.set({options: {cards: cardNumInput.value, time: timeInput.value}});
}
function loadOptions(){
chrome.storage.local.get({options: {cards:3,time:5}},e=>{
console.log("getting options");
cardNumInput.value = e.options.cards;
timeInput.value = e.options.time;
});
}
function loadDeckEntries(){
chrome.storage.local.get({decksStore:emptyDecksStore},e=>{
console.log("getting deck entries");
if(e.decksStore.decks.length){
decksList.innerHTML = "";
for(let deck of e.decksStore.decks){
decksList.insertAdjacentHTML("beforeend",
`<li id="deck.${deck.id}">${deck.name}<i class="fa-pull-right fa fa-trash"></i></li>`);
document.getElementById(`deck.${deck.id}`).addEventListener("click",onDeckSelect);
}
}
loadSelectedDeck();
});
}
|
b07cad9e8d2518c9cfe3bd03f6817dd457589d15
|
[
"JavaScript",
"Markdown"
] | 5
|
JavaScript
|
dumnicki/KeepLearning
|
9cf57f10c246fc8de2b5f7227c6359765ebce85c
|
46a4d1ea7d0137dc52c478897577e0e494e75936
|
refs/heads/main
|
<file_sep>// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init()
// 云函数入口函数
exports.main = async (event, context) => {
const wxContext = cloud.getWXContext()
return {
circum:(event.width + event.height)*2,
area:event.width*event.height
}
}<file_sep>// miniprogram/pages/familySupportOrder/familuSupportOrder.js
Page({
/**
* 页面的初始数据
*/
data: {
list:[
{
pagePath:"/pages/familySupportIndex/familySupportIndex",
text:"家政",
iconPath:"/images/tabIcons/首页.svg",
selectedIconPath:"/images/tabIcons/首页(选中).svg"
},
{
pagePath:"/pages/index/index",
text:"测试页",
iconPath:"/images/tabIcons/订单.svg",
selectedIconPath:"/images/tabIcons/订单(选中).svg"
},
{
pagePath:"/pages/familySupportOrder/familySupportOrder",
text:"订单",
iconPath:"/images/tabIcons/订单.svg",
selectedIconPath:"/images/tabIcons/订单(选中).svg"
},
{
pagePath:"/pages/familySupportHome/familySupportHome",
text:"我的",
iconPath:"/images/tabIcons/我的.svg",
selectedIconPath:"/images/tabIcons/我的(选中).svg"
}
]
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function () {
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function () {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function () {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function () {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function () {
},
/**
* 用户点击右上角分享
*/
onShareAppMessage: function () {
}
})<file_sep>//app.js
App({
onLaunch: function () {
if (!wx.cloud) {
console.error('请使用 2.2.3 或以上的基础库以使用云能力')
} else {
wx.cloud.init({
// env 参数说明:
// env 参数决定接下来小程序发起的云开发调用(wx.cloud.xxx)会默认请求到哪个云环境的资源
// 此处请填入环境 ID, 环境 ID 可打开云控制台查看
// 如不填则使用默认环境(第一个创建的环境)
// env: 'my-env-id',
env: 'cloud1-8giyelmo48e04b7e',
traceUser: true,
})
}
this.globalData = {}
},
// 入驻申请界面
idcardFront:"https://636c-cloud1-8giyelmo48e04b7e-1305708349.tcb.qcloud.la/pics/%E4%B8%AA%E4%BA%BA%E5%85%A5%E9%A9%BB%E7%95%8C%E9%9D%A2/%E8%BA%AB%E4%BB%BD%E8%AF%81%E6%AD%A3%E9%9D%A2.png?sign=0edf7d4ce31b0bf1cc5a73294310db04&t=1620279514",
idcardBack:"https://636c-cloud1-8giyelmo48e04b7e-1305708349.tcb.qcloud.la/pics/%E4%B8%AA%E4%BA%BA%E5%85%A5%E9%A9%BB%E7%95%8C%E9%9D%A2/%E8%BA%AB%E4%BB%BD%E8%AF%81%E8%83%8C%E9%9D%A2.png?sign=2a77f641380f0c665aaea55cd881b198&t=1620279688"
})
<file_sep>// miniprogram/pages/familySupportMemberAdd/familySupportMemberAdd.js
const app = getApp();
Page({
/**
* 页面的初始数据
*/
data: {
cardRule:[{
required: true
},{
type: 'number',
min: 16,
max: 19,
message: "长度在16-19之间"
}],
trueName:"", // 服务者姓名
phoneNumber:"", // 手机号码
idCardNumber:"", // 身份证号码
idcardUrlFront : "", // 身份证正面图片本地临时路径
idcardFrontFileID:"", // 身份证正面云存储后的 fileID
idcardUrlBack : "", // 身份证背面图片本地临时路径
idcardBackFileID:"", // 身份证背面云存储后的 fileID
selfIntroduction:"", // 自我介绍
householdElectrical:false, // 家电维装
houseClean:false, // 保洁清洗
houseRepair:false, // 房屋修装
furnitureRepair:false, // 家具维装
rushPipe:false, // 管道疏通
others:false, // 其他
pics:[], // 其它个人信息图片
otherInfoFileIDs:new Array(), // 其它个人信息图片 fileID 集合
status:"in review" // 入驻申请状态 in review; verified; unverified
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
this.setData({
// 初始化界面图片(身份证默认图片赋值)
idcardUrlFront : app.idcardFront,
idcardUrlBack : app.idcardBack
})
// 查询数据库是否有该用户的入驻申请,根据情况显示不同的页面
// 审核中in review 审核通过verified 审核未通过unverified
let db = wx.cloud.database();
// db.collection("serverProviderInfo").
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function () {
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function () {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function () {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function () {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function () {
},
/**
* 用户点击右上角分享
*/
onShareAppMessage: function () {
},
/**
* 身份证正面
*/
chooseFrontIdCard: function() {
let tempFilePaths = this.data.idcardUrlFront;
wx.chooseImage({
count: 1,
sizeType:'compressed',
sourceType: ['album', 'camera'],
success: res => {
// tempFilePath可以作为img标签的src属性显示图片
tempFilePaths = res.tempFilePaths
console.log("插入新图片了,地址:" + tempFilePaths)
this.setData({
idcardUrlFront:tempFilePaths
})
}
})
},
/**
* 身份证背面
*/
chooseBackIdCard: function (params) {
let tempFilePaths = this.data.idcardUrlBack;
wx.chooseImage({
count: 1,
sizeType:'compressed',
sourceType: ['album', 'camera'],
success: res => {
// tempFilePath可以作为img标签的src属性显示图片
tempFilePaths = res.tempFilePaths
console.log("插入新图片了,地址:" + tempFilePaths)
this.setData({
idcardUrlBack:tempFilePaths
})
}
})
},
/**
* 服务行业数组绑定
*/
serverFields(param) {
this.setData({
householdElectrical:this.judgeFields(param.detail.value,"家电维装"),
houseClean:this.judgeFields(param.detail.value,"保洁清洗"),
houseRepair:this.judgeFields(param.detail.value,"房屋修装"),
furnitureRepair:this.judgeFields(param.detail.value,"家具维装"),
rushPipe:this.judgeFields(param.detail.value,"管道疏通"),
others:this.judgeFields(param.detail.value,"其他")
})
},
/**
* 数组筛选实现
*/
judgeFields(fieldsArray,field) {
let array = Array.from(fieldsArray);
for (let i = 0; i < array.length; i++) {
if (array[i] == field) {
return true;
}
}
return false;
},
/**
* 照片增加绑定
*/
imageAdd: function(param) {
console.log(param.detail)
this.setData({
pics:param.detail.all
})
},
/**
* 照片去除绑定
*/
imageRemove: function(param) {
this.setData({
pics:param.detail.all
})
},
submitUserInfo: async function(param) {
wx.showLoading({
title: '加载中',
mask:true,
})
// this.printBindingInfos();
// 上传身份证图片,获取 fileID
await this.storeIDCardFilesIntoCloudDB();
// 上传个人信息图片,获取 fileID
await this.storeManInfoFilesIntoCloudDB();
// 提交审核存储申请信息到与数据库
this.storeInfoIntoCloudDB();
console.log("上传完成,更新完成")
// 提交审核,上传完毕后跳转到
wx.redirectTo({
url: '/pages/familySupportMemberAddDone/familySupportMemberAddDone',
})
},
/**
* 将需要审核的身份证图片存到云存储,获得图片的 fileID 并绑定
*/
storeIDCardFilesIntoCloudDB: async function() {
// const cloudPath = `pics/个人入驻界面/${Date.now()}-${Math.floor(Math.random(0, 1) * 1000)}` + this.data.idcardUrlFront.match(/\.[^.]+?$/);
let idcardUrlArray = [this.data.idcardUrlFront[0], this.data.idcardUrlBack[0]];
for (let i = 0; i < idcardUrlArray.length; i++) {
const cloudPath = `pics/个人入驻界面/身份证/${Date.now()}-${Math.floor(Math.random(0, 1) * 1000)}`;
await wx.cloud.uploadFile({
cloudPath,
filePath:idcardUrlArray[i],
}).then(res=> {
if(i == 0) {
this.setData({
idcardFrontFileID:res.fileID
})
} else if (i==1) {
this.setData({
idcardBackFileID:res.fileID
})
}
}).catch(error => {
console.log(error)
})
}
},
/**
* 将需要审核的个人信息图片存到云存储,获得图片的 fileID 并绑定
*/
storeManInfoFilesIntoCloudDB: async function() {
// const cloudPath = `pics/个人入驻界面/${Date.now()}-${Math.floor(Math.random(0, 1) * 1000)}` + this.data.idcardUrlFront.match(/\.[^.]+?$/);
let picsArray = new Array();
for (let i = 0; i < this.data.pics.length; i++) {
const cloudPath = `pics/个人入驻界面/其它信息/${Date.now()}-${Math.floor(Math.random(0, 1) * 1000)}`;
await wx.cloud.uploadFile({
cloudPath,
filePath:this.data.pics[i].url,
}).then(res=> {
picsArray.push(res.fileID)
this.setData({
otherInfoFileIDs:picsArray
})
}).catch(error => {
console.log(error)
})
}
},
/**
* 将入驻申请的信息(个人信息、照片的 fileID)存入到数据库
*/
storeInfoIntoCloudDB: function() {
// 将图片在云存储中的相关信息与服务提供者的其他信息一同添加到数据库集合中 (serverProviderInfo)
const db = wx.cloud.database();
const _ = db.command;
db.collection("serverProviderInfo").add({
data: {
trueName:this.data.trueName,
idCardNo:this.data.idCardNumber,
phoneNumber:this.data.phoneNumber,
folders:[
{folderName:"个人入驻界面/身份证",
files:
{
idCardFrontFileID:this.data.idcardFrontFileID,
idCardBackFileID:this.data.idcardBackFileID
}
},
{folderName:"个人入驻界面/其它信息",
files:this.data.otherInfoFileIDs
},
],
selfIntroduction:this.data.selfIntroduction,
serverFields:
{
householdElectrical:this.data.householdElectrical,
houseClean:this.data.houseClean,
houseRepair:this.data.houseRepair,
furnitureRepair:this.data.furnitureRepair,
rushPipe:this.data.rushPipe,
others:this.data.others
},
status:this.data.status
}
}).then(res => {
console.log(res)
}).catch(error => {
})
},
/**
* 打印相关信息
*/
printBindingInfos: function() {
console.log(this.data.pics);
console.log("真实姓名:" + this.data.trueName +"\n"
+ "手机号码:" + this.data.phoneNumber +"\n" +
"身份证号码:" + this.data.idCardNumber + "\n" +
"身份证正面路径:" + this.data.idcardUrlFront + "\n" +
"身份证背面路径:" + this.data.idcardUrlFront + "\n" +
"自我介绍:" + this.data.selfIntroduction + "\n" +
"选择的服务行业:" + "\n" +
(this.data.householdElectrical?"家电维装\n":"") +
(this.data.houseClean?"保洁清洗\n":"") +
(this.data.houseRepair?"房屋修装\n":"") +
(this.data.furnitureRepair?"家具维装\n":"") +
(this.data.rushPipe?"管道疏通\n":"") +
(this.data.others?"其他\n":"") +
"上传的多张图片路径:"
);
}
})<file_sep>// 云函数模板
// 部署:在 cloud-functions/login 文件夹右击选择 “上传并部署”
const cloud = require('wx-server-sdk')
// 初始化 cloud
cloud.init({
// API 调用都保持和云函数当前所在环境一致
env: cloud.DYNAMIC_CURRENT_ENV
})
/**
* 这个示例将经自动鉴权过的小程序用户 openid 返回给小程序端
*
* event 参数包含小程序端调用传入的 data
*
*/
exports.main = async (event, context) => {
console.log("服务端打印的 event ",event)
console.log("服务端打印的 context ",context)
// 可执行其他自定义逻辑
// console.log 的内容可以在云开发云函数调用日志查看
// 获取 WX Context (微信调用上下文),包括 OPENID、APPID、及 UNIONID(需满足 UNIONID 获取条件)等信息
const wxContext = cloud.getWXContext()
console.log("getWXContext 返回的结果" + wxContext)
let lesson = "云开发技术训练营";
let enname = "CloudBase Camp";
let x = 3, y = 4, z = 5.001, a = -3, b = -4, c = -5;
let now = new Date();
return {
movie: { name: "霸王别姬", img: "https://img3.doubanio.com/view/photo/s_ratio_poster/public/p1910813120.webp", desc: "风华绝代。" },
movielist:["肖申克的救赎", "霸王别姬", "这个杀手不太冷", "阿甘正传", "美丽人生"],
charat: lesson.charAt(4),
concat: enname.concat(lesson),
uppercase: enname.toUpperCase(),
abs: Math.abs(b),
pow: Math.pow(x, y),
sign: Math.sign(a),
now: now.toString(),
fullyear: now.getFullYear(),
date: now.getDate(),
day: now.getDay(),
hours: now.getHours(),
minutes: now.getMinutes(),
seconds: now.getSeconds(),
time: now.getTime(),
event,
openid: wxContext.OPENID,
appid: wxContext.APPID,
unionid: wxContext.UNIONID,
}
// return {
// event,
// openid: wxContext.OPENID,
// appid: wxContext.APPID,
// unionid: wxContext.UNIONID,
// env: wxContext.ENV,
// }
}
|
aaeb615d6240b6511211d25ce26cfc2ab3bbf879
|
[
"JavaScript"
] | 5
|
JavaScript
|
HQ-Dev/CleanRoom
|
83e45551aad5c708f0d2339d69222fddbfd5e007
|
1f047fad714c745210ab4015f31eac7a12e8a912
|
refs/heads/master
|
<repo_name>HIG-Student/Programvaruteknik_Servlet<file_sep>/Programvaruteknik_Servlet/src/se/hig/programvaruteknik/servlet/StatisticsServlet.java
package se.hig.programvaruteknik.servlet;
import java.io.IOException;
import java.util.Map;
import java.util.TreeMap;
import java.util.function.BiFunction;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.owlike.genson.Genson;
import se.hig.programvaruteknik.data.ConstantSourceBuilder;
import se.hig.programvaruteknik.data.DataCollectionToJSONConverter;
import se.hig.programvaruteknik.data.SMHILocation;
import se.hig.programvaruteknik.data.SMHISourceBuilder;
import se.hig.programvaruteknik.data.SMHISourceBuilder.DataType;
import se.hig.programvaruteknik.data.SMHISourceBuilder.Period;
import se.hig.programvaruteknik.data.StockSourceBuilder;
import se.hig.programvaruteknik.data.StockSourceBuilder.StockInfo;
import se.hig.programvaruteknik.data.StockSourceBuilder.StockName;
import se.hig.programvaruteknik.model.DataCollection;
import se.hig.programvaruteknik.model.DataCollectionBuilder;
import se.hig.programvaruteknik.model.DataSourceBuilder;
import se.hig.programvaruteknik.model.Resolution;
/**
* Servlet implementation class SampleServlet
*
* @author <NAME> (<EMAIL>)
*/
@WebServlet("/SampleServlet")
public class StatisticsServlet extends HttpServlet
{
private static final long serialVersionUID = 1L;
private BiFunction<Boolean, DataCollection, String> JSONFormatter;
/**
* Server entry-point
*/
public StatisticsServlet()
{
this((pretty, source) ->
{
return new DataCollectionToJSONConverter(source, pretty).getString();
});
}
/**
* Use custom JSONFormatter
*/
public StatisticsServlet(BiFunction<Boolean, DataCollection, String> JSONFormatter)
{
this.JSONFormatter = JSONFormatter;
}
@SuppressWarnings("serial")
@Override
protected void doOptions(HttpServletRequest arg0, HttpServletResponse arg1) throws ServletException, IOException
{
Map<String, Object> info = new TreeMap<>();
info.put("StockInformation", new TreeMap<String, Object>()
{
{
put("types", new TreeMap<String, Object>()
{
{
put("type", "fixed");
put("values", new TreeMap<String, Object>()
{
{
for (StockInfo info : StockInfo.values())
{
put(info.name(), new TreeMap<String, String>()
{
{
put("name", info.getName());
put("description", info.getDescription());
}
});
}
}
});
}
});
put("names", new TreeMap<String, Object>()
{
{
put("type", "custom");
put("values", new TreeMap<String, Object>()
{
{
for (StockName name : StockName.values())
{
put(name.name(), new TreeMap<String, String>()
{
{
put("name", name.getDescription());
}
});
}
}
});
}
});
}
});
info.put("WeatherData", new TreeMap<String, Object>()
{
{
put("types", new TreeMap<String, Object>()
{
{
put("type", "fixed");
put("values", new TreeMap<String, Object>()
{
{
for (DataType dataType : DataType.values())
{
put(dataType.name(), new TreeMap<String, String>()
{
{
put("name", dataType.name());
}
});
}
}
});
}
});
put("places", new TreeMap<String, Object>()
{
{
put("type", "fixed");
put("values", new TreeMap<String, Object>()
{
{
for (SMHILocation location : SMHILocation.values())
{
put(location.name(), new TreeMap<String, String>()
{
{
put("name", location.name());
}
});
}
}
});
}
});
}
});
arg1.setCharacterEncoding("UTF-8");
arg1.getWriter().append(new Genson().serialize(info));
}
@SuppressWarnings(
{
"unchecked",
"rawtypes"
})
private <E extends Enum> E getEnum(Class<E> enumType, String name, String onError)
{
try
{
return (E) Enum.valueOf(enumType, name);
}
catch (Exception e)
{
throw new RequestException(onError);
}
}
private String getPart(String[] all, Integer index, String onError)
{
if (index >= all.length) throw new RequestException(onError);
return all[index];
}
private DataSourceBuilder getDataSource(String parameters, String name)
{
if (parameters == null) throw new RequestException("The parameter '" + name + "' are required!");
String[] args = parameters.split(",");
DataSourceBuilder builder = null;
String type = getPart(args, 0, "Source type for '" + name + "' is required!");
if (type.equalsIgnoreCase("Constant"))
{
builder = new ConstantSourceBuilder();
}
if (type.equalsIgnoreCase("Stock"))
{
builder = new StockSourceBuilder();
((StockSourceBuilder) builder).setStockInfo(
args.length > 3 ? getEnum(
StockInfo.class,
args[2],
"Invalid stock info for '" + name + "'") : StockInfo.PRICE);
String stock_name = getPart(args, 1, "Stock-name for '" + name + "' is required!");
if (!StockSourceBuilder
.checkValidName(stock_name)) throw new RequestException("Invalid stock name for '" + name + "'");
((StockSourceBuilder) builder).setStock(stock_name, Integer.MAX_VALUE);
}
if (type.equalsIgnoreCase("Weather"))
{
builder = new SMHISourceBuilder(
DataType.TEMPERATURE,
getEnum(
SMHILocation.class,
getPart(args, 1, "Location required for '" + name + "'"),
"Invalid location for '" + name + "'"));
((SMHISourceBuilder) builder).setPeriod(Period.OLD);
}
if (builder == null) throw new RequestException("Unknown source type for '" + name + "'");
return builder;
}
private boolean getPretty(HttpServletRequest request)
{
return "true".equalsIgnoreCase(request.getParameter("pretty"));
}
private Resolution getResolution(HttpServletRequest request)
{
String resolution = request.getParameter("resolution");
if (resolution == null) return Resolution.DAY;
try
{
return Resolution.valueOf(resolution.toUpperCase());
}
catch (Exception e)
{
throw new RequestException("Invalid resolution!");
}
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
response.setCharacterEncoding("UTF-8");
try
{
boolean pretty = getPretty(request);
Resolution resolution = getResolution(request);
DataSourceBuilder sourceA = getDataSource(request.getParameter("sourceA"), "sourceA");
DataSourceBuilder sourceB = getDataSource(request.getParameter("sourceB"), "sourceB");
DataCollectionBuilder builder = new DataCollectionBuilder(sourceA.build(), sourceB.build(), resolution);
DataCollectionToJSONConverter converter = new DataCollectionToJSONConverter(builder.getResult(), pretty);
response.setContentType("application/json;charset=UTF-8");
response.getWriter().append(converter.getString());
}
catch (RequestException e)
{
response.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
}
catch (Throwable e)
{
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Unexpected error!");
e.printStackTrace();
}
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
doGet(request, response);
}
private class RequestException extends RuntimeException
{
private RequestException(String e)
{
super(e);
}
}
}
<file_sep>/Programvaruteknik_Servlet/src/se/hig/programvaruteknik/data/DataCollectionToJSONConverter.java
package se.hig.programvaruteknik.data;
import java.util.LinkedList;
import java.util.function.Consumer;
import java.util.Map.Entry;
import se.hig.programvaruteknik.model.DataCollection;
import se.hig.programvaruteknik.model.MatchedDataPair;
/**
* Gets the statistics about weather and goals as a JSON
*
* @author <NAME> (<EMAIL>)
*/
public class DataCollectionToJSONConverter
{
private boolean pretty = false;
private LinkedList<Consumer<StringBuilder>> lines = new LinkedList<>();
private String result;
private void appendLine(@SuppressWarnings("unchecked") Consumer<StringBuilder>... actions)
{
if (actions == null) return;
for (Consumer<StringBuilder> action : actions)
{
lines.add(action);
}
if (pretty) lines.add(N);
}
private Consumer<StringBuilder> T = (b) ->
{
if (pretty) b.append("\t");
};
private Consumer<StringBuilder> N = (b) ->
{
if (pretty) b.append("\n");
};
private Consumer<StringBuilder> V(Object obj)
{
return (b) -> b.append(obj);
}
private Consumer<StringBuilder> Q(String str)
{
return (b) ->
{
if (str == null)
b.append("null");
else
{
b.append("\"");
b.append(str);
b.append("\"");
}
};
}
private void removeLast()
{
lines.removeLast();
}
/**
* Supplies JSON from a map
*
* @param source
* The data collection to transform into JSON
* @param pretty
* If it should have a pretty format
*/
public DataCollectionToJSONConverter(DataCollection source, boolean pretty)
{
this.pretty = pretty;
generateJSON(source);
}
@SuppressWarnings("unchecked")
private void generateJSON(DataCollection source)
{
appendLine(V("{"));
appendLine(T, Q("data"), V(":"));
appendLine(T, V("{"));
appendLine(T, T, Q("name"), V(":"), Q(source.getTitle()), V(","));
appendLine(T, T, Q("a_name"), V(":"), Q(source.getXUnit()), V(","));
appendLine(T, T, Q("a_source_name"), V(":"), Q(source.getXSourceName()), V(","));
appendLine(T, T, Q("a_source_link"), V(":"), Q(source.getXSourceLink()), V(","));
appendLine(T, T, Q("b_name"), V(":"), Q(source.getYUnit()), V(","));
appendLine(T, T, Q("b_source_name"), V(":"), Q(source.getYSourceName()), V(","));
appendLine(T, T, Q("b_source_link"), V(":"), Q(source.getYSourceLink()), V(","));
appendLine(T, T, Q("data"), V(":"));
appendLine(T, T, V("{"));
MatchedDataPair pair = null;
for (Entry<String, MatchedDataPair> entry : source.getData().entrySet())
{
pair = entry.getValue();
appendLine(T, T, T, Q(entry.getKey()), V(":"));
appendLine(T, T, T, V("{"));
appendLine(T, T, T, T, Q("a"), V(":"), V(pair.getXValue()), V(","));
appendLine(T, T, T, T, Q("b"), V(":"), V(pair.getYValue()));
appendLine(T, T, T, V("}"), V(","));
}
if (pair != null)
{
if (pretty) removeLast();
removeLast();
appendLine(V(""));
}
appendLine(T, T, V("}"));
appendLine(T, V("}"));
appendLine(V("}"));
StringBuilder builder = new StringBuilder();
for (Consumer<StringBuilder> line : lines)
{
line.accept(builder);
}
result = builder.toString();
}
/**
* Returns the JSON
*
* @return The JSON
*/
public String getString()
{
return result;
}
}
|
7ab39f3df5615a166e7a4ae30dd89c02d00ad17b
|
[
"Java"
] | 2
|
Java
|
HIG-Student/Programvaruteknik_Servlet
|
c303345052f822ac44dce4b4618cc2b84c960eb3
|
875fbf03e887a17307c01f21b72b5d2a5896208a
|
refs/heads/master
|
<file_sep>/*
* https://github.com/nikolapesic2802/Programming-Practice/blob/master/Schools/main.cpp
*/
#define fast ios_base::sync_with_stdio(0),cin.tie(0),cout.tie(0)
#include <bits/stdc++.h>
using namespace std;
#define sqr 547
#define mid (l+r)/2
#define pb push_back
#define ppb pop_back
#define fi first
#define se second
#define lb lower_bound
#define ub upper_bound
#define ins insert
#define era erase
#define C continue
#define mem(dp,i) memset(dp,i,sizeof(dp))
#define mset multiset
#define all(x) x.begin(), x.end()
typedef long long ll;
typedef short int si;
typedef long double ld;
typedef pair<int,int> pi;
typedef pair<ll,ll> pll;
typedef vector<int> vi;
typedef vector<ll> vll;
typedef vector<pi> vpi;
typedef vector<pll> vpll;
const ll inf=1e18;
const ll mod=1e9+7;
const ld pai=acos(-1);
ll n , m , s , ans ;
pll a[300009] ;
mset< pair < ll , pll > , greater < pair < ll , pll > > > t , ntm , nts ;
int main () {
cin >> n >> m >> s ;
for ( int i = 0 ; i < n ; i ++ ) {
cin >> a[i].fi >> a[i].se ;
}
sort ( a , a + n ) ;
reverse ( a , a + n ) ;
for ( ll i = 0 ; i < m ; i ++ ) {
ans += a[i].fi ;
t.ins ( { a[i].se - a[i].fi , { a[i].fi , a[i].se } } ) ;
}
for ( ll i = m ; i < n ; i ++ ) {
ntm .ins ( { a[i].fi , { a[i].fi , a[i].se } } ) ;
nts .ins ( { a[i].se , { a[i].fi , a[i].se } } ) ;
}
for ( ll i = 0 ; i < s ; i ++ ) {
ll val1 = nts.begin()->fi ;
ll val2 = t.begin()->se.se - t.begin()->se.fi + ntm.begin()->fi;
if ( val1 >= val2 ) {
ans += val1 ;
ll a = nts.begin()->se.fi , b = nts.begin()->se.se ;
nts .era ( nts .find ( { b , { a , b } } ) ) ;
ntm .era ( ntm .find ( { a , { a , b } } ) ) ;
}
else {
ans += val2 ;
ll A = t.begin()->se.fi , B = t.begin()->se.se ;
t .era ( t.begin() ) ;
ll a = ntm.begin()->se.fi , b = ntm.begin()->se.se ;
nts .era ( nts .find ( { b , { a , b } } ) ) ;
ntm .era ( ntm .find ( { a , { a , b } } ) ) ;
t .ins ( { b - a , { a , b } } ) ;
}
}
cout << ans << endl ;
}
|
af39be08551d6b7e084a9d1a054d0d928d82b5a8
|
[
"C++"
] | 1
|
C++
|
besherislambouley/school
|
27df5f1c9138009f76bb74799cecadc910749b0a
|
113bec18e2ad8158e80397f4c813a03cc2186fc8
|
refs/heads/master
|
<repo_name>0x1100010010/rails-capstone<file_sep>/app/helpers/transactions_helper.rb
module TransactionsHelper
def groups(transaction)
grr = []
transaction.group_ids&.each { |id| grr << current_user.groups.find(id) }
grr
end
def group_icon(transaction)
unless groups(transaction).empty?
html_out = ''
html_out << image_tag(groups(transaction).first.icon, class: 'mw-100').html_safe
end
render inline: html_out
end
def groups_list(transaction)
if groups(transaction)
html_out = ''
groups(transaction).each do |group|
html_out << (link_to group.name, group, class: 'badge bg-info m-1').html_safe
end
end
render inline: html_out
end
end
<file_sep>/app/views/transaction_groups/_transaction_group.json.jbuilder
json.extract! transaction_group, :id, :group_id, :transaction_id, :created_at, :updated_at
json.url transaction_group_url(transaction_group, format: :json)
<file_sep>/app/views/transaction_groups/show.json.jbuilder
json.partial! 'transaction_groups/transaction_group', transaction_group: @transaction_group
<file_sep>/test/controllers/transaction_groups_controller_test.rb
require 'test_helper'
class TransactionGroupsControllerTest < ActionDispatch::IntegrationTest
setup do
@transaction_group = transaction_groups(:one)
end
test 'should get index' do
get transaction_groups_url
assert_response :success
end
test 'should get new' do
get new_transaction_group_url
assert_response :success
end
test 'should create transaction_group' do
assert_difference('TransactionGroup.count') do
post transaction_groups_url,
params: { transaction_group: { group_id: @transaction_group.group_id,
transaction_id: @transaction_group.transaction_id } }
end
assert_redirected_to transaction_group_url(TransactionGroup.last)
end
test 'should show transaction_group' do
get transaction_group_url(@transaction_group)
assert_response :success
end
test 'should get edit' do
get edit_transaction_group_url(@transaction_group)
assert_response :success
end
test 'should update transaction_group' do
patch transaction_group_url(@transaction_group),
params: { transaction_group: { group_id: @transaction_group.group_id,
transaction_id: @transaction_group.transaction_id } }
assert_redirected_to transaction_group_url(@transaction_group)
end
test 'should destroy transaction_group' do
assert_difference('TransactionGroup.count', -1) do
delete transaction_group_url(@transaction_group)
end
assert_redirected_to transaction_groups_url
end
end
<file_sep>/app/models/user.rb
class User < ApplicationRecord
validates :name, length: { maximum: 30 }
validates :username, presence: true, uniqueness: true, length: { maximum: 20 }
has_many :transactions, dependent: :destroy
has_many :groups, dependent: :destroy
def external_transactions
transactions.order(created_at: :desc).select { |t| t.transaction_group_ids.empty? }
end
def external_transactions_total
external_transactions.map { |t| t.amount.to_i }.sum
end
def total_amount
sum = 0
transactions.each { |t| sum += t.amount.to_i }
sum
end
end
<file_sep>/spec/models/group_spec.rb
require 'rails_helper'
RSpec.describe Group, type: :model do
it 'creates group can be created by user' do
@user = User.create(name: 'John', username: 'johnny')
@group = @user.groups.new(name: 'McDonalds', description: 'McDonalds transactions', icon: 'https://upload.wikimedia.org/wikipedia/commons/5/50/McDonald%27s_SVG_logo.svg')
expect(@group.valid?).to be true
end
it 'creates group can be created without name user' do
@group = Group.new(name: 'McDonalds', description: 'McDonalds transactions', icon: 'https://upload.wikimedia.org/wikipedia/commons/5/50/McDonald%27s_SVG_logo.svg')
expect(@group.valid?).to be false
end
it 'checks if group can be created without name' do
@group = Group.new(description: 'McDonalds transactions', icon: 'https://upload.wikimedia.org/wikipedia/commons/5/50/McDonald%27s_SVG_logo.svg')
expect(@group.valid?).to be false
end
it 'checks if group can be created without description' do
@group = Group.new(name: 'McDonalds', icon: 'https://upload.wikimedia.org/wikipedia/commons/5/50/McDonald%27s_SVG_logo.svg')
expect(@group.valid?).to be false
end
end
<file_sep>/app/controllers/transaction_groups_controller.rb
class TransactionGroupsController < ApplicationController
before_action :set_transaction_group, only: %i[show edit update destroy]
# GET /transaction_groups or /transaction_groups.json
def index
@transaction_groups = TransactionGroup.all
end
# GET /transaction_groups/1 or /transaction_groups/1.json
def show; end
# GET /transaction_groups/new
def new
@transaction_group = TransactionGroup.new
end
# GET /transaction_groups/1/edit
def edit; end
# POST /transaction_groups or /transaction_groups.json
def create
@transaction_group = TransactionGroup.new(transaction_group_params)
respond_to do |format|
if @transaction_group.save
format.html { redirect_to request.referrer, notice: 'Transaction group was successfully created.' }
format.json { render :show, status: :created, location: @transaction_group }
else
format.html { render :new, status: :unprocessable_entity }
format.json { render json: @transaction_group.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /transaction_groups/1 or /transaction_groups/1.json
def update
respond_to do |format|
if @transaction_group.update(transaction_group_params)
format.html { redirect_to @transaction_group, notice: 'Transaction group was successfully updated.' }
format.json { render :show, status: :ok, location: @transaction_group }
else
format.html { render :edit, status: :unprocessable_entity }
format.json { render json: @transaction_group.errors, status: :unprocessable_entity }
end
end
end
# DELETE /transaction_groups/1 or /transaction_groups/1.json
def destroy
@transaction_group.destroy
respond_to do |format|
format.html { redirect_to request.referrer, notice: 'Transaction group was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_transaction_group
@transaction_group = TransactionGroup.find(params[:id])
end
# Only allow a list of trusted parameters through.
def transaction_group_params
params.permit(:group_id, :transaction_id)
end
end
<file_sep>/app/models/transaction.rb
class Transaction < ApplicationRecord
belongs_to :author, class_name: 'User', foreign_key: 'user_id'
has_many :transaction_groups, dependent: :destroy
validates :name, length: { maximum: 30 }
validates :amount, presence: true, numericality: true
def group_ids
transaction_groups.map(&:group_id)
end
def group_id
transaction_groups.first.group_id unless transaction_group_ids.empty?
end
end
<file_sep>/app/validators/remote_image_validator.rb
class RemoteImageValidator < ActiveModel::Validator
def validate(record)
url = URI.parse(record.icon)
Net::HTTP.start(url.host, url.port) do |http|
unless http.head(url.request_uri)['Content-Type'].start_with? 'image'
return record.errors.add :base, 'This person is evil'
end
end
end
end
<file_sep>/app/helpers/application_helper.rb
module ApplicationHelper
def current_user
if session[:user_id]
begin
@current_user ||= User.find(session[:user_id])
rescue ActiveRecord::RecordNotFound
# rescue Exception
# # handle everything else
# raise
end
else
@current_user = nil
end
end
def require_session
redirect_to welcome_path, alert: 'Sign Up or Sign In to access this feature!' unless current_user
end
def render_submit(form)
if request.fullpath.include?('edit')
form.submit 'Update', class: 'btn btn-primary py-3 text-light mb-2 shadow-0'
else
form.submit 'Create', class: 'btn btn-primary py-3 text-light mb-2 shadow-0'
end
end
def render_header
html_out = ''
if current_user
html_out << "<li class='nav-item'><%= link_to 'Groups', groups_path, class: 'nav-link px-3' %></li>"
html_out << "<li class='nav-item'><%= link_to 'Transactions', transactions_path, class: 'nav-link px-3' %></li>"
html_out << "<li class='nav-item'>"
html_out << "<%= link_to 'Extenal Transactions', external_transactions_path, class: 'nav-link px-3' %></li>"
html_out << "<li class='nav-item'><%= link_to current_user.name, current_user, class: 'nav-link px-3' %></li>"
html_out << "<li class='nav-item'><%= link_to 'Sign Out', signout_path, class: 'nav-link px-3' %></li>"
else
html_out << "<li class='nav-item'>
<%= link_to 'Sign In', signin_path, class: 'nav-link px-3'if current_page?(signup_path) %>
<%= link_to 'Sign Up', signup_path, class: 'nav-link px-3' if current_page?(signin_path) %>
</li>"
end
render inline: html_out
end
end
<file_sep>/db/seeds.rb
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the bin/rails db:seed command (or created alongside the database with db:setup).
#
# Examples:
#
# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }])
# Character.create(name: 'Luke', movie: movies.first)
users = User.create!([{ name: 'x', username: 'x' }, { name: 'y', username: 'y' }, { name: 'z', username: 'z' } ])
users.each do |user|
user.transactions.create!([{ name: 'transaction_by_'+user.name+'_i', amount: 100 }, { name: 'transaction_by_'+user.name+'_ii', amount: 200 }, { name: 'transaction_by_'+user.name+'_iii', amount: 300 }])
user.groups.create!([{ name: 'group_by_'+user.name+'_i', description: 'Group description', icon: 'https://www.braintreepayments.com/images/products/schematic/icon-fraud-check.svg' }, { name: 'group_by_'+user.name+'_ii', description: 'Group description', icon: 'https://www.braintreepayments.com/images/products/schematic/icon-fraud-check.svg' }, { name: 'group_by_'+user.name+'_iii', description: 'Group description', icon: 'https://www.braintreepayments.com/images/products/schematic/icon-fraud-check.svg' }])
end
<file_sep>/config/routes.rb
Rails.application.routes.draw do
get 'welcome', to: 'welcome#index'
resources :transaction_groups
resources :groups
# For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
resources :sessions, only: [:new, :create, :destroy]
scope :sessions do
get 'signup', to: 'users#new'
get 'signin', to: 'sessions#new'
get 'signout', to: 'sessions#destroy'
end
resources :users
resources :transactions
get 'external_transactions', to: 'transactions#index_external_transactions'
root to: 'users#home'
end
<file_sep>/spec/models/transaction_spec.rb
require 'rails_helper'
RSpec.describe Transaction, type: :model do
it 'creates transaction can be created by user' do
@user = User.create(name: 'John', username: 'johnny')
@transaction = @user.transactions.new(name: 'McDonalds', amount: 15)
expect(@transaction.valid?).to be true
end
it 'creates transaction can be created without name user' do
@transaction = Transaction.create(name: 'McDonalds transaction', amount: 15)
expect(@transaction.valid?).to be false
end
it 'checks if transaction can be created without name' do
@transaction = Transaction.create(amount: 15)
expect(@transaction.valid?).to be false
end
it 'checks if transaction can be created without amount' do
@transaction = Transaction.create(name: 'McDonalds transaction')
expect(@transaction.valid?).to be false
end
it 'checks if transaction can be created with wrong value' do
@transaction = Transaction.create(name: 'McDonalds transaction', amount: '15')
expect(@transaction.valid?).to be false
end
end
<file_sep>/app/models/group.rb
class Group < ApplicationRecord
include ActiveModel::Validations
belongs_to :owner, class_name: 'User', foreign_key: 'user_id'
has_many :transaction_groups, dependent: :destroy
validates :name, length: { maximum: 30 }
validates :description, presence: true, length: { maximum: 300 }
validates :icon, presence: true
def transaction_ids
transaction_groups.map(&:transaction_id)
end
def transaction_sum
transaction_ids.map { |id| Transaction.find(id).amount.to_i }.sum
end
end
<file_sep>/test/system/transaction_groups_test.rb
require 'application_system_test_case'
class TransactionGroupsTest < ApplicationSystemTestCase
setup do
@transaction_group = transaction_groups(:one)
end
test 'visiting the index' do
visit transaction_groups_url
assert_selector 'h1', text: 'Transaction Groups'
end
test 'creating a Transaction group' do
visit transaction_groups_url
click_on 'New Transaction Group'
fill_in 'Group', with: @transaction_group.group_id
fill_in 'Transaction', with: @transaction_group.transaction_id
click_on 'Create Transaction group'
assert_text 'Transaction group was successfully created'
click_on 'Back'
end
test 'updating a Transaction group' do
visit transaction_groups_url
click_on 'Edit', match: :first
fill_in 'Group', with: @transaction_group.group_id
fill_in 'Transaction', with: @transaction_group.transaction_id
click_on 'Update Transaction group'
assert_text 'Transaction group was successfully updated'
click_on 'Back'
end
test 'destroying a Transaction group' do
visit transaction_groups_url
page.accept_confirm do
click_on 'Destroy', match: :first
end
assert_text 'Transaction group was successfully destroyed'
end
end
<file_sep>/app/models/transaction_group.rb
class TransactionGroup < ApplicationRecord
belongs_to :group
belongs_to :user_transaction, class_name: 'Transaction', foreign_key: 'transaction_id'
end
<file_sep>/spec/models/user_spec.rb
require 'rails_helper'
RSpec.describe User, type: :model do
it 'creates user correctly' do
@user = User.new(name: 'John', username: 'johnny')
expect(@user.valid?).to be true
end
it 'checks if user can be created without name' do
@user = User.new
expect(@user.valid?).to be false
end
it 'checks if user with same username can be created' do
User.create(name: 'John', username: 'johnny')
@user = User.new(name: 'John')
expect(@user.valid?).to be false
end
end
<file_sep>/app/helpers/users_helper.rb
module UsersHelper
# Use callbacks to share common setup or constraints between actions.
def set_user
@user = User.find(params[:id])
end
# Only allow a list of trusted parameters through.
def user_params
params.require(:user).permit(:name, :username)
end
def start_session(user)
if user
session[:user_id] = user.id
redirect_to root_url, notice: "User #{user.name} account signed up successfully!"
else
flash.now[:alert] = 'Username is invalid'
end
end
end
<file_sep>/README.md
# Le-Transactions
> Le-Transactions is a web application (Mobile screen only) that let you keep recode of your transactions and group them to organize.
>
> This project is the Capstone Project for the  Rails Technical Curriculum.
>
> The project design is inspired by [Snapscan](https://www.behance.net/gallery/19759151/Snapscan-iOs-design-and-branding) concept designed by [<NAME>](https://www.behance.net/gregoirevella)
## Screenshot

## Built With
- HTML
- ERB
- SCSS
- Ruby
- JavaScript
- CSS
- Bootstrap
- SQL
## Live Demo
[Live Demo Link](https://rails-capstone-bashforger.herokuapp.com/)
### Prerequisites
Text Editor (VSCode is suggested.)
Ruby
Rails
Bundler
Yarn
SQL
## Getting Started
To get a local copy up and running follow these simple example steps:
- Open your terminal
- Clone this project `git clone https://github.com/bashforger/rails-capstone`
- Go to the project folder `cd rails-capstone`
### Install
- Run `bundle install`
- Migrate the database `rails db:migrate`
## Author
👤 **<NAME>**
- GitHub: [@bashforger](https://github.com/bashforger)
- Twitter: [@bashforge](https://twitter.com/bashforge)
- LinkedIn: [<NAME>](https://www.linkedin.com/in/muhammad-adeel-danish/)
## 🤝 Contributing
Contributions, issues and feature requests are welcome! Start by:
- Forking the project
- Cloning the project to your local machine
- `cd` into the project directory
- Run `git checkout -b your-branch-name`
- Make your contributions
- Push your branch up to your forked repository
- Open a Pull Request with a detailed description to the development branch of the original project for a review
## Show your support
Give a ⭐️ if you like this project!
<file_sep>/app/controllers/sessions_controller.rb
class SessionsController < ApplicationController
def new
redirect_to root_path if current_user
end
def create
@user = User.find_by_username(params[:username])
if @user
session[:user_id] = @user.id
redirect_to root_path, notice: 'Signed in successfully!'
else
flash.now[:alert] = 'Username is invalid'
render 'new'
end
end
def destroy
reset_session
redirect_to root_url, notice: 'Signed out successfully!'
end
end
<file_sep>/app/helpers/groups_helper.rb
module GroupsHelper
def transaction_exists?(transaction)
@group.transaction_groups.find_by(transaction_id: transaction.id)
end
def render_controls(event)
return unless current_user && event.creator.id == current_user.id
@html_out = ''
@html_out << "<%= link_to event do %>
<i class=\"fas fa-link\"></i>
<% end %>
<%= link_to edit_event_path(event) do %>
<i class=\"far fa-edit\"></i>
<% end %>
<%= link_to event, method: :delete, data: { confirm: 'Are you sure?' } do %>
<i class=\"fas fa-trash\"></i>
<% end %>"
render inline: @html_out, locals: { event: event }
end
end
|
52cc82d6905c448c8e4cba62647988c93e1bfdad
|
[
"Markdown",
"Ruby"
] | 21
|
Ruby
|
0x1100010010/rails-capstone
|
4d71007062ffc83320087a454c200af3d63ba861
|
c69b4d09d47d3b729eea6399f1b7066a3b177260
|
refs/heads/master
|
<file_sep>using System;
namespace StudentOrganizer.Entities
{
//Entity for interaction with database
public class Student
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
public string Status { get; set; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using StudentOrganizer.Dao;
using StudentOrganizer.Models;
using StudentOrganizer.Services;
using StudentOrganizer.Services.Interfaces;
namespace StudentOrganizer.Controllers
{
public class StudentController : Controller
{
//IStudentService _studentService;
private IValidatorService _validatorService = new ValidatorService();
//UniversityDatabase _db = new UniversityDatabase();
public IActionResult StudentView()
{
//Add stuff to the model
//Turn into students
//List<StudentModel> students = _studentService.ConvertToStudentList(Dt);
List<StudentModel> students = DummyData.DummyStudents.getDummyStudentList();
//Validate
List<string> errors = _validatorService.validateStudents(students);
var model = new StudentListModel
{
Students = students,
Errors = errors
};
return View(model);
}
//protected override void Dispose(bool disposing)
//{
// if(_db != null)
// {
// _db.Dispose();
// }
// base.Dispose(disposing);
//}
}
}
<file_sep>using System;
using System.Collections.Generic;
namespace StudentOrganizer.Models
{
public class StudentListModel
{
public List<StudentModel> Students { get; set; }
public List<string> Errors { get; set; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.IO;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using OfficeOpenXml;
using StudentOrganizer.Models;
using StudentOrganizer.Services;
using StudentOrganizer.Services.Interfaces;
namespace StudentOrganizer.Controllers
{
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
[ActionName("UploadStudents")]
[HttpGet]
public IActionResult UploadStudents(string path = "~/Content/SampleData.xlsx")
{
// Turn into datatable
// FIXME: I am using a mac and there's most people use EPPlus to convert an XLSX file to a DataTable:
// a) ToDataTable method
// b) package.Workbooks.Workbooks.First
// c) package.Workbooks.Workbook[0]
// d) package.Workbooks.Workbook[1]
// e) package.Workbooks.Workbook["Sheet1"]
// I tried all these solutions and several others. I left the converter I wrote so you could see what I planned on doing.
// FileInfo fi = new FileInfo(path);
// ExcelPackage package = new ExcelPackage(fi);
// DataTable Dt = ToDataTable(package);
return RedirectToAction("StudentView", "Student");
}
public IActionResult Privacy()
{
return View();
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using StudentOrganizer.Models;
namespace StudentOrganizer.Services.Interfaces
{
public interface IValidatorService
{
List<string> validateStudents(List<StudentModel> students);
List<string> validateStudent(StudentModel student);
bool validateString(String incoming, int maxLength, bool required);
bool validateInt (String incoming, bool mustBePositive);
bool validateStatus(String incoming);
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Data;
using StudentOrganizer.Models;
namespace StudentOrganizer.Services.Interfaces
{
public interface IStudentService
{
List<StudentModel> ConvertToStudentList(DataTable dataTable);
}
}
<file_sep>using System;
using System.Collections.Generic;
using Xunit;
using StudentOrganizer.Services;
namespace StudentOrganizer.xTests
{
public class ValidatorServiceTest
{
private ValidatorService _validatorService;
private static readonly List<string> STRING_VALID_LIST = new List<string>(new string[] { "ASDF", "qwerwerty", "1234" });
private static readonly List<string> STRING_EMPTY_LIST = new List<string>(new string[] { "", null });
private static readonly List<string> INT_SUCCESS_LIST = new List<string>(new string[] { "1", "2", "3" });
private static readonly List<string> INT_FAIL_LIST = new List<string>(new string[] { "a", "12.324", null });
private static readonly List<string> STATUS_SUCCESS_LIST = new List<string>(new string[] { "Active", "Inactive", "Hold" } );
private static readonly List<string> STATUS_FAIL_LIST = new List<string>(new string[] { "asdf", "2" } );
[Fact]
public void validatestringOfCorrectLength()
{
_validatorService = new ValidatorService();
// strings with valid data and under max length are valid
foreach(string test in STRING_VALID_LIST)
{
Assert.True(_validatorService.validateString(test, test.Length, false));
}
}
[Fact]
public void validatestringOfIncorrectLength()
{
_validatorService = new ValidatorService();
// strings with valid data and over the max length are invalid
foreach (string test in STRING_VALID_LIST)
{
Assert.False(_validatorService.validateString(test, test.Length - 1, false));
}
}
[Fact]
public void validatestringEmptyAndNotRequired()
{
_validatorService = new ValidatorService();
// strings with null or empty values and aren't required are valid
foreach (string test in STRING_EMPTY_LIST)
{
Assert.True(_validatorService.validateString(test, 1, false));
}
}
[Fact]
public void validatestringEmptyAndRequired()
{
_validatorService = new ValidatorService();
// strings with null or empty values and are required are invalid
foreach (string test in STRING_EMPTY_LIST)
{
Assert.False(_validatorService.validateString(test, 1, true));
}
}
[Fact]
public void validateIntSuccessTest()
{
_validatorService = new ValidatorService();
foreach (string test in INT_SUCCESS_LIST)
{
Assert.True(_validatorService.validateInt(test, true));
}
}
[Fact]
public void validateIntInvalidIntTest()
{
_validatorService = new ValidatorService();
foreach(string test in INT_FAIL_LIST)
{
Assert.False(_validatorService.validateInt(test, false));
}
}
[Fact]
public void validateIntValidButNegative1()
{
_validatorService = new ValidatorService();
//-1 is valid if not required
Assert.True(_validatorService.validateInt("-1", false));
}
[Fact]
public void validateIntValidButNegative2()
{
_validatorService = new ValidatorService();
//Negative 1 is not positive
Assert.False(_validatorService.validateInt("-1", true));
}
[Fact]
public void validateIntValidButNegative3()
{
_validatorService = new ValidatorService();
//Zero is not positive
Assert.False(_validatorService.validateInt("0", true));
}
[Fact]
public void validateStatusValid()
{
_validatorService = new ValidatorService();
foreach (string test in STATUS_SUCCESS_LIST)
{
Assert.True(_validatorService.validateStatus(test));
}
}
[Fact]
public void validateStatusInvalid()
{
_validatorService = new ValidatorService();
foreach (string test in STATUS_FAIL_LIST)
{
Assert.False(_validatorService.validateStatus(test));
}
}
}
}
<file_sep>using System;
namespace StudentOrganizer.Models
{
public class StudentModel
{
public String Id { get; set; }
public String FirstName { get; set; }
public String LastName { get; set; }
public String Age { get; set; }
public String Status { get; set; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using StudentOrganizer.Services.Interfaces;
using StudentOrganizer.Codes;
using StudentOrganizer.Models;
namespace StudentOrganizer.Services
{
public class ValidatorService : IValidatorService
{
public List<string> validateStudents(List<StudentModel> students)
{
List<string> errors = new List<string>();
foreach(StudentModel student in students)
{
errors.AddRange(validateStudent(student));
}
return errors;
}
public List<string> validateStudent(StudentModel student)
{
List<string> errors = new List<string>();
if (!this.validateInt(student.Id, false))
{
errors.Add("Invalid ID");
}
if (!this.validateString(student.FirstName, 50, true))
{
errors.Add("Invalid First Name");
}
if (!this.validateString(student.FirstName, 50, true))
{
errors.Add("Invalid Last Name");
}
if(!this.validateInt(student.Age, true))
{
errors.Add("Invalid Age");
}
if (!this.validateStatus(student.Status))
{
errors.Add("Invalid Status");
}
return errors;
}
public bool validateString(String incoming, int maxLength, bool required)
{
bool result = false;
if (String.IsNullOrEmpty(incoming))
{
result = !required;
}
else result |= incoming.Length <= maxLength;
return result;
}
public bool validateInt(String incoming, bool mustBePositive)
{
int result;
bool success = Int32.TryParse(incoming, out result);
//Success if int and if it's positive or it's not required to be positive
return success && ( (result > 0) || !mustBePositive );
}
public bool validateStatus(String incoming)
{
return Status.STATUS_OPTIONS.Contains(incoming);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Data;
using StudentOrganizer.Models;
using StudentOrganizer.Services.Interfaces;
namespace StudentOrganizer.Services
{
public class StudentService : IStudentService
{
private readonly IValidatorService _validatorService;
public List<StudentModel> ConvertToStudentList(DataTable dataTable)
{
List<StudentModel> students = new List<StudentModel>();
if(dataTable != null)
{
for(int i = 0; i < dataTable.Rows.Count; i++)
{
StudentModel student = new StudentModel
{
Id = (string)dataTable.Rows[i]["Id"],
FirstName = (string)dataTable.Rows[i]["FirstName"],
LastName = (string)dataTable.Rows[i]["LastName"],
Age = (string)dataTable.Rows[i]["Age"],
Status = (string)dataTable.Rows[i]["Status"]
};
students.Add(student);
}
}
return students;
}
}
}
<file_sep>
using System.Collections.Generic;
namespace StudentOrganizer.Codes {
static class Status
{
public static readonly string ACTIVE = "Active";
public static readonly string INACTIVE = "Inactive";
public static readonly string HOLD = "Hold";
public static readonly List<string> STATUS_OPTIONS = new List<string>(new string[] { ACTIVE, INACTIVE, HOLD });
}
}<file_sep>using System;
using System.Data.Entity;
using Microsoft.EntityFrameworkCore;
using StudentOrganizer.Entities;
namespace StudentOrganizer.Dao
{
//Stub for future database
public class UniversityDatabase : DbContext
{
public DbSet<Student> Students { get; set; }
}
}
|
e2269242c93f2368d72a9b90eec0f2a822adb753
|
[
"C#"
] | 12
|
C#
|
AusNacht/StudentOrganizer
|
5e779c1e5d3e920f6c72285ca566f14e0f1b5d60
|
52386847185d4f982f9e064a292daa32f044b59f
|
refs/heads/master
|
<file_sep>Whiteboard
----------
* install node
* npm install -d
* node server.js
Useful Links
------------
Express
> http://expressjs.com/
Socket.IO
> http://socket.io
MongoDB Node Driver
> http://mongodb.github.io/node-mongodb-native/2.0/
License
-------
MIT
<file_sep>// client side socket
var socket = io(),
id,
handle
;
socket.on('load', function({ connectionId, userCount, strokeHistory, chatHistory }) {
id = connectionId;
handle = "Client " + id;
// load global state: canvas, chat messages, & user count
for (var stroke of strokeHistory) draw(stroke);
for (var chat of chatHistory) appendMessage(chat);
updateCount(userCount);
});
socket.on('draw', function({ stroke }) {
draw(stroke);
});
socket.on('clear', function() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
});
socket.on('chat', function(message) {
appendMessage(message);
});
socket.on('count', function(userCount) {
updateCount(userCount);
});
// drawing
var canvas,
ctx,
flag = false,
prevX = 0,
prevY = 0,
currX = 0,
currY = 0,
width = 2,
color = 'black'
;
function initCanvas() {
canvas = document.getElementById('whiteboard');
ctx = canvas.getContext('2d');
ctx.lineCap = 'round';
ctx.lineJoin = 'round';
// emit client input to server
canvas.addEventListener('mousemove', function (e) {
if (flag) {
updateXY(e);
draw({ prevX, prevY, currX, currY, width, color });
emitMouse('move', e);
}
}, false);
canvas.addEventListener('mousedown', function (e) {
flag = true;
updateXY(e);
draw({ prevX, prevY, currX, currY, width, color });
emitMouse('down', e);
}, false);
canvas.addEventListener('mouseup', function (e) {
flag = false;
}, false);
canvas.addEventListener('mouseout', function (e) {
flag = false;
}, false);
}
function updateXY(e) {
if (e.type === 'mousedown') {
prevX = e.clientX - canvas.offsetLeft;
prevY = e.clientY - canvas.offsetTop;
currX = e.clientX - canvas.offsetLeft;
currY = e.clientY - canvas.offsetTop;
} else if (e.type === 'mousemove') {
prevX = currX;
prevY = currY;
currX = e.clientX - canvas.offsetLeft;
currY = e.clientY - canvas.offsetTop;
}
}
function emitMouse(type, e) {
socket.emit('draw', {
type,
color,
width,
id,
canvasX: e.clientX - canvas.offsetLeft,
canvasY: e.clientY - canvas.offsetTop,
});
}
function draw(stroke) {
ctx.beginPath();
ctx.moveTo(stroke.prevX, stroke.prevY);
ctx.lineTo(stroke.currX, stroke.currY);
ctx.lineWidth = stroke.width;
ctx.strokeStyle = stroke.color;
ctx.stroke();
ctx.closePath();
}
function chooseColor({ id }) {
color = id;
width = 2;
}
function erase() {
color = 'white';
width = 14;
}
function clearCanvas() {
if (confirm('Clear Whiteboard?')) {
socket.emit('clear');
}
}
// chat
$(function() {
$("#h").focus();
});
$('#handleform').submit(function() {
if ($('#h').val() !== '') {
handle = $('#h').val();
}
$('#handlebox').addClass('hide');
$('#chatbox').removeClass('hide');
$('#messages').scrollTop( $('#messages')[0].scrollHeight );
$(function() {
$("#m").focus();
});
return false; // cancel submit action
});
$('#chatform').submit(function() {
socket.emit('chat', {
handle,
'text': $('#m').val()
});
$('#m').val('');
return false;
});
function appendMessage({ handle, text, color, date }) {
var time = displayTime(date);
var message = `<li><p id="time">[${time}]</p> <b class="${color}">${handle}</b>: ${text}</li>`;
$('#messages').append($(message));
$('#messages').scrollTop( $('#messages')[0].scrollHeight );
}
function displayTime(dateMS) {
var time = new Date(dateMS);
var hours = time.getHours();
var minutes = time.getMinutes();
var seconds = time.getSeconds();
var meridiem;
if (minutes < 10) minutes = '0' + minutes;
if (seconds < 10) seconds = '0' + seconds;
if (hours >= 12) {
meridiem = 'pm';
if (hours > 12) hours -= 12;
} else {
meridiem = 'am';
if (hours === 0) hours = 12;
}
return hours + ':' + minutes + meridiem; // + ':' + seconds + ' ';
}
// online user counter
function updateCount(n) {
$('#count').text(n);
}<file_sep>'use strict';
var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();
var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var favicon = require('serve-favicon');
var stringHash = require('string-hash');
var async = require('async');
var db = require('./db');
app.use(favicon(__dirname + '/assets/images/favicon.ico'));
app.set('port', process.env.PORT || 3000);
app.use(express.static(__dirname + '/assets'));
app.get('/', function (req, res) {
res.sendFile(__dirname + '/index.html');
});
// connect to mongodb on start up
db.connect(function (err) {
if (err) {
console.log('Unable to connect to Mongo.');
process.exit(1); // exit with failure code
} else {
http.listen(app.get('port'), function () {
console.log('Server running on localhost:' + app.get('port'));
});
}
});
/* server side socket */
var connectionId = 1,
strokeById = {},
// necessary since canvas only has 'single cursor'
totalConnections = 0;
io.on('connection', function (socket) {
totalConnections++;
console.log('A connection has been made! ID: ' + connectionId);
socket.broadcast.emit('count', totalConnections);
// initialize client
async.parallel([db.getStrokes, db.getChats], function (err, results) {
if (err) throw err;
var _results = _slicedToArray(results, 2);
var strokes = _results[0];
var chats = _results[1];
socket.emit('load', {
'connectionId': connectionId,
'userCount': totalConnections,
'strokeHistory': strokes,
'chatHistory': chats
});
strokeById[connectionId] = {};
connectionId++;
});
// receive client emission, save canvas state, & emit to all clients
socket.on('draw', function (_ref) {
var type = _ref.type;
var color = _ref.color;
var width = _ref.width;
var id = _ref.id;
var canvasX = _ref.canvasX;
var canvasY = _ref.canvasY;
var prevStroke = strokeById[id];
if (type === 'down') {
var currStroke = {
prevX: canvasX,
prevY: canvasY,
currX: canvasX,
currY: canvasY,
width: width,
color: color
};
} else if (type === 'move') {
var currStroke = {
prevX: prevStroke.currX,
prevY: prevStroke.currY,
currX: canvasX,
currY: canvasY,
width: width,
color: color
};
}
strokeById[id] = currStroke;
db.addStroke(currStroke);
socket.broadcast.emit('draw', { 'stroke': currStroke });
});
socket.on('clear', function () {
db.clearStrokes();
io.emit('clear');
});
socket.on('chat', function (_ref2) {
var handle = _ref2.handle;
var text = _ref2.text;
var message = {
handle: handle,
text: text,
color: getColor(handle),
date: Date.now()
};
db.addChat(message);
io.emit('chat', message);
});
socket.on('disconnect', function () {
totalConnections--;
io.emit('count', totalConnections);
console.log('A user has disconnected.');
});
});
function getColor(handle) {
var colors = ['green', 'blue', 'red', 'black', 'orange'];
var randomIndex = Math.abs(stringHash(handle) % colors.length);
return colors[randomIndex];
}
<file_sep>var MongoClient = require('mongodb').MongoClient;
//var { mongoURL } = require('./config.js');
var url = `mongodb://${process.env.db_username}:${process.env.db_password}@<EMAIL>:37814/heroku_1cjc54ck`;
var state = {
db: null,
};
function connect(callback) {
if (state.db) return callback();
MongoClient.connect(url, function(err, db) {
if (err) return callback(err);
state.db = db;
callback(); // error parameter undefined
});
}
function get() {
return state.db;
}
function getStrokes(callback) {
if (!state.db) throw new Error('Not connected to DB');
var strokeColl = state.db.collection('stroke');
strokeColl.find().toArray(function(err, docs) {
callback(err, docs);
});
}
function getChats(callback) {
if (!state.db) throw new Error('Not connected to DB');
var chatColl = state.db.collection('chat');
chatColl.find().sort({date: 1}).toArray(function(err, docs) {
callback(err, docs);
});
}
function addStroke(obj) {
if (!state.db) throw new Error('Not connected to DB');
var strokeColl = state.db.collection('stroke');
// console.log('trying to insert', obj);
strokeColl.insertOne(obj, function(err) {
if (err) throw err;
});
}
function addChat(obj) {
if (!state.db) throw new Error('Not connected to DB');
var chatColl = state.db.collection('chat');
chatColl.insertOne(obj, function(err) {
if (err) throw err;
});
}
function clearStrokes() {
if (!state.db) throw new Error('Not connected to DB');
var strokeColl = state.db.collection('stroke');
strokeColl.deleteMany({});
}
function close(callback) {
if (state.db) {
state.db.close(function(err, result) {
state.db = null;
callback(err);
});
}
}
module.exports = {
connect,
get,
getStrokes,
getChats,
addStroke,
addChat,
clearStrokes,
close,
};
|
7ed5aaa2e4af6ee0067190bb161bdc3eea596412
|
[
"Markdown",
"JavaScript"
] | 4
|
Markdown
|
KiKiKi-KiKi/whiteboard
|
e5e46e09a5bbc68b252bc0198dfe1eb00aa1ec07
|
6bea17b87858a3853390fac25af94a32bb4982a6
|
refs/heads/master
|
<file_sep>function Haversine(...opts) {
this.opts = opts;
this.radii = {
km: 6371,
miles: 3960,
meters: 6371000,
nmi: 3440,
feet: 20908800,
yards: 6969600
}
this.toRad = deg => (deg * Math.PI) / 180;
this.toDeg = rad => (rad * 180) / Math.PI;
}
Haversine.prototype.distance = function(start, end, options = this.opts) {
const R = options.unit ? this.radii[options.unit] : this.radii.km;
const dLat = this.toRad(end.latitude - start.latitude);
const dLon = this.toRad(end.longitude - start.longitude);
const lat1 = this.toRad(start.latitude);
const lat2 = this.toRad(end.latitude);
const a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.sin(dLon / 2) * Math.sin(dLon / 2) *
Math.cos(lat1) * Math.cos(lat2);
const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
return R * c;
}
Haversine.prototype.targetCoordinates = function(current, target, options = this.opts) {
const R = options.unit ? this.radii[options.unit] : this.radii.km;
const { distance, heading } = target;
const { latitude, longitude } = current;
const bearing = this.toRad(heading);
const lat1 = this.toRad(latitude);
const lon1 = this.toRad(longitude);
const lat2 = Math.asin(Math.sin(lat1) * Math.cos(distance / R) +
Math.cos(lat1) * Math.sin(distance / R) * Math.cos(bearing));
const lon2 = lon1 + Math.atan2(Math.sin(bearing) * Math.sin(distance / R) *
Math.cos(lat1), Math.cos(distance / R) - Math.sin(lat1) * Math.sin(lat2));
return {
latitude: this.toDeg(lat2),
longitude: this.toDeg(lon2)
}
}
module.exports = Haversine;
<file_sep># node-haversine
|
87ef4e65651266e7392906cda916746618be5301
|
[
"JavaScript",
"Markdown"
] | 2
|
JavaScript
|
brotholopithicus/node-haversine
|
d6f5391b710c8ae9c72b0e8e58b525854edff93a
|
58229a0db288992a1455b39dae42bb207cb90265
|
refs/heads/master
|
<file_sep>Simple Flask App
================
.. image:: https://travis-ci.org/AddaKowalczyk8/se_hello_printer_app.svg?branch=master
:target: https://travis-ci.org/AddaKowalczyk8/se_hello_printer_app
.. image:: https://app.statuscake.com/button/index.php?Track=oIcafpmold&Days=1&Design=5
:target: https://www.statuscake.com
.. image:: https://api.codeclimate.com/v1/badges/75441815f43e7878a05a/maintainability
:target: https://codeclimate.com/github/AddaKowalczyk8/se_hello_printer_app/maintainability
:alt: Maintainability
.. image:: https://api.codeclimate.com/v1/badges/75441815f43e7878a05a/test_coverage
:target: https://codeclimate.com/github/AddaKowalczyk8/se_hello_printer_app/test_coverage
:alt: Test Coverage
Aplikacja Dydaktyczna wyświetlająca imię i wiadomość w różnych formatach dla zajęć
o Continuous Integration, Continuous Delivery i Continuous Deployment.
- Rozpocząnając pracę z projektem (wykorzystując virtualenv). Hermetyczne środowisko dla pojedyńczej aplikacji w python-ie:
::
source /usr/bin/virtualenvwrapper.sh
mkvirtualenv wsb-simple-flask-app
pip install -r requirements.txt
pip install -r test_requirements.txt
- Uruchamianie applikacji:
::
# jako zwykły program
python main.py
# albo:
PYTHONPATH=. FLASK_APP=hello_world flask run
- Uruchamianie testów (see: http://doc.pytest.org/en/latest/capture.html):
::
PYTHONPATH=. py.test
PYTHONPATH=. py.test --verbose -s
- Uruchamianie smoke testów:
::
make test_smoke
make test_smoke_siege_local
make test_smoke_siege_heroku
- Kontynuując pracę z projektem, aktywowanie hermetycznego środowiska dla aplikacji py:
::
source /usr/bin/virtualenvwrapper.sh
workon wsb-simple-flask-app
- Integracja z TravisCI:
::
Dodanie do repozytorium pliku konfiguracyjnego .travis.yml dla projektu python (see: https://docs.travis-ci.com/user/languages/python/)
- Instalacja pakietu do repozytorium (see: https://hub.docker.com)
- Deployment do heroku z maszyny dev, z wykorzystaniem gunicorn (see: https://devcenter.heroku.com/articles/python-gunicorn)
- Deployment do heroku z TravisCI (see: https://docs.travis-ci.com/user/deployment/heroku/)
- Monitoring z Statuscake (see: https://www.statuscake.com/)
- Badge z TravisCI:
.. image:: https://travis-ci.org/AddaKowalczyk8/se_hello_printer_app.svg?branch=master
:target: https://travis-ci.org/AddaKowalczyk8/se_hello_printer_app
- Badge z Statuscake
1 dzień:
.. image:: https://app.statuscake.com/button/index.php?Track=oIcafpmold&Days=1&Design=1
:target: https://www.statuscake.com
30 dni:
.. image:: https://app.statuscake.com/button/index.php?Track=oIcafpmold&Days=30&Design=1
:target: https://www.statuscake.com
- Code Climate:
Jakość kodu:
.. image:: https://api.codeclimate.com/v1/badges/75441815f43e7878a05a/maintainability
:target: https://codeclimate.com/github/AddaKowalczyk8/se_hello_printer_app/maintainability
:alt: Maintainability
Pokrycie kodu testami:
.. image:: https://api.codeclimate.com/v1/badges/75441815f43e7878a05a/test_coverage
:target: https://codeclimate.com/github/AddaKowalczyk8/se_hello_printer_app/test_coverage
:alt: Test Coverage
Pomocnicze
==========
- Instalacja python virtualenv i virtualenvwrapper:
::
yum install python-pip
pip install -U pip
pip install virtualenv
pip install virtualenvwrapper
- Instalacja docker-a:
::
yum remove docker \
docker-common \
container-selinux \
docker-selinux \
docker-engine
yum install -y yum-utils
yum-config-manager \
--add-repo \
https://download.docker.com/linux/centos/docker-ce.repo
yum makecache fast
yum install docker-ce
systemctl start docker
Materiały
=========
- https://virtualenvwrapper.readthedocs.io/en/latest/
<file_sep>mock
pytest
flake8
pytest-cov
requests
jmespath
coverage>=4.0,<4.4
codeclimate-test-reporter
selenium
pyvirtualdisplay
<file_sep>from selenium import webdriver
from pyvirtualdisplay import Display
import unittest
import time
import pytest
@pytest.mark.uitest
class TestFormater(unittest.TestCase):
def test_plain_lowercase(self):
# Add following 2 line before start the Chrome
display = Display(visible=0, size=(800, 800))
display.start()
options = webdriver.ChromeOptions()
#All the arguments added for chromium to work on selenium
options.add_argument("--no-sandbox") #This make Chromium reachable
options.add_argument("--no-default-browser-check") #Overrides default choices
options.add_argument("--no-first-run")
options.add_argument("--disable-default-apps")
driver = webdriver.Chrome('/home/travis/virtualenv/python2.7.14/bin/chromedriver',chrome_options=options)
driver.get("http://127.0.0.1:5000/ui")
link = driver.find_element_by_xpath("/html/body/div/div/a")
link.click()
time.sleep(2)
driver.quit()
<file_sep>SERVICE_NAME=hello-world-printer
MY_DOCKER_NAME=$(SERVICE_NAME)
.PHONY: test deps test-api test_ui
.DEFAULT_GOAL := test
deps:
pip install -r requirements.txt; \
pip install -r test_requirements.txt;
lint:
flake8 hello_world test
test:
PYTHONPATH=. py.test --ignore=test_ui
test_cov:
PYTHONPATH=. py.test --verbose -s --cov=. --ignore=test_ui
test_xunit:
PYTHONPATH=. py.test -s --cov=. --junit-xml=test_results.xml --ignore=test_ui
test_ui:
PYTHONPATH=. py.test -s --verbose test_ui/test_ui.py
test-api:
python test-api/api_test.py
run:
python main.py
codeclimate:
codeclimate-test-reporter --file .coverage
docker_build:
docker build -t $(MY_DOCKER_NAME) .
docker_run: docker_build
docker run \
--name $(SERVICE_NAME)-dev \
-p 5000:5000 \
-d $(MY_DOCKER_NAME)
test_smoke:
curl -s -o /dev/null -w "%{http_code}" --fail 127.0.0.1:5000
test_smoke_siege_local:
siege -t30s c2 http://127.0.0.1:5000
test_smoke_siege_heroku:
siege -t30s c2 https://shielded-reef-85462.herokuapp.com/
USERNAME=addakowalczyk
TAG=$(USERNAME)/$(MY_DOCKER_NAME)
docker_push: docker_build
@docker login --username $(USERNAME) --password $${DOCKER_PASSWORD}; \
docker tag $(MY_DOCKER_NAME) $(TAG); \
docker push $(TAG);\
docker logout;
|
ab712cbff80b87da5272b8fd0e97e5ce8d2a5347
|
[
"Makefile",
"Python",
"Text",
"reStructuredText"
] | 4
|
reStructuredText
|
AddaKowalczyk8/se_hello_printer_app
|
7e604afed22aa23b4aa4e85ff2738c38d2e15313
|
3e4332400c2c9e746a3d1773ba228ec42b8361ae
|
HEAD
|
<file_sep><form name=alunos action=alunos_sql.php>
<center><table border=1 width=10%>
<input name=acao value=alterar type=hidden>
<tr>
<td>
<?
echo " <input name=codaluno value=$codaluno type=hidden>";
$sql_alunos="
SELECT
codaluno, aluno
FROM
alunos
WHERE
codaluno=$codaluno
";
$cons_alunos=pg_query($sql_alunos);
$alunos=pg_fetch_object($cons_alunos);
echo" <input name=aluno size=25% value='$alunos->aluno'>";
?>
</td>
</tr>
<tr>
<td align=center>
<a href=javascript:salvar()><img src=../imagens/salvar.png></a>
<a href=<?php echo "alunos.php?acao=lista"; ?>><img src=../imagens/cancelar.png></a>
</td>
</tr>
</form>
</table>
<script>
function salvar()
{
if (alunos.aluno.value == "")
{
alert("Por favor preencha o nome do aluno !!!");
alunos.aluno.focus();
exit;
}
document.alunos.submit();
}
</script>
<file_sep><?
include('../inc/conecta.inc');
switch ($acao)
{
case novo:
$sql_alunos="INSERT INTO alunos (aluno) VALUES ('$aluno')";
pg_query($sql_alunos);
break;
case alterar:
$sql_alunos="UPDATE alunos SET aluno='$aluno' WHERE codaluno=$codaluno";
pg_query($sql_alunos);
break;
case excluir:
$sql_alunos="DELETE FROM alunos WHERE codaluno=$codaluno";
pg_query($sql_alunos);
break;
}
header('location:alunos.php?acao=lista');
?>
<file_sep><?
include('../inc/conecta.inc');
include('../inc/cabecalho.php');
switch($acao)
{
case lista:
include('cabecalho_grades.php');
include('lista_grades.php');
break;
case novo;
include('novo_grades.php');
break;
case alterar;
include('alterar_grades.php');
break;
}
?>
<file_sep><?
include('../inc/conecta.inc');
switch ($acao)
{
case novo:
$sql_disciplinas="INSERT INTO disciplinas (disciplina) VALUES ('$disciplina')";
//echo "$sql_disciplinas";
pg_query($sql_disciplinas);
break;
case alterar:
$sql_disciplinas="UPDATE disciplinas SET disciplina='$disciplina' WHERE coddisciplina=$coddisciplina";
pg_query($sql_disciplinas);
break;
case excluir:
$sql_disciplinas="DELETE FROM disciplinas WHERE coddisciplina=$coddisciplina";
pg_query($sql_disciplinas);
break;
}
header('location:disciplinas.php?acao=lista');
?>
<file_sep><style>
.botao
{
height:40;
font-size:15px;
}
</style>
<?
$sql_grades="
SELECT
codgrade, turmas.turma, disciplinas.disciplina
FROM
grades
LEFT JOIN turmas ON turmas.codturma=grades.codturma
LEFT JOIN disciplinas ON disciplinas.coddisciplina=grades.coddisciplina
ORDER BY
codgrade desc
LIMIT 10
";
$cons_grades=pg_query($sql_grades);
while ($grades=pg_fetch_object($cons_grades))
{
# Zebrado
if ($cor==$corzebrado) $cor=''; else $cor=$corzebrado;
?>
<tr>
<td><?php echo "$grades->turma"; ?></td>
<td><?php echo "$grades->disciplina"; ?></td>
<td align=center>
<a href=javascript:alterar(<?php echo "$grades->codgrade"; ?>)><img src=../imagens/alterar.png title=Alterar></a>
<a href=javascript:excluir(<?php echo "$grades->codgrade"; ?>)><img src=../imagens/excluir.png title=Excluir></a></td>
</tr>
<?php }
?>
</table>
<p><br></p>
<center><input type=button class=botao value='Emitir Relatório' onclick=javascript:relatorio()></center>
<script>
function excluir(codgrade)
{
if (confirm('Deseja realmente excluir o registro?'+codgrade))
{
location.replace('grades_sql.php?acao=excluir&codgrade='+codgrade);
}
}
function alterar(codgrade)
{
location.replace('grades.php?acao=alterar&codgrade='+codgrade);
}
function relatorio()
{
window.open('relatorios.php')
}
</script>
<file_sep><?
include('../inc/conecta.inc');
include('../inc/cabecalho.php');
switch($acao)
{
case lista:
include('cabecalho_turmas.php');
include('lista_turmas.php');
break;
case novo;
include('novo_turmas.php');
break;
case alterar;
include('alterar_turmas.php');
break;
}
?>
<file_sep><?
include('../inc/conecta.inc');
include('../inc/cabecalho.php');
switch($acao)
{
case lista:
include('cabecalho_matriculas.php');
include('lista_matriculas.php');
break;
case novo;
include('novo_matriculas.php');
break;
case alterar;
include('alterar_matriculas.php');
break;
}
?>
<file_sep><form name=turmas action=turmas_sql.php>
<center><table border=1 width=10%>
<input name=acao value=novo type=hidden>
<tr>
<td>Nome do turma: <input name=turma size=25%></td>
</tr>
<tr>
<td align=center>
<a href=javascript:salvar()><img src=../imagens/salvar.png></a>
<a href=<?php echo "turmas.php?acao=lista"; ?>><img src=../imagens/cancelar.png></a>
</td>
</tr>
</table>
</form>
</center>
<script>
function salvar()
{
if (turmas.turma.value == "")
{
alert("Por favor preencha o nome do turma !!!");
turmas.turma.focus();
exit;
}
document.turmas.submit();
}
</script>
<file_sep><style>
.botao
{
height:40;
font-size:15px;
}
</style>
<?
$sql_alunos="
SELECT
codaluno, aluno
FROM
alunos
ORDER BY
codaluno desc
LIMIT 10
";
$cons_alunos=pg_query($sql_alunos);
while ($alunos=pg_fetch_object($cons_alunos))
{
# Zebrado
if ($cor==$corzebrado) $cor=''; else $cor=$corzebrado;
?>
<tr>
<td><?php echo "$alunos->aluno"; ?></td>
<td align=center>
<a href=javascript:alterar(<?php echo "$alunos->codaluno"; ?>)><img src=../imagens/alterar.png title=Alterar></a>
<a href=javascript:excluir(<?php echo "$alunos->codaluno"; ?>)><img src=../imagens/excluir.png title=Excluir></a></td>
</tr>
<?php }
?>
</table>
<p><br></p>
<center><input type=button class=botao value='Emitir Relatório' onclick=javascript:relatorio()></center>
<script>
function excluir(codaluno)
{
if (confirm('Deseja realmente excluir o registro?'+codaluno))
{
location.replace('alunos_sql.php?acao=excluir&codaluno='+codaluno);
}
}
function alterar(codaluno)
{
location.replace('alunos.php?acao=alterar&codaluno='+codaluno);
}
function relatorio()
{
window.open('relatorios.php')
}
</script>
<file_sep><form name=disciplinas action=disciplinas_sql.php>
<center><table border=1 width=10%>
<input name=acao value=alterar type=hidden>
<tr>
<td>
<?
echo " <input name=coddisciplina value=$coddisciplina type=hidden>";
$sql_disciplinas="
SELECT
coddisciplina, disciplina
FROM
disciplinas
WHERE
coddisciplina=$coddisciplina
";
$cons_disciplinas=pg_query($sql_disciplinas);
$disciplinas=pg_fetch_object($cons_disciplinas);
echo" <input name=disciplina size=25% value='$disciplinas->disciplina'>";
?>
</td>
</tr>
<tr>
<td align=center>
<a href=javascript:salvar()><img src=../imagens/salvar.png></a>
<a href=<?php echo "disciplinas.php?acao=lista"; ?>><img src=../imagens/cancelar.png></a>
</td>
</tr>
</form>
</table>
<script>
function salvar()
{
if (disciplinas.disciplina.value == "")
{
alert("Por favor preencha o nome do disciplina !!!");
disciplinas.disciplina.focus();
exit;
}
document.disciplinas.submit();
}
</script>
<file_sep><?
include('../inc/conecta.inc');
include('../inc/cabecalho.php');
switch($acao)
{
case lista:
include('cabecalho_alunos.php');
include('lista_alunos.php');
break;
case novo;
include('novo_alunos.php');
break;
case alterar;
include('alterar_alunos.php');
break;
}
?>
<file_sep><?
include('../inc/conecta.inc');
switch ($acao)
{
case novo:
$sql_turmas="INSERT INTO turmas (turma) VALUES ('$turma')";
pg_query($sql_turmas);
break;
case alterar:
$sql_turmas="UPDATE turmas SET turma='$turma' WHERE codturma=$codturma";
pg_query($sql_turmas);
break;
case excluir:
$sql_turmas="DELETE FROM turmas WHERE codturma=$codturma";
pg_query($sql_turmas);
break;
}
header('location:turmas.php?acao=lista');
?>
<file_sep><?
include('../inc/conecta.inc');
include('../inc/cabecalho.php');
switch($acao)
{
case lista:
include('cabecalho_exercicios.php');
include('lista_exercicios.php');
break;
case novo;
include('novo_exercicios.php');
break;
case alterar;
include('alterar_exercicios.php');
break;
}
?>
<file_sep><?
header('location:inc/cabecalho.php');
?>
<file_sep><html>
<head>
<title>Relatório</title>
<link rel="stylesheet" type="text/css" href="../inc/relatorio.css">
<style>
.dados td{
text-align: center;
}
</style>
</head>
<body>
<div class='container'>
<div class="cabecalho">
<?php
require_once "../inc/conecta.inc";
require_once "../inc/cabecalho_agenda.inc";
?>
</div>
<div class="titulo">LISTA DE ALUNOS DA TURMA 112</div>
<div class="corpo">
<table class='dados'>
<tr>
<th width='20%'>TURMA</th>
<th width='60%'>ALUNOS</th>
<th width='20%'>EXERCICIO</th>
</tr>
<?php
$sql_alunos="
SELECT
turmas.turma, alunos.aluno, exercicios.exercicio
FROM
seleciona_matriculas
LEFT JOIN turmas ON turmas.codturma=seleciona_matriculas.codturma
LEFT JOIN alunos ON alunos.codaluno=seleciona_matriculas.codaluno
LEFT JOIN exercicios ON exercicios.codexercicio=seleciona_matriculas.codexercicio";
$cons_alunos=pg_query($sql_alunos);
while ($alunos=pg_fetch_object($cons_alunos))
{
?>
<tr>
<td><?php echo $alunos->turma; ?></td>
<td><?php echo $alunos->aluno; ?></td>
<td><?php echo $alunos->exercicio; ?></td>
</tr>
<?php
}
?>
</table></center><br>
<p><br></p>
<p><br></p>
<p><br></p>
<p><br></p>
<p><br></p>
<p><br></p>
<p><br></p>
<p><br></p>
<p><br></p>
<p><br></p>
<p><br></p>
<p><br></p>
<p><br></p>
</div>
<center><NAME></center>
</div>
</body>
</html>
<file_sep><form name=disciplinas action=disciplinas_sql.php>
<center><table border=1 width=10%>
<input name=acao value=novo type=hidden>
<tr>
<td>Nome do disciplina: <input name=disciplina size=25%></td>
</tr>
<tr>
<td align=center>
<a href=javascript:salvar()><img src=../imagens/salvar.png></a>
<a href=<?php echo "disciplinas.php?acao=lista"; ?>><img src=../imagens/cancelar.png></a>
</td>
</tr>
</table>
</form>
</center>
<script>
function salvar()
{
if (disciplinas.disciplina.value == "")
{
alert("Por favor preencha o nome do disciplina !!!");
disciplinas.disciplina.focus();
exit;
}
document.disciplinas.submit();
}
</script>
<file_sep><form name=exercicios action=exercicios_sql.php>
<center><table border=1 width=10%>
<input name=acao value=novo type=hidden>
<tr>
<td>Nome do exercicio: <input name=exercicio size=25%></td>
</tr>
<tr>
<td align=center>
<a href=javascript:salvar()><img src=../imagens/salvar.png></a>
<a href=<?php echo "exercicios.php?acao=lista"; ?>><img src=../imagens/cancelar.png></a>
</td>
</tr>
</table>
</form>
</center>
<script>
function salvar()
{
if (exercicios.exercicio.value == "")
{
alert("Por favor preencha o nome do exercicio !!!");
exercicios.exercicio.focus();
exit;
}
document.exercicios.submit();
}
</script>
<file_sep><form name=turmas action=turmas_sql.php>
<center><table border=1 width=10%>
<input name=acao value=alterar type=hidden>
<tr>
<td>
<?
echo " <input name=codturma value=$codturma type=hidden>";
$sql_turmas="
SELECT
codturma, turma
FROM
turmas
WHERE
codturma=$codturma
";
$cons_turmas=pg_query($sql_turmas);
$turmas=pg_fetch_object($cons_turmas);
echo" <input name=turma size=25% value='$turmas->turma'>";
?>
</td>
</tr>
<tr>
<td align=center>
<a href=javascript:salvar()><img src=../imagens/salvar.png></a>
<a href=<?php echo "turmas.php?acao=lista"; ?>><img src=../imagens/cancelar.png></a>
</td>
</tr>
</form>
</table>
<script>
function salvar()
{
if (turmas.turma.value == "")
{
alert("Por favor preencha o nome do turma !!!");
turmas.turma.focus();
exit;
}
document.turmas.submit();
}
</script>
<file_sep><form name=exercicios action=exercicios_sql.php>
<center><table border=1 width=10%>
<input name=acao value=alterar type=hidden>
<tr>
<td>
<?
echo " <input name=codexercicio value=$codexercicio type=hidden>";
$sql_exercicios="
SELECT
codexercicio, exercicio
FROM
exercicios
WHERE
codexercicio=$codexercicio
";
$cons_exercicios=pg_query($sql_exercicios);
$exercicios=pg_fetch_object($cons_exercicios);
echo" <input name=exercicio size=25% value='$exercicios->exercicio'>";
?>
</td>
</tr>
<tr>
<td align=center>
<a href=javascript:salvar()><img src=../imagens/salvar.png></a>
<a href=<?php echo "exercicios.php?acao=lista"; ?>><img src=../imagens/cancelar.png></a>
</td>
</tr>
</form>
</table>
<script>
function salvar()
{
if (exercicios.exercicio.value == "")
{
alert("Por favor preencha o nome do exercicio !!!");
exercicios.exercicio.focus();
exit;
}
document.exercicios.submit();
}
</script>
<file_sep><form name=alunos action=alunos_sql.php>
<center><table border=1 width=10%>
<input name=acao value=novo type=hidden>
<tr>
<td>Nome do aluno: <input name=aluno size=25%></td>
</tr>
<tr>
<td align=center>
<a href=javascript:salvar()><img src=../imagens/salvar.png></a>
<a href=<?php echo "alunos.php?acao=lista"; ?>><img src=../imagens/cancelar.png></a>
</td>
</tr>
</table>
</form>
</center>
<script>
function salvar()
{
if (alunos.aluno.value == "")
{
alert("Por favor preencha o nome do aluno !!!");
alunos.aluno.focus();
exit;
}
document.alunos.submit();
}
</script>
<file_sep><?
include('../inc/conecta.inc');
include('../inc/cabecalho.php');
switch($acao)
{
case lista:
include('cabecalho_disciplinas.php');
include('lista_disciplinas.php');
break;
case novo;
include('novo_disciplinas.php');
break;
case alterar;
include('alterar_disciplinas.php');
break;
}
?>
<file_sep><style>
.botao
{
height:40;
font-size:15px;
}
</style>
<?
$sql_matriculas="
SELECT
codmatricula, turmas.turma, alunos.aluno, exercicios.exercicio
FROM
matriculas
LEFT JOIN turmas ON turmas.codturma=matriculas.codturma
LEFT JOIN alunos ON alunos.codaluno=matriculas.codaluno
LEFT JOIN exercicios ON exercicios.codexercicio=matriculas.codexercicio
ORDER BY
codmatricula desc
LIMIT 10
";
$cons_matriculas=pg_query($sql_matriculas);
while ($matriculas=pg_fetch_object($cons_matriculas))
{
# Zebrado
if ($cor==$corzebrado) $cor=''; else $cor=$corzebrado;
?>
<tr>
<td><?php echo "$matriculas->turma"; ?></td>
<td><?php echo "$matriculas->aluno"; ?></td>
<td><?php echo "$matriculas->exercicio"; ?></td>
<td align=center>
<a href=javascript:alterar(<?php echo "$matriculas->codmatricula"; ?>)><img src=../imagens/alterar.png title=Alterar></a>
<a href=javascript:excluir(<?php echo "$matriculas->codmatricula"; ?>)><img src=../imagens/excluir.png title=Excluir></a></td>
</tr>
<?php }
?>
</table>
<p><br></p>
<center><input type=button class=botao value='Emitir Relatório' onclick=javascript:relatorio()></center>
<script>
function excluir(codmatricula)
{
if (confirm('Deseja realmente excluir o registro?'+codmatricula))
{
location.replace('matriculas_sql.php?acao=excluir&codmatricula='+codmatricula);
}
}
function alterar(codmatricula)
{
location.replace('matriculas.php?acao=alterar&codmatricula='+codmatricula);
}
function relatorio()
{
window.open('relatorios.php')
}
</script>
<file_sep><?
$conexao=pg_connect ('host=localhost dbname=escola user=escola password=<PASSWORD>');
?>
<file_sep>--CREATE DATABASE escola;
--USUÁRIO: escola;
--SENHA: 123456;
--##########################################################
CREATE TABLE alunos (
codaluno SERIAL PRIMARY KEY,
aluno VARCHAR (255)
);
CREATE VIEW seleciona_alunos AS
SELECT codaluno, aluno
FROM alunos;
--##########################################################
CREATE TABLE turmas (
codturma SERIAL PRIMARY KEY,
turma integer
);
CREATE VIEW seleciona_turmas AS
SELECT codturma, turma
FROM turmas;
--##########################################################
CREATE TABLE disciplinas (
coddisciplina SERIAL PRIMARY KEY,
disciplina VARCHAR(255)
);
CREATE VIEW seleciona_disciplinas AS
SELECT coddisciplina, disciplina
FROM disciplinas;
--##########################################################
CREATE TABLE grades (
codgrade SERIAL PRIMARY KEY,
codturma INTEGER REFERENCES turmas (codturma),
coddisciplina INTEGER REFERENCES disciplinas (coddisciplina)
);
CREATE VIEW seleciona_grades AS
SELECT codgrade, grade
FROM grades;
--##########################################################
--##########################################################
CREATE TABLE exercicios (
codexercicio SERIAL PRIMARY KEY,
exercicio integer
);
CREATE VIEW seleciona_exercicios AS
SELECT codexercicio, exercicio
FROM exercicios;
--##########################################################
CREATE TABLE matriculas (
codmatricula SERIAL PRIMARY KEY,
codturma INTEGER REFERENCES turmas (codturma),
codaluno INTEGER REFERENCES alunos (codaluno),
codexercicio INTEGER REFERENCES exercicios (codexercicio)
);
CREATE VIEW seleciona_matriculas AS
SELECT codmatricula, codturma, codaluno, codexercicio
FROM matriculas;
--SELECIONANDO UMA VIEW
SELECT
turmas.turma, alunos.aluno, exercicios.exercicio
FROM
seleciona_matriculas
LEFT JOIN turmas ON turmas.codturma=seleciona_matriculas.codturma
LEFT JOIN alunos ON alunos.codaluno=seleciona_matriculas.codaluno
LEFT JOIN exercicios ON exercicios.codexercicio=seleciona_matriculas.codexercicio
<file_sep><?
include('../inc/conecta.inc');
switch ($acao)
{
case novo:
$sql_exercicios="INSERT INTO exercicios (exercicio) VALUES ('$exercicio')";
pg_query($sql_exercicios);
break;
case alterar:
$sql_exercicios="UPDATE exercicios SET exercicio='$exercicio' WHERE codexercicio=$codexercicio";
pg_query($sql_exercicios);
break;
case excluir:
$sql_exercicios="DELETE FROM exercicios WHERE codexercicio=$codexercicio";
pg_query($sql_exercicios);
break;
}
header('location:exercicios.php?acao=lista');
?>
<file_sep><html>
<head>
<title>Relatório</title>
<link rel="stylesheet" type="text/css" href="../inc/relatorio.css">
<style>
.dados td{
text-align: center;
}
</style>
</head>
<body>
<div class='container'>
<div class="cabecalho">
<?php
require_once "../inc/conecta.inc";
require_once "../inc/cabecalho_agenda.inc";
?>
</div>
<div class="titulo">TÍTULO DO RELATÓRIO AQUI</div>
<div class="corpo">
<?php
echo "<table class='dados'>";
echo "<th width='60%'>COLUNA 1</th>";
echo "<th width='40%'>COLUNA 2</th>";
echo "</table>";
?>
<p><br></p>
<p><br></p>
<p><br></p>
<p><br></p>
<p><br></p>
<p><br></p>
<p><br></p>
<p><br></p>
<p><br></p>
<p><br></p>
<p><br></p>
<p><br></p>
<p><br></p>
</div>
<center>Rodapé aqui</center>
</div>
</body>
</html>
|
e6b64683a203f167c8ba4284c23098dd50affcf3
|
[
"SQL",
"PHP"
] | 26
|
PHP
|
VitorHugoSilva/escola
|
809c25f993f5d436c2d0bce3191e9da8dee7ebc1
|
9baa4578b892147d75d0d6c8f6c4551bd8baed30
|
refs/heads/master
|
<file_sep>package com.kjoshi.droidsqlite.db;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import com.kjoshi.droidsqlite.model.Customer;
import java.util.ArrayList;
/**
* The CustomerRepo class is a class to perform customer operations.
*
* @author <NAME>
* @version 1.0
* @since 2016-06-29
*/
public class CustomerRepo {
private final static String TAG = CustomerRepo.class.getSimpleName();
private Context mContext;
CustomerDbHelper mDbHelper;
public CustomerRepo(Context _context) {
this.mContext = _context;
mDbHelper = CustomerDbHelper.getInstance(_context);
}
/**
* This is the method to add a customer in database.
*
* @param Customer parameter used.
* @return void if there is an exception then exception would be thrown.
* @throws IOException On input error.
*/
public void addCustomer(Customer customer) {
// Create and/or open the database for writing
SQLiteDatabase db = mDbHelper.getWritableDatabase();
// It's a good idea to wrap our insert in a transaction. This helps with performance and ensures
// consistency of the database.
db.beginTransaction();
try {
ContentValues values = new ContentValues();
values.put(CustomerContract.CustomerTable.COLUMN_CUSTOMER_ID, customer.getCustomerId());
values.put(CustomerContract.CustomerTable.COLUMN_CUSTOMER_FIRST_NAME, customer.getFirstName());
values.put(CustomerContract.CustomerTable.COLUMN_CUSTOMER_LAST_NAME, customer.getLastName());
values.put(CustomerContract.CustomerTable.COLUMN_CUSTOMER_EMAIL, customer.getEmail());
values.put(CustomerContract.CustomerTable.COLUMN_CUSTOMER_PHONE, customer.getPhone());
values.put(CustomerContract.CustomerTable.COLUMN_CUSTOMER_COMPANY, customer.getCompany());
db.insertOrThrow(CustomerContract.CustomerTable.TABLE_NAME, null, values);
db.setTransactionSuccessful();
} catch (Exception e) {
Log.d(TAG, e.getMessage());
} finally {
db.endTransaction();
}
}
/**
* This is the method to add a customer in database.
*
* @param N/A parameter used.
* @return String as Customer ID or exception if there is an exception then exception would be thrown.
* @throws IOException On input error.
*/
public String getLastInsertedCustomerNumber() {
String customerId = "";
// Create and/or open the database for writing
SQLiteDatabase db = mDbHelper.getWritableDatabase();
// It's a good idea to wrap our insert in a transaction. This helps with performance and ensures
// consistency of the database.
db.beginTransaction();
try {
String[] columnsSelectionQuery = {CustomerContract.CustomerTable.COLUMN_CUSTOMER_ID};
//String[] orderBy = {ORDER BY column DESC LIMIT 1}
Cursor cursor = db.query(CustomerContract.CustomerTable.TABLE_NAME, columnsSelectionQuery, null, null, null, null, CustomerContract.CustomerTable.COLUMN_CUSTOMER_ID + " DESC LIMIT 1");
if (cursor.moveToFirst()) {
do {
customerId = cursor.getString(cursor.getColumnIndex(CustomerContract.CustomerTable.COLUMN_CUSTOMER_ID));
// do what ever you want here
} while (cursor.moveToNext());
}
cursor.close();
Log.d(TAG, customerId);
} catch (Exception e) {
Log.d(TAG, e.getMessage());
} finally {
db.endTransaction();
}
return customerId;
}
}
<file_sep>package com.kjoshi.droidsqlite.controller;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import com.kjoshi.droidsqlite.db.CustomerRepo;
import com.kjoshi.droidsqlite.model.Customer;
/**
* CustomerController will control all the operation related to Customers wther they are database reslated or consume API.
*
* @author <NAME>
* @version 1.0
* @since 2016-06-30
*/
public class CustomerController {
private final static String TAG = CustomerController.class.getSimpleName();
private Context mContext;
private final static String CUSTOMER_ID_PRE = "CN";
//Define a constructor to accept Context as argument.
public CustomerController(Context _context) {
this.mContext = _context;
}
/**
* This is the method to add a customer in database.
*
* @param Customer parameter used.
* @return true or false as per success or failure of database operation.
* @throws IOException On input error.
*/
public boolean addCustomer(Customer customer) {
try {
//If customer ID is null then generate a new and set in Customer Object.
if (customer.getCustomerId() == null) {
customer.setCustomerId(generateCustomerId());
}
//Create a object of Customer repository and call addCustomer method to perform a operation to add a customer in SQLIte.
CustomerRepo repo = new CustomerRepo(mContext);
repo.addCustomer(customer);
} catch (Exception e) {
Log.e(TAG, e.getMessage());
}
return true;
}
/**
* This is the method to generate a unique customer ID with "AN" and appending a sequential number..
*
* @param No parameter used.
* @return String customerId
* @throws IOException On input error.
*/
private String generateCustomerId() {
String newCustomerNumber = "";
try {
CustomerRepo repo = new CustomerRepo(mContext);
String customerId = repo.getLastInsertedCustomerNumber();
if (customerId != null && !customerId.isEmpty()) {
String customerNumber = customerId.substring(2);
//covert it into int
int custNo = Integer.parseInt(customerNumber);
custNo++;
newCustomerNumber = CUSTOMER_ID_PRE + custNo;
} else {
newCustomerNumber = CUSTOMER_ID_PRE + 0001;
}
} catch (Exception e) {
Log.e(TAG, e.getMessage());
}
return newCustomerNumber;
}
}
|
0ab6513bfa04e2e2eb6a8c64ecf747c4d2ec8007
|
[
"Java"
] | 2
|
Java
|
kjoshi07/DroidSQLite
|
51d801b94d905104aad19a9536b98f1a6af79ba9
|
4540c978f5435d4aef4533da4f6d140e3e1b6dbe
|
refs/heads/master
|
<file_sep># pystan-sklearn
This module provides a scikit-learn estimator class based on Stan (http://github.com/stan-dev/pystan).
This allows all of the functionality of scikit-learn to be used in the fitting and checking of Stan models.
Run example.py from the root pystan-sklearn directory for an example of a grid search over the 'mu' hyperparameter in the 'Eight Schools' example.
<file_sep>import numpy as np
import pystan
from sklearn.base import BaseEstimator
class StanModel_(pystan.StanModel):
def __del__(self):
"""
This method is being used carelessly in sklearn's GridSearchCV class,
creating and destroying copies of the estimator, which is causing the
directory containing the compiled Stan code to be deleted. It is
replaced here with an empty method to avoid this problem. This means
a potential proliferation of temporary directories.
"""
pass
class StanEstimator(BaseEstimator):
"""
A new sklearn estimator class derived for use with pystan.
"""
def __init__(self, **kwargs):
for key,value in kwargs.items():
setattr(self,key,value)
def set_model(self, code):
"""
Sets and compiles a Stan model for this estimator.
"""
self.model = StanModel_(model_code=code)
def set_data(self, *args, **kwargs):
"""
Sets the data for use with this estimator.
Uses the 'data' keyword argument if provided, else it
uses the 'make_data' method.
"""
if 'data' not in kwargs or kwargs[data] is None:
data = self.make_data()
else:
data = kwargs[data]
self.data = data
for key,value in data.items():
setattr(self,key,value)
def make_data(self, *args, **kwargs):
"""
A model-specific method for constructing the data to be used by
the model. May be limited to the data passed to the Stan model's
fitter, or may also include other items as well. Should return
a dictionary."""
raise NotImplementedError("")
def optimize(self, X, y):
"""
Optimizes the estimator based on covariates X and observations y.
"""
for key in self.data.keys():
self.data[key] = getattr(self,key)
self.best = self.model.optimizing(data=self.data)
def get_params(self, deep=False):
"""
Gets model parameters. These are just attributes of the estimator
as set in __init__ and possibly in other methods.
"""
return self.__dict__
def fit(self, X, y):
"""
Fits the estimator based on covariates X and observations y.
"""
print(X.shape,len(y))
self.optimize(X,y)
for key,value in self.best.items():
setattr(self,key,value)
def transform(self, X, y=None, **fit_params):
"""
Performs a transform step on the covariates after fitting.
In the basic form here it just returns the covariates.
"""
return X
def predict(self, X):
"""
Generates a prediction based on X, the array of covariates.
"""
n_samples = X.shape[0]
prediction = []
for i in range(n_samples):
prediction.append(self.predict_(X,i))
return prediction
def predict_(self, X, i):
"""
Generates a prediction for one sample, based on X, the array of
covariates and i, a point in that array (1D), or row (2D), etc.
This must be implemented for each model.
"""
raise NotImplementedError("")
def score(self, X, y):
"""
Generates a score for the prediction based on X, the array of
covariates, and y, the observation.
"""
prediction = self.predict(X)
return self.score_(prediction,y)
def score_(self, prediction, y):
"""
Generates a score based on the prediction (from X), and the
observation y.
"""
raise NotImplementedError("")
@classmethod
def get_posterior_mean(cls, fit):
"""
Implemented because get_posterior_mean is (was?) broken in pystan:
https://github.com/stan-dev/pystan/issues/107
"""
means = {}
x = fit.extract()
for key,value in x.items()[:-1]:
means[key] = value.mean(axis=0)
return means
<file_sep>import numpy as np
from scipy.stats import norm
from sklearn.model_selection import ShuffleSplit,GridSearchCV
from pystan_sklearn import StanEstimator
#############################################################
# All of this from the eight schools example.
schools_code = """
data {
int<lower=0> J; // number of schools
real y[J]; // estimated treatment effects
real<lower=0> sigma[J]; // s.e. of effect estimates
}
parameters {
real mu;
real<lower=0> tau;
real eta[J];
}
transformed parameters {
real theta[J];
for (j in 1:J)
theta[j] = mu + tau * eta[j];
}
model {
eta ~ normal(0, 1);
y ~ normal(theta, sigma);
}
"""
schools_dat = {'J': 8,
'y': [28, 8, -3, 7, -1, 1, 18, 12],
'sigma': [15, 10, 16, 11, 9, 11, 10, 18]}
#############################################################
# First we have to make an estimator specific to our model.
# For now, I don't have a good way of automatically implementing this
# in a general way based on the model code.
class EightSchoolsEstimator(StanEstimator):
# Implement a make_data method for the estimator.
# This tells the sklearn estimator what things to pass along
# as data to the Stan model.
# This is trivial here but can be more complex for larger models.
def make_data(self,search_data=None):
data = schools_dat
if search_data:
data.update({key:value[0] for key,value in search_data.items()})
return data
# Implement a predict_ method for the estimator.
# This tells the sklearn estimator how to make a prediction for one sample.
# This is based on the prediction for the mean theta above.
def predict_(self,X,j):
theta_j = self.mu + self.tau * self.eta[j];
return (theta_j,self.sigma[j])
# Implement a score_ method for the estimator.
# This tells the sklearn estimator how to score one observed sample against
# the prediction from the model.
# It is based on the fitted values of theta and sigma.
def score_(self,prediction,y):
likelihoods = np.zeros(len(y))
for j,(theta_j,sigma_j) in enumerate(prediction):
likelihoods[j] = norm.pdf(y[j],theta_j,sigma_j)
return np.log(likelihoods).sum()
# Initialize StanEstimator instance.
estimator = EightSchoolsEstimator()
# Compile the model code.
estimator.set_model(schools_code)
# Search over these parameter values.
search_data = {'mu':[0.3,1.0,3.0]}
# Create a data dictionary for use with the estimator.
# Note that this 'data' means different things in sklearn and Stan.
data = estimator.make_data(search_data=search_data)
# Set the data (set estimator attributes).
estimator.set_data(data)
# Set the y data.
# Use the observed effect from the Stan code here (e.g. "y").
y = data['y']
# Set the X data, i.e. the covariates.
# In this example there is no X data so we just use an array of ones.
X = np.ones((len(y),1))
#vstack((data['subject_ids'],data['test_ids'])).transpose()
# Fraction of data held out for testing.
test_size = 2.0/len(y)
# A cross-validation class from sklearn.
# Use the sample size variable from the Stan code here (e.g. "J").
cv = ShuffleSplit(n_splits=10, test_size=test_size)
# A grid search class over parameters from sklearn.
grid = GridSearchCV(estimator, search_data, cv=cv)
# Fit the model over the parameter grid.
grid.fit(X,y)
# Print the parameter values with the best scores (best predictive accuracy).
print(grid.best_params_)
|
89b3f158659080efab8854b9f086ee62f06abc7d
|
[
"Markdown",
"Python"
] | 3
|
Markdown
|
rgerkin/pystan-sklearn
|
5c5cffe5389abb58fa85d0a47bd4760128b19d8a
|
8ff3d7ee8450fe58b2d6a2e5ae3076daa8d16477
|
refs/heads/master
|
<file_sep>module.exports = {
jwtSecret: process.env.JWT_SECRET || '<KEY>'
};
|
041fa025e6b958796f48f48f530eb736b529f86a
|
[
"JavaScript"
] | 1
|
JavaScript
|
smwellmer/stagecoach
|
6e23bc48032c276c4293cf6f6a2d96291e28d11a
|
f48fcdb4c34d4776629da04d11ec2e9d59ddc976
|
refs/heads/main
|
<file_sep>const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const userSchema = new Schema({
name: {
type: String,
required: false
},
email: {
type: String,
required: true
},
password:{
type:String,
required:true
},
resetPassToken:String,
resetPassExpiration:Date,
cart: {
items: [
{
productId: {
type: Schema.Types.ObjectId,
ref: 'Products',
required: true
},
quantity: {
type: Number,
required: true
}
}
]
}
})
userSchema.methods.addToCart = function (product) {
const cartIndex = this.cart.items.findIndex(cp => {
return cp.productId.toString() === product._id.toString();
})
let updatedQuantity = 1;
const updatedCartProdItems = [...this.cart.items];
if (cartIndex >= 0) {
updatedQuantity = this.cart.items[cartIndex].quantity + 1;
updatedCartProdItems[cartIndex].quantity = updatedQuantity;
} else {
updatedCartProdItems.push({
productId: product._id,
quantity: updatedQuantity
});
}
const updatedCart = {
items: updatedCartProdItems
}
this.cart = updatedCart;
return this.save();
}
userSchema.methods.getCart = function () {
return this.populate('cart.items.productId')
.execPopulate()
// .then(prods => {
// return prods;
// });
}
userSchema.methods.deleteItemFromCart = function (prodId) {
const updatedCartItems = this.cart.items.filter(p => {
return p.productId.toString() !== prodId.toString()
});
this.cart.items=updatedCartItems;
return this.save();
}
userSchema.methods.clearCart = function () {
this.cart={items:[]};
return this.save();
}
module.exports = mongoose.model('User', userSchema);
//by direct mongoDB
// const mongodb=require('mongodb');
// const getDB=require('../utils/database').getDb;
// class User{
// constructor(userName,email,cart,id){
// this.name=userName;
// this.email=email;
// this.cart=cart;
// this._id=id;
// }
// save(){
// const db=getDB();
// return db.collection('users').insetOne(this);
// }
// static findById(id){
// const db=getDB();
// return db.collection('users').findOne({_id:new mongodb.ObjectID(id)});
// }
// addToCart(product){
// const cartIndex=this.cart.items.findIndex(cp=>{
// return cp.productId.toString() === product._id.toString();
// })
// let updatedQuantity=1;
// const updatedCartProdItems=[...this.cart.items];
// if(cartIndex >=0){
// updatedQuantity=this.cart.items[cartIndex].quantity +1;
// updatedCartProdItems[cartIndex].quantity=updatedQuantity;
// }else{
// updatedCartProdItems.push({productId:new mongodb.ObjectID(product._id),quantity:updatedQuantity});
// }
// const updatedCart={
// items:updatedCartProdItems
// }
// const db=getDB();
// return db.collection('users').updateOne({_id:new mongodb.ObjectID(this._id)},{$set:{cart:updatedCart}});
// }
// getCart(){
// const db=getDB();
// const prodIds=this.cart.items.map(prod=>{
// return prod.productId;
// });
// return db.collection('products').find({_id:{$in:prodIds}}).toArray()
// .then(prods=>{
// return prods.map(prd=>{
// return {
// ...prd,quantity:this.cart.items.find(item=>{
// return item.productId.toString()=== prd._id.toString();
// }).quantity
// };
// });
// });
// }
// deleteItemFromCart(prodId){
// const db=getDB();
// const updatedCartItems=this.cart.items.filter(p=>{
// return p.productId.toString()!==prodId.toString()
// });
// return db.collection('users').updateOne(
// {_id:new mongodb.ObjectID(this._id)},
// {$set:{cart:{items:updatedCartItems} } } );
// }
// addOrder(){
// const db=getDB();
// return this.getCart()
// .then(products=>{
// const order={
// items:products,
// user:{
// _id:new mongodb.ObjectId(this._id),
// name:this.name
// }
// }
// return db.collection('orders').insertOne(order)
// })
// .then((data)=>{
// this.cart={items:[]};
// return db.collection('users').updateOne(
// {_id:new mongodb.ObjectId(this._id)},
// {$set:{cart:{items:[]}}})
// })
// }
// getOrders(){
// const db=getDB();
// return db.collection('orders').find({'user._id':new mongodb.ObjectId(this._id)}).toArray();
// }
// }
// module.exports=User;<file_sep>const express=require('express');
const path=require('path');
const shopController=require('../controllers/shop');
const isAuth=require('../middleware/is-auth');
const router=express.Router();
router.get('/',shopController.getIndex);
router.get('/products',shopController.getProduct);
router.get('/products/:productId',shopController.getSingleProduct);
router.get('/cart',isAuth,shopController.getCart);
router.post('/cart',isAuth,shopController.postCart);
router.post('/cart-delete-item',isAuth,shopController.postCartDeleteProduct)
router.get('/orders',isAuth,shopController.getOrders);
router.get('/checkout',isAuth,shopController.getCheckout);
router.post('/create-order',isAuth,shopController.postOrders)
module.exports = router;<file_sep>const User = require('../utils/db_mongoose').Users;
const bcrypt = require('bcryptjs');
const crypto= require('crypto');
exports.getAuth = (req, res, next) => {
// const isloggedin=req.get('Cookie').split(';')[0].split('=')[1];
// console.log(isloggedin);
let message= req.flash('error');
if(message.length>0){
message=message[0];
}else{
message=null;
}
res.render('auth/login',
{
path: "/login",
pageTitle: "Login ",
isAuthenticated: req.session.isloggedin,
errorMessage:message
}
);
}
exports.postLogin = (req, res, next) => {
//coookie setup
// res.setHeader('Set-Cookie','loggedIn=true') //set cookie name loggedIn
// req.isLoggedin=true;
const email = req.body.email;
const password = <PASSWORD>;
User.findOne({ email: email })
.then((user) => {
if (!user) {
req.flash('error','Invalid Email or Password')
return res.redirect('/login');
}
bcrypt.compare(password, user.<PASSWORD>)
.then((doMatch) => {
if (doMatch) {
req.session.isloggedin = true;
req.session.user = user;
return req.session.save((err) => {
console.log(err);
res.redirect('/');
});
}
return res.redirect('/login');
})
.catch(err => {
console.log(err);
})
})
.catch(err => {
console.log(err);
})
}
exports.postLogout = (req, res, next) => {
req.session.destroy((err) => {
console.log(err);
res.redirect('/')
})
}
exports.getSignup = (req, res, next) => {
// const isloggedin=req.get('Cookie').split(';')[0].split('=')[1];
// console.log(isloggedin);
let message= req.flash('error');
if(message.length>0){
message=message[0];
}else{
message=null;
}
res.render('auth/signup', { path: "/signup", pageTitle: "Signup ", isAuthenticated: req.session.isloggedin,errorMessage:message });
}
exports.postSignup = (req, res, next) => {
const email=req.body.email;
const password=req.body.password;
const confirmPassword=req.body.confirmPassword;
User.findOne({email:email})
.then(userDoc=>{
if(userDoc){
req.flash('error','User already exists, Please try again with differant email id')
return res.redirect('/signup')
}
return bcrypt
.hash(password,12)
.then(encryptedPass=>{
const user= new User({
email:email,
password:<PASSWORD>,
cart:{
items:[]
}
});
return user.save();
})
})
.then(user=>{
return res.redirect('/login');
})
}
exports.getReset=(req,res,next)=>{
let message= req.flash('error');
if(message.length>0){
message=message[0];
}else{
message=null;
}
res.render('auth/resetPassword',
{
path: "/resetPassword",
pageTitle: "Reset Password",
isAuthenticated: req.session.isloggedin,
errorMessage:message
});
}
exports.postResetPass=(req,res,next)=>{
let message= req.flash('error');
let token;
if(message.length>0){
message=message[0];
}else{
message=null;
}
crypto.randomBytes(42,(err,buffer)=>{
if(err){
console.log(err);
return res.redirect('/reset');
}
User.findOne({email:req.body.email})
.then(result=>{
if(!result){
req.flash('error','User not found');
return res.redirect('/reset');
}
token=buffer.toString('hex');
result.resetPassToken=token;
result.resetPassExpiration=Date.now() +3600000;
return result.save();
})
.then(()=>{
res.redirect(`/reset/${token}`);
})
.catch(err=>{
console.log(err);
})
});
}
exports.getResetPassToken=(req,res,next)=>{
let message= req.flash('error');
let token=req.params.token;
if(message.length>0){
message=message[0];
}else{
message=null;
}
User.findOne({resetPassToken:token,resetPassExpiration:{$gt:Date.now()}})
.then((result)=>{
res.render('auth/new-password',
{
path: "/new-password",
pageTitle: "Reset Password",
isAuthenticated: req.session.isloggedin,
errorMessage:message,
resetPasstoken:token,
email:result.email
});
})
.catch(err=>{
console.log(err);
})
}
exports.postNewPassword=(req,res,next)=>{
const token=req.body.token;
const email=req.body.email;
let resetUser;
User.findOne({email:email,resetPassToken:token,resetPassExpiration:{$gt:Date.now()}})
.then((data)=>{
if(!data){
req.flash('error','Token expires');
res.redirect('/reset');
}
resetUser=data;
return bcrypt.hash(req.body.password,12)
})
.then((hasedPassword)=>{
resetUser.password=<PASSWORD>;
resetUser.resetPassExpiration=<PASSWORD>;
resetUser.resetPassToken=<PASSWORD>;
return resetUser.save();
})
.then(()=>{
res.redirect('/login');
})
.catch(err=>{
console.log(err);
})
}<file_sep>const mongodb =require('mongodb');
const MongoClient= mongodb.MongoClient;
const uri = "mongodb+srv://rahul_nodeTut:<EMAIL>/shop?retryWrites=true&w=majority";
let _db;
const mongoClient=(callback)=>{
MongoClient.connect(uri,{ useUnifiedTopology: true })
.then((result)=>{
console.log('database connected');
_db=result.db('shop');
callback();
})
.catch((err)=>{
console.log("Error",err);
})
}
const getDb=()=>{
if(_db){
return _db;
}
throw 'No Database connected'
}
exports.mongoConnect=mongoClient;
exports.getDb=getDb;<file_sep>const path=require('path');
//this will return main folder path in which app.js or starting file is avaliable in out case its
//D:\personal\Node-Practice\Node-Maxmillan-tut\working with Express\handling_routes_with_express
module.exports=path.dirname(require.main.filename);
<file_sep>//product model with mongoose
const { ObjectID } = require('mongodb');
const mongoose=require('mongoose');
const Schema=mongoose.Schema;
const prodSchema=new Schema({
title:{
type:String,
required:true
},
price:{
type:Number,
required:true
},
desc:{
type:String,
required:true
},
imageUrl:{
type:String,
required:true
},
userId:{
type:Schema.Types.ObjectId,
ref:'User',
required:true
}
})
module.exports=mongoose.model('Products',prodSchema);
//product model with fs and mongoclient
// const fs=require('fs');
// const path =require('path');
// const mongodb=require('mongodb');
// const Cart=require('./cart')
// const getDb=require('../utils/database').getDb;
// const p =path.join(path.dirname(require.main.filename),'data','products.json');
// const getProductFromFile=(cb)=>{
// fs.readFile(p,(err,fileData)=>{
// if(err){
// cb([]);
// }else{
// cb(JSON.parse(fileData));
// }
// })
// }
// module.exports= class Product{
// constructor(id,title,imageUrl,price,desc,userId){
// this._id=id;
// this.title=title;
// this.imageUrl=imageUrl;
// this.price=price;
// this.desc=desc;
// this.userId=userId;
// }
// save(){
// // console.log(this);
// // getProductFromFile((products)=>{
// // if(this.id){
// // console.log(this.id,"",p);
// // console.log('here')
// // const existingProdIndex=products.findIndex(p=>p.id===this.id);
// // let updatedProduct=[...products];
// // updatedProduct[existingProdIndex]=this;
// // fs.writeFile(p,JSON.stringify(updatedProduct),(err)=>{
// // console.log(err);
// // });
// // }else{
// // this.id=Math.floor(Math.random() * (999999 - 1 + 1) + 1).toString();
// // products.push(this)
// // fs.writeFile(p,JSON.stringify(products),(err)=>{
// // console.log(err);
// // });
// // }
// // })
// //using DB
// const db=getDb();
// db.collection('products').insertOne(this)
// .then()
// .catch(err=>{
// console.log(err);
// })
// }
// update(){
// const db=getDb();
// if(this._id){
// return db.collection('products')
// .updateOne({_id:new mongodb.ObjectID(this._id)},{$set:{title:this.title,imageUrl:this.imageUrl,price:this.price,desc:this.desc}})
// }
// }
// static fetchAll(){
// const db=getDb();
// return db.collection('products').find().toArray()
// .then(products=>{
// return products;
// })
// .catch(err=>{
// console.log(err);
// })
// }
// static finById(id){
// // getProductFromFile((products)=>{
// // const product=products.find(p=>p.id===id);
// // cb(product);
// // })
// //ObjectID methods
// //console.log(new mongodb.ObjectID(id).valueOf())
// //using DB
// const db=getDb();
// return db.collection('products').find({_id: new mongodb.ObjectID(id)}).next()
// .then(products=>{
// return products;
// })
// .catch(err=>{
// console.log(err);
// })
// }
// static deleteById(id){
// // getProductFromFile(products=>{
// // const prod=products.find(p=>p.id===id);
// // const updatedProduts=products.filter(p=>p.id !==id);
// // fs.writeFile(p,JSON.stringify(updatedProduts),err=>{
// // if(!err){
// // Cart.deleteProduct(id,prod.price)
// // }else{
// // console.log(err);
// // }
// // })
// // })
// //using DB
// const db=getDb();
// return db.collection('products').remove({_id:new mongodb.ObjectID(id)})
// }
// }<file_sep>const authController=require('../controllers/auth');
const express=require('express');
const router=express.Router();
router.get('/login',authController.getAuth)
router.post('/login',authController.postLogin);
router.post('/logout',authController.postLogout);
router.get('/signup',authController.getSignup)
router.post('/signup',authController.postSignup)
router.get('/reset',authController.getReset);
router.post('/reset',authController.postResetPass);
router.get('/reset/:token',authController.getResetPassToken)
router.post('/reset/newPassword',authController.postNewPassword)
module.exports=router;
<file_sep>const fs=require('fs');
const path=require('path')
const p =path.join(path.dirname(require.main.filename),'data','cart.json');
module.exports= class Cart{
static addProduct(id,productPrice){
fs.readFile(p,(err,fileData)=>{
let cart={products:[],totalPrice:0};
if(!err){
cart= JSON.parse(fileData);
}
const existingProdIndex=cart.products.findIndex(p=>p.id===id)
const existingProduct=cart.products[existingProdIndex];
let updatedProduct
if(existingProduct){
updatedProduct={...existingProduct};
updatedProduct.qty+=1;
cart.products=[...cart.products];
cart.products[existingProdIndex]=updatedProduct;
}else{
updatedProduct={id:id,qty:1};
cart.products=[...cart.products,updatedProduct];
}
cart.totalPrice+= parseFloat(productPrice);
fs.writeFile(p,JSON.stringify(cart),(err)=>{
console.log(err);
})
})
}
static deleteProduct(id,prodPrice){
fs.readFile(p,(err,fileData)=>{
if(err){
return
}
const cart= JSON.parse(fileData);
let updatedCart={...cart}
const prod=updatedCart.products.find(p=>p.id===id);
if(!prod){
return;
}
const prodQty=prod.qty;
updatedCart.products=updatedCart.products.filter(p=>p.id !== id);
updatedCart.totalPrice=updatedCart.totalPrice- (prodPrice *prodQty);
fs.writeFile(p,JSON.stringify(updatedCart),(err)=>{
console.log(err);
})
})
}
static getCart(cb){
fs.readFile(p,(err,fileData)=>{
if(err){
cb(null)
}else{
const cart=JSON.parse(fileData);
cb(cart);
}
});
}
}<file_sep>const Product=require('../models/product');
const Cart=require('../models/cart');
const User = require('../models/user');
const db=require('../utils/db_mongoose');
const { ObjectID } = require('mongodb');
const { Orders } = require('../utils/db_mongoose');
const Products=db.Product;
const Order=db.Orders;
exports.getProduct=(req,res,next)=>{
//res.send({"Message":"Hello"});
// Product.fetchAll((data)=>{
// res.render("shop/product-list",{prods:data,path:"/products",pageTitle:"MyShop"});
// })
//following will send file
//res.sendfile need absolute path so with the help of path module we can do path join
// res.sendFile(path.join(rootDir, 'views','shop.html'))
///below method use to render page with set default view engine so here its with ejs
//res.render("shop",{prods:productData,path:"/shop",pageTitle:"MyShop"});
//using DB
// Product.fetchAll()
// .then(data=>{
// res.render("shop/product-list",{prods:data,path:"/products",pageTitle:"MyShop"});
// })
// .catch(err=>{
// console.log(err);
// })
//using mongoose
Products.find()
.then(data=>{
res.render("shop/product-list",{prods:data,path:"/products",pageTitle:"MyShop",isAuthenticated:req.session.isloggedin});
})
.catch(err=>{
console.log(err);
})
}
exports.getSingleProduct= (req,res,next)=>{
const prodID= req.params.productId;
console.log("productID",prodID);
Products.findById({_id: new ObjectID(prodID)})
.then((data)=>{
res.render("shop/product-detail",{product:data,path:"/products",pageTitle:"MyShop",isAuthenticated:req.session.isloggedin});
})
.catch(err=>{
console.log(err);
})
}
exports.getIndex=(req,res,next)=>{
// Product.fetchAll((data)=>{
// res.render("shop/index",{prods:data,path:"/shop",pageTitle:"MyShop"});
// })
//using DB
// Product.fetchAll()
// .then(data=>{
// res.render("shop/index",{prods:data,path:"/shop",pageTitle:"MyShop"});
// })
// .catch(err=>{
// console.log(err);
// })
//using mongoose
Products.find()
.then(data=>{
res.render("shop/index",{prods:data,path:"/shop",pageTitle:"MyShop",isAuthenticated:req.session.isloggedin});
})
.catch(err=>{
console.log(err);
})
}
exports.getCart=(req,res,next)=>{
// Cart.getCart(cart=>{
// Product.fetchAll((data)=>{
// const cartProduct=[]
// for(product of data ){
// const cartProductData= cart.products.find(p=>p.id===product.id);
// if(cartProductData){
// cartProduct.push({productData:product,qty:cartProductData.qty});
// }
// }
// res.render("shop/cart",{prods:data,path:"/cart",pageTitle:"Your Cart",products:cartProduct});
// })
// })
req.user.getCart()
.then(data=>{
res.render('shop/cart',{path:'/cart',pageTitle:'Your Cart',products:data.cart.items,isAuthenticated:req.session.isloggedin})
})
}
exports.postCart=(req,res,next)=>{
const prodId=req.body.productId;
// Product.finById(prodId,(prodData)=>{
// Cart.addProduct(prodId,prodData.price)
// })
Products.findById(prodId)
.then(prodData=>{
return req.user.addToCart(prodData)
})
.then(result=>{
res.redirect('/cart');
})
.catch(err=>{console.log(err)})
// res.redirect('/cart');
}
exports.postCartDeleteProduct=(req,res,next)=>{
const prodId=req.body.productId;
console.log(prodId);
// if(prodId){
// Product.finById(prodId,(prodData)=>{
// Cart.deleteProduct(prodId,prodData.price);
// res.redirect('/cart');
// })
// }
// else{
// throw 'Product Not found';
// }
req.user.deleteItemFromCart(prodId)
.then(result=>{
res.redirect('/cart');
})
.catch(err=>{
console.log(err);
})
}
exports.getOrders=(req,res,next)=>{
// Product.fetchAll((data)=>{
// res.render("shop/orders",{prods:data,path:"/orders",pageTitle:"Your orders"});
// })
// req.user.getOrders()
// .then(data=>{
// console.log(data);
// res.render("shop/orders",{orders:data,path:"/orders",pageTitle:"Your orders"});
// })
//by mongoose
Orders.find({"user.userId":req.user._id})
.then(data=>{
res.render("shop/orders",{orders:data,path:"/orders",pageTitle:"Your orders",isAuthenticated:req.session.isloggedin});
})
.catch(err=>{
console.log(err);
})
}
exports.postOrders=(req,res,next)=>{
req.user.getCart()
.then(result=>{
const products=result.cart.items.map(p=>{
return {quantity:p.quantity,product:{...p.productId._doc}} ///._doc to get data and not meta data here we need all produ data like title,des,price so that we can create obj using spred and only get _doc obj which has only data and not metadaa to be store
});
const order= new Order(
{
user:{
userId:req.user
},
products:products
}
)
return order.save();
})
.then(result=>{
return req.user.clearCart();
})
.then(()=>{
res.redirect('/orders');
})
.catch(err=>{
console.log(err);
})
}
exports.getCheckout=(req,res,next)=>{
Product.fetchAll((data)=>{
res.render("shop/checkout",{prods:data,path:"/checkout",pageTitle:"Checkout",isAuthenticated:req.session.isloggedin});
})
}
|
a1a6b69f5a040abd48df7d3acd1090638998c8c1
|
[
"JavaScript"
] | 9
|
JavaScript
|
rahulgarale/shopping-website
|
a037b5403da23b1506df3bb7811e28cb5d7c215e
|
9af082bfda46000adebc28cdb27994cb1941ee9a
|
refs/heads/master
|
<file_sep># Projeto
Projeto - PHP/MySQL
# SitePHP
<file_sep><?php
require('config.php');
$nome = $_POST['nome'];
$assu = $_POST['assunto'];
$tel = $_POST['tele'];
$email = $_POST['email'];
$msg = $_POST['mensagem'];
$sql = "INSERT INTO contato (nome,assunto,telefone,email,mensagem) VALUES ('".$nome."','".$assu."','".$tel."','".$email."','".$msg."');";
$query = mysqli_query($conexao, $sql);
if ($query) {
echo "<script>alert('enviado com sucesso');
location.href = 'index.html';
</script>";
//enviando mensagem direta para outros quem conecta
$mensagem = "
<h3>Loja Fashe</h3>
<p>
<b>".$nome."</b>, recebemos seu email, logo entraremos em contato
</p>
";
$headers[] = 'MIME-Version: 1.0';
$headers[] = 'Content-type: text/html; charset=utf8';
mail($to,"Formulario de Contato",$mensagem,$headers);
}
?>
<file_sep><?php
require('config.php');
$sql = "SELECT¨* FROM notificacao WHERE status = 0";
$query = mysqli_query($conexao, $sql);
$notify = mysql_num_rows();_
?><file_sep>-- phpMyAdmin SQL Dump
-- version 4.7.4
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: 09-Set-2018 às 16:55
-- Versão do servidor: 10.1.30-MariaDB
-- PHP Version: 7.2.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: `site_personalizado`
--
-- --------------------------------------------------------
--
-- Estrutura da tabela `contato`
--
CREATE TABLE `contato` (
`id` int(11) NOT NULL,
`nome` varchar(100) NOT NULL,
`assunto` varchar(100) NOT NULL,
`telefone` int(12) NOT NULL,
`email` varchar(100) NOT NULL,
`mensagem` text NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Extraindo dados da tabela `contato`
--
INSERT INTO `contato` (`id`, `nome`, `assunto`, `telefone`, `email`, `mensagem`) VALUES
(4, 'valeria', 'meu nome', 1234565433, '<EMAIL>', '<NAME>'),
(5, '<NAME>', 'meu nomedfghytrfedscxv', 2147483647, '<EMAIL>', 'asdfghfds'),
(7, '<NAME>', 'meu nome', 12345678, '<EMAIL>', '<PASSWORD>');
-- --------------------------------------------------------
--
-- Estrutura da tabela `notificacao`
--
CREATE TABLE `notificacao` (
`id` int(11) NOT NULL,
`id_contato` int(11) NOT NULL,
`status` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Extraindo dados da tabela `notificacao`
--
INSERT INTO `notificacao` (`id`, `id_contato`, `status`) VALUES
(1, 1, 0),
(2, 2, 0);
-- --------------------------------------------------------
--
-- Estrutura da tabela `users_admin`
--
CREATE TABLE `users_admin` (
`id` int(11) NOT NULL,
`nome` int(11) NOT NULL,
`usuario` varchar(50) NOT NULL,
`senha` varchar(30) NOT NULL,
`email` varchar(50) NOT NULL,
`urlImg` varchar(36) NOT NULL,
`nivel` enum('0','1') NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Indexes for dumped tables
--
--
-- Indexes for table `contato`
--
ALTER TABLE `contato`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `notificacao`
--
ALTER TABLE `notificacao`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `users_admin`
--
ALTER TABLE `users_admin`
ADD PRIMARY KEY (`nome`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `contato`
--
ALTER TABLE `contato`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=8;
--
-- AUTO_INCREMENT for table `notificacao`
--
ALTER TABLE `notificacao`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;
--
-- AUTO_INCREMENT for table `users_admin`
--
ALTER TABLE `users_admin`
MODIFY `nome` int(11) NOT NULL AUTO_INCREMENT;
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 */;
|
8a15a40f63749e16764985927175a4564514cf18
|
[
"Markdown",
"SQL",
"PHP"
] | 4
|
Markdown
|
Valeria-Marques/SitePHP
|
cc7757b8faa2b278b4b3c410fab544583b2ca886
|
173e14e8b182e4119288fcf38191c4df0a91a094
|
refs/heads/master
|
<repo_name>berezovskyi/lambda-test-node<file_sep>/main.js
console.log('Loading function');
var doc = require('dynamodb-doc');
var dynamo = new doc.DynamoDB();
/**
* Provide an event that contains the following keys:
*
* - operation: one of the operations in the switch statement below
* - tableName: required for operations that interact with DynamoDB
* - payload: a parameter to pass to the operation being performed
*/
exports.handler = function(event, context) {
//console.log('Received event:', JSON.stringify(event, null, 2));
var operation = event.operation;
if (event.tableName) {
event.payload.TableName = event.tableName;
}
switch (operation) {
case 'create':
var resp = dynamo.putItem(event.payload, context.done);
context.succeed("created");
break;
case 'read':
dynamo.getItem(event.payload, context.done);
break;
case 'update':
dynamo.updateItem(event.payload, context.done);
break;
case 'delete':
dynamo.deleteItem(event.payload, context.done);
break;
case 'list':
dynamo.scan(event.payload, context.done);
break;
case 'echo':
context.succeed(event.payload);
break;
case 'ping':
context.succeed('pong');
break;
default:
context.fail(new Error('Unrecognized operation "' + operation + '"'));
}
};
<file_sep>/README.md
# lambda-test-node
Node.js blueprint used in tests
|
1b891d850f0d304142446ec5b58de88eefffca3e
|
[
"JavaScript",
"Markdown"
] | 2
|
JavaScript
|
berezovskyi/lambda-test-node
|
4aee8706a2dc3cefdedf77ad7629c816f3b42171
|
aced7a31f2f4f6f7ca9324c1f6f036f8b6f11a3f
|
refs/heads/master
|
<repo_name>ibrahimuslu/udacity-p1<file_sep>/problem_1.py
class DoubleNode:
def __init__(self, key,value):
self.value = value
self.key = key
self.next = None
self.previous = None
class DoublyLinkedList:
def __init__(self):
self.head = None
self.tail = None
def append(self, value):
if self.head is None:
self.head = DoubleNode(value)
self.tail = self.head
return
self.tail.next = DoubleNode(value)
self.tail.next.previous = self.tail
self.tail = self.tail.next
return
def remove(self,node):
if(node.next != None):
node.next.previous = node.previous
else:
self.tail = node.previous
if(node.previous!=None):
node.previous.next = node.next
else:
self.head = node.next
def pushTop(self,node):
node.previous = None
node.next = self.head
if(self.head != None):
self.head.previous = node
self.head = node
if( self.tail == None):
self.tail = self.head
class LinkedListNode:
def __init__(self, key, value):
self.key = key
self.value = value
self.next = None
class HashMap:
def __init__(self, initial_size = 15):
self.bucket_array = [None for _ in range(initial_size)]
self.p = 31
self.num_entries = 0
self.load_factor = 0.7
def put(self, key, value):
bucket_index = self.get_bucket_index(key)
new_node = LinkedListNode(key, value)
head = self.bucket_array[bucket_index]
# check if key is already present in the map, and update it's value
while head is not None:
if head.key == key:
head.value = value
return
head = head.next
# key not found in the chain --> create a new entry and place it at the head of the chain
head = self.bucket_array[bucket_index]
new_node.next = head
self.bucket_array[bucket_index] = new_node
self.num_entries += 1
# check for load factor
current_load_factor = self.num_entries / len(self.bucket_array)
if current_load_factor > self.load_factor:
self.num_entries = 0
self._rehash()
def get(self, key):
bucket_index = self.get_hash_code(key)
head = self.bucket_array[bucket_index]
while head is not None:
if head.key == key:
return head.value
head = head.next
return None
def get_bucket_index(self, key):
bucket_index = self.get_hash_code(key)
return bucket_index
def get_hash_code(self, key):
key = str(key)
num_buckets = len(self.bucket_array)
current_coefficient = 1
hash_code = 0
for character in key:
hash_code += ord(character) * current_coefficient
hash_code = hash_code % num_buckets # compress hash_code
current_coefficient *= self.p
current_coefficient = current_coefficient % num_buckets # compress coefficient
return hash_code % num_buckets # one last compression before returning
def size(self):
return self.num_entries
def _rehash(self):
old_num_buckets = len(self.bucket_array)
old_bucket_array = self.bucket_array
num_buckets = 2 * old_num_buckets
self.bucket_array = [None for _ in range(num_buckets)]
for head in old_bucket_array:
while head is not None:
key = head.key
value = head.value
self.put(key, value) # we can use our put() method to rehash
head = head.next
def delete(self, key):
bucket_index = self.get_bucket_index(key)
head = self.bucket_array[bucket_index]
previous = None
while head is not None:
if head.key == key:
if previous is None:
self.bucket_array[bucket_index] = head.next
else:
previous.next = head.next
self.num_entries -= 1
return
else:
previous = head
head = head.next
class LRU_Cache(object):
def __init__(self, capacity):
# Initialize class variables
self.cache_memory = HashMap(capacity)
self.leastRecent = DoublyLinkedList()
self.num_entries = 0
self.capacity = capacity
def get(self, key):
returnNode = self.cache_memory.get(key)
if(returnNode != None):
self.leastRecent.remove(returnNode)
self.leastRecent.pushTop(returnNode)
return returnNode.value
return -1
def set(self,key,value):
newNode = self.cache_memory.get(key)
if(newNode == None):
newNode = DoubleNode(key,value)
# print("capacity ",self.capacity)
if(self.num_entries < self.capacity):
self.leastRecent.pushTop(newNode)
# print(self.leastRecent.tail.key)
else:
# print('delete')
# print(self.leastRecent.tail.key)
self.cache_memory.delete(self.leastRecent.tail.key)
self.num_entries-=1
self.leastRecent.remove(self.leastRecent.tail)
self.leastRecent.pushTop(newNode)
self.cache_memory.put(key,newNode)
self.num_entries+=1
# print("num_entries",self.num_entries);
## First test case
our_cache = LRU_Cache(5)
# print("num_entries",our_cache.num_entries);
our_cache.set(1, 1)
our_cache.set(2, 2)
our_cache.set(3, 3)
our_cache.set(4, 4)
print(our_cache.get(1)) # returns 1
print(our_cache.get(2) ) # returns 2
print(our_cache.get(9) ) # returns -1 because 9 is not present in the cache
our_cache.set(5, 5)
our_cache.set(6, 6)
print(our_cache.get(3)) # returns -1 because the cache reached it's capacity and 3 was the least recently used entry
## Second test case
second_cache = LRU_Cache(1000)
# print("num_entries",our_cache.num_entries);
for i in range(1000):
second_cache.set(i, i)
print(second_cache.get(1)) # returns 1
print(second_cache.get(202) ) # returns 2
print(second_cache.get(1002) ) # returns -1 because 9 is not present in the cache
second_cache.set(123, 523)
second_cache.set(1001, 123)
print(second_cache.get(2)) # returns -1 because the cache reached it's capacity and 2 was the least recently used entry
## Third test case
third_cache = LRU_Cache(10000)
# print("num_entries",our_cache.num_entries);
for i in range(10000):
third_cache.set(i, i)
print(third_cache.get(1)) # returns 1
print(third_cache.get(2022) ) # returns 2
print(third_cache.get(10002) ) # returns -1 because 9 is not present in the cache
third_cache.set(123, 5233)
third_cache.set(10001, 1231)
print(our_cache.get(3)) # returns -1 because the cache reached it's capacity and 2 was the least recently used entry
<file_sep>/problem_5.py
import hashlib
from datetime import datetime
class Block:
def __init__(self,data):
self.timestamp = datetime.timestamp(datetime.now())
self.data = data
self.previous_hash = 0
self.hash = self.calc_hash(data)
self.next = None
def calc_hash(self,data):
sha = hashlib.sha256()
hash_str = (str(self.previous_hash)+str(data)+str(self.timestamp)).encode('utf-8')
sha.update(hash_str)
return sha.hexdigest()
class Blockchain:
def __init__(self):
self.head = None
def __str__(self):
cur_head = self.head
out_string = ""
while cur_head:
out_string += str(cur_head.hash)+":"+str(cur_head.data) + " -> "
cur_head = cur_head.next
return out_string
def size(self):
size = 0
node = self.head
while node:
size += 1
node = node.next
return size
def append(self, data):
if self.head is None:
self.head = Block(data)
return
block = Block(data)
block.previous_hash = self.head.hash
block.next = self.head
self.head = block
bc = Blockchain()
bc.append("selam")
bc.append("hi")
bc.append("hola")
print(bc)
bc1 = Blockchain()
bc1.append("wonder")
bc1.append("land")
bc1.append("never")
print(bc1)
bc2 = Blockchain()
bc2.append("covid")
bc2.append("hide")
bc2.append("blood")
print(bc2)<file_sep>/explanation_4.md
1. Time complexity analysis of finding if the user in group
- its independent from the given parameters number of times and it is only dependent of the group depth so it is in O(1) complexity
2. Space complexity analysis of finding if the user in group
- the same and not dependent on the parameters given but to fixed number of depth of the groups<file_sep>/README.md
# udacity-p1
Data Structures and Algorithms Project 1
<file_sep>/problem_6.py
class Node:
def __init__(self, value):
self.value = value
self.next = None
def __repr__(self):
return str(self.value)
class LinkedList:
def __init__(self):
self.head = None
def __str__(self):
cur_head = self.head
out_string = ""
while cur_head:
out_string += str(cur_head.value) + " -> "
cur_head = cur_head.next
return out_string
def append(self, value):
if self.head is None:
self.head = Node(value)
return
node = self.head
while node.next:
node = node.next
node.next = Node(value)
def size(self):
size = 0
node = self.head
while node:
size += 1
node = node.next
return size
def union(llist_1, llist_2):
uniList = set()
node = llist_1.head
while node:
uniList.add(node)
node = node.next
node = llist_2.head
while node:
uniList.add(node)
node = node.next
return uniList
def intersection(llist_1, llist_2):
intersectList = set()
newSecond = LinkedList()
node = llist_1.head
while node:
innode = llist_2.head
previous = None
while innode:
#print(node.value, innode.value, node.value==innode.value)
if node.value == innode.value:
intersectList.add(node)
#print(node.value, innode.value,intersectList)
if previous:
previous.next = innode.next
else:
llist_2.head = innode.next
#print(llist_2)
previous = innode
innode = innode.next
node = node.next
return intersectList
# Test case 1
linked_list_1 = LinkedList()
linked_list_2 = LinkedList()
element_1 = [3,2,4,35,6,65,6,4,3,21]
element_2 = [6,32,4,9,6,1,11,21,1]
for i in element_1:
linked_list_1.append(i)
for i in element_2:
linked_list_2.append(i)
print()
print(linked_list_1)
print(linked_list_2)
print()
print ('union', union(linked_list_1,linked_list_2))
print ('intersection', intersection(linked_list_1,linked_list_2))
# Test case 2
linked_list_3 = LinkedList()
linked_list_4 = LinkedList()
element_1 = [3,2,4,35,6,65,6,4,3,23]
element_2 = [1,7,8,9,11,21,1]
for i in element_1:
linked_list_3.append(i)
for i in element_2:
linked_list_4.append(i)
print()
print(linked_list_3)
print(linked_list_4)
print()
print ('union', union(linked_list_3,linked_list_4))
print ('intersection', intersection(linked_list_3,linked_list_4))
# Test case 3
linked_list_6 = LinkedList()
linked_list_7 = LinkedList()
element_1 = [1,1,1,1,1,1,1,1]
element_2 = [1,7,8,9,11,21,1]
for i in element_1:
linked_list_6.append(i)
for i in element_2:
linked_list_7.append(i)
print()
print(linked_list_6)
print(linked_list_7)
print()
print ('union', union(linked_list_6,linked_list_7))
print ('intersection', intersection(linked_list_6,linked_list_7))
<file_sep>/problem_3.py
import sys
from collections import deque
class Queue():
def __init__(self):
self.q = deque()
def enq(self,value):
self.q.appendleft(value)
def deq(self):
if len(self.q) > 0:
return self.q.pop()
else:
return None
def __len__(self):
return len(self.q)
def __repr__(self):
if len(self.q) > 0:
s = "<enqueue here>\n_________________\n"
s += "\n_________________\n".join([str(item) for item in self.q])
s += "\n_________________\n<dequeue here>"
return s
else:
return "<queue is empty>"
class Node(object):
def __init__(self,value = None,p=0):
self.value = value
self.priority = p
self.left = None
self.right = None
def set_value(self,value):
self.value = value
def get_value(self):
return self.value
def get_priority(self):
return self.priority
def set_left_child(self,left):
self.left = left
def set_right_child(self, right):
self.right = right
def get_left_child(self):
return self.left
def get_right_child(self):
return self.right
def has_left_child(self):
return self.left != None
def has_right_child(self):
return self.right != None
# define __repr_ to decide what a print statement displays for a Node object
def __repr__(self):
return f"Node({self.get_value()}:{self.get_priority()})"
def __str__(self):
return f"Node({self.get_value()}:{self.get_priority()})"
class Tree():
def __init__(self, value=None):
self.root = Node(value)
def get_root(self):
return self.root
def set_root(self,node):
self.root = node
def __repr__(self):
level = 0
q = Queue()
visit_order = list()
node = self.get_root()
q.enq( (node,level) )
while(len(q) > 0):
node, level = q.deq()
if node == None:
visit_order.append( ("<empty>", level))
continue
visit_order.append( (node, level) )
if node.has_left_child():
q.enq( (node.get_left_child(), level +1 ))
else:
q.enq( (None, level +1) )
if node.has_right_child():
q.enq( (node.get_right_child(), level +1 ))
else:
q.enq( (None, level +1) )
s = "Tree\n"
previous_level = -1
for i in range(len(visit_order)):
node, level = visit_order[i]
if level == previous_level:
s += " | " + str(node)
else:
s += "\n" + str(node)
previous_level = level
return s
def huffman_tree(data):
freq = dict()
for c in data:
freq[c] = freq.get(c,0)+1
queue = Queue()
for f in sorted(freq, key=freq.get):
queue.enq(Node(f,freq[f]))
while len(queue)>1:
node_left = queue.deq()
node_right = queue.deq()
new = Node(None,node_left.priority+node_right.priority)
new.set_left_child(node_left)
new.set_right_child(node_right)
queue.enq(new)
huffTree = Tree()
huffTree.set_root(queue.deq())
return huffTree
def huffman_encoding(data):
tree = huffman_tree(data)
str = ''
huffmanCode = dict()
huffman_encoder(tree.get_root(),str,huffmanCode)
encoded_data = ''
for c in data:
encoded_data = encoded_data + huffmanCode[c]
# print(huffmanCode)
return encoded_data, tree
def huffman_encoder(root, str, huffmanCode):
if (root is None):
return
if (root.get_left_child() is None and root.get_right_child() is None):
huffmanCode[root.value] = str
huffman_encoder(root.get_left_child(),str+'0',huffmanCode)
huffman_encoder(root.get_right_child(),str+'1',huffmanCode)
def huffman_decoder(root,str,index):
if (root is None):
return '', index
if (root.get_left_child() is None and root.get_right_child() is None):
return root.get_value(), index
index = index+1
if(str[index]=='0'):
return huffman_decoder(root.get_left_child(),str,index)
elif(str[index]=='1'):
return huffman_decoder(root.get_right_child(),str,index)
def huffman_decoding(data,tree):
decoded_data = ''
index = -1
while (index < len(data)-1):
root = tree.get_root()
d,index = huffman_decoder(root,data,index)
decoded_data = decoded_data+d
return decoded_data
def test_case(a_great_sentence):
print ("The size of the data is: {}\n".format(sys.getsizeof(a_great_sentence)))
print ("The content of the data is: {}\n".format(a_great_sentence))
encoded_data, tree = huffman_encoding(a_great_sentence)
print ("The size of the encoded data is: {}\n".format(sys.getsizeof(int(encoded_data, base=2))))
print ("The content of the encoded data is: {}\n".format(encoded_data))
decoded_data = huffman_decoding(encoded_data, tree)
print ("The size of the decoded data is: {}\n".format(sys.getsizeof(decoded_data)))
print ("The content of the encoded data is: {}\n".format(decoded_data))
a_great_sentences = ["The bird is the word", "abcdefghijklmnopqrstuvyz", "Udacity is the number one platform for learning"]
for a in a_great_sentences:
test_case(a)<file_sep>/explanation_5.md
This problem also make me very delightfull because of blockchain was very complex thing for me before and I understand now that it is very simple
1. Time complexity analysis of Blockchain
- append to blockchain is O(1) except with the cyrptography algorithm we used in the chain since it is only a special linkedlist
2. Space complexity analysis of Blockchain
- with data itself there is 256 bit hash data and timestamp information is occupy space A(3n)<file_sep>/explanation_3.md
I would like to emphasize that the most educative problem is this one. I really enjoyed while trying to solve this. I have used almost all data structures learned in this problem
1. The complexity analysis of Huffman Encoding
- encoding algorithm is starting with creating a huffman tree. The tree algorithm has O(n) complexity
after that the algorithm is going through each char in the given string and finds the binary representation of huffman code so it O(n*n/2) because max depth of huffman tree is n/2
- decoding algorithm need the huffman tree created before and so no need to create again but decoding still needs to loop over the string given and need loop over the tree so it is O(n*n/2)
2. space complexity analysis of Huffman algorithm
- tree queue used for the algorithm. A(n)<file_sep>/explanation_1.md
1. Time complexity analysis of LRU Cache algorithm
- Write in cache is O(n) because of searching if the key is exist in the Linked List data structure which is used for finding Least Recent Used item
- However read from cache is O(1)
2. Space complexity analysis of LRU Cache algorithm
Spaced used for Map is determined and Linked List data structure is also using extra memory for creating an efficient cache algorithm. But the space is determined so it is A(1)<file_sep>/explanation_6.md
1. The complexity analysis of Union and Intersect
- Union time complexity is O(2n)
- Intersect time complexity is O(n^2)<file_sep>/problem_2.py
import os
def find_files(suffix, path):
"""
Find all files beneath path with file name suffix.
Note that a path may contain further subdirectories
and those subdirectories may also contain further subdirectories.
There are no limit to the depth of the subdirectories can be.
Args:
suffix(str): suffix if the file name to be found
path(str): path of the file system
Returns:
a list of paths
"""
cList = []
return recurFindFiles(suffix,path,cList)
def recurFindFiles (suffix,path,cList):
# print(path,os.path.isdir(path))
if(os.path.isdir(path)):
# print(os.listdir(path))
for f in os.listdir(path):
# print(f,os.path.isdir(path+"/"+f))
if(os.path.isdir(path+"/"+f)):
# print(os.listdir(path+"/"+f))
recurFindFiles(suffix,(path+"/"+f),cList)
# print(f,f.endswith(suffix))
if (f.endswith(suffix) and os.path.isfile(path+"/"+f)):
cList.append(f)
return cList
print(find_files('.c','testdir'))
print(find_files('.h','testdir'))
print(find_files('..','testdir'))<file_sep>/explanation_2.md
1. Time complexity analysis of finding files in a directory
- If we take n as the directory number parameter then the complexity is n times(*) - since the algorithm visits every directory once and because of using systems find function omitting that - max depth(md) of the folders and the all file number(fn) of whole folders so it is sth O(n*md*fd)
2. Space complexity analysis of finding files in a directory
- the max depth of the recursion and the found files name size A(nd)
|
9ca68acda64db0a6d3790facbcc1dec5630d5579
|
[
"Markdown",
"Python"
] | 12
|
Python
|
ibrahimuslu/udacity-p1
|
543494e7ec13e3e6fb717255faa14758cb83bdf1
|
ed2f6de275299a2a13458cee8eda5ad4598f4043
|
refs/heads/master
|
<file_sep># Jeffrey's WebDev Portfolio *featuring React*
### <NAME>
UW Full Stack BootCamp
Week 20 Homework: React Portfolio Update
[<NAME>'s WebDev Portfolio](https://jeffreyadamo.github.io/ReactPortfolio/)
July 20, 2020
<img src="./src/utils/images/index.png" height="300">
## Objective
Here's a showcase of my web development portfolio with projects and homework assignments completed while enrolled in **UW's Full Stack Web Developemnt boot camp**. This is the *third* iteration of portfolios during this course. This version features **ReactJS** design and was initiated in week 20. The previous version was in week 8 using Materialize CSS framework, JavaScript and JQuery. A simple portfolio was also created in week 2 where HTML and CSS were the only languages introduced.
This portfolio features updates to the following:
* [Porfolio](#)
* [GitHub Profile](https://github.com/jeffreyadamo)
* [Resume](https://drive.google.com/file/d/1aIuHTJ-yNRtMZkgQxSn8pqImSvtq8YX_/view?usp=sharing)
* [LinkedIn Profile](https://www.linkedin.com/in/jeffadamo)
## Portfolio Features:
### Designed using [React](#)
Multiple CSS Frameworks utilized for portfolio items include:
* *This portfolio* uses [MaterializeCSS](https://materializecss.com/) framework
* Week 7 Group Project: Pandemic Pantry used [ZURB Foundation](https://get.foundation/sites/docs/)
* Weel 6: Weather Dashboard & Work Day Scheduler used [BootstrapCDN](https://getbootstrap.com/docs/4.4/getting-started/introduction/)
## Demo:
<img src="./src/utils/images/portfolio.gif" height="300">
* Mobile-first design. Links collapse into a hamburger (as seen on Iphone6):
### Portfolio.html
User is greeted with cards containing information on featured projects. Image of landing page is displayed with title and links to GitHub Pages and GitHub Repository. The cards can be clicked on to display more information on the back of the card. A demo button allows the user to see a .gif previewing the interaction of the website in a modal.
### Contact.html
User is greeted with same landing as index.html, but with a few more details describing that the images are clickable links that direct toward GitHub Profile, LinkedIn Profile, and email using "mailto:<EMAIL>". There is also an link to my resume hosted on Google Drive:
### Aboutme.html
User is greeted with some content about myself. Below is displayed on an iPad and shows the hamburger's usage and how by clicking on my name on the navbar, the user will be directed back to index.html.
## Issues/Future Development:
I would like to see a message form in /contact for direct email commenting
<img src="./src/utils/images/contactIssue.png" height="300"><file_sep>self.__precacheManifest = (self.__precacheManifest || []).concat([
{
"revision": "<KEY>cdb<KEY>",
"url": "/ReactPortfolio/index.html"
},
{
"revision": "3425936af6ea3f8f1ed2",
"url": "/ReactPortfolio/static/css/main.c307d49c.chunk.css"
},
{
"revision": "08875cff905fa422f832",
"url": "/ReactPortfolio/static/js/2.aa39f4ee.chunk.js"
},
{
"revision": "d8b4173f7a8b6c66c369ccd5944b6a3e",
"url": "/ReactPortfolio/static/js/2.aa39f4ee.chunk.js.LICENSE.txt"
},
{
"revision": "3425936af6ea3f8f1ed2",
"url": "/ReactPortfolio/static/js/main.adc6427e.chunk.js"
},
{
"revision": "97a1c7d0b592075495b7",
"url": "/ReactPortfolio/static/js/runtime-main.ad87311a.js"
},
{
"revision": "c33b36cc2e7ddd4584232fd14c04543a",
"url": "/ReactPortfolio/static/media/PandemicPantry.c33b36cc.png"
},
{
"revision": "0e2412ac0b7ab42426ee721b85ceae46",
"url": "/ReactPortfolio/static/media/WorkDay2.0e2412ac.gif"
},
{
"revision": "e834c2dc2c170981bbc014801eca8b35",
"url": "/ReactPortfolio/static/media/bioImage.e834c2dc.JPG"
},
{
"revision": "445ed0cdec3805ad9b4ba6fe8f3cddd2",
"url": "/ReactPortfolio/static/media/burgerDemo.445ed0cd.gif"
},
{
"revision": "349d4c9f0f3e74b09273f623686da695",
"url": "/ReactPortfolio/static/media/burgerHome.349d4c9f.png"
},
{
"revision": "9d399fcb8a19d13430415061a015a6ad",
"url": "/ReactPortfolio/static/media/employeeTracker.9d399fcb.png"
},
{
"revision": "66cc5ad5f048f4460a8054bfda8d5829",
"url": "/ReactPortfolio/static/media/employeeTrackerDemo.66cc5ad5.gif"
},
{
"revision": "c614347ab1c7c0ae96b267c57f666aef",
"url": "/ReactPortfolio/static/media/full-bloom.c614347a.png"
},
{
"revision": "e1edf6e4802a86f436223d96a9ad8c91",
"url": "/ReactPortfolio/static/media/gmail_logo_PNG5.e1edf6e4.png"
},
{
"revision": "139b1d88f105d3f23a22beae5004b373",
"url": "/ReactPortfolio/static/media/pandemicPantry.139b1d88.gif"
},
{
"revision": "ff749590123ed89ee10648d5b40e53a5",
"url": "/ReactPortfolio/static/media/travEx.ff749590.png"
},
{
"revision": "9364b9faf07d8015356aed66adf75dd5",
"url": "/ReactPortfolio/static/media/travExDemo.9364b9fa.gif"
},
{
"revision": "5339574716e3de66de204ea849ab1566",
"url": "/ReactPortfolio/static/media/weatherDashboard.53395747.png"
},
{
"revision": "8035939c27fd3118698e21c199ee223a",
"url": "/ReactPortfolio/static/media/weatherDashboard.8035939c.gif"
},
{
"revision": "7e6b424df9e10861a20e1f5ab353a163",
"url": "/ReactPortfolio/static/media/workDay.7e6b424d.png"
}
]);
|
7a0d4b945ef54d88d0d9ec0744e7fd0df40fe5ec
|
[
"Markdown",
"JavaScript"
] | 2
|
Markdown
|
jeffreyadamo/ReactPortfolio
|
4621f45c8373cc4563f11fd9e93f6cfe5b6aec0d
|
d4bc51a74c67e531671a8545b41dde7dfb9a4196
|
refs/heads/master
|
<repo_name>misakilou/formationsf<file_sep>/src/Command/PromoteAdmin.php
<?php
namespace App\Command;
use App\Entity\User;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
class PromoteAdmin extends Command
{
private $em;
protected static $defaultName = "user:make:admin";
public function __construct(EntityManagerInterface $em)
{
$this->em = $em;
parent::__construct();
}
protected function configure()
{
$this
->setDescription('Promote a user to role Admin')
->addOption(
'user',
'u',
InputOption::VALUE_REQUIRED,
'user mail '
)
;
}
protected function execute(InputInterface $input , OutputInterface $output){
try{
$userEmail = $input->getOption('user');
/** @var User $user */
$user = $this->em->getRepository(User::class)->findOneBy([
'email' => $userEmail
]);
if(!$user){
$output->writeln("<bg=red>impossible de trouver l'utilisateur</>");
return Command::SUCCESS;
}
$user->setRoles([
'ROLE_ADMIN'
]);
$this->em->persist($user);
$this->em->flush();
$output->writeln("<bg=blue>Utilisateur $userEmail a bien été promu <fg=green>ADMIN</></>");
return Command::SUCCESS;
}
catch(\Exception $e){
return Command::FAILURE;
}
}
}<file_sep>/src/Form/ArticleCreationFormType.php
<?php
namespace App\Form;
use App\Entity\Article;
use App\Entity\Author;
use App\Entity\Categorys;
use Doctrine\ORM\EntityRepository;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
class ArticleCreationFormType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('categorys' , EntityType::class, [
'class' => Categorys::class,
'choice_label' => 'title',
'multiple' => true,
'expanded' => true,
'query_builder' => function(EntityRepository $er)
{
return $er->createQueryBuilder("c")
->orderBy('c.title' ,'asc');
},
])
->add('currency', ChoiceType::class, [
'multiple' => false,
'choices' => [
'EUR' => "EUR",
'USD' => "USD",
],
])
->add('amount')
->add('title')
->add('content')
->add('author', EntityType::class,[
'class' => Author::class,
'choice_label' => 'fullname',
'query_builder' => function(EntityRepository $er)
{
return $er->createQueryBuilder("a")
->orderBy('a.LastName , a.firstName', 'asc');
},
])
->add('Valider', SubmitType::class)
;
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => Article::class,
]);
}
}
<file_sep>/src/Twig/DisplayCurrencyExtension.php
<?php
namespace App\Twig;
use Twig\Extension\AbstractExtension;
use Twig\TwigFilter;
class DisplayCurrencyExtension extends AbstractExtension
{
public function getFilters()
{
return [
new TwigFilter('displayCurrencyFormatter', [$this , 'displayCurrency']) ,
];
}
public function displayCurrency($amount, $currencySymbol = null)
{
if($currencySymbol){
return number_format($amount, 2 , " $currencySymbol ", ' ');
}
return number_format($amount, 2 , '.', ' ');
}
}<file_sep>/src/Service/ConvertCurrencyService.php
<?php
namespace App\Service;
use App\Entity\CurrencyRate;
use App\Repository\CurrencyRateRepository;
use Doctrine\ORM\EntityManagerInterface;
use PHPUnit\Util\Exception;
class ConvertCurrencyService
{
private $em;
private $rate;
public function __construct(EntityManagerInterface $em)
{
$this->em = $em;
}
/**
* @param $fromCurrency
* @param $toCurrency
* @return object
*/
public function getRate($fromCurrency , $toCurrency){
if($this->rate !== null){
return $this->rate ;
}
if($fromCurrency == $toCurrency){
$this->rate = 1;
return $this->rate;
}
$rateRecord = $this->em->getRepository(CurrencyRate::class)->findOneBy(
[
"fromCurrency" => $fromCurrency,
'toCurrency' => $toCurrency,
],
[
'validityDate' => 'desc'
]
);
if(!$rateRecord){
throw new \Exception('IDK this currency');
}
$this->rate = $rateRecord->getRate();
return $this->rate ;
}
public function checkRate($rate , $fromCurrency, $toCurrency){
$currentRate = $this->getRate($fromCurrency , $toCurrency);
if($rate === $currentRate)
{
return true ;
}
//FIXME: CheckPreviousRate pour checker une fois
/** @var CurrencyRateRepository $repo */
$repo = $this->em->getRepository(CurrencyRate::class);
try{
$previousRate = $repo->getPreviousRate();
}
catch(\Exception $e){
return false;
}
if($rate === $previousRate){
return true;
}
return false;
}
public function convert($amount , $fromCurrency , $toCurrency)
{
return $amount * $this->getRate($fromCurrency , $toCurrency);
}
public function storeCurrencyPairRates(string $fromCurrency , string $toCurrency, $rate, \DateTime $date){
$currencyRate = new CurrencyRate();
$currencyRate->setFromCurrency($fromCurrency);
$currencyRate->setToCurrency($toCurrency);
$currencyRate->setRate($rate);
$currencyRate->setValidityDate($date);
$this->em->persist($currencyRate);
$this->em->flush();
}
}<file_sep>/public/js/ajaxRemove.js
$(function(){
$('.ajax-remove-trigger').click(function(e){
let path = $(this).attr('data-path');
e.preventDefault();
$.ajax({
url: path,
type: "GET",
dataType: "json",
success: function(data)
{
if(data.success)
{
$(this).fadeOut('slow' , function(){
$(this).parents(".removable-element").remove();
});
}
else if(data.message){
alert(data.message);
}
}.bind(this)
});
});
});<file_sep>/src/Controller/PaymentController.php
<?php
namespace App\Controller;
use App\Entity\User;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
class PaymentController extends AbstractController
{
public function creditAccount(Request $request){
$this->denyAccessUnlessGranted('ROLE_USER');
$amount = $request->request->get('amount');
if($amount !== null && $amount > 0)
{
/** @var User $user */
$user = $this->getUser();
$amount = $user->incrementBalance($amount);
$em = $this->getDoctrine()->getManager();
$em->persist($user);
$em->flush();
return $this->redirectToRoute('monblog_home');
}
return $this->render('payment/credit.html.twig');
}
}<file_sep>/tests/Service/CalculatorServiceTest.php
<?php
namespace App\Tests\Service;
use App\Service\CalculatorService;
use PHPUnit\Framework\TestCase;
class CalculatorServiceTest extends TestCase
{
public function testAdd(){
$calculator = new CalculatorService();
$result = $calculator->add(5,10);
$this->assertEquals(15, $result);
}
}<file_sep>/src/EventListener/UpdateArticlePriceListener.php
<?php
namespace App\EventListener;
use App\Entity\Article;
use App\Service\Notificator;
use Doctrine\ORM\Event\PreUpdateEventArgs;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Mercure\PublisherInterface;
use Symfony\Component\Mercure\Update;
class UpdateArticlePriceListener
{
private $notificator;
public function __construct(Notificator $notificator)
{
$this->notificator = $notificator;
}
public function preUpdate(Article $article , PreUpdateEventArgs $args){
if(!$args->hasChangedField('amount'))
{
return;
}
$this->notificator->publicNotification('http://monblog/article-price' , ['id' => $article->getId() , 'newPrice' => $article->getAmount()]);
// $update = new Update(
// 'http://monblog/article-price',
// json_encode(
// [
// 'id' => $article->getId(),
// 'newPrice' => $article->getAmount(),
// ]
// )
// );
//
// // Sync, or async (RabbitMQ, Kafka...)
// $publisher = $this->publisher ;
// $publisher($update);
}
}<file_sep>/src/EventSubscriber/LogginSubscriber.php
<?php
namespace App\EventSubscriber;
use App\Entity\User;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\EntityManagerInterface;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
use Symfony\Component\Security\Http\SecurityEvents;
use Symfony\Component\Validator\Constraints\Date;
class LogginSubscriber implements EventSubscriberInterface
{
private $em;
public function __construct(EntityManagerInterface $em)
{
$this->em = $em;
}
public function onLogin(InteractiveLoginEvent $event){
/** @var User $user */
$user = $event->getAuthenticationToken()->getUser();
$user->setLastConnectionDate(new \DateTime('now'));
$this->em->persist($user);
$this->em->flush();
}
public static function getSubscribedEvents()
{
return [
SecurityEvents::INTERACTIVE_LOGIN =>
['onLogin', 0],
];
}
}<file_sep>/src/EventListener/UpdateArticleExplicitContentListener.php
<?php
namespace App\EventListener;
use App\Entity\Article;
use App\Service\ExplicitContentCheckerService;
use App\Service\MyLogger;
use Doctrine\ORM\Event\LifecycleEventArgs;
class UpdateArticleExplicitContentListener
{
private $logger;
private $explicitContentChecker;
public function __construct(MyLogger $logger, ExplicitContentCheckerService $explicitContentChecker)
{
$this->logger = $logger;
$this->explicitContentChecker = $explicitContentChecker;
}
public function postUpdate(Article $article , LifecycleEventArgs $event){
$content = $article->getContent();
if($this->explicitContentChecker->checkContent($content))
{
$this->logger->write('Warning !! dans '.$article->getTitle());
}
}
}<file_sep>/src/Form/AuthorCreationFormType.php
<?php
namespace App\Form;
use App\Entity\Author;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\DateType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
class AuthorCreationFormType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('title')
->add('firstName')
->add('LastName')
->add('birthDate', DateType::class, [
'format' => 'dd-MM-yyyy',
'years' => range(date_create()->format('Y') , date_create()->format('Y') - 120)
])
->add('biography')
->add('Sauvegarder', SubmitType::class)
;
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => Author::class,
]);
}
}
<file_sep>/src/Service/MyLogger.php
<?php
namespace App\Service;
class MyLogger
{
private $path;
public function __construct(string $logPath)
{
$this->path = $logPath;
}
public function write(string $str){
$handle = fopen($this->path , 'a');
$nowStr = date_create('now Europe/Paris')->format('Y/m/d H:i:s');
fwrite($handle , $nowStr.':');
fwrite($handle , $str.chr(10));
fclose($handle);
}
}<file_sep>/src/Twig/CurrencyConvertExtension.php
<?php
namespace App\Twig;
use App\Service\ConvertCurrencyService;
use Twig\Extension\AbstractExtension;
use Twig\TwigFilter;
class CurrencyConvertExtension extends AbstractExtension
{
private $converter;
public function __construct(ConvertCurrencyService $converter)
{
$this->converter = $converter;
}
public function getFilters()
{
return [
new TwigFilter('currencyConverter', [$this , 'displayConverter']) ,
];
}
public function displayConverter($amount , $fromCurrency , $toCurrency){
return $this->converter->convert($amount , $fromCurrency , $toCurrency);
}
}<file_sep>/src/Entity/Article.php
<?php
namespace App\Entity;
use App\Repository\ArticleRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity(repositoryClass=ArticleRepository::class)
*/
class Article
{
/**
* @ORM\Id()
* @ORM\GeneratedValue()
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\Column(type="datetime")
*/
private $creationDate;
/**
* @ORM\Column(type="datetime", nullable=true)
*/
private $lastUpdateDate;
/**
* @ORM\Column(type="string", length=255)
*/
private $title;
/**
* @ORM\Column(type="text")
*/
private $content;
/**
* @ORM\ManyToOne(targetEntity=Author::class, inversedBy="articles")
* @ORM\JoinColumn(nullable=true)
*/
private $author;
/**
* @ORM\ManyToMany(targetEntity=Categorys::class, inversedBy="articles")
*/
private $categorys;
/**
* @ORM\Column(type="decimal", precision=20, scale=6, nullable=true)
*/
private $amount;
/**
* @ORM\Column(type="string", length=3, nullable=true)
*/
private $currency;
public function __construct()
{
$this->categorys = new ArrayCollection();
$this->currency = 'EUR';
$this->amount = 1;
}
public function getId(): ?int
{
return $this->id;
}
public function getCreationDate(): ?\DateTimeInterface
{
return $this->creationDate;
}
public function setCreationDate(\DateTimeInterface $creationDate): self
{
$this->creationDate = $creationDate;
return $this;
}
public function getLastUpdateDate(): ?\DateTimeInterface
{
return $this->lastUpdateDate;
}
public function setLastUpdateDate(?\DateTimeInterface $lastUpdateDate): self
{
$this->lastUpdateDate = $lastUpdateDate;
return $this;
}
public function getTitle(): ?string
{
return $this->title;
}
public function setTitle(string $title): self
{
$this->title = $title;
return $this;
}
public function getContent(): ?string
{
return $this->content;
}
public function setContent(string $content): self
{
$this->content = $content;
return $this;
}
public function getAuthor(): ?Author
{
return $this->author;
}
public function setAuthor(?Author $author): self
{
$this->author = $author;
return $this;
}
/**
* @return Collection|Categorys[]
*/
public function getCategorys(): Collection
{
return $this->categorys;
}
public function addCategory(Categorys $category): self
{
if (!$this->categorys->contains($category)) {
$this->categorys[] = $category;
}
return $this;
}
public function removeCategory(Categorys $category): self
{
if ($this->categorys->contains($category)) {
$this->categorys->removeElement($category);
}
return $this;
}
public function getAmount(): ?string
{
return $this->amount;
}
public function setAmount(?string $amount): self
{
$this->amount = $amount;
return $this;
}
public function getCurrency(): ?string
{
return $this->currency;
}
public function setCurrency(?string $currency): self
{
$this->currency = $currency;
return $this;
}
}
<file_sep>/src/Command/CurrencyUpdaterCommand.php
<?php
namespace App\Command;
use App\Service\ConvertCurrencyService;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\HttpClient\HttpClient;
class CurrencyUpdaterCommand extends Command
{
private $apiKey;
private $baseUrl;
private $currencyConverter;
protected static $defaultName = "currency:grab";
public function __construct($apiKey , $baseUrl, ConvertCurrencyService $currencyConverter)
{
$this->apiKey = $apiKey;
$this->baseUrl = $baseUrl;
$this->currencyConverter = $currencyConverter;
parent::__construct();
}
protected function configure(){
$this
->setDescription('Grab the last currency rate and store in db');
}
public function execute(InputInterface $input , OutputInterface $output)
{
$output->writeln("start grabing currency rates...") ;
$start = microtime(true) ;
$endpoint = $this->baseUrl.'live';
$client = HttpClient::create();
$response = $client->request('GET', $endpoint ,[
'query' => [
'access_key' => $this->apiKey,
'currencies' => 'EUR',
],
]);
$apiResponse = $response->toArray();
$output->writeln(print_r($apiResponse));
$now = new \DateTime('now');
$rate = $apiResponse['quotes']['USDEUR'];
$this->currencyConverter->storeCurrencyPairRates('USD', 'EUR', $rate, $now);
$rate = 1 / $rate;
$this->currencyConverter->storeCurrencyPairRates('EUR', 'USD', $rate, $now);
$elapsed = microtime(true) - $start ;
$output->writeln("currency rates fetched and stored in $elapsed sec.") ;
return Command::SUCCESS;
}
}<file_sep>/src/Service/ExplicitContentCheckerService.php
<?php
namespace App\Service;
use App\Entity\Article;
class ExplicitContentCheckerService
{
private $banned_word = '<PASSWORD>';
/**
* @param $content
* @return bool
*/
public function checkContent($content)
{
return strpos(strtolower($content) , $this->banned_word) !== false ;
}
}<file_sep>/src/Twig/AgeExtension.php
<?php
namespace App\Twig;
use Twig\Extension\AbstractExtension;
use Twig\TwigFilter;
class AgeExtension extends AbstractExtension
{
public function getFilters()
{
return [
new TwigFilter('age', [$this , 'getAge']) ,
];
}
/**
* Return the diff between the datenow and the passed arg
* @param \DateTime $dateTime
* @return string
*/
public function getAge(\DateTime $dateTime){
$now = new \DateTime('now');
$diff = $now->diff($dateTime);
return $diff->format('%y');
}
}<file_sep>/src/Controller/ArticleController.php
<?php
namespace App\Controller;
use App\Entity\Article;
use App\Entity\User;
use App\Exception\PaymentException;
use App\Form\ArticleCreationFormType;
use App\Service\ConvertCurrencyService;
use App\Service\MercureCookieGenerator;
use Doctrine\ORM\EntityManager;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
class ArticleController extends AbstractController
{
public function showAll(){
$allArticles = $this->getDoctrine()->getRepository(Article::class)->findAllWithAuthorAndCategorys();
return $this->render("article/showAll.html.twig",
[
'allArticles' => $allArticles,
]
);
}
public function show($id , ConvertCurrencyService $converter , MercureCookieGenerator $cookieGenerator){
$this->denyAccessUnlessGranted('ROLE_USER');
/** @var User $user */
$user = $this->getUser();
$article = $this->getDoctrine()->getRepository(Article::class)->find($id);
if(!$article){
throw $this->createNotFoundException('Impossible de trouver l\'auteur');
}
$em = $this->getDoctrine()->getManager();
try{
$articlePrice = 1;
if($user->getCurrency() != 'EUR'){
$articlePrice = $converter->convert($articlePrice , 'EUR' , $user->getCurrency());
}
$user->decrementBalance($articlePrice);
$em->persist($user);
}
catch(PaymentException $e){
return $this->redirectToRoute('monblog_credit');
}
$em->flush();
$cookie = $cookieGenerator->generatePrivate($article);
$response = $this->render("article/show.html.twig",
[
'article' => $article,
]
);
$response->headers->set("set-cookie", $cookie);
return $response;
}
public function create(Request $request){
if(!$this->isGranted('ROLE_ADMIN')){
throw $this->createNotFoundException('nope');
}
$article = new Article();
$form = $this->createForm(ArticleCreationFormType::class, $article);
$form->handleRequest($request);
if($form->isSubmitted() && $form->isValid()){
$article->setCreationDate(new \DateTime('now'));
$em = $this->getDoctrine()->getManager();
$em->persist($article);
$em->flush();
return $this->redirectToRoute('monblog_article_showAll');
}
return $this->render("article/create.html.twig",[
'form' => $form->createView(),
]);
}
public function update($id , Request $request)
{
if(!$this->isGranted('ROLE_ADMIN')){
throw $this->createNotFoundException('nope');
}
$em = $this->getDoctrine()->getManager();
$article = $em->getRepository(Article::class)->find($id);
if(!$article){
throw $this->createNotFoundException('Impossible de trouver l\'auteur (modification)');
}
$form = $this->createForm(ArticleCreationFormType::class, $article);
$form->handleRequest(546);
if($form->isSubmitted() && $form->isValid()){
$article->setLastUpdateDate(new \DateTime('now'));
$em->persist($article);
$em->flush();
return $this->redirectToRoute('monblog_article_showAll');
}
return $this->render('article/update.html.twig' ,
[
'form' => $form->createView(),
]);
}
public function delete($id){
if(!$this->isGranted('ROLE_ADMIN')){
throw $this->createNotFoundException('nope');
}
$em = $this->getDoctrine()->getManager();
$article = $em->getRepository(Article::class)->find($id);
if($article){
$em->remove($article);
$em->flush();
}
return $this->redirectToRoute('monblog_article_showAll');
}
public function deleteAjax($id){
if(!$this->isGranted('ROLE_ADMIN')){
throw $this->createNotFoundException('nope');
}
$em = $this->getDoctrine()->getManager();
$article = $em->getRepository(Article::class)->find($id);
if($article){
$em->remove($article);
$em->flush();
}
return $this->json(
[
'success' => true,
'message' => 'OK !',
]
);
}
}
<file_sep>/src/Entity/Author.php
<?php
namespace App\Entity;
use App\Repository\AuthorRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
/**
* @ORM\Entity(repositoryClass=AuthorRepository::class)
*/
class Author
{
/**
* @ORM\Id()
* @ORM\GeneratedValue()
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\Column(type="string", length=5)
*/
private $title;
/**
* @ORM\Column(type="string", length=255)
* @Assert\NotBlank
* @Assert\Length(
* min = 2,
* max = 30,
* minMessage="Veuillez entrer au moins {{ limit }} caracteres",
* maxMessage="Veuillez entrer au plus {{ limit }} caracteres",
* )
*/
private $firstName;
/**
* @ORM\Column(type="string", length=255)
*/
private $LastName;
/**
* @ORM\Column(type="datetime")
* @Assert\LessThan(
* value = "-4 years",
* message = "Nos bloggeurs doivent avoir plus de 4 ans"
* )
*/
private $birthDate;
/**
* @ORM\Column(type="text", nullable=true)
*/
private $biography;
/**
* @ORM\OneToMany(targetEntity=Article::class, mappedBy="author")
*/
private $articles;
public function __construct()
{
$this->articles = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getTitle(): ?string
{
return $this->title;
}
public function setTitle(string $title): self
{
$this->title = $title;
return $this;
}
public function getFirstName(): ?string
{
return $this->firstName;
}
public function setFirstName(string $firstName): self
{
$this->firstName = $firstName;
return $this;
}
public function getLastName(): ?string
{
return $this->LastName;
}
public function setLastName(string $LastName): self
{
$this->LastName = $LastName;
return $this;
}
public function getBirthDate(): ?\DateTimeInterface
{
return $this->birthDate;
}
public function setBirthDate(\DateTimeInterface $birthDate): self
{
$this->birthDate = $birthDate;
return $this;
}
public function getBiography(): ?string
{
return $this->biography;
}
public function setBiography(?string $biography): self
{
$this->biography = $biography;
return $this;
}
public function getFullName() :string{
return $this->title.' '.$this->firstName.' '.$this->LastName;
}
/**
* @return Collection|Article[]
*/
public function getArticles(): Collection
{
return $this->articles;
}
public function addArticle(Article $article): self
{
if (!$this->articles->contains($article)) {
$this->articles[] = $article;
$article->setAuthor($this);
}
return $this;
}
public function removeArticle(Article $article): self
{
if ($this->articles->contains($article)) {
$this->articles->removeElement($article);
// set the owning side to null (unless already changed)
if ($article->getAuthor() === $this) {
$article->setAuthor(null);
}
}
return $this;
}
}
<file_sep>/src/Entity/CurrencyRate.php
<?php
namespace App\Entity;
use App\Repository\CurrencyRateRepository;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity(repositoryClass=CurrencyRateRepository::class)
*/
class CurrencyRate
{
/**
* @ORM\Id()
* @ORM\GeneratedValue()
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\Column(type="date")
*/
private $validityDate;
/**
* @ORM\Column(type="decimal", precision=20, scale=6)
*/
private $rate;
/**
* @ORM\Column(type="string", length=3)
*/
private $fromCurrency;
/**
* @ORM\Column(type="string", length=3)
*/
private $toCurrency;
public function getId(): ?int
{
return $this->id;
}
public function getValidityDate(): ?\DateTimeInterface
{
return $this->validityDate;
}
public function setValidityDate(\DateTimeInterface $validityDate): self
{
$this->validityDate = $validityDate;
return $this;
}
public function getRate(): ?string
{
return $this->rate;
}
public function setRate(string $rate): self
{
$this->rate = $rate;
return $this;
}
public function getFromCurrency(): ?string
{
return $this->fromCurrency;
}
public function setFromCurrency(string $fromCurrency): self
{
$this->fromCurrency = $fromCurrency;
return $this;
}
public function getToCurrency(): ?string
{
return $this->toCurrency;
}
public function setToCurrency(string $toCurrency): self
{
$this->toCurrency = $toCurrency;
return $this;
}
}
<file_sep>/src/Controller/HomeController.php
<?php
namespace App\Controller;
use App\Service\MyLogger;
use App\Service\Notificator;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Mercure\PublisherInterface;
use Symfony\Component\Mercure\Update;
use Symfony\Component\Routing\Annotation\Route;
class HomeController extends AbstractController
{
private $logger;
public function __construct(MyLogger $logger)
{
$this->logger = $logger;
}
public function main(){
/*$this->logger->write('toto');*/
return $this->render('home/main.html.twig',
[
"message" => "Coucou",
]
);
}
//
// public function indexByPage($page){
//
// die('Affiche la page '.$page);
//
// }
//
// public function indexByLetter($letter){
// die('Affiche la page '.$letter);
// }
public function TestMercure(PublisherInterface $publisher)
{
$update = new Update(
'http://monblog/test-socket/5',
json_encode([
'message' => 'toto'
])
);
$publisher($update);
//
// $notificator->privateNotification('http://monblog/test-socket/5', [
// 'message' => 'toto'
// ]);
return new Response('published!');
}
public function getChatAjax(Request $request ,Notificator $notificator){
$message = $request->request->get('message');
$id = $request->request->get('id');
$notificator->publicNotification('http://monblog/test-socket/'.$id, [
'message' => $message
]);
return $this->json(1);
}
}
<file_sep>/src/Controller/CategoryController.php
<?php
namespace App\Controller;
use App\Entity\Author;
use App\Entity\Categorys;
use App\Form\CategorysType;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
class CategoryController extends AbstractController
{
public function showAll(Request $request){
$em = $this->getDoctrine()->getManager();
$allCategorys = $em->getRepository(Categorys::class)->findAll();
$category = new Categorys();
$form = $this->createForm(CategorysType::class , $category);
$form->handleRequest($request);
if($form->isSubmitted() && $form->isValid()){
$em->persist($category);
$em->flush();
return $this->redirectToRoute('monblog_category_showAll');
}
return $this->render("category/showAll.html.twig",
[
'allCategorys' => $allCategorys,
'form' => $form->createView(),
]
);
}
public function update($id , Request $request)
{
$em = $this->getDoctrine()->getManager();
$category = $em->getRepository(Categorys::class)->find($id);
if(!$category){
throw $this->createNotFoundException('Impossible de trouver l\'auteur (modification)');
}
$form = $this->createForm(CategorysType::class, $category);
$form->handleRequest($request);
if($form->isSubmitted() && $form->isValid()){
$em->persist($category);
$em->flush();
return $this->redirectToRoute('monblog_category_showAll');
}
return $this->render('category/update.html.twig' ,
[
'form' => $form->createView(),
]);
}
public function deleteAjax($id){
$em = $this->getDoctrine()->getManager();
$category = $em->getRepository(Categorys::class)->find($id);
if($category){
$em->remove($category);
$em->flush();
}
return $this->json(
[
'success' => true,
'message' => 'OK !',
]
);
}
}
<file_sep>/src/Controller/AuthorController.php
<?php
namespace App\Controller;
use App\Entity\Author;
use App\Form\AuthorCreationFormType;
use App\Repository\AuthorRepository;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
class AuthorController extends AbstractController
{
public function showAll(){
$allAuthors = $this->getDoctrine()->getRepository(Author::class)->findBy([],
['firstName' => 'asc',
'LastName' => 'asc']);
return $this->render("author/showAll.html.twig",
[
'allAuthors' => $allAuthors,
]
);
}
public function show($id){
$author = $this->getDoctrine()->getRepository(Author::class)->find($id);
if(!$author){
throw $this->createNotFoundException('Impossible de trouver l\'auteur');
}
return $this->render("author/show.html.twig",
[
'author' => $author,
]
);
}
public function create(Request $request){
if(!$this->isGranted('ROLE_ADMIN')){
throw $this->createNotFoundException('nope');
}
$author = new Author();
$form = $this->createForm(AuthorCreationFormType::class, $author);
$form->handleRequest($request);
if($form->isSubmitted() && $form->isValid()){
$em = $this->getDoctrine()->getManager();
$em->persist($author);
$em->flush();
return $this->redirectToRoute('monblog_author_showAll');
}
return $this->render("author/create.html.twig",[
'form' => $form->createView(),
]);
}
public function update($id , Request $request)
{
if(!$this->isGranted('ROLE_ADMIN')){
throw $this->createNotFoundException('nope');
}
$em = $this->getDoctrine()->getManager();
$author = $em->getRepository(Author::class)->find($id);
if(!$author){
throw $this->createNotFoundException('Impossible de trouver l\'auteur (modification)');
}
$form = $this->createForm(AuthorCreationFormType::class, $author);
$form->handleRequest($request);
if($form->isSubmitted() && $form->isValid()){
$em->persist($author);
$em->flush();
return $this->redirectToRoute('monblog_author_showAll');
}
return $this->render('author/update.html.twig' ,
[
'form' => $form->createView(),
]);
}
public function deleteAjax($id){
if(!$this->isGranted('ROLE_ADMIN')){
throw $this->createNotFoundException('nope');
}
$em = $this->getDoctrine()->getManager();
$author = $em->getRepository(Author::class)->find($id);
if($author){
$em->remove($author);
$em->flush();
}
return $this->json(
[
'success' => true,
'message' => 'OK !',
]
);
}
}
<file_sep>/src/Service/Notificator.php
<?php
namespace App\Service;
use Symfony\Component\Mercure\PublisherInterface;
use Symfony\Component\Mercure\Update;
class Notificator
{
private $publisher;
public function __construct(PublisherInterface $publisher)
{
$this->publisher = $publisher;
}
public function publicNotification(string $topics , array $params){
$update = new Update(
$topics,
json_encode($params)
);
$publisher = $this->publisher;
$publisher($update);
}
public function privateNotification(string $topics , array $params){
$update = new Update(
$topics,
json_encode($params),
true
);
$publisher = $this->publisher;
$publisher($update);
}
}<file_sep>/src/Repository/CurrencyRateRepository.php
<?php
namespace App\Repository;
use App\Entity\CurrencyRate;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
use PHPUnit\Util\Exception;
/**
* @method CurrencyRate|null find($id, $lockMode = null, $lockVersion = null)
* @method CurrencyRate|null findOneBy(array $criteria, array $orderBy = null)
* @method CurrencyRate[] findAll()
* @method CurrencyRate[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
*/
class CurrencyRateRepository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, CurrencyRate::class);
}
public function getPreviousRate(){
$result = $this->createQueryBuilder('c')
->orderBy('validityDate', 'DESC')
->setMaxResults(2)
->getQuery()
->getResult();
if(!$result || count($result) < 2) {
throw new Exception('il y a pas de taux precedents');
}
/** @var CurrencyRate $previousRateObj */
$previousRateObj = $result[1];
return $previousRateObj->getRate();
}
// /**
// * @return CurrencyRate[] Returns an array of CurrencyRate objects
// */
/*
public function findByExampleField($value)
{
return $this->createQueryBuilder('c')
->andWhere('c.exampleField = :val')
->setParameter('val', $value)
->orderBy('c.id', 'ASC')
->setMaxResults(10)
->getQuery()
->getResult()
;
}
*/
/*
public function findOneBySomeField($value): ?CurrencyRate
{
return $this->createQueryBuilder('c')
->andWhere('c.exampleField = :val')
->setParameter('val', $value)
->getQuery()
->getOneOrNullResult()
;
}
*/
}
<file_sep>/src/EventSubscriber/AJAXBeforeFIlterSubscriber.php
<?php
namespace App\EventSubscriber;
use Symfony\Component\Finder\Exception\AccessDeniedException;
use Symfony\Component\HttpKernel\Event\ControllerEvent;
use Symfony\Component\HttpKernel\Event\KernelEvent;
use Symfony\Component\HttpKernel\KernelEvents;
class AJAXBeforeFIlterSubscriber
{
public function onController(ControllerEvent $event){
$controller = $event->getController();
if(is_array($controller)){
$method_name = $controller[1];
if(
strpos($method_name,'Ajax') !== false
&& $event->getRequest()->isXmlHttpRequest()
)
{
throw new AccessDeniedException('Ajax only');
}
}
}
public static function getSubscribedEvents()
{
return [
KernelEvents::CONTROLLER =>
['onController', 0],
];
}
}<file_sep>/src/Service/MercureCookieGenerator.php
<?php
namespace App\Service;
use App\Entity\Article;
use App\Entity\User;
use Lcobucci\JWT\Builder;
use Lcobucci\JWT\Signer\Hmac\Sha256;
use Lcobucci\JWT\Signer\Key;
class MercureCookieGenerator
{
private $secret;
public function __construct(string $secret)
{
$this->secret = $secret;
}
public function generatePrivate(Article $article , int $duration = 30){
$id = $article->getId();
$token = (new Builder())
->expiresAt(time()+$duration)
->withClaim('mercure', [
'subscribe' => [
'http://monblog/test-socket/'.$id
]
])
->getToken(new Sha256(), new Key($this->secret))
;
$cookieString = sprintf('mercureAuthorization=%s; path=/.well-known/mercure; secure; httponly; SameSite=strict' , $token);
return $cookieString ;
}
}
|
bce4c741615e123ec047f638d716d8abffd57f86
|
[
"JavaScript",
"PHP"
] | 27
|
PHP
|
misakilou/formationsf
|
0a00b354b24dc744996c1bc798f1c5fab7bb1f7b
|
450390b093c5ceb2bbcccd3256281a62bf97e8fb
|
refs/heads/master
|
<file_sep>var p1Button = document.querySelector("#p1");
var p1Display = document.querySelector("#p1Display");
var p1Score = 0;
var p2Button = document.querySelector("#p2");
var p2Display = document.querySelector("#p2Display");
var p2Score = 0;
var resetButton = document.querySelector("#reset");
var limitInput = document.querySelector("#limit");
var winingDisplay = document.querySelector("#winnerNumber")
var gameOver = false;
var winnerScore = 5;
// Game reset
function reset(){
p1Score = 0;
p2Score = 0;
p1Display.textContent = 0;
p2Display.textContent = 0;
p1Display.classList.remove('winner');
p2Display.classList.remove('winner');
gameOver = false;
}
// Limit score
limitInput.addEventListener("change", function(){
// just to show we can use the "this" keyword here
// winingDisplay.textContent = limitInput.value;
winingDisplay.textContent = this.value;
// same here
// winnerScore = limitInput.value;
winnerScore = Number(this.value);
reset();
});
resetButton.addEventListener("click", function(){
reset();
});
// Player
function playerCount(button, output, score){
button.addEventListener('click', function(){
if (!gameOver) {
score++;
if (winnerScore === score) {
gameOver = true;
output.classList.add('winner');
}
output.textContent = score;
}else{
reset(score);
}
});
}
playerCount(p1Button, p1Display, p1Score);
playerCount(p2Button, p2Display, p2Score);
// THE CODE I WANT TO REFACTOR
// p1Button.addEventListener("click", function(){
// if (!gameOver) {
// p1Score++;
// if (winnerScore === p1Score) {
// gameOver = true;
// p1Display.classList.add('winner');
// }
// p1Display.textContent = p1Score;
// }
// });
// p2Button.addEventListener("click", function(){
// if (!gameOver) {
// p2Score++;
// if (winnerScore === p2Score) {
// gameOver = true;
// p2Display.classList.add('winner');
// }
// p2Display.textContent = p2Score;
// }
// });
|
4c3963ef40eaddb9c4ab8685484df2e78245d574
|
[
"JavaScript"
] | 1
|
JavaScript
|
RNwebdk/Score-Application
|
ce611c30ddf0603273faa10b9b930cb51b77ab12
|
bee5807ca5f3f4b3df093f69b56c5f5fd8598377
|
refs/heads/master
|
<file_sep>#!/usr/bin/env python3
import urllib.request
import xmltodict
def metro_status(line, language):
# Getting XML data
URL = "http://www2.stm.info/1997/alertesmetro/esm.xml"
metro_website = urllib.request.urlopen(URL)
metro_info = metro_website.read()
metro_website.close()
xml_data = xmltodict.parse(metro_info)
for i in xml_data['Root']['Ligne']:
nline = i["NoLigne"]
if line == "green" and nline == "1" or line == "all" and nline == "1":
print("Green line status: {0}"
.format(i["msg{0}".format(language)]
.encode('ascii', 'replace').decode('utf-8')))
if line == "orange" and nline == "2" or line == "all" and nline == "2":
print("Orange line status: {0}"
.format(i["msg{0}".format(language)]
.encode('ascii', 'replace').decode('utf-8')))
if line == "yellow" and nline == "4" or line == "all" and nline == "4":
print("Yellow line status: {0}"
.format(i["msg{0}".format(language)]
.encode('ascii', 'replace').decode('utf-8')))
if line == "blue" and nline == "5" or line == "all" and nline == "5":
print("Blue line status: {0}"
.format(i["msg{0}".format(language)]
.encode('ascii', 'replace').decode('utf-8')))
<file_sep>unicodecsv==0.14.1
xmltodict==0.10.1
<file_sep>#!/usr/bin/env python3
import sqlite3
import time
def next_departures(bus_number, stop_code, date, time, nb_departure, db_file):
# Getting the 10 next departures
conn = sqlite3.connect(db_file)
c = conn.cursor()
sql_var = (bus_number, stop_code, date)
c.execute("""SELECT st.departure_time
FROM trips t
INNER JOIN stop_times st
ON t.trip_id=st.trip_id
INNER JOIN stops s
ON st.stop_id=s.stop_id
WHERE t.route_id=?
AND s.stop_code=?
AND service_id=(SELECT service_id
FROM calendar_dates
WHERE date=?)
ORDER BY st.departure_time""", sql_var)
query_result = []
for i in c.fetchall():
query_result.append(i[0])
conn.close()
result = []
departures_listed = 0
for i in query_result:
dep_time = i.split(':')
if dep_time[0] == time[0] and dep_time[1] >= time[1]:
result.append("{0}:{1}".format(dep_time[0], dep_time[1]))
departures_listed += 1
elif dep_time[0] > time[0]:
result.append("{0}:{1}".format(dep_time[0], dep_time[1]))
departures_listed += 1
if departures_listed is nb_departure:
break
return result
def all_bus_stop(bus_number, db_file):
# Getting all bus stop for this bus
conn = sqlite3.connect(db_file)
c = conn.cursor()
sql_var = (bus_number, time.strftime('%Y%m%d'))
c.execute("""SELECT stop_name, stop_code, trip_headsign
FROM trips t
INNER JOIN stop_times st
ON t.trip_id=st.trip_id
INNER JOIN stops s
ON st.stop_id=s.stop_id
WHERE t.route_id=?
AND service_id=(SELECT service_id
FROM calendar_dates
WHERE date=?)
AND direction_id = 0
GROUP BY stop_code
ORDER BY stop_sequence
""", sql_var)
query_result = c.fetchall()
result = ["---------"]
result.append("Direction {0}".format(query_result[0][2]))
result.append("----------")
for i in query_result:
result.append("[{0}] {1}".format(i[0], i[1]))
c.execute("""SELECT stop_name, stop_code, trip_headsign
FROM trips t
INNER JOIN stop_times st
ON t.trip_id=st.trip_id
INNER JOIN stops s
ON st.stop_id=s.stop_id
WHERE t.route_id=?
AND service_id=(SELECT service_id
FROM calendar_dates
WHERE date=?)
AND direction_id = 1
GROUP BY stop_code
ORDER BY stop_sequence
""", sql_var)
query_result = c.fetchall()
result.append("----------")
result.append("Direction {0}".format(query_result[0][2]))
result.append("----------")
for i in query_result:
result.append("[{0}] {1}".format(i[0], i[1]))
conn.close()
return result
def all_bus_for_stop_code(stop_code, db_file):
# Getting all bus at this bus code
conn = sqlite3.connect(db_file)
c = conn.cursor()
sql_var = (stop_code,)
c.execute("""SELECT DISTINCT route_id
FROM trips t
INNER JOIN stop_times st
ON t.trip_id=st.trip_id
INNER JOIN stops s
ON st.stop_id=s.stop_id
AND s.stop_code=?""", sql_var)
result = []
for i in c.fetchall():
result.append(i[0])
conn.close()
return result
def metro_status(line, language):
# Getting XML data
URL = "http://www2.stm.info/1997/alertesmetro/esm.xml"
metro_website = urllib.request.urlopen(URL)
metro_info = metro_website.read()
metro_website.close()
xml_data = xmltodict.parse(metro_info)
for i in xml_data['Root']['Ligne']:
nline = i["NoLigne"]
if line == "green" and nline == "1" or line == "all" and nline == "1":
print("Green line status: {0}"
.format(i["msg{0}".format(language)]
.encode('ascii', 'replace').decode('utf-8')))
if line == "orange" and nline == "2" or line == "all" and nline == "2":
print("Orange line status: {0}"
.format(i["msg{0}".format(language)]
.encode('ascii', 'replace').decode('utf-8')))
if line == "yellow" and nline == "4" or line == "all" and nline == "4":
print("Yellow line status: {0}"
.format(i["msg{0}".format(language)]
.encode('ascii', 'replace').decode('utf-8')))
if line == "blue" and nline == "5" or line == "all" and nline == "5":
print("Blue line status: {0}"
.format(i["msg{0}".format(language)]
.encode('ascii', 'replace').decode('utf-8')))
<file_sep>#!/usr/bin/env python3
from stmcli import database
import os
import sqlite3
import shutil
import time
import urllib
from urllib import error, request
import zipfile
def download_gtfs_data(data_dir):
extract_location = "{0}/stm/".format(data_dir)
try:
output_zip = "{0}/gtfs.zip".format(data_dir)
zip_url = "http://www.stm.info/sites/default/files/gtfs/gtfs_stm.zip"
urllib.request.urlretrieve(zip_url, output_zip)
except urllib.error.HTTPError as err:
print("Error {0} while trying to downloads stm infos")
exit(1)
# Extracting
if not os.path.isdir(extract_location):
os.makedirs(extract_location)
zip = zipfile.ZipFile(output_zip)
zip.extractall(path=extract_location)
os.unlink(output_zip)
def check_for_update(db_file, data_dir, force_update):
# Check if db_file exist
if not os.path.isfile(db_file):
answer = "y"
if not force_update:
answer = input("No data found, update? [y/n] ")
if answer == "y":
download_gtfs_data(data_dir)
database.create_db(db_file)
database.load_stm_data(db_file, data_dir)
shutil.rmtree("{0}/stm".format(data_dir))
else:
print("Can't continue without data.")
exit(0)
# Check if GTFS data update is needed
curr_date = time.strftime('%Y%m%d')
conn = sqlite3.connect(db_file)
c = conn.cursor()
c.execute('SELECT * FROM calendar_dates WHERE date={0}'.format(curr_date))
t = c.fetchone()
conn.close()
if t is None or not os.path.isfile(db_file):
answer = "y"
if not force_update:
answer = input("Data update needed, update now? [y/n] ")
if answer == "y":
os.unlink(db_file)
download_gtfs_data(data_dir)
database.create_db(db_file)
database.load_stm_data(db_file, data_dir)
shutil.rmtree("{0}/stm".format(data_dir))
else:
print("Data update needed for stmcli to work.")
exit(0)
def date_in_scope(date, db_file):
conn = sqlite3.connect(db_file)
c = conn.cursor()
c.execute('SELECT * FROM calendar_dates WHERE date={0}'.format(date))
t = c.fetchone()
conn.close()
if t is None:
return False
else:
return True
<file_sep>#!/usr/bin/env python3
import os
import sqlite3
import unicodecsv
def init_table(db_file):
conn = sqlite3.connect(db_file)
conn.execute('''CREATE TABLE agency
(agency_id char(3),
agency_name char(40) not null,
agency_url char(60) not null,
agency_timezone char(20) not null,
agency_lang char(10),
agency_phone char(20),
agency_fare_url char(255)
);''')
conn.execute('''CREATE TABLE stops
(stop_id int primary key not null,
stop_code int,
stop_name char(50) not null,
stop_lat int not null,
stop_long int not null,
stop_url char(60),
wheelchair_accessible boolean
);''')
conn.execute('''CREATE TABLE routes
(route_id int primary key not null,
agency_id int,
route_short_name char(10) not null,
route_long_name char(40) not null,
route_type char(10) not null,
route_url text,
route_color char(6),
route_text_color char(6)
);''')
conn.execute('''CREATE TABLE trips
(route_id int not null,
service_id int not null,
trip_id char(20) primary key not null,
trip_headsign char(50),
direction_id boolean,
wheelchair_accessible int,
shape_id char(15),
note_fr char(255),
note_en char(255)
);''')
conn.execute('''CREATE TABLE stop_times
(trip_id char(20) not null,
arrival_time char(8) not null,
departure_time char(8) not null,
stop_id int not null,
stop_sequence int not null
);''')
conn.execute('''CREATE TABLE calendar_dates
(service_id char(3) not null,
date date not null,
exception_type boolean not null
);''')
conn.close()
def load_data(data_file, db_file, stmcli_data_dir):
conn = sqlite3.connect(db_file)
cursor = conn.cursor()
file_path = "{0}/stm/".format(stmcli_data_dir) + data_file
with open(file_path, 'rb') as input_file:
reader = unicodecsv.reader(input_file, delimiter=",")
data = [row for row in reader]
if "agency" in data_file:
print("agency")
cursor.executemany('''INSERT INTO agency
VALUES (?, ?, ?, ?, ?, ?, ?);''', data)
elif "stops" in data_file:
print("stops")
cursor.executemany('''INSERT INTO stops
VALUES (?, ?, ?, ?, ?, ?, ?);''', data)
elif "routes" in data_file:
print("routes")
cursor.executemany('''INSERT INTO routes
VALUES (?, ?, ?, ?, ?, ?, ?, ?);''', data)
elif "trips" in data_file:
print("trips")
cursor.executemany('''INSERT INTO trips
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?);''', data)
elif "stop_times" in data_file:
print("stop_times")
cursor.executemany('''INSERT INTO stop_times
VALUES (?, ?, ?, ?, ?);''', data)
elif "calendar_dates" in data_file:
print("calendar_dates")
cursor.executemany('''INSERT INTO calendar_dates
VALUES (?, ?, ?);''', data)
else:
print("There is no table for " + data_file)
conn.commit()
conn.close()
def create_db(db_file):
if not os.path.isfile(db_file):
init_table(db_file)
print("Database Created")
else:
print("Database already exist")
def load_stm_data(db_file, stmcli_data_dir):
stm_file_dir = os.listdir("{0}/stm".format(stmcli_data_dir))
for filename in stm_file_dir:
load_data(filename, db_file, stmcli_data_dir)
|
61e7bbb2fb36341a82e7702c8b1e03b865f17b39
|
[
"Python",
"Text"
] | 5
|
Python
|
arthtux/stmcli
|
df578d49007174129a00f73fd678feeb8f8e0419
|
d7eefdf01ab0beec85bda9dd997229a9f2eb0b2a
|
refs/heads/master
|
<file_sep>package item
import (
"github.com/df-mc/dragonfly/dragonfly/item/armour"
"github.com/df-mc/dragonfly/dragonfly/item/bucket"
"github.com/df-mc/dragonfly/dragonfly/item/tool"
"github.com/df-mc/dragonfly/dragonfly/world"
)
//noinspection SpellCheckingInspection
func init() {
world.RegisterItem("minecraft:wooden_pickaxe", Pickaxe{Tier: tool.TierWood})
world.RegisterItem("minecraft:golden_pickaxe", Pickaxe{Tier: tool.TierGold})
world.RegisterItem("minecraft:stone_pickaxe", Pickaxe{Tier: tool.TierStone})
world.RegisterItem("minecraft:iron_pickaxe", Pickaxe{Tier: tool.TierIron})
world.RegisterItem("minecraft:diamond_pickaxe", Pickaxe{Tier: tool.TierDiamond})
world.RegisterItem("minecraft:netherite_pickaxe", Pickaxe{Tier: tool.TierNetherite})
world.RegisterItem("minecraft:wooden_axe", Axe{Tier: tool.TierWood})
world.RegisterItem("minecraft:golden_axe", Axe{Tier: tool.TierGold})
world.RegisterItem("minecraft:stone_axe", Axe{Tier: tool.TierStone})
world.RegisterItem("minecraft:iron_axe", Axe{Tier: tool.TierIron})
world.RegisterItem("minecraft:diamond_axe", Axe{Tier: tool.TierDiamond})
world.RegisterItem("minecraft:netherite_axe", Axe{Tier: tool.TierNetherite})
world.RegisterItem("minecraft:wooden_shovel", Shovel{Tier: tool.TierWood})
world.RegisterItem("minecraft:golden_shovel", Shovel{Tier: tool.TierGold})
world.RegisterItem("minecraft:stone_shovel", Shovel{Tier: tool.TierStone})
world.RegisterItem("minecraft:iron_shovel", Shovel{Tier: tool.TierIron})
world.RegisterItem("minecraft:diamond_shovel", Shovel{Tier: tool.TierDiamond})
world.RegisterItem("minecraft:netherite_shovel", Shovel{Tier: tool.TierNetherite})
world.RegisterItem("minecraft:wooden_sword", Sword{Tier: tool.TierWood})
world.RegisterItem("minecraft:golden_sword", Sword{Tier: tool.TierGold})
world.RegisterItem("minecraft:stone_sword", Sword{Tier: tool.TierStone})
world.RegisterItem("minecraft:iron_sword", Sword{Tier: tool.TierIron})
world.RegisterItem("minecraft:diamond_sword", Sword{Tier: tool.TierDiamond})
world.RegisterItem("minecraft:netherite_sword", Sword{Tier: tool.TierNetherite})
world.RegisterItem("minecraft:leather_helmet", Helmet{Tier: armour.TierLeather})
world.RegisterItem("minecraft:golden_helmet", Helmet{Tier: armour.TierGold})
world.RegisterItem("minecraft:chainmail_helmet", Helmet{Tier: armour.TierChain})
world.RegisterItem("minecraft:iron_helmet", Helmet{Tier: armour.TierIron})
world.RegisterItem("minecraft:diamond_helmet", Helmet{Tier: armour.TierDiamond})
world.RegisterItem("minecraft:netherite_helmet", Helmet{Tier: armour.TierNetherite})
world.RegisterItem("minecraft:leather_chestplate", Chestplate{Tier: armour.TierLeather})
world.RegisterItem("minecraft:golden_chestplate", Chestplate{Tier: armour.TierGold})
world.RegisterItem("minecraft:chainmail_chestplate", Chestplate{Tier: armour.TierChain})
world.RegisterItem("minecraft:iron_chestplate", Chestplate{Tier: armour.TierIron})
world.RegisterItem("minecraft:diamond_chestplate", Chestplate{Tier: armour.TierDiamond})
world.RegisterItem("minecraft:netherite_chestplate", Chestplate{Tier: armour.TierNetherite})
world.RegisterItem("minecraft:leather_leggings", Leggings{Tier: armour.TierLeather})
world.RegisterItem("minecraft:golden_leggings", Leggings{Tier: armour.TierGold})
world.RegisterItem("minecraft:chainmail_leggings", Leggings{Tier: armour.TierChain})
world.RegisterItem("minecraft:iron_leggings", Leggings{Tier: armour.TierIron})
world.RegisterItem("minecraft:diamond_leggings", Leggings{Tier: armour.TierDiamond})
world.RegisterItem("minecraft:netherite_leggings", Leggings{Tier: armour.TierNetherite})
world.RegisterItem("minecraft:leather_boots", Boots{Tier: armour.TierLeather})
world.RegisterItem("minecraft:golden_boots", Boots{Tier: armour.TierGold})
world.RegisterItem("minecraft:chainmail_boots", Boots{Tier: armour.TierChain})
world.RegisterItem("minecraft:iron_boots", Boots{Tier: armour.TierIron})
world.RegisterItem("minecraft:diamond_boots", Boots{Tier: armour.TierDiamond})
world.RegisterItem("minecraft:netherite_boots", Boots{Tier: armour.TierNetherite})
world.RegisterItem("minecraft:bucket", Bucket{})
world.RegisterItem("minecraft:bucket", Bucket{Content: bucket.Water()})
world.RegisterItem("minecraft:bucket", Bucket{Content: bucket.Lava()})
}
<file_sep>package player
import (
"fmt"
"github.com/df-mc/dragonfly/dragonfly/block"
blockAction "github.com/df-mc/dragonfly/dragonfly/block/action"
"github.com/df-mc/dragonfly/dragonfly/cmd"
"github.com/df-mc/dragonfly/dragonfly/entity"
"github.com/df-mc/dragonfly/dragonfly/entity/action"
"github.com/df-mc/dragonfly/dragonfly/entity/damage"
"github.com/df-mc/dragonfly/dragonfly/entity/effect"
"github.com/df-mc/dragonfly/dragonfly/entity/healing"
"github.com/df-mc/dragonfly/dragonfly/entity/physics"
"github.com/df-mc/dragonfly/dragonfly/entity/state"
"github.com/df-mc/dragonfly/dragonfly/event"
"github.com/df-mc/dragonfly/dragonfly/internal/entity_internal"
"github.com/df-mc/dragonfly/dragonfly/item"
"github.com/df-mc/dragonfly/dragonfly/item/armour"
"github.com/df-mc/dragonfly/dragonfly/item/inventory"
"github.com/df-mc/dragonfly/dragonfly/item/tool"
"github.com/df-mc/dragonfly/dragonfly/player/bossbar"
"github.com/df-mc/dragonfly/dragonfly/player/chat"
"github.com/df-mc/dragonfly/dragonfly/player/form"
"github.com/df-mc/dragonfly/dragonfly/player/scoreboard"
"github.com/df-mc/dragonfly/dragonfly/player/skin"
"github.com/df-mc/dragonfly/dragonfly/player/title"
"github.com/df-mc/dragonfly/dragonfly/session"
"github.com/df-mc/dragonfly/dragonfly/world"
"github.com/df-mc/dragonfly/dragonfly/world/difficulty"
"github.com/df-mc/dragonfly/dragonfly/world/gamemode"
"github.com/df-mc/dragonfly/dragonfly/world/particle"
"github.com/df-mc/dragonfly/dragonfly/world/sound"
"github.com/go-gl/mathgl/mgl64"
"github.com/google/uuid"
"go.uber.org/atomic"
"image/color"
"math/rand"
"net"
"strings"
"sync"
"time"
)
// Player is an implementation of a player entity. It has methods that implement the behaviour that players
// need to play in the world.
type Player struct {
name string
uuid uuid.UUID
xuid string
pos, velocity atomic.Value
nameTag atomic.String
yaw, pitch, absorptionHealth atomic.Float64
gameModeMu sync.RWMutex
gameMode gamemode.GameMode
skin skin.Skin
sMutex sync.RWMutex
// s holds the session of the player. This field should not be used directly, but instead,
// Player.session() should be called.
s *session.Session
hMutex sync.RWMutex
// h holds the current handler of the player. It may be changed at any time by calling the Start method.
h Handler
inv, offHand *inventory.Inventory
armour *inventory.Armour
heldSlot *atomic.Uint32
sneaking, sprinting, swimming, invisible, onGround atomic.Bool
speed atomic.Float64
health *entity_internal.HealthManager
effects *entity.EffectManager
immunity atomic.Value
breaking atomic.Bool
breakingPos atomic.Value
lastBreakDuration time.Duration
breakParticleCounter atomic.Uint32
hunger *hungerManager
}
// New returns a new initialised player. A random UUID is generated for the player, so that it may be
// identified over network.
func New(name string, skin skin.Skin, pos mgl64.Vec3) *Player {
p := &Player{}
*p = Player{
inv: inventory.New(36, func(slot int, item item.Stack) {
if slot == int(p.heldSlot.Load()) {
p.broadcastItems(slot, item)
}
}),
uuid: uuid.New(),
offHand: inventory.New(2, p.broadcastItems),
armour: inventory.NewArmour(p.broadcastArmour),
hunger: newHungerManager(),
health: entity_internal.NewHealthManager(),
effects: entity.NewEffectManager(),
gameMode: gamemode.Adventure{},
h: NopHandler{},
name: name,
skin: skin,
speed: *atomic.NewFloat64(0.1),
nameTag: *atomic.NewString(name),
heldSlot: atomic.NewUint32(0),
}
p.pos.Store(pos)
p.velocity.Store(mgl64.Vec3{})
p.immunity.Store(time.Now())
p.breakingPos.Store(world.BlockPos{})
return p
}
// NewWithSession returns a new player for a network session, so that the network session can control the
// player.
// A set of additional fields must be provided to initialise the player with the client's data, such as the
// name and the skin of the player.
func NewWithSession(name, xuid string, uuid uuid.UUID, skin skin.Skin, s *session.Session, pos mgl64.Vec3) *Player {
p := New(name, skin, pos)
p.s, p.uuid, p.xuid, p.skin = s, uuid, xuid, skin
p.inv, p.offHand, p.armour, p.heldSlot = s.HandleInventories()
chat.Global.Subscribe(p)
return p
}
// Name returns the username of the player. If the player is controlled by a client, it is the username of
// the client. (Typically the XBOX Live name)
func (p *Player) Name() string {
return p.name
}
// UUID returns the UUID of the player. This UUID will remain consistent with an XBOX Live account, and will,
// unlike the name of the player, never change.
// It is therefore recommended to use the UUID over the name of the player. Additionally, it is recommended to
// use the UUID over the XUID because of its standard format.
func (p *Player) UUID() uuid.UUID {
return p.uuid
}
// XUID returns the XBOX Live user ID of the player. It will remain consistent with the XBOX Live account,
// and will not change in the lifetime of an account.
// The XUID is a number that can be parsed as an int64. No more information on what it represents is
// available, and the UUID should be preferred.
// The XUID returned is empty if the Player is not connected to a network session.
func (p *Player) XUID() string {
return p.xuid
}
// Skin returns the skin that a player joined with. This skin will be visible to other players that the player
// is shown to.
// If the player was not connected to a network session, a default skin will be set.
func (p *Player) Skin() skin.Skin {
return p.skin
}
// Handle changes the current handler of the player. As a result, events called by the player will call
// handlers of the Handler passed.
// Handle sets the player's handler to NopHandler if nil is passed.
func (p *Player) Handle(h Handler) {
p.hMutex.Lock()
defer p.hMutex.Unlock()
if h == nil {
h = NopHandler{}
}
p.h = h
}
// Message sends a formatted message to the player. The message is formatted following the rules of
// fmt.Sprintln, however the newline at the end is not written.
func (p *Player) Message(a ...interface{}) {
p.session().SendMessage(format(a))
}
// SendPopup sends a formatted popup to the player. The popup is shown above the hotbar of the player and
// overwrites/is overwritten by the name of the item equipped.
// The popup is formatted following the rules of fmt.Sprintln without a newline at the end.
func (p *Player) SendPopup(a ...interface{}) {
p.session().SendPopup(format(a))
}
// SendTip sends a tip to the player. The tip is shown in the middle of the screen of the player.
// The tip is formatted following the rules of fmt.Sprintln without a newline at the end.
func (p *Player) SendTip(a ...interface{}) {
p.session().SendTip(format(a))
}
// SendTitle sends a title to the player. The title may be configured to change the duration it is displayed
// and the text it shows.
// If non-empty, the subtitle is shown in a smaller font below the title. The same counts for the action text
// of the title, which is shown in a font similar to that of a tip/popup.
func (p *Player) SendTitle(t title.Title) {
p.session().SetTitleDurations(t.FadeInDuration(), t.Duration(), t.FadeOutDuration())
p.session().SendTitle(t.Text())
if t.Subtitle() != "" {
p.session().SendSubtitle(t.Subtitle())
}
if t.ActionText() != "" {
p.session().SendActionBarMessage(t.ActionText())
}
}
// SendScoreboard sends a scoreboard to the player. The scoreboard will be present indefinitely until removed
// by the caller.
// SendScoreboard may be called at any time to change the scoreboard of the player.
func (p *Player) SendScoreboard(scoreboard *scoreboard.Scoreboard) {
p.session().SendScoreboard(scoreboard.Name())
p.session().SendScoreboardLines(scoreboard.Lines())
}
// RemoveScoreboard removes any scoreboard currently present on the screen of the player. Nothing happens if
// the player has no scoreboard currently active.
func (p *Player) RemoveScoreboard() {
p.session().RemoveScoreboard()
}
// SendBossBar sends a boss bar to the player, so that it will be shown indefinitely at the top of the
// player's screen.
// The boss bar may be removed by calling Player.RemoveBossBar().
func (p *Player) SendBossBar(bar bossbar.BossBar) {
p.session().SendBossBar(bar.Text(), bar.HealthPercentage())
}
// RemoveBossBar removes any boss bar currently active on the player's screen. If no boss bar is currently
// present, nothing happens.
func (p *Player) RemoveBossBar() {
p.session().RemoveBossBar()
}
// Chat writes a message in the global chat (chat.Global). The message is prefixed with the name of the
// player and is formatted following the rules of fmt.Sprintln.
func (p *Player) Chat(msg ...interface{}) {
if p.Dead() {
return
}
message := format(msg)
ctx := event.C()
p.handler().HandleChat(ctx, &message)
ctx.Continue(func() {
chat.Global.Printf("<%v> %v\n", p.name, message)
})
}
// ExecuteCommand executes a command passed as the player. If the command could not be found, or if the usage
// was incorrect, an error message is sent to the player.
func (p *Player) ExecuteCommand(commandLine string) {
if p.Dead() {
return
}
args := strings.Split(commandLine, " ")
commandName := strings.TrimPrefix(args[0], "/")
command, ok := cmd.ByAlias(commandName)
if !ok {
output := &cmd.Output{}
output.Errorf("Unknown command '%v'", commandName)
p.SendCommandOutput(output)
return
}
ctx := event.C()
p.handler().HandleCommandExecution(ctx, command, args[1:])
ctx.Continue(func() {
command.Execute(strings.TrimPrefix(commandLine, "/"+commandName+" "), p)
})
}
// Disconnect closes the player and removes it from the world.
// Disconnect, unlike Close, allows a custom message to be passed to show to the player when it is
// disconnected. The message is formatted following the rules of fmt.Sprintln without a newline at the end.
func (p *Player) Disconnect(msg ...interface{}) {
p.session().Disconnect(format(msg))
p.close()
}
// Transfer transfers the player to a server at the address passed. If the address could not be resolved, an
// error is returned. If it is returned, the player is closed and transferred to the server.
func (p *Player) Transfer(address string) (err error) {
addr, err := net.ResolveUDPAddr("udp", address)
if err != nil {
return err
}
ctx := event.C()
p.handler().HandleTransfer(ctx, addr)
ctx.Continue(func() {
p.session().Transfer(addr.IP, addr.Port)
err = p.Close()
})
return
}
// SendCommandOutput sends the output of a command to the player.
func (p *Player) SendCommandOutput(output *cmd.Output) {
p.session().SendCommandOutput(output)
}
// SendForm sends a form to the player for the client to fill out. Once the client fills it out, the Submit
// method of the form will be called.
// Note that the client may also close the form instead of filling it out, which will result in the form not
// having its Submit method called at all. Forms should never depend on the player actually filling out the
// form.
func (p *Player) SendForm(f form.Form) {
p.session().SendForm(f)
}
// ShowCoordinates enables the vanilla coordinates for the player.
func (p *Player) ShowCoordinates() {
p.session().EnableCoordinates(true)
}
// HideCoordinates disables the vanilla coordinates for the player.
func (p *Player) HideCoordinates() {
p.session().EnableCoordinates(false)
}
// SetNameTag changes the name tag displayed over the player in-game. Changing the name tag does not change
// the player's name in, for example, the player list or the chat.
func (p *Player) SetNameTag(name string) {
p.nameTag.Store(name)
p.updateState()
}
// SetSpeed sets the speed of the player. The value passed is the blocks/tick speed that the player will then
// obtain.
func (p *Player) SetSpeed(speed float64) {
p.speed.Store(speed)
p.s.SendSpeed(speed)
}
// Speed returns the speed of the player, returning a value that indicates the blocks/tick speed. The default
// speed of a player is 0.1.
func (p *Player) Speed() float64 {
return p.speed.Load()
}
// Health returns the current health of the player. It will always be lower than Player.MaxHealth().
func (p *Player) Health() float64 {
return p.health.Health()
}
// MaxHealth returns the maximum amount of health that a player may have. The MaxHealth will always be higher
// than Player.Health().
func (p *Player) MaxHealth() float64 {
return p.health.MaxHealth()
}
// SetMaxHealth sets the maximum health of the player. If the current health of the player is higher than the
// new maximum health, the health is set to the new maximum.
// SetMaxHealth panics if the max health passed is 0 or lower.
func (p *Player) SetMaxHealth(health float64) {
p.health.SetMaxHealth(health)
p.session().SendHealth(p.health)
}
// addHealth adds health to the player's current health.
func (p *Player) addHealth(health float64) {
p.health.AddHealth(health)
p.session().SendHealth(p.health)
}
// Heal heals the entity for a given amount of health. The source passed represents the cause of the
// healing, for example healing.SourceFood if the entity healed by having a full food bar. If the health
// added to the original health exceeds the entity's max health, Heal will not add the full amount.
// If the health passed is negative, Heal will not do anything.
func (p *Player) Heal(health float64, source healing.Source) {
if p.Dead() || health < 0 || !p.survival() {
return
}
ctx := event.C()
p.handler().HandleHeal(ctx, &health, source)
ctx.Continue(func() {
p.addHealth(health)
})
}
// Hurt hurts the player for a given amount of damage. The source passed represents the cause of the damage,
// for example damage.SourceEntityAttack if the player is attacked by another entity.
// If the final damage exceeds the health that the player currently has, the player is killed and will have to
// respawn.
// If the damage passed is negative, Hurt will not do anything.
func (p *Player) Hurt(dmg float64, source damage.Source) {
if p.Dead() || dmg < 0 || !p.survival() {
return
}
ctx := event.C()
p.handler().HandleHurt(ctx, &dmg, source)
ctx.Continue(func() {
if source.ReducedByArmour() {
p.Exhaust(0.1)
}
finalDamage := p.FinalDamageFrom(dmg, source)
a := p.absorption()
if a > 0 && (effect.Absorption{}).Absorbs(source) {
if finalDamage > a {
finalDamage -= a
p.SetAbsorption(0)
p.effects.Remove(effect.Absorption{}, p)
} else {
p.SetAbsorption(a - finalDamage)
finalDamage = 0
}
}
p.addHealth(-finalDamage)
for _, viewer := range p.World().Viewers(p.Position()) {
viewer.ViewEntityAction(p, action.Hurt{})
}
p.immunity.Store(time.Now().Add(time.Second / 2))
if p.Dead() {
p.kill(source)
}
})
}
// FinalDamageFrom resolves the final damage received by the player if it is attacked by the source passed
// with the damage passed. FinalDamageFrom takes into account things such as the armour worn and the
// enchantments on the individual pieces.
// The damage returned will be at the least 0.
func (p *Player) FinalDamageFrom(dmg float64, src damage.Source) float64 {
if src.ReducedByArmour() {
defencePoints, damageToArmour := 0.0, int(dmg/4)
if damageToArmour == 0 {
damageToArmour++
}
for i := 0; i < 4; i++ {
it, _ := p.armour.Inv().Item(i)
if a, ok := it.Item().(armour.Armour); ok {
defencePoints += a.DefencePoints()
if _, ok := it.Item().(item.Durable); ok {
_ = p.armour.Inv().SetItem(i, p.damageItem(it, damageToArmour))
}
}
}
// Armour in Bedrock edition reduces the damage taken by 4% for every armour point that the player
// has, with a maximum of 4*20=80%
dmg -= dmg * 0.04 * defencePoints
}
for _, e := range p.Effects() {
if resistance, ok := e.(effect.Resistance); ok {
dmg *= resistance.Multiplier(src)
}
}
// TODO: Account for enchantments.
if dmg < 0 {
dmg = 0
}
return dmg
}
// SetAbsorption sets the absorption health of a player. This extra health shows as golden hearts and do not
// actually increase the maximum health. Once the hearts are lost, they will not regenerate.
// Nothing happens if a negative number is passed.
func (p *Player) SetAbsorption(health float64) {
if health < 0 {
return
}
p.absorptionHealth.Store(health)
p.session().SendAbsorption(health)
}
// absorption returns the absorption health that the player has.
func (p *Player) absorption() float64 {
return p.absorptionHealth.Load()
}
// KnockBack knocks the player back with a given force and height. A source is passed which indicates the
// source of the velocity, typically the position of an attacking entity. The source is used to calculate the
// direction which the entity should be knocked back in.
func (p *Player) KnockBack(src mgl64.Vec3, force, height float64) {
if p.Dead() || !p.survival() {
return
}
if p.session() == session.Nop {
// TODO: Implement server-side movement and knock-back.
return
}
velocity := p.Position().Sub(src)
velocity[1] = 0
velocity = velocity.Normalize().Mul(force)
velocity[1] = height
resistance := 0.0
for _, i := range p.armour.All() {
if a, ok := i.Item().(armour.Armour); ok {
resistance += a.KnockBackResistance()
}
}
p.session().SendVelocity(velocity.Mul(1 - resistance))
}
// AttackImmune checks if the player is currently immune to entity attacks, meaning it was recently attacked.
func (p *Player) AttackImmune() bool {
return p.immunity.Load().(time.Time).After(time.Now())
}
// Food returns the current food level of a player. The level returned is guaranteed to always be between 0
// and 20. Every half drumstick is one level.
func (p *Player) Food() int {
return p.hunger.Food()
}
// SetFood sets the food level of a player. The level passed must be in a range of 0-20. If the level passed
// is negative, the food level will be set to 0. If the level exceeds 20, the food level will be set to 20.
func (p *Player) SetFood(level int) {
p.hunger.SetFood(level)
p.sendFood()
}
// AddFood adds a number of points to the food level of the player. If the new food level is negative or if
// it exceeds 20, it will be set to 0 or 20 respectively.
func (p *Player) AddFood(points int) {
p.hunger.AddFood(points)
p.sendFood()
}
// Saturate saturates the player's food bar with the amount of food points and saturation points passed. The
// total saturation of the player will never exceed its total food level.
func (p *Player) Saturate(food int, saturation float64) {
p.hunger.saturate(food, saturation)
p.sendFood()
}
// sendFood sends the current food properties to the client.
func (p *Player) sendFood() {
p.hunger.mu.RLock()
defer p.hunger.mu.RUnlock()
p.session().SendFood(p.hunger.foodLevel, p.hunger.saturationLevel, p.hunger.exhaustionLevel)
}
// AddEffect adds an entity.Effect to the Player. If the effect is instant, it is applied to the Player
// immediately. If not, the effect is applied to the player every time the Tick method is called.
// AddEffect will overwrite any effects present if the level of the effect is higher than the existing one, or
// if the effects' levels are equal and the new effect has a longer duration.
func (p *Player) AddEffect(e entity.Effect) {
p.effects.Add(e, p)
p.session().SendEffect(e)
p.updateState()
}
// RemoveEffect removes any effect that might currently be active on the Player.
func (p *Player) RemoveEffect(e entity.Effect) {
p.effects.Remove(e, p)
p.session().SendEffectRemoval(e)
p.updateState()
}
// Effects returns any effect currently applied to the entity. The returned effects are guaranteed not to have
// expired when returned.
func (p *Player) Effects() []entity.Effect {
return p.effects.Effects()
}
// Exhaust exhausts the player by the amount of points passed if the player is in survival mode. If the total
// exhaustion level exceeds 4, a saturation point, or food point, if saturation is 0, will be subtracted.
func (p *Player) Exhaust(points float64) {
if !p.survival() {
return
}
before := p.hunger.Food()
if (p.World().Difficulty() != difficulty.Peaceful{}) {
p.hunger.exhaust(points)
}
after := p.hunger.Food()
if before != after {
// Temporarily set the food level back so that it hasn't yet changed once the event is handled.
p.hunger.SetFood(before)
ctx := event.C()
p.handler().HandleFoodLoss(ctx, before, after)
ctx.Continue(func() {
p.hunger.SetFood(after)
if before >= 7 && after <= 6 {
// The client will stop sprinting by itself too, but we force it just to be sure.
p.StopSprinting()
}
})
}
p.sendFood()
}
// survival checks if the player is considered to be survival, meaning either adventure or survival game mode.
func (p *Player) survival() bool {
return p.GameMode() == gamemode.Survival{} || p.GameMode() == gamemode.Adventure{}
}
// canEdit checks if the player has a game mode that allows it to edit the world.
func (p *Player) canEdit() bool {
return p.GameMode() == gamemode.Creative{} || p.GameMode() == gamemode.Survival{}
}
// Dead checks if the player is considered dead. True is returned if the health of the player is equal to or
// lower than 0.
func (p *Player) Dead() bool {
return p.Health() <= 0
}
// kill kills the player, clearing its inventories and resetting it to its base state.
func (p *Player) kill(src damage.Source) {
for _, viewer := range p.World().Viewers(p.Position()) {
viewer.ViewEntityAction(p, action.Death{})
}
p.addHealth(-p.MaxHealth())
p.StopSneaking()
p.StopSprinting()
p.inv.Clear()
p.armour.Clear()
p.offHand.Clear()
for _, e := range p.Effects() {
p.RemoveEffect(e)
}
p.handler().HandleDeath(src)
// Wait for a little bit before removing the entity. The client displays a death animation while the
// player is dying.
time.AfterFunc(time.Millisecond*1100, func() {
if p.session() == session.Nop {
_ = p.Close()
return
}
if p.Dead() {
p.SetInvisible()
// We have an actual client connected to this player: We change its position server side so that in
// the future, the client won't respawn on the death location when disconnecting. The client should
// not see the movement itself yet, though.
p.pos.Store(p.World().Spawn().Vec3())
}
})
}
// Respawn spawns the player after it dies, so that its health is replenished and it is spawned in the world
// again. Nothing will happen if the player does not have a session connected to it.
func (p *Player) Respawn() {
if !p.Dead() || p.World() == nil || p.session() == session.Nop {
return
}
pos := p.World().Spawn().Vec3Middle()
p.handler().HandleRespawn(&pos)
p.addHealth(p.MaxHealth())
p.hunger.Reset()
p.sendFood()
p.World().AddEntity(p)
p.SetVisible()
p.Teleport(pos)
p.session().SendRespawn()
}
// StartSprinting makes a player start sprinting, increasing the speed of the player by 30% and making
// particles show up under the feet. The player will only start sprinting if its food level is high enough.
// If the player is sneaking when calling StartSprinting, it is stopped from sneaking.
func (p *Player) StartSprinting() {
if !p.sprinting.CAS(false, true) {
return
}
if !p.hunger.canSprint() {
return
}
p.StopSneaking()
p.SetSpeed(p.Speed() * 1.3)
p.updateState()
}
// Sprinting checks if the player is currently sprinting.
func (p *Player) Sprinting() bool {
return p.sprinting.Load()
}
// StopSprinting makes a player stop sprinting, setting back the speed of the player to its original value.
func (p *Player) StopSprinting() {
if !p.sprinting.CAS(true, false) {
return
}
p.SetSpeed(p.Speed() / 1.3)
p.updateState()
}
// StartSneaking makes a player start sneaking. If the player is already sneaking, StartSneaking will not do
// anything.
// If the player is sprinting while StartSneaking is called, the sprinting is stopped.
func (p *Player) StartSneaking() {
if !p.sneaking.CAS(false, true) {
return
}
p.StopSprinting()
p.updateState()
}
// Sneaking checks if the player is currently sneaking.
func (p *Player) Sneaking() bool {
return p.sneaking.Load()
}
// StopSneaking makes a player stop sneaking if it currently is. If the player is not sneaking, StopSneaking
// will not do anything.
func (p *Player) StopSneaking() {
if !p.sneaking.CAS(true, false) {
return
}
p.updateState()
}
// StartSwimming makes the player start swimming if it is not currently doing so. If the player is sneaking
// while StartSwimming is called, the sneaking is stopped.
func (p *Player) StartSwimming() {
if !p.swimming.CAS(false, true) {
return
}
p.StopSneaking()
p.updateState()
}
// Swimming checks if the player is currently swimming.
func (p *Player) Swimming() bool {
return p.swimming.Load()
}
// StopSwimming makes the player stop swimming if it is currently doing so.
func (p *Player) StopSwimming() {
if !p.swimming.CAS(true, false) {
return
}
p.updateState()
}
// SetInvisible sets the player invisible, so that other players will not be able to see it.
func (p *Player) SetInvisible() {
if !p.invisible.CAS(false, true) {
return
}
p.updateState()
}
// SetVisible sets the player visible again, so that other players can see it again. If the player was already
// visible, nothing happens.
func (p *Player) SetVisible() {
if !p.invisible.CAS(true, false) {
return
}
p.updateState()
}
// Inventory returns the inventory of the player. This inventory holds the items stored in the normal part of
// the inventory and the hotbar. It also includes the item in the main hand as returned by Player.HeldItems().
func (p *Player) Inventory() *inventory.Inventory {
return p.inv
}
// Armour returns the armour inventory of the player. This inventory yields 4 slots, for the helmet,
// chestplate, leggings and boots respectively.
func (p *Player) Armour() item.ArmourContainer {
return p.armour
}
// HeldItems returns the items currently held in the hands of the player. The first item stack returned is the
// one held in the main hand, the second is held in the off-hand.
// If no item was held in a hand, the stack returned has a count of 0. Stack.Empty() may be used to check if
// the hand held anything.
func (p *Player) HeldItems() (mainHand, offHand item.Stack) {
offHand, _ = p.offHand.Item(1)
mainHand, _ = p.inv.Item(int(p.heldSlot.Load()))
return mainHand, offHand
}
// SetHeldItems sets items to the main hand and the off-hand of the player. The Stacks passed may be empty
// (Stack.Empty()) to clear the held item.
func (p *Player) SetHeldItems(mainHand, offHand item.Stack) {
_ = p.inv.SetItem(int(p.heldSlot.Load()), mainHand)
_ = p.offHand.SetItem(1, offHand)
}
// SetGameMode sets the game mode of a player. The game mode specifies the way that the player can interact
// with the world that it is in.
func (p *Player) SetGameMode(mode gamemode.GameMode) {
p.gameModeMu.Lock()
p.gameMode = mode
p.gameModeMu.Unlock()
p.session().SendGameMode(mode)
}
// GameMode returns the current game mode assigned to the player. If not changed, the game mode returned will
// be the same as that of the world that the player spawns in.
// The game mode may be changed using Player.SetGameMode().
func (p *Player) GameMode() gamemode.GameMode {
p.gameModeMu.RLock()
mode := p.gameMode
p.gameModeMu.RUnlock()
return mode
}
// UseItem uses the item currently held in the player's main hand in the air. Generally, nothing happens,
// unless the held item implements the item.Usable interface, in which case it will be activated.
// This generally happens for items such as throwable items like snowballs.
func (p *Player) UseItem() {
if !p.canReach(p.Position()) {
return
}
i, left := p.HeldItems()
ctx := event.C()
p.handler().HandleItemUse(ctx)
ctx.Continue(func() {
usable, ok := i.Item().(item.Usable)
if !ok {
// The item wasn't usable, so we can stop doing anything right away.
return
}
ctx := &item.UseContext{}
if usable.Use(p.World(), p, ctx) {
// We only swing the player's arm if the item held actually does something. If it doesn't, there is no
// reason to swing the arm.
p.swingArm()
p.SetHeldItems(p.subtractItem(p.damageItem(i, ctx.Damage), ctx.CountSub), left)
p.addNewItem(ctx)
}
})
}
// UseItemOnBlock uses the item held in the main hand of the player on a block at the position passed. The
// player is assumed to have clicked the face passed with the relative click position clickPos.
// If the item could not be used successfully, for example when the position is out of range, the method
// returns immediately.
func (p *Player) UseItemOnBlock(pos world.BlockPos, face world.Face, clickPos mgl64.Vec3) {
if !p.canReach(pos.Vec3Centre()) {
return
}
i, left := p.HeldItems()
ctx := event.C()
p.handler().HandleItemUseOnBlock(ctx, pos, face, clickPos)
ctx.Continue(func() {
if activatable, ok := p.World().Block(pos).(block.Activatable); ok {
// If a player is sneaking, it will not activate the block clicked, unless it is not holding any
// items, in which the block will activated as usual.
if !p.Sneaking() || i.Empty() {
p.swingArm()
// The block was activated: Blocks such as doors must always have precedence over the item being
// used.
activatable.Activate(pos, face, p.World(), p)
return
}
}
if i.Empty() {
return
}
if usableOnBlock, ok := i.Item().(item.UsableOnBlock); ok {
// The item does something when used on a block.
ctx := &item.UseContext{}
if usableOnBlock.UseOnBlock(pos, face, clickPos, p.World(), p, ctx) {
p.swingArm()
p.SetHeldItems(p.subtractItem(p.damageItem(i, ctx.Damage), ctx.CountSub), left)
p.addNewItem(ctx)
}
} else if b, ok := i.Item().(world.Block); ok && p.canEdit() {
// The item IS a block, meaning it is being placed.
replacedPos := pos
if replaceable, ok := p.World().Block(pos).(block.Replaceable); !ok || !replaceable.ReplaceableBy(b) {
// The block clicked was either not replaceable, or not replaceable using the block passed.
replacedPos = pos.Side(face)
}
if replaceable, ok := p.World().Block(replacedPos).(block.Replaceable); ok && replaceable.ReplaceableBy(b) && !replacedPos.OutOfBounds() {
if p.placeBlock(replacedPos, b) && p.survival() {
p.SetHeldItems(p.subtractItem(i, 1), left)
}
}
}
})
ctx.Stop(func() {
p.World().SetBlock(pos, p.World().Block(pos))
p.World().SetBlock(pos.Side(face), p.World().Block(pos.Side(face)))
if liq, ok := p.World().Liquid(pos); ok {
p.World().SetLiquid(pos, liq)
}
if liq, ok := p.World().Liquid(pos.Side(face)); ok {
p.World().SetLiquid(pos.Side(face), liq)
}
})
}
// UseItemOnEntity uses the item held in the main hand of the player on the entity passed, provided it is
// within range of the player.
// If the item held in the main hand of the player does nothing when used on an entity, nothing will happen.
func (p *Player) UseItemOnEntity(e world.Entity) {
if !p.canReach(e.Position()) {
return
}
i, left := p.HeldItems()
ctx := event.C()
p.handler().HandleItemUseOnEntity(ctx, e)
ctx.Continue(func() {
if usableOnEntity, ok := i.Item().(item.UsableOnEntity); ok {
ctx := &item.UseContext{}
if usableOnEntity.UseOnEntity(e, e.World(), p, ctx) {
p.swingArm()
p.SetHeldItems(p.subtractItem(p.damageItem(i, ctx.Damage), ctx.CountSub), left)
p.addNewItem(ctx)
}
}
})
}
// AttackEntity uses the item held in the main hand of the player to attack the entity passed, provided it is
// within range of the player.
// The damage dealt to the entity will depend on the item held by the player and any effects the player may
// have.
// If the player cannot reach the entity at its position, the method returns immediately.
func (p *Player) AttackEntity(e world.Entity) {
if !p.canReach(e.Position()) {
return
}
i, left := p.HeldItems()
ctx := event.C()
p.handler().HandleAttackEntity(ctx, e)
ctx.Continue(func() {
p.swingArm()
living, ok := e.(entity.Living)
if !ok {
return
}
if living.AttackImmune() {
return
}
p.StopSprinting()
healthBefore := living.Health()
damageDealt := i.AttackDamage()
for _, e := range p.Effects() {
if strength, ok := e.(effect.Strength); ok {
damageDealt += damageDealt * strength.Multiplier()
} else if weakness, ok := e.(effect.Weakness); ok {
damageDealt += damageDealt * weakness.Multiplier()
}
}
living.Hurt(damageDealt, damage.SourceEntityAttack{Attacker: p})
living.KnockBack(p.Position(), 0.45, 0.3608)
if mgl64.FloatEqual(healthBefore, living.Health()) {
p.World().PlaySound(entity.EyePosition(e), sound.Attack{})
} else {
p.World().PlaySound(entity.EyePosition(e), sound.Attack{Damage: true})
p.Exhaust(0.1)
}
if durable, ok := i.Item().(item.Durable); ok {
p.SetHeldItems(p.damageItem(i, durable.DurabilityInfo().AttackDurability), left)
}
})
}
// StartBreaking makes the player start breaking the block at the position passed using the item currently
// held in its main hand.
// If no block is present at the position, or if the block is out of range, StartBreaking will return
// immediately and the block will not be broken. StartBreaking will stop the breaking of any block that the
// player might be breaking before this method is called.
func (p *Player) StartBreaking(pos world.BlockPos) {
p.AbortBreaking()
if _, air := p.World().Block(pos).(block.Air); air || !p.canReach(pos.Vec3Centre()) {
// The block was either out of range or air, so it can't be broken by the player.
return
}
ctx := event.C()
p.handler().HandleStartBreak(ctx, pos)
ctx.Continue(func() {
p.breaking.Store(true)
p.breakingPos.Store(pos)
p.swingArm()
breakTime := p.breakTime(pos)
for _, viewer := range p.World().Viewers(pos.Vec3()) {
viewer.ViewBlockAction(pos, blockAction.StartCrack{BreakTime: breakTime})
}
p.lastBreakDuration = breakTime
})
}
// breakTime returns the time needed to break a block at the position passed, taking into account the item
// held, if the player is on the ground/underwater and if the player has any effects.
func (p *Player) breakTime(pos world.BlockPos) time.Duration {
held, _ := p.HeldItems()
breakTime := block.BreakDuration(p.World().Block(pos), held)
if !p.OnGround() {
breakTime *= 5
}
if _, ok := p.World().Liquid(world.BlockPosFromVec3(p.Position().Add(mgl64.Vec3{0, p.EyeHeight()}))); ok {
breakTime *= 5
}
for _, e := range p.Effects() {
if haste, ok := e.(effect.Haste); ok {
breakTime = time.Duration(float64(breakTime) * haste.Multiplier())
} else if fatigue, ok := e.(effect.MiningFatigue); ok {
breakTime = time.Duration(float64(breakTime) * fatigue.Multiplier())
} else if conduitPower, ok := e.(effect.ConduitPower); ok {
breakTime = time.Duration(float64(breakTime) * conduitPower.Multiplier())
}
}
return breakTime
}
// FinishBreaking makes the player finish breaking the block it is currently breaking, or returns immediately
// if the player isn't breaking anything.
// FinishBreaking will stop the animation and break the block.
func (p *Player) FinishBreaking() {
if !p.breaking.Load() {
return
}
p.AbortBreaking()
p.BreakBlock(p.breakingPos.Load().(world.BlockPos))
}
// AbortBreaking makes the player stop breaking the block it is currently breaking, or returns immediately
// if the player isn't breaking anything.
// Unlike FinishBreaking, AbortBreaking does not stop the animation.
func (p *Player) AbortBreaking() {
if !p.breaking.CAS(true, false) {
return
}
p.breakParticleCounter.Store(0)
pos := p.breakingPos.Load().(world.BlockPos)
for _, viewer := range p.World().Viewers(pos.Vec3()) {
viewer.ViewBlockAction(pos, blockAction.StopCrack{})
}
}
// ContinueBreaking makes the player continue breaking the block it started breaking after a call to
// Player.StartBreaking().
// The face passed is used to display particles on the side of the block broken.
func (p *Player) ContinueBreaking(face world.Face) {
if !p.breaking.Load() {
return
}
pos := p.breakingPos.Load().(world.BlockPos)
p.swingArm()
b := p.World().Block(pos)
p.World().AddParticle(pos.Vec3(), particle.PunchBlock{Block: b, Face: face})
if p.breakParticleCounter.Add(1)%5 == 0 {
// We send this sound only every so often. Vanilla doesn't send it every tick while breaking
// either. Every 5 ticks seems accurate.
p.World().PlaySound(pos.Vec3(), sound.BlockBreaking{Block: p.World().Block(pos)})
}
breakTime := p.breakTime(pos)
if breakTime != p.lastBreakDuration {
for _, viewer := range p.World().Viewers(pos.Vec3()) {
viewer.ViewBlockAction(pos, blockAction.ContinueCrack{BreakTime: breakTime})
}
p.lastBreakDuration = breakTime
}
}
// PlaceBlock makes the player place the block passed at the position passed, granted it is within the range
// of the player.
// A use context may be passed to obtain information on if the block placement was successful. (SubCount will
// be incremented). Nil may also be passed for the context parameter.
func (p *Player) PlaceBlock(pos world.BlockPos, b world.Block, ctx *item.UseContext) {
if p.placeBlock(pos, b) {
ctx.CountSub++
}
}
// placeBlock makes the player place the block passed at the position passed, granted it is within the range
// of the player. A bool is returned indicating if a block was placed successfully.
func (p *Player) placeBlock(pos world.BlockPos, b world.Block) (success bool) {
defer func() {
if !success {
p.World().SetBlock(pos, p.World().Block(pos))
}
}()
if !p.canReach(pos.Vec3Centre()) || !p.canEdit() {
return false
}
if p.obstructedPos(pos, b) {
return false
}
ctx := event.C()
p.handler().HandleBlockPlace(ctx, pos, b)
ctx.Continue(func() {
p.World().PlaceBlock(pos, b)
p.World().PlaySound(pos.Vec3(), sound.BlockPlace{Block: b})
p.swingArm()
success = true
})
ctx.Stop(func() {
pos.Neighbours(func(neighbour world.BlockPos) {
p.World().SetBlock(neighbour, p.World().Block(neighbour))
})
p.World().SetBlock(pos, p.World().Block(pos))
})
return
}
// obstructedPos checks if the position passed is obstructed if the block passed is attempted to be placed.
// This returns true if there is an entity in the way that could prevent the block from being placed.
func (p *Player) obstructedPos(pos world.BlockPos, b world.Block) bool {
blockBoxes := []physics.AABB{physics.NewAABB(mgl64.Vec3{}, mgl64.Vec3{1, 1, 1})}
if aabb, ok := b.(block.AABBer); ok {
blockBoxes = aabb.AABB(pos, p.World())
}
for i, box := range blockBoxes {
blockBoxes[i] = box.Translate(pos.Vec3())
}
around := p.World().EntitiesWithin(physics.NewAABB(mgl64.Vec3{-3, -3, -3}, mgl64.Vec3{3, 3, 3}).Translate(pos.Vec3()))
for _, e := range around {
if _, ok := e.(*entity.Item); ok {
// Placing blocks inside of item entities is fine.
continue
}
if physics.AnyIntersections(blockBoxes, e.AABB().Translate(e.Position())) {
return true
}
}
return false
}
// BreakBlock makes the player break a block in the world at a position passed. If the player is unable to
// reach the block passed, the method returns immediately.
func (p *Player) BreakBlock(pos world.BlockPos) {
if !p.canReach(pos.Vec3Centre()) || !p.canEdit() {
return
}
b := p.World().Block(pos)
if _, air := b.(block.Air); air {
// Don't do anything if the position broken is already air.
return
}
if _, breakable := b.(block.Breakable); !breakable && p.survival() {
// Block cannot be broken server-side. Set the block back so viewers have it resent and cancel all
// further action.
p.World().SetBlock(pos, p.World().Block(pos))
return
}
ctx := event.C()
p.handler().HandleBlockBreak(ctx, pos)
ctx.Continue(func() {
p.swingArm()
p.World().BreakBlock(pos)
held, left := p.HeldItems()
for _, drop := range p.drops(held, b) {
itemEntity := entity.NewItem(drop, pos.Vec3Centre())
itemEntity.SetVelocity(mgl64.Vec3{rand.Float64()*0.2 - 0.1, 0.2, rand.Float64()*0.2 - 0.1})
p.World().AddEntity(itemEntity)
}
p.Exhaust(0.005)
if !block.BreaksInstantly(b, held) {
if durable, ok := held.Item().(item.Durable); ok {
p.SetHeldItems(p.damageItem(held, durable.DurabilityInfo().BreakDurability), left)
}
}
})
ctx.Stop(func() {
p.World().SetBlock(pos, p.World().Block(pos))
})
}
// drops returns the drops that the player can get from the block passed using the item held.
func (p *Player) drops(held item.Stack, b world.Block) []item.Stack {
t, ok := held.Item().(tool.Tool)
if !ok {
t = tool.None{}
}
var drops []item.Stack
if container, ok := b.(block.Container); ok {
// If the block is a container, it should drop its inventory contents regardless whether the
// player is in creative mode or not.
drops = container.Inventory().Contents()
if breakable, ok := b.(block.Breakable); ok && p.survival() {
if breakable.BreakInfo().Harvestable(t) {
drops = breakable.BreakInfo().Drops(t)
}
}
container.Inventory().Clear()
} else if breakable, ok := b.(block.Breakable); ok && p.survival() {
if breakable.BreakInfo().Harvestable(t) {
drops = breakable.BreakInfo().Drops(t)
}
} else if it, ok := b.(world.Item); ok && p.survival() {
drops = []item.Stack{item.NewStack(it, 1)}
}
return drops
}
// Teleport teleports the player to a target position in the world. Unlike Move, it immediately changes the
// position of the player, rather than showing an animation.
func (p *Player) Teleport(pos mgl64.Vec3) {
// Generally it is expected you are teleported to the middle of the block.
pos = pos.Add(mgl64.Vec3{0.5, 0, 0.5})
ctx := event.C()
p.handler().HandleTeleport(ctx, pos)
ctx.Continue(func() {
p.teleport(pos)
})
}
// teleport teleports the player to a target position in the world. It does not call the handler of the
// player.
func (p *Player) teleport(pos mgl64.Vec3) {
p.session().ViewEntityTeleport(p, pos)
for _, v := range p.World().Viewers(p.Position()) {
v.ViewEntityTeleport(p, pos)
}
p.pos.Store(pos)
}
// Move moves the player from one position to another in the world, by adding the delta passed to the current
// position of the player.
func (p *Player) Move(deltaPos mgl64.Vec3) {
if p.Dead() || deltaPos.ApproxEqual(mgl64.Vec3{}) {
return
}
ctx := event.C()
p.handler().HandleMove(ctx, p.Position().Add(deltaPos), p.Yaw(), p.Pitch())
ctx.Continue(func() {
for _, v := range p.World().Viewers(p.Position()) {
v.ViewEntityMovement(p, deltaPos, 0, 0)
}
p.pos.Store(p.Position().Add(deltaPos))
if p.Swimming() {
p.Exhaust(0.01 * deltaPos.Len())
} else if p.Sprinting() {
p.Exhaust(0.1 * deltaPos.Len())
}
})
ctx.Stop(func() {
p.teleport(p.Position())
})
}
// Rotate rotates the player, adding deltaYaw and deltaPitch to the respective values.
func (p *Player) Rotate(deltaYaw, deltaPitch float64) {
if p.Dead() || (mgl64.FloatEqual(deltaYaw, 0) && mgl64.FloatEqual(deltaPitch, 0)) {
return
}
p.handler().HandleMove(event.C(), p.Position(), p.Yaw()+deltaYaw, p.Pitch()+deltaPitch)
// Cancelling player rotation is rather scuffed, so we don't do that.
for _, v := range p.World().Viewers(p.Position()) {
v.ViewEntityMovement(p, mgl64.Vec3{}, deltaYaw, deltaPitch)
}
p.yaw.Store(p.Yaw() + deltaYaw)
p.pitch.Store(p.Pitch() + deltaPitch)
}
// Facing returns the horizontal direction that the player is facing.
func (p *Player) Facing() world.Direction {
return entity.Facing(p)
}
// World returns the world that the player is currently in.
func (p *Player) World() *world.World {
w, _ := world.OfEntity(p)
return w
}
// Position returns the current position of the player. It may be changed as the player moves or is moved
// around the world.
func (p *Player) Position() mgl64.Vec3 {
return p.pos.Load().(mgl64.Vec3)
}
// Yaw returns the yaw of the entity. This is horizontal rotation (rotation around the vertical axis), and
// is 0 when the entity faces forward.
func (p *Player) Yaw() float64 {
return p.yaw.Load()
}
// Pitch returns the pitch of the entity. This is vertical rotation (rotation around the horizontal axis),
// and is 0 when the entity faces forward.
func (p *Player) Pitch() float64 {
return p.pitch.Load()
}
// Collect makes the player collect the item stack passed, adding it to the inventory.
func (p *Player) Collect(s item.Stack) (n int) {
ctx := event.C()
p.handler().HandleItemPickup(ctx, s)
ctx.Continue(func() {
n, _ = p.Inventory().AddItem(s)
})
return
}
// OpenBlockContainer opens a block container, such as a chest, at the position passed. If no container was
// present at that location, OpenBlockContainer does nothing.
// OpenBlockContainer will also do nothing if the player has no session connected to it.
func (p *Player) OpenBlockContainer(pos world.BlockPos) {
if p.session() == session.Nop {
return
}
p.session().OpenBlockContainer(pos)
}
// Latency returns a rolling average of latency between the sending and the receiving end of the connection of
// the player.
// The latency returned is updated continuously and is half the round trip time (RTT).
// If the Player does not have a session associated with it, Latency returns 0.
func (p *Player) Latency() time.Duration {
if p.session() == session.Nop {
return 0
}
return p.session().Latency()
}
// Tick ticks the entity, performing actions such as checking if the player is still breaking a block.
func (p *Player) Tick(current int64) {
if p.Dead() {
return
}
if _, ok := p.World().Liquid(world.BlockPosFromVec3(p.Position())); !ok {
p.StopSwimming()
}
if p.checkOnGround() {
p.onGround.Store(true)
} else {
p.onGround.Store(false)
}
p.tickFood()
p.effects.Tick(p)
if p.Position()[1] < 0 && p.survival() && current%10 == 0 {
p.Hurt(4, damage.SourceVoid{})
}
}
// tickFood ticks food related functionality, such as the depletion of the food bar and regeneration if it
// is full enough.
func (p *Player) tickFood() {
p.hunger.foodTick++
if p.hunger.foodTick == 10 && (p.hunger.canQuicklyRegenerate() || p.World().Difficulty() == difficulty.Peaceful{}) {
p.hunger.foodTick = 0
p.regenerate()
if (p.World().Difficulty() == difficulty.Peaceful{}) {
p.AddFood(1)
}
} else if p.hunger.foodTick == 80 {
p.hunger.foodTick = 0
if p.hunger.canRegenerate() {
p.regenerate()
} else if p.hunger.starving() {
p.starve()
}
}
}
// regenerate attempts to regenerate half a heart of health, typically caused by a full food bar.
func (p *Player) regenerate() {
if p.Health() == p.MaxHealth() {
return
}
p.Heal(1, healing.SourceFood{})
p.Exhaust(6)
}
// starve deals starvation damage to the player if the difficult allows it. In peaceful mode, no damage will
// ever be dealt. In easy mode, damage will only be dealt if the player has more than 10 health. In normal
// mode, damage will only be dealt if the player has more than 2 health and in hard mode, damage will always
// be dealt.
func (p *Player) starve() {
switch p.World().Difficulty().(type) {
case difficulty.Peaceful:
return
case difficulty.Easy:
if p.Health() <= 10 {
return
}
case difficulty.Normal:
if p.Health() <= 2 {
return
}
}
p.Hurt(1, damage.SourceStarvation{})
}
// checkOnGround checks if the player is currently considered to be on the ground.
func (p *Player) checkOnGround() bool {
pos := p.Position()
pAABB := p.AABB().Translate(pos)
min, max := pAABB.Min(), pAABB.Max()
for x := min[0]; x <= max[0]+1; x++ {
for z := min[2]; z <= max[2]+1; z++ {
for y := pos[1] - 1; y < pos[1]+1; y++ {
bPos := world.BlockPosFromVec3(mgl64.Vec3{x, y, z})
b := p.World().Block(bPos)
aabbList := []physics.AABB{physics.NewAABB(mgl64.Vec3{}, mgl64.Vec3{1, 1, 1})}
if aabb, ok := b.(block.AABBer); ok {
aabbList = aabb.AABB(bPos, p.World())
}
for _, aabb := range aabbList {
if aabb.GrowVertically(0.05).Translate(bPos.Vec3()).IntersectsWith(pAABB) {
return true
}
}
}
}
}
return false
}
// Velocity returns the current velocity of the player.
func (p *Player) Velocity() mgl64.Vec3 {
// TODO: Implement server-side movement of player entities.
return p.velocity.Load().(mgl64.Vec3)
}
// SetVelocity sets the velocity of the player.
func (p *Player) SetVelocity(v mgl64.Vec3) {
// TODO: Implement server-side movement of player entities.
p.velocity.Store(v)
}
// AABB returns the axis aligned bounding box of the player.
func (p *Player) AABB() physics.AABB {
switch {
case p.Sneaking():
return physics.NewAABB(mgl64.Vec3{-0.3, 0, -0.3}, mgl64.Vec3{0.3, 1.65, 0.3})
case p.Swimming():
return physics.NewAABB(mgl64.Vec3{-0.3, 0, -0.3}, mgl64.Vec3{0.3, 0.6, 0.3})
default:
return physics.NewAABB(mgl64.Vec3{-0.3, 0, -0.3}, mgl64.Vec3{0.3, 1.8, 0.3})
}
}
// OnGround checks if the player is considered to be on the ground.
func (p *Player) OnGround() bool {
return p.onGround.Load()
}
// EyeHeight returns the eye height of the player: 1.62.
func (p *Player) EyeHeight() float64 {
return 1.62
}
// State returns the current state of the player. Types from the `entity/state` package are returned
// depending on what the player is currently doing.
func (p *Player) State() (s []state.State) {
if p.Sneaking() {
s = append(s, state.Sneaking{})
}
if p.Sprinting() {
s = append(s, state.Sprinting{})
}
if p.Swimming() {
s = append(s, state.Swimming{})
}
if p.canBreathe() || !p.survival() {
s = append(s, state.Breathing{})
}
if p.invisible.Load() {
s = append(s, state.Invisible{})
}
colour, ambient := effect.ResultingColour(p.Effects())
if (colour != color.RGBA{}) {
s = append(s, state.EffectBearing{ParticleColour: colour, Ambient: ambient})
}
s = append(s, state.Named{NameTag: p.nameTag.Load()})
return
}
// updateState updates the state of the player to all viewers of the player.
func (p *Player) updateState() {
for _, v := range p.World().Viewers(p.Position()) {
v.ViewEntityState(p, p.State())
}
}
// canBreathe checks if the player is currently able to breathe. If it's underwater and the player does not
// have the water breathing or conduit power effect, this returns false.
func (p *Player) canBreathe() bool {
for _, e := range p.Effects() {
if _, waterBreathing := e.(effect.WaterBreathing); waterBreathing {
return true
}
if _, conduitPower := e.(effect.ConduitPower); conduitPower {
return true
}
}
_, submerged := p.World().Liquid(world.BlockPosFromVec3(p.Position().Add(mgl64.Vec3{0, p.EyeHeight()})))
return !submerged
}
// swingArm makes the player swing its arm.
func (p *Player) swingArm() {
if p.Dead() {
return
}
for _, v := range p.World().Viewers(p.Position()) {
v.ViewEntityAction(p, action.SwingArm{})
}
}
// Close closes the player and removes it from the world.
// Close disconnects the player with a 'Connection closed.' message. Disconnect should be used to disconnect a
// player with a custom message.
func (p *Player) Close() error {
if p.World() == nil {
return nil
}
p.session().Disconnect("Connection closed.")
p.close()
return nil
}
// damageItem damages the item stack passed with the damage passed and returns the new stack. If the item
// broke, a breaking sound is played.
// If the player is not survival, the original stack is returned.
func (p *Player) damageItem(s item.Stack, d int) item.Stack {
if !p.survival() || d == 0 {
return s
}
ctx := event.C()
p.handler().HandleItemDamage(ctx, s, d)
ctx.Continue(func() {
s = s.Damage(d)
if s.Empty() {
p.World().PlaySound(p.Position(), sound.ItemBreak{})
}
})
return s
}
// subtractItem subtracts d from the count of the item stack passed and returns it, if the player is in
// survival or adventure mode.
func (p *Player) subtractItem(s item.Stack, d int) item.Stack {
if p.survival() && d != 0 {
return s.Grow(-d)
}
return s
}
// addNewItem adds the new item of the context passed to the inventory.
func (p *Player) addNewItem(ctx *item.UseContext) {
if !p.survival() || ctx.NewItem.Empty() {
return
}
held, left := p.HeldItems()
if held.Empty() {
p.SetHeldItems(ctx.NewItem, left)
return
}
// TODO: Drop item entities when inventory is full.
_, _ = p.Inventory().AddItem(ctx.NewItem)
}
// canReach checks if a player can reach a position with its current range. The range depends on if the player
// is either survival or creative mode.
func (p *Player) canReach(pos mgl64.Vec3) bool {
const (
eyeHeight = 1.62
creativeRange = 13.0
survivalRange = 7.0
)
if (p.GameMode() == gamemode.Spectator{}) {
return false
}
eyes := p.Position().Add(mgl64.Vec3{0, eyeHeight})
if (p.GameMode() == gamemode.Creative{}) {
return world.Distance(eyes, pos) <= creativeRange && !p.Dead()
}
return world.Distance(eyes, pos) <= survivalRange && !p.Dead()
}
// close closed the player without disconnecting it. It executes code shared by both the closing and the
// disconnecting of players.
func (p *Player) close() {
p.handler().HandleQuit()
p.Handle(NopHandler{})
chat.Global.Unsubscribe(p)
p.sMutex.Lock()
s := p.s
p.s = nil
// Clear the inventories so that they no longer hold references to the connection.
_ = p.inv.Close()
_ = p.offHand.Close()
_ = p.armour.Close()
p.sMutex.Unlock()
if p.xuid == "" {
p.World().RemoveEntity(p)
} else if s != nil {
s.CloseConnection()
}
}
// session returns the network session of the player. If it has one, it is returned. If not, a no-op session
// is returned.
func (p *Player) session() *session.Session {
p.sMutex.RLock()
s := p.s
p.sMutex.RUnlock()
if s == nil {
return session.Nop
}
return s
}
// handler returns the handler of the player.
func (p *Player) handler() Handler {
p.hMutex.RLock()
handler := p.h
p.hMutex.RUnlock()
return handler
}
// broadcastItems broadcasts the items held to viewers.
func (p *Player) broadcastItems(int, item.Stack) {
for _, viewer := range p.World().Viewers(p.Position()) {
viewer.ViewEntityItems(p)
}
}
// broadcastArmour broadcasts the armour equipped to viewers.
func (p *Player) broadcastArmour(int, item.Stack) {
for _, viewer := range p.World().Viewers(p.Position()) {
viewer.ViewEntityArmour(p)
}
}
// format is a utility function to format a list of values to have spaces between them, but no newline at the
// end, which is typically used for sending messages, popups and tips.
func format(a []interface{}) string {
return strings.TrimSuffix(strings.TrimSuffix(fmt.Sprintln(a...), "\n"), "\n")
}
<file_sep>package entity
import (
"github.com/df-mc/dragonfly/dragonfly/entity/action"
"github.com/df-mc/dragonfly/dragonfly/entity/physics"
"github.com/df-mc/dragonfly/dragonfly/entity/state"
"github.com/df-mc/dragonfly/dragonfly/item"
"github.com/df-mc/dragonfly/dragonfly/world"
"github.com/go-gl/mathgl/mgl64"
"sync/atomic"
)
// Item represents an item entity which may be added to the world. Players and several humanoid entities such
// as zombies are able to pick up these entities so that the items are added to their inventory.
type Item struct {
age int
i item.Stack
velocity, pos atomic.Value
*movementComputer
}
// NewItem creates a new item entity using the item stack passed. The item entity will be positioned at the
// position passed.
// If the stack's count exceeds its max count, the count of the stack will be changed to the maximum.
func NewItem(i item.Stack, pos mgl64.Vec3) *Item {
if i.Count() > i.MaxCount() {
i = i.Grow(i.Count() - i.MaxCount())
}
it := &Item{i: i, movementComputer: &movementComputer{
gravity: 0.04,
dragBeforeGravity: true,
}}
it.pos.Store(pos)
it.velocity.Store(mgl64.Vec3{})
return it
}
// Item returns the item stack that the item entity holds.
func (it *Item) Item() item.Stack {
return it.i
}
// Position returns the current position of the item entity.
func (it *Item) Position() mgl64.Vec3 {
return it.pos.Load().(mgl64.Vec3)
}
// World returns the world that the item entity is currently in, or nil if it is not added to a world.
func (it *Item) World() *world.World {
w, _ := world.OfEntity(it)
return w
}
// Tick ticks the entity, performing movement.
func (it *Item) Tick(current int64) {
if it.Position()[1] < 0 && current%10 == 0 {
_ = it.Close()
return
}
if it.age++; it.age > 6000 {
_ = it.Close()
return
}
it.pos.Store(it.tickMovement(it))
it.checkNearby()
}
// checkNearby checks the entities of the chunks around for item collectors and other item stacks. If a
// collector is found in range, the item will be picked up. If another item stack with the same item type is
// found in range, the item stacks will merge.
func (it *Item) checkNearby() {
for _, e := range it.World().EntitiesWithin(it.AABB().Translate(it.Position()).Grow(0.75)) {
if e == it {
// Skip the item entity itself.
continue
}
if collector, ok := e.(item.Collector); ok {
// A collector was within range to pick up the entity.
it.collect(collector)
return
} else if other, ok := e.(*Item); ok {
// Another item entity was in range to merge with.
if it.merge(other) {
return
}
}
}
}
// merge merges the item entity with another item entity.
func (it *Item) merge(other *Item) bool {
if other.i.Count() == other.i.MaxCount() || it.i.Count() == it.i.MaxCount() {
// Either stack is already filled up to the maximum, meaning we can't change anything any way.
return false
}
if !it.i.Comparable(other.i) {
return false
}
a, b := other.i.AddStack(it.i)
newA := NewItem(a, other.Position())
newA.SetVelocity(other.Velocity())
it.World().AddEntity(newA)
if !b.Empty() {
newB := NewItem(b, it.Position())
newB.SetVelocity(it.Velocity())
it.World().AddEntity(newB)
}
_ = it.Close()
_ = other.Close()
return true
}
// collect makes a collector collect the item (or at least part of it).
func (it *Item) collect(collector item.Collector) {
for _, viewer := range it.World().Viewers(it.Position()) {
viewer.ViewEntityAction(it, action.PickedUp{Collector: collector})
}
n := collector.Collect(it.i)
if n == 0 {
return
}
if n == it.i.Count() {
// The collector picked up the entire stack.
_ = it.Close()
return
}
// Create a new item entity and shrink it by the amount of items that the collector collected.
it.World().AddEntity(NewItem(it.i.Grow(-n), it.Position()))
_ = it.Close()
}
// Velocity returns the current velocity of the item. The values in the Vec3 returned represent the speed on
// that axis in blocks/tick.
func (it *Item) Velocity() mgl64.Vec3 {
return it.velocity.Load().(mgl64.Vec3)
}
// SetVelocity sets the velocity of the item entity. The values in the Vec3 passed represent the speed on
// that axis in blocks/tick.
func (it *Item) SetVelocity(v mgl64.Vec3) {
it.velocity.Store(v)
}
// Yaw always returns 0.
func (it *Item) Yaw() float64 { return 0 }
// Pitch always returns 0.
func (it *Item) Pitch() float64 { return 0 }
// AABB ...
func (it *Item) AABB() physics.AABB {
return physics.NewAABB(mgl64.Vec3{-0.125, 0, -0.125}, mgl64.Vec3{0.125, 0.25, 0.125})
}
// State ...
func (it *Item) State() []state.State {
return nil
}
// Close closes the item, removing it from the world that it is currently in.
func (it *Item) Close() error {
it.World().RemoveEntity(it)
return nil
}
<file_sep>package item
import (
"github.com/df-mc/dragonfly/dragonfly/internal/item_internal"
"github.com/df-mc/dragonfly/dragonfly/item/tool"
"github.com/df-mc/dragonfly/dragonfly/world"
"github.com/df-mc/dragonfly/dragonfly/world/sound"
"github.com/go-gl/mathgl/mgl64"
)
// Axe is a tool generally used for mining wood-like blocks. It may also be used to break some plant-like
// blocks at a faster pace such as pumpkins.
type Axe struct {
// Tier is the tier of the axe.
Tier tool.Tier
}
// UseOnBlock handles the stripping of logs when a player clicks a log with an axe.
func (a Axe) UseOnBlock(pos world.BlockPos, _ world.Face, _ mgl64.Vec3, w *world.World, _ User, ctx *UseContext) bool {
if b := w.Block(pos); item_internal.IsUnstrippedLog(b) {
strippedLog := item_internal.StripLog(b)
w.SetBlock(pos, strippedLog)
w.PlaySound(pos.Vec3(), sound.ItemUseOn{Block: strippedLog})
ctx.DamageItem(1)
return true
}
return false
}
// MaxCount always returns 1.
func (a Axe) MaxCount() int {
return 1
}
// DurabilityInfo ...
func (a Axe) DurabilityInfo() DurabilityInfo {
return DurabilityInfo{
MaxDurability: a.Tier.Durability,
BrokenItem: simpleItem(Stack{}),
AttackDurability: 2,
BreakDurability: 1,
}
}
// AttackDamage ...
func (a Axe) AttackDamage() float64 {
return a.Tier.BaseAttackDamage + 2
}
// ToolType ...
func (a Axe) ToolType() tool.Type {
return tool.TypeAxe
}
// HarvestLevel ...
func (a Axe) HarvestLevel() int {
return a.Tier.HarvestLevel
}
// BaseMiningEfficiency ...
func (a Axe) BaseMiningEfficiency(world.Block) float64 {
return a.Tier.BaseMiningEfficiency
}
// EncodeItem ...
func (a Axe) EncodeItem() (id int32, meta int16) {
switch a.Tier {
case tool.TierWood:
return 271, 0
case tool.TierGold:
return 286, 0
case tool.TierStone:
return 275, 0
case tool.TierIron:
return 258, 0
case tool.TierDiamond:
return 279, 0
case tool.TierNetherite:
return 746, 0
}
panic("invalid axe tier")
}
<file_sep>package mcdb
import (
"bytes"
"encoding/binary"
"fmt"
"github.com/df-mc/dragonfly/dragonfly/world"
"github.com/df-mc/dragonfly/dragonfly/world/chunk"
"github.com/df-mc/dragonfly/dragonfly/world/difficulty"
"github.com/df-mc/dragonfly/dragonfly/world/gamemode"
"github.com/df-mc/goleveldb/leveldb"
"github.com/df-mc/goleveldb/leveldb/opt"
"github.com/sandertv/gophertunnel/minecraft/nbt"
"github.com/sandertv/gophertunnel/minecraft/protocol"
"io/ioutil"
"os"
"path/filepath"
"time"
)
// Provider implements a world provider for the Minecraft world format, which is based on a leveldb database.
type Provider struct {
db *leveldb.DB
dir string
d data
}
// chunkVersion is the current version of chunks.
const chunkVersion = 19
// New creates a new provider reading and writing files to files under the path passed. If a world is present
// at the path, New will parse its data and initialise the world with it. If the data cannot be parsed, an
// error is returned.
func New(dir string) (*Provider, error) {
_ = os.MkdirAll(filepath.Join(dir, "db"), 0777)
p := &Provider{dir: dir}
if _, err := os.Stat(filepath.Join(dir, "level.dat")); os.IsNotExist(err) {
// A level.dat was not currently present for the world.
p.initDefaultLevelDat()
} else {
f, err := ioutil.ReadFile(filepath.Join(dir, "level.dat"))
if err != nil {
return nil, fmt.Errorf("error opening level.dat file: %w", err)
}
// The first 8 bytes are a useless header (version and length): We don't need it.
if len(f) < 8 {
// The file did not have enough content, meaning it is corrupted. We return an error.
return nil, fmt.Errorf("level.dat exists but has no data")
}
if err := nbt.UnmarshalEncoding(f[8:], &p.d, nbt.LittleEndian); err != nil {
return nil, fmt.Errorf("error decoding level.dat NBT: %w", err)
}
p.d.WorldStartCount++
}
db, err := leveldb.OpenFile(filepath.Join(dir, "db"), &opt.Options{
Compression: opt.FlateCompression,
BlockSize: 16 * opt.KiB,
})
if err != nil {
return nil, fmt.Errorf("error opening leveldb database: %w", err)
}
p.db = db
return p, nil
}
// initDefaultLevelDat initialises a default level.dat file.
func (p *Provider) initDefaultLevelDat() {
p.d.DoDayLightCycle = true
p.d.BaseGameVersion = protocol.CurrentVersion
p.d.LevelName = "World"
p.d.SpawnY = 128
p.d.GameType = 2
p.d.StorageVersion = 8
p.d.Generator = 1
p.d.NetworkVersion = protocol.CurrentProtocol
p.d.Abilities.WalkSpeed = 0.1
p.d.PVP = true
p.d.WorldStartCount = 1
p.d.RandomTickSpeed = 1
p.d.FallDamage = true
p.d.FireDamage = true
p.d.DrowningDamage = true
p.d.CommandsEnabled = true
p.d.MultiPlayerGame = true
}
// LoadTime returns the time as it was stored in the level.dat of the world loaded.
func (p *Provider) LoadTime() int64 {
return p.d.Time
}
// SaveTime saves the time to the level.dat of the world.
func (p *Provider) SaveTime(time int64) {
p.d.Time = time
}
// LoadTimeCycle returns whether the time is cycling or not.
func (p *Provider) LoadTimeCycle() bool {
return p.d.DoDayLightCycle
}
// SaveTimeCycle saves the state of the time cycle, either running or stopped, to the level.dat.
func (p *Provider) SaveTimeCycle(running bool) {
p.d.DoDayLightCycle = running
}
// WorldName returns the name of the world that the provider provides data for.
func (p *Provider) WorldName() string {
return p.d.LevelName
}
// SetWorldName sets the name of the world to the string passed.
func (p *Provider) SetWorldName(name string) {
p.d.LevelName = name
}
// WorldSpawn returns the spawn of the world as present in the level.dat.
func (p *Provider) WorldSpawn() world.BlockPos {
y := p.d.SpawnY
if p.d.SpawnY > 256 {
// TODO: Spawn at the highest block of the world. We're currently doing a guess.
y = 90
}
return world.BlockPos{int(p.d.SpawnX), int(y), int(p.d.SpawnZ)}
}
// SetWorldSpawn sets the spawn of the world to a new one.
func (p *Provider) SetWorldSpawn(pos world.BlockPos) {
p.d.SpawnX, p.d.SpawnY, p.d.SpawnZ = int32(pos.X()), int32(pos.Y()), int32(pos.Z())
}
// LoadChunk loads a chunk at the position passed from the leveldb database. If it doesn't exist, exists is
// false. If an error is returned, exists is always assumed to be true.
func (p *Provider) LoadChunk(position world.ChunkPos) (c *chunk.Chunk, exists bool, err error) {
data := chunk.SerialisedData{}
key := index(position)
// This key is where the version of a chunk resides. The chunk version has changed many times, without any
// actual substantial changes, so we don't check this.
_, err = p.db.Get(append(key, keyVersion), nil)
if err == leveldb.ErrNotFound {
return nil, false, nil
} else if err != nil {
return nil, true, fmt.Errorf("error reading version: %w", err)
}
data.Data2D, err = p.db.Get(append(key, key2DData), nil)
if err == leveldb.ErrNotFound {
return nil, false, nil
} else if err != nil {
return nil, true, fmt.Errorf("error reading 2D data: %w", err)
}
data.BlockNBT, err = p.db.Get(append(key, keyBlockEntities), nil)
// Block entities aren't present when there aren't any, so it's okay if we can't find the key.
if err != nil && err != leveldb.ErrNotFound {
return nil, true, fmt.Errorf("error reading block entities: %w", err)
}
for y := byte(0); y < 16; y++ {
data.SubChunks[y], err = p.db.Get(append(key, keySubChunkData, y), nil)
if err == leveldb.ErrNotFound {
// No sub chunk present at this Y level. We skip this one and move to the next, which might still
// be present.
continue
} else if err != nil {
return nil, true, fmt.Errorf("error reading 2D sub chunk %v: %w", y, err)
}
}
c, err = chunk.DiskDecode(data)
return c, true, err
}
// SaveChunk saves a chunk at the position passed to the leveldb database. Its version is written as the
// version in the chunkVersion constant.
func (p *Provider) SaveChunk(position world.ChunkPos, c *chunk.Chunk) error {
data := chunk.DiskEncode(c, false)
key := index(position)
_ = p.db.Put(append(key, keyVersion), []byte{chunkVersion}, nil)
_ = p.db.Put(append(key, key2DData), data.Data2D, nil)
finalisation := make([]byte, 4)
binary.LittleEndian.PutUint32(finalisation, 2)
_ = p.db.Put(append(key, keyFinalisation), finalisation, nil)
if len(data.BlockNBT) != 0 {
// We only write block NBT if there actually is any.
_ = p.db.Put(append(key, keyBlockEntities), data.BlockNBT, nil)
}
for y, sub := range data.SubChunks {
if len(sub) == 0 {
// No sub chunk here: Delete it from the database and continue.
_ = p.db.Delete(append(key, keySubChunkData, byte(y)), nil)
continue
}
_ = p.db.Put(append(key, keySubChunkData, byte(y)), sub, nil)
}
return nil
}
// LoadDefaultGameMode returns the default game mode stored in the level.dat.
func (p *Provider) LoadDefaultGameMode() gamemode.GameMode {
switch p.d.GameType {
default:
return gamemode.Adventure{}
case 0:
return gamemode.Survival{}
case 1:
return gamemode.Creative{}
case 2:
return gamemode.Adventure{}
case 3:
return gamemode.Spectator{}
}
}
// SaveDefaultGameMode changes the default game mode in the level.dat.
func (p *Provider) SaveDefaultGameMode(mode gamemode.GameMode) {
switch mode.(type) {
case gamemode.Survival:
p.d.GameType = 0
case gamemode.Creative:
p.d.GameType = 1
case gamemode.Adventure:
p.d.GameType = 2
case gamemode.Spectator:
p.d.GameType = 3
}
}
// LoadDifficulty loads the difficulty stored in the level.dat.
func (p *Provider) LoadDifficulty() difficulty.Difficulty {
switch p.d.Difficulty {
default:
return difficulty.Normal{}
case 0:
return difficulty.Peaceful{}
case 1:
return difficulty.Easy{}
case 3:
return difficulty.Hard{}
}
}
// SaveDifficulty saves the difficulty passed to the level.dat.
func (p *Provider) SaveDifficulty(d difficulty.Difficulty) {
switch d.(type) {
case difficulty.Peaceful:
p.d.Difficulty = 0
case difficulty.Easy:
p.d.Difficulty = 1
case difficulty.Normal:
p.d.Difficulty = 2
case difficulty.Hard:
p.d.Difficulty = 3
}
}
// LoadEntities loads all entities from the chunk position passed.
func (p *Provider) LoadEntities(world.ChunkPos) ([]world.Entity, error) {
// TODO: Implement entities.
return nil, nil
}
// SaveEntities saves all entities to the chunk position passed.
func (p *Provider) SaveEntities(world.ChunkPos, []world.Entity) error {
// TODO: Implement entities.
return nil
}
// LoadBlockNBT loads all block entities from the chunk position passed.
func (p *Provider) LoadBlockNBT(position world.ChunkPos) ([]map[string]interface{}, error) {
data, err := p.db.Get(append(index(position), keyBlockEntities), nil)
if err != leveldb.ErrNotFound && err != nil {
return nil, err
}
var a []map[string]interface{}
buf := bytes.NewBuffer(data)
dec := nbt.NewDecoderWithEncoding(buf, nbt.LittleEndian)
for buf.Len() != 0 {
var m map[string]interface{}
if err := dec.Decode(&m); err != nil {
return nil, fmt.Errorf("error decoding block NBT: %w", err)
}
a = append(a, m)
}
return a, nil
}
// SaveBlockNBT saves all block NBT data to the chunk position passed.
func (p *Provider) SaveBlockNBT(position world.ChunkPos, data []map[string]interface{}) error {
if len(data) == 0 {
return p.db.Delete(append(index(position), keyBlockEntities), nil)
}
buf := bytes.NewBuffer(nil)
enc := nbt.NewEncoderWithEncoding(buf, nbt.LittleEndian)
for _, d := range data {
if err := enc.Encode(d); err != nil {
return fmt.Errorf("error encoding block NBT: %w", err)
}
}
return p.db.Put(append(index(position), keyBlockEntities), buf.Bytes(), nil)
}
// Close closes the provider, saving any file that might need to be saved, such as the level.dat.
func (p *Provider) Close() error {
p.d.LastPlayed = time.Now().Unix()
f, err := os.OpenFile(filepath.Join(p.dir, "level.dat"), os.O_TRUNC|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
return fmt.Errorf("error opening level.dat file: %w", err)
}
buf := bytes.NewBuffer(nil)
_ = binary.Write(buf, binary.LittleEndian, int32(3))
nbtData, err := nbt.MarshalEncoding(p.d, nbt.LittleEndian)
if err != nil {
return fmt.Errorf("error encoding level.dat to NBT: %w", err)
}
_ = binary.Write(buf, binary.LittleEndian, int32(len(nbtData)))
_, _ = buf.Write(nbtData)
_, _ = f.Write(buf.Bytes())
if err := f.Close(); err != nil {
return fmt.Errorf("error closing level.dat: %w", err)
}
//noinspection SpellCheckingInspection
if err := ioutil.WriteFile(filepath.Join(p.dir, "levelname.txt"), []byte(p.d.LevelName), 0644); err != nil {
return fmt.Errorf("error writing levelname.txt: %w", err)
}
return p.db.Close()
}
// index returns a byte buffer holding the written index of the chunk position passed.
func index(position world.ChunkPos) []byte {
x, z := uint32(position[0]), uint32(position[1])
return []byte{
byte(x), byte(x >> 8), byte(x >> 16), byte(x >> 24),
byte(z), byte(z >> 8), byte(z >> 16), byte(z >> 24),
}
}
<file_sep>package block
import (
"github.com/df-mc/dragonfly/dragonfly/entity/physics"
"github.com/df-mc/dragonfly/dragonfly/item"
"github.com/df-mc/dragonfly/dragonfly/world"
"github.com/df-mc/dragonfly/dragonfly/world/sound"
)
// Activatable represents a block that may be activated by a viewer of the world. When activated, the block
// will execute some specific logic.
type Activatable interface {
// Activate activates the block at a specific block position. The face clicked is passed, as well as the
// world in which the block was activated and the viewer that activated it.
Activate(pos world.BlockPos, clickedFace world.Face, w *world.World, u item.User)
}
// LightEmitter represents a block that emits light when placed. Blocks such as torches or lanterns implement
// this interface.
type LightEmitter interface {
// LightEmissionLevel returns the light emission level of the block, a number from 0-15 where 15 is the
// brightest and 0 means it doesn't emit light at all.
LightEmissionLevel() uint8
}
// LightDiffuser represents a block that diffuses light. This means that a specific amount of light levels
// will be subtracted when light passes through the block.
// Blocks that do not implement LightDiffuser will be assumed to be solid: Light will not be able to pass
// through these blocks.
type LightDiffuser interface {
// LightDiffusionLevel returns the amount of light levels that is subtracted when light passes through
// this block. Some locks, such as leaves, have this behaviour. A diffusion level of 15 means that all
// light will be completely blocked when light passes through the block.
LightDiffusionLevel() uint8
}
// Replaceable represents a block that may be replaced by another block automatically. An example is grass,
// which may be replaced by clicking it with another block.
type Replaceable interface {
// ReplaceableBy returns a bool which indicates if the block is replaceable by another block.
ReplaceableBy(b world.Block) bool
}
// replaceable checks if the block at the position passed is replaceable with the block passed.
func replaceable(w *world.World, pos world.BlockPos, with world.Block) bool {
if pos.OutOfBounds() {
return false
}
b := w.Block(pos)
if replaceable, ok := b.(Replaceable); ok {
return replaceable.ReplaceableBy(with)
}
return false
}
// firstReplaceable finds the first replaceable block position eligible to have a block placed on it after
// clicking on the position and face passed.
// If none can be found, the bool returned is false.
func firstReplaceable(w *world.World, pos world.BlockPos, face world.Face, with world.Block) (world.BlockPos, world.Face, bool) {
if replaceable(w, pos, with) {
// A replaceable block was clicked, so we can replace it. This will then be assumed to be placed on
// the top face. (Torches, for example, will get attached to the floor when clicking tall grass.)
return pos, world.FaceUp, true
}
side := pos.Side(face)
if replaceable(w, side, with) {
return side, face, true
}
return pos, face, false
}
// place places the block passed at the position passed. If the user implements the block.Placer interface, it
// will use its PlaceBlock method. If not, the block is placed without interaction from the user.
func place(w *world.World, pos world.BlockPos, b world.Block, user item.User, ctx *item.UseContext) {
if placer, ok := user.(Placer); ok {
placer.PlaceBlock(pos, b, ctx)
return
}
w.PlaceBlock(pos, b)
w.PlaySound(pos.Vec3(), sound.BlockPlace{Block: b})
}
// placed checks if an item was placed with the use context passed.
func placed(ctx *item.UseContext) bool {
return ctx.CountSub > 0
}
// AABBer represents a block that has one or multiple specific Axis Aligned Bounding Boxes. These boxes are
// used to calculate collision.
type AABBer interface {
// AABB returns all the axis aligned bounding boxes of the block.
AABB(pos world.BlockPos, w *world.World) []physics.AABB
}
// boolByte returns 1 if the bool passed is true, or 0 if it is false.
func boolByte(b bool) uint8 {
if b {
return 1
}
return 0
}
// noNBT may be embedded by blocks that have no NBT.
type noNBT struct{}
// HasNBT ...
func (noNBT) HasNBT() bool {
return false
}
// nbt may be embedded by blocks that do have NBT.
type nbt struct{}
// HasNBT ...
func (nbt) HasNBT() bool {
return true
}
<file_sep>package item
import (
"github.com/df-mc/dragonfly/dragonfly/world"
"github.com/go-gl/mathgl/mgl64"
)
// MaxCounter represents an item that has a specific max count. By default, each item will be expected to have
// a maximum count of 64. MaxCounter may be implemented to change this behaviour.
type MaxCounter interface {
// MaxCount returns the maximum number of items that a stack may be composed of. The number returned must
// be positive.
MaxCount() int
}
// UsableOnBlock represents an item that may be used on a block. If an item implements this interface, the
// UseOnBlock method is called whenever the item is used on a block.
type UsableOnBlock interface {
// UseOnBlock is called when an item is used on a block. The world passed is the world that the item was
// used in. The user passed is the entity that used the item. Usually this entity is a player.
// The position of the block that was clicked, along with the clicked face and the position clicked
// relative to the corner of the block are passed.
// UseOnBlock returns a bool indicating if the item was used successfully.
UseOnBlock(pos world.BlockPos, face world.Face, clickPos mgl64.Vec3, w *world.World, user User, ctx *UseContext) bool
}
// UsableOnEntity represents an item that may be used on an entity. If an item implements this interface, the
// UseOnEntity method is called whenever the item is used on an entity.
type UsableOnEntity interface {
// UseOnEntity is called when an item is used on an entity. The world passed is the world that the item is
// used in, and the entity clicked and the user of the item are also passed.
// UseOnEntity returns a bool indicating if the item was used successfully.
UseOnEntity(e world.Entity, w *world.World, user User, ctx *UseContext) bool
}
// Usable represents an item that may be used 'in the air'. If an item implements this interface, the Use
// method is called whenever the item is used while pointing at the air. (For example, when throwing an egg.)
type Usable interface {
// Use is called when the item is used in the air. The user that used the item and the world that the item
// was used in are passed to the method.
// Use returns a bool indicating if the item was used successfully.
Use(w *world.World, user User, ctx *UseContext) bool
}
// UseContext is passed to every item Use methods. It may be used to subtract items or to deal damage to them
// after the action is complete.
type UseContext struct {
Damage int
CountSub int
// NewItem is the item that is added after the item is used. If the player no longer has an item in the
// hand, it'll be added there.
NewItem Stack
}
// DamageItem damages the item used by d points.
func (ctx *UseContext) DamageItem(d int) { ctx.Damage += d }
// SubtractFromCount subtracts d from the count of the item stack used.
func (ctx *UseContext) SubtractFromCount(d int) { ctx.CountSub += d }
// Weapon is an item that may be used as a weapon. It has an attack damage which may be different to the 2
// damage that attacking with an empty hand deals.
type Weapon interface {
// AttackDamage returns the custom attack damage of the weapon. The damage returned must not be negative.
AttackDamage() float64
}
// nameable represents a block that may be named. These are often containers such as chests, which have a
// name displayed in their interface.
type nameable interface {
// WithName returns the block itself, except with a custom name applied to it.
WithName(a ...interface{}) world.Item
}
// User represents an entity that is able to use an item in the world, typically entities such as players,
// which interact with the world using an item.
type User interface {
// Facing returns the direction that the user is facing.
Facing() world.Direction
// Position returns the current position of the user in the world.
Position() mgl64.Vec3
// Yaw returns the yaw of the entity. This is horizontal rotation (rotation around the vertical axis), and
// is 0 when the entity faces forward.
Yaw() float64
// Pitch returns the pitch of the entity. This is vertical rotation (rotation around the horizontal axis),
// and is 0 when the entity faces forward.
Pitch() float64
HeldItems() (right, left Stack)
SetHeldItems(right, left Stack)
}
// Collector represents an entity in the world that is able to collect an item, typically an entity such as
// a player or a zombie.
type Collector interface {
world.Entity
// Collect collects the stack passed. It is called if the Collector is standing near an item entity that
// may be picked up.
// The count of items collected from the stack n is returned.
Collect(stack Stack) (n int)
}
// Carrier represents an entity that is able to carry an item.
type Carrier interface {
// HeldItems returns the items currently held by the entity. Viewers of the entity will be able to see
// these items.
HeldItems() (mainHand, offHand Stack)
}
<file_sep>package item_internal
import (
"github.com/df-mc/dragonfly/dragonfly/world"
)
// Air holds an air block.
var Air world.Block
// GrassPath holds a grass path block.
var GrassPath world.Block
// Grass holds a grass block.
var Grass world.Block
// Water and Lava hold blocks for their respective liquids.
var Water, Lava world.Liquid
// IsUnstrippedLog is a function set to check if a block is a log.
var IsUnstrippedLog func(b world.Block) bool
// StripLog is a function used to convert a log block to a stripped log block.
var StripLog func(b world.Block) world.Block
// IsWater is a function used to check if a liquid is water.
var IsWater func(b world.Liquid) bool
// Replaceable is a function used to check if a block is replaceable.
var Replaceable func(w *world.World, pos world.BlockPos, with world.Block) bool
<file_sep>package effect
import (
"github.com/df-mc/dragonfly/dragonfly/entity"
"github.com/df-mc/dragonfly/dragonfly/entity/healing"
"image/color"
"time"
)
// Regeneration is an effect that causes the entity that it is added to to slowly regenerate health. The level
// of the effect influences the speed with which the entity regenerates.
type Regeneration struct {
lastingEffect
}
// Apply applies health to the entity.Living passed if the duration of the effect is at the right tick.
func (r Regeneration) Apply(e entity.Living) {
interval := 50 >> r.Lvl
if tickDuration(r.Dur)%interval == 0 {
e.Heal(1, healing.SourceRegenerationEffect{})
}
}
// WithDuration ...
func (r Regeneration) WithDuration(d time.Duration) entity.Effect {
return Regeneration{r.withDuration(d)}
}
// RGBA ...
func (Regeneration) RGBA() color.RGBA {
return color.RGBA{R: 0xcd, G: 0x5c, B: 0xab, A: 0xff}
}
<file_sep>package block
import (
"github.com/df-mc/dragonfly/dragonfly/block/colour"
"github.com/df-mc/dragonfly/dragonfly/item"
"github.com/df-mc/dragonfly/dragonfly/world"
)
// StainedTerracotta is a block formed from clay, with a hardness and blast resistance comparable to stone. In contrast
// to Terracotta, t can be coloured in the same 16 colours that wool can be dyed, but more dulled and earthen.
type StainedTerracotta struct {
noNBT
// Colour specifies the colour of the block.
Colour colour.Colour
}
// BreakInfo ...
func (t StainedTerracotta) BreakInfo() BreakInfo {
return BreakInfo{
Hardness: 1.25,
Harvestable: pickaxeHarvestable,
Effective: pickaxeEffective,
Drops: simpleDrops(item.NewStack(t, 1)),
}
}
// EncodeItem ...
func (t StainedTerracotta) EncodeItem() (id int32, meta int16) {
return 159, int16(t.Colour.Uint8())
}
// EncodeBlock ...
func (t StainedTerracotta) EncodeBlock() (name string, properties map[string]interface{}) {
colourName := t.Colour.String()
if t.Colour == colour.LightGrey() {
// Light grey is actually called "silver" in the block state. Mojang pls.
colourName = "silver"
}
return "minecraft:stained_hardened_clay", map[string]interface{}{"color": colourName}
}
// Hash ...
func (t StainedTerracotta) Hash() uint64 {
return hashStainedTerracotta | (uint64(t.Colour.Uint8()) << 32)
}
// allStainedTerracotta returns stained terracotta blocks with all possible colours.
func allStainedTerracotta() []world.Block {
b := make([]world.Block, 0, 16)
for _, c := range colour.All() {
b = append(b, StainedTerracotta{Colour: c})
}
return b
}
<file_sep>
[Network]
# The address of the server, including the port. The server will be listening on this address. If another
# server is already running on this port, please select a different port.
Address = ":19132"
[Server]
# The name as it shows up in the server list. Minecraft colour codes may be used in this name to format the
# name of the server.
Name = "Dragonfly Server"
# The maximum amount of players accepted into the server. If set to 0, there is no player limit. The max
# player count will increase as more players join.
MaximumPlayers = 0
# The message shown to players when the server is shutting down. The message may be left empty to direct
# players to the server list directly.
ShutdownMessage = "Server closed."
[World]
# The name of the world of the server. The name will show up at the top of the player list in the in-game
# pause menu. It has no functionality beyond that.
Name = "World"
# The folder that the world files (will) reside in, relative to the working directory. If not currently
# present, the folder will be made.
Folder = "world"
# The maximum chunk radius that players may set in their settings. If they try to set it above this number,
# it will be capped and set to the max.
MaximumChunkRadius = 32
# SimulationDistance is the maximum distance in chunks that a chunk must be to a player in order for
# it to receive random ticks. This field may be set to 0 to disable random block updates altogether.
SimulationDistance = 8
<file_sep>package session
import (
"fmt"
"github.com/sandertv/gophertunnel/minecraft/protocol"
"github.com/sandertv/gophertunnel/minecraft/protocol/packet"
)
// MobEquipmentHandler handles the MobEquipment packet.
type MobEquipmentHandler struct{}
// Handle ...
func (*MobEquipmentHandler) Handle(p packet.Packet, s *Session) error {
pk := p.(*packet.MobEquipment)
if pk.EntityRuntimeID != selfEntityRuntimeID {
return ErrSelfRuntimeID
}
if pk.WindowID == protocol.WindowIDOffHand {
// This window ID is expected, but we don't handle it.
return nil
}
if pk.WindowID != protocol.WindowIDInventory {
return fmt.Errorf("only main inventory should be involved, got window ID %v", pk.WindowID)
}
// The slot that the player might have selected must be within the hotbar: The held item cannot be in a
// different place in the inventory.
if pk.InventorySlot > 8 {
return fmt.Errorf("slot exceeds hotbar range 0-8: slot is %v", pk.InventorySlot)
}
if s.heldSlot.Swap(uint32(pk.InventorySlot)) == uint32(pk.InventorySlot) {
// Old slot was the same as new slot, so don't do anything.
return nil
}
clientSideItem := stackToItem(pk.NewItem)
actual, _ := s.inv.Item(int(pk.InventorySlot))
// The item the client claims to have must be identical to the one we have registered server-side.
if !clientSideItem.Comparable(actual) {
// Only ever debug these as they are frequent and expected to happen whenever client and server get
// out of sync.
s.log.Debugf("failed processing packet from %v (%v): *packet.MobEquipment: client-side item must be identical to server-side item, but got different types: client: %v vs server: %v", s.conn.RemoteAddr(), s.c.Name(), clientSideItem, actual)
}
if clientSideItem.Count() != actual.Count() {
// Only ever debug these as they are frequent and expected to happen whenever client and server get
// out of sync.
s.log.Debugf("failed processing packet from %v (%v): *packet.MobEquipment: client-side item must be identical to server-side item, but got different counts: client: %v vs server: %v", s.conn.RemoteAddr(), s.c.Name(), clientSideItem.Count(), actual.Count())
}
for _, viewer := range s.c.World().Viewers(s.c.Position()) {
viewer.ViewEntityItems(s.c)
}
return nil
}
<file_sep>package session
import (
"github.com/df-mc/dragonfly/dragonfly/world"
)
// entityMetadata represents a map that holds metadata associated with an entity. The data held in the map
// depends on the entity and varies on a per-entity basis.
type entityMetadata map[uint32]interface{}
// defaultEntityMetadata returns an entity metadata object with default values. It is equivalent to setting
// all properties to their default values and disabling all flags.
func defaultEntityMetadata(e world.Entity) entityMetadata {
m := entityMetadata{}
m.setFlag(dataKeyFlags, dataFlagAffectedByGravity)
bb := e.AABB()
m[dataKeyBoundingBoxWidth] = float32(bb.Width())
m[dataKeyBoundingBoxHeight] = float32(bb.Height())
m[dataKeyPotionColour] = int32(0)
m[dataKeyPotionAmbient] = byte(0)
return m
}
// setFlag sets a flag with a specific index in the int64 stored in the entity metadata map to the value
// passed. It is typically used for entity metadata flags.
func (m entityMetadata) setFlag(key uint32, index uint8) {
if v, ok := m[key]; !ok {
m[key] = int64(0) ^ (1 << uint64(index))
} else {
m[key] = v.(int64) ^ (1 << uint64(index))
}
}
//noinspection GoUnusedConst
const (
dataKeyFlags = iota
dataKeyHealth
dataKeyVariant
dataKeyColour
dataKeyNameTag
dataKeyOwnerRuntimeID
dataKeyTargetRuntimeID
dataKeyAir
dataKeyPotionColour
dataKeyPotionAmbient
dataKeyBoundingBoxWidth = 53
dataKeyBoundingBoxHeight = 54
)
//noinspection GoUnusedConst
const (
dataFlagOnFire = iota
dataFlagSneaking
dataFlagRiding
dataFlagSprinting
dataFlagAction
dataFlagInvisible
dataFlagNoAI = 16
dataFlagBreathing = 35
dataFlagAffectedByGravity = 48
dataFlagSwimming = 56
)
<file_sep>package block
import (
"github.com/df-mc/dragonfly/dragonfly/block/wood"
"github.com/df-mc/dragonfly/dragonfly/entity/physics"
"github.com/df-mc/dragonfly/dragonfly/item"
"github.com/df-mc/dragonfly/dragonfly/item/tool"
"github.com/df-mc/dragonfly/dragonfly/world"
"github.com/go-gl/mathgl/mgl64"
)
// WoodSlab is a half block that allows entities to walk up blocks without jumping.
type WoodSlab struct {
noNBT
// Wood is the type of wood of the slabs. This field must have one of the values found in the material
// package.
Wood wood.Wood
// UpsideDown specifies if the slabs are upside down.
UpsideDown bool
// Double specifies if the slab is a double slab. These double slabs can be made by placing another slab
// on an existing slab.
Double bool
}
// UseOnBlock handles the placement of slabs with relation to them being upside down or not and handles slabs
// being turned into double slabs.
func (s WoodSlab) UseOnBlock(pos world.BlockPos, face world.Face, clickPos mgl64.Vec3, w *world.World, user item.User, ctx *item.UseContext) (used bool) {
clickedBlock := w.Block(pos)
if clickedSlab, ok := clickedBlock.(WoodSlab); ok && !s.Double {
if (face == world.FaceUp && !clickedSlab.Double && clickedSlab.Wood == s.Wood && !clickedSlab.UpsideDown) ||
(face == world.FaceDown && !clickedSlab.Double && clickedSlab.Wood == s.Wood && clickedSlab.UpsideDown) {
// A half slab of the same type was clicked at the top, so we can make it full.
clickedSlab.Double = true
place(w, pos, clickedSlab, user, ctx)
return placed(ctx)
}
}
if sideSlab, ok := w.Block(pos.Side(face)).(WoodSlab); ok && !replaceable(w, pos, s) && !s.Double {
// The block on the side of the one clicked was a slab and the block clicked was not replaceable, so
// the slab on the side must've been half and may now be filled if the wood types are the same.
if !sideSlab.Double && sideSlab.Wood == s.Wood {
sideSlab.Double = true
place(w, pos.Side(face), sideSlab, user, ctx)
return placed(ctx)
}
}
pos, face, used = firstReplaceable(w, pos, face, s)
if !used {
return
}
if face == world.FaceDown || (clickPos[1] > 0.5 && face != world.FaceUp) {
s.UpsideDown = true
}
place(w, pos, s, user, ctx)
return placed(ctx)
}
// BreakInfo ...
func (s WoodSlab) BreakInfo() BreakInfo {
return BreakInfo{
Hardness: 2,
Harvestable: alwaysHarvestable,
Effective: axeEffective,
Drops: func(t tool.Tool) []item.Stack {
if s.Double {
s.Double = false
// If the slab is double, it should drop two single slabs.
return []item.Stack{item.NewStack(s, 2)}
}
return []item.Stack{item.NewStack(s, 1)}
},
}
}
// LightDiffusionLevel returns 0 if the slab is a half slab, or 15 if it is double.
func (s WoodSlab) LightDiffusionLevel() uint8 {
if s.Double {
return 15
}
return 0
}
// AABB ...
func (s WoodSlab) AABB(world.BlockPos, *world.World) []physics.AABB {
if s.Double {
return []physics.AABB{physics.NewAABB(mgl64.Vec3{}, mgl64.Vec3{1, 1, 1})}
}
if s.UpsideDown {
return []physics.AABB{physics.NewAABB(mgl64.Vec3{0, 0.5, 0}, mgl64.Vec3{1, 1, 1})}
}
return []physics.AABB{physics.NewAABB(mgl64.Vec3{}, mgl64.Vec3{1, 0.5, 1})}
}
// EncodeItem ...
func (s WoodSlab) EncodeItem() (id int32, meta int16) {
switch s.Wood {
case wood.Oak():
if s.Double {
return 157, 0
}
return 158, 0
case wood.Spruce():
if s.Double {
return 157, 1
}
return 158, 1
case wood.Birch():
if s.Double {
return 157, 2
}
return 158, 2
case wood.Jungle():
if s.Double {
return 157, 3
}
return 158, 3
case wood.Acacia():
if s.Double {
return 157, 4
}
return 158, 4
case wood.DarkOak():
if s.Double {
return 157, 5
}
return 158, 5
}
panic("invalid wood type")
}
// EncodeBlock ...
func (s WoodSlab) EncodeBlock() (name string, properties map[string]interface{}) {
if s.Double {
return "minecraft:double_wooden_slab", map[string]interface{}{"top_slot_bit": s.UpsideDown, "wood_type": s.Wood.String()}
}
return "minecraft:wooden_slab", map[string]interface{}{"top_slot_bit": s.UpsideDown, "wood_type": s.Wood.String()}
}
// Hash ...
func (s WoodSlab) Hash() uint64 {
return hashWoodSlab | (uint64(boolByte(s.UpsideDown)) << 32) | (uint64(boolByte(s.Double)) << 33) | (uint64(s.Wood.Uint8()) << 34)
}
// CanDisplace ...
func (s WoodSlab) CanDisplace(b world.Liquid) bool {
_, ok := b.(Water)
return !s.Double && ok
}
// SideClosed ...
func (s WoodSlab) SideClosed(pos, side world.BlockPos, w *world.World) bool {
// Only returns true if the side is below the slab and if the slab is not upside down.
return !s.UpsideDown && side[1] == pos[1]-1
}
// allWoodSlabs returns all states of wood slabs.
func allWoodSlabs() (slabs []world.Block) {
f := func(double bool, upsideDown bool) {
slabs = append(slabs, WoodSlab{Double: double, UpsideDown: upsideDown, Wood: wood.Oak()})
slabs = append(slabs, WoodSlab{Double: double, UpsideDown: upsideDown, Wood: wood.Spruce()})
slabs = append(slabs, WoodSlab{Double: double, UpsideDown: upsideDown, Wood: wood.Birch()})
slabs = append(slabs, WoodSlab{Double: double, UpsideDown: upsideDown, Wood: wood.Jungle()})
slabs = append(slabs, WoodSlab{Double: double, UpsideDown: upsideDown, Wood: wood.Acacia()})
slabs = append(slabs, WoodSlab{Double: double, UpsideDown: upsideDown, Wood: wood.DarkOak()})
}
f(false, false)
f(false, true)
f(true, false)
f(true, true)
return
}
<file_sep>package sound
// Attack is a sound played when an entity, most notably a player, attacks another entity.
type Attack struct {
// Damage specifies if the attack actually dealt damage to the other entity. If set to false, the sound
// will be different than when set to true.
Damage bool
sound
}
<file_sep>package effect
import (
"github.com/df-mc/dragonfly/dragonfly/entity"
"github.com/df-mc/dragonfly/dragonfly/entity/damage"
"image/color"
"time"
)
// Absorption is a lasting effect that increases the health of an entity over the maximum. Once this extra
// health is lost, it will not regenerate.
type Absorption struct {
lastingEffect
}
// Absorbs checks if Absorption absorbs the damage source passed.
func (a Absorption) Absorbs(src damage.Source) bool {
switch src.(type) {
case damage.SourceWitherEffect, damage.SourceInstantDamageEffect, damage.SourcePoisonEffect, damage.SourceStarvation:
return true
}
return false
}
// Start ...
func (a Absorption) Start(e entity.Living) {
if i, ok := e.(interface {
SetAbsorption(health float64)
}); ok {
i.SetAbsorption(4 * float64(a.Lvl))
}
}
// Stop ...
func (a Absorption) Stop(e entity.Living) {
if i, ok := e.(interface {
SetAbsorption(health float64)
}); ok {
i.SetAbsorption(0)
}
}
// WithDuration ...
func (a Absorption) WithDuration(d time.Duration) entity.Effect {
return Absorption{a.withDuration(d)}
}
// RGBA ...
func (a Absorption) RGBA() color.RGBA {
return color.RGBA{R: 0x25, G: 0x52, B: 0xa5, A: 0xff}
}
<file_sep>package state
import "image/color"
// State represents a part of the state of an entity. Entities may hold a combination of these to indicate
// things such as whether it is sprinting or on fire.
type State interface {
__()
}
// Sneaking makes the entity show up as if it is sneaking.
type Sneaking struct{}
// Sprinting makes an entity show up as if it is sprinting: Particles will show up when the entity moves
// around the world.
type Sprinting struct{}
// Swimming makes an entity show up as if it is swimming.
type Swimming struct{}
// Breathing makes an entity breath: This state will not show up for entities other than players.
type Breathing struct{}
// Invisible makes an entity invisible, so that other players won't be able to see it.
type Invisible struct{}
// EffectBearing makes an entity show up as if it is bearing effects. Coloured particles will be shown around
// the player.
type EffectBearing struct {
// ParticleColour holds the colour of the particles that are displayed around the entity.
ParticleColour color.RGBA
// Ambient specifies if the effects are ambient. If true, the particles will be shown less frequently
// around the entity.
Ambient bool
}
// Named makes an entity show a specific name tag above it.
type Named struct {
// NameTag is the name displayed. This name may have colour codes, newlines etc in it, much like a normal
// message.
NameTag string
}
func (Sneaking) __() {}
func (Swimming) __() {}
func (Breathing) __() {}
func (Sprinting) __() {}
func (Invisible) __() {}
func (Named) __() {}
func (EffectBearing) __() {}
<file_sep>package block
import (
"github.com/df-mc/dragonfly/dragonfly/entity/physics"
"github.com/df-mc/dragonfly/dragonfly/world"
)
// Air is the block present in otherwise empty space.
type Air struct{ noNBT }
// CanDisplace ...
func (Air) CanDisplace(world.Liquid) bool {
return true
}
// HasLiquidDrops ...
func (Air) HasLiquidDrops() bool {
return false
}
// LightDiffusionLevel ...
func (Air) LightDiffusionLevel() uint8 {
return 0
}
// EncodeItem ...
func (Air) EncodeItem() (id int32, meta int16) {
return 0, 0
}
// EncodeBlock ...
func (Air) EncodeBlock() (name string, properties map[string]interface{}) {
return "minecraft:air", nil
}
// Hash ...
func (Air) Hash() uint64 {
return hashAir
}
// AABB returns an empty Axis Aligned Bounding Box (as nothing can collide with air).
func (Air) AABB(world.BlockPos, *world.World) []physics.AABB {
return nil
}
// ReplaceableBy always returns true.
func (Air) ReplaceableBy(world.Block) bool {
return true
}
<file_sep>package block
import (
"github.com/df-mc/dragonfly/dragonfly/block/wood"
"github.com/df-mc/dragonfly/dragonfly/entity/physics"
"github.com/df-mc/dragonfly/dragonfly/item"
"github.com/df-mc/dragonfly/dragonfly/world"
"github.com/go-gl/mathgl/mgl64"
)
// WoodStairs are blocks that allow entities to walk up blocks without jumping. They are crafted using planks.
type WoodStairs struct {
noNBT
// Wood is the type of wood of the stairs. This field must have one of the values found in the material
// package.
Wood wood.Wood
// UpsideDown specifies if the stairs are upside down. If set to true, the full side is at the top part
// of the block.
UpsideDown bool
// Facing is the direction that the full side of the stairs is facing.
Facing world.Direction
}
// UseOnBlock handles the directional placing of stairs and makes sure they are properly placed upside down
// when needed.
func (s WoodStairs) UseOnBlock(pos world.BlockPos, face world.Face, clickPos mgl64.Vec3, w *world.World, user item.User, ctx *item.UseContext) (used bool) {
pos, face, used = firstReplaceable(w, pos, face, s)
if !used {
return
}
s.Facing = user.Facing()
if face == world.FaceDown || (clickPos[1] > 0.5 && face != world.FaceUp) {
s.UpsideDown = true
}
place(w, pos, s, user, ctx)
return placed(ctx)
}
// BreakInfo ...
func (s WoodStairs) BreakInfo() BreakInfo {
return BreakInfo{
Hardness: 2,
Harvestable: alwaysHarvestable,
Effective: axeEffective,
Drops: simpleDrops(item.NewStack(s, 1)),
}
}
// LightDiffusionLevel always returns 0.
func (WoodStairs) LightDiffusionLevel() uint8 {
return 0
}
// AABB ...
func (s WoodStairs) AABB(pos world.BlockPos, w *world.World) []physics.AABB {
b := []physics.AABB{physics.NewAABB(mgl64.Vec3{}, mgl64.Vec3{1, 0.5, 1})}
if s.UpsideDown {
b[0] = physics.NewAABB(mgl64.Vec3{0, 0.5, 0}, mgl64.Vec3{1, 1, 1})
}
t := s.cornerType(pos, w)
if t == noCorner || t == cornerRightInner || t == cornerRightOuter {
b = append(b, physics.NewAABB(mgl64.Vec3{0.5, 0.5, 0.5}, mgl64.Vec3{0.5, 1, 0.5}).
ExtendTowards(int(s.Facing), 0.5).
ExtendTowards(int(s.Facing.Rotate90()), 0.5).
ExtendTowards(int(s.Facing.Rotate90().Opposite()), 0.5))
}
if t == cornerRightOuter {
b = append(b, physics.NewAABB(mgl64.Vec3{0.5, 0.5, 0.5}, mgl64.Vec3{0.5, 1, 0.5}).
ExtendTowards(int(s.Facing), 0.5).
ExtendTowards(int(s.Facing.Rotate90().Opposite()), 0.5))
} else if t == cornerLeftOuter {
b = append(b, physics.NewAABB(mgl64.Vec3{0.5, 0.5, 0.5}, mgl64.Vec3{0.5, 1, 0.5}).
ExtendTowards(int(s.Facing), 0.5).
ExtendTowards(int(s.Facing.Rotate90()), 0.5))
} else if t == cornerRightInner {
b = append(b, physics.NewAABB(mgl64.Vec3{0.5, 0.5, 0.5}, mgl64.Vec3{0.5, 1, 0.5}).
ExtendTowards(int(s.Facing.Opposite()), 0.5).
ExtendTowards(int(s.Facing.Rotate90().Opposite()), 0.5))
} else if t == cornerLeftInner {
b = append(b, physics.NewAABB(mgl64.Vec3{0.5, 0.5, 0.5}, mgl64.Vec3{0.5, 1, 0.5}).
ExtendTowards(int(s.Facing.Opposite()), 0.5).
ExtendTowards(int(s.Facing.Rotate90()), 0.5))
}
if s.UpsideDown {
for i := range b[1:] {
b[i] = b[i].Translate(mgl64.Vec3{0, -0.5})
}
}
return b
}
// EncodeItem ...
func (s WoodStairs) EncodeItem() (id int32, meta int16) {
switch s.Wood {
case wood.Oak():
return 53, 0
case wood.Spruce():
return 134, 0
case wood.Birch():
return 135, 0
case wood.Jungle():
return 136, 0
case wood.Acacia():
return 163, 0
case wood.DarkOak():
return 164, 0
}
panic("invalid wood type")
}
// EncodeBlock ...
func (s WoodStairs) EncodeBlock() (name string, properties map[string]interface{}) {
switch s.Wood {
case wood.Oak():
return "minecraft:oak_stairs", map[string]interface{}{"upside_down_bit": s.UpsideDown, "weirdo_direction": toStairsDirection(s.Facing)}
case wood.Spruce():
return "minecraft:spruce_stairs", map[string]interface{}{"upside_down_bit": s.UpsideDown, "weirdo_direction": toStairsDirection(s.Facing)}
case wood.Birch():
return "minecraft:birch_stairs", map[string]interface{}{"upside_down_bit": s.UpsideDown, "weirdo_direction": toStairsDirection(s.Facing)}
case wood.Jungle():
return "minecraft:jungle_stairs", map[string]interface{}{"upside_down_bit": s.UpsideDown, "weirdo_direction": toStairsDirection(s.Facing)}
case wood.Acacia():
return "minecraft:acacia_stairs", map[string]interface{}{"upside_down_bit": s.UpsideDown, "weirdo_direction": toStairsDirection(s.Facing)}
case wood.DarkOak():
return "minecraft:dark_oak_stairs", map[string]interface{}{"upside_down_bit": s.UpsideDown, "weirdo_direction": toStairsDirection(s.Facing)}
}
panic("invalid wood type")
}
// Hash ...
func (s WoodStairs) Hash() uint64 {
return hashWoodStairs | (uint64(boolByte(s.UpsideDown)) << 32) | (uint64(s.Facing) << 33) | (uint64(s.Wood.Uint8()) << 35)
}
// toStairDirection converts a facing to a stairs direction for Minecraft.
func toStairsDirection(v world.Direction) int32 {
return int32(3 - v)
}
// CanDisplace ...
func (WoodStairs) CanDisplace(b world.Liquid) bool {
_, ok := b.(Water)
return ok
}
// SideClosed ...
func (s WoodStairs) SideClosed(pos, side world.BlockPos, w *world.World) bool {
if !s.UpsideDown && side[1] == pos[1]-1 {
// Non-upside down stairs have a closed side at the bottom.
return true
}
t := s.cornerType(pos, w)
if t == cornerRightOuter || t == cornerLeftOuter {
// Small corner blocks, they do not block water flowing out horizontally.
return false
} else if t == noCorner {
// Not a corner, so only block directly behind the stairs.
return pos.Side(s.Facing.Face()) == side
}
if t == cornerRightInner {
return side == pos.Side(s.Facing.Rotate90().Face()) || side == pos.Side(s.Facing.Face())
}
return side == pos.Side(s.Facing.Rotate90().Opposite().Face()) || side == pos.Side(s.Facing.Face())
}
const (
noCorner = iota
cornerRightInner
cornerLeftInner
cornerRightOuter
cornerLeftOuter
)
// cornerType returns the type of the corner that the stairs form, or 0 if it does not form a corner with any
// other stairs.
func (s WoodStairs) cornerType(pos world.BlockPos, w *world.World) uint8 {
// TODO: Make stairs of all types curve.
rotatedFacing := s.Facing.Rotate90()
if closedSide, ok := w.Block(pos.Side(s.Facing.Face())).(WoodStairs); ok && closedSide.UpsideDown == s.UpsideDown {
if closedSide.Facing == rotatedFacing {
return cornerLeftOuter
} else if closedSide.Facing == rotatedFacing.Opposite() {
// This will only form a corner if there is not a stair on the right of this one with the same
// direction.
if side, ok := w.Block(pos.Side(s.Facing.Rotate90().Face())).(WoodStairs); !ok || side.Facing != s.Facing || side.UpsideDown != s.UpsideDown {
return cornerRightOuter
}
return noCorner
}
}
if openSide, ok := w.Block(pos.Side(s.Facing.Opposite().Face())).(WoodStairs); ok && openSide.UpsideDown == s.UpsideDown {
if openSide.Facing == rotatedFacing {
// This will only form a corner if there is not a stair on the right of this one with the same
// direction.
if side, ok := w.Block(pos.Side(s.Facing.Rotate90().Face())).(WoodStairs); !ok || side.Facing != s.Facing || side.UpsideDown != s.UpsideDown {
return cornerRightInner
}
} else if openSide.Facing == rotatedFacing.Opposite() {
return cornerLeftInner
}
}
return noCorner
}
// allWoodStairs returns all states of wood stairs.
func allWoodStairs() (stairs []world.Block) {
f := func(facing world.Direction, upsideDown bool) {
stairs = append(stairs, WoodStairs{Facing: facing, UpsideDown: upsideDown, Wood: wood.Oak()})
stairs = append(stairs, WoodStairs{Facing: facing, UpsideDown: upsideDown, Wood: wood.Spruce()})
stairs = append(stairs, WoodStairs{Facing: facing, UpsideDown: upsideDown, Wood: wood.Birch()})
stairs = append(stairs, WoodStairs{Facing: facing, UpsideDown: upsideDown, Wood: wood.Jungle()})
stairs = append(stairs, WoodStairs{Facing: facing, UpsideDown: upsideDown, Wood: wood.Acacia()})
stairs = append(stairs, WoodStairs{Facing: facing, UpsideDown: upsideDown, Wood: wood.DarkOak()})
}
for i := world.Direction(0); i <= 3; i++ {
f(i, true)
f(i, false)
}
return
}
<file_sep>package block
import (
"github.com/df-mc/dragonfly/dragonfly/entity/physics"
"github.com/df-mc/dragonfly/dragonfly/event"
"github.com/df-mc/dragonfly/dragonfly/world"
"github.com/df-mc/dragonfly/dragonfly/world/sound"
"time"
)
// Water is a natural fluid that generates abundantly in the world.
type Water struct {
noNBT
// Still makes the water appear as if it is not flowing.
Still bool
// Depth is the depth of the water. This is a number from 1-8, where 8 is a source block and 1 is the
// smallest possible water block.
Depth int
// Falling specifies if the water is falling. Falling water will always appear as a source block, but its
// behaviour differs when it starts spreading.
Falling bool
}
// AABB returns no boxes.
func (Water) AABB(world.BlockPos, *world.World) []physics.AABB {
return nil
}
// LiquidDepth returns the depth of the water.
func (w Water) LiquidDepth() int {
return w.Depth
}
// SpreadDecay returns 1 - The amount of levels decreased upon spreading.
func (Water) SpreadDecay() int {
return 1
}
// WithDepth returns the water with the depth passed.
func (w Water) WithDepth(depth int, falling bool) world.Liquid {
w.Depth = depth
w.Falling = falling
w.Still = false
return w
}
// LiquidFalling returns Water.Falling.
func (w Water) LiquidFalling() bool {
return w.Falling
}
// HasLiquidDrops ...
func (Water) HasLiquidDrops() bool {
return false
}
// ReplaceableBy ...
func (Water) ReplaceableBy(world.Block) bool {
return true
}
// LightDiffusionLevel ...
func (Water) LightDiffusionLevel() uint8 {
return 2
}
// ScheduledTick ...
func (w Water) ScheduledTick(pos world.BlockPos, wo *world.World) {
if w.Depth == 7 {
// Attempt to form new water source blocks.
count := 0
pos.Neighbours(func(neighbour world.BlockPos) {
if neighbour[1] == pos[1] {
if liquid, ok := wo.Liquid(neighbour); ok {
if water, ok := liquid.(Water); ok && water.Depth == 8 && !water.Falling {
count++
}
}
}
})
if count >= 2 {
func() {
if canFlowInto(w, wo, pos.Side(world.FaceDown), true) {
return
}
// Only form a new source block if there either is no water below this block, or if the water
// below this is not falling (full source block).
wo.SetLiquid(pos, Water{Depth: 8, Still: true})
}()
}
}
tickLiquid(w, pos, wo)
}
// NeighbourUpdateTick ...
func (Water) NeighbourUpdateTick(pos, _ world.BlockPos, wo *world.World) {
wo.ScheduleBlockUpdate(pos, time.Second/4)
}
// LiquidType ...
func (Water) LiquidType() string {
return "water"
}
// Harden hardens the water if lava flows into it.
func (w Water) Harden(pos world.BlockPos, wo *world.World, flownIntoBy *world.BlockPos) bool {
if flownIntoBy == nil {
return false
}
if lava, ok := wo.Block(pos.Side(world.FaceUp)).(Lava); ok {
ctx := event.C()
wo.Handler().HandleLiquidHarden(ctx, pos, w, lava, Stone{})
ctx.Continue(func() {
wo.PlaceBlock(pos, Stone{})
wo.PlaySound(pos.Vec3Centre(), sound.Fizz{})
})
return true
} else if lava, ok := wo.Block(*flownIntoBy).(Lava); ok {
ctx := event.C()
wo.Handler().HandleLiquidHarden(ctx, pos, w, lava, Cobblestone{})
ctx.Continue(func() {
wo.PlaceBlock(*flownIntoBy, Cobblestone{})
wo.PlaySound(pos.Vec3Centre(), sound.Fizz{})
})
return true
}
return false
}
// EncodeBlock ...
func (w Water) EncodeBlock() (name string, properties map[string]interface{}) {
if w.Depth < 1 || w.Depth > 8 {
panic("invalid water depth, must be between 1 and 8")
}
v := 8 - w.Depth
if w.Falling {
v += 8
}
if w.Still {
return "minecraft:water", map[string]interface{}{"liquid_depth": int32(v)}
}
return "minecraft:flowing_water", map[string]interface{}{"liquid_depth": int32(v)}
}
// Hash ...
func (w Water) Hash() uint64 {
return hashWater | (uint64(boolByte(w.Falling)) << 32) | (uint64(boolByte(w.Still)) << 33) | (uint64(w.Depth) << 34)
}
// allWater returns a list of all water states.
func allWater() (b []world.Block) {
f := func(still, falling bool) {
b = append(b, Water{Still: still, Falling: falling, Depth: 8})
b = append(b, Water{Still: still, Falling: falling, Depth: 7})
b = append(b, Water{Still: still, Falling: falling, Depth: 6})
b = append(b, Water{Still: still, Falling: falling, Depth: 5})
b = append(b, Water{Still: still, Falling: falling, Depth: 4})
b = append(b, Water{Still: still, Falling: falling, Depth: 3})
b = append(b, Water{Still: still, Falling: falling, Depth: 2})
b = append(b, Water{Still: still, Falling: falling, Depth: 1})
}
f(true, true)
f(true, false)
f(false, false)
f(false, true)
return
}
<file_sep>package effect
import (
"github.com/df-mc/dragonfly/dragonfly/entity"
"image/color"
"time"
)
// Speed is a lasting effect that increases the speed of an entity by 20% for each level that the effect has.
type Speed struct {
lastingEffect
}
// Start ...
func (s Speed) Start(e entity.Living) {
speed := 1 + float64(s.Lvl)*0.2
e.SetSpeed(e.Speed() * speed)
}
// End ...
func (s Speed) End(e entity.Living) {
speed := 1 + float64(s.Lvl)*0.2
e.SetSpeed(e.Speed() / speed)
}
// WithDuration ...
func (s Speed) WithDuration(d time.Duration) entity.Effect {
return Speed{s.withDuration(d)}
}
// RGBA ...
func (Speed) RGBA() color.RGBA {
return color.RGBA{R: 0x7c, G: 0xaf, B: 0xc6, A: 0xff}
}
<file_sep>package mcdb
// data holds a collection of data that specify a range of settings of the world. These settings usually
// alter the way that players interact with the world.
// The data held here is usually saved in a level.dat file of the world.
//noinspection SpellCheckingInspection
type data struct {
BaseGameVersion string `nbt:"baseGameVersion"`
ConfirmedPlatformLockedContent bool
CenterMapsToOrigin bool
Difficulty int32
EduOffer int32 `nbt:"eduOffer"`
FlatWorldLayers string
ForceGameType bool
GameType int32
Generator int32
InventoryVersion string
LANBroadcast bool
LANBroadcastIntent bool
LastPlayed int64
LevelName string
LimitedWorldOriginX int32
LimitedWorldOriginY int32
LimitedWorldOriginZ int32
MinimumCompatibleClientVersion []int32
MultiPlayerGame bool `nbt:"MultiplayerGame"`
MultiPlayerGameIntent bool `nbt:"MultiplayerGameIntent"`
NetherScale int32
NetworkVersion int32
Platform int32
PlatformBroadcastIntent int32
RandomSeed int64
ShowTags bool `nbt:"showtags"`
SpawnX, SpawnY, SpawnZ int32
SpawnV1Villagers bool
StorageVersion int32
Time int64
XBLBroadcast bool
XBLBroadcastIntent int32
XBLBroadcastMode int32
Abilities struct {
AttackMobs bool `nbt:"attackmobs"`
AttackPlayers bool `nbt:"attackplayers"`
Build bool `nbt:"build"`
Mine bool `nbt:"mine"`
DoorsAndSwitches bool `nbt:"doorsandswitches"`
FlySpeed float32 `nbt:"flySpeed"`
Flying bool `nbt:"flying"`
InstantBuild bool `nbt:"instabuild"`
Invulnerable bool `nbt:"invulnerable"`
Lightning bool `nbt:"lightning"`
MayFly bool `nbt:"mayfly"`
OP bool `nbt:"op"`
OpenContainers bool `nbt:"opencontainers"`
PermissionsLevel int32 `nbt:"permissionsLevel"`
PlayerPermissionsLevel int32 `nbt:"playerPermissionsLevel"`
Teleport bool `nbt:"teleport"`
WalkSpeed float32 `nbt:"walkSpeed"`
} `nbt:"abilities"`
BonusChestEnabled bool `nbt:"bonusChestEnabled"`
BonusChestSpawned bool `nbt:"bonusChestSpawned"`
CommandBlockOutput bool `nbt:"commandblockoutput"`
CommandBlocksEnabled bool `nbt:"commandblocksenabled"`
CommandsEnabled bool `nbt:"commandsEnabled"`
CurrentTick int64 `nbt:"currentTick"`
DoDayLightCycle bool `nbt:"dodaylightcycle"`
DoEntityDrops bool `nbt:"doentitydrops"`
DoFireTick bool `nbt:"dofiretick"`
DoImmediateRespawn bool `nbt:"doimmediaterespawn"`
DoInsomnia bool `nbt:"doinsomnia"`
DoMobLoot bool `nbt:"domobloot"`
DoMobSpawning bool `nbt:"domobspawning"`
DoTileDrops bool `nbt:"dotiledrops"`
DoWeatherCycle bool `nbt:"doweathercycle"`
DrowningDamage bool `nbt:"drowningdamage"`
EduLevel bool `nbt:"eduLevel"`
EducationFeaturesEnabled bool `nbt:"educationFeaturesEnabled"`
ExperimentalGamePlay bool `nbt:"experimentalgameplay"`
FallDamage bool `nbt:"falldamage"`
FireDamage bool `nbt:"firedamage"`
FunctionCommandLimit int32 `nbt:"functioncommandlimit"`
HasBeenLoadedInCreative bool `nbt:"hasBeenLoadedInCreative"`
HasLockedBehaviourPack bool `nbt:"hasLockedBehaviorPack"`
HasLockedResourcePack bool `nbt:"hasLockedResourcePack"`
ImmutableWorld bool `nbt:"immutableWorld"`
IsFromLockedTemplate bool `nbt:"isFromLockedTemplate"`
IsFromWorldTemplate bool `nbt:"isFromWorldTemplate"`
IsWorldTemplateOptionLocked bool `nbt:"isWorldTemplateOptionLocked"`
KeepInventory bool `nbt:"keepinventory"`
LastOpenedWithVersion []int32 `nbt:"lastOpenedWithVersion"`
LightningLevel float32 `nbt:"lightningLevel"`
LightningTime int32 `nbt:"lightningTime"`
MaxCommandChainLength int32 `nbt:"maxcommandchainlength"`
MobGriefing bool `nbt:"mobgriefing"`
NaturalRegeneration bool `nbt:"naturalregeneration"`
PRID string `nbt:"prid"`
PVP bool `nbt:"pvp"`
RainLevel float32 `nbt:"rainLevel"`
RainTime int32 `nbt:"rainTime"`
RandomTickSpeed int32 `nbt:"randomtickspeed"`
RequiresCopiedPackRemovalCheck bool `nbt:"requiresCopiedPackRemovalCheck"`
SendCommandFeedback bool `nbt:"sendcommandfeedback"`
ServerChunkTickRange int32 `nbt:"serverChunkTickRange"`
ShowCoordinates bool `nbt:"showcoordinates"`
ShowDeathMessages bool `nbt:"showdeathmessages"`
SpawnMobs bool `nbt:"spawnMobs"`
SpawnRadius int32 `nbt:"spawnradius"`
StartWithMapEnabled bool `nbt:"startWithMapEnabled"`
TexturePacksRequired bool `nbt:"texturePacksRequired"`
TNTExplodes bool `nbt:"tntexplodes"`
UseMSAGamerTagsOnly bool `nbt:"useMsaGamertagsOnly"`
WorldStartCount int64 `nbt:"worldStartCount"`
}
<file_sep>package block
import (
"github.com/df-mc/dragonfly/dragonfly/block/wood"
"github.com/df-mc/dragonfly/dragonfly/item"
"github.com/df-mc/dragonfly/dragonfly/world"
)
// Planks are common blocks used in crafting recipes. They are made by crafting logs into planks.
type Planks struct {
noNBT
// Wood is the type of wood of the planks. This field must have one of the values found in the material
// package.
Wood wood.Wood
}
// BreakInfo ...
func (p Planks) BreakInfo() BreakInfo {
return BreakInfo{
Hardness: 2,
Harvestable: alwaysHarvestable,
Effective: axeEffective,
Drops: simpleDrops(item.NewStack(p, 1)),
}
}
// EncodeItem ...
func (p Planks) EncodeItem() (id int32, meta int16) {
switch p.Wood {
case wood.Oak():
return 5, 0
case wood.Spruce():
return 5, 1
case wood.Birch():
return 5, 2
case wood.Jungle():
return 5, 3
case wood.Acacia():
return 5, 4
case wood.DarkOak():
return 5, 5
}
panic("invalid wood type")
}
// EncodeBlock ...
func (p Planks) EncodeBlock() (name string, properties map[string]interface{}) {
return "minecraft:planks", map[string]interface{}{"wood_type": p.Wood.String()}
}
// Hash ...
func (p Planks) Hash() uint64 {
return hashPlanks | (uint64(p.Wood.Uint8()) << 32)
}
// allPlanks returns all planks types.
func allPlanks() []world.Block {
return []world.Block{
Planks{Wood: wood.Oak()},
Planks{Wood: wood.Spruce()},
Planks{Wood: wood.Birch()},
Planks{Wood: wood.Jungle()},
Planks{Wood: wood.Acacia()},
Planks{Wood: wood.DarkOak()},
}
}
<file_sep>package block
import (
"github.com/df-mc/dragonfly/dragonfly/block/colour"
"github.com/df-mc/dragonfly/dragonfly/entity/physics"
"github.com/df-mc/dragonfly/dragonfly/item"
"github.com/df-mc/dragonfly/dragonfly/world"
"github.com/go-gl/mathgl/mgl64"
"time"
)
// Carpet is a colourful block that can be obtained by killing/shearing sheep, or crafted using four string.
type Carpet struct {
noNBT
Colour colour.Colour
}
// CanDisplace ...
func (Carpet) CanDisplace(b world.Liquid) bool {
_, water := b.(Water)
return water
}
// SideClosed ...
func (Carpet) SideClosed(world.BlockPos, world.BlockPos, *world.World) bool {
return false
}
// AABB ...
func (Carpet) AABB(world.BlockPos, *world.World) []physics.AABB {
return []physics.AABB{physics.NewAABB(mgl64.Vec3{}, mgl64.Vec3{1, 0.0625, 1})}
}
// BreakInfo ...
func (c Carpet) BreakInfo() BreakInfo {
return BreakInfo{
Hardness: 0.1,
Harvestable: alwaysHarvestable,
Effective: neverEffective,
Drops: simpleDrops(item.NewStack(c, 1)),
}
}
// EncodeItem ...
func (c Carpet) EncodeItem() (id int32, meta int16) {
return 171, int16(c.Colour.Uint8())
}
// EncodeBlock ...
func (c Carpet) EncodeBlock() (name string, properties map[string]interface{}) {
return "minecraft:carpet", map[string]interface{}{"color": c.Colour.String()}
}
// Hash ...
func (c Carpet) Hash() uint64 {
return hashCarpet | (uint64(c.Colour.Uint8()) << 32)
}
// HasLiquidDrops ...
func (Carpet) HasLiquidDrops() bool {
return true
}
// NeighbourUpdateTick ...
func (Carpet) NeighbourUpdateTick(pos, changed world.BlockPos, w *world.World) {
if _, ok := w.Block(pos.Add(world.BlockPos{0, -1})).(Air); ok {
w.ScheduleBlockUpdate(pos, time.Second/20)
}
}
// ScheduledTick ...
func (Carpet) ScheduledTick(pos world.BlockPos, w *world.World) {
if _, ok := w.Block(pos.Add(world.BlockPos{0, -1})).(Air); ok {
w.BreakBlock(pos)
}
}
// UseOnBlock handles not placing carpets on top of air blocks.
func (c Carpet) UseOnBlock(pos world.BlockPos, face world.Face, _ mgl64.Vec3, wrld *world.World, user item.User, ctx *item.UseContext) (used bool) {
pos, _, used = firstReplaceable(wrld, pos, face, c)
if !used {
return
}
if _, ok := wrld.Block((world.BlockPos{pos.X(), pos.Y() - 1, pos.Z()})).(Air); ok {
return
}
place(wrld, pos, c, user, ctx)
return placed(ctx)
}
// allCarpets returns carpet blocks with all possible colours.
func allCarpets() []world.Block {
b := make([]world.Block, 0, 16)
for _, c := range colour.All() {
b = append(b, Carpet{Colour: c})
}
return b
}
<file_sep>package effect
import (
"github.com/df-mc/dragonfly/dragonfly/entity"
"image/color"
"time"
)
// Weakness is a lasting effect that reduces the damage dealt to other entities with melee attacks.
type Weakness struct {
lastingEffect
}
// Multiplier returns the damage multiplier of the effect.
func (w Weakness) Multiplier() float64 {
v := -0.2 * float64(w.Lvl)
if v < -1 {
v = -1
}
return v
}
// WithDuration ...
func (w Weakness) WithDuration(d time.Duration) entity.Effect {
return Weakness{w.withDuration(d)}
}
// RGBA ...
func (Weakness) RGBA() color.RGBA {
return color.RGBA{R: 0x48, G: 0x4d, B: 0x48, A: 0xff}
}
<file_sep>package chunk
import "sync"
// Chunk is a segment in the world with a size of 16x16x256 blocks. A chunk contains multiple sub chunks
// and stores other information such as biomes.
// It is not safe to call methods on Chunk simultaneously from multiple goroutines.
type Chunk struct {
sync.Mutex
// sub holds all sub chunks part of the chunk. The pointers held by the array are nil if no sub chunk is
// allocated at the indices.
sub [16]*SubChunk
// biomes is an array of biome IDs. There is one biome ID for every column in the chunk.
biomes [256]uint8
// blockEntities holds all block entities of the chunk, prefixed by their absolute position.
blockEntities map[[3]int]map[string]interface{}
}
// New initialises a new chunk and returns it, so that it may be used.
func New() *Chunk {
return &Chunk{blockEntities: make(map[[3]int]map[string]interface{})}
}
// Sub returns a list of all sub chunks present in the chunk.
func (chunk *Chunk) Sub() []*SubChunk {
return chunk.sub[:]
}
// BiomeID returns the biome ID at a specific column in the chunk.
func (chunk *Chunk) BiomeID(x, z uint8) uint8 {
return chunk.biomes[columnOffset(x, z)]
}
// SetBiomeID sets the biome ID at a specific column in the chunk.
func (chunk *Chunk) SetBiomeID(x, z, biomeID uint8) {
chunk.biomes[columnOffset(x, z)] = biomeID
}
// Light returns the light level at a specific position in the chunk.
func (chunk *Chunk) Light(x, y, z uint8) uint8 {
i := y >> 4
if chunk.sub[i] == nil {
return 15
}
return chunk.sub[i].Light(x&15, y&15, z&15)
}
// SkyLight returns the sky light level at a specific position in the chunk.
func (chunk *Chunk) SkyLight(x, y, z uint8) uint8 {
i := y >> 4
if chunk.sub[i] == nil {
return 15
}
return chunk.sub[i].SkyLightAt(x&15, y&15, z&15)
}
// RuntimeID returns the runtime ID of the block at a given x, y and z in a chunk at the given layer. If no
// sub chunk exists at the given y, the block is assumed to be air.
func (chunk *Chunk) RuntimeID(x, y, z uint8, layer uint8) uint32 {
sub := chunk.sub[y>>4]
if sub == nil {
// The sub chunk was not initialised, so we can conclude that the block at that location would be
// an air block. (always runtime ID 0)
return 0
}
return sub.RuntimeID(x, y, z, layer)
}
// fullSkyLight is used to copy full light to newly created sub chunks.
var fullSkyLight [2048]byte
// SetRuntimeID sets the runtime ID of a block at a given x, y and z in a chunk at the given layer. If no
// SubChunk exists at the given y, a new SubChunk is created and the block is set.
func (chunk *Chunk) SetRuntimeID(x, y, z uint8, layer uint8, runtimeID uint32) {
i := y >> 4
sub := chunk.sub[i]
if sub == nil {
// The first layer is initialised in the next call to Layer().
sub = &SubChunk{skyLight: fullSkyLight}
chunk.sub[i] = sub
}
if len(sub.storages) < 2 && runtimeID == 0 && layer == 1 {
// Air was set at the second layer, but there were less than 2 layers, so there already was air there.
// Don't do anything with this, just return.
return
}
sub.Layer(layer).SetRuntimeID(x, y, z, runtimeID)
}
// HighestLightBlocker iterates from the highest non-empty sub chunk downwards to find the Y value of the
// highest block that completely blocks any light from going through. If none is found, the value returned is
// 0.
func (chunk *Chunk) HighestLightBlocker(x, z uint8) uint8 {
for subY := 15; subY >= 0; subY-- {
sub := chunk.sub[subY]
if sub == nil || len(sub.storages) == 0 {
continue
}
for y := 15; y >= 0; y-- {
totalY := uint8(y | (subY << 4))
rid := sub.storages[0].RuntimeID(x, totalY, z)
if _, ok := FilteringBlocks[rid]; !ok {
return totalY
}
}
}
return 0
}
// SetBlockNBT sets block NBT data to a given position in the chunk. If the data passed is nil, the block NBT
// currently present will be cleared.
func (chunk *Chunk) SetBlockNBT(pos [3]int, data map[string]interface{}) {
if data == nil {
delete(chunk.blockEntities, pos)
return
}
chunk.blockEntities[pos] = data
}
// BlockNBT returns a list of all block NBT data set in the chunk.
func (chunk *Chunk) BlockNBT() map[[3]int]map[string]interface{} {
return chunk.blockEntities
}
// Compact compacts the chunk as much as possible, getting rid of any sub chunks that are empty, and compacts
// all storages in the sub chunks to occupy as little space as possible.
// Compact should be called right before the chunk is saved in order to optimise the storage space.
func (chunk *Chunk) Compact() {
for i, sub := range chunk.sub {
if sub == nil {
continue
}
sub.compact()
if len(sub.storages) == 0 {
chunk.sub[i] = nil
}
}
}
// columnOffset returns the offset in a byte slice that the column at a specific x and z may be found.
func columnOffset(x, z uint8) uint8 {
return (x & 15) | (z&15)<<4
}
<file_sep>package effect
import (
"github.com/df-mc/dragonfly/dragonfly/entity"
"image/color"
"time"
)
// instantEffect forms the base of an instant effect.
type instantEffect struct {
// Lvl holds the level of the effect. A higher level results in a more powerful effect, whereas a negative
// level will generally inverse effect.
Lvl int
}
// Instant always returns true for instant effects.
func (instantEffect) Instant() bool {
return true
}
// Level returns the level of the instant effect.
func (i instantEffect) Level() int {
return i.Lvl
}
// Duration always returns 0 for instant effects.
func (instantEffect) Duration() time.Duration {
return 0
}
// ShowParticles always returns false for instant effects.
func (instantEffect) ShowParticles() bool {
return false
}
// AmbientSource always returns false for instant effects.
func (instantEffect) AmbientSource() bool {
return false
}
// RGBA always returns an empty color.RGBA.
func (instantEffect) RGBA() color.RGBA {
return color.RGBA{}
}
// End ...
func (instantEffect) End(entity.Living) {}
// Start ...
func (instantEffect) Start(entity.Living) {}
// lastingEffect forms the base of an effect that lasts for a specific duration.
type lastingEffect struct {
// Lvl holds the level of the effect. A higher level results in a more powerful effect, whereas a negative
// level will generally inverse effect.
Lvl int
// Dur holds the duration of the effect. One will be subtracted every time the entity that the effect is
// added to is ticked.
Dur time.Duration
// HideParticles hides the coloured particles of the effect when added to an entity.
HideParticles bool
// Ambient specifies if the effect comes from an ambient source, such as from a beacon or conduit. The
// particles displayed when Ambient is true are less visible.
Ambient bool
}
// Instant always returns false for lasting effects.
func (lastingEffect) Instant() bool {
return false
}
// Level returns the level of the lasting effect.
func (l lastingEffect) Level() int {
return l.Lvl
}
// Duration returns the leftover duration of the lasting effect.
func (l lastingEffect) Duration() time.Duration {
return l.Dur
}
// ShowParticles returns true if the effect does not display particles.
func (l lastingEffect) ShowParticles() bool {
return !l.HideParticles
}
// AmbientSource specifies if the effect comes from a beacon or conduit.
func (l lastingEffect) AmbientSource() bool {
return l.Ambient
}
// withDuration returns the lastingEffect with the duration passed.
func (l lastingEffect) withDuration(d time.Duration) lastingEffect {
l.Dur = d
return l
}
// End ...
func (lastingEffect) End(entity.Living) {}
// Start ...
func (lastingEffect) Start(entity.Living) {}
// Apply ...
func (lastingEffect) Apply(living entity.Living) {}
// tickDuration returns the duration as in-game ticks.
func tickDuration(d time.Duration) int {
return int(d / (time.Second / 20))
}
// ResultingColour calculates the resulting colour of the effects passed and returns a bool specifying if the
// effects were ambient effects, which will cause their particles to display less frequently.
func ResultingColour(effects []entity.Effect) (color.RGBA, bool) {
r, g, b, a := 0, 0, 0, 0
l := len(effects)
if l == 0 {
return color.RGBA{}, false
}
ambient := true
for _, e := range effects {
c := e.RGBA()
r += int(c.R)
g += int(c.G)
b += int(c.B)
a += int(c.A)
if !e.AmbientSource() {
ambient = false
}
}
return color.RGBA{R: uint8(r / l), G: uint8(g / l), B: uint8(b / l), A: uint8(a / l)}, ambient
}
<file_sep>package block
import (
"github.com/df-mc/dragonfly/dragonfly/item"
)
// Beacon is a block that projects a light beam skyward, and can provide status effects such as Speed, Jump
// Boost, Haste, Regeneration, Resistance, or Strength to nearby players.
type Beacon struct{ nbt }
// TODO: Implement beacons properly.
// BreakInfo ...
func (b Beacon) BreakInfo() BreakInfo {
return BreakInfo{
Hardness: 3,
Harvestable: alwaysHarvestable,
Effective: nothingEffective,
Drops: simpleDrops(item.NewStack(b, 1)),
}
}
// EncodeItem ...
func (b Beacon) EncodeItem() (id int32, meta int16) {
return 138, 0
}
// EncodeBlock ...
func (b Beacon) EncodeBlock() (name string, properties map[string]interface{}) {
return "minecraft:beacon", nil
}
// Hash ...
func (Beacon) Hash() uint64 {
return hashBeacon
}
<file_sep>package block
import (
"github.com/df-mc/dragonfly/dragonfly/entity/physics"
"github.com/df-mc/dragonfly/dragonfly/item"
"github.com/df-mc/dragonfly/dragonfly/world"
"github.com/go-gl/mathgl/mgl64"
"math/rand"
"time"
)
// Kelp is an underwater block which can grow on top of solids underwater.
type Kelp struct {
noNBT
// Age is the age of the kelp block which can be 0-15. If age is 15, kelp won't grow any further.
Age int
}
// BreakInfo ...
func (k Kelp) BreakInfo() BreakInfo {
// Kelp can be instantly destroyed.
return BreakInfo{
Hardness: 0.0,
Harvestable: alwaysHarvestable,
Effective: nothingEffective,
Drops: simpleDrops(item.NewStack(k, 1)),
}
}
// EncodeItem ...
func (Kelp) EncodeItem() (id int32, meta int16) {
return 335, 0
}
// EncodeBlock ...
func (k Kelp) EncodeBlock() (name string, properties map[string]interface{}) {
return "minecraft:kelp", map[string]interface{}{"age": int32(k.Age)}
}
// Hash ...
func (k Kelp) Hash() uint64 {
return hashKelp | (uint64(k.Age) << 32)
}
// CanDisplace will return true if the liquid is Water, since kelp can waterlog.
func (Kelp) CanDisplace(b world.Liquid) bool {
_, water := b.(Water)
return water
}
// SideClosed will always return false since kelp doesn't close any side.
func (Kelp) SideClosed(pos, side world.BlockPos, w *world.World) bool {
return false
}
// AABB will always return nil, since Kelp can be placed even if someone is standing on its placement position.
func (Kelp) AABB(world.BlockPos, *world.World) []physics.AABB {
return nil
}
// withRandomAge returns a new Kelp block with its age value randomized between 0 and 14.
func (k Kelp) withRandomAge() Kelp {
// In Java Edition, Kelp's age value can be up to 25, but MCPE limits it to 15.
k.Age = rand.Intn(14)
return k
}
// UseOnBlock ...
func (k Kelp) UseOnBlock(pos world.BlockPos, face world.Face, _ mgl64.Vec3, w *world.World, user item.User, ctx *item.UseContext) (used bool) {
pos, _, used = firstReplaceable(w, pos, face, k)
if !used {
return
}
switch w.Block(pos.Add(world.BlockPos{0, -1})).(type) {
// Kelp blocks must be placed on a solid or another kelp block, TODO: Replace this to check for a solid in the future when a Solid interface exists.
case Air, Water:
return false
}
liquid, ok := w.Liquid(pos)
if !ok {
return false
} else if _, ok := liquid.(Water); !ok || liquid.LiquidDepth() < 8 {
return false
}
// When first placed, kelp gets a random age between 0 and 14 in MCBE.
place(w, pos, k.withRandomAge(), user, ctx)
return placed(ctx)
}
// NeighbourUpdateTick ...
func (k Kelp) NeighbourUpdateTick(pos, changed world.BlockPos, w *world.World) {
if _, ok := w.Liquid(pos); !ok {
w.BreakBlock(pos)
return
}
if changed.Y()-1 == pos.Y() {
// When a kelp block is broken above, the kelp block underneath it gets a new random age.
w.PlaceBlock(pos, k.withRandomAge())
}
switch w.Block(pos.Add(world.BlockPos{0, -1})).(type) {
// Kelp blocks can only exist on top of a solid or another kelp block, TODO: Replace this to check for a solid in the future when a Solid interface exists.
case Air, Water:
w.ScheduleBlockUpdate(pos, time.Second/20)
}
}
// ScheduledTick ...
func (Kelp) ScheduledTick(pos world.BlockPos, w *world.World) {
if _, ok := w.Liquid(pos); !ok {
w.BreakBlock(pos)
return
}
// Kelp blocks can only exist on top of a solid or another kelp block, TODO: Replace this to check for a solid in the future when a Solid interface exists.
switch w.Block(pos.Add(world.BlockPos{0, -1})).(type) {
// As of now, the breaking logic has to be in here as well to avoid issues.
case Air, Water:
w.BreakBlock(pos)
}
}
// RandomTick ...
func (k Kelp) RandomTick(pos world.BlockPos, w *world.World, r *rand.Rand) {
if r.Intn(100) < 15 && k.Age < 15 {
// Every random tick, there's a 14% chance for Kelp to grow if its age is below 15.
abovePos := pos.Add(world.BlockPos{0, 1})
liquid, ok := w.Liquid(abovePos)
// For kelp to grow, there must be only water above.
if !ok {
return
} else if _, ok := liquid.(Water); ok {
switch w.Block(abovePos).(type) {
case Air, Water:
w.PlaceBlock(abovePos, Kelp{Age: k.Age + 1})
if liquid.LiquidDepth() < 8 {
// When kelp grows into a water block, the water block becomes a source block.
w.SetLiquid(abovePos, Water{Still: true, Depth: 8, Falling: false})
}
}
}
}
w.ScheduleBlockUpdate(pos, time.Second/20)
}
// allKelp returns all possible states of a kelp block.
func allKelp() (b []world.Block) {
for i := 0; i < 16; i++ {
b = append(b, Kelp{Age: i})
}
return
}
<file_sep>package world
import (
"github.com/go-gl/mathgl/mgl64"
"math"
"unsafe"
)
// BlockPos holds the position of a block. The position is represented of an array with an x, y and z value,
// where the y value is positive.
type BlockPos [3]int
// X returns the X coordinate of the block position.
func (p BlockPos) X() int {
return p[0]
}
// Y returns the Y coordinate of the block position.
func (p BlockPos) Y() int {
return p[1]
}
// Z returns the Z coordinate of the block position.
func (p BlockPos) Z() int {
return p[2]
}
// OutOfBounds checks if the Y value is either bigger than 255 or smaller than 0.
func (p BlockPos) OutOfBounds() bool {
y := p[1]
return y > 255 || y < 0
}
// Add adds two block positions together and returns a new one with the combined values.
func (p BlockPos) Add(pos BlockPos) BlockPos {
return BlockPos{p[0] + pos[0], p[1] + pos[1], p[2] + pos[2]}
}
// Vec3 returns a vec3 holding the same coordinates as the block position.
func (p BlockPos) Vec3() mgl64.Vec3 {
return mgl64.Vec3{float64(p[0]), float64(p[1]), float64(p[2])}
}
// Vec3Middle returns a Vec3 holding the coordinates of the block position with 0.5 added on both horizontal
// axes.
func (p BlockPos) Vec3Middle() mgl64.Vec3 {
return mgl64.Vec3{float64(p[0]) + 0.5, float64(p[1]), float64(p[2]) + 0.5}
}
// Vec3Centre returns a Vec3 holding the coordinates of the block position with 0.5 added on all axes.
func (p BlockPos) Vec3Centre() mgl64.Vec3 {
return mgl64.Vec3{float64(p[0]) + 0.5, float64(p[1]) + 0.5, float64(p[2]) + 0.5}
}
// Side returns the position on the side of this block position, at a specific face.
func (p BlockPos) Side(face Face) BlockPos {
switch face {
case FaceUp:
p[1]++
case FaceDown:
p[1]--
case FaceNorth:
p[2]--
case FaceSouth:
p[2]++
case FaceWest:
p[0]--
case FaceEast:
p[0]++
}
return p
}
// Neighbours calls the function passed for each of the block position's neighbours. If the Y value is below
// 0 or above 255, the function will not be called for that position.
func (p BlockPos) Neighbours(f func(neighbour BlockPos)) {
y := p[1]
if y > 255 || y < 0 {
return
}
p[0]++
f(p)
p[0] -= 2
f(p)
p[0]++
p[1]++
if p[1] <= 255 {
f(p)
}
p[1] -= 2
if p[1] >= 0 {
f(p)
}
p[1]++
p[2]++
f(p)
p[2] -= 2
f(p)
}
// blockPosFromNBT returns a position from the X, Y and Z components stored in the NBT data map passed. The
// map is assumed to have an 'x', 'y' and 'z' key.
//noinspection GoCommentLeadingSpace
func blockPosFromNBT(data map[string]interface{}) BlockPos {
//lint:ignore S1005 Double assignment is done explicitly to prevent panics.
xInterface, _ := data["x"]
//lint:ignore S1005 Double assignment is done explicitly to prevent panics.
yInterface, _ := data["y"]
//lint:ignore S1005 Double assignment is done explicitly to prevent panics.
zInterface, _ := data["z"]
x, _ := xInterface.(int32)
y, _ := yInterface.(int32)
z, _ := zInterface.(int32)
return BlockPos{int(x), int(y), int(z)}
}
// BlockPosFromVec3 returns a block position by a Vec3, rounding the values down adequately.
func BlockPosFromVec3(vec3 mgl64.Vec3) BlockPos {
return BlockPos{int(math.Floor(vec3[0])), int(math.Floor(vec3[1])), int(math.Floor(vec3[2]))}
}
// ChunkPos holds the position of a chunk. The type is provided as a utility struct for keeping track of a
// chunk's position. Chunks do not themselves keep track of that. Chunk positions are different than block
// positions in the way that increasing the X/Z by one means increasing the absolute value on the X/Z axis in
// terms of blocks by 16.
type ChunkPos [2]int32
// X returns the X coordinate of the chunk position.
func (p ChunkPos) X() int32 {
return p[0]
}
// Z returns the Z coordinate of the chunk position.
func (p ChunkPos) Z() int32 {
return p[1]
}
// Hash returns the hash of the chunk position. It is essentially the bytes of the X and Z values of the
// position following each other.
func (p ChunkPos) Hash() string {
x, z := p[0], p[1]
v := []byte{
uint8(x >> 24), uint8(x >> 16), uint8(x >> 8), uint8(x),
uint8(z >> 24), uint8(z >> 16), uint8(z >> 8), uint8(z),
}
// We can 'safely' unsafely turn the byte slice into a string here, as the byte slice will never be
// changed. (It never leaves the method.)
return *(*string)(unsafe.Pointer(&v))
}
// chunkPosFromVec3 returns a chunk position from the Vec3 passed. The coordinates of the chunk position are
// those of the Vec3 divided by 16, then rounded down.
func chunkPosFromVec3(vec3 mgl64.Vec3) ChunkPos {
return ChunkPos{
int32(math.Floor(vec3[0] / 16)),
int32(math.Floor(vec3[2] / 16)),
}
}
// chunkPosFromBlockPos returns a chunk position of the chunk that a block at this position would be in.
func chunkPosFromBlockPos(p BlockPos) ChunkPos {
return ChunkPos{int32(p[0] >> 4), int32(p[2] >> 4)}
}
// Distance returns the distance between two vectors.
func Distance(a, b mgl64.Vec3) float64 {
return math.Sqrt(
math.Pow(b[0]-a[0], 2) +
math.Pow(b[1]-a[1], 2) +
math.Pow(b[2]-a[2], 2),
)
}
<file_sep>package entity
import (
"github.com/df-mc/dragonfly/dragonfly/entity/physics"
"github.com/df-mc/dragonfly/dragonfly/world"
"github.com/go-gl/mathgl/mgl64"
"math"
)
// boxes returns the axis aligned bounding box of a block.
func boxes(b world.Block, pos world.BlockPos, w *world.World) []physics.AABB {
if aabb, ok := b.(interface {
AABB(pos world.BlockPos, w *world.World) []physics.AABB
}); ok {
return aabb.AABB(pos, w)
}
return []physics.AABB{physics.NewAABB(mgl64.Vec3{}, mgl64.Vec3{1, 1, 1})}
}
// movementComputer is used to compute movement of an entity. When constructed, the gravity of the entity
// the movement is computed for must be passed.
type movementComputer struct {
onGround bool
gravity float64
dragBeforeGravity bool
}
// tickMovement performs a movement tick on an entity. Velocity is applied and changed according to the values
// of its drag and gravity.
// The new position of the entity after movement is returned.
func (c *movementComputer) tickMovement(e world.Entity) mgl64.Vec3 {
toMove, velocity := c.handleCollision(e)
e.SetVelocity(velocity)
v := c.move(e, toMove)
e.SetVelocity(c.applyGravity(e))
e.SetVelocity(c.applyFriction(e))
return v
}
// applyGravity applies gravity to the entity's velocity. By default, 0.08 is subtracted from the y value, or
// a different value if the Gravity
func (c *movementComputer) applyGravity(e world.Entity) mgl64.Vec3 {
velocity := e.Velocity()
if c.dragBeforeGravity {
velocity[1] *= 0.98
}
velocity[1] -= c.gravity
if !c.dragBeforeGravity {
velocity[1] *= 0.98
}
return velocity
}
// applyFriction applies friction to the entity, reducing its velocity on the X and Z axes.
func (c *movementComputer) applyFriction(e world.Entity) mgl64.Vec3 {
velocity := e.Velocity()
if c.onGround {
velocity[0] *= 0.6
velocity[2] *= 0.6
return velocity
}
velocity[0] *= 0.91
velocity[2] *= 0.91
return velocity
}
// move moves the entity so that all viewers in the world can see it, adding the velocity to the position.
func (c *movementComputer) move(e world.Entity, deltaPos mgl64.Vec3) mgl64.Vec3 {
if deltaPos.ApproxEqualThreshold(mgl64.Vec3{}, 0.01) {
return e.Position()
}
for _, v := range e.World().Viewers(e.Position()) {
v.ViewEntityMovement(e, deltaPos.Add(mgl64.Vec3{0, 0.125, 0}), 0, 0)
}
return e.Position().Add(deltaPos)
}
// handleCollision handles the collision of the entity with blocks, adapting the velocity of the entity if it
// happens to collide with a block.
// The final velocity and the Vec3 that the entity should move is returned.
func (c *movementComputer) handleCollision(e world.Entity) (move mgl64.Vec3, velocity mgl64.Vec3) {
// TODO: Implement collision with other entities.
velocity = e.Velocity()
deltaX, deltaY, deltaZ := velocity[0], velocity[1], velocity[2]
// Entities only ever have a single bounding box.
entityAABB := e.AABB().Translate(e.Position())
blocks := blockAABBsAround(e, entityAABB.Extend(velocity))
if !mgl64.FloatEqual(deltaY, 0) {
// First we move the entity AABB on the Y axis.
for _, blockAABB := range blocks {
deltaY = entityAABB.CalculateYOffset(blockAABB, deltaY)
}
entityAABB = entityAABB.Translate(mgl64.Vec3{0, deltaY})
}
if !mgl64.FloatEqual(deltaX, 0) {
// Then on the X axis.
for _, blockAABB := range blocks {
deltaX = entityAABB.CalculateXOffset(blockAABB, deltaX)
}
entityAABB = entityAABB.Translate(mgl64.Vec3{deltaX})
}
if !mgl64.FloatEqual(deltaZ, 0) {
// And finally on the Z axis.
for _, blockAABB := range blocks {
deltaZ = entityAABB.CalculateZOffset(blockAABB, deltaZ)
}
}
if !mgl64.FloatEqual(velocity[0], 0) {
// The Y velocity of the entity is currently not 0, meaning it is moving either up or down. We can
// then assume the entity is not currently on the ground.
c.onGround = false
}
if !mgl64.FloatEqual(deltaX, velocity[0]) {
velocity[0] = 0
}
if !mgl64.FloatEqual(deltaY, velocity[1]) {
// The entity either hit the ground or hit the ceiling.
if velocity[1] < 0 {
// The entity was going down, so we can assume it is now on the ground.
c.onGround = true
}
velocity[1] = 0
}
if !mgl64.FloatEqual(deltaZ, velocity[2]) {
velocity[2] = 0
}
return mgl64.Vec3{deltaX, deltaY, deltaZ}, velocity
}
// blockAABBsAround returns all blocks around the entity passed, using the AABB passed to make a prediction of
// what blocks need to have their AABB returned.
func blockAABBsAround(e world.Entity, aabb physics.AABB) []physics.AABB {
w := e.World()
grown := aabb.Grow(0.25)
min, max := grown.Min(), grown.Max()
minX, minY, minZ := int(math.Floor(min[0])), int(math.Floor(min[1])), int(math.Floor(min[2]))
maxX, maxY, maxZ := int(math.Ceil(max[0])), int(math.Ceil(max[1])), int(math.Ceil(max[2]))
// A prediction of one AABB per block, plus an additional 2, in case
blockAABBs := make([]physics.AABB, 0, (maxX-minX)*(maxY-minY)*(maxZ-minZ)+2)
for y := minY; y <= maxY; y++ {
for x := minX; x <= maxX; x++ {
for z := minZ; z <= maxZ; z++ {
pos := world.BlockPos{x, y, z}
boxes := boxes(e.World().Block(pos), pos, w)
for _, box := range boxes {
blockAABBs = append(blockAABBs, box.Translate(mgl64.Vec3{float64(x), float64(y), float64(z)}))
}
}
}
}
return blockAABBs
}
// OnGround checks if the entity that this computer calculates is currently on the ground.
func (c *movementComputer) OnGround() bool {
return c.onGround
}
<file_sep>package wood
import "fmt"
// Wood represents a type of wood of a block. Some blocks, such as log blocks, bark blocks, wooden planks and
// others carry one of these types.
type Wood struct {
wood
}
// Oak returns oak wood material.
func Oak() Wood {
return Wood{wood(0)}
}
// Spruce returns spruce wood material.
func Spruce() Wood {
return Wood{wood(1)}
}
// Birch returns birch wood material.
func Birch() Wood {
return Wood{wood(2)}
}
// Jungle returns jungle wood material.
func Jungle() Wood {
return Wood{wood(3)}
}
// Acacia returns acacia wood material.
func Acacia() Wood {
return Wood{wood(4)}
}
// DarkOak returns dark oak wood material.
func DarkOak() Wood {
return Wood{wood(5)}
}
type wood uint8
// Uint8 returns the wood as a uint8.
func (w wood) Uint8() uint8 {
return uint8(w)
}
// Name ...
func (w wood) Name() string {
switch w {
case 0:
return "Oak"
case 1:
return "Spruce"
case 2:
return "Birch"
case 3:
return "Jungle"
case 4:
return "Acacia"
case 5:
return "Dark Oak"
}
panic("unknown wood type")
}
// FromString ...
func (w wood) FromString(s string) (interface{}, error) {
switch s {
case "oak":
return Wood{wood(0)}, nil
case "spruce":
return Wood{wood(1)}, nil
case "birch":
return Wood{wood(2)}, nil
case "jungle":
return Wood{wood(3)}, nil
case "acacia":
return Wood{wood(4)}, nil
case "dark_oak":
return Wood{wood(5)}, nil
}
return nil, fmt.Errorf("unexpected wood type '%v', expecting one of 'oak', 'spruce', 'birch', 'jungle', 'acacia' or 'dark_oak'", s)
}
// String ...
func (w wood) String() string {
switch w {
case 0:
return "oak"
case 1:
return "spruce"
case 2:
return "birch"
case 3:
return "jungle"
case 4:
return "acacia"
case 5:
return "dark_oak"
}
panic("unknown wood type")
}
<file_sep>package action
// Action represents an action that may be performed by an entity. Typically, these actions are sent to
// viewers in a world so that they can see these actions.
type Action interface {
__()
}
// SwingArm makes an entity or player swing its arm.
type SwingArm struct{ action }
// Hurt makes an entity display the animation for being hurt. The entity will be shown as red for a short
// duration.
type Hurt struct{ action }
// Death makes an entity display the death animation. After this animation, the entity disappears from viewers
// watching it.
type Death struct{ action }
// PickedUp makes an item get picked up by a collector. After this animation, the item disappears from viewers
// watching it.
type PickedUp struct {
// Collector is the entity that collected the item.
Collector interface{}
action
}
// action implements the Action interface. Structures in this package may embed it to gets its functionality
// out of the box.
type action struct{}
func (action) __() {}
<file_sep>package block
import "github.com/df-mc/dragonfly/dragonfly/world"
// Light is an invisible block that can produce any light level.
type Light struct {
noNBT
// Level is the light level that the light block produces. It is a number from 0-15, where 15 is the
// brightest and 0 is no light at all.
Level int
}
// ReplaceableBy ...
func (l Light) ReplaceableBy(world.Block) bool {
return true
}
// EncodeItem ...
func (l Light) EncodeItem() (id int32, meta int16) {
return -215, int16(l.Level)
}
// LightEmissionLevel ...
func (l Light) LightEmissionLevel() uint8 {
return uint8(l.Level)
}
// LightDiffusionLevel ...
func (l Light) LightDiffusionLevel() uint8 {
return 0
}
// EncodeBlock ...
func (l Light) EncodeBlock() (name string, properties map[string]interface{}) {
return "minecraft:light_block", map[string]interface{}{"block_light_level": int32(l.Level)}
}
// Hash ...
func (l Light) Hash() uint64 {
return hashLight | (uint64(l.Level) << 32)
}
// allLight returns all possible light blocks.
func allLight() []world.Block {
m := make([]world.Block, 0, 16)
for i := 0; i < 16; i++ {
m = append(m, Light{Level: i})
}
return m
}
<file_sep>package block
// Bedrock is a block that is indestructible in survival.
type Bedrock struct {
noNBT
// InfiniteBurning specifies if the bedrock block is set aflame and will burn forever. This is the case
// for bedrock found under end crystals on top of the end pillars.
InfiniteBurning bool
}
// EncodeItem ...
func (Bedrock) EncodeItem() (id int32, meta int16) {
return 7, 0
}
// EncodeBlock ...
func (b Bedrock) EncodeBlock() (name string, properties map[string]interface{}) {
//noinspection SpellCheckingInspection
return "minecraft:bedrock", map[string]interface{}{"infiniburn_bit": b.InfiniteBurning}
}
// Hash ...
func (b Bedrock) Hash() uint64 {
return hashBedrock | (uint64(boolByte(b.InfiniteBurning)) << 32)
}
<file_sep>package effect
import (
"github.com/df-mc/dragonfly/dragonfly/entity"
"image/color"
"time"
)
// JumpBoost is a lasting effect that causes the affected entity to be able to jump much higher, depending on
// the level of the effect.
type JumpBoost struct {
lastingEffect
}
// WithDuration ...
func (j JumpBoost) WithDuration(d time.Duration) entity.Effect {
return JumpBoost{j.withDuration(d)}
}
// RGBA ...
func (JumpBoost) RGBA() color.RGBA {
return color.RGBA{R: 0x22, G: 0xff, B: 0x4c, A: 0xff}
}
<file_sep>package sound
import (
"github.com/df-mc/dragonfly/dragonfly/world"
"github.com/go-gl/mathgl/mgl64"
)
// BlockPlace is a sound sent when a block is placed.
type BlockPlace struct {
// Block is the block which is placed, for which a sound should be played. The sound played depends on
// the block type.
Block world.Block
sound
}
// BlockBreaking is a sound sent continuously while a player is breaking a block.
type BlockBreaking struct {
// Block is the block which is being broken, for which a sound should be played. The sound played depends
// on the block type.
Block world.Block
sound
}
// Fizz is a sound sent when a lava block and a water block interact with each other in a way that one of
// them turns into a solid block.
type Fizz struct{ sound }
// ChestOpen is played when a chest is opened.
type ChestOpen struct{ sound }
// ChestClose is played when a chest is closed.
type ChestClose struct{ sound }
// Deny is a sound played when a block is placed or broken above a 'Deny' block from Education edition.
type Deny struct{ sound }
// sound implements the world.Sound interface.
type sound struct{}
// Play ...
func (sound) Play(*world.World, mgl64.Vec3) {}
<file_sep>package effect
import (
"github.com/df-mc/dragonfly/dragonfly/entity"
"github.com/df-mc/dragonfly/dragonfly/entity/damage"
"image/color"
"time"
)
// Wither is a lasting effect that causes an entity to take continuous damage that is capable of killing an
// entity.
type Wither struct {
lastingEffect
}
// Apply ...
func (w Wither) Apply(e entity.Living) {
interval := 80 >> w.Lvl
if tickDuration(w.Dur)%interval == 0 {
e.Hurt(1, damage.SourceWitherEffect{})
}
}
// WithDuration ...
func (w Wither) WithDuration(d time.Duration) entity.Effect {
return Wither{w.withDuration(d)}
}
// RGBA ...
func (Wither) RGBA() color.RGBA {
return color.RGBA{R: 0x35, G: 0x2a, B: 0x27, A: 0xff}
}
<file_sep>package session
import (
"github.com/df-mc/dragonfly/dragonfly/item"
"github.com/df-mc/dragonfly/dragonfly/player/form"
"github.com/df-mc/dragonfly/dragonfly/player/skin"
"github.com/df-mc/dragonfly/dragonfly/world"
"github.com/df-mc/dragonfly/dragonfly/world/gamemode"
"github.com/go-gl/mathgl/mgl64"
"github.com/google/uuid"
)
// Controllable represents an entity that may be controlled by a Session. Generally, a Controllable is
// implemented in the form of a Player.
// Methods in Controllable will be added as Session needs them in order to handle packets.
type Controllable interface {
world.Entity
item.Carrier
form.Submitter
Move(deltaPos mgl64.Vec3)
Speed() float64
EyeHeight() float64
Rotate(deltaYaw, deltaPitch float64)
Chat(msg ...interface{})
ExecuteCommand(commandLine string)
GameMode() gamemode.GameMode
SetGameMode(mode gamemode.GameMode)
UseItem()
UseItemOnBlock(pos world.BlockPos, face world.Face, clickPos mgl64.Vec3)
UseItemOnEntity(e world.Entity)
BreakBlock(pos world.BlockPos)
AttackEntity(e world.Entity)
Respawn()
StartSneaking()
Sneaking() bool
StopSneaking()
StartSprinting()
Sprinting() bool
StopSprinting()
StartSwimming()
Swimming() bool
StopSwimming()
StartBreaking(pos world.BlockPos)
ContinueBreaking(face world.Face)
FinishBreaking()
AbortBreaking()
Exhaust(points float64)
// Name returns the display name of the controllable. This name is shown in-game to other viewers of the
// world.
Name() string
// UUID returns the UUID of the controllable. It must be unique for all controllable entities present in
// the server.
UUID() uuid.UUID
// XUID returns the XBOX Live User ID of the controllable. Every controllable must have one of these, as
// they must be connected to an XBOX Live account.
XUID() string
// Skin returns the skin of the controllable. Each controllable must have a skin, as it defines how the
// entity looks in the world.
Skin() skin.Skin
}
<file_sep>package world
import "fmt"
// Face represents the face of a block or entity.
type Face int
// FromString returns a Face by a string.
func (f Face) FromString(s string) (interface{}, error) {
switch s {
case "down":
return FaceDown, nil
case "up":
return FaceUp, nil
case "north":
return FaceNorth, nil
case "south":
return FaceSouth, nil
case "west":
return FaceWest, nil
case "east":
return FaceEast, nil
}
return nil, fmt.Errorf("unexpected facing '%v', expecting one of 'down', 'up', 'north', 'south', 'west' or 'east'", s)
}
const (
// FaceDown represents the bottom face of a block.
FaceDown Face = iota
// FaceUp represents the top face of a block.
FaceUp
// FaceNorth represents the north face of a block.
FaceNorth
// FaceSouth represents the south face of a block.
FaceSouth
// FaceWest represents the west face of the block.
FaceWest
// FaceEast represents the east face of the block.
FaceEast
)
// Opposite returns the opposite face. FaceDown will return up, north will return south and west will return east,
// and vice versa.
func (f Face) Opposite() Face {
switch f {
default:
return FaceUp
case FaceUp:
return FaceDown
case FaceNorth:
return FaceSouth
case FaceSouth:
return FaceNorth
case FaceWest:
return FaceEast
case FaceEast:
return FaceWest
}
}
// Axis returns the axis the face is facing. FaceEast and west correspond to the x axis, north and south to the z
// axis and up and down to the y axis.
func (f Face) Axis() Axis {
switch f {
default:
return Y
case FaceEast, FaceWest:
return X
case FaceNorth, FaceSouth:
return Z
}
}
<file_sep>package effect
import (
"github.com/df-mc/dragonfly/dragonfly/entity"
"github.com/df-mc/dragonfly/dragonfly/entity/damage"
"image/color"
"time"
)
// Poison is a lasting effect that causes the affected entity to lose health gradually. Poison cannot kill,
// unlike FatalPoison.
type Poison struct {
lastingEffect
}
// Apply ...
func (p Poison) Apply(e entity.Living) {
interval := 50 >> p.Lvl
if tickDuration(p.Dur)%interval == 0 {
e.Hurt(1, damage.SourcePoisonEffect{})
}
}
// WithDuration ...
func (p Poison) WithDuration(d time.Duration) entity.Effect {
return Poison{p.withDuration(d)}
}
// RGBA ...
func (p Poison) RGBA() color.RGBA {
return color.RGBA{R: 0x4e, G: 0x93, B: 0x31, A: 0xff}
}
<file_sep>package effect
import (
"github.com/df-mc/dragonfly/dragonfly/entity"
"github.com/df-mc/dragonfly/dragonfly/entity/damage"
"image/color"
"time"
)
// Resistance is a lasting effect that reduces the damage taken from any sources except for void damage or
// custom damage.
type Resistance struct {
lastingEffect
}
// Multiplier returns a damage multiplier for the damage source passed.
func (r Resistance) Multiplier(e damage.Source) float64 {
switch e.(type) {
case damage.SourceVoid, damage.SourceStarvation, damage.SourceCustom:
return 1
}
v := 1 - 0.2*float64(r.Lvl)
if v <= 0 {
v = 0
}
return v
}
// WithDuration ...
func (r Resistance) WithDuration(d time.Duration) entity.Effect {
return Resistance{r.withDuration(d)}
}
// RGBA ...
func (Resistance) RGBA() color.RGBA {
return color.RGBA{R: 0x99, G: 0x45, B: 0x3a, A: 0xff}
}
<file_sep>package block
import (
"github.com/df-mc/dragonfly/dragonfly/item"
"github.com/df-mc/dragonfly/dragonfly/item/tool"
)
// GoldBlock is a precious metal block crafted from 9 gold ingots.
type GoldBlock struct{ noNBT }
// BreakInfo ...
func (g GoldBlock) BreakInfo() BreakInfo {
return BreakInfo{
Hardness: 5,
Harvestable: func(t tool.Tool) bool {
return t.ToolType() == tool.TypePickaxe && t.HarvestLevel() >= tool.TierIron.HarvestLevel
},
Effective: pickaxeEffective,
Drops: simpleDrops(item.NewStack(g, 1)),
}
}
// EncodeItem ...
func (g GoldBlock) EncodeItem() (id int32, meta int16) {
return 41, 0
}
// EncodeBlock ...
func (g GoldBlock) EncodeBlock() (name string, properties map[string]interface{}) {
return "minecraft:gold_block", nil
}
// Hash ...
func (GoldBlock) Hash() uint64 {
return hashGoldBlock
}
<file_sep>package block
import "github.com/df-mc/dragonfly/dragonfly/item"
// Cobblestone is a common block, obtained from mining stone.
type Cobblestone struct {
noNBT
// Mossy specifies if the cobblestone is mossy. This variant of cobblestone is typically found in
// dungeons or in small clusters in the giant tree taiga biome.
Mossy bool
}
// BreakInfo ...
func (c Cobblestone) BreakInfo() BreakInfo {
return BreakInfo{
Hardness: 2,
Harvestable: pickaxeHarvestable,
Effective: pickaxeEffective,
Drops: simpleDrops(item.NewStack(c, 1)),
}
}
// EncodeItem ...
func (c Cobblestone) EncodeItem() (id int32, meta int16) {
if c.Mossy {
return 48, 0
}
return 4, 0
}
// EncodeBlock ...
func (c Cobblestone) EncodeBlock() (name string, properties map[string]interface{}) {
if c.Mossy {
return "minecraft:mossy_cobblestone", nil
}
return "minecraft:cobblestone", nil
}
// Hash ...
func (c Cobblestone) Hash() uint64 {
return hashCobblestone | (uint64(boolByte(c.Mossy)) << 32)
}
<file_sep>package block
import (
"github.com/df-mc/dragonfly/dragonfly/item"
"github.com/df-mc/dragonfly/dragonfly/world"
"math/rand"
)
// Grass blocks generate abundantly across the surface of the world.
type Grass struct {
noNBT
// Path specifies if the grass was made into a path or not. If true, the block will have only 15/16th of
// the height of a full block.
Path bool
}
// NeighbourUpdateTick handles the turning from grass path into dirt if a block is placed on top of it.
func (g Grass) NeighbourUpdateTick(pos, _ world.BlockPos, w *world.World) {
if !g.Path {
return
}
if _, air := w.Block(pos.Add(world.BlockPos{0, 1})).(Air); !air {
// Technically vanilla doesn't always turn grass paths into dirt when a block is placed above it,
// for example torches, but the logic doesn't make sense.
w.SetBlock(pos, Dirt{})
}
}
// RandomTick handles the ticking of grass, which may or may not result in the spreading of grass onto dirt.
func (g Grass) RandomTick(pos world.BlockPos, w *world.World, r *rand.Rand) {
if g.Path {
// Don't spread grass paths.
return
}
aboveLight := w.Light(pos.Add(world.BlockPos{0, 1}))
if aboveLight < 4 {
// The light above the block is too low: The grass turns to dirt.
w.SetBlock(pos, Dirt{})
return
}
if aboveLight < 9 {
// Don't attempt to spread if the light level is lower than 9.
return
}
// Four attempts to spread to another block.
for i := 0; i < 4; i++ {
spreadPos := pos.Add(world.BlockPos{r.Intn(3) - 1, r.Intn(5) - 3, r.Intn(3) - 1})
b := w.Block(spreadPos)
if dirt, ok := b.(Dirt); !ok || dirt.Coarse {
continue
}
// Don't spread grass to places where dirt is exposed to hardly any light.
if w.Light(spreadPos.Add(world.BlockPos{0, 1})) < 4 {
continue
}
w.SetBlock(spreadPos, g)
}
}
// BreakInfo ...
func (g Grass) BreakInfo() BreakInfo {
return BreakInfo{
Hardness: 0.6,
Harvestable: alwaysHarvestable,
Effective: shovelEffective,
Drops: simpleDrops(item.NewStack(Dirt{}, 1)),
}
}
// EncodeItem ...
func (g Grass) EncodeItem() (id int32, meta int16) {
if g.Path {
return 198, 0
}
return 2, 0
}
// EncodeBlock ...
func (g Grass) EncodeBlock() (name string, properties map[string]interface{}) {
if g.Path {
return "minecraft:grass_path", nil
}
return "minecraft:grass", nil
}
// Hash ...
func (g Grass) Hash() uint64 {
return hashGrass | (uint64(boolByte(g.Path)) << 32)
}
<file_sep>package block
import (
"github.com/df-mc/dragonfly/dragonfly/block/wood"
"github.com/df-mc/dragonfly/dragonfly/item"
"github.com/df-mc/dragonfly/dragonfly/world"
"github.com/go-gl/mathgl/mgl64"
)
// Log is a naturally occurring block found in trees, primarily used to create planks. It comes in six
// species: oak, spruce, birch, jungle, acacia, and dark oak.
// Stripped log is a variant obtained by using an axe on a log.
type Log struct {
noNBT
// Wood is the type of wood of the log. This field must have one of the values found in the material
// package.
Wood wood.Wood
// Stripped specifies if the log is stripped or not.
Stripped bool
// Axis is the axis which the log block faces.
Axis world.Axis
}
// UseOnBlock handles the rotational placing of logs.
func (l Log) UseOnBlock(pos world.BlockPos, face world.Face, _ mgl64.Vec3, w *world.World, user item.User, ctx *item.UseContext) (used bool) {
pos, face, used = firstReplaceable(w, pos, face, l)
if !used {
return
}
l.Axis = face.Axis()
place(w, pos, l, user, ctx)
return placed(ctx)
}
// BreakInfo ...
func (l Log) BreakInfo() BreakInfo {
return BreakInfo{
Hardness: 2,
Harvestable: alwaysHarvestable,
Effective: axeEffective,
Drops: simpleDrops(item.NewStack(l, 1)),
}
}
// EncodeItem ...
func (l Log) EncodeItem() (id int32, meta int16) {
switch l.Wood {
case wood.Oak():
if l.Stripped {
return -10, 0
}
return 17, 0
case wood.Spruce():
if l.Stripped {
return -5, 0
}
return 17, 1
case wood.Birch():
if l.Stripped {
return -6, 0
}
return 17, 2
case wood.Jungle():
if l.Stripped {
return -7, 0
}
return 17, 3
case wood.Acacia():
if l.Stripped {
return -8, 0
}
return 162, 0
case wood.DarkOak():
if l.Stripped {
return -9, 0
}
return 162, 1
}
panic("invalid wood type")
}
// EncodeBlock ...
func (l Log) EncodeBlock() (name string, properties map[string]interface{}) {
if !l.Stripped {
switch l.Wood {
case wood.Oak(), wood.Spruce(), wood.Birch(), wood.Jungle():
return "minecraft:log", map[string]interface{}{"pillar_axis": l.Axis.String(), "old_log_type": l.Wood.String()}
case wood.Acacia(), wood.DarkOak():
return "minecraft:log2", map[string]interface{}{"pillar_axis": l.Axis.String(), "new_log_type": l.Wood.String()}
}
}
switch l.Wood {
case wood.Oak():
return "minecraft:stripped_oak_log", map[string]interface{}{"pillar_axis": l.Axis.String()}
case wood.Spruce():
return "minecraft:stripped_spruce_log", map[string]interface{}{"pillar_axis": l.Axis.String()}
case wood.Birch():
return "minecraft:stripped_birch_log", map[string]interface{}{"pillar_axis": l.Axis.String()}
case wood.Jungle():
return "minecraft:stripped_jungle_log", map[string]interface{}{"pillar_axis": l.Axis.String()}
case wood.Acacia():
return "minecraft:stripped_acacia_log", map[string]interface{}{"pillar_axis": l.Axis.String()}
case wood.DarkOak():
return "minecraft:stripped_dark_oak_log", map[string]interface{}{"pillar_axis": l.Axis.String()}
}
panic("invalid wood type")
}
// Hash ...
func (l Log) Hash() uint64 {
return hashLog | (uint64(boolByte(l.Stripped)) << 32) | (uint64(l.Axis) << 33) | (uint64(l.Wood.Uint8()) << 35)
}
// allLogs returns a list of all possible log states.
func allLogs() (logs []world.Block) {
f := func(axis world.Axis, stripped bool) {
logs = append(logs, Log{Axis: axis, Stripped: stripped, Wood: wood.Oak()})
logs = append(logs, Log{Axis: axis, Stripped: stripped, Wood: wood.Spruce()})
logs = append(logs, Log{Axis: axis, Stripped: stripped, Wood: wood.Birch()})
logs = append(logs, Log{Axis: axis, Stripped: stripped, Wood: wood.Jungle()})
logs = append(logs, Log{Axis: axis, Stripped: stripped, Wood: wood.Acacia()})
logs = append(logs, Log{Axis: axis, Stripped: stripped, Wood: wood.DarkOak()})
}
for axis := world.Axis(0); axis < 3; axis++ {
f(axis, true)
f(axis, false)
}
return
}
<file_sep>package session
import (
"fmt"
"github.com/df-mc/dragonfly/dragonfly/item"
"github.com/df-mc/dragonfly/dragonfly/world/gamemode"
"github.com/sandertv/gophertunnel/minecraft/protocol"
"github.com/sandertv/gophertunnel/minecraft/protocol/packet"
"math"
"time"
)
// ItemStackRequestHandler handles the ItemStackRequest packet. It handles the actions done within the
// inventory.
type ItemStackRequestHandler struct {
currentRequest int32
changes map[byte]map[byte]protocol.StackResponseSlotInfo
responseChanges map[int32]map[byte]map[byte]responseChange
current time.Time
}
// responseChange represents a change in a specific item stack response. It holds the timestamp of the
// response which is used to get rid of changes that the client will have received.
type responseChange struct {
id int32
timestamp time.Time
}
// Handle ...
func (h *ItemStackRequestHandler) Handle(p packet.Packet, s *Session) error {
pk := p.(*packet.ItemStackRequest)
h.current = time.Now()
s.inTransaction.Store(true)
defer s.inTransaction.Store(false)
for _, req := range pk.Requests {
h.currentRequest = req.RequestID
if err := h.handleRequest(req, s); err != nil {
// Item stacks being out of sync isn't uncommon, so don't error. Just debug the error and let the
// revert do its work.
s.log.Debugf("error resolving item stack request: %v", err)
return nil
}
}
return nil
}
// handleRequest resolves a single item stack request from the client.
func (h *ItemStackRequestHandler) handleRequest(req protocol.ItemStackRequest, s *Session) (err error) {
defer func() {
if err != nil {
h.reject(req.RequestID, s)
return
}
h.resolve(req.RequestID, s)
}()
for _, action := range req.Actions {
switch a := action.(type) {
case *protocol.TakeStackRequestAction:
err = h.handleTake(a, s)
case *protocol.PlaceStackRequestAction:
err = h.handlePlace(a, s)
case *protocol.SwapStackRequestAction:
err = h.handleSwap(a, s)
case *protocol.DestroyStackRequestAction:
err = h.handleDestroy(a, s)
case *protocol.CraftCreativeStackRequestAction:
err = h.handleCreativeCraft(a, s)
case *protocol.CraftResultsDeprecatedStackRequestAction:
// Don't do anything with this.
default:
return fmt.Errorf("unhandled stack request action %#v", action)
}
if err != nil {
err = fmt.Errorf("%T: %w", action, err)
return
}
}
return
}
// handleTake handles a Take stack request action.
func (h *ItemStackRequestHandler) handleTake(a *protocol.TakeStackRequestAction, s *Session) error {
return h.handleTransfer(a.Source, a.Destination, a.Count, s)
}
// handlePlace handles a Place stack request action.
func (h *ItemStackRequestHandler) handlePlace(a *protocol.PlaceStackRequestAction, s *Session) error {
return h.handleTransfer(a.Source, a.Destination, a.Count, s)
}
// handleSwap handles a Swap stack request action.
func (h *ItemStackRequestHandler) handleSwap(a *protocol.SwapStackRequestAction, s *Session) error {
if err := h.verifySlots(s, a.Source, a.Destination); err != nil {
return fmt.Errorf("slot out of sync: %w", err)
}
i, _ := h.itemInSlot(a.Source, s)
dest, _ := h.itemInSlot(a.Destination, s)
h.setItemInSlot(a.Source, dest, s)
h.setItemInSlot(a.Destination, i, s)
return nil
}
// handleCreativeCraft handles the CreativeCraft request action.
func (h *ItemStackRequestHandler) handleCreativeCraft(a *protocol.CraftCreativeStackRequestAction, s *Session) error {
if (s.c.GameMode() != gamemode.Creative{} && s.c.GameMode() != gamemode.Spectator{}) {
return fmt.Errorf("can only craft creative items in gamemode creative/spectator")
}
index := a.CreativeItemNetworkID - 1
if int(index) >= len(item.CreativeItems()) {
return fmt.Errorf("creative item with network ID %v does not exist", index)
}
it := item.CreativeItems()[index]
it = it.Grow(it.MaxCount() - 1)
h.setItemInSlot(protocol.StackRequestSlotInfo{
ContainerID: containerCreativeOutput,
Slot: 50,
StackNetworkID: item_id(it),
}, it, s)
return nil
}
// handleDestroy handles the destroying of an item by moving it into the creative inventory.
func (h *ItemStackRequestHandler) handleDestroy(a *protocol.DestroyStackRequestAction, s *Session) error {
if (s.c.GameMode() != gamemode.Creative{} && s.c.GameMode() != gamemode.Spectator{}) {
return fmt.Errorf("can only destroy items in gamemode creative/spectator")
}
if err := h.verifySlot(a.Source, s); err != nil {
return fmt.Errorf("source slot out of sync: %w", err)
}
i, _ := h.itemInSlot(a.Source, s)
if i.Count() < int(a.Count) {
return fmt.Errorf("client attempted to destroy %v items, but only %v present", a.Count, i.Count())
}
h.setItemInSlot(a.Source, i.Grow(-int(a.Count)), s)
return nil
}
// handleTransfer handles the transferring of x count from a source slot to a destination slot.
func (h *ItemStackRequestHandler) handleTransfer(from, to protocol.StackRequestSlotInfo, count byte, s *Session) error {
if err := h.verifySlots(s, from, to); err != nil {
return fmt.Errorf("source slot out of sync: %w", err)
}
i, _ := h.itemInSlot(from, s)
dest, _ := h.itemInSlot(to, s)
if !i.Comparable(dest) {
return fmt.Errorf("client tried transferring %v to %v, but the stacks are incomparable", i, dest)
}
if i.Count() < int(count) {
return fmt.Errorf("client tried subtracting %v from item count, but there are only %v", count, i.Count())
}
if (dest.Count()+int(count) > dest.MaxCount()) && !dest.Empty() {
return fmt.Errorf("client tried adding %v to item count %v, but max is %v", count, dest.Count(), dest.MaxCount())
}
if dest.Empty() {
dest = i.Grow(-math.MaxInt32)
}
h.setItemInSlot(from, i.Grow(-int(count)), s)
h.setItemInSlot(to, dest.Grow(int(count)), s)
return nil
}
// verifySlots verifies a list of slots passed.
func (h *ItemStackRequestHandler) verifySlots(s *Session, slots ...protocol.StackRequestSlotInfo) error {
for _, slot := range slots {
if err := h.verifySlot(slot, s); err != nil {
return err
}
}
return nil
}
// verifySlot checks if the slot passed by the client is the same as that expected by the server.
func (h *ItemStackRequestHandler) verifySlot(slot protocol.StackRequestSlotInfo, s *Session) error {
h.tryAcknowledgeChanges(slot)
if len(h.responseChanges) > 256 {
return fmt.Errorf("too many unacknowledged request slot changes")
}
i, err := h.itemInSlot(slot, s)
if err != nil {
return err
}
clientID, err := h.resolveID(slot)
if err != nil {
return err
}
// The client seems to send negative stack network IDs for predictions, which we can ignore. We'll simply
// override this network ID later.
if id := item_id(i); id != clientID {
return fmt.Errorf("stack ID mismatch: client expected %v, but server had %v", clientID, id)
}
return nil
}
// resolveID resolves the stack network ID in the slot passed. If it is negative, it points to an earlier
// request, in which case it will look it up in the changes of an earlier response to a request to find the
// actual stack network ID in the slot. If it is positive, the ID will be returned again.
func (h *ItemStackRequestHandler) resolveID(slot protocol.StackRequestSlotInfo) (int32, error) {
if slot.StackNetworkID >= 0 {
return slot.StackNetworkID, nil
}
containerChanges, ok := h.responseChanges[slot.StackNetworkID]
if !ok {
return 0, fmt.Errorf("slot pointed to stack request %v, but request could not be found", slot.StackNetworkID)
}
changes, ok := containerChanges[slot.ContainerID]
if !ok {
return 0, fmt.Errorf("slot pointed to stack request %v with container %v, but that container was not changed in the request", slot.StackNetworkID, slot.ContainerID)
}
actual, ok := changes[slot.Slot]
if !ok {
return 0, fmt.Errorf("slot pointed to stack request %v with container %v and slot %v, but that slot was not changed in the request", slot.StackNetworkID, slot.ContainerID, slot.Slot)
}
return actual.id, nil
}
// tryAcknowledgeChanges iterates through all cached response changes and checks if the stack request slot
// info passed from the client has the right stack network ID in any of the stored slots. If this is the case,
// that entry is removed, so that the maps are cleaned up eventually.
func (h *ItemStackRequestHandler) tryAcknowledgeChanges(slot protocol.StackRequestSlotInfo) {
for requestID, containerChanges := range h.responseChanges {
for containerID, changes := range containerChanges {
for slotIndex, val := range changes {
if (slot.Slot == slotIndex && slot.StackNetworkID >= 0 && slot.ContainerID == containerID) || h.current.Sub(val.timestamp) > time.Second*5 {
delete(changes, slotIndex)
}
}
if len(changes) == 0 {
delete(containerChanges, containerID)
}
}
if len(containerChanges) == 0 {
delete(h.responseChanges, requestID)
}
}
}
// itemInSlot looks for the item in the slot as indicated by the slot info passed.
func (h *ItemStackRequestHandler) itemInSlot(slot protocol.StackRequestSlotInfo, s *Session) (item.Stack, error) {
inventory, ok := s.invByID(int32(slot.ContainerID))
if !ok {
return item.Stack{}, fmt.Errorf("unable to find container with ID %v", slot.ContainerID)
}
i, err := inventory.Item(int(slot.Slot))
if err != nil {
return i, err
}
return i, nil
}
// setItemInSlot sets an item stack in the slot of a container present in the slot info.
func (h *ItemStackRequestHandler) setItemInSlot(slot protocol.StackRequestSlotInfo, i item.Stack, s *Session) {
inventory, _ := s.invByID(int32(slot.ContainerID))
_ = inventory.SetItem(int(slot.Slot), i)
if h.changes[slot.ContainerID] == nil {
h.changes[slot.ContainerID] = map[byte]protocol.StackResponseSlotInfo{}
}
respSlot := protocol.StackResponseSlotInfo{
Slot: slot.Slot,
HotbarSlot: slot.Slot,
Count: byte(i.Count()),
StackNetworkID: item_id(i),
}
h.changes[slot.ContainerID][slot.Slot] = respSlot
if h.responseChanges[h.currentRequest] == nil {
h.responseChanges[h.currentRequest] = map[byte]map[byte]responseChange{}
}
if h.responseChanges[h.currentRequest][slot.ContainerID] == nil {
h.responseChanges[h.currentRequest][slot.ContainerID] = map[byte]responseChange{}
}
h.responseChanges[h.currentRequest][slot.ContainerID][slot.Slot] = responseChange{
id: respSlot.StackNetworkID,
timestamp: h.current,
}
}
// resolve resolves the request with the ID passed.
func (h *ItemStackRequestHandler) resolve(id int32, s *Session) {
info := make([]protocol.StackResponseContainerInfo, 0, len(h.changes))
for container, slotInfo := range h.changes {
slots := make([]protocol.StackResponseSlotInfo, 0, len(slotInfo))
for _, slot := range slotInfo {
slots = append(slots, slot)
}
info = append(info, protocol.StackResponseContainerInfo{
ContainerID: container,
SlotInfo: slots,
})
}
s.writePacket(&packet.ItemStackResponse{Responses: []protocol.ItemStackResponse{{
Success: true,
RequestID: id,
ContainerInfo: info,
}}})
h.changes = map[byte]map[byte]protocol.StackResponseSlotInfo{}
}
// reject rejects the item stack request sent by the client so that it is reverted client-side.
func (h *ItemStackRequestHandler) reject(id int32, s *Session) {
s.writePacket(&packet.ItemStackResponse{
Responses: []protocol.ItemStackResponse{{
Success: false,
RequestID: id,
}},
})
h.changes = map[byte]map[byte]protocol.StackResponseSlotInfo{}
}
<file_sep>package particle
import (
"github.com/df-mc/dragonfly/dragonfly/world"
"github.com/go-gl/mathgl/mgl64"
)
// BlockBreak is a particle sent when a block is broken. It represents a bunch of particles that are textured
// like the block that the particle holds.
type BlockBreak struct {
// Block is the block of which particles should be shown. The particles will change depending on what
// block is held.
Block world.Block
}
// PunchBlock is a particle shown when a player is punching a block. It shows particles of a specific block
// type at a particular face of a block.
type PunchBlock struct {
// Block is the block of which particles should be shown. The particles will change depending on what
// block is punched.
Block world.Block
// Face is the face of the block that was punched. It is here that the particles will be shown.
Face world.Face
}
// BlockForceField is a particle that shows up as a block that turns invisible from an opaque black colour.
type BlockForceField struct{}
// Spawn ...
func (PunchBlock) Spawn(*world.World, mgl64.Vec3) {}
// Spawn ...
func (BlockBreak) Spawn(*world.World, mgl64.Vec3) {}
// Spawn ...
func (BlockForceField) Spawn(*world.World, mgl64.Vec3) {}
<file_sep>package effect
import (
"github.com/df-mc/dragonfly/dragonfly/entity"
"image/color"
"time"
)
// Haste is a lasting effect that increases the mining speed of a player by 20% for each level of the effect.
type Haste struct {
lastingEffect
}
// Multiplier returns the mining speed multiplier from this effect.
func (h Haste) Multiplier() float64 {
v := 1 - float64(h.Lvl)*0.1
if v < 0 {
v = 0
}
return v
}
// WithDuration ...
func (h Haste) WithDuration(d time.Duration) entity.Effect {
return Haste{h.withDuration(d)}
}
// RGBA ...
func (Haste) RGBA() color.RGBA {
return color.RGBA{R: 0xd9, G: 0xc0, B: 0x43, A: 0xff}
}
<file_sep>package session
import (
"bytes"
"errors"
"fmt"
"github.com/df-mc/dragonfly/dragonfly/item/inventory"
"github.com/df-mc/dragonfly/dragonfly/player/chat"
"github.com/df-mc/dragonfly/dragonfly/player/form"
"github.com/df-mc/dragonfly/dragonfly/world"
"github.com/go-gl/mathgl/mgl64"
"github.com/sandertv/gophertunnel/minecraft"
"github.com/sandertv/gophertunnel/minecraft/protocol"
"github.com/sandertv/gophertunnel/minecraft/protocol/packet"
"github.com/sandertv/gophertunnel/minecraft/text"
"github.com/sirupsen/logrus"
"go.uber.org/atomic"
"sync"
"time"
)
// Session handles incoming packets from connections and sends outgoing packets by providing a thin layer
// of abstraction over direct packets. A Session basically 'controls' an entity.
type Session struct {
log *logrus.Logger
c Controllable
conn *minecraft.Conn
handlers map[uint32]packetHandler
// onStop is called when the session is stopped. The controllable passed is the controllable that the
// session controls.
onStop func(controllable Controllable)
scoreboardObj atomic.String
chunkBuf *bytes.Buffer
chunkLoader *world.Loader
chunkRadius, maxChunkRadius int32
teleportMu sync.Mutex
teleportPos *mgl64.Vec3
// currentEntityRuntimeID holds the runtime ID assigned to the last entity. It is incremented for every
// entity spawned to the session.
currentEntityRuntimeID atomic.Uint64
entityMutex sync.RWMutex
// entityRuntimeIDs holds a list of all runtime IDs of entities spawned to the session.
entityRuntimeIDs map[world.Entity]uint64
entities map[uint64]world.Entity
// heldSlot is the slot in the inventory that the controllable is holding.
heldSlot *atomic.Uint32
inv, offHand, ui *inventory.Inventory
armour *inventory.Armour
openedWindowID atomic.Uint32
inTransaction, containerOpened atomic.Bool
openedWindow, openedPos atomic.Value
swingingArm atomic.Bool
blobMu sync.Mutex
blobs map[uint64][]byte
openChunkTransactions []map[uint64]struct{}
invOpened bool
}
// Nop represents a no-operation session. It does not do anything when sending a packet to it.
var Nop = &Session{}
// session is a slice of all open sessions. It is protected by the sessionMu, which must be locked whenever
// accessing the value.
var sessions []*Session
var sessionMu sync.Mutex
// selfEntityRuntimeID is the entity runtime (or unique) ID of the controllable that the session holds.
const selfEntityRuntimeID = 1
// ErrSelfRuntimeID is an error returned during packet handling for fields that refer to the player itself and
// must therefore always be 1.
var ErrSelfRuntimeID = errors.New("invalid entity runtime ID: runtime ID for self must always be 1")
// New returns a new session using a controllable entity. The session will control this entity using the
// packets that it receives.
// New takes the connection from which to accept packets. It will start handling these packets after a call to
// Session.Start().
func New(conn *minecraft.Conn, maxChunkRadius int, log *logrus.Logger) *Session {
r := conn.ChunkRadius()
if r > maxChunkRadius {
r = maxChunkRadius
_ = conn.WritePacket(&packet.ChunkRadiusUpdated{ChunkRadius: int32(r)})
}
s := &Session{
chunkBuf: bytes.NewBuffer(make([]byte, 0, 4096)),
openChunkTransactions: make([]map[uint64]struct{}, 0, 8),
ui: inventory.New(51, nil),
handlers: map[uint32]packetHandler{},
entityRuntimeIDs: map[world.Entity]uint64{},
entities: map[uint64]world.Entity{},
blobs: map[uint64][]byte{},
chunkRadius: int32(r),
maxChunkRadius: int32(maxChunkRadius),
conn: conn,
log: log,
currentEntityRuntimeID: *atomic.NewUint64(1),
heldSlot: atomic.NewUint32(0),
}
s.openedWindow.Store(inventory.New(1, nil))
s.openedPos.Store(world.BlockPos{})
s.registerHandlers()
return s
}
// Start makes the session start handling incoming packets from the client and initialises the controllable of
// the session in the world.
// The function passed will be called when the session stops running.
func (s *Session) Start(c Controllable, w *world.World, onStop func(controllable Controllable)) {
s.onStop = onStop
s.c = c
s.entityRuntimeIDs[c] = selfEntityRuntimeID
s.entities[selfEntityRuntimeID] = c
s.chunkLoader = world.NewLoader(int(s.chunkRadius), w, s)
s.chunkLoader.Move(w.Spawn().Vec3Middle())
s.initPlayerList()
w.AddEntity(s.c)
s.c.SetGameMode(w.DefaultGameMode())
s.SendAvailableCommands()
s.SendSpeed(0.1)
go s.handlePackets()
yellow := text.Yellow()
chat.Global.Println(yellow(s.conn.IdentityData().DisplayName, "has joined the game"))
s.writePacket(&packet.CreativeContent{Items: creativeItems()})
}
// Close closes the session, which in turn closes the controllable and the connection that the session
// manages.
func (s *Session) Close() error {
s.closeCurrentContainer()
_ = s.conn.Close()
_ = s.chunkLoader.Close()
_ = s.c.Close()
yellow := text.Yellow()
chat.Global.Println(yellow(s.conn.IdentityData().DisplayName, "has left the game"))
s.c.World().RemoveEntity(s.c)
// This should always be called last due to the timing of the removal of entity runtime IDs.
s.closePlayerList()
s.entityMutex.Lock()
s.entityRuntimeIDs = map[world.Entity]uint64{}
s.entities = map[uint64]world.Entity{}
s.entityMutex.Unlock()
if s.onStop != nil {
s.onStop(s.c)
s.onStop = nil
}
return nil
}
// CloseConnection closes the underlying connection of the session so that the session ends up being closed
// eventually.
func (s *Session) CloseConnection() {
_ = s.conn.Close()
}
// Latency returns the latency of the connection.
func (s *Session) Latency() time.Duration {
return s.conn.Latency()
}
// handlePackets continuously handles incoming packets from the connection. It processes them accordingly.
// Once the connection is closed, handlePackets will return.
func (s *Session) handlePackets() {
c := make(chan struct{})
defer func() {
// If this function ends up panicking, we don't want to call s.Close() as it may cause the entire
// server to freeze without printing the actual panic message.
// Instead, we check if there is a panic to recover, and just propagate the panic if this does happen
// to be the case.
if err := recover(); err != nil {
panic(err)
}
c <- struct{}{}
_ = s.Close()
}()
go s.sendChunks(c)
for {
pk, err := s.conn.ReadPacket()
if err != nil {
return
}
if err := s.handlePacket(pk); err != nil {
// An error occurred during the handling of a packet. Print the error and stop handling any more
// packets.
s.log.Debugf("failed processing packet from %v (%v): %v\n", s.conn.RemoteAddr(), s.c.Name(), err)
return
}
}
}
// sendChunks continuously sends chunks to the player, until a value is sent to the closeChan passed.
func (s *Session) sendChunks(stop <-chan struct{}) {
const maxChunkTransactions = 8
t := time.NewTicker(time.Second / 20)
defer t.Stop()
for {
select {
case <-t.C:
if s.chunkLoader.World() != s.c.World() {
s.chunkLoader.ChangeWorld(s.c.World())
}
s.blobMu.Lock()
toLoad := maxChunkTransactions - len(s.openChunkTransactions)
s.blobMu.Unlock()
if toLoad > 4 {
toLoad = 4
}
if err := s.chunkLoader.Load(toLoad); err != nil {
// The world was closed. This should generally never happen.
s.log.Errorf("error loading chunk: %v", err)
return
}
case <-stop:
return
}
}
}
// handlePacket handles an incoming packet, processing it accordingly. If the packet had invalid data or was
// otherwise not valid in its context, an error is returned.
func (s *Session) handlePacket(pk packet.Packet) error {
handler, ok := s.handlers[pk.ID()]
if !ok {
s.log.Debugf("unhandled packet %T%v from %v\n", pk, fmt.Sprintf("%+v", pk)[1:], s.conn.RemoteAddr())
return nil
}
if handler == nil {
// A nil handler means it was explicitly unhandled.
return nil
}
if err := handler.Handle(pk, s); err != nil {
return fmt.Errorf("%T: %w", pk, err)
}
return nil
}
// registerHandlers registers all packet handlers found in the packetHandler package.
func (s *Session) registerHandlers() {
s.handlers = map[uint32]packetHandler{
packet.IDActorFall: nil,
packet.IDAnimate: nil,
packet.IDBossEvent: nil,
packet.IDClientCacheBlobStatus: &ClientCacheBlobStatusHandler{},
packet.IDCommandRequest: &CommandRequestHandler{},
packet.IDContainerClose: &ContainerCloseHandler{},
packet.IDEmote: &EmoteHandler{},
packet.IDEmoteList: nil,
packet.IDInteract: &InteractHandler{},
packet.IDInventoryTransaction: &InventoryTransactionHandler{},
packet.IDItemStackRequest: &ItemStackRequestHandler{changes: make(map[byte]map[byte]protocol.StackResponseSlotInfo), responseChanges: map[int32]map[byte]map[byte]responseChange{}},
packet.IDLevelSoundEvent: nil,
packet.IDMobEquipment: &MobEquipmentHandler{},
packet.IDModalFormResponse: &ModalFormResponseHandler{forms: make(map[uint32]form.Form)},
packet.IDMovePlayer: nil,
packet.IDPlayerAction: &PlayerActionHandler{},
packet.IDPlayerAuthInput: &PlayerAuthInputHandler{},
packet.IDRequestChunkRadius: &RequestChunkRadiusHandler{},
packet.IDRespawn: &RespawnHandler{},
packet.IDText: &TextHandler{},
packet.IDTickSync: nil,
}
}
// writePacket writes a packet to the session's connection if it is not Nop.
func (s *Session) writePacket(pk packet.Packet) {
if s == Nop {
return
}
_ = s.conn.WritePacket(pk)
}
// initPlayerList initialises the player list of the session and sends the session itself to all other
// sessions currently open.
func (s *Session) initPlayerList() {
sessionMu.Lock()
sessions = append(sessions, s)
for _, session := range sessions {
// AddStack the player of the session to all sessions currently open, and add the players of all sessions
// currently open to the player list of the new session.
session.addToPlayerList(s)
s.addToPlayerList(session)
}
sessionMu.Unlock()
}
// closePlayerList closes the player list of the session and removes the session from the player list of all
// other sessions.
func (s *Session) closePlayerList() {
sessionMu.Lock()
n := make([]*Session, 0, len(sessions)-1)
for _, session := range sessions {
if session != s {
n = append(n, session)
}
// Remove the player of the session from the player list of all other sessions.
session.removeFromPlayerList(s)
}
sessions = n
sessionMu.Unlock()
}
<file_sep>package block
import (
"github.com/df-mc/dragonfly/dragonfly/item"
)
// Terracotta is a block formed from clay, with a hardness and blast resistance comparable to stone. For colouring it,
// take a look at StainedTerracotta.
type Terracotta struct{ noNBT }
// BreakInfo ...
func (t Terracotta) BreakInfo() BreakInfo {
return BreakInfo{
Hardness: 1.25,
Harvestable: pickaxeHarvestable,
Effective: pickaxeEffective,
Drops: simpleDrops(item.NewStack(t, 1)),
}
}
// EncodeItem ...
func (t Terracotta) EncodeItem() (id int32, meta int16) {
return 172, meta
}
// EncodeBlock ...
func (t Terracotta) EncodeBlock() (name string, properties map[string]interface{}) {
return "minecraft:hardened_clay", map[string]interface{}{}
}
// Hash ...
func (t Terracotta) Hash() uint64 {
return hashTerracotta
}
<file_sep>package block
import (
"github.com/df-mc/dragonfly/dragonfly/block/colour"
"github.com/df-mc/dragonfly/dragonfly/item"
"github.com/df-mc/dragonfly/dragonfly/world"
)
// Wool is a colourful block that can be obtained by killing/shearing sheep, or crafted using four string.
type Wool struct {
noNBT
Colour colour.Colour
}
// BreakInfo ...
func (w Wool) BreakInfo() BreakInfo {
return BreakInfo{
Hardness: 0.8,
Harvestable: alwaysHarvestable,
Effective: shearsEffective,
Drops: simpleDrops(item.NewStack(w, 1)),
}
}
// EncodeItem ...
func (w Wool) EncodeItem() (id int32, meta int16) {
return 35, int16(w.Colour.Uint8())
}
// EncodeBlock ...
func (w Wool) EncodeBlock() (name string, properties map[string]interface{}) {
return "minecraft:wool", map[string]interface{}{"color": w.Colour.String()}
}
// Hash ...
func (w Wool) Hash() uint64 {
return hashWool | (uint64(w.Colour.Uint8()) << 32)
}
// allWool returns wool blocks with all possible colours.
func allWool() []world.Block {
b := make([]world.Block, 0, 16)
for _, c := range colour.All() {
b = append(b, Wool{Colour: c})
}
return b
}
<file_sep>package physics
import (
"github.com/go-gl/mathgl/mgl64"
)
// AABB represents an Axis Aligned Bounding Box in a 3D space. It is defined as two Vec3s, of which one is the
// minimum and one is the maximum.
type AABB struct {
min, max mgl64.Vec3
}
// NewAABB creates a new axis aligned bounding box with the minimum and maximum coordinates provided.
func NewAABB(min, max mgl64.Vec3) AABB {
return AABB{min: min, max: max}
}
// Grow grows the bounding box in all directions by x and returns the new bounding box.
func (aabb AABB) Grow(x float64) AABB {
add := mgl64.Vec3{x, x, x}
return AABB{min: aabb.min.Sub(add), max: aabb.max.Add(add)}
}
// GrowVertically grows the bounding box by x on the vertical axis and returns the new bounding box.
func (aabb AABB) GrowVertically(x float64) AABB {
add := mgl64.Vec3{0, x}
return AABB{min: aabb.min.Sub(add), max: aabb.max.Add(add)}
}
// Min returns the minimum coordinate of the bounding box.
func (aabb AABB) Min() mgl64.Vec3 {
return aabb.min
}
// Max returns the maximum coordinate of the bounding box.
func (aabb AABB) Max() mgl64.Vec3 {
return aabb.max
}
// Width returns the width of the AABB.
func (aabb AABB) Width() float64 {
return aabb.max[0] - aabb.min[0]
}
// Length returns the length of the AABB.
func (aabb AABB) Length() float64 {
return aabb.max[2] - aabb.min[2]
}
// Height returns the height of the AABB.
func (aabb AABB) Height() float64 {
return aabb.max[1] - aabb.min[1]
}
// Extend expands the AABB on all axes as represented by the Vec3 passed. Negative coordinates result in an
// expansion towards the negative axis, and vice versa for positive coordinates.
func (aabb AABB) Extend(vec mgl64.Vec3) AABB {
if vec[0] < 0 {
aabb.min[0] += vec[0]
} else if vec[0] > 0 {
aabb.max[0] += vec[0]
}
if vec[1] < 0 {
aabb.min[1] += vec[1]
} else if vec[1] > 0 {
aabb.max[1] += vec[1]
}
if vec[2] < 0 {
aabb.min[2] += vec[2]
} else if vec[2] > 0 {
aabb.max[2] += vec[2]
}
return aabb
}
// ExtendTowards extends the bounding box by x in a given direction.
func (aabb AABB) ExtendTowards(d int, x float64) AABB {
switch d {
case 0:
aabb.max[1] += x
case 1:
aabb.min[1] -= x
case 2:
aabb.min[2] -= x
case 3:
aabb.max[2] += x
case 4:
aabb.min[0] -= x
case 5:
aabb.max[0] += x
}
return aabb
}
// Translate moves the entire AABB with the Vec3 given. The (minimum and maximum) x, y and z coordinates are
// moved by those in the Vec3 passed.
func (aabb AABB) Translate(vec mgl64.Vec3) AABB {
return NewAABB(aabb.min.Add(vec), aabb.max.Add(vec))
}
// IntersectsWith checks if the AABB intersects with another AABB, returning true if this is the case.
func (aabb AABB) IntersectsWith(other AABB) bool {
if other.max[0]-aabb.min[0] > 1e-5 && aabb.max[0]-other.min[0] > 1e-5 {
if other.max[1]-aabb.min[1] > 1e-5 && aabb.max[1]-other.min[1] > 1e-5 {
return other.max[2]-aabb.min[2] > 1e-5 && aabb.max[2]-other.min[2] > 1e-5
}
}
return false
}
// AnyIntersections checks if any of boxes1 have intersections with any of boxes2 and returns true if this
// happens to be the case.
func AnyIntersections(boxes []AABB, search AABB) bool {
for _, box := range boxes {
if box.IntersectsWith(search) {
return true
}
}
return false
}
// Vec3Within checks if the AABB has a Vec3 within it, returning true if it does.
func (aabb AABB) Vec3Within(vec mgl64.Vec3) bool {
if vec[0] <= aabb.min[0] || vec[0] >= aabb.max[0] {
return false
}
if vec[2] <= aabb.min[2] || vec[2] >= aabb.max[2] {
return false
}
return vec[1] > aabb.min[1] && vec[1] < aabb.max[1]
}
// CalculateXOffset calculates the offset on the X axis between two bounding boxes, returning a delta always
// smaller than or equal to deltaX if deltaX is bigger than 0, or always bigger than or equal to deltaX if it
// is smaller than 0.
func (aabb AABB) CalculateXOffset(nearby AABB, deltaX float64) float64 {
// Bail out if not within the same Y/Z plane.
if aabb.max[1] <= nearby.min[1] || aabb.min[1] >= nearby.max[1] {
return deltaX
} else if aabb.max[2] <= nearby.min[2] || aabb.min[2] >= nearby.max[2] {
return deltaX
}
if deltaX > 0 && aabb.max[0] <= nearby.min[0] {
difference := nearby.min[0] - aabb.max[0]
if difference < deltaX {
deltaX = difference
}
}
if deltaX < 0 && aabb.min[0] >= nearby.max[0] {
difference := nearby.max[0] - aabb.min[0]
if difference > deltaX {
deltaX = difference
}
}
return deltaX
}
// CalculateYOffset calculates the offset on the Y axis between two bounding boxes, returning a delta always
// smaller than or equal to deltaY if deltaY is bigger than 0, or always bigger than or equal to deltaY if it
// is smaller than 0.
func (aabb AABB) CalculateYOffset(nearby AABB, deltaY float64) float64 {
// Bail out if not within the same X/Z plane.
if aabb.max[0] <= nearby.min[0] || aabb.min[0] >= nearby.max[0] {
return deltaY
} else if aabb.max[2] <= nearby.min[2] || aabb.min[2] >= nearby.max[2] {
return deltaY
}
if deltaY > 0 && aabb.max[1] <= nearby.min[1] {
difference := nearby.min[1] - aabb.max[1]
if difference < deltaY {
deltaY = difference
}
}
if deltaY < 0 && aabb.min[1] >= nearby.max[1] {
difference := nearby.max[1] - aabb.min[1]
if difference > deltaY {
deltaY = difference
}
}
return deltaY
}
// CalculateZOffset calculates the offset on the Z axis between two bounding boxes, returning a delta always
// smaller than or equal to deltaZ if deltaZ is bigger than 0, or always bigger than or equal to deltaZ if it
// is smaller than 0.
func (aabb AABB) CalculateZOffset(nearby AABB, deltaZ float64) float64 {
// Bail out if not within the same X/Y plane.
if aabb.max[0] <= nearby.min[0] || aabb.min[0] >= nearby.max[0] {
return deltaZ
} else if aabb.max[1] <= nearby.min[1] || aabb.min[1] >= nearby.max[1] {
return deltaZ
}
if deltaZ > 0 && aabb.max[2] <= nearby.min[2] {
difference := nearby.min[2] - aabb.max[2]
if difference < deltaZ {
deltaZ = difference
}
}
if deltaZ < 0 && aabb.min[2] >= nearby.max[2] {
difference := nearby.max[2] - aabb.min[2]
if difference > deltaZ {
deltaZ = difference
}
}
return deltaZ
}
<file_sep>package item
import (
"github.com/df-mc/dragonfly/dragonfly/internal/item_internal"
"github.com/df-mc/dragonfly/dragonfly/item/tool"
"github.com/df-mc/dragonfly/dragonfly/world"
"github.com/df-mc/dragonfly/dragonfly/world/sound"
"github.com/go-gl/mathgl/mgl64"
)
// Shovel is a tool generally used for mining ground-like blocks, such as sand, gravel and dirt. Additionally,
// shovels may be used to turn grass into grass paths.
type Shovel struct {
// Tier is the tier of the shovel.
Tier tool.Tier
}
// UseOnBlock handles the creation of grass path blocks from grass blocks.
func (s Shovel) UseOnBlock(pos world.BlockPos, face world.Face, _ mgl64.Vec3, w *world.World, _ User, ctx *UseContext) bool {
if grass := w.Block(pos); grass == item_internal.Grass {
if face == world.FaceDown {
// Grass paths are not created when the bottom face is clicked.
return false
}
if w.Block(pos.Add(world.BlockPos{0, 1})) != item_internal.Air {
// Grass paths can only be created if air is above the grass block.
return false
}
w.SetBlock(pos, item_internal.GrassPath)
w.PlaySound(pos.Vec3(), sound.ItemUseOn{Block: item_internal.GrassPath})
ctx.DamageItem(1)
return true
}
return false
}
// MaxCount always returns 1.
func (s Shovel) MaxCount() int {
return 1
}
// AttackDamage returns the attack damage of the shovel.
func (s Shovel) AttackDamage() float64 {
return s.Tier.BaseAttackDamage
}
// ToolType returns the tool type for shovels.
func (s Shovel) ToolType() tool.Type {
return tool.TypeShovel
}
// HarvestLevel ...
func (s Shovel) HarvestLevel() int {
return s.Tier.HarvestLevel
}
// BaseMiningEfficiency ...
func (s Shovel) BaseMiningEfficiency(world.Block) float64 {
return s.Tier.BaseMiningEfficiency
}
// DurabilityInfo ...
func (s Shovel) DurabilityInfo() DurabilityInfo {
return DurabilityInfo{
MaxDurability: s.Tier.Durability,
BrokenItem: simpleItem(Stack{}),
AttackDurability: 2,
BreakDurability: 1,
}
}
// EncodeItem ...
func (s Shovel) EncodeItem() (id int32, meta int16) {
switch s.Tier {
case tool.TierWood:
return 269, 0
case tool.TierGold:
return 284, 0
case tool.TierStone:
return 273, 0
case tool.TierIron:
return 256, 0
case tool.TierDiamond:
return 277, 0
case tool.TierNetherite:
return 744, 0
}
panic("invalid shovel tier")
}
<file_sep>package effect
import (
"github.com/df-mc/dragonfly/dragonfly/entity"
"image/color"
"time"
)
// Strength is a lasting effect that increases the damage dealt with melee attacks when applied to an entity.
type Strength struct {
lastingEffect
}
// Multiplier returns the damage multiplier of the effect.
func (s Strength) Multiplier() float64 {
return 0.3 * float64(s.Lvl)
}
// WithDuration ...
func (s Strength) WithDuration(d time.Duration) entity.Effect {
return Strength{s.withDuration(d)}
}
// RGBA ...
func (Strength) RGBA() color.RGBA {
return color.RGBA{R: 0x93, G: 0x24, B: 0x23, A: 0xff}
}
<file_sep>package session
import (
"encoding/json"
"fmt"
"github.com/df-mc/dragonfly/dragonfly/block"
"github.com/df-mc/dragonfly/dragonfly/entity"
_ "github.com/df-mc/dragonfly/dragonfly/entity/effect"
"github.com/df-mc/dragonfly/dragonfly/internal/entity_internal"
"github.com/df-mc/dragonfly/dragonfly/internal/nbtconv"
"github.com/df-mc/dragonfly/dragonfly/item"
"github.com/df-mc/dragonfly/dragonfly/item/inventory"
"github.com/df-mc/dragonfly/dragonfly/player/form"
"github.com/df-mc/dragonfly/dragonfly/player/skin"
"github.com/df-mc/dragonfly/dragonfly/world"
"github.com/df-mc/dragonfly/dragonfly/world/gamemode"
"github.com/go-gl/mathgl/mgl64"
"github.com/google/uuid"
"github.com/sandertv/gophertunnel/minecraft/protocol"
"github.com/sandertv/gophertunnel/minecraft/protocol/packet"
"go.uber.org/atomic"
"math"
"net"
"strings"
"time"
_ "unsafe" // Imported for compiler directives.
)
// closeCurrentContainer closes the container the player might currently have open.
func (s *Session) closeCurrentContainer() {
if !s.containerOpened.Load() {
return
}
s.closeWindow()
pos := s.openedPos.Load().(world.BlockPos)
if container, ok := s.c.World().Block(pos).(block.Container); ok {
container.RemoveViewer(s, s.c.World(), pos)
}
}
// SendRespawn spawns the controllable of the session client-side in the world, provided it is has died.
func (s *Session) SendRespawn() {
s.writePacket(&packet.Respawn{
Position: vec64To32(s.c.Position().Add(mgl64.Vec3{0, entityOffset(s.c)})),
State: packet.RespawnStateReadyToSpawn,
EntityRuntimeID: selfEntityRuntimeID,
})
}
// sendInv sends the inventory passed to the client with the window ID.
func (s *Session) sendInv(inv *inventory.Inventory, windowID uint32) {
pk := &packet.InventoryContent{
WindowID: windowID,
Content: make([]protocol.ItemInstance, 0, s.inv.Size()),
}
for _, i := range inv.All() {
pk.Content = append(pk.Content, instanceFromItem(i))
}
s.writePacket(pk)
}
const (
containerArmour = 6
containerChest = 7
containerInventoryChestOpened = 12
containerCraftingGrid = 13
containerHotbar = 27
containerInventory = 28
containerOffHand = 33
containerCursor = 58
containerCreativeOutput = 59
)
// invByID attempts to return an inventory by the ID passed. If found, the inventory is returned and the bool
// returned is true.
func (s *Session) invByID(id int32) (*inventory.Inventory, bool) {
switch id {
case containerCraftingGrid, containerCreativeOutput, containerCursor:
// UI inventory.
return s.ui, true
case containerHotbar, containerInventory, containerInventoryChestOpened:
// Hotbar 'inventory', rest of inventory, inventory when container is opened.
return s.inv, true
case containerOffHand:
return s.offHand, true
case containerArmour:
// Armour inventory.
return s.armour.Inv(), true
case containerChest:
// Chests, potentially other containers too.
if s.containerOpened.Load() {
return s.openedWindow.Load().(*inventory.Inventory), true
}
}
return nil, false
}
// Disconnect disconnects the client and ultimately closes the session. If the message passed is non-empty,
// it will be shown to the client.
func (s *Session) Disconnect(message string) {
if s != Nop {
s.writePacket(&packet.Disconnect{
HideDisconnectionScreen: message == "",
Message: message,
})
_ = s.conn.Flush()
_ = s.conn.Close()
}
}
// SendSpeed sends the speed of the player in an UpdateAttributes packet, so that it is updated client-side.
func (s *Session) SendSpeed(speed float64) {
s.writePacket(&packet.UpdateAttributes{
EntityRuntimeID: selfEntityRuntimeID,
Attributes: []protocol.Attribute{{
Name: "minecraft:movement",
Value: float32(speed),
Max: math.MaxFloat32,
Min: 0,
Default: 0.1,
}},
})
}
// SendFood ...
func (s *Session) SendFood(food int, saturation, exhaustion float64) {
s.writePacket(&packet.UpdateAttributes{
EntityRuntimeID: selfEntityRuntimeID,
Attributes: []protocol.Attribute{
{
Name: "minecraft:player.hunger",
Value: float32(food),
Max: 20, Min: 0, Default: 20,
},
{
Name: "minecraft:player.saturation",
Value: float32(saturation),
Max: 20, Min: 0, Default: 20,
},
{
Name: "minecraft:player.exhaustion",
Value: float32(exhaustion),
Max: 5, Min: 0, Default: 0,
},
},
})
}
// SendVelocity sends the velocity of the player to the client.
func (s *Session) SendVelocity(velocity mgl64.Vec3) {
s.writePacket(&packet.SetActorMotion{
EntityRuntimeID: selfEntityRuntimeID,
Velocity: vec64To32(velocity),
})
}
// SendForm sends a form to the client of the connection. The Submit method of the form is called when the
// client submits the form.
func (s *Session) SendForm(f form.Form) {
var n []map[string]interface{}
m := map[string]interface{}{}
switch frm := f.(type) {
case form.Custom:
m["type"], m["title"] = "custom_form", frm.Title()
for _, e := range frm.Elements() {
n = append(n, elemToMap(e))
}
m["content"] = n
case form.Menu:
m["type"], m["title"], m["content"] = "form", frm.Title(), frm.Body()
for _, button := range frm.Buttons() {
v := map[string]interface{}{"text": button.Text}
if button.Image != "" {
buttonType := "path"
if strings.HasPrefix(button.Image, "http:") || strings.HasPrefix(button.Image, "https:") {
buttonType = "url"
}
v["image"] = map[string]interface{}{"type": buttonType, "data": button.Image}
}
n = append(n, v)
}
m["buttons"] = n
case form.Modal:
m["type"], m["title"], m["content"] = "modal", frm.Title(), frm.Body()
buttons := frm.Buttons()
m["button1"], m["button2"] = buttons[0].Text, buttons[1].Text
}
b, _ := json.Marshal(m)
h := s.handlers[packet.IDModalFormResponse].(*ModalFormResponseHandler)
id := h.currentID.Add(1)
h.mu.Lock()
if len(h.forms) > 10 {
s.log.Debugf("SendForm %v: more than 10 active forms: dropping an existing one.", s.c.Name())
for k := range h.forms {
delete(h.forms, k)
break
}
}
h.forms[id] = f
h.mu.Unlock()
s.writePacket(&packet.ModalFormRequest{
FormID: id,
FormData: b,
})
}
// elemToMap encodes a form element to its representation as a map to be encoded to JSON for the client.
func elemToMap(e form.Element) map[string]interface{} {
switch element := e.(type) {
case form.Toggle:
return map[string]interface{}{
"type": "toggle",
"text": element.Text,
"default": element.Default,
}
case form.Input:
return map[string]interface{}{
"type": "input",
"text": element.Text,
"default": element.Default,
"placeholder": element.Placeholder,
}
case form.Label:
return map[string]interface{}{
"type": "label",
"text": element.Text,
}
case form.Slider:
return map[string]interface{}{
"type": "slider",
"text": element.Text,
"min": element.Min,
"max": element.Max,
"step": element.StepSize,
"default": element.Default,
}
case form.Dropdown:
return map[string]interface{}{
"type": "dropdown",
"text": element.Text,
"default": element.DefaultIndex,
"options": element.Options,
}
case form.StepSlider:
return map[string]interface{}{
"type": "step_slider",
"text": element.Text,
"default": element.DefaultIndex,
"steps": element.Options,
}
}
panic("should never happen")
}
// Transfer transfers the player to a server with the IP and port passed.
func (s *Session) Transfer(ip net.IP, port int) {
s.writePacket(&packet.Transfer{
Address: ip.String(),
Port: uint16(port),
})
}
// SendGameMode sends the game mode of the Controllable of the session to the client. It makes sure the right
// flags are set to create the full game mode.
func (s *Session) SendGameMode(mode gamemode.GameMode) {
flags, id := uint32(0), int32(packet.GameTypeSurvival)
switch mode.(type) {
case gamemode.Creative:
flags = packet.AdventureFlagAllowFlight
id = packet.GameTypeCreative
case gamemode.Adventure:
flags |= packet.AdventureFlagWorldImmutable
id = packet.GameTypeAdventure
case gamemode.Spectator:
flags, id = packet.AdventureFlagWorldImmutable|packet.AdventureFlagAllowFlight|packet.AdventureFlagMuted|packet.AdventureFlagNoClip|packet.AdventureFlagNoPVP, packet.GameTypeCreativeSpectator
}
s.writePacket(&packet.AdventureSettings{
Flags: flags,
PermissionLevel: packet.PermissionLevelMember,
PlayerUniqueID: 1,
ActionPermissions: uint32(packet.ActionPermissionBuildAndMine | packet.ActionPermissionDoorsAndSwitched | packet.ActionPermissionOpenContainers | packet.ActionPermissionAttackPlayers | packet.ActionPermissionAttackMobs),
})
s.writePacket(&packet.SetPlayerGameType{GameType: id})
}
// SendHealth sends the health and max health to the player.
func (s *Session) SendHealth(health *entity_internal.HealthManager) {
s.writePacket(&packet.UpdateAttributes{
EntityRuntimeID: selfEntityRuntimeID,
Attributes: []protocol.Attribute{{
Name: "minecraft:health",
Value: float32(math.Ceil(health.Health())),
Max: float32(math.Ceil(health.MaxHealth())),
Default: 20,
}},
})
}
// SendAbsorption sends the absorption value passed to the player.
func (s *Session) SendAbsorption(value float64) {
max := value
if math.Mod(value, 2) != 0 {
max = value + 1
}
s.writePacket(&packet.UpdateAttributes{
EntityRuntimeID: selfEntityRuntimeID,
Attributes: []protocol.Attribute{{
Name: "minecraft:absorption",
Value: float32(math.Ceil(value)),
Max: float32(math.Ceil(max)),
}},
})
}
// SendEffect sends an effects passed to the player.
func (s *Session) SendEffect(e entity.Effect) {
s.SendEffectRemoval(e)
id, _ := effect_idByEffect(e)
s.writePacket(&packet.MobEffect{
EntityRuntimeID: selfEntityRuntimeID,
Operation: packet.MobEffectAdd,
EffectType: int32(id),
Amplifier: int32(e.Level() - 1),
Particles: e.ShowParticles(),
Duration: int32(e.Duration() / (time.Second / 20)),
})
}
// SendEffectRemoval sends the removal of an effect passed.
func (s *Session) SendEffectRemoval(e entity.Effect) {
id, ok := effect_idByEffect(e)
if !ok {
panic(fmt.Sprintf("unregistered effect type %T", e))
}
s.writePacket(&packet.MobEffect{
EntityRuntimeID: selfEntityRuntimeID,
Operation: packet.MobEffectRemove,
EffectType: int32(id),
})
}
// SendGameRules sends all the provided game rules to the player. Once sent, they will be immediately updated
// on the client if they are valid.
func (s *Session) sendGameRules(gameRules map[string]interface{}) {
s.writePacket(&packet.GameRulesChanged{GameRules: gameRules})
}
// EnableCoordinates will either enable or disable coordinates for the player depending on the value given.
func (s *Session) EnableCoordinates(enable bool) {
//noinspection SpellCheckingInspection
s.sendGameRules(map[string]interface{}{"showcoordinates": enable})
}
// addToPlayerList adds the player of a session to the player list of this session. It will be shown in the
// in-game pause menu screen.
func (s *Session) addToPlayerList(session *Session) {
c := session.c
s.entityMutex.Lock()
runtimeID := uint64(1)
if session != s {
runtimeID = s.currentEntityRuntimeID.Add(1)
}
s.entityRuntimeIDs[c] = runtimeID
s.entities[runtimeID] = c
s.entityMutex.Unlock()
s.writePacket(&packet.PlayerList{
ActionType: packet.PlayerListActionAdd,
Entries: []protocol.PlayerListEntry{{
UUID: c.UUID(),
EntityUniqueID: int64(runtimeID),
Username: c.Name(),
XUID: c.XUID(),
Skin: skinToProtocol(c.Skin()),
}},
})
}
// skinToProtocol converts a skin to its protocol representation.
func skinToProtocol(s skin.Skin) protocol.Skin {
var animations []protocol.SkinAnimation
for _, animation := range s.Animations {
protocolAnim := protocol.SkinAnimation{
ImageWidth: uint32(animation.Bounds().Max.X),
ImageHeight: uint32(animation.Bounds().Max.Y),
ImageData: animation.Pix,
AnimationType: 0,
FrameCount: float32(animation.FrameCount),
}
switch animation.Type() {
case skin.AnimationHead:
protocolAnim.AnimationType = protocol.SkinAnimationHead
case skin.AnimationBody32x32:
protocolAnim.AnimationType = protocol.SkinAnimationBody32x32
case skin.AnimationBody128x128:
protocolAnim.AnimationType = protocol.SkinAnimationBody128x128
}
animations = append(animations, protocolAnim)
}
return protocol.Skin{
SkinID: uuid.New().String(),
SkinResourcePatch: s.ModelConfig.Encode(),
SkinImageWidth: uint32(s.Bounds().Max.X),
SkinImageHeight: uint32(s.Bounds().Max.Y),
SkinData: s.Pix,
CapeImageWidth: uint32(s.Cape.Bounds().Max.X),
CapeImageHeight: uint32(s.Cape.Bounds().Max.Y),
CapeData: s.Cape.Pix,
SkinGeometry: s.Model,
PersonaSkin: s.Persona,
CapeID: uuid.New().String(),
FullSkinID: uuid.New().String(),
Animations: animations,
Trusted: true,
}
}
// removeFromPlayerList removes the player of a session from the player list of this session. It will no
// longer be shown in the in-game pause menu screen.
func (s *Session) removeFromPlayerList(session *Session) {
c := session.c
s.entityMutex.Lock()
delete(s.entityRuntimeIDs, c)
delete(s.entities, s.entityRuntimeIDs[c])
s.entityMutex.Unlock()
s.writePacket(&packet.PlayerList{
ActionType: packet.PlayerListActionRemove,
Entries: []protocol.PlayerListEntry{{
UUID: c.UUID(),
}},
})
}
// HandleInventories starts handling the inventories of the Controllable of the session. It sends packets when
// slots in the inventory are changed.
func (s *Session) HandleInventories() (inv, offHand *inventory.Inventory, armour *inventory.Armour, heldSlot *atomic.Uint32) {
s.inv = inventory.New(36, func(slot int, item item.Stack) {
if slot == int(s.heldSlot.Load()) {
for _, viewer := range s.c.World().Viewers(s.c.Position()) {
viewer.ViewEntityItems(s.c)
}
}
if !s.inTransaction.Load() {
s.writePacket(&packet.InventorySlot{
WindowID: protocol.WindowIDInventory,
Slot: uint32(slot),
NewItem: instanceFromItem(item),
})
}
})
s.offHand = inventory.New(2, func(slot int, item item.Stack) {
for _, viewer := range s.c.World().Viewers(s.c.Position()) {
viewer.ViewEntityItems(s.c)
}
if !s.inTransaction.Load() {
s.writePacket(&packet.InventorySlot{
WindowID: protocol.WindowIDOffHand,
Slot: uint32(slot),
NewItem: instanceFromItem(item),
})
}
})
s.armour = inventory.NewArmour(func(slot int, item item.Stack) {
for _, viewer := range s.c.World().Viewers(s.c.Position()) {
viewer.ViewEntityArmour(s.c)
}
if !s.inTransaction.Load() {
s.writePacket(&packet.InventorySlot{
WindowID: protocol.WindowIDArmour,
Slot: uint32(slot),
NewItem: instanceFromItem(item),
})
}
})
return s.inv, s.offHand, s.armour, s.heldSlot
}
// stackFromItem converts an item.Stack to its network ItemStack representation.
func stackFromItem(it item.Stack) protocol.ItemStack {
if it.Empty() {
return protocol.ItemStack{}
}
id, meta := it.Item().EncodeItem()
return protocol.ItemStack{
ItemType: protocol.ItemType{
NetworkID: id,
MetadataValue: meta,
},
Count: int16(it.Count()),
NBTData: nbtconv.ItemToNBT(it, true),
}
}
// instanceFromItem converts an item.Stack to its network ItemInstance representation.
func instanceFromItem(it item.Stack) protocol.ItemInstance {
return protocol.ItemInstance{
StackNetworkID: item_id(it),
Stack: stackFromItem(it),
}
}
// stackToItem converts a network ItemStack representation back to an item.Stack.
func stackToItem(it protocol.ItemStack) item.Stack {
t, ok := world_itemByID(it.NetworkID, it.MetadataValue)
if !ok {
t = block.Air{}
}
//noinspection SpellCheckingInspection
if nbter, ok := t.(world.NBTer); ok && len(it.NBTData) != 0 {
t = nbter.DecodeNBT(it.NBTData).(world.Item)
}
s := item.NewStack(t, int(it.Count))
return nbtconv.ItemFromNBT(it.NBTData, &s)
}
// creativeItems returns all creative inventory items as protocol item stacks.
func creativeItems() []protocol.CreativeItem {
it := make([]protocol.CreativeItem, 0, len(item.CreativeItems()))
for index, i := range item.CreativeItems() {
it = append(it, protocol.CreativeItem{
CreativeItemNetworkID: uint32(index) + 1,
Item: stackFromItem(i),
})
}
return it
}
// The following functions use the go:linkname directive in order to make sure the item.byID and item.toID
// functions do not need to be exported.
//go:linkname world_itemByID github.com/df-mc/dragonfly/dragonfly/world.itemByID
//noinspection ALL
func world_itemByID(id int32, meta int16) (world.Item, bool)
//go:linkname item_id github.com/df-mc/dragonfly/dragonfly/item.id
//noinspection ALL
func item_id(s item.Stack) int32
//go:linkname effect_idByEffect github.com/df-mc/dragonfly/dragonfly/entity/effect.idByEffect
//noinspection ALL
func effect_idByEffect(entity.Effect) (int, bool)
<file_sep>package effect
import (
"github.com/df-mc/dragonfly/dragonfly/entity"
"image/color"
"time"
)
// HealthBoost causes the affected entity to have its maximum health changed for a specific duration.
type HealthBoost struct {
lastingEffect
}
// Start ...
func (h HealthBoost) Start(e entity.Living) {
e.SetMaxHealth(e.MaxHealth() + 4*float64(h.Lvl))
}
// End ...
func (h HealthBoost) End(e entity.Living) {
e.SetMaxHealth(e.MaxHealth() - 4*float64(h.Lvl))
}
// WithDuration ...
func (h HealthBoost) WithDuration(d time.Duration) entity.Effect {
return HealthBoost{h.withDuration(d)}
}
// RGBA ...
func (HealthBoost) RGBA() color.RGBA {
return color.RGBA{R: 0xf8, G: 0x7d, B: 0x23, A: 0xff}
}
<file_sep>package world
import (
"fmt"
)
// Item represents an item that may be added to an inventory. It has a method to encode the item to an ID and
// a metadata value.
type Item interface {
// EncodeItem encodes the item to its Minecraft representation, which consists of a numerical ID and a
// metadata value.
EncodeItem() (id int32, meta int16)
}
// NBTer represents either an item or a block which may decode NBT data and encode to NBT data. Typically
// this is done to store additional data.
type NBTer interface {
// DecodeNBT returns the item or block, depending on which of those the NBTer was, with the NBT data
// decoded into it.
DecodeNBT(data map[string]interface{}) interface{}
EncodeNBT() map[string]interface{}
}
// RegisterItem registers an item with the ID and meta passed. Once registered, items may be obtained from an
// ID and metadata value using itemByID().
// If an item with the ID and meta passed already exists, RegisterItem panics.
func RegisterItem(name string, item Item) {
id, meta := item.EncodeItem()
k := (id << 4) | int32(meta)
if _, ok := items[k]; ok {
panic(fmt.Sprintf("item registered with ID %v and meta %v already exists", id, meta))
}
items[k] = item
itemsNames[name] = id
names[id] = name
}
var items = map[int32]Item{}
var itemsNames = map[string]int32{}
var names = map[int32]string{}
// itemByID attempts to return an item by the ID and meta it was registered with. If found, the item found is
// returned and the bool true.
//lint:ignore U1000 Function is used using compiler directives.
func itemByID(id int32, meta int16) (Item, bool) {
it, ok := items[(id<<4)|int32(meta)]
if !ok {
// Also try obtaining the item with a metadata value of 0, for cases with durability.
it, ok = items[(id<<4)|int32(0)]
}
return it, ok
}
// itemByName attempts to return an item by a name and a metadata value, rather than an ID.
//lint:ignore U1000 Function is used using compiler directives.
//noinspection GoUnusedFunction
func itemByName(name string, meta int16) (Item, bool) {
id, ok := itemsNames[name]
if !ok {
return nil, false
}
return itemByID(id, meta)
}
// itemToName encodes an item to its string ID and metadata value.
//lint:ignore U1000 Function is used using compiler directives.
//noinspection GoUnusedFunction
func itemToName(it Item) (name string, meta int16) {
id, meta := it.EncodeItem()
return names[id], meta
}
<file_sep>package effect
import (
"github.com/df-mc/dragonfly/dragonfly/entity"
"image/color"
"time"
)
// WaterBreathing is a lasting effect that allows the affected entity to breath underwater until the effect
// expires.
type WaterBreathing struct {
lastingEffect
}
// WithDuration ...
func (w WaterBreathing) WithDuration(d time.Duration) entity.Effect {
return WaterBreathing{w.withDuration(d)}
}
// RGBA ...
func (w WaterBreathing) RGBA() color.RGBA {
return color.RGBA{R: 0x2e, G: 0x52, B: 0x99, A: 0xff}
}
<file_sep>module github.com/df-mc/dragonfly
go 1.13
require (
github.com/brentp/intintmap v0.0.0-20190211203843-30dc0ade9af9
github.com/cespare/xxhash v1.1.0
github.com/df-mc/goleveldb v1.1.8
github.com/go-gl/mathgl v0.0.0-20190713194549-592312d8590a
github.com/google/uuid v1.1.1
github.com/kr/pretty v0.1.0 // indirect
github.com/kylelemons/godebug v1.1.0 // indirect
github.com/pelletier/go-toml v1.8.0
github.com/sahilm/fuzzy v0.1.0
github.com/sandertv/gophertunnel v1.7.7
github.com/sirupsen/logrus v1.6.0
github.com/yourbasic/radix v0.0.0-20180308122924-cbe1cc82e907
go.uber.org/atomic v1.6.0
golang.org/x/image v0.0.0-20200618115811-c13761719519 // indirect
golang.org/x/sys v0.0.0-20200622214017-ed371f2e16b4 // indirect
golang.org/x/text v0.3.3 // indirect
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 // indirect
)
<file_sep>package effect
import (
"github.com/df-mc/dragonfly/dragonfly/entity"
"image/color"
"math"
"time"
)
// MiningFatigue is a lasting effect that decreases the mining speed of a player by 10% for each level of the
// effect.
type MiningFatigue struct {
lastingEffect
}
// Multiplier returns the mining speed multiplier from this effect.
func (m MiningFatigue) Multiplier() float64 {
return math.Pow(3, float64(m.Lvl))
}
// WithDuration ...
func (m MiningFatigue) WithDuration(d time.Duration) entity.Effect {
return MiningFatigue{m.withDuration(d)}
}
// RGBA ...
func (MiningFatigue) RGBA() color.RGBA {
return color.RGBA{R: 0x4a, G: 0x42, B: 0x17, A: 0xff}
}
<file_sep>package block
import (
"github.com/df-mc/dragonfly/dragonfly/item"
"github.com/df-mc/dragonfly/dragonfly/item/tool"
)
// Obsidian is a dark purple block known for its high blast resistance and strength, most commonly found when
// water flows over lava.
type Obsidian struct{ noNBT }
// EncodeItem ...
func (Obsidian) EncodeItem() (id int32, meta int16) {
return 49, 0
}
// EncodeBlock ...
func (Obsidian) EncodeBlock() (name string, properties map[string]interface{}) {
return "minecraft:obsidian", nil
}
// Hash ...
func (Obsidian) Hash() uint64 {
return hashObsidian
}
// BreakInfo ...
func (o Obsidian) BreakInfo() BreakInfo {
return BreakInfo{
Hardness: 50,
Harvestable: func(t tool.Tool) bool {
return t.ToolType() == tool.TypePickaxe && t.HarvestLevel() >= tool.TierDiamond.HarvestLevel
},
Effective: pickaxeEffective,
Drops: simpleDrops(item.NewStack(o, 1)),
}
}
<file_sep>package session
import (
"fmt"
"github.com/df-mc/dragonfly/dragonfly/world"
"github.com/sandertv/gophertunnel/minecraft/protocol"
"github.com/sandertv/gophertunnel/minecraft/protocol/packet"
)
// InventoryTransactionHandler handles the InventoryTransaction packet.
type InventoryTransactionHandler struct{}
// Handle ...
func (h *InventoryTransactionHandler) Handle(p packet.Packet, s *Session) error {
pk := p.(*packet.InventoryTransaction)
switch data := pk.TransactionData.(type) {
case *protocol.NormalTransactionData:
h.resendInventories(s)
s.log.Debugf("failed processing packet from %v (%v): InventoryTransaction: unhandled normal transaction %#v\n", s.conn.RemoteAddr(), s.c.Name(), data)
return nil
case *protocol.UseItemOnEntityTransactionData:
return h.handleUseItemOnEntityTransaction(data, s)
case *protocol.UseItemTransactionData:
return h.handleUseItemTransaction(data, s)
}
return fmt.Errorf("unhandled inventory transaction type %T", pk.TransactionData)
}
// resendInventories resends all inventories of the player.
func (h *InventoryTransactionHandler) resendInventories(s *Session) {
s.sendInv(s.inv, protocol.WindowIDInventory)
s.sendInv(s.ui, protocol.WindowIDUI)
s.sendInv(s.offHand, protocol.WindowIDOffHand)
s.sendInv(s.armour.Inv(), protocol.WindowIDArmour)
}
// handleUseItemOnEntityTransaction
func (h *InventoryTransactionHandler) handleUseItemOnEntityTransaction(data *protocol.UseItemOnEntityTransactionData, s *Session) error {
s.swingingArm.Store(true)
defer s.swingingArm.Store(false)
e, ok := s.entityFromRuntimeID(data.TargetEntityRuntimeID)
if !ok {
return fmt.Errorf("invalid entity interaction: no entity found with runtime ID %v", data.TargetEntityRuntimeID)
}
if data.TargetEntityRuntimeID == selfEntityRuntimeID {
return fmt.Errorf("invalid entity interaction: players cannot interact with themselves")
}
switch data.ActionType {
case protocol.UseItemOnEntityActionInteract:
s.c.UseItemOnEntity(e)
case protocol.UseItemOnEntityActionAttack:
s.c.AttackEntity(e)
default:
return fmt.Errorf("unhandled UseItemOnEntity ActionType %v", data.ActionType)
}
return nil
}
// handleUseItemTransaction
func (h *InventoryTransactionHandler) handleUseItemTransaction(data *protocol.UseItemTransactionData, s *Session) error {
pos := world.BlockPos{int(data.BlockPosition[0]), int(data.BlockPosition[1]), int(data.BlockPosition[2])}
s.swingingArm.Store(true)
defer s.swingingArm.Store(false)
switch data.ActionType {
case protocol.UseItemActionBreakBlock:
s.c.BreakBlock(pos)
case protocol.UseItemActionClickBlock:
// We reset the inventory so that we can send the held item update without the client already
// having done that client-side.
s.sendInv(s.inv, protocol.WindowIDInventory)
s.c.UseItemOnBlock(pos, world.Face(data.BlockFace), vec32To64(data.ClickedPosition))
case protocol.UseItemActionClickAir:
s.c.UseItem()
default:
return fmt.Errorf("unhandled UseItem ActionType %v", data.ActionType)
}
return nil
}
<file_sep>package effect
import (
"github.com/df-mc/dragonfly/dragonfly/entity"
"image/color"
"time"
)
// Levitation is a lasting effect that causes the affected entity to slowly levitate upwards. It is roughly
// the opposite of the SlowFalling effect.
type Levitation struct {
lastingEffect
}
// WithDuration ...
func (l Levitation) WithDuration(d time.Duration) entity.Effect {
return Levitation{l.withDuration(d)}
}
// RGBA ...
func (Levitation) RGBA() color.RGBA {
return color.RGBA{R: 0xce, G: 0xff, B: 0xff, A: 0xff}
}
<file_sep>package item
import (
"fmt"
"github.com/df-mc/dragonfly/dragonfly/world"
"reflect"
"strings"
"sync/atomic"
)
// Stack represents a stack of items. The stack shares the same item type and has a count which specifies the
// size of the stack.
type Stack struct {
id int32
item world.Item
count int
customName string
lore []string
damage int
data map[string]interface{}
enchantments map[reflect.Type]Enchantment
}
// NewStack returns a new stack using the item type and the count passed. NewStack panics if the count passed
// is negative or if the item type passed is nil.
func NewStack(t world.Item, count int) Stack {
if count < 0 {
panic("cannot use negative count for item stack")
}
if t == nil {
panic("cannot have a stack with item type nil")
}
return Stack{item: t, count: count, id: newID()}
}
// Count returns the amount of items that is present on the stack. The count is guaranteed never to be
// negative.
func (s Stack) Count() int {
return s.count
}
// MaxCount returns the maximum count that the stack is able to hold when added to an inventory or when added
// to an item entity.
func (s Stack) MaxCount() int {
if counter, ok := s.item.(MaxCounter); ok {
return counter.MaxCount()
}
return 64
}
// Grow grows the Stack's count by n, returning the resulting Stack. If a positive number is passed, the stack
// is grown, whereas if a negative size is passed, the resulting Stack will have a lower count. The count of
// the returned Stack will never be negative.
func (s Stack) Grow(n int) Stack {
s.count += n
if s.count < 0 {
s.count = 0
}
s.id = newID()
return s
}
// Durability returns the current durability of the item stack. If the item is not one that implements the
// Durable interface, BaseDurability will always return -1.
// The closer the durability returned is to 0, the closer the item is to breaking.
func (s Stack) Durability() int {
if durable, ok := s.Item().(Durable); ok {
return durable.DurabilityInfo().MaxDurability - s.damage
}
return -1
}
// MaxDurability returns the maximum durability that the item stack is able to have. If the item does not
// implement the Durable interface, MaxDurability will always return -1.
func (s Stack) MaxDurability() int {
if durable, ok := s.Item().(Durable); ok {
return durable.DurabilityInfo().MaxDurability
}
return -1
}
// Damage returns a new stack that is damaged by the amount passed. (Meaning, its durability lowered by the
// amount passed.) If the item does not implement the Durable interface, the original stack is returned.
// The damage passed may be negative to add durability.
// If the final durability reaches 0 or below, the item returned is the resulting item of the breaking of the
// item. If the final durability reaches a number higher than the maximum durability, the stack returned will
// get the maximum durability.
func (s Stack) Damage(d int) Stack {
durable, ok := s.Item().(Durable)
if !ok {
// Not a durable item.
return s
}
info := durable.DurabilityInfo()
if s.Durability()-d <= 0 {
// A durability of 0, so the item is broken.
return info.BrokenItem()
}
if s.Durability()-d > info.MaxDurability {
// We've passed the maximum durability, so we just need to make sure the final durability of the item
// will be equal to the max.
s.damage, d = 0, 0
}
s.damage += d
return s
}
// WithDurability returns a new item stack with the durability passed. If the item does not implement the
// Durable interface, WithDurability returns the original stack.
// The closer the durability d is to 0, the closer the item is to breaking. If a durability of 0 is passed,
// a stack with the item type of the BrokenItem is returned. If a durability is passed that exceeds the
// maximum durability, the stack returned will have the maximum durability.
func (s Stack) WithDurability(d int) Stack {
durable, ok := s.Item().(Durable)
if !ok {
// Not a durable item.
return s
}
maxDurability := durable.DurabilityInfo().MaxDurability
if d > maxDurability {
// A durability bigger than the max, so the item has no damage at all.
s.damage = 0
return s
}
if d == 0 {
// A durability of 0, so the item is broken.
return durable.DurabilityInfo().BrokenItem()
}
s.damage = maxDurability - d
return s
}
// Empty checks if the stack is empty (has a count of 0).
func (s Stack) Empty() bool {
return s.Count() == 0 || s.item == nil
}
// Item returns the item that the stack holds. If the stack is considered empty (Stack.Empty()), Item will
// always return nil.
func (s Stack) Item() world.Item {
if s.Empty() || s.item == nil {
return nil
}
return s.item
}
// AttackDamage returns the attack damage of the stack. By default, the value returned is 2.0. If the item
// held implements the item.Weapon interface, this damage may be different.
func (s Stack) AttackDamage() float64 {
if weapon, ok := s.Item().(Weapon); ok {
// Bonus attack damage from weapons is a bit quirky in Bedrock Edition: Even though tools say they
// have, for example, + 5 Attack Damage, it is actually 1 + 5, while punching with a hand in Bedrock
// Edition deals 2 damage, not 1 like in Java Edition.
// The tooltip displayed in-game is therefore not exactly correct.
return weapon.AttackDamage() + 1
}
return 2.0
}
// WithCustomName returns a copy of the Stack with the custom name passed. The custom name is formatted
// according to the rules of fmt.Sprintln.
func (s Stack) WithCustomName(a ...interface{}) Stack {
s.customName = format(a)
if !strings.HasPrefix(s.customName, "§r") {
// We always reset it if it's not already done, because Vanilla makes custom names in italic, which
// servers generally just don't want.
s.customName = "§r" + s.customName
}
if nameable, ok := s.Item().(nameable); ok {
s.item = nameable.WithName(a...)
}
return s
}
// CustomName returns the custom name set for the Stack. An empty string is returned if the Stack has no
// custom name set.
func (s Stack) CustomName() string {
return s.customName
}
// WithLore returns a copy of the Stack with the lore passed. Each string passed is put on a different line,
// where the first string is at the top and the last at the bottom.
// The lore may be cleared by passing no lines into the Stack.
func (s Stack) WithLore(lines ...string) Stack {
s.lore = lines
return s
}
// Lore returns the lore set for the Stack. If no lore is present, the slice returned has a len of 0.
func (s Stack) Lore() []string {
return s.lore
}
// WithValue returns the current Stack with a value set at a specific key. This method may be used to
// associate custom data with the item stack, which will persist through server restarts.
// The value stored may later be obtained by making a call to Stack.Value().
//
// WithValue may be called with a nil value, in which case the value at the key will be cleared.
//
// WithValue stores values by encoding them using the encoding/gob package. Users of WithValue must ensure
// that their value is valid for encoding with this package.
func (s Stack) WithValue(key string, val interface{}) Stack {
s.data = copyMap(s.data)
if val != nil {
s.data[key] = val
} else {
delete(s.data, key)
}
return s
}
// Value attempts to return a value set to the Stack using Stack.WithValue(). If a value is found by the key
// passed, it is returned and ok is true. If not found, the value returned is nil and ok is false.
func (s Stack) Value(key string) (val interface{}, ok bool) {
val, ok = s.data[key]
return val, ok
}
// WithEnchantment returns the current stack with the passed enchantment. If the enchantment is not compatible
// with the item stack, it will not be applied and will return the original stack.
func (s Stack) WithEnchantment(ench Enchantment) Stack {
if !ench.CompatibleWith(s) {
return s
}
s.enchantments = copyEnchantments(s.enchantments)
s.enchantments[reflect.TypeOf(ench)] = ench
return s
}
// WithoutEnchantment returns the current stack but with the passed enchantment removed.
func (s Stack) WithoutEnchantment(enchant Enchantment) Stack {
s.enchantments = copyEnchantments(s.enchantments)
delete(s.enchantments, reflect.TypeOf(enchant))
return s
}
// Enchantment attempts to return an enchantment set to the Stack using Stack.WithEnchantment(). If an enchantment
// is found, the enchantment and the bool true is returned.
func (s Stack) Enchantment(enchant Enchantment) (Enchantment, bool) {
ench, ok := s.enchantments[reflect.TypeOf(enchant)]
return ench, ok
}
// Enchantments returns an array of all Enchantments on the item.
func (s Stack) Enchantments() []Enchantment {
e := make([]Enchantment, 0, len(s.enchantments))
for _, ench := range s.enchantments {
e = append(e, ench)
}
return e
}
// AddStack adds another stack to the stack and returns both stacks. The first stack returned will have as
// many items in it as possible to fit in the stack, according to a max count of either 64 or otherwise as
// returned by Item.MaxCount(). The second stack will have the leftover items: It may be empty if the count of
// both stacks together don't exceed the max count.
// If the two stacks are not comparable, AddStack will return both the original stack and the stack passed.
func (s Stack) AddStack(s2 Stack) (a, b Stack) {
if !s.Comparable(s2) {
// The items are not comparable and thus cannot be stacked together.
return s, s2
}
if s.Count() >= s.MaxCount() {
// No more items could be added to the original stack.
return s, s2
}
diff := s.MaxCount() - s.Count()
if s2.Count() < diff {
diff = s2.Count()
}
s.count, s2.count = s.count+diff, s2.count-diff
s.id, s2.id = newID(), newID()
return s, s2
}
// Comparable checks if two stacks can be considered comparable. True is returned if the two stacks have an
// equal item type and have equal enchantments, lore and custom names, or if one of the stacks is empty.
func (s Stack) Comparable(s2 Stack) bool {
if s.Empty() || s2.Empty() {
return true
}
id, meta := s.Item().EncodeItem()
id2, meta2 := s2.Item().EncodeItem()
if id != id2 || meta != meta2 || s.damage != s2.damage {
return false
}
if s.customName != s2.customName || len(s.lore) != len(s2.lore) {
return false
}
for i := range s.lore {
if s.lore[i] != s2.lore[i] {
return false
}
}
if !reflect.DeepEqual(s.data, s2.data) {
return false
}
if nbt, ok := s.Item().(world.NBTer); ok {
nbt2, ok := s2.Item().(world.NBTer)
if !ok {
return false
}
return reflect.DeepEqual(nbt.EncodeNBT(), nbt2.EncodeNBT())
}
return true
}
// String implements the fmt.Stringer interface.
func (s Stack) String() string {
if s.item == nil {
return fmt.Sprintf("Stack<nil> x%v", s.count)
}
return fmt.Sprintf("Stack<%T%+v>(custom name='%v', lore='%v') x%v", s.item, s.item, s.customName, s.lore, s.count)
}
// values returns all values associated with the stack by users.
//lint:ignore U1000 Function is used using compiler directives.
//noinspection GoUnusedFunction
func values(s Stack) map[string]interface{} {
return s.data
}
// stackID is a counter for unique stack IDs.
var stackID = new(int32)
// newID returns a new unique stack ID.
func newID() int32 {
return atomic.AddInt32(stackID, 1)
}
// id returns the unique ID of the stack passed.
//lint:ignore U1000 Function is used using compiler directives.
//noinspection GoUnusedFunction
func id(s Stack) int32 {
if s.Empty() {
return 0
}
return s.id
}
// format is a utility function to format a list of values to have spaces between them, but no newline at the
// end, which is typically used for sending messages, popups and tips.
func format(a []interface{}) string {
return strings.TrimSuffix(fmt.Sprintln(a...), "\n")
}
// copyMap makes a copy of the map passed. It does not recursively copy the map.
func copyMap(m map[string]interface{}) map[string]interface{} {
cp := make(map[string]interface{}, len(m))
for k, v := range m {
cp[k] = v
}
return cp
}
// copyEnchantments makes a copy of the enchantments map passed. It does not recursively copy the map.
func copyEnchantments(m map[reflect.Type]Enchantment) map[reflect.Type]Enchantment {
cp := make(map[reflect.Type]Enchantment, len(m))
for k, v := range m {
cp[k] = v
}
return cp
}
<file_sep>package item
import (
"github.com/df-mc/dragonfly/dragonfly/internal/item_internal"
"github.com/df-mc/dragonfly/dragonfly/item/bucket"
"github.com/df-mc/dragonfly/dragonfly/world"
"github.com/df-mc/dragonfly/dragonfly/world/sound"
"github.com/go-gl/mathgl/mgl64"
)
// Bucket is a tool used to carry water, lava, milk and fish.
type Bucket struct {
// Content is the content that the bucket has. By default, this value resolves to an empty bucket.
Content bucket.Content
}
// MaxCount returns 16.
func (b Bucket) MaxCount() int {
if b.Empty() {
return 16
}
return 1
}
// Empty returns true if the bucket is empty.
func (b Bucket) Empty() bool {
return b.Content == bucket.Content{}
}
// UseOnBlock handles the bucket filling and emptying logic.
func (b Bucket) UseOnBlock(pos world.BlockPos, face world.Face, _ mgl64.Vec3, w *world.World, _ User, ctx *UseContext) bool {
if b.Empty() {
return b.fillFrom(pos, w, ctx)
}
var liq world.Liquid
if b.Content == bucket.Water() {
liq = item_internal.Water
} else if b.Content == bucket.Lava() {
liq = item_internal.Lava
} else {
return false
}
if d, ok := w.Block(pos).(world.LiquidDisplacer); (ok && d.CanDisplace(liq)) || item_internal.Replaceable(w, pos, liq) {
w.SetLiquid(pos, liq)
} else if d, ok := w.Block(pos.Side(face)).(world.LiquidDisplacer); (ok && d.CanDisplace(liq)) || item_internal.Replaceable(w, pos.Side(face), liq) {
w.SetLiquid(pos.Side(face), liq)
} else {
return false
}
w.PlaySound(pos.Vec3Centre(), sound.BucketEmpty{Liquid: liq})
ctx.NewItem = NewStack(Bucket{}, 1)
ctx.SubtractFromCount(1)
return true
}
// fillFrom fills a bucket from the liquid at the position passed in the world. If there is no liquid or if
// the liquid is no source, fillFrom returns false.
func (b Bucket) fillFrom(pos world.BlockPos, w *world.World, ctx *UseContext) bool {
liquid, ok := w.Liquid(pos)
if !ok {
return false
}
if liquid.LiquidDepth() != 8 || liquid.LiquidFalling() {
// Only allow picking up liquid source blocks.
return false
}
w.SetLiquid(pos, nil)
w.PlaySound(pos.Vec3Centre(), sound.BucketFill{Liquid: liquid})
if item_internal.IsWater(liquid) {
ctx.NewItem = NewStack(Bucket{Content: bucket.Water()}, 1)
} else {
ctx.NewItem = NewStack(Bucket{Content: bucket.Lava()}, 1)
}
ctx.SubtractFromCount(1)
return true
}
// EncodeItem ...
func (b Bucket) EncodeItem() (id int32, meta int16) {
switch b.Content {
case bucket.Water():
return 325, 8
case bucket.Lava():
return 325, 10
}
return 325, 0
}
<file_sep>package effect
import (
"github.com/df-mc/dragonfly/dragonfly/entity"
"github.com/df-mc/dragonfly/dragonfly/entity/damage"
"time"
)
// InstantDamage is an instant effect that causes a living entity to immediately take some damage, depending
// on the level and the potency of the effect.
type InstantDamage struct {
instantEffect
// Potency specifies the potency of the instant damage. By default this value is 1, which means 100% of
// the instant damage will be applied to an entity. A lingering damage potion, for example, has a potency
// of 0.5: It deals 1.5 hearts damage (per tick) instead of 3.
Potency float64
}
// Apply ...
func (i InstantDamage) Apply(e entity.Living) {
if i.Potency == 0 {
// Potency of 1 by default.
i.Potency = 1
}
base := 3 << i.Lvl
e.Hurt(float64(base)*i.Potency, damage.SourceInstantDamageEffect{})
}
// WithDuration ...
func (i InstantDamage) WithDuration(d time.Duration) entity.Effect {
return i
}
<file_sep>package effect
import (
"github.com/df-mc/dragonfly/dragonfly/entity"
"image/color"
"time"
)
// SlowFalling is a lasting effect that causes the affected entity to fall very slowly.
type SlowFalling struct {
lastingEffect
}
// WithDuration ...
func (s SlowFalling) WithDuration(d time.Duration) entity.Effect {
return SlowFalling{s.withDuration(d)}
}
// RGBA ...
func (SlowFalling) RGBA() color.RGBA {
return color.RGBA{R: 0xf7, G: 0xf8, B: 0xe0, A: 0xff}
}
<file_sep>package player
import (
"github.com/df-mc/dragonfly/dragonfly/cmd"
"github.com/df-mc/dragonfly/dragonfly/entity/damage"
"github.com/df-mc/dragonfly/dragonfly/entity/healing"
"github.com/df-mc/dragonfly/dragonfly/event"
"github.com/df-mc/dragonfly/dragonfly/item"
"github.com/df-mc/dragonfly/dragonfly/world"
"github.com/go-gl/mathgl/mgl64"
"net"
)
// Handler handles events that are called by a player. Implementations of Handler may be used to listen to
// specific events such as when a player chats or moves.
type Handler interface {
// HandleMove handles the movement of a player. ctx.Cancel() may be called to cancel the movement event.
// The new position, yaw and pitch are passed.
HandleMove(ctx *event.Context, newPos mgl64.Vec3, newYaw, newPitch float64)
// HandleTeleport handles the teleportation of a player. ctx.Cancel() may be called to cancel it.
HandleTeleport(ctx *event.Context, pos mgl64.Vec3)
// HandleChat handles a message sent in the chat by a player. ctx.Cancel() may be called to cancel the
// message being sent in chat.
// The message may be changed by assigning to *message.
HandleChat(ctx *event.Context, message *string)
// HandleFoodLoss handles the food bar of a player depleting naturally, for example because the player was
// sprinting and jumping. ctx.Cancel() may be called to cancel the food points being lost.
HandleFoodLoss(ctx *event.Context, from, to int)
// HandleHeal handles the player being healed by a healing source. ctx.Cancel() may be called to cancel
// the healing.
// The health added may be changed by assigning to *health.
HandleHeal(ctx *event.Context, health *float64, src healing.Source)
// HandleHurt handles the player being hurt by any damage source. ctx.Cancel() may be called to cancel the
// damage being dealt to the player.
// The damage dealt to the player may be changed by assigning to *damage.
HandleHurt(ctx *event.Context, damage *float64, src damage.Source)
// HandleDeath handles the player dying to a particular damage cause.
HandleDeath(src damage.Source)
// HandleRespawn handles the respawning of the player in the world. The spawn position passed may be
// changed by assigning to *pos.
HandleRespawn(pos *mgl64.Vec3)
// HandleStartBreak handles the player starting to break a block at the position passed. ctx.Cancel() may
// be called to stop the player from breaking the block completely.
HandleStartBreak(ctx *event.Context, pos world.BlockPos)
// HandleBlockBreak handles a block that is being broken by a player. ctx.Cancel() may be called to cancel
// the block being broken.
HandleBlockBreak(ctx *event.Context, pos world.BlockPos)
// HandleBlockPlace handles the player placing a specific block at a position in its world. ctx.Cancel()
// may be called to cancel the block being placed.
HandleBlockPlace(ctx *event.Context, pos world.BlockPos, b world.Block)
// HandleItemUse handles the player using an item in the air. It is called for each item, although most
// will not actually do anything. Items such as snowballs may be thrown if HandleItemUse does not cancel
// the context using ctx.Cancel(). It is not called if the player is holding no item.
HandleItemUse(ctx *event.Context)
// HandleItemUseOnBlock handles the player using the item held in its main hand on a block at the block
// position passed. The face of the block clicked is also passed, along with the relative click position.
// The click position has X, Y and Z values which are all in the range 0.0-1.0. It is also called if the
// player is holding no item.
HandleItemUseOnBlock(ctx *event.Context, pos world.BlockPos, face world.Face, clickPos mgl64.Vec3)
// HandleItemUseOnEntity handles the player using the item held in its main hand on an entity passed to
// the method.
// HandleItemUseOnEntity is always called when a player uses an item on an entity, regardless of whether
// the item actually does anything when used on an entity. It is also called if the player is holding no
// item.
HandleItemUseOnEntity(ctx *event.Context, e world.Entity)
// HandleAttackEntity handles the player attacking an entity using the item held in its hand. ctx.Cancel()
// may be called to cancel the attack, which will cancel damage dealt to the target and will stop the
// entity from being knocked back.
// The entity attacked may not be alive (implements entity.Living), in which case no damage will be dealt
// and the target won't be knocked back.
// The entity attacked may also be immune when this method is called, in which case no damage and knock-
// back will be dealt.
HandleAttackEntity(ctx *event.Context, e world.Entity)
// HandleItemDamage handles the event wherein the item either held by the player or as armour takes
// damage through usage.
// The type of the item may be checked to determine whether it was armour or a tool used. The damage to
// the item is passed.
HandleItemDamage(ctx *event.Context, i item.Stack, damage int)
// HandleItemPickup handles the player picking up an item from the ground. The item stack laying on the
// ground is passed. ctx.Cancel() may be called to prevent the player from picking up the item.
HandleItemPickup(ctx *event.Context, i item.Stack)
// HandleTransfer handles a player being transferred to another server. ctx.Cancel() may be called to
// cancel the transfer.
HandleTransfer(ctx *event.Context, addr *net.UDPAddr)
// HandleCommandExecution handles the command execution of a player, who wrote a command in the chat.
// ctx.Cancel() may be called to cancel the command execution.
HandleCommandExecution(ctx *event.Context, command cmd.Command, args []string)
// HandleQuit handles the closing of a player. It is always called when the player is disconnected,
// regardless of the reason.
HandleQuit()
}
// NopHandler implements the Handler interface but does not execute any code when an event is called. The
// default handler of players is set to NopHandler.
// Users may embed NopHandler to avoid having to implement each method.
type NopHandler struct{}
// Compile time check to make sure NopHandler implements Handler.
var _ Handler = (*NopHandler)(nil)
// HandleMove ...
func (NopHandler) HandleMove(*event.Context, mgl64.Vec3, float64, float64) {}
// HandleTeleport ...
func (NopHandler) HandleTeleport(*event.Context, mgl64.Vec3) {}
// HandleCommandExecution ...
func (NopHandler) HandleCommandExecution(*event.Context, cmd.Command, []string) {}
// HandleTransfer ...
func (NopHandler) HandleTransfer(*event.Context, *net.UDPAddr) {}
// HandleChat ...
func (NopHandler) HandleChat(*event.Context, *string) {}
// HandleStartBreak ...
func (NopHandler) HandleStartBreak(*event.Context, world.BlockPos) {}
// HandleBlockBreak ...
func (NopHandler) HandleBlockBreak(*event.Context, world.BlockPos) {}
// HandleBlockPlace ...
func (NopHandler) HandleBlockPlace(*event.Context, world.BlockPos, world.Block) {}
// HandleItemPickup ...
func (NopHandler) HandleItemPickup(*event.Context, item.Stack) {}
// HandleItemUse ...
func (NopHandler) HandleItemUse(*event.Context) {}
// HandleItemUseOnBlock ...
func (NopHandler) HandleItemUseOnBlock(*event.Context, world.BlockPos, world.Face, mgl64.Vec3) {
}
// HandleItemUseOnEntity ...
func (NopHandler) HandleItemUseOnEntity(*event.Context, world.Entity) {}
// HandleItemDamage ...
func (NopHandler) HandleItemDamage(*event.Context, item.Stack, int) {}
// HandleAttackEntity ...
func (NopHandler) HandleAttackEntity(*event.Context, world.Entity) {}
// HandleHurt ...
func (NopHandler) HandleHurt(*event.Context, *float64, damage.Source) {}
// HandleHeal ...
func (NopHandler) HandleHeal(*event.Context, *float64, healing.Source) {}
// HandleFoodLoss ...
func (NopHandler) HandleFoodLoss(*event.Context, int, int) {}
// HandleDeath ...
func (NopHandler) HandleDeath(damage.Source) {}
// HandleRespawn ...
func (NopHandler) HandleRespawn(*mgl64.Vec3) {}
// HandleQuit ...
func (NopHandler) HandleQuit() {}
<file_sep>package effect
import (
"github.com/df-mc/dragonfly/dragonfly/entity"
"image/color"
"time"
)
// Blindness is a lasting effect that greatly reduces the vision range of the entity affected.
type Blindness struct {
lastingEffect
}
// WithDuration ...
func (b Blindness) WithDuration(d time.Duration) entity.Effect {
return Blindness{b.withDuration(d)}
}
// RGBA ...
func (Blindness) RGBA() color.RGBA {
return color.RGBA{R: 0x1f, G: 0x1f, B: 0x23, A: 0xff}
}
<file_sep>package block
const (
hashAir uint64 = iota
hashBeacon
hashBedrock
hashCarpet
hashChest
hashCobblestone
hashConcrete
hashDiamondBlock
hashDirt
hashEmeraldBlock
hashGlass
hashGlazedTerracotta
hashGoldBlock
hashGrass
hashIronBlock
hashKelp
hashLava
hashLeaves
hashLight
hashLog
hashObsidian
hashPlanks
hashSponge
hashStainedTerracotta
hashStone
hashGranite
hashDiorite
hashAndesite
hasAndesite
hashTerracotta
hashWater
hashWoodSlab
hashWoodStairs
hashWool
)
<file_sep>package effect
import (
"github.com/df-mc/dragonfly/dragonfly/entity"
"github.com/df-mc/dragonfly/dragonfly/entity/healing"
"time"
)
// InstantHealth is an instant effect that causes the player that it is applied to to immediately regain some
// health. The amount of health regained depends on the effect level and potency.
type InstantHealth struct {
instantEffect
// Potency specifies the potency of the instant health. By default this value is 1, which means 100% of
// the instant health will be applied to an entity. A lingering health potion, for example, has a potency
// of 0.5: It heals 1 heart (per tick) instead of 2.
Potency float64
}
// Apply instantly heals the entity.Living passed for a bit of health, depending on the effect level and
// potency.
func (i InstantHealth) Apply(e entity.Living) {
if i.Potency == 0 {
// Potency of 1 by default.
i.Potency = 1
}
base := 2 << i.Lvl
e.Heal(float64(base)*i.Potency, healing.SourceInstantHealthEffect{})
}
// WithDuration ...
func (i InstantHealth) WithDuration(d time.Duration) entity.Effect {
return i
}
<file_sep>package effect
import (
"github.com/df-mc/dragonfly/dragonfly/entity"
"reflect"
)
// Register registers an entity.Effect with a specific ID to translate from and to on disk and network. An
// entity.Effect instance may be created by creating a struct instance in this package like
// effect.Regeneration{}.
func Register(id int, e entity.Effect) {
effects[id] = e
effectIds[reflect.TypeOf(e)] = id
}
// init registers all implemented effects.
func init() {
Register(1, Speed{})
Register(2, Slowness{})
Register(3, Haste{})
Register(4, MiningFatigue{})
Register(5, Strength{})
Register(6, InstantHealth{})
Register(7, InstantDamage{})
Register(8, JumpBoost{})
Register(9, Nausea{})
Register(10, Regeneration{})
Register(11, Resistance{})
// TODO: (12) Fire resistance. (Requires fire/lava damage)
Register(13, WaterBreathing{})
Register(14, Invisibility{})
Register(15, Blindness{})
Register(16, NightVision{})
Register(17, Hunger{})
Register(18, Weakness{})
Register(19, Poison{})
Register(20, Wither{})
Register(21, HealthBoost{})
Register(22, Absorption{})
Register(23, Saturation{})
Register(24, Levitation{})
Register(25, FatalPoison{})
Register(26, ConduitPower{})
Register(27, SlowFalling{})
// TODO: (28) Bad omen. (Requires villages ...)
// TODO: (29) Hero of the village. (Requires villages ...)
}
var (
effects = map[int]entity.Effect{}
effectIds = map[reflect.Type]int{}
)
// effectByID attempts to return an effect by the ID it was registered with. If found, the effect found
// is returned and the bool true.
//lint:ignore U1000 Function is used using compiler directives.
//noinspection GoUnusedFunction
func effectByID(id int) (entity.Effect, bool) {
effect, ok := effects[id]
return effect, ok
}
// idByEffect attempts to return the ID an effect was registered with. If found, the id is returned and
// the bool true.
//lint:ignore U1000 Function is used using compiler directives.
//noinspection GoUnusedFunction
func idByEffect(e entity.Effect) (int, bool) {
id, ok := effectIds[reflect.TypeOf(e)]
return id, ok
}
<file_sep>package effect
import (
"github.com/df-mc/dragonfly/dragonfly/entity"
"image/color"
"time"
)
// Hunger is a lasting effect that causes an affected player to gradually lose saturation and food.
type Hunger struct {
lastingEffect
}
// Apply ...
func (h Hunger) Apply(e entity.Living) {
v := float64(h.Lvl) * 0.005
if i, ok := e.(interface {
Exhaust(points float64)
}); ok {
i.Exhaust(v)
}
}
// WithDuration ...
func (h Hunger) WithDuration(d time.Duration) entity.Effect {
return Hunger{h.withDuration(d)}
}
// RGBA ...
func (Hunger) RGBA() color.RGBA {
return color.RGBA{R: 0x58, G: 0x76, B: 0x53, A: 0xff}
}
<file_sep>package block
import (
"github.com/df-mc/dragonfly/dragonfly/entity/physics"
"github.com/df-mc/dragonfly/dragonfly/event"
"github.com/df-mc/dragonfly/dragonfly/world"
"github.com/df-mc/dragonfly/dragonfly/world/sound"
"time"
)
// Lava is a light-emitting fluid block that causes fire damage.
type Lava struct {
noNBT
// Still makes the lava not spread whenever it is updated. Still lava cannot be acquired in the game
// without world editing.
Still bool
// Depth is the depth of the water. This is a number from 1-8, where 8 is a source block and 1 is the
// smallest possible lava block.
Depth int
// Falling specifies if the lava is falling. Falling lava will always appear as a source block, but its
// behaviour differs when it starts spreading.
Falling bool
}
// AABB returns no boxes.
func (Lava) AABB(world.BlockPos, *world.World) []physics.AABB {
return nil
}
// ReplaceableBy ...
func (Lava) ReplaceableBy(world.Block) bool {
return true
}
// HasLiquidDrops ...
func (Lava) HasLiquidDrops() bool {
return false
}
// LightDiffusionLevel always returns 2.
func (Lava) LightDiffusionLevel() uint8 {
return 2
}
// LightEmissionLevel returns 15.
func (Lava) LightEmissionLevel() uint8 {
return 15
}
// NeighbourUpdateTick ...
func (l Lava) NeighbourUpdateTick(pos, _ world.BlockPos, w *world.World) {
if !l.Harden(pos, w, nil) {
w.ScheduleBlockUpdate(pos, time.Second*3/2)
}
}
// ScheduledTick ...
func (l Lava) ScheduledTick(pos world.BlockPos, w *world.World) {
if !l.Harden(pos, w, nil) {
tickLiquid(l, pos, w)
}
}
// LiquidDepth returns the depth of the lava.
func (l Lava) LiquidDepth() int {
return l.Depth
}
// SpreadDecay always returns 2.
func (Lava) SpreadDecay() int {
return 2
}
// WithDepth returns a new Lava block with the depth passed and falling if set to true.
func (l Lava) WithDepth(depth int, falling bool) world.Liquid {
l.Depth = depth
l.Falling = falling
l.Still = false
return l
}
// LiquidFalling checks if the lava is falling.
func (l Lava) LiquidFalling() bool {
return l.Falling
}
// LiquidType returns "lava" as a unique identifier for the lava liquid.
func (Lava) LiquidType() string {
return "lava"
}
// Harden handles the hardening logic of lava.
func (l Lava) Harden(pos world.BlockPos, w *world.World, flownIntoBy *world.BlockPos) bool {
var ok bool
var water, b world.Block
if flownIntoBy == nil {
var water, b world.Block
pos.Neighbours(func(neighbour world.BlockPos) {
if b != nil || neighbour[1] == pos[1]-1 {
return
}
if waterBlock, ok := w.Block(neighbour).(Water); ok {
water = waterBlock
if l.Depth == 8 && !l.Falling {
b = Obsidian{}
return
}
b = Cobblestone{}
}
})
if b != nil {
ctx := event.C()
w.Handler().HandleLiquidHarden(ctx, pos, l, water, b)
ctx.Continue(func() {
w.PlaySound(pos.Vec3Centre(), sound.Fizz{})
w.PlaceBlock(pos, b)
})
return true
}
return false
}
water, ok = w.Block(*flownIntoBy).(Water)
if !ok {
return false
}
if l.Depth == 8 && !l.Falling {
b = Obsidian{}
} else {
b = Cobblestone{}
}
ctx := event.C()
w.Handler().HandleLiquidHarden(ctx, pos, l, water, b)
ctx.Continue(func() {
w.PlaceBlock(pos, b)
w.PlaySound(pos.Vec3Centre(), sound.Fizz{})
})
return true
}
// EncodeBlock ...
func (l Lava) EncodeBlock() (name string, properties map[string]interface{}) {
if l.Depth < 1 || l.Depth > 8 {
panic("invalid lava depth, must be between 1 and 8")
}
v := 8 - l.Depth
if l.Falling {
v += 8
}
if l.Still {
return "minecraft:lava", map[string]interface{}{"liquid_depth": int32(v)}
}
return "minecraft:flowing_lava", map[string]interface{}{"liquid_depth": int32(v)}
}
// Hash ...
func (l Lava) Hash() uint64 {
return hashLava | (uint64(boolByte(l.Falling)) << 32) | (uint64(boolByte(l.Still)) << 33) | (uint64(l.Depth) << 34)
}
// allLava returns a list of all lava states.
func allLava() (b []world.Block) {
f := func(still, falling bool) {
b = append(b, Lava{Still: still, Falling: falling, Depth: 8})
b = append(b, Lava{Still: still, Falling: falling, Depth: 7})
b = append(b, Lava{Still: still, Falling: falling, Depth: 6})
b = append(b, Lava{Still: still, Falling: falling, Depth: 5})
b = append(b, Lava{Still: still, Falling: falling, Depth: 4})
b = append(b, Lava{Still: still, Falling: falling, Depth: 3})
b = append(b, Lava{Still: still, Falling: falling, Depth: 2})
b = append(b, Lava{Still: still, Falling: falling, Depth: 1})
}
f(true, true)
f(true, false)
f(false, false)
f(false, true)
return
}
<file_sep>package block
import (
"github.com/df-mc/dragonfly/dragonfly/item"
"github.com/df-mc/dragonfly/dragonfly/item/tool"
)
// EmeraldBlock is a precious mineral block crafted using 9 emeralds.
type EmeraldBlock struct{ noNBT }
// BreakInfo ...
func (e EmeraldBlock) BreakInfo() BreakInfo {
return BreakInfo{
Hardness: 5,
Harvestable: func(t tool.Tool) bool {
return t.ToolType() == tool.TypePickaxe && t.HarvestLevel() >= tool.TierIron.HarvestLevel
},
Effective: pickaxeEffective,
Drops: simpleDrops(item.NewStack(e, 1)),
}
}
// EncodeItem ...
func (e EmeraldBlock) EncodeItem() (id int32, meta int16) {
return 133, 0
}
// EncodeBlock ...
func (e EmeraldBlock) EncodeBlock() (name string, properties map[string]interface{}) {
return "minecraft:emerald_block", nil
}
// Hash ...
func (EmeraldBlock) Hash() uint64 {
return hashEmeraldBlock
}
<file_sep>package dragonfly
// Config is the configuration of a Dragonfly server. It holds settings that affect different aspects of the
// server, such as its name and maximum players.
type Config struct {
// Network holds settings related to network aspects of the server.
Network struct {
// Address is the address on which the server should listen. Players may connect to this address in
// order to join.
Address string
}
Server struct {
// Name is the name of the server as it shows up in the server list.
Name string
// MaximumPlayers is the maximum amount of players allowed to join the server at the same time. If set
// to 0, the amount of maximum players will grow every time a player joins.
MaximumPlayers int
// ShutdownMessage is the message shown to players when the server shuts down. If empty, players will
// be directed to the menu screen right away.
ShutdownMessage string
}
World struct {
// Name is the name of the world that the server holds. A world with this name will be loaded and
// the name will be displayed at the top of the player list in the in-game pause menu.
Name string
// Folder is the folder that the data of the world resides in.
Folder string
// MaximumChunkRadius is the maximum chunk radius that players may set in their settings. If they try
// to set it above this number, it will be capped and set to the max.
MaximumChunkRadius int
// SimulationDistance is the maximum distance in chunks that a chunk must be to a player in order for
// it to receive random ticks. This field may be set to 0 to disable random block updates altogether.
SimulationDistance int
}
}
// DefaultConfig returns a configuration with the default values filled out.
func DefaultConfig() Config {
c := Config{}
c.Network.Address = ":19132"
c.Server.Name = "Dragonfly Server"
c.Server.ShutdownMessage = "Server closed."
c.World.Name = "World"
c.World.Folder = "world"
c.World.MaximumChunkRadius = 32
c.World.SimulationDistance = 8
return c
}
<file_sep>package inventory
import (
"errors"
"fmt"
"github.com/df-mc/dragonfly/dragonfly/item"
"math"
"strings"
"sync"
)
// Inventory represents an inventory containing items. These inventories may be carried by entities or may be
// held by blocks such as chests.
// The size of an inventory may be specified upon construction, but cannot be changed after. The zero value of
// an inventory is invalid. Use New() to obtain a new inventory.
// Inventory is safe for concurrent usage: Its values are protected by a mutex.
type Inventory struct {
mu sync.RWMutex
slots []item.Stack
f func(slot int, item item.Stack)
canAdd func(s item.Stack, slot int) bool
}
// ErrSlotOutOfRange is returned by any methods on inventory when a slot is passed which is not within the
// range of valid values for the inventory.
var ErrSlotOutOfRange = errors.New("slot is out of range: must be in range 0 <= slot < inventory.Size()")
// New creates a new inventory with the size passed. The inventory size cannot be changed after it has been
// constructed.
// A function may be passed which is called every time a slot is changed. The function may also be nil, if
// nothing needs to be done.
func New(size int, f func(slot int, item item.Stack)) *Inventory {
if size <= 0 {
panic("inventory size must be at least 1")
}
if f == nil {
f = func(slot int, item item.Stack) {}
}
return &Inventory{slots: make([]item.Stack, size), f: f, canAdd: func(s item.Stack, slot int) bool { return true }}
}
// Item attempts to obtain an item from a specific slot in the inventory. If an item was present in that slot,
// the item is returned and the error is nil. If no item was present in the slot, a Stack with air as its item
// and a count of 0 is returned. Stack.Empty() may be called to check if this is the case.
// Item only returns an error if the slot passed is out of range. (0 <= slot < inventory.Size())
func (inv *Inventory) Item(slot int) (item.Stack, error) {
inv.check()
if !inv.validSlot(slot) {
return item.Stack{}, ErrSlotOutOfRange
}
inv.mu.RLock()
i := inv.slots[slot]
inv.mu.RUnlock()
return i, nil
}
// SetItem sets a stack of items to a specific slot in the inventory. If an item is already present in the
// slot, that item will be overwritten.
// SetItem will return an error if the slot passed is out of range. (0 <= slot < inventory.Size())
func (inv *Inventory) SetItem(slot int, item item.Stack) error {
inv.check()
if !inv.validSlot(slot) {
return ErrSlotOutOfRange
}
inv.mu.Lock()
f := inv.setItem(slot, item)
inv.mu.Unlock()
f()
return nil
}
// All returns the full content of the inventory, copying all items into a new slice.
func (inv *Inventory) All() []item.Stack {
r := make([]item.Stack, inv.Size())
inv.mu.RLock()
copy(r, inv.slots)
inv.mu.RUnlock()
return r
}
// AddItem attempts to add an item to the inventory. It does so in a couple of steps: It first iterates over
// the inventory to make sure no existing stacks of the same type exist. If these stacks do exist, the item
// added is first added on top of those stacks to make sure they are fully filled.
// If no existing stacks with leftover space are left, empty slots will be filled up with the remainder of the
// item added.
// If the item could not be fully added to the inventory, an error is returned along with the count that was
// added to the inventory.
func (inv *Inventory) AddItem(it item.Stack) (n int, err error) {
if it.Empty() {
return 0, nil
}
first := it.Count()
inv.mu.Lock()
for slot, invIt := range inv.slots {
if invIt.Empty() {
// This slot was empty, and we should first try to add the item stack to existing stacks.
continue
}
a, b := invIt.AddStack(it)
f := inv.setItem(slot, a)
//noinspection GoDeferInLoop
defer f()
it = b
if it.Empty() {
inv.mu.Unlock()
// We were able to add the entire stack to existing stacks in the inventory.
return first, nil
}
}
for slot, invIt := range inv.slots {
if !invIt.Empty() {
// We can only use empty slots now: All existing stacks have already been filled up.
continue
}
a, b := it.Grow(-math.MaxInt32).AddStack(it)
f := inv.setItem(slot, a)
//noinspection GoDeferInLoop
defer f()
it = b
if it.Empty() {
inv.mu.Unlock()
// We were able to add the entire stack to empty slots.
return first, nil
}
}
inv.mu.Unlock()
// We were unable to clear out the entire stack to be added to the inventory: There wasn't enough space.
return first - it.Count(), fmt.Errorf("could not add full item stack to inventory")
}
// RemoveItem attempts to remove an item from the inventory. It will visit all slots in the inventory and
// empties them until it.Count() items have been removed from the inventory.
// If less than it.Count() items could be found in the inventory, an error is returned.
func (inv *Inventory) RemoveItem(it item.Stack) error {
toRemove := it.Count()
inv.mu.Lock()
for slot, slotIt := range inv.slots {
if slotIt.Empty() {
continue
}
if !slotIt.Comparable(it) {
// The items were not comparable: Continue with the next slot.
continue
}
f := inv.setItem(slot, slotIt.Grow(-toRemove))
//noinspection GoDeferInLoop
defer f()
toRemove -= slotIt.Count()
if toRemove <= 0 {
// No more items left to remove: We can exit the loop.
inv.mu.Unlock()
return nil
}
}
if toRemove <= 0 {
inv.mu.Unlock()
return nil
}
inv.mu.Unlock()
return fmt.Errorf("could not remove all items from the inventory")
}
// Contents returns a list of all contents of the inventory. This method excludes air items, so the method
// only ever returns item stacks which actually represent an item.
func (inv *Inventory) Contents() []item.Stack {
contents := make([]item.Stack, 0, inv.Size())
inv.mu.RLock()
for _, it := range inv.slots {
if !it.Empty() {
contents = append(contents, it)
}
}
inv.mu.RUnlock()
return contents
}
// Empty checks if the inventory is fully empty: It iterates over the inventory and makes sure every stack in
// it is empty.
func (inv *Inventory) Empty() bool {
inv.mu.RLock()
defer inv.mu.RUnlock()
for _, it := range inv.slots {
if !it.Empty() {
return false
}
}
return true
}
// Clear clears the entire inventory. All items are removed.
func (inv *Inventory) Clear() {
inv.mu.Lock()
for slot := range inv.slots {
f := inv.setItem(slot, item.Stack{})
//noinspection GoDeferInLoop
defer f()
}
inv.mu.Unlock()
}
// setItem sets an item to a specific slot and overwrites the existing item. It calls the function which is
// called for every item change and does so without locking the inventory.
func (inv *Inventory) setItem(slot int, item item.Stack) func() {
if !inv.canAdd(item, slot) {
return func() {}
}
if item.Count() > item.MaxCount() {
item = item.Grow(item.MaxCount() - item.Count())
}
inv.slots[slot] = item
return func() {
inv.f(slot, item)
}
}
// Size returns the size of the inventory. It is always the same value as that passed in the call to New() and
// is always at least 1.
func (inv *Inventory) Size() int {
inv.mu.RLock()
l := len(inv.slots)
inv.mu.RUnlock()
return l
}
// Close closes the inventory, freeing the function called for every slot change. It also clears any items
// that may currently be in the inventory.
// The returned error is always nil.
func (inv *Inventory) Close() error {
inv.Clear()
inv.mu.Lock()
inv.f = func(int, item.Stack) {}
inv.mu.Unlock()
return nil
}
// String implements the fmt.Stringer interface.
func (inv *Inventory) String() string {
s := make([]string, 0, inv.Size())
inv.mu.RLock()
for _, it := range inv.slots {
s = append(s, it.String())
}
inv.mu.RUnlock()
return "{" + strings.Join(s, ", ") + "}"
}
// validSlot checks if the slot passed is valid for the inventory. It returns false if the slot is either
// smaller than 0 or bigger/equal to the size of the inventory's size.
func (inv *Inventory) validSlot(slot int) bool {
return slot >= 0 && slot < inv.Size()
}
// check panics if the inventory is valid, and panics if it is not. This typically happens if the inventory
// was not created using New().
func (inv *Inventory) check() {
if inv.Size() == 0 {
panic("uninitialised inventory: inventory must be constructed using inventory.New()")
}
}
<file_sep>package bossbar
import (
"fmt"
"strings"
)
// BossBar represents a boss bar that may be sent to a player. It is shown as a purple bar with text above
// it. The health shown by the bar may be changed.
type BossBar struct {
text string
health float64
}
// New creates a new boss bar with the text passed. The text is formatted according to the rules of
// fmt.Sprintln.
// By default, the boss bar will have a full health bar. To change this, use BossBar.SetHealthPercentage().
func New(text ...interface{}) BossBar {
return BossBar{text: format(text), health: 1}
}
// Text returns the text of the boss bar: The text passed when creating the bar using New().
func (bar BossBar) Text() string {
return bar.text
}
// WithHealthPercentage sets the health percentage of the boss bar. The value passed must be between 0 and 1.
// If a value out of that range is passed, SetHealthPercentage panics.
// The new BossBar with the changed health percentage is returned.
func (bar BossBar) WithHealthPercentage(v float64) BossBar {
if v < 0 || v > 1 {
panic("boss bar: value out of range: health percentage must be between 0.0 and 1.0")
}
bar.health = v
return bar
}
// HealthPercentage returns the health percentage of the boss bar. The number returned is a value between 0
// and 1, with 0 being an empty boss bar and 1 being a full one.
func (bar BossBar) HealthPercentage() float64 {
return bar.health
}
// format is a utility function to format a list of values to have spaces between them, but no newline at the
// end, which is typically used for sending messages, popups and tips.
func format(a []interface{}) string {
return strings.TrimSuffix(fmt.Sprintln(a...), "\n")
}
<file_sep>package block
import (
"github.com/df-mc/dragonfly/dragonfly/item/tool"
)
// Glass is a decorative, fully transparent solid block that can be dyed into stained glass.
type Glass struct{ noNBT }
// BreakInfo ...
func (g Glass) BreakInfo() BreakInfo {
return BreakInfo{
Hardness: 0.3,
Drops: simpleDrops(),
Harvestable: func(t tool.Tool) bool {
return true
},
Effective: nothingEffective,
}
}
// EncodeItem ...
func (g Glass) EncodeItem() (id int32, meta int16) {
return 20, 0
}
// EncodeBlock ...
func (g Glass) EncodeBlock() (name string, properties map[string]interface{}) {
return "minecraft:glass", nil
}
// Hash ...
func (Glass) Hash() uint64 {
return hashGlass
}
<file_sep>package block
import (
"github.com/df-mc/dragonfly/dragonfly/item"
)
type (
// Stone is a block found underground in the world or on mountains.
Stone struct{ noNBT }
// Granite is a type of igneous rock.
Granite polishable
// Diorite is a type of igneous rock.
Diorite polishable
// Andesite is a type of igneous rock.
Andesite polishable
// polishable forms the base of blocks that may be polished.
polishable struct {
noNBT
// Polished specifies if the block is polished or not. When set to true, the block will represent its
// polished variant, for example polished andesite.
Polished bool
}
)
var stoneBreakInfo = BreakInfo{
Hardness: 1.5,
Harvestable: pickaxeHarvestable,
Effective: pickaxeEffective,
Drops: simpleDrops(item.NewStack(Cobblestone{}, 1)),
}
// BreakInfo ...
func (s Stone) BreakInfo() BreakInfo {
return stoneBreakInfo
}
// BreakInfo ...
func (g Granite) BreakInfo() BreakInfo {
i := stoneBreakInfo
i.Drops = simpleDrops(item.NewStack(g, 1))
return i
}
// BreakInfo ...
func (d Diorite) BreakInfo() BreakInfo {
i := stoneBreakInfo
i.Drops = simpleDrops(item.NewStack(d, 1))
return i
}
// BreakInfo ...
func (a Andesite) BreakInfo() BreakInfo {
i := stoneBreakInfo
i.Drops = simpleDrops(item.NewStack(a, 1))
return i
}
// EncodeItem ...
func (s Stone) EncodeItem() (id int32, meta int16) {
return 1, 0
}
// EncodeItem ...
func (a Andesite) EncodeItem() (id int32, meta int16) {
if a.Polished {
return 1, 6
}
return 1, 5
}
// EncodeItem ...
func (d Diorite) EncodeItem() (id int32, meta int16) {
if d.Polished {
return 1, 4
}
return 1, 3
}
// EncodeItem ...
func (g Granite) EncodeItem() (id int32, meta int16) {
if g.Polished {
return 1, 2
}
return 1, 1
}
// EncodeBlock ...
func (Stone) EncodeBlock() (name string, properties map[string]interface{}) {
return "minecraft:stone", map[string]interface{}{"stone_type": "stone"}
}
// Hash ...
func (Stone) Hash() uint64 {
return hashStone
}
// EncodeBlock ...
func (a Andesite) EncodeBlock() (name string, properties map[string]interface{}) {
if a.Polished {
return "minecraft:stone", map[string]interface{}{"stone_type": "andesite_smooth"}
}
return "minecraft:stone", map[string]interface{}{"stone_type": "andesite"}
}
// Hash ...
func (a Andesite) Hash() uint64 {
return hashAndesite | (uint64(boolByte(a.Polished)) << 32)
}
// EncodeBlock ...
func (d Diorite) EncodeBlock() (name string, properties map[string]interface{}) {
if d.Polished {
return "minecraft:stone", map[string]interface{}{"stone_type": "diorite_smooth"}
}
return "minecraft:stone", map[string]interface{}{"stone_type": "diorite"}
}
// Hash ...
func (d Diorite) Hash() uint64 {
return hashDiorite | (uint64(boolByte(d.Polished)) << 32)
}
// EncodeBlock ...
func (g Granite) EncodeBlock() (name string, properties map[string]interface{}) {
if g.Polished {
return "minecraft:stone", map[string]interface{}{"stone_type": "granite_smooth"}
}
return "minecraft:stone", map[string]interface{}{"stone_type": "granite"}
}
// Hash ...
func (g Granite) Hash() uint64 {
return hashGranite | (uint64(boolByte(g.Polished)) << 32)
}
<file_sep>package effect
import (
"github.com/df-mc/dragonfly/dragonfly/entity"
"image/color"
"time"
)
// Invisibility is a lasting effect that causes the affected entity to turn invisible. While invisible, the
// entity's armour is still visible and effect particles will still be displayed.
type Invisibility struct {
lastingEffect
}
// Start ...
func (Invisibility) Start(e entity.Living) {
if i, ok := e.(interface {
SetInvisible()
SetVisible()
}); ok {
i.SetInvisible()
}
}
// End ...
func (Invisibility) End(e entity.Living) {
if i, ok := e.(interface {
SetInvisible()
SetVisible()
}); ok {
i.SetVisible()
}
}
// WithDuration ...
func (i Invisibility) WithDuration(d time.Duration) entity.Effect {
return Invisibility{i.withDuration(d)}
}
// RGBA ...
func (Invisibility) RGBA() color.RGBA {
return color.RGBA{R: 0x7f, G: 0x83, B: 0x92, A: 0xff}
}
<file_sep>package block
import "github.com/df-mc/dragonfly/dragonfly/item"
// Dirt is a block found abundantly in most biomes under a layer of grass blocks at the top of the normal
// world.
type Dirt struct {
noNBT
// Coarse specifies if the dirt should be off the coarse dirt variant. Grass blocks won't spread on
// the block if set to true.
Coarse bool
}
// BreakInfo ...
func (d Dirt) BreakInfo() BreakInfo {
return BreakInfo{
Hardness: 0.5,
Harvestable: alwaysHarvestable,
Effective: shovelEffective,
Drops: simpleDrops(item.NewStack(d, 1)),
}
}
// EncodeItem ...
func (d Dirt) EncodeItem() (id int32, meta int16) {
if d.Coarse {
meta = 1
}
return 3, meta
}
// EncodeBlock ...
func (d Dirt) EncodeBlock() (name string, properties map[string]interface{}) {
if d.Coarse {
return "minecraft:dirt", map[string]interface{}{"dirt_type": "coarse"}
}
return "minecraft:dirt", map[string]interface{}{"dirt_type": "normal"}
}
// Hash ...
func (d Dirt) Hash() uint64 {
return hashDirt | (uint64(boolByte(d.Coarse)) << 32)
}
<file_sep>package inventory
import (
"fmt"
"github.com/df-mc/dragonfly/dragonfly/item"
)
// Armour represents an inventory for armour. It has 4 slots, one for a helmet, chestplate, leggings and
// boots respectively. NewArmour() must be used to create a valid armour inventory.
// Armour inventories, like normal Inventories, are safe for concurrent usage.
type Armour struct {
inv *Inventory
}
// NewArmour returns an armour inventory that is ready to be used. The zero value of an inventory.Armour is
// not valid for usage.
// The function passed is called when a slot is changed. It may be nil to not call anything.
func NewArmour(f func(slot int, item item.Stack)) *Armour {
inv := New(4, f)
inv.canAdd = canAddArmour
return &Armour{inv: inv}
}
// canAddArmour checks if the item passed can be worn as armour in the slot passed.
func canAddArmour(s item.Stack, slot int) bool {
ok := s.Empty()
if ok {
return true
}
i := s.Item()
switch slot {
case 0:
_, ok = i.(item.Helmet)
// TODO: Allow turtle helmets, pumpkins and mob skulls here.
case 1:
_, ok = i.(item.Chestplate)
// TODO: Allow elytra here.
case 2:
_, ok = i.(item.Leggings)
case 3:
_, ok = i.(item.Boots)
}
return ok
}
// SetHelmet sets the item stack passed as the helmet in the inventory.
func (a *Armour) SetHelmet(helmet item.Stack) {
_ = a.inv.SetItem(0, helmet)
}
// Helmet returns the item stack set as helmet in the inventory.
func (a *Armour) Helmet() item.Stack {
i, _ := a.inv.Item(0)
return i
}
// SetChestplate sets the item stack passed as the chestplate in the inventory.
func (a *Armour) SetChestplate(chestplate item.Stack) {
_ = a.inv.SetItem(1, chestplate)
}
// Chestplate returns the item stack set as chestplate in the inventory.
func (a *Armour) Chestplate() item.Stack {
i, _ := a.inv.Item(1)
return i
}
// SetLeggings sets the item stack passed as the leggings in the inventory.
func (a *Armour) SetLeggings(leggings item.Stack) {
_ = a.inv.SetItem(2, leggings)
}
// Leggings returns the item stack set as leggings in the inventory.
func (a *Armour) Leggings() item.Stack {
i, _ := a.inv.Item(2)
return i
}
// SetBoots sets the item stack passed as the boots in the inventory.
func (a *Armour) SetBoots(boots item.Stack) {
_ = a.inv.SetItem(3, boots)
}
// Boots returns the item stack set as boots in the inventory.
func (a *Armour) Boots() item.Stack {
i, _ := a.inv.Item(3)
return i
}
// All returns all items (including) air of the armour inventory in the order of helmet, chestplate, leggings,
// boots.
func (a *Armour) All() []item.Stack {
return a.inv.All()
}
// Clear clears the armour inventory, removing all items currently present.
func (a *Armour) Clear() {
a.inv.Clear()
}
// String converts the armour to a readable string representation.
func (a *Armour) String() string {
return fmt.Sprintf("{helmet: %v, chestplate: %v, leggings: %v, boots: %v}", a.Helmet(), a.Chestplate(), a.Leggings(), a.Boots())
}
// Inv returns the underlying Inventory instance.
func (a *Armour) Inv() *Inventory {
return a.inv
}
// Close closes the armour inventory, removing the slot change function.
func (a *Armour) Close() error {
return a.inv.Close()
}
<file_sep>package block
import (
"github.com/df-mc/dragonfly/dragonfly/block/colour"
"github.com/df-mc/dragonfly/dragonfly/block/wood"
"github.com/df-mc/dragonfly/dragonfly/internal/item_internal"
"github.com/df-mc/dragonfly/dragonfly/world"
_ "unsafe" // Imported for compiler directives.
)
// init registers all blocks implemented by Dragonfly.
func init() {
// Always register Air first so we can use 0 runtime IDs as air.
world.RegisterBlock(Air{})
world.RegisterBlock(Stone{})
world.RegisterBlock(Granite{}, Granite{Polished: true})
world.RegisterBlock(Diorite{}, Diorite{Polished: true})
world.RegisterBlock(Andesite{}, Andesite{Polished: true})
world.RegisterBlock(Grass{}, Grass{Path: true})
world.RegisterBlock(Dirt{}, Dirt{Coarse: true})
world.RegisterBlock(Cobblestone{}, Cobblestone{Mossy: true})
world.RegisterBlock(allKelp()...)
world.RegisterBlock(allLogs()...)
world.RegisterBlock(allLeaves()...)
world.RegisterBlock(Bedrock{}, Bedrock{InfiniteBurning: true})
world.RegisterBlock(Chest{Facing: world.East}, Chest{Facing: world.West}, Chest{Facing: world.North}, Chest{Facing: world.South})
world.RegisterBlock(allConcrete()...)
world.RegisterBlock(allLight()...)
world.RegisterBlock(allPlanks()...)
world.RegisterBlock(allWoodStairs()...)
world.RegisterBlock(allWoodSlabs()...)
world.RegisterBlock(allWater()...)
world.RegisterBlock(allLava()...)
world.RegisterBlock(Obsidian{})
world.RegisterBlock(DiamondBlock{})
world.RegisterBlock(Glass{})
world.RegisterBlock(EmeraldBlock{})
world.RegisterBlock(GoldBlock{})
world.RegisterBlock(IronBlock{})
world.RegisterBlock(Beacon{})
world.RegisterBlock(Sponge{})
world.RegisterBlock(Sponge{Wet: true})
world.RegisterBlock(allStainedTerracotta()...)
world.RegisterBlock(allGlazedTerracotta()...)
world.RegisterBlock(Terracotta{})
world.RegisterBlock(allCarpets()...)
world.RegisterBlock(allWool()...)
}
func init() {
world.RegisterItem("minecraft:air", Air{})
world.RegisterItem("minecraft:stone", Stone{})
world.RegisterItem("minecraft:stone", Granite{})
world.RegisterItem("minecraft:stone", Granite{Polished: true})
world.RegisterItem("minecraft:stone", Diorite{})
world.RegisterItem("minecraft:stone", Diorite{Polished: true})
world.RegisterItem("minecraft:stone", Andesite{})
world.RegisterItem("minecraft:stone", Andesite{Polished: true})
world.RegisterItem("minecraft:grass", Grass{})
world.RegisterItem("minecraft:grass_path", Grass{Path: true})
world.RegisterItem("minecraft:dirt", Dirt{})
world.RegisterItem("minecraft:dirt", Dirt{Coarse: true})
world.RegisterItem("minecraft:cobblestone", Cobblestone{})
world.RegisterItem("minecraft:bedrock", Bedrock{})
world.RegisterItem("minecraft:kelp", Kelp{})
world.RegisterItem("minecraft:log", Log{Wood: wood.Oak()})
world.RegisterItem("minecraft:log", Log{Wood: wood.Spruce()})
world.RegisterItem("minecraft:log", Log{Wood: wood.Birch()})
world.RegisterItem("minecraft:log", Log{Wood: wood.Jungle()})
world.RegisterItem("minecraft:leaves", Leaves{Wood: wood.Oak()})
world.RegisterItem("minecraft:leaves", Leaves{Wood: wood.Spruce()})
world.RegisterItem("minecraft:leaves", Leaves{Wood: wood.Birch()})
world.RegisterItem("minecraft:leaves", Leaves{Wood: wood.Jungle()})
world.RegisterItem("minecraft:chest", Chest{})
world.RegisterItem("minecraft:mossy_cobblestone", Cobblestone{Mossy: true})
world.RegisterItem("minecraft:leaves2", Leaves{Wood: wood.Acacia()})
world.RegisterItem("minecraft:leaves2", Leaves{Wood: wood.DarkOak()})
world.RegisterItem("minecraft:log2", Log{Wood: wood.Acacia()})
world.RegisterItem("minecraft:log2", Log{Wood: wood.DarkOak()})
world.RegisterItem("minecraft:stripped_spruce_log", Log{Wood: wood.Spruce(), Stripped: true})
world.RegisterItem("minecraft:stripped_birch_log", Log{Wood: wood.Birch(), Stripped: true})
world.RegisterItem("minecraft:stripped_jungle_log", Log{Wood: wood.Jungle(), Stripped: true})
world.RegisterItem("minecraft:stripped_acacia_log", Log{Wood: wood.Acacia(), Stripped: true})
world.RegisterItem("minecraft:stripped_dark_oak_log", Log{Wood: wood.DarkOak(), Stripped: true})
world.RegisterItem("minecraft:stripped_oak_log", Log{Wood: wood.Oak(), Stripped: true})
for _, c := range colour.All() {
world.RegisterItem("minecraft:concrete", Concrete{Colour: c})
world.RegisterItem("minecraft:stained_hardened_clay", StainedTerracotta{Colour: c})
world.RegisterItem("minecraft:carpet", Carpet{Colour: c})
world.RegisterItem("minecraft:wool", Wool{Colour: c})
colourName := c.String()
if c == colour.LightGrey() {
colourName = "silver"
}
world.RegisterItem("minecraft:"+colourName+"_glazed_terracotta", GlazedTerracotta{Colour: c})
}
for _, b := range allLight() {
world.RegisterItem("minecraft:light_block", b.(world.Item))
}
for _, b := range allPlanks() {
world.RegisterItem("minecraft:planks", b.(world.Item))
}
world.RegisterItem("minecraft:oak_stairs", WoodStairs{Wood: wood.Oak()})
world.RegisterItem("minecraft:spruce_stairs", WoodStairs{Wood: wood.Spruce()})
world.RegisterItem("minecraft:birch_stairs", WoodStairs{Wood: wood.Birch()})
world.RegisterItem("minecraft:jungle_stairs", WoodStairs{Wood: wood.Jungle()})
world.RegisterItem("minecraft:acacia_stairs", WoodStairs{Wood: wood.Acacia()})
world.RegisterItem("minecraft:dark_oak_stairs", WoodStairs{Wood: wood.DarkOak()})
world.RegisterItem("minecraft:wooden_slab", WoodSlab{Wood: wood.Oak()})
world.RegisterItem("minecraft:wooden_slab", WoodSlab{Wood: wood.Spruce()})
world.RegisterItem("minecraft:wooden_slab", WoodSlab{Wood: wood.Birch()})
world.RegisterItem("minecraft:wooden_slab", WoodSlab{Wood: wood.Jungle()})
world.RegisterItem("minecraft:wooden_slab", WoodSlab{Wood: wood.Acacia()})
world.RegisterItem("minecraft:wooden_slab", WoodSlab{Wood: wood.DarkOak()})
world.RegisterItem("minecraft:double_wooden_slab", WoodSlab{Wood: wood.Oak(), Double: true})
world.RegisterItem("minecraft:double_wooden_slab", WoodSlab{Wood: wood.Spruce(), Double: true})
world.RegisterItem("minecraft:double_wooden_slab", WoodSlab{Wood: wood.Birch(), Double: true})
world.RegisterItem("minecraft:double_wooden_slab", WoodSlab{Wood: wood.Jungle(), Double: true})
world.RegisterItem("minecraft:double_wooden_slab", WoodSlab{Wood: wood.Acacia(), Double: true})
world.RegisterItem("minecraft:double_wooden_slab", WoodSlab{Wood: wood.DarkOak(), Double: true})
world.RegisterItem("minecraft:obsidian", Obsidian{})
world.RegisterItem("minecraft:diamond_block", DiamondBlock{})
world.RegisterItem("minecraft:glass", Glass{})
world.RegisterItem("minecraft:emerald_block", EmeraldBlock{})
world.RegisterItem("minecraft:gold_block", GoldBlock{})
world.RegisterItem("minecraft:iron_block", IronBlock{})
world.RegisterItem("minecraft:beacon", Beacon{})
world.RegisterItem("minecraft:sponge", Sponge{})
world.RegisterItem("minecraft:wet_sponge", Sponge{Wet: true})
world.RegisterItem("minecraft:hardened_clay", Terracotta{})
}
func init() {
item_internal.Air = Air{}
item_internal.Grass = Grass{}
item_internal.GrassPath = Grass{Path: true}
item_internal.IsUnstrippedLog = func(b world.Block) bool {
l, ok := b.(Log)
return ok && !l.Stripped
}
item_internal.StripLog = func(b world.Block) world.Block {
l := b.(Log)
l.Stripped = true
return l
}
item_internal.Lava = Lava{Depth: 8, Still: true}
item_internal.Water = Water{Depth: 8, Still: true}
item_internal.IsWater = func(b world.Liquid) bool {
_, ok := b.(Water)
return ok
}
item_internal.Replaceable = replaceable
}
// readSlice reads an interface slice from a map at the key passed.
//noinspection GoCommentLeadingSpace
func readSlice(m map[string]interface{}, key string) []interface{} {
//lint:ignore S1005 Double assignment is done explicitly to prevent panics.
v, _ := m[key]
b, _ := v.([]interface{})
return b
}
// readString reads a string from a map at the key passed.
//noinspection GoCommentLeadingSpace
func readString(m map[string]interface{}, key string) string {
//lint:ignore S1005 Double assignment is done explicitly to prevent panics.
v, _ := m[key]
b, _ := v.(string)
return b
}
<file_sep>package dragonfly
import (
"encoding/base64"
"errors"
"fmt"
_ "github.com/df-mc/dragonfly/dragonfly/item" // Imported for compiler directives.
"github.com/df-mc/dragonfly/dragonfly/player"
"github.com/df-mc/dragonfly/dragonfly/player/skin"
"github.com/df-mc/dragonfly/dragonfly/session"
"github.com/df-mc/dragonfly/dragonfly/world"
"github.com/df-mc/dragonfly/dragonfly/world/generator"
"github.com/df-mc/dragonfly/dragonfly/world/mcdb"
"github.com/go-gl/mathgl/mgl32"
"github.com/go-gl/mathgl/mgl64"
"github.com/google/uuid"
"github.com/sandertv/gophertunnel/minecraft"
"github.com/sandertv/gophertunnel/minecraft/protocol"
"github.com/sandertv/gophertunnel/minecraft/protocol/login"
"github.com/sandertv/gophertunnel/minecraft/text"
"github.com/sirupsen/logrus"
"go.uber.org/atomic"
"log"
"os"
"os/signal"
"sync"
"syscall"
"time"
_ "unsafe" // Imported for compiler directives.
)
// Server implements a Dragonfly server. It runs the main server loop and handles the connections of players
// trying to join the server.
type Server struct {
started atomic.Bool
name atomic.String
c Config
log *logrus.Logger
listener *minecraft.Listener
world *world.World
players chan *player.Player
startTime time.Time
playerMutex sync.RWMutex
// p holds a map of all players currently connected to the server. When they leave, they are removed from
// the map.
p map[uuid.UUID]*player.Player
}
// New returns a new server using the Config passed. If nil is passed, a default configuration is returned.
// (A call to dragonfly.DefaultConfig().)
// The Logger passed will be used to log errors and information to. If nil is passed, a default Logger is
// used by calling logrus.New().
// Note that no two servers should be active at the same time. Doing so anyway will result in unexpected
// behaviour.
func New(c *Config, log *logrus.Logger) *Server {
if log == nil {
log = logrus.New()
}
if c == nil {
conf := DefaultConfig()
c = &conf
}
s := &Server{
c: *c,
log: log,
players: make(chan *player.Player),
world: world.New(log, c.World.SimulationDistance),
p: make(map[uuid.UUID]*player.Player),
name: *atomic.NewString(c.Server.Name),
}
return s
}
// Accept accepts an incoming player into the server. It blocks until a player connects to the server.
// Accept returns an error if the Server is closed using a call to Close.
func (server *Server) Accept() (*player.Player, error) {
p, ok := <-server.players
if !ok {
return nil, errors.New("server closed")
}
server.playerMutex.Lock()
server.p[p.UUID()] = p
server.playerMutex.Unlock()
return p, nil
}
// World returns the world of the server. Players will be spawned in this world and this world will be read
// from and written to when the world is edited.
func (server *Server) World() *world.World {
return server.world
}
// Run runs the server and blocks until it is closed using a call to Close(). When called, the server will
// accept incoming connections. Run will block the current goroutine until the server is stopped. To start
// the server on a different goroutine, use (*Server).Start() instead.
// After a call to Run, calls to Server.Accept() may be made to accept players into the server.
func (server *Server) Run() error {
if !server.started.CAS(false, true) {
panic("server already running")
}
server.log.Info("Starting server...")
server.loadWorld()
if err := server.startListening(); err != nil {
return err
}
item_registerVanillaCreativeItems()
world_registerAllStates()
server.run()
return nil
}
// Start runs the server but does not block, unlike Run, but instead accepts connections on a different
// goroutine. Connections will be accepted until the listener is closed using a call to Close.
// One started, players may be accepted using Server.Accept().
func (server *Server) Start() error {
if !server.started.CAS(false, true) {
panic("server already running")
}
server.log.Info("Starting server...")
server.loadWorld()
if err := server.startListening(); err != nil {
return err
}
item_registerVanillaCreativeItems()
world_registerAllStates()
go server.run()
return nil
}
// Uptime returns the duration that the server has been running for. Measurement starts the moment a call to
// Server.Start or Server.Run is made.
func (server *Server) Uptime() time.Duration {
if !server.running() {
return 0
}
return time.Since(server.startTime)
}
// PlayerCount returns the current player count of the server. It is equivalent to calling
// len(server.Players()).
func (server *Server) PlayerCount() int {
server.playerMutex.RLock()
defer server.playerMutex.RUnlock()
return len(server.p)
}
// MaxPlayerCount returns the maximum amount of players that are allowed to play on the server at the same
// time. Players trying to join when the server is full will be refused to enter.
// If the config has a maximum player count set to 0, MaxPlayerCount will return Server.PlayerCount + 1.
func (server *Server) MaxPlayerCount() int {
if server.c.Server.MaximumPlayers == 0 {
return server.PlayerCount() + 1
}
return server.c.Server.MaximumPlayers
}
// Players returns a list of all players currently connected to the server. Note that the slice returned is
// not updated when new players join or leave, so it is only valid for as long as no new players join or
// players leave.
func (server *Server) Players() []*player.Player {
server.playerMutex.RLock()
defer server.playerMutex.RUnlock()
players := make([]*player.Player, 0, len(server.p))
for _, p := range server.p {
players = append(players, p)
}
return players
}
// Player looks for a player on the server with the UUID passed. If found, the player is returned and the bool
// returns holds a true value. If not, the bool returned is false and the player is nil.
func (server *Server) Player(uuid uuid.UUID) (*player.Player, bool) {
server.playerMutex.RLock()
defer server.playerMutex.RUnlock()
if p, ok := server.p[uuid]; ok {
return p, true
}
return nil, false
}
// SetNamef sets the name of the Server, also known as the MOTD. This name is displayed in the server list.
// The formatting of the name passed follows the rules of fmt.Sprintf.
func (server *Server) SetNamef(format string, a ...interface{}) {
server.name.Store(fmt.Sprintf(format, a...))
}
// SetName sets the name of the Server, also known as the MOTD. This name is displayed in the server list.
// The formatting of the name passed follows the rules of fmt.Sprint.
func (server *Server) SetName(a ...interface{}) {
server.name.Store(fmt.Sprint(a...))
}
// Close closes the server, making any call to Run/Accept cancel immediately.
func (server *Server) Close() error {
if !server.running() {
panic("server not yet running")
}
server.log.Info("Server shutting down...")
defer server.log.Info("Server stopped.")
server.log.Debug("Disconnecting players...")
server.playerMutex.RLock()
for _, p := range server.p {
p.Disconnect(text.Yellow()(server.c.Server.ShutdownMessage))
}
server.playerMutex.RUnlock()
server.log.Debug("Closing world...")
if err := server.world.Close(); err != nil {
return err
}
server.log.Debug("Closing listener...")
return server.listener.Close()
}
// CloseOnProgramEnd closes the server right before the program ends, so that all data of the server are
// saved properly.
func (server *Server) CloseOnProgramEnd() {
c := make(chan os.Signal, 2)
signal.Notify(c, syscall.SIGINT, syscall.SIGTERM)
go func() {
<-c
if err := server.Close(); err != nil {
server.log.Errorf("error shutting down server: %v", err)
}
}()
}
// running checks if the server is currently running.
func (server *Server) running() bool {
return server.started.Load()
}
// startListening starts making the EncodeBlock listener listen, accepting new connections from players.
func (server *Server) startListening() error {
server.startTime = time.Now()
w := server.log.Writer()
defer func() {
_ = w.Close()
}()
server.listener = &minecraft.Listener{
// We wrap a log.Logger around our Logrus logger so that it will print in the same format as the
// normal Logrus logger would.
ErrorLog: log.New(w, "", 0),
ServerName: server.c.Server.Name,
MaximumPlayers: server.c.Server.MaximumPlayers,
}
//noinspection SpellCheckingInspection
if err := server.listener.Listen("raknet", server.c.Network.Address); err != nil {
return fmt.Errorf("listening on address failed: %w", err)
}
server.listener.StatusProvider(statusProvider{s: server})
server.log.Infof("Server running on %v.\n", server.listener.Addr())
return nil
}
// run runs the server, continuously accepting new connections from players. It returns when the server is
// closed by a call to Close.
func (server *Server) run() {
server.World().Generator(generator.Flat{})
for {
c, err := server.listener.Accept()
if err != nil {
// Accept will only return an error if the Listener was closed, meaning trying to continue
// listening is futile.
close(server.players)
return
}
go server.handleConn(c.(*minecraft.Conn))
}
}
// handleConn handles an incoming connection accepted from the Listener.
func (server *Server) handleConn(conn *minecraft.Conn) {
//noinspection SpellCheckingInspection
data := minecraft.GameData{
WorldName: server.c.World.Name,
Blocks: server.blockEntries(),
PlayerPosition: vec64To32(server.world.Spawn().Vec3Centre()),
PlayerGameMode: 1,
// We set these IDs to 1, because that's how the session will treat them.
EntityUniqueID: 1,
EntityRuntimeID: 1,
Time: int64(server.world.Time()),
GameRules: map[string]interface{}{"naturalregeneration": false},
Difficulty: 2,
ServerAuthoritativeMovement: true,
ServerAuthoritativeInventory: true,
}
if err := conn.StartGame(data); err != nil {
_ = server.listener.Disconnect(conn, "Connection timeout.")
server.log.Debugf("connection %v failed spawning: %v\n", conn.RemoteAddr(), err)
return
}
id, err := uuid.Parse(conn.IdentityData().Identity)
if err != nil {
_ = conn.Close()
server.log.Warnf("connection %v has a malformed UUID ('%v')\n", conn.RemoteAddr(), id)
return
}
server.players <- server.createPlayer(id, conn)
}
// handleSessionClose handles the closing of a session. It removes the player of the session from the server.
func (server *Server) handleSessionClose(controllable session.Controllable) {
server.playerMutex.Lock()
delete(server.p, controllable.UUID())
server.playerMutex.Unlock()
}
// createPlayer creates a new player instance using the UUID and connection passed.
func (server *Server) createPlayer(id uuid.UUID, conn *minecraft.Conn) *player.Player {
s := session.New(conn, server.c.World.MaximumChunkRadius, server.log)
p := player.NewWithSession(conn.IdentityData().DisplayName, conn.IdentityData().XUID, id, server.createSkin(conn.ClientData()), s, server.world.Spawn().Vec3Middle())
s.Start(p, server.world, server.handleSessionClose)
return p
}
// loadWorld loads the world of the server, ending the program if the world could not be loaded.
func (server *Server) loadWorld() {
server.log.Debug("Loading world...")
p, err := mcdb.New(server.c.World.Folder)
if err != nil {
server.log.Fatalf("error loading world: %v", err)
}
server.world.Provider(p)
server.log.Debugf("Loaded world '%v'.", server.world.Name())
}
// createSkin creates a new skin using the skin data found in the client data in the login, and returns it.
func (server *Server) createSkin(data login.ClientData) skin.Skin {
// gopher tunnel guarantees the following values are valid data and are of the correct size.
skinData, _ := base64.StdEncoding.DecodeString(data.SkinData)
modelData, _ := base64.StdEncoding.DecodeString(data.SkinGeometry)
skinResourcePatch, _ := base64.StdEncoding.DecodeString(data.SkinResourcePatch)
modelConfig, _ := skin.DecodeModelConfig(skinResourcePatch)
playerSkin := skin.New(data.SkinImageWidth, data.SkinImageHeight)
playerSkin.Persona = data.PersonaSkin
playerSkin.Pix = skinData
playerSkin.Model = modelData
playerSkin.ModelConfig = modelConfig
for _, animation := range data.AnimatedImageData {
var t skin.AnimationType
switch animation.Type {
case protocol.SkinAnimationHead:
t = skin.AnimationHead
case protocol.SkinAnimationBody32x32:
t = skin.AnimationBody32x32
case protocol.SkinAnimationBody128x128:
t = skin.AnimationBody128x128
}
anim := skin.NewAnimation(animation.ImageWidth, animation.ImageHeight, t)
anim.FrameCount = int(animation.Frames)
anim.Pix, _ = base64.StdEncoding.DecodeString(animation.Image)
playerSkin.Animations = append(playerSkin.Animations, anim)
}
return playerSkin
}
// blockEntries loads a list of all block state entries of the server, ready to be sent in the StartGame
// packet.
func (server *Server) blockEntries() (entries []interface{}) {
for _, b := range world_allBlocks() {
name, properties := b.EncodeBlock()
entries = append(entries, map[string]interface{}{
"block": map[string]interface{}{
"version": protocol.CurrentBlockVersion,
"name": name,
"states": properties,
},
})
}
return
}
// vec64To32 converts a mgl64.Vec3 to a mgl32.Vec3.
func vec64To32(vec3 mgl64.Vec3) mgl32.Vec3 {
return mgl32.Vec3{float32(vec3[0]), float32(vec3[1]), float32(vec3[2])}
}
//go:linkname world_registerAllStates github.com/df-mc/dragonfly/dragonfly/world.registerAllStates
//noinspection ALL
func world_registerAllStates()
//go:linkname item_registerVanillaCreativeItems github.com/df-mc/dragonfly/dragonfly/item.registerVanillaCreativeItems
//noinspection ALL
func item_registerVanillaCreativeItems()
//go:linkname world_allBlocks github.com/df-mc/dragonfly/dragonfly/world.allBlocks
//noinspection ALL
func world_allBlocks() []world.Block
<file_sep>package entity
import (
"image/color"
"reflect"
"sync"
"time"
)
// Effect represents an effect that may be added to a living entity. Effects may either be instant or last
// for a specific duration.
type Effect interface {
// Instant checks if the effect is instance. If it is instant, the effect will only be ticked a single
// time when added to an entity.
Instant() bool
// Apply applies the effect to an entity. For instant effects, this method applies the effect once, such
// as healing the Living entity for instant health.
Apply(e Living)
// Level returns the level of the effect. A higher level generally means a more powerful effect.
Level() int
// Duration returns the leftover duration of the effect.
Duration() time.Duration
// WithDuration returns the effect with a duration passed.
WithDuration(d time.Duration) Effect
// RGBA returns the colour of the effect. If multiple effects are present, the colours will be mixed
// together to form a new colour.
RGBA() color.RGBA
// ShowParticles checks if the particle should show particles. If not, entities that have the effect
// will not display particles around them.
ShowParticles() bool
// AmbientSource specifies if the effect came from an ambient source, such as a beacon or conduit. The
// particles will be less visible when this is true.
AmbientSource() bool
// Start is called for lasting events. It is sent the first time the effect is applied to an entity.
Start(e Living)
// End is called for lasting events. It is sent the moment the effect expires.
End(e Living)
}
// EffectManager manages the effects of an entity. The effect manager will only store effects that last for
// a specific duration. Instant effects are applied instantly and not stored.
type EffectManager struct {
mu sync.Mutex
effects map[reflect.Type]Effect
}
// NewEffectManager creates and returns a new initialised EffectManager.
func NewEffectManager() *EffectManager {
return &EffectManager{effects: map[reflect.Type]Effect{}}
}
// Add adds an effect to the manager. If the effect is instant, it is applied to the Living entity passed
// immediately. If not, the effect is added to the EffectManager and is applied to the entity every time the
// Tick method is called.
// Effect levels of 0 or below will not do anything.
func (m *EffectManager) Add(e Effect, entity Living) {
m.mu.Lock()
defer m.mu.Unlock()
if e.Level() <= 0 {
return
}
if e.Instant() {
e.Apply(entity)
return
}
t := reflect.TypeOf(e)
existing, ok := m.effects[t]
if !ok {
m.effects[t] = e
e.Start(entity)
return
}
if existing.Level() > e.Level() || (existing.Level() == e.Level() && existing.Duration() > e.Duration()) {
return
}
m.effects[t] = e
e.Start(entity)
}
// Remove removes any Effect present in the EffectManager with the type of the effect passed.
func (m *EffectManager) Remove(e Effect, entity Living) {
m.mu.Lock()
defer m.mu.Unlock()
t := reflect.TypeOf(e)
if existing, ok := m.effects[t]; ok {
existing.End(entity)
}
delete(m.effects, t)
}
// Effects returns a list of all effects currently present in the effect manager. This will never include
// effects that have expired.
func (m *EffectManager) Effects() []Effect {
m.mu.Lock()
defer m.mu.Unlock()
e := make([]Effect, 0, len(m.effects))
for _, effect := range m.effects {
e = append(e, effect)
}
return e
}
// Tick ticks the EffectManager, applying all of its effects to the Living entity passed when applicable and
// removing expired effects.
func (m *EffectManager) Tick(entity Living) {
m.mu.Lock()
e := make([]Effect, 0, len(m.effects))
for i, effect := range m.effects {
e = append(e, effect)
m.effects[i] = effect.WithDuration(effect.Duration() - time.Second/20)
if m.expired(effect) {
delete(m.effects, i)
effect.End(entity)
continue
}
}
m.mu.Unlock()
for _, effect := range e {
effect.Apply(entity)
}
}
// expired checks if an Effect has expired.
func (m *EffectManager) expired(e Effect) bool {
return e.Duration() <= 0
}
<file_sep>package block
import (
"github.com/df-mc/dragonfly/dragonfly/item"
"github.com/df-mc/dragonfly/dragonfly/item/tool"
"github.com/df-mc/dragonfly/dragonfly/world"
"math"
"time"
)
// Breakable represents a block that may be broken by a player in survival mode. Blocks not include are blocks
// such as bedrock.
type Breakable interface {
// BreakInfo returns information of the block related to the breaking of it.
BreakInfo() BreakInfo
}
// BreakDuration returns the base duration that breaking the block passed takes when being broken using the
// item passed.
func BreakDuration(b world.Block, i item.Stack) time.Duration {
breakable, ok := b.(Breakable)
if !ok {
return math.MaxInt64
}
t, ok := i.Item().(tool.Tool)
if !ok {
t = tool.None{}
}
info := breakable.BreakInfo()
breakTime := info.Hardness * 5
if info.Harvestable(t) {
breakTime = info.Hardness * 1.5
}
if info.Effective(t) {
breakTime /= t.BaseMiningEfficiency(b)
}
// TODO: Account for haste, efficiency etc here.
timeInTicksAccurate := math.Round(breakTime/0.05) * 0.05
return (time.Duration(math.Round(timeInTicksAccurate*20)) * time.Second) / 20
}
// BreaksInstantly checks if the block passed can be broken instantly using the item stack passed to break
// it.
func BreaksInstantly(b world.Block, i item.Stack) bool {
breakable, ok := b.(Breakable)
if !ok {
return false
}
hardness := breakable.BreakInfo().Hardness
if hardness == 0 {
return true
}
t, ok := i.Item().(tool.Tool)
if !ok || !breakable.BreakInfo().Effective(t) {
return false
}
// TODO: Account for haste, efficiency etc here.
efficiencyVal := 0.0
hasteVal := 0.0
return (t.BaseMiningEfficiency(b)+efficiencyVal)*hasteVal >= hardness*30
}
// BreakInfo is a struct returned by every block. It holds information on block breaking related data, such as
// the tool type and tier required to break it.
type BreakInfo struct {
// Hardness is the hardness of the block, which influences the speed with which the block may be mined.
Hardness float64
// Harvestable is a function called to check if the block is harvestable using the tool passed. If the
// item used to break the block is not a tool, a tool.None is passed.
Harvestable func(t tool.Tool) bool
// Effective is a function called to check if the block can be mined more effectively with the tool passed
// than with an empty hand.
Effective func(t tool.Tool) bool
// Drops is a function called to get the drops of the block if it is broken using the tool passed. If the
// item used to break the block is not a tool, a tool.None is passed.
Drops func(t tool.Tool) []item.Stack
}
// neverEffective is a convenience function for blocks that are mined the same by all tools.
var neverEffective = func(t tool.Tool) bool {
return true
}
// pickaxeEffective is a convenience function for blocks that are effectively mined with a pickaxe.
var pickaxeEffective = func(t tool.Tool) bool {
return t.ToolType() == tool.TypePickaxe
}
// axeEffective is a convenience function for blocks that are effectively mined with an axe.
var axeEffective = func(t tool.Tool) bool {
return t.ToolType() == tool.TypeAxe
}
// shearsEffective is a convenience function for blocks that are effectively mined with shears.
var shearsEffective = func(t tool.Tool) bool {
return t.ToolType() == tool.TypeShears
}
// shovelEffective is a convenience function for blocks that are effectively mined with an axe.
var shovelEffective = func(t tool.Tool) bool {
return t.ToolType() == tool.TypeShovel
}
// nothingEffective is a convenience function for blocks that cannot be mined efficiently with any tool.
var nothingEffective = func(tool.Tool) bool {
return false
}
// alwaysHarvestable is a convenience function for blocks that are harvestable using any item.
var alwaysHarvestable = func(t tool.Tool) bool {
return true
}
// pickaxeHarvestable is a convenience function for blocks that are harvestable using any kind of pickaxe.
var pickaxeHarvestable = pickaxeEffective
// simpleDrops returns a drops function that returns the items passed.
func simpleDrops(s ...item.Stack) func(t tool.Tool) []item.Stack {
return func(t tool.Tool) []item.Stack {
return s
}
}
<file_sep>package block
import (
"github.com/df-mc/dragonfly/dragonfly/block/colour"
"github.com/df-mc/dragonfly/dragonfly/item"
"github.com/df-mc/dragonfly/dragonfly/world"
)
// Concrete is a solid block which comes in the 16 regular dye colors, created by placing concrete powder
// adjacent to water.
type Concrete struct {
noNBT
// Colour is the colour of the concrete block.
Colour colour.Colour
}
// BreakInfo ...
func (c Concrete) BreakInfo() BreakInfo {
return BreakInfo{
Hardness: 1.8,
Harvestable: pickaxeHarvestable,
Effective: pickaxeEffective,
Drops: simpleDrops(item.NewStack(c, 1)),
}
}
// EncodeItem ...
func (c Concrete) EncodeItem() (id int32, meta int16) {
return 236, int16(c.Colour.Uint8())
}
// EncodeBlock ...
func (c Concrete) EncodeBlock() (name string, properties map[string]interface{}) {
return "minecraft:concrete", map[string]interface{}{"color": c.Colour.String()}
}
// Hash ...
func (c Concrete) Hash() uint64 {
return hashConcrete | (uint64(c.Colour.Uint8()) << 32)
}
// allConcrete returns concrete blocks with all possible colours.
func allConcrete() []world.Block {
b := make([]world.Block, 0, 16)
for _, c := range colour.All() {
b = append(b, Concrete{Colour: c})
}
return b
}
<file_sep>package effect
import (
"github.com/df-mc/dragonfly/dragonfly/entity"
"image/color"
"time"
)
// NightVision is a lasting effect that causes the affected entity to see in dark places as though they were
// fully lit up.
type NightVision struct {
lastingEffect
}
// WithDuration ...
func (n NightVision) WithDuration(d time.Duration) entity.Effect {
return NightVision{n.withDuration(d)}
}
// RGBA ...
func (NightVision) RGBA() color.RGBA {
return color.RGBA{R: 0x1f, G: 0x1f, B: 0xa1, A: 0xff}
}
<file_sep>package effect
import (
"github.com/df-mc/dragonfly/dragonfly/entity"
"image/color"
"time"
)
// Slowness is a lasting effect that decreases the movement speed of a living entity by 15% for each level
// that the effect has.
type Slowness struct {
lastingEffect
}
// Start ...
func (s Slowness) Start(e entity.Living) {
slowness := 1 - float64(s.Lvl)*0.15
if slowness <= 0 {
slowness = 0.00001
}
e.SetSpeed(e.Speed() * slowness)
}
// Stop ...
func (s Slowness) Stop(e entity.Living) {
slowness := 1 - float64(s.Lvl)*0.15
if slowness <= 0 {
slowness = 0.00001
}
e.SetSpeed(e.Speed() / slowness)
}
// WithDuration ...
func (s Slowness) WithDuration(d time.Duration) entity.Effect {
return Slowness{s.withDuration(d)}
}
// RGBA ...
func (Slowness) RGBA() color.RGBA {
return color.RGBA{R: 0x5a, G: 0x6c, B: 0x81, A: 0xff}
}
<file_sep>package session
import (
"bytes"
"github.com/cespare/xxhash"
"github.com/df-mc/dragonfly/dragonfly/block"
blockAction "github.com/df-mc/dragonfly/dragonfly/block/action"
"github.com/df-mc/dragonfly/dragonfly/entity"
"github.com/df-mc/dragonfly/dragonfly/entity/action"
"github.com/df-mc/dragonfly/dragonfly/entity/state"
"github.com/df-mc/dragonfly/dragonfly/item"
"github.com/df-mc/dragonfly/dragonfly/item/inventory"
"github.com/df-mc/dragonfly/dragonfly/world"
"github.com/df-mc/dragonfly/dragonfly/world/chunk"
"github.com/df-mc/dragonfly/dragonfly/world/particle"
"github.com/df-mc/dragonfly/dragonfly/world/sound"
"github.com/go-gl/mathgl/mgl32"
"github.com/go-gl/mathgl/mgl64"
"github.com/google/uuid"
"github.com/sandertv/gophertunnel/minecraft/nbt"
"github.com/sandertv/gophertunnel/minecraft/protocol"
"github.com/sandertv/gophertunnel/minecraft/protocol/packet"
)
// ViewChunk ...
func (s *Session) ViewChunk(pos world.ChunkPos, c *chunk.Chunk, blockEntities map[world.BlockPos]world.Block) {
if !s.conn.ClientCacheEnabled() {
s.sendNetworkChunk(pos, c, blockEntities)
return
}
s.sendBlobHashes(pos, c, blockEntities)
}
// sendBlobHashes sends chunk blob hashes of the data of the chunk and stores the data in a map of blobs. Only
// data that the client doesn't yet have will be sent over the network.
func (s *Session) sendBlobHashes(pos world.ChunkPos, c *chunk.Chunk, blockEntities map[world.BlockPos]world.Block) {
data := chunk.DiskEncode(c, true)
count := byte(0)
for y := byte(0); y < 16; y++ {
if data.SubChunks[y] != nil {
count = y + 1
}
}
blobs := make([][]byte, 0, count+1)
for y := byte(0); y < count; y++ {
if data.SubChunks[y] == nil {
blobs = append(blobs, []byte{chunk.SubChunkVersion, 0})
continue
}
blobs = append(blobs, data.SubChunks[y])
}
blobs = append(blobs, data.Data2D[512:])
m := make(map[uint64]struct{}, len(blobs))
hashes := make([]uint64, len(blobs))
for i, blob := range blobs {
h := xxhash.Sum64(blob)
hashes[i] = h
m[h] = struct{}{}
}
s.blobMu.Lock()
s.openChunkTransactions = append(s.openChunkTransactions, m)
if len(s.blobs) > 4096 {
s.blobMu.Unlock()
s.log.Errorf("player %v has too many blobs pending %v: disconnecting", s.c.Name(), len(s.blobs))
_ = s.c.Close()
return
}
for i, hash := range hashes {
s.blobs[hash] = blobs[i]
}
s.blobMu.Unlock()
raw := bytes.NewBuffer(make([]byte, 1, 32))
enc := nbt.NewEncoderWithEncoding(raw, nbt.NetworkLittleEndian)
for pos, b := range blockEntities {
data := b.(world.NBTer).EncodeNBT()
data["x"], data["y"], data["z"] = int32(pos[0]), int32(pos[1]), int32(pos[2])
_ = enc.Encode(enc)
}
s.writePacket(&packet.LevelChunk{
ChunkX: pos[0],
ChunkZ: pos[1],
SubChunkCount: uint32(count),
CacheEnabled: true,
BlobHashes: hashes,
RawPayload: raw.Bytes(),
})
}
// sendNetworkChunk sends a network encoded chunk to the client.
func (s *Session) sendNetworkChunk(pos world.ChunkPos, c *chunk.Chunk, blockEntities map[world.BlockPos]world.Block) {
data := chunk.NetworkEncode(c)
count := byte(0)
for y := byte(0); y < 16; y++ {
if data.SubChunks[y] != nil {
count = y + 1
}
}
for y := byte(0); y < count; y++ {
if data.SubChunks[y] == nil {
_ = s.chunkBuf.WriteByte(chunk.SubChunkVersion)
// We write zero here, meaning the sub chunk has no block storages: The sub chunk is completely
// empty.
_ = s.chunkBuf.WriteByte(0)
continue
}
_, _ = s.chunkBuf.Write(data.SubChunks[y])
}
_, _ = s.chunkBuf.Write(data.Data2D)
_, _ = s.chunkBuf.Write(data.BlockNBT)
enc := nbt.NewEncoderWithEncoding(s.chunkBuf, nbt.NetworkLittleEndian)
for pos, b := range blockEntities {
data := b.(world.NBTer).EncodeNBT()
data["x"], data["y"], data["z"] = int32(pos[0]), int32(pos[1]), int32(pos[2])
_ = enc.Encode(enc)
}
s.writePacket(&packet.LevelChunk{
ChunkX: pos[0],
ChunkZ: pos[1],
SubChunkCount: uint32(count),
RawPayload: append([]byte(nil), s.chunkBuf.Bytes()...),
})
s.chunkBuf.Reset()
}
// ViewEntity ...
func (s *Session) ViewEntity(e world.Entity) {
if s.entityRuntimeID(e) == selfEntityRuntimeID {
return
}
var runtimeID uint64
s.entityMutex.Lock()
_, controllable := e.(Controllable)
if id, ok := s.entityRuntimeIDs[e]; ok && controllable {
runtimeID = id
} else {
runtimeID = s.currentEntityRuntimeID.Add(1)
s.entityRuntimeIDs[e] = runtimeID
s.entities[runtimeID] = e
}
s.entityMutex.Unlock()
switch v := e.(type) {
case Controllable:
s.writePacket(&packet.PlayerSkin{
UUID: v.UUID(),
Skin: skinToProtocol(v.Skin()),
})
s.writePacket(&packet.AddPlayer{
UUID: v.UUID(),
Username: v.Name(),
EntityUniqueID: int64(runtimeID),
EntityRuntimeID: runtimeID,
Position: vec64To32(e.Position()),
Pitch: float32(e.Pitch()),
Yaw: float32(e.Yaw()),
HeadYaw: float32(e.Yaw()),
})
case *entity.Item:
s.writePacket(&packet.AddItemActor{
EntityUniqueID: int64(runtimeID),
EntityRuntimeID: runtimeID,
Item: stackFromItem(v.Item()),
Position: vec64To32(v.Position()),
})
default:
s.writePacket(&packet.AddActor{
EntityUniqueID: int64(runtimeID),
EntityRuntimeID: runtimeID,
// TODO: Add methods for entity types.
EntityType: "",
Position: vec64To32(e.Position()),
Pitch: float32(e.Pitch()),
Yaw: float32(e.Yaw()),
HeadYaw: float32(e.Yaw()),
})
}
}
// HideEntity ...
func (s *Session) HideEntity(e world.Entity) {
if s.entityRuntimeID(e) == selfEntityRuntimeID {
return
}
s.entityMutex.Lock()
id, ok := s.entityRuntimeIDs[e]
if _, controllable := e.(Controllable); !controllable {
delete(s.entityRuntimeIDs, e)
delete(s.entities, s.entityRuntimeIDs[e])
}
s.entityMutex.Unlock()
if !ok {
// The entity was already removed some other way. We don't need to send a packet.
return
}
s.writePacket(&packet.RemoveActor{EntityUniqueID: int64(id)})
}
// ViewEntityMovement ...
func (s *Session) ViewEntityMovement(e world.Entity, deltaPos mgl64.Vec3, deltaYaw, deltaPitch float64) {
id := s.entityRuntimeID(e)
if id == selfEntityRuntimeID {
return
}
switch e.(type) {
case Controllable:
s.writePacket(&packet.MovePlayer{
EntityRuntimeID: id,
Position: vec64To32(e.Position().Add(deltaPos).Add(mgl64.Vec3{0, entityOffset(e)})),
Pitch: float32(e.Pitch() + deltaPitch),
Yaw: float32(e.Yaw() + deltaYaw),
HeadYaw: float32(e.Yaw() + deltaYaw),
OnGround: e.OnGround(),
})
default:
flags := byte(0)
if e.OnGround() {
flags |= packet.MoveFlagOnGround
}
s.writePacket(&packet.MoveActorAbsolute{
EntityRuntimeID: id,
Position: vec64To32(e.Position().Add(deltaPos).Add(mgl64.Vec3{0, entityOffset(e)})),
Rotation: vec64To32(mgl64.Vec3{e.Pitch() + deltaPitch, e.Yaw() + deltaYaw}),
Flags: flags,
})
}
}
// entityOffset returns the offset that entities have client-side.
func entityOffset(e world.Entity) float64 {
switch e.(type) {
case Controllable:
return 1.62
case *entity.Item:
return 0.125
}
return 0
}
// ViewTime ...
func (s *Session) ViewTime(time int) {
s.writePacket(&packet.SetTime{Time: int32(time)})
}
// ViewEntityTeleport ...
func (s *Session) ViewEntityTeleport(e world.Entity, position mgl64.Vec3) {
id := s.entityRuntimeID(e)
if id == selfEntityRuntimeID {
s.chunkLoader.Move(position)
s.teleportMu.Lock()
s.teleportPos = &position
s.teleportMu.Unlock()
}
switch e.(type) {
case Controllable:
s.writePacket(&packet.MovePlayer{
EntityRuntimeID: id,
Position: vec64To32(position.Add(mgl64.Vec3{0, entityOffset(e)})),
Pitch: float32(e.Pitch()),
Yaw: float32(e.Yaw()),
HeadYaw: float32(e.Yaw()),
Mode: packet.MoveModeTeleport,
})
default:
s.writePacket(&packet.MoveActorAbsolute{
EntityRuntimeID: id,
Position: vec64To32(position.Add(mgl64.Vec3{0, entityOffset(e)})),
Rotation: vec64To32(mgl64.Vec3{e.Pitch(), e.Yaw()}),
Flags: packet.MoveFlagTeleport,
})
}
}
// ViewEntityItems ...
func (s *Session) ViewEntityItems(e world.Entity) {
runtimeID := s.entityRuntimeID(e)
if runtimeID == selfEntityRuntimeID {
// Don't view the items of the entity if the entity is the Controllable of the session.
return
}
c, ok := e.(item.Carrier)
if !ok {
return
}
mainHand, offHand := c.HeldItems()
// Show the main hand item.
s.writePacket(&packet.MobEquipment{
EntityRuntimeID: runtimeID,
NewItem: stackFromItem(mainHand),
})
// Show the off-hand item.
s.writePacket(&packet.MobEquipment{
EntityRuntimeID: runtimeID,
NewItem: stackFromItem(offHand),
WindowID: protocol.WindowIDOffHand,
})
}
// ViewEntityArmour ...
func (s *Session) ViewEntityArmour(e world.Entity) {
runtimeID := s.entityRuntimeID(e)
if runtimeID == selfEntityRuntimeID {
// Don't view the items of the entity if the entity is the Controllable of the session.
return
}
armoured, ok := e.(item.Armoured)
if !ok {
return
}
inv := armoured.Armour()
// Show the main hand item.
s.writePacket(&packet.MobArmourEquipment{
EntityRuntimeID: runtimeID,
Helmet: stackFromItem(inv.Helmet()),
Chestplate: stackFromItem(inv.Chestplate()),
Leggings: stackFromItem(inv.Leggings()),
Boots: stackFromItem(inv.Boots()),
})
}
// ViewParticle ...
func (s *Session) ViewParticle(pos mgl64.Vec3, p world.Particle) {
switch pa := p.(type) {
case particle.BlockForceField:
s.writePacket(&packet.LevelEvent{
EventType: packet.EventParticleBlockForceField,
Position: vec64To32(pos),
})
case particle.BlockBreak:
s.writePacket(&packet.LevelEvent{
EventType: packet.EventParticleDestroy,
Position: vec64To32(pos),
EventData: int32(s.blockRuntimeID(pa.Block)),
})
case particle.PunchBlock:
s.writePacket(&packet.LevelEvent{
EventType: packet.EventParticlePunchBlock,
Position: vec64To32(pos),
EventData: int32(s.blockRuntimeID(pa.Block)) | (int32(pa.Face) << 24),
})
}
}
// ViewSound ...
func (s *Session) ViewSound(pos mgl64.Vec3, soundType world.Sound) {
pk := &packet.LevelSoundEvent{
Position: vec64To32(pos),
EntityType: ":",
ExtraData: -1,
}
switch so := soundType.(type) {
case sound.Deny:
pk.SoundType = packet.SoundEventDeny
case sound.BlockPlace:
pk.SoundType, pk.ExtraData = packet.SoundEventPlace, int32(s.blockRuntimeID(so.Block))
case sound.ChestClose:
pk.SoundType = packet.SoundEventChestClosed
case sound.ChestOpen:
pk.SoundType = packet.SoundEventChestOpen
case sound.BlockBreaking:
pk.SoundType, pk.ExtraData = packet.SoundEventHit, int32(s.blockRuntimeID(so.Block))
case sound.ItemBreak:
pk.SoundType = packet.SoundEventBreak
case sound.ItemUseOn:
pk.SoundType, pk.ExtraData = packet.SoundEventItemUseOn, int32(s.blockRuntimeID(so.Block))
case sound.Fizz:
pk.SoundType = packet.SoundEventFizz
case sound.Attack:
pk.SoundType, pk.EntityType = packet.SoundEventAttackStrong, "minecraft:player"
if !so.Damage {
pk.SoundType = packet.SoundEventAttackNoDamage
}
case sound.BucketFill:
if _, water := so.Liquid.(block.Water); water {
pk.SoundType = packet.SoundEventBucketFillWater
break
}
pk.SoundType = packet.SoundEventBucketFillLava
case sound.BucketEmpty:
if _, water := so.Liquid.(block.Water); water {
pk.SoundType = packet.SoundEventBucketEmptyWater
break
}
pk.SoundType = packet.SoundEventBucketEmptyLava
}
s.writePacket(pk)
}
// ViewBlockUpdate ...
func (s *Session) ViewBlockUpdate(pos world.BlockPos, b world.Block, layer int) {
runtimeID, _ := world.BlockRuntimeID(b)
blockPos := protocol.BlockPos{int32(pos[0]), int32(pos[1]), int32(pos[2])}
s.writePacket(&packet.UpdateBlock{
Position: blockPos,
NewBlockRuntimeID: runtimeID,
Flags: packet.BlockUpdateNetwork,
Layer: uint32(layer),
})
if v, ok := b.(world.NBTer); ok {
s.writePacket(&packet.BlockActorData{
Position: blockPos,
NBTData: v.EncodeNBT(),
})
}
}
// ViewEntityAction ...
func (s *Session) ViewEntityAction(e world.Entity, a action.Action) {
switch act := a.(type) {
case action.SwingArm:
if _, ok := e.(Controllable); ok {
if s.entityRuntimeID(e) == selfEntityRuntimeID && s.swingingArm.Load() {
return
}
s.writePacket(&packet.Animate{
ActionType: packet.AnimateActionSwingArm,
EntityRuntimeID: s.entityRuntimeID(e),
})
return
}
s.writePacket(&packet.ActorEvent{
EntityRuntimeID: s.entityRuntimeID(e),
EventType: packet.ActorEventStartAttack,
})
case action.Hurt:
s.writePacket(&packet.ActorEvent{
EntityRuntimeID: s.entityRuntimeID(e),
EventType: packet.ActorEventHurt,
})
case action.Death:
s.writePacket(&packet.ActorEvent{
EntityRuntimeID: s.entityRuntimeID(e),
EventType: packet.ActorEventDeath,
})
case action.PickedUp:
s.writePacket(&packet.TakeItemActor{
ItemEntityRuntimeID: s.entityRuntimeID(e),
TakerEntityRuntimeID: s.entityRuntimeID(act.Collector.(world.Entity)),
})
}
}
// ViewEntityState ...
func (s *Session) ViewEntityState(e world.Entity, states []state.State) {
m := defaultEntityMetadata(e)
for _, eState := range states {
switch st := eState.(type) {
case state.Sneaking:
m.setFlag(dataKeyFlags, dataFlagSneaking)
case state.Sprinting:
m.setFlag(dataKeyFlags, dataFlagSprinting)
case state.Breathing:
m.setFlag(dataKeyFlags, dataFlagBreathing)
case state.Invisible:
m.setFlag(dataKeyFlags, dataFlagInvisible)
case state.Swimming:
m.setFlag(dataKeyFlags, dataFlagSwimming)
case state.Named:
m[dataKeyNameTag] = st.NameTag
case state.EffectBearing:
m[dataKeyPotionColour] = (int32(st.ParticleColour.A) << 24) | (int32(st.ParticleColour.R) << 16) | (int32(st.ParticleColour.G) << 8) | int32(st.ParticleColour.B)
if st.Ambient {
m[dataKeyPotionAmbient] = byte(1)
} else {
m[dataKeyPotionAmbient] = byte(0)
}
}
}
s.writePacket(&packet.SetActorData{
EntityRuntimeID: s.entityRuntimeID(e),
EntityMetadata: m,
})
}
// OpenBlockContainer ...
func (s *Session) OpenBlockContainer(pos world.BlockPos) {
s.closeCurrentContainer()
b, ok := s.c.World().Block(pos).(block.Container)
if !ok {
// The block was no container.
return
}
b.AddViewer(s, s.c.World(), pos)
nextID := s.nextWindowID()
s.containerOpened.Store(true)
s.openedWindow.Store(b.Inventory())
s.openedPos.Store(pos)
var containerType byte
switch b.(type) {
}
s.writePacket(&packet.ContainerOpen{
WindowID: nextID,
ContainerType: containerType,
ContainerPosition: protocol.BlockPos{int32(pos[0]), int32(pos[1]), int32(pos[2])},
ContainerEntityUniqueID: -1,
})
s.sendInv(b.Inventory(), uint32(nextID))
}
// ViewSlotChange ...
func (s *Session) ViewSlotChange(slot int, newItem item.Stack) {
if !s.containerOpened.Load() {
return
}
if s.inTransaction.Load() {
// Don't send slot changes to the player itself.
return
}
s.writePacket(&packet.InventorySlot{
WindowID: s.openedWindowID.Load(),
Slot: uint32(slot),
NewItem: instanceFromItem(newItem),
})
}
// ViewBlockAction ...
func (s *Session) ViewBlockAction(pos world.BlockPos, a blockAction.Action) {
blockPos := protocol.BlockPos{int32(pos[0]), int32(pos[1]), int32(pos[2])}
switch t := a.(type) {
case blockAction.Open:
s.writePacket(&packet.BlockEvent{
Position: blockPos,
EventType: packet.BlockEventChangeChestState,
EventData: 1,
})
case blockAction.Close:
s.writePacket(&packet.BlockEvent{
Position: blockPos,
EventType: packet.BlockEventChangeChestState,
})
case blockAction.StartCrack:
s.writePacket(&packet.LevelEvent{
EventType: packet.EventBlockStartBreak,
Position: vec64To32(pos.Vec3()),
EventData: int32(65535 / (t.BreakTime.Seconds() * 20)),
})
case blockAction.StopCrack:
s.writePacket(&packet.LevelEvent{
EventType: packet.EventBlockStopBreak,
Position: vec64To32(pos.Vec3()),
EventData: 0,
})
case blockAction.ContinueCrack:
s.writePacket(&packet.LevelEvent{
EventType: 3602,
Position: vec64To32(pos.Vec3()),
EventData: int32(65535 / (t.BreakTime.Seconds() * 20)),
})
}
}
// ViewEmote ...
func (s *Session) ViewEmote(player world.Entity, emote uuid.UUID) {
s.writePacket(&packet.Emote{
EntityRuntimeID: s.entityRuntimeID(player),
EmoteID: emote.String(),
Flags: packet.EmoteFlagServerSide,
})
}
// nextWindowID produces the next window ID for a new window. It is an int of 1-99.
func (s *Session) nextWindowID() byte {
if s.openedWindowID.CAS(99, 1) {
return 1
}
return byte(s.openedWindowID.Add(1))
}
// closeWindow closes the container window currently opened. If no window is open, closeWindow will do
// nothing.
func (s *Session) closeWindow() {
if !s.containerOpened.CAS(true, false) {
return
}
s.openedWindow.Store(inventory.New(1, nil))
s.writePacket(&packet.ContainerClose{WindowID: byte(s.openedWindowID.Load())})
}
// blockRuntimeID returns the runtime ID of the block passed.
func (s *Session) blockRuntimeID(b world.Block) uint32 {
id, _ := world.BlockRuntimeID(b)
return id
}
// entityRuntimeID returns the runtime ID of the entity passed.
//noinspection GoCommentLeadingSpace
func (s *Session) entityRuntimeID(e world.Entity) uint64 {
s.entityMutex.RLock()
//lint:ignore S1005 Double assignment is done explicitly to prevent panics.
id, _ := s.entityRuntimeIDs[e]
s.entityMutex.RUnlock()
return id
}
// entityFromRuntimeID attempts to return an entity by its runtime ID. False is returned if no entity with the
// ID could be found.
func (s *Session) entityFromRuntimeID(id uint64) (world.Entity, bool) {
s.entityMutex.RLock()
e, ok := s.entities[id]
s.entityMutex.RUnlock()
return e, ok
}
// Position ...
func (s *Session) Position() mgl64.Vec3 {
return s.c.Position()
}
// vec32To64 converts a mgl32.Vec3 to a mgl64.Vec3.
func vec32To64(vec3 mgl32.Vec3) mgl64.Vec3 {
return mgl64.Vec3{float64(vec3[0]), float64(vec3[1]), float64(vec3[2])}
}
// vec64To32 converts a mgl64.Vec3 to a mgl32.Vec3.
func vec64To32(vec3 mgl64.Vec3) mgl32.Vec3 {
return mgl32.Vec3{float32(vec3[0]), float32(vec3[1]), float32(vec3[2])}
}
<file_sep>package effect
import (
"github.com/df-mc/dragonfly/dragonfly/entity"
"image/color"
"time"
)
// Saturation is a lasting effect that causes the affected player to regain food and saturation.
type Saturation struct {
lastingEffect
}
// Apply ...
func (s Saturation) Apply(e entity.Living) {
if i, ok := e.(interface {
Saturate(food int, saturation float64)
}); ok {
i.Saturate(1*s.Lvl, 2*float64(s.Lvl))
}
}
// WithDuration ...
func (s Saturation) WithDuration(d time.Duration) entity.Effect {
return Saturation{s.withDuration(d)}
}
// RGBA ...
func (s Saturation) RGBA() color.RGBA {
return color.RGBA{R: 0xf8, G: 0x24, B: 0x23, A: 0xff}
}
<file_sep>package block
import (
"fmt"
"github.com/df-mc/dragonfly/dragonfly/block/action"
"github.com/df-mc/dragonfly/dragonfly/entity/physics"
"github.com/df-mc/dragonfly/dragonfly/internal/nbtconv"
"github.com/df-mc/dragonfly/dragonfly/item"
"github.com/df-mc/dragonfly/dragonfly/item/inventory"
"github.com/df-mc/dragonfly/dragonfly/world"
"github.com/df-mc/dragonfly/dragonfly/world/sound"
"github.com/go-gl/mathgl/mgl64"
"strings"
"sync"
)
// Chest is a container block which may be used to store items. Chests may also be paired to create a bigger
// single container.
// The empty value of Chest is not valid. It must be created using item.NewChest().
type Chest struct {
nbt
// Facing is the direction that the chest is facing.
Facing world.Direction
// CustomName is the custom name of the chest. This name is displayed when the chest is opened, and may
// include colour codes.
CustomName string
inventory *inventory.Inventory
viewerMu *sync.RWMutex
viewers *[]ContainerViewer
}
// NewChest creates a new initialised chest. The inventory is properly initialised.
func NewChest() Chest {
m := new(sync.RWMutex)
v := new([]ContainerViewer)
return Chest{
inventory: inventory.New(27, func(slot int, item item.Stack) {
m.RLock()
for _, viewer := range *v {
viewer.ViewSlotChange(slot, item)
}
m.RUnlock()
}),
viewerMu: m,
viewers: v,
}
}
// Inventory returns the inventory of the chest. The size of the inventory will be 27 or 54, depending on
// whether the chest is single or double.
func (c Chest) Inventory() *inventory.Inventory {
return c.inventory
}
// WithName returns the chest after applying a specific name to the block.
func (c Chest) WithName(a ...interface{}) world.Item {
c.CustomName = strings.TrimSuffix(fmt.Sprintln(a...), "\n")
return c
}
// AABB ...
func (c Chest) AABB(world.BlockPos, *world.World) []physics.AABB {
return []physics.AABB{physics.NewAABB(mgl64.Vec3{0.025, 0, 0.025}, mgl64.Vec3{0.975, 0.95, 0.975})}
}
// CanDisplace ...
func (Chest) CanDisplace(b world.Liquid) bool {
_, water := b.(Water)
return water
}
// SideClosed ...
func (Chest) SideClosed(world.BlockPos, world.BlockPos, *world.World) bool {
return false
}
// open opens the chest, displaying the animation and playing a sound.
func (c Chest) open(w *world.World, pos world.BlockPos) {
for _, v := range w.Viewers(pos.Vec3()) {
v.ViewBlockAction(pos, action.Open{})
}
w.PlaySound(pos.Vec3Centre(), sound.ChestOpen{})
}
// close closes the chest, displaying the animation and playing a sound.
func (c Chest) close(w *world.World, pos world.BlockPos) {
for _, v := range w.Viewers(pos.Vec3()) {
v.ViewBlockAction(pos, action.Close{})
}
w.PlaySound(pos.Vec3Centre(), sound.ChestClose{})
}
// AddViewer adds a viewer to the chest, so that it is updated whenever the inventory of the chest is changed.
func (c Chest) AddViewer(v ContainerViewer, w *world.World, pos world.BlockPos) {
c.viewerMu.Lock()
if len(*c.viewers) == 0 {
c.open(w, pos)
}
*c.viewers = append(*c.viewers, v)
c.viewerMu.Unlock()
}
// RemoveViewer removes a viewer from the chest, so that slot updates in the inventory are no longer sent to
// it.
func (c Chest) RemoveViewer(v ContainerViewer, w *world.World, pos world.BlockPos) {
c.viewerMu.Lock()
if len(*c.viewers) == 0 {
c.viewerMu.Unlock()
return
}
newViewers := make([]ContainerViewer, 0, len(*c.viewers)-1)
for _, viewer := range *c.viewers {
if viewer != v {
newViewers = append(newViewers, viewer)
}
}
*c.viewers = newViewers
if len(*c.viewers) == 0 {
c.close(w, pos)
}
c.viewerMu.Unlock()
}
// Activate ...
func (c Chest) Activate(pos world.BlockPos, _ world.Face, _ *world.World, u item.User) {
if opener, ok := u.(ContainerOpener); ok {
opener.OpenBlockContainer(pos)
}
}
// UseOnBlock ...
func (c Chest) UseOnBlock(pos world.BlockPos, face world.Face, _ mgl64.Vec3, w *world.World, user item.User, ctx *item.UseContext) (used bool) {
pos, _, used = firstReplaceable(w, pos, face, c)
if !used {
return
}
//noinspection GoAssignmentToReceiver
c = NewChest()
c.Facing = user.Facing().Opposite()
place(w, pos, c, user, ctx)
return placed(ctx)
}
// BreakInfo ...
func (c Chest) BreakInfo() BreakInfo {
return BreakInfo{
Hardness: 2.5,
Harvestable: alwaysHarvestable,
Effective: axeEffective,
Drops: simpleDrops(append(c.inventory.Contents(), item.NewStack(c, 1))...),
}
}
// Drops returns the drops of the chest. This includes all items held in the inventory and the chest itself.
func (c Chest) Drops() []item.Stack {
return append(c.inventory.Contents(), item.NewStack(c, 1))
}
// DecodeNBT ...
func (c Chest) DecodeNBT(data map[string]interface{}) interface{} {
facing := c.Facing
//noinspection GoAssignmentToReceiver
c = NewChest()
c.Facing = facing
c.CustomName = readString(data, "CustomName")
nbtconv.InvFromNBT(c.inventory, readSlice(data, "Items"))
return c
}
// EncodeNBT ...
func (c Chest) EncodeNBT() map[string]interface{} {
if c.inventory == nil {
facing, customName := c.Facing, c.CustomName
//noinspection GoAssignmentToReceiver
c = NewChest()
c.Facing, c.CustomName = facing, customName
}
m := map[string]interface{}{
"Items": nbtconv.InvToNBT(c.inventory),
"id": "Chest",
}
if c.CustomName != "" {
m["CustomName"] = c.CustomName
}
return m
}
// LightDiffusionLevel ...
func (Chest) LightDiffusionLevel() uint8 {
return 0
}
// EncodeItem ...
func (Chest) EncodeItem() (id int32, meta int16) {
return 54, 0
}
// EncodeBlock ...
func (c Chest) EncodeBlock() (name string, properties map[string]interface{}) {
return "minecraft:chest", map[string]interface{}{"facing_direction": 2 + int32(c.Facing)}
}
// Hash ...
func (c Chest) Hash() uint64 {
return hashChest | (uint64(c.Facing) << 32)
}
<file_sep>package block
import (
"github.com/df-mc/dragonfly/dragonfly/item"
"github.com/df-mc/dragonfly/dragonfly/world"
"github.com/df-mc/dragonfly/dragonfly/world/particle"
"github.com/go-gl/mathgl/mgl64"
)
// Sponge is a block that can be used to remove water around itself when placed, turning into a wet sponge in the
// process.
type Sponge struct {
noNBT
// Wet specifies whether the dry or the wet variant of the block is used.
Wet bool
}
// BreakInfo ...
func (s Sponge) BreakInfo() BreakInfo {
return BreakInfo{
Hardness: 0.6,
Drops: simpleDrops(item.NewStack(s, 1)),
Effective: nothingEffective,
Harvestable: alwaysHarvestable,
}
}
// EncodeItem ...
func (s Sponge) EncodeItem() (id int32, meta int16) {
if s.Wet {
meta = 1
}
return 19, meta
}
// EncodeBlock ...
func (s Sponge) EncodeBlock() (name string, properties map[string]interface{}) {
if s.Wet {
return "minecraft:sponge", map[string]interface{}{"sponge_type": "wet"}
}
return "minecraft:sponge", map[string]interface{}{"sponge_type": "dry"}
}
// Hash ...
func (s Sponge) Hash() uint64 {
return hashSponge | (uint64(boolByte(s.Wet)) << 32)
}
// UseOnBlock places the sponge, absorbs nearby water if it's still dry and flags it as wet if any water has been
// absorbed.
func (s Sponge) UseOnBlock(pos world.BlockPos, face world.Face, _ mgl64.Vec3, w *world.World, user item.User, ctx *item.UseContext) (used bool) {
pos, _, used = firstReplaceable(w, pos, face, s)
if !used {
return
}
place(w, pos, s, user, ctx)
return placed(ctx)
}
// NeighbourUpdateTick checks for nearby water flow. If water could be found and the sponge is dry, it will absorb the
// water and be flagged as wet.
func (s Sponge) NeighbourUpdateTick(pos, _ world.BlockPos, w *world.World) {
// The sponge is dry, so it can absorb nearby water.
if !s.Wet {
if s.absorbWater(pos, w) > 0 {
// Water has been absorbed, so we flag the sponge as wet.
s.setWet(pos, w)
}
}
}
// setWet flags a sponge as wet. It replaces the block at pos by a wet sponge block and displays a block break
// particle at the sponge's position with an offset of 0.5 on each axis.
func (s Sponge) setWet(pos world.BlockPos, w *world.World) {
s.Wet = true
w.SetBlock(pos, s)
w.AddParticle(pos.Vec3().Add(mgl64.Vec3{0.5, 0.5, 0.5}), particle.BlockBreak{Block: Water{Depth: 1}})
}
// absorbWater replaces water blocks near the sponge by air out to a taxicab geometry of 7 in all directions.
// The maximum for absorbed blocks is 65.
// The returned int specifies the amount of replaced water blocks.
func (s Sponge) absorbWater(pos world.BlockPos, w *world.World) int {
// distanceToSponge binds a world.BlockPos to its distance from the sponge's position.
type distanceToSponge struct {
block world.BlockPos
distance int32
}
queue := make([]distanceToSponge, 0)
queue = append(queue, distanceToSponge{pos, 0})
// A sponge can only absorb up to 65 water blocks.
replaced := 0
for replaced < 65 {
if len(queue) == 0 {
break
}
// Pop the next distanceToSponge entry from the queue.
next := queue[0]
queue = queue[1:]
next.block.Neighbours(func(neighbour world.BlockPos) {
liquid, found := w.Liquid(neighbour)
if found {
if _, isWater := liquid.(Water); isWater {
w.SetLiquid(neighbour, nil)
replaced++
if next.distance < 7 {
queue = append(queue, distanceToSponge{neighbour, next.distance + 1})
}
}
}
})
}
return replaced
}
<file_sep>package world
import (
blockAction "github.com/df-mc/dragonfly/dragonfly/block/action"
"github.com/df-mc/dragonfly/dragonfly/entity/action"
"github.com/df-mc/dragonfly/dragonfly/entity/state"
"github.com/df-mc/dragonfly/dragonfly/world/chunk"
"github.com/go-gl/mathgl/mgl64"
"github.com/google/uuid"
)
// Viewer is a viewer in the world. It can view changes that are made in the world, such as the addition of
// entities and the changes of blocks.
type Viewer interface {
// Position returns the position of the viewer.
Position() mgl64.Vec3
// ViewEntity views the entity passed. It is called for every entity that the viewer may encounter in the
// world, either by moving entities or by moving the viewer using a world.Loader.
ViewEntity(e Entity)
// HideEntity stops viewing the entity passed. It is called for every entity that leaves the viewing range
// of the viewer, either by its movement or the movement of the viewer using a world.Loader.
HideEntity(e Entity)
// ViewEntityMovement views the movement of an entity. The entity is moved with a delta position, yaw and
// pitch, which, when applied to values of the entity, will result in the final values.
ViewEntityMovement(e Entity, deltaPos mgl64.Vec3, deltaYaw, deltaPitch float64)
// ViewEntityTeleport views the teleportation of an entity. The entity is immediately moved to a different
// target position.
ViewEntityTeleport(e Entity, position mgl64.Vec3)
// ViewChunk views the chunk passed at a particular position. It is called for every chunk loaded using
// the world.Loader.
ViewChunk(pos ChunkPos, c *chunk.Chunk, blockNBT map[BlockPos]Block)
// ViewTime views the time of the world. It is called every time the time is changed or otherwise every
// second.
ViewTime(time int)
// ViewEntityItems views the items currently held by an entity that is able to equip items.
ViewEntityItems(e Entity)
// ViewEntityArmour views the items currently equipped as armour by the entity.
ViewEntityArmour(e Entity)
// ViewEntityAction views an action performed by an entity. Available actions may be found in the `action`
// package, and include things such as swinging an arm.
ViewEntityAction(e Entity, a action.Action)
// ViewEntityState views the current state of an entity. It is called whenever an entity changes its
// physical appearance, for example when sprinting.
ViewEntityState(e Entity, s []state.State)
// ViewParticle views a particle spawned at a given position in the world. It is called when a particle,
// for example a block breaking particle, is spawned near the player.
ViewParticle(pos mgl64.Vec3, p Particle)
// ViewSound is called when a sound is played in the world.
ViewSound(pos mgl64.Vec3, s Sound)
// ViewBlockUpdate views the updating of a block. It is called when a block is set at the position passed
// to the method.
ViewBlockUpdate(pos BlockPos, b Block, layer int)
// ViewBlockAction views an action performed by a block. Available actions may be found in the `action`
// package, and include things such as a chest opening.
ViewBlockAction(pos BlockPos, a blockAction.Action)
// ViewEmote views an emote being performed by another entity.
ViewEmote(player Entity, emote uuid.UUID)
}
<file_sep>package world
import (
"context"
"fmt"
"github.com/df-mc/dragonfly/dragonfly/entity/physics"
"github.com/df-mc/dragonfly/dragonfly/world/chunk"
"github.com/df-mc/dragonfly/dragonfly/world/difficulty"
"github.com/df-mc/dragonfly/dragonfly/world/gamemode"
"github.com/go-gl/mathgl/mgl64"
"github.com/sirupsen/logrus"
"go.uber.org/atomic"
"math/rand"
"sync"
"time"
)
// World implements a Minecraft world. It manages all aspects of what players can see, such as blocks,
// entities and particles.
// World generally provides a synchronised state: All entities, blocks and players usually operate in this
// world, so World ensures that all its methods will always be safe for simultaneous calls.
type World struct {
name atomic.String
log *logrus.Logger
unixTime, currentTick, time atomic.Int64
timeStopped atomic.Bool
rdonly atomic.Bool
lastPos ChunkPos
lastChunk *chunkData
stopTick context.Context
cancelTick context.CancelFunc
doneTicking chan struct{}
gameModeMu sync.RWMutex
defaultGameMode gamemode.GameMode
difficultyMu sync.RWMutex
difficulty difficulty.Difficulty
handlerMu sync.RWMutex
handler Handler
providerMu sync.RWMutex
prov Provider
genMu sync.RWMutex
gen Generator
chunkMu sync.RWMutex
// chunks holds a cache of chunks currently loaded. These chunks are cleared from this map after some time
// of not being used.
chunks map[ChunkPos]*chunkData
r *rand.Rand
simDistSq int32
randomTickSpeed atomic.Uint32
updateMu sync.Mutex
// blockUpdates is a map of tick time values indexed by the block position at which an update is
// scheduled. If the current tick exceeds the tick value passed, the block update will be performed
// and the entry will be removed from the map.
blockUpdates map[BlockPos]int64
updatePositions []BlockPos
toTick []toTick
positionCache []ChunkPos
entitiesToTick []TickerEntity
}
// New creates a new initialised world. The world may be used right away, but it will not be saved or loaded
// from files until it has been given a different provider than the default. (NoIOProvider)
// By default, the name of the world will be 'World'.
func New(log *logrus.Logger, simulationDistance int) *World {
ctx, cancel := context.WithCancel(context.Background())
w := &World{
r: rand.New(rand.NewSource(time.Now().Unix())),
blockUpdates: map[BlockPos]int64{},
defaultGameMode: gamemode.Survival{},
difficulty: difficulty.Normal{},
prov: NoIOProvider{},
gen: NopGenerator{},
handler: NopHandler{},
doneTicking: make(chan struct{}),
simDistSq: int32(simulationDistance * simulationDistance),
randomTickSpeed: *atomic.NewUint32(3),
unixTime: *atomic.NewInt64(time.Now().Unix()),
log: log,
stopTick: ctx,
cancelTick: cancel,
name: *atomic.NewString("World"),
}
w.initChunkCache()
go w.startTicking()
go w.chunkCacheJanitor()
return w
}
// Name returns the display name of the world. Generally, this name is displayed at the top of the player list
// in the pause screen in-game.
// If a provider is set, the name will be updated according to the name that it provides.
func (w *World) Name() string {
return w.name.Load()
}
// Block reads a block from the position passed. If a chunk is not yet loaded at that position, the chunk is
// loaded, or generated if it could not be found in the world save, and the block returned. Chunks will be
// loaded synchronously.
func (w *World) Block(pos BlockPos) Block {
y := pos[1]
if y > 255 || y < 0 {
// Fast way out.
return air()
}
chunkPos := ChunkPos{int32(pos[0] >> 4), int32(pos[2] >> 4)}
c, err := w.chunk(chunkPos)
if err != nil {
w.log.Errorf("error getting block: %v", err)
return air()
}
rid := c.RuntimeID(uint8(pos[0]), uint8(pos[1]), uint8(pos[2]), 0)
c.Unlock()
state := registeredStates[rid]
if state.HasNBT() {
if _, ok := state.(NBTer); ok {
// The block was also a block entity, so we look it up in the block entity map.
b, ok := c.e[pos]
if ok {
return b
}
}
}
return state
}
// blockInChunk reads a block from the world at the position passed. The block is assumed to be in the chunk
// passed, which is also assumed to be locked already or otherwise not yet accessible.
func (w *World) blockInChunk(c *chunkData, pos BlockPos) (Block, error) {
if pos.OutOfBounds() {
// Fast way out.
return air(), nil
}
state := registeredStates[c.RuntimeID(uint8(pos[0]), uint8(pos[1]), uint8(pos[2]), 0)]
if _, ok := state.(NBTer); ok {
// The block was also a block entity, so we look it up in the block entity map.
b, ok := c.e[pos]
if ok {
return b, nil
}
}
return state, nil
}
// runtimeID gets the block runtime ID at a specific position in the world.
//lint:ignore U1000 Function is used using compiler directives.
//noinspection GoUnusedFunction
func runtimeID(w *World, pos BlockPos) uint32 {
if pos[1] < 0 || pos[1] > 255 {
// Fast way out.
return 0
}
c, err := w.chunk(chunkPosFromBlockPos(pos))
if err != nil {
return 0
}
rid := c.RuntimeID(uint8(pos[0]&0xf), uint8(pos[1]), uint8(pos[2]&0xf), 0)
c.Unlock()
return rid
}
// highestLightBlocker gets the Y value of the highest fully light blocking block at the x and z values
// passed in the world.
//lint:ignore U1000 Function is used using compiler directives.
//noinspection GoUnusedFunction
func highestLightBlocker(w *World, x, z int) uint8 {
c, err := w.chunk(chunkPosFromBlockPos(BlockPos{x, 0, z}))
if err != nil {
return 0
}
v := c.HighestLightBlocker(uint8(x), uint8(z))
c.Unlock()
return v
}
// SetBlock writes a block to the position passed. If a chunk is not yet loaded at that position, the chunk is
// first loaded or generated if it could not be found in the world save.
// SetBlock panics if the block passed has not yet been registered using RegisterBlock().
// Nil may be passed as the block to set the block to air.
// SetBlock should be avoided in situations where performance is critical when needing to set a lot of blocks
// to the world. BuildStructure may be used instead.
func (w *World) SetBlock(pos BlockPos, b Block) {
y := pos[1]
if y > 255 || y < 0 {
// Fast way out.
return
}
x, z := int32(pos[0]>>4), int32(pos[2]>>4)
c, err := w.chunk(ChunkPos{x, z})
if err != nil {
return
}
var h int64
if b != nil {
h = int64(b.Hash())
}
runtimeID, ok := runtimeIDsHashes.Get(h)
if !ok {
w.log.Errorf("runtime ID of block state %+v not found", b)
return
}
c.SetRuntimeID(uint8(pos[0]), uint8(pos[1]), uint8(pos[2]), 0, uint32(runtimeID))
c.Unlock()
var hasNBT bool
if b != nil {
hasNBT = b.HasNBT()
}
if hasNBT {
if _, hasNBT := b.(NBTer); hasNBT {
c.e[pos] = b
}
} else {
delete(c.e, pos)
}
for _, viewer := range c.v {
viewer.ViewBlockUpdate(pos, b, 0)
}
}
// setBlockInChunk sets a block in the chunk passed at a specific position. Unlike setBlock, setBlockInChunk
// does not send block updates to viewer.
func (w *World) setBlockInChunk(c *chunkData, pos BlockPos, b Block) error {
runtimeID, ok := runtimeIDsHashes.Get(int64(b.Hash()))
if !ok {
return fmt.Errorf("runtime ID of block state %+v not found", b)
}
c.SetRuntimeID(uint8(pos[0]), uint8(pos[1]), uint8(pos[2]), 0, uint32(runtimeID))
if _, hasNBT := b.(NBTer); hasNBT {
c.e[pos] = b
} else {
delete(c.e, pos)
}
return nil
}
// breakParticle has its value set in the block_internal package.
var breakParticle func(b Block) Particle
// BreakBlock breaks a block at the position passed. Unlike when setting the block at that position to air,
// BreakBlock will also show particles and update blocks around the position.
func (w *World) BreakBlock(pos BlockPos) {
old := w.Block(pos)
w.SetBlock(pos, nil)
w.AddParticle(pos.Vec3Centre(), breakParticle(old))
if liq, ok := w.Liquid(pos); ok {
// Move the liquid down a layer.
w.SetLiquid(pos, liq)
} else {
w.doBlockUpdatesAround(pos)
}
}
// PlaceBlock places a block at the position passed. Unlike when using SetBlock, PlaceBlock also schedules
// block updates around the position.
// If the block can displace liquids at the position placed, it will do so, and liquid source blocks will be
// put into the same block as the one passed.
func (w *World) PlaceBlock(pos BlockPos, b Block) {
var liquid Liquid
if displacer, ok := b.(LiquidDisplacer); ok {
liq, ok := w.Liquid(pos)
if ok && displacer.CanDisplace(liq) && liq.LiquidDepth() == 8 {
liquid = liq
}
}
w.SetBlock(pos, b)
if liquid != nil {
w.SetLiquid(pos, liquid)
return
}
w.SetLiquid(pos, nil)
}
// BuildStructure builds a Structure passed at a specific position in the world. Unlike SetBlock, it takes a
// Structure implementation, which provides blocks to be placed at a specific location.
// BuildStructure is specifically tinkered to be able to process a large batch of chunks simultaneously and
// will do so within much less time than separate SetBlock calls would.
// The method operates on a per-chunk basis, setting all blocks within a single chunk part of the structure
// before moving on to the next chunk.
func (w *World) BuildStructure(pos BlockPos, s Structure) {
dim := s.Dimensions()
width, height, length := dim[0], dim[1], dim[2]
maxX, maxZ := pos[0]+width, pos[2]+length
for chunkX := pos[0] >> 4; chunkX < ((pos[0]+width)>>4)+1; chunkX++ {
for chunkZ := pos[2] >> 4; chunkZ < ((pos[2]+length)>>4)+1; chunkZ++ {
// We approach this on a per-chunk basis, so that we can keep only one chunk in memory at a time
// while not needing to acquire a new chunk lock for every block. This also allows us not to send
// block updates, but instead send a single chunk update once.
chunkPos := ChunkPos{int32(chunkX), int32(chunkZ)}
c, err := w.chunk(chunkPos)
if err != nil {
w.log.Errorf("error loading chunk for structure: %v", err)
}
f := func(x, y, z int) Block {
if x>>4 == chunkX && z>>4 == chunkZ {
b, _ := w.blockInChunk(c, BlockPos{x, y, z})
return b
}
return w.Block(BlockPos{x, y, z})
}
baseX, baseZ := chunkX<<4, chunkZ<<4
for localX := 0; localX < 16; localX++ {
xOffset := baseX + localX
if xOffset < pos[0] || xOffset >= maxX {
continue
}
for localZ := 0; localZ < 16; localZ++ {
zOffset := baseZ + localZ
if zOffset < pos[2] || zOffset >= maxZ {
continue
}
for y := 0; y < height; y++ {
if y+pos[1] > 255 {
// We've hit the height limit for blocks.
break
} else if y+pos[1] < 0 {
// We've got a block below the minimum, but other blocks might still reach above
// it, so don't break but continue.
continue
}
placePos := BlockPos{xOffset, y + pos[1], zOffset}
if b := s.At(xOffset-pos[0], y, zOffset-pos[2], f); b != nil {
if err := w.setBlockInChunk(c, placePos, b); err != nil {
w.log.Errorf("error setting block of structure: %v", err)
}
}
if liq := s.AdditionalLiquidAt(xOffset-pos[0], y, zOffset-pos[2]); liq != nil {
runtimeID, ok := BlockRuntimeID(liq)
if !ok {
w.log.Errorf("runtime ID of block state %+v not found", liq)
continue
}
c.SetRuntimeID(uint8(xOffset), uint8(y+pos[1]), uint8(zOffset), 1, runtimeID)
} else {
c.SetRuntimeID(uint8(xOffset), uint8(y+pos[1]), uint8(zOffset), 1, 0)
}
}
}
}
// After setting all blocks of the structure within a single chunk, we show the new chunk to all
// viewers once, and unlock it.
for _, viewer := range c.v {
viewer.ViewChunk(chunkPos, c.Chunk, c.e)
}
c.Unlock()
}
}
}
// Liquid attempts to return any liquid block at the position passed. This liquid may be in the foreground or
// in any other layer.
// If found, the liquid is returned. If not, the bool returned is false and the liquid is nil.
func (w *World) Liquid(pos BlockPos) (Liquid, bool) {
if pos.OutOfBounds() {
// Fast way out.
return nil, false
}
c, err := w.chunk(chunkPosFromBlockPos(pos))
if err != nil {
w.log.Errorf("failed getting liquid: error getting chunk at position %v: %w", chunkPosFromBlockPos(pos), err)
return nil, false
}
x, y, z := uint8(pos[0]), uint8(pos[1]), uint8(pos[2])
id := c.RuntimeID(x, y, z, 0)
b, ok := blockByRuntimeID(id)
if !ok {
w.log.Errorf("failed getting liquid: cannot get block by runtime ID %v", id)
c.Unlock()
return nil, false
}
if liq, ok := b.(Liquid); ok {
c.Unlock()
return liq, true
}
id = c.RuntimeID(x, y, z, 1)
b, ok = blockByRuntimeID(id)
c.Unlock()
if !ok {
w.log.Errorf("failed getting liquid: cannot get block by runtime ID %v", id)
return nil, false
}
if liq, ok := b.(Liquid); ok {
return liq, true
}
return nil, false
}
// SetLiquid sets the liquid at a specific position in the world. Unlike SetBlock, SetLiquid will not
// overwrite any existing blocks. It will instead be in the same position as a block currently there, unless
// there already is a liquid at that position, in which case it will be overwritten.
// If nil is passed for the liquid, any liquid currently present will be removed.
func (w *World) SetLiquid(pos BlockPos, b Liquid) {
if pos.OutOfBounds() {
// Fast way out.
return
}
chunkPos := chunkPosFromBlockPos(pos)
c, err := w.chunk(chunkPos)
if err != nil {
w.log.Errorf("failed setting liquid: error getting chunk at position %v: %w", chunkPosFromBlockPos(pos), err)
return
}
if b == nil {
w.removeLiquids(c, pos)
c.Unlock()
w.doBlockUpdatesAround(pos)
return
}
x, y, z := uint8(pos[0]), uint8(pos[1]), uint8(pos[2])
if !replaceable(w, c, pos, b) {
current, err := w.blockInChunk(c, pos)
if err != nil {
c.Unlock()
w.log.Errorf("failed setting liquid: error getting block at position %v: %w", chunkPosFromBlockPos(pos), err)
return
}
if displacer, ok := current.(LiquidDisplacer); !ok || !displacer.CanDisplace(b) {
c.Unlock()
return
}
}
runtimeID, ok := BlockRuntimeID(b)
if !ok {
c.Unlock()
w.log.Errorf("failed setting liquid: runtime ID of block state %+v not found", b)
return
}
if w.removeLiquids(c, pos) {
c.SetRuntimeID(x, y, z, 0, runtimeID)
for _, v := range c.v {
v.ViewBlockUpdate(pos, b, 0)
}
} else {
c.SetRuntimeID(x, y, z, 1, runtimeID)
for _, v := range c.v {
v.ViewBlockUpdate(pos, b, 1)
}
}
c.Unlock()
w.doBlockUpdatesAround(pos)
}
// removeLiquids removes any liquid blocks that may be present at a specific block position in the chunk
// passed.
// The bool returned specifies if no blocks were left on the foreground layer.
func (w *World) removeLiquids(c *chunkData, pos BlockPos) bool {
x, y, z := uint8(pos[0]), uint8(pos[1]), uint8(pos[2])
noneLeft := false
if noLeft, changed := w.removeLiquidOnLayer(c.Chunk, x, y, z, 0); noLeft {
if changed {
for _, v := range c.v {
v.ViewBlockUpdate(pos, air(), 0)
}
}
noneLeft = true
}
if _, changed := w.removeLiquidOnLayer(c.Chunk, x, y, z, 1); changed {
for _, v := range c.v {
v.ViewBlockUpdate(pos, air(), 1)
}
}
return noneLeft
}
// removeLiquidOnLayer removes a liquid block from a specific layer in the chunk passed, returning true if
// successful.
func (w *World) removeLiquidOnLayer(c *chunk.Chunk, x, y, z, layer uint8) (bool, bool) {
id := c.RuntimeID(x, y, z, layer)
b, ok := blockByRuntimeID(id)
if !ok {
w.log.Errorf("failed removing liquids: cannot get block by runtime ID %v", id)
return false, false
}
if _, ok := b.(Liquid); ok {
c.SetRuntimeID(x, y, z, layer, 0)
return true, true
}
return id == 0, false
}
// additionalLiquid checks if the block at a position has additional liquid on another layer and returns the
// liquid if so.
func (w *World) additionalLiquid(pos BlockPos) (Liquid, bool) {
if pos.OutOfBounds() {
// Fast way out.
return nil, false
}
c, err := w.chunk(chunkPosFromBlockPos(pos))
if err != nil {
w.log.Errorf("failed getting liquid: error getting chunk at position %v: %w", chunkPosFromBlockPos(pos), err)
return nil, false
}
id := c.RuntimeID(uint8(pos[0]), uint8(pos[1]), uint8(pos[2]), 1)
c.Unlock()
b, ok := blockByRuntimeID(id)
if !ok {
w.log.Errorf("failed getting liquid: cannot get block by runtime ID %v", id)
return nil, false
}
liq, ok := b.(Liquid)
return liq, ok
}
// Light returns the light level at the position passed. This is the highest of the sky and block light.
// The light value returned is a value in the range 0-15, where 0 means there is no light present, whereas
// 15 means the block is fully lit.
func (w *World) Light(pos BlockPos) uint8 {
if pos[1] > 255 {
// Above the rest of the world, so full sky light.
return 15
}
if pos[1] < 0 {
// Fast way out.
return 0
}
c, err := w.chunk(chunkPosFromBlockPos(pos))
if err != nil {
return 0
}
l := c.Light(uint8(pos[0]), uint8(pos[1]), uint8(pos[2]))
c.Unlock()
return l
}
// SkyLight returns the sky light level at the position passed. This light level is not influenced by blocks
// that emit light, such as torches or glowstone. The light value, similarly to Light, is a value in the
// range 0-15, where 0 means no light is present.
func (w *World) SkyLight(pos BlockPos) uint8 {
if pos[1] > 255 {
// Above the rest of the world, so full sky light.
return 15
}
if pos[1] < 0 {
// Fast way out.
return 0
}
c, err := w.chunk(chunkPosFromBlockPos(pos))
if err != nil {
return 0
}
l := c.SkyLight(uint8(pos[0]), uint8(pos[1]), uint8(pos[2]))
c.Unlock()
return l
}
// Time returns the current time of the world. The time is incremented every 1/20th of a second, unless
// World.StopTime() is called.
func (w *World) Time() int {
return int(w.time.Load())
}
// SetTime sets the new time of the world. SetTime will always work, regardless of whether the time is stopped
// or not.
func (w *World) SetTime(new int) {
w.time.Store(int64(new))
for _, viewer := range w.allViewers() {
viewer.ViewTime(new)
}
}
// StopTime stops the time in the world. When called, the time will no longer cycle and the world will remain
// at the time when StopTime is called. The time may be restarted by calling World.StartTime().
// StopTime will not do anything if the time is already stopped.
func (w *World) StopTime() {
w.timeStopped.Store(true)
}
// StartTime restarts the time in the world. When called, the time will start cycling again and the day/night
// cycle will continue. The time may be stopped again by calling World.StopTime().
// StartTime will not do anything if the time is already started.
func (w *World) StartTime() {
w.timeStopped.Store(false)
}
// AddParticle spawns a particle at a given position in the world. Viewers that are viewing the chunk will be
// shown the particle.
func (w *World) AddParticle(pos mgl64.Vec3, p Particle) {
p.Spawn(w, pos)
for _, viewer := range w.Viewers(pos) {
viewer.ViewParticle(pos, p)
}
}
// PlaySound plays a sound at a specific position in the world. Viewers of that position will be able to hear
// the sound if they're close enough.
func (w *World) PlaySound(pos mgl64.Vec3, s Sound) {
for _, viewer := range w.Viewers(pos) {
viewer.ViewSound(pos, s)
}
}
// entityWorlds holds a list of all entities added to a world. It may be used to lookup the world that an
// entity is currently in.
var entityWorlds = map[Entity]*World{}
var worldsMu sync.RWMutex
// AddEntity adds an entity to the world at the position that the entity has. The entity will be visible to
// all viewers of the world that have the chunk of the entity loaded.
// If the chunk that the entity is in is not yet loaded, it will first be loaded.
// If the entity passed to AddEntity is currently in a world, it is first removed from that world.
func (w *World) AddEntity(e Entity) {
if e.World() != nil {
e.World().RemoveEntity(e)
}
worldsMu.Lock()
entityWorlds[e] = w
worldsMu.Unlock()
chunkPos := chunkPosFromVec3(e.Position())
c, err := w.chunk(chunkPos)
if err != nil {
w.log.Errorf("error loading chunk to add entity: %v", err)
}
viewers := c.v
c.entities = append(c.entities, e)
c.Unlock()
for _, viewer := range viewers {
// We show the entity to all viewers currently in the chunk that the entity is spawned in.
showEntity(e, viewer)
}
}
// RemoveEntity removes an entity from the world that is currently present in it. Any viewers of the entity
// will no longer be able to see it.
// RemoveEntity operates assuming the position of the entity is the same as where it is currently in the
// world. If it can not find it there, it will loop through all entities and try to find it.
// RemoveEntity assumes the entity is currently loaded and in a loaded chunk. If not, the function will not do
// anything.
func (w *World) RemoveEntity(e Entity) {
chunkPos := chunkPosFromVec3(e.Position())
worldsMu.Lock()
delete(entityWorlds, e)
worldsMu.Unlock()
c, ok := w.chunkFromCache(chunkPos)
if !ok {
// The chunk wasn't loaded, so we can't remove any entity from the chunk.
return
}
c.Lock()
n := make([]Entity, 0, len(c.entities))
for _, entity := range c.entities {
if entity != e {
n = append(n, entity)
continue
}
}
c.entities = n
for _, viewer := range c.v {
viewer.HideEntity(e)
}
c.Unlock()
}
// EntitiesWithin does a lookup through the entities in the chunks touched by the AABB passed, returning all
// those which are contained within the AABB when it comes to their position.
func (w *World) EntitiesWithin(aabb physics.AABB) []Entity {
// Make an estimate of 16 entities on average.
m := make([]Entity, 0, 16)
// We expand it by 3 blocks in all horizontal directions to account for entities that may be in
// neighbouring chunks while having a bounding box that extends into the current one.
minPos, maxPos := chunkPosFromVec3(aabb.Min()), chunkPosFromVec3(aabb.Max())
for x := minPos[0]; x <= maxPos[0]; x++ {
for z := minPos[1]; z <= maxPos[1]; z++ {
c, ok := w.chunkFromCache(ChunkPos{x, z})
if !ok {
// The chunk wasn't loaded, so there are no entities here.
continue
}
c.Lock()
for _, entity := range c.entities {
if aabb.Vec3Within(entity.Position()) {
// The entity position was within the AABB, so we add it to the slice to return.
m = append(m, entity)
}
}
c.Unlock()
}
}
return m
}
// OfEntity attempts to return a world that an entity is currently in. If the entity was not currently added
// to a world, the world returned is nil and the bool returned is false.
func OfEntity(e Entity) (*World, bool) {
worldsMu.RLock()
w, ok := entityWorlds[e]
worldsMu.RUnlock()
return w, ok
}
// Spawn returns the spawn of the world. Every new player will by default spawn on this position in the world
// when joining.
func (w *World) Spawn() BlockPos {
return w.provider().WorldSpawn()
}
// SetSpawn sets the spawn of the world to a different position. The player will be spawned in the center of
// this position when newly joining.
func (w *World) SetSpawn(pos BlockPos) {
w.provider().SetWorldSpawn(pos)
}
// DefaultGameMode returns the default game mode of the world. When players join, they are given this game
// mode.
// The default game mode may be changed using SetDefaultGameMode().
func (w *World) DefaultGameMode() gamemode.GameMode {
w.gameModeMu.RLock()
defer w.gameModeMu.RUnlock()
return w.defaultGameMode
}
// SetDefaultGameMode changes the default game mode of the world. When players join, they are then given that
// game mode.
func (w *World) SetDefaultGameMode(mode gamemode.GameMode) {
w.gameModeMu.Lock()
defer w.gameModeMu.Unlock()
w.defaultGameMode = mode
}
// Difficulty returns the difficulty of the world. Properties of mobs in the world and the player's hunger
// will depend on this difficulty.
func (w *World) Difficulty() difficulty.Difficulty {
w.difficultyMu.RLock()
defer w.difficultyMu.RUnlock()
return w.difficulty
}
// SetDifficulty changes the difficulty of a world.
func (w *World) SetDifficulty(d difficulty.Difficulty) {
w.difficultyMu.Lock()
defer w.difficultyMu.Unlock()
w.difficulty = d
}
// SetRandomTickSpeed sets the random tick speed of blocks. By default, each sub chunk has 3 blocks randomly
// ticked per sub chunk, so the default value is 3. Setting this value to 0 will stop random ticking
// altogether, while setting it higher results in faster ticking.
func (w *World) SetRandomTickSpeed(v int) {
w.randomTickSpeed.Store(uint32(v))
}
// ScheduleBlockUpdate schedules a block update at the position passed after a specific delay. If the block at
// that position does not handle block updates, nothing will happen.
func (w *World) ScheduleBlockUpdate(pos BlockPos, delay time.Duration) {
if pos.OutOfBounds() {
return
}
w.updateMu.Lock()
if _, exists := w.blockUpdates[pos]; exists {
w.updateMu.Unlock()
return
}
w.blockUpdates[pos] = w.currentTick.Load() + delay.Nanoseconds()/int64(time.Second/20)
w.updateMu.Unlock()
}
// doBlockUpdatesAround schedules block updates directly around and on the position passed.
func (w *World) doBlockUpdatesAround(pos BlockPos) {
if pos.OutOfBounds() {
return
}
changed := pos
w.updateNeighbour(pos, changed)
pos.Neighbours(func(pos BlockPos) {
w.updateNeighbour(pos, changed)
})
}
// updateNeighbour ticks the position passed as a result of the neighbour passed being updated.
func (w *World) updateNeighbour(pos, changedNeighbour BlockPos) {
if ticker, ok := w.Block(pos).(NeighbourUpdateTicker); ok {
ticker.NeighbourUpdateTick(pos, changedNeighbour, w)
}
if liquid, ok := w.additionalLiquid(pos); ok {
if ticker, ok := liquid.(NeighbourUpdateTicker); ok {
ticker.NeighbourUpdateTick(pos, changedNeighbour, w)
}
}
}
// Provider changes the provider of the world to the provider passed. If nil is passed, the NoIOProvider
// will be set, which does not read or write any data.
func (w *World) Provider(p Provider) {
w.providerMu.Lock()
defer w.providerMu.Unlock()
if p == nil {
p = NoIOProvider{}
}
w.prov = p
w.name.Store(p.WorldName())
w.gameModeMu.Lock()
w.defaultGameMode = p.LoadDefaultGameMode()
w.gameModeMu.Unlock()
w.difficultyMu.Lock()
w.difficulty = p.LoadDifficulty()
w.difficultyMu.Unlock()
w.time.Store(p.LoadTime())
w.timeStopped.Store(!p.LoadTimeCycle())
w.initChunkCache()
}
// ReadOnly makes the world read only. Chunks will no longer be saved to disk, just like entities and data
// in the level.dat.
func (w *World) ReadOnly() {
w.rdonly.Store(true)
}
// Generator changes the generator of the world to the one passed. If nil is passed, the generator is set to
// the default, NopGenerator.
func (w *World) Generator(g Generator) {
w.genMu.Lock()
defer w.genMu.Unlock()
if g == nil {
g = NopGenerator{}
}
w.gen = g
}
// Handle changes the current Handler of the world. As a result, events called by the world will call
// handlers of the Handler passed.
// Handle sets the world's Handler to NopHandler if nil is passed.
func (w *World) Handle(h Handler) {
w.handlerMu.Lock()
defer w.handlerMu.Unlock()
if h == nil {
h = NopHandler{}
}
w.handler = h
}
// Viewers returns a list of all viewers viewing the position passed. A viewer will be assumed to be watching
// if the position is within one of the chunks that the viewer is watching.
func (w *World) Viewers(pos mgl64.Vec3) []Viewer {
c, ok := w.chunkFromCache(chunkPosFromVec3(pos))
if !ok {
return nil
}
c.Lock()
viewers := make([]Viewer, len(c.v))
copy(viewers, c.v)
c.Unlock()
return viewers
}
// Close closes the world and saves all chunks currently loaded.
func (w *World) Close() error {
w.cancelTick()
<-w.doneTicking
w.log.Debug("Saving chunks in memory to disk...")
w.chunkMu.Lock()
chunksToSave := make(map[ChunkPos]*chunkData, len(w.chunks))
for pos, c := range w.chunks {
// We delete all chunks from the cache and save them to the provider.
delete(w.chunks, pos)
chunksToSave[pos] = c
}
w.chunkMu.Unlock()
for pos, c := range chunksToSave {
w.saveChunk(pos, c)
}
if !w.rdonly.Load() {
w.log.Debug("Updating level.dat values...")
w.provider().SaveTime(w.time.Load())
w.provider().SaveTimeCycle(!w.timeStopped.Load())
w.gameModeMu.RLock()
w.provider().SaveDefaultGameMode(w.defaultGameMode)
w.gameModeMu.RUnlock()
w.difficultyMu.RLock()
w.provider().SaveDifficulty(w.difficulty)
w.difficultyMu.RUnlock()
}
w.log.Debug("Closing provider...")
if err := w.provider().Close(); err != nil {
w.log.Errorf("error closing world provider: %v", err)
}
w.Handle(NopHandler{})
return nil
}
// startTicking starts ticking the world, updating all entities, blocks and other features such as the time of
// the world, as required.
func (w *World) startTicking() {
ticker := time.NewTicker(time.Second / 20)
defer ticker.Stop()
for {
select {
case <-ticker.C:
w.unixTime.Store(time.Now().Unix())
w.tick()
case <-w.stopTick.Done():
// The world was closed, so we should stop ticking.
w.doneTicking <- struct{}{}
return
}
}
}
// tick ticks the world and updates the time, blocks and entities that require updates.
func (w *World) tick() {
viewers := w.allViewers()
if len(viewers) == 0 {
return
}
tick := w.currentTick.Add(1)
if !w.timeStopped.Load() {
w.time.Add(1)
}
if tick%20 == 0 {
for _, viewer := range viewers {
viewer.ViewTime(int(w.time.Load()))
}
}
w.tickEntities(tick)
w.tickRandomBlocks(viewers)
w.tickScheduledBlocks(tick)
}
// tickScheduledBlocks executes scheduled block ticks in chunks that are still loaded at the time of
// execution.
func (w *World) tickScheduledBlocks(tick int64) {
w.updateMu.Lock()
for pos, scheduledTick := range w.blockUpdates {
if scheduledTick <= tick {
w.updatePositions = append(w.updatePositions, pos)
delete(w.blockUpdates, pos)
}
}
w.updateMu.Unlock()
for _, pos := range w.updatePositions {
if ticker, ok := w.Block(pos).(ScheduledTicker); ok {
ticker.ScheduledTick(pos, w)
}
if liquid, ok := w.additionalLiquid(pos); ok {
if ticker, ok := liquid.(ScheduledTicker); ok {
ticker.ScheduledTick(pos, w)
}
}
}
w.updatePositions = w.updatePositions[:0]
}
// toTick is a struct used to keep track of blocks that need to be ticked upon a random tick.
type toTick struct {
b RandomTicker
pos BlockPos
}
// tickRandomBlocks executes random block ticks in each sub chunk in the world that has at least one viewer
// registered from the viewers passed.
func (w *World) tickRandomBlocks(viewers []Viewer) {
if w.simDistSq == 0 {
// NOP if the simulation distance is 0.
return
}
tickSpeed := w.randomTickSpeed.Load()
for _, viewer := range viewers {
pos := viewer.Position()
w.positionCache = append(w.positionCache, ChunkPos{
// Technically we could obtain the wrong chunk position here due to truncating, but this
// inaccuracy doesn't matter and it allows us to cut a corner.
int32(pos[0]) >> 4,
int32(pos[2]) >> 4,
})
}
w.chunkMu.RLock()
for pos := range w.chunks {
c := w.chunks[pos]
withinSimDist := false
for _, chunkPos := range w.positionCache {
xDiff, zDiff := chunkPos[0]-pos[0], chunkPos[1]-pos[1]
if (xDiff*xDiff)+(zDiff*zDiff) <= w.simDistSq {
// The chunk was within the simulation distance of at least one viewer, so we can proceed to
// ticking the block.
withinSimDist = true
break
}
}
if !withinSimDist {
// No viewers in this chunk that are within the simulation distance, so proceed to the next.
continue
}
c.Lock()
subChunks := c.Sub()
// In total we generate 3 random blocks per sub chunk.
for j := uint32(0); j < tickSpeed; j++ {
// We generate 3 random uint64s. Out of a single uint64, we can pull 16 uint4s, which means we can
// obtain a total of 16 coordinates on one axis from one uint64. One for each sub chunk.
ra, rb, rc := int(w.r.Uint64()), int(w.r.Uint64()), int(w.r.Uint64())
for i := 0; i < 64; i += 4 {
sub := subChunks[i>>2]
if sub == nil {
// No sub chunk present, so skip it right away.
continue
}
layers := sub.Layers()
if len(layers) == 0 {
// No layers present, so skip it right away.
continue
}
x, y, z := ra>>i&0xf, rb>>i&0xf, rc>>i&0xf
// Generally we would want to make sure the block has its block entities, but provided blocks
// with block entities are generally ticked already, we are safe to assume that blocks
// implementing the RandomTicker don't rely on additional block entity data.
rid := layers[0].RuntimeID(uint8(x), uint8(y), uint8(z))
if rid == 0 {
// The block was air, take the fast route out.
continue
}
if randomTicker, ok := registeredStates[rid].(RandomTicker); ok {
w.toTick = append(w.toTick, toTick{b: randomTicker, pos: BlockPos{int(pos[0]<<4) + x, y + i>>2, int(pos[1]<<4) + z}})
}
}
}
c.Unlock()
}
w.chunkMu.RUnlock()
for _, a := range w.toTick {
a.b.RandomTick(a.pos, w, w.r)
}
w.toTick = w.toTick[:0]
w.positionCache = w.positionCache[:0]
}
// tickEntities ticks all entities in the world, making sure they are still located in the correct chunks and
// updating where necessary.
func (w *World) tickEntities(tick int64) {
type entityToMove struct {
e Entity
after *chunkData
viewersBefore []Viewer
}
var entitiesToMove []entityToMove
w.chunkMu.RLock()
// We first iterate over all chunks to see if entities move out of them. We make sure not to lock two
// chunks at the same time.
for chunkPos, c := range w.chunks {
c.Lock()
chunkEntities := make([]Entity, 0, len(c.entities))
for _, entity := range c.entities {
if ticker, ok := entity.(TickerEntity); ok {
w.entitiesToTick = append(w.entitiesToTick, ticker)
}
// The entity was stored using an outdated chunk position. We update it and make sure it is ready
// for viewers to view it.
newChunkPos := chunkPosFromVec3(entity.Position())
if newChunkPos != chunkPos {
newC, ok := w.chunks[newChunkPos]
if !ok {
continue
}
entitiesToMove = append(entitiesToMove, entityToMove{e: entity, viewersBefore: append([]Viewer(nil), c.v...), after: newC})
continue
}
chunkEntities = append(chunkEntities, entity)
}
c.entities = chunkEntities
c.Unlock()
}
w.chunkMu.RUnlock()
for _, move := range entitiesToMove {
move.after.Lock()
move.after.entities = append(move.after.entities, move.e)
viewersAfter := move.after.v
move.after.Unlock()
for _, viewer := range move.viewersBefore {
if !w.hasViewer(viewer, viewersAfter) {
// First we hide the entity from all viewers that were previously viewing it, but no
// longer are.
viewer.HideEntity(move.e)
}
}
for _, viewer := range viewersAfter {
if !w.hasViewer(viewer, move.viewersBefore) {
// Then we show the entity to all viewers that are now viewing the entity in the new
// chunk.
showEntity(move.e, viewer)
}
}
}
for _, ticker := range w.entitiesToTick {
if _, ok := OfEntity(ticker.(Entity)); !ok {
continue
}
// We gather entities to tick and tick them later, so that the lock on the entity mutex is no longer
// active.
ticker.Tick(tick)
}
w.entitiesToTick = w.entitiesToTick[:0]
}
// addViewer adds a viewer to the world at a given position. Any events that happen in the chunk at that
// position, such as block changes, entity changes etc., will be sent to the viewer.
func (w *World) addViewer(c *chunkData, viewer Viewer) {
c.v = append(c.v, viewer)
// After adding the viewer to the chunk, we also need to send all entities currently in the chunk that the
// viewer is added to.
entities := c.entities
c.Unlock()
for _, entity := range entities {
showEntity(entity, viewer)
}
viewer.ViewTime(w.Time())
}
// removeViewer removes a viewer from the world at a given position. All entities will be hidden from the
// viewer and no more calls will be made when events in the chunk happen.
func (w *World) removeViewer(pos ChunkPos, viewer Viewer) {
c, ok := w.chunkFromCache(pos)
if !ok {
return
}
c.Lock()
n := make([]Viewer, 0, len(c.v))
for _, v := range c.v {
if v != viewer {
// Add all viewers but the one to remove to the new viewers slice.
n = append(n, v)
}
}
c.v = n
// After removing the viewer from the chunk, we also need to hide all entities from the viewer.
for _, entity := range c.entities {
viewer.HideEntity(entity)
}
c.Unlock()
}
// hasViewer checks if a chunk at a particular chunk position has the viewer passed. If so, true is returned.
func (w *World) hasViewer(viewer Viewer, viewers []Viewer) bool {
for _, v := range viewers {
if v == viewer {
return true
}
}
return false
}
// allViewers returns a list of all viewers of the world, regardless of where in the world they are viewing.
func (w *World) allViewers() []Viewer {
var v []Viewer
found := make(map[Viewer]struct{})
w.chunkMu.RLock()
for _, c := range w.chunks {
c.Lock()
for _, viewer := range c.v {
if _, ok := found[viewer]; ok {
// We've already found this viewer in another chunk. Don't add it again.
continue
}
found[viewer] = struct{}{}
v = append(v, viewer)
}
c.Unlock()
}
w.chunkMu.RUnlock()
return v
}
// provider returns the provider of the world. It should always be used, rather than direct field access, in
// order to provide synchronisation safety.
func (w *World) provider() Provider {
w.providerMu.RLock()
provider := w.prov
w.providerMu.RUnlock()
return provider
}
// Handler returns the Handler of the world. It should always be used, rather than direct field access, in
// order to provide synchronisation safety.
func (w *World) Handler() Handler {
w.handlerMu.RLock()
handler := w.handler
w.handlerMu.RUnlock()
return handler
}
// generator returns the generator of the world. It should always be used, rather than direct field access, in
// order to provide synchronisation safety.
func (w *World) generator() Generator {
w.genMu.RLock()
generator := w.gen
w.genMu.RUnlock()
return generator
}
// chunkFromCache attempts to fetch a chunk at the chunk position passed from the cache. If not found, the
// chunk returned is nil and false is returned.
func (w *World) chunkFromCache(pos ChunkPos) (*chunkData, bool) {
w.chunkMu.RLock()
c, ok := w.chunks[pos]
w.chunkMu.RUnlock()
return c, ok
}
// showEntity shows an entity to a viewer of the world. It makes sure everything of the entity, including the
// items held, is shown.
func showEntity(e Entity, viewer Viewer) {
viewer.ViewEntity(e)
viewer.ViewEntityState(e, e.State())
viewer.ViewEntityItems(e)
viewer.ViewEntityArmour(e)
}
// chunk reads a chunk from the position passed. If a chunk at that position is not yet loaded, the chunk is
// loaded from the provider, or generated if it did not yet exist. Both of these actions are done
// synchronously.
// An error is returned if the chunk could not be loaded successfully.
// chunk locks the chunk returned, meaning that any call to chunk made at the same time has to wait until the
// user calls Chunk.Unlock() on the chunk returned.
func (w *World) chunk(pos ChunkPos) (*chunkData, error) {
var needsLight bool
var err error
w.chunkMu.Lock()
if pos == w.lastPos && w.lastChunk != nil {
c := w.lastChunk
w.chunkMu.Unlock()
c.Lock()
return c, nil
}
c, ok := w.chunks[pos]
if !ok {
c, err = w.loadChunk(pos)
if err != nil {
w.chunkMu.Unlock()
return nil, err
}
w.chunks[pos] = c
needsLight = true
}
w.lastChunk, w.lastPos = c, pos
w.chunkMu.Unlock()
if needsLight {
w.calculateLight(c.Chunk, pos)
}
c.Lock()
return c, nil
}
// loadChunk attempts to load a chunk from the provider, or generates a chunk if one doesn't currently exist.
func (w *World) loadChunk(pos ChunkPos) (*chunkData, error) {
c, found, err := w.provider().LoadChunk(pos)
if err != nil {
return nil, fmt.Errorf("error loading chunk %v: %w", pos, err)
}
if !found {
// The provider doesn't have a chunk saved at this position, so we generate a new one.
c = chunk.New()
w.generator().GenerateChunk(pos, c)
return newChunkData(c), nil
}
data := newChunkData(c)
entities, err := w.provider().LoadEntities(pos)
if err != nil {
return nil, fmt.Errorf("error loading entities of chunk %v: %w", pos, err)
}
data.entities = entities
blockEntities, err := w.provider().LoadBlockNBT(pos)
if err != nil {
return nil, fmt.Errorf("error loading block entities of chunk %v: %w", pos, err)
}
w.loadIntoBlocks(data, blockEntities)
return data, nil
}
// calculateLight calculates the light in the chunk passed and spreads the light of any of the surrounding
// neighbours if they have all chunks loaded around it as a result of the one passed.
func (w *World) calculateLight(c *chunk.Chunk, pos ChunkPos) {
c.Lock()
chunk.FillLight(c)
c.Unlock()
w.chunkMu.RLock()
for x := int32(-1); x <= 1; x++ {
for z := int32(-1); z <= 1; z++ {
// For all of the neighbours of this chunk, if they exist, check if all neighbours of that chunk
// now exist because of this one.
centrePos := ChunkPos{pos[0] + x, pos[1] + z}
neighbour, ok := w.chunks[centrePos]
if !ok {
continue
}
neighbour.Lock()
// We first attempt to spread the light of all neighbours into the ones around them.
w.spreadLight(neighbour.Chunk, centrePos)
neighbour.Unlock()
}
}
// If the chunk loaded happened to be in the middle of a bunch of other chunks, we are able to spread it
// right away, so we try to do that.
w.spreadLight(c, pos)
w.chunkMu.RUnlock()
}
// spreadLight spreads the light from the chunk passed at the position passed to all neighbours if each of
// them is loaded.
func (w *World) spreadLight(c *chunk.Chunk, pos ChunkPos) {
neighbours, allPresent := make([]*chunk.Chunk, 0, 8), true
for x := int32(-1); x <= 1; x++ {
for z := int32(-1); z <= 1; z++ {
neighbour, ok := w.chunks[ChunkPos{pos[0] + x, pos[1] + z}]
if !ok {
allPresent = false
break
}
if !(x == 0 && z == 0) {
neighbours = append(neighbours, neighbour.Chunk)
}
}
}
if allPresent {
for _, neighbour := range neighbours {
neighbour.Lock()
}
// All neighbours of the current one are present, so we can spread the light from this chunk
// to all neighbours.
chunk.SpreadLight(c, neighbours)
for _, neighbour := range neighbours {
neighbour.Unlock()
}
}
}
// loadIntoBlocks loads the block entity data passed into blocks located in a specific chunk. The blocks that
// have block NBT will then be stored into memory.
func (w *World) loadIntoBlocks(c *chunkData, blockEntityData []map[string]interface{}) {
c.e = make(map[BlockPos]Block, len(blockEntityData))
for _, data := range blockEntityData {
pos := blockPosFromNBT(data)
id := c.RuntimeID(uint8(pos[0]), uint8(pos[1]), uint8(pos[2]), 0)
b, ok := blockByRuntimeID(id)
if !ok {
w.log.Errorf("error loading block entity data: could not find block state by runtime ID %v", id)
continue
}
if nbt, ok := b.(NBTer); ok {
b = nbt.DecodeNBT(data).(Block)
}
c.e[pos] = b
}
}
// saveChunk is called when a chunk is removed from the cache. We first compact the chunk, then we write it to
// the provider.
func (w *World) saveChunk(pos ChunkPos, c *chunkData) {
c.Lock()
// We allocate a new map for all block entities.
m := make([]map[string]interface{}, 0, len(c.e))
for pos, b := range c.e {
// Encode the block entities and add the 'x', 'y' and 'z' tags to it.
data := b.(NBTer).EncodeNBT()
data["x"], data["y"], data["z"] = int32(pos[0]), int32(pos[1]), int32(pos[2])
m = append(m, data)
}
if !w.rdonly.Load() {
c.Compact()
if err := w.provider().SaveChunk(pos, c.Chunk); err != nil {
w.log.Errorf("error saving chunk %v to provider: %v", pos, err)
}
if err := w.provider().SaveEntities(pos, c.entities); err != nil {
w.log.Errorf("error saving entities in chunk %v to provider: %v", pos, err)
}
if err := w.provider().SaveBlockNBT(pos, m); err != nil {
w.log.Errorf("error saving block NBT in chunk %v to provider: %v", pos, err)
}
}
entities := c.entities
c.entities = nil
c.Unlock()
for _, entity := range entities {
_ = entity.Close()
}
}
// initChunkCache initialises the chunk cache of the world to its default values.
func (w *World) initChunkCache() {
w.chunkMu.Lock()
w.chunks = make(map[ChunkPos]*chunkData)
w.chunkMu.Unlock()
}
// chunkCacheJanitor runs until the world is closed, cleaning chunks that are no longer in use from the cache.
func (w *World) chunkCacheJanitor() {
t := time.NewTicker(time.Minute * 5)
defer t.Stop()
chunksToRemove := map[ChunkPos]*chunkData{}
for {
select {
case <-t.C:
w.chunkMu.Lock()
for pos, c := range w.chunks {
if len(c.v) == 0 {
chunksToRemove[pos] = c
delete(w.chunks, pos)
}
}
w.chunkMu.Unlock()
for pos, c := range chunksToRemove {
w.saveChunk(pos, c)
delete(chunksToRemove, pos)
}
case <-w.stopTick.Done():
return
}
}
}
// chunkData represents the data of a chunk including the block entities and viewers. This data is protected
// by the mutex present in the chunk.Chunk held.
type chunkData struct {
*chunk.Chunk
e map[BlockPos]Block
v []Viewer
entities []Entity
}
// newChunkData returns a new chunkData wrapper around the chunk.Chunk passed.
func newChunkData(c *chunk.Chunk) *chunkData {
return &chunkData{Chunk: c, e: map[BlockPos]Block{}}
}
<file_sep>package effect
import (
"github.com/df-mc/dragonfly/dragonfly/entity"
"image/color"
"time"
)
// ConduitPower is a lasting effect that grants the affected entity the ability to breathe underwater and
// allows the entity to break faster when underwater or in the rain. (Similarly to haste.)
type ConduitPower struct {
lastingEffect
}
// Multiplier returns the mining speed multiplier from this effect.
func (c ConduitPower) Multiplier() float64 {
v := 1 - float64(c.Lvl)*0.1
if v < 0 {
v = 0
}
return v
}
// WithDuration ...
func (c ConduitPower) WithDuration(d time.Duration) entity.Effect {
return ConduitPower{c.withDuration(d)}
}
// RGBA ...
func (c ConduitPower) RGBA() color.RGBA {
return color.RGBA{R: 0x1d, G: 0xc2, B: 0xd1, A: 0xff}
}
<file_sep>package effect
import (
"github.com/df-mc/dragonfly/dragonfly/entity"
"github.com/df-mc/dragonfly/dragonfly/entity/damage"
"image/color"
"time"
)
// FatalPoison is a lasting effect that causes the affected entity to lose health gradually. FatalPoison,
// unlike Poison, can kill the entity it is applied to.
type FatalPoison struct {
lastingEffect
}
// Apply ...
func (p FatalPoison) Apply(e entity.Living) {
interval := 50 >> p.Lvl
if tickDuration(p.Dur)%interval == 0 {
e.Hurt(1, damage.SourcePoisonEffect{Fatal: true})
}
}
// WithDuration ...
func (p FatalPoison) WithDuration(d time.Duration) entity.Effect {
return FatalPoison{p.withDuration(d)}
}
// RGBA ...
func (p FatalPoison) RGBA() color.RGBA {
return color.RGBA{R: 0x4e, G: 0x93, B: 0x31, A: 0xff}
}
<file_sep>package block
import (
"github.com/df-mc/dragonfly/dragonfly/block/wood"
"github.com/df-mc/dragonfly/dragonfly/item/tool"
"github.com/df-mc/dragonfly/dragonfly/world"
)
// Leaves are blocks that grow as part of trees which mainly drop saplings and sticks.
type Leaves struct {
noNBT
// Wood is the type of wood of the leaves. This field must have one of the values found in the material
// package.
Wood wood.Wood
// Persistent specifies if the leaves are persistent, meaning they will not decay as a result of no wood
// being nearby.
Persistent bool
shouldUpdate bool
}
// BreakInfo ...
func (l Leaves) BreakInfo() BreakInfo {
return BreakInfo{
Hardness: 0.2,
Harvestable: alwaysHarvestable,
Effective: func(t tool.Tool) bool {
return t.ToolType() == tool.TypeShears || t.ToolType() == tool.TypeHoe
},
// TODO: Add saplings and apples and drop them here.
Drops: simpleDrops(),
}
}
// EncodeItem ...
func (l Leaves) EncodeItem() (id int32, meta int16) {
switch l.Wood {
case wood.Oak():
return 18, 0
case wood.Spruce():
return 18, 1
case wood.Birch():
return 18, 2
case wood.Jungle():
return 18, 3
case wood.Acacia():
return 161, 0
case wood.DarkOak():
return 161, 1
}
panic("invalid wood type")
}
// LightDiffusionLevel ...
func (Leaves) LightDiffusionLevel() uint8 {
return 1
}
// CanDisplace ...
func (Leaves) CanDisplace(b world.Liquid) bool {
_, ok := b.(Water)
return ok
}
// SideClosed ...
func (Leaves) SideClosed(world.BlockPos, world.BlockPos, *world.World) bool {
return false
}
// EncodeBlock ...
func (l Leaves) EncodeBlock() (name string, properties map[string]interface{}) {
switch l.Wood {
case wood.Oak(), wood.Spruce(), wood.Birch(), wood.Jungle():
return "minecraft:leaves", map[string]interface{}{"old_leaf_type": l.Wood.String(), "persistent_bit": l.Persistent, "update_bit": l.shouldUpdate}
case wood.Acacia(), wood.DarkOak():
return "minecraft:leaves2", map[string]interface{}{"new_leaf_type": l.Wood.String(), "persistent_bit": l.Persistent, "update_bit": l.shouldUpdate}
}
panic("invalid wood type")
}
// Hash ...
func (l Leaves) Hash() uint64 {
return hashLeaves | (uint64(boolByte(l.Persistent)) << 32) | (uint64(boolByte(l.shouldUpdate)) << 33) | (uint64(l.Wood.Uint8()) << 34)
}
// allLogs returns a list of all possible leaves states.
func allLeaves() (leaves []world.Block) {
f := func(persistent, update bool) {
leaves = append(leaves, Leaves{Wood: wood.Oak(), Persistent: persistent, shouldUpdate: update})
leaves = append(leaves, Leaves{Wood: wood.Spruce(), Persistent: persistent, shouldUpdate: update})
leaves = append(leaves, Leaves{Wood: wood.Birch(), Persistent: persistent, shouldUpdate: update})
leaves = append(leaves, Leaves{Wood: wood.Jungle(), Persistent: persistent, shouldUpdate: update})
leaves = append(leaves, Leaves{Wood: wood.Acacia(), Persistent: persistent, shouldUpdate: update})
leaves = append(leaves, Leaves{Wood: wood.DarkOak(), Persistent: persistent, shouldUpdate: update})
}
f(true, true)
f(true, false)
f(false, true)
f(false, false)
return
}
<file_sep>package effect
import (
"github.com/df-mc/dragonfly/dragonfly/entity"
"image/color"
"time"
)
// Nausea is a lasting effect that causes the screen to warp, similarly to when entering a nether portal.
type Nausea struct {
lastingEffect
}
// WithDuration ...
func (n Nausea) WithDuration(d time.Duration) entity.Effect {
return Nausea{n.withDuration(d)}
}
// RGBA ...
func (Nausea) RGBA() color.RGBA {
return color.RGBA{R: 0x55, G: 0x1d, B: 0x4a, A: 0xff}
}
<file_sep>package block
import (
"github.com/df-mc/dragonfly/dragonfly/block/colour"
"github.com/df-mc/dragonfly/dragonfly/item"
"github.com/df-mc/dragonfly/dragonfly/world"
"github.com/go-gl/mathgl/mgl64"
)
// GlazedTerracotta is a vibrant solid block that comes in the 16 regular dye colours.
type GlazedTerracotta struct {
noNBT
// Colour specifies the colour of the block.
Colour colour.Colour
// Facing specifies the face of the block.
Facing world.Direction
}
// BreakInfo ...
func (t GlazedTerracotta) BreakInfo() BreakInfo {
return BreakInfo{
Hardness: 1.4,
Harvestable: pickaxeHarvestable,
Effective: pickaxeEffective,
Drops: simpleDrops(item.NewStack(t, 1)),
}
}
// EncodeItem ...
func (t GlazedTerracotta) EncodeItem() (id int32, meta int16) {
// Item ID for glazed terracotta is equal to 220 + colour number.
return int32(220 + t.Colour.Uint8()), meta
}
// EncodeBlock ...
func (t GlazedTerracotta) EncodeBlock() (name string, properties map[string]interface{}) {
colourName := t.Colour.String()
if t.Colour == colour.LightGrey() {
// Light grey is actually called "silver" in the block state. Mojang pls.
colourName = "silver"
}
return "minecraft:" + colourName + "_glazed_terracotta", map[string]interface{}{"facing_direction": int32(2 + t.Facing)}
}
// Hash ...
func (t GlazedTerracotta) Hash() uint64 {
return hashGlazedTerracotta | (uint64(t.Colour.Uint8()) << 32)
}
// UseOnBlock ensures the proper facing is used when placing a glazed terracotta block, by using the opposite of the player.
func (t GlazedTerracotta) UseOnBlock(pos world.BlockPos, face world.Face, _ mgl64.Vec3, w *world.World, user item.User, ctx *item.UseContext) (used bool) {
pos, _, used = firstReplaceable(w, pos, face, t)
if !used {
return
}
t.Facing = user.Facing().Opposite()
place(w, pos, t, user, ctx)
return placed(ctx)
}
// allGlazedTerracotta returns glazed terracotta blocks with all possible colours.
func allGlazedTerracotta() []world.Block {
b := make([]world.Block, 0, 16)
for _, c := range colour.All() {
b = append(b, GlazedTerracotta{Colour: c})
}
return b
}
|
00af8c23256204c0b6ea93afc6d4c442afdc2333
|
[
"TOML",
"Go Module",
"Go"
] | 102
|
Go
|
dragonfly-tech/dragonfly
|
d41c96a75dc28dc10b4706e83f90bb498f2d724c
|
7a2e29b28b2744ca86e9cd4f7f71bbcfd64a8da2
|
refs/heads/master
|
<file_sep>import requests
long_url = input("Input Long URL : ")
if not long_url:
print("Empty Long URL")
exit()
# Credential Authentication
username = "o_4lovj8rfbu"
password = "<PASSWORD>"
# Log In to Get Access Token
auth_response = requests.post(
"https://api-ssl.bitly.com/oauth/access_token",
auth=(username, password)
)
if auth_response.status_code == 200:
access_token = auth_response.content.decode()
else:
print("Authentication Failed!")
exit()
# Get GUID to Shortener URL
headers = {"Authorization": f"Bearer {access_token}"}
group_response = requests.get(
"https://api-ssl.bitly.com/v4/groups",
headers=headers
)
if group_response.status_code == 200:
guid = group_response.json()['groups'][0]['guid']
else:
print("Get Group Failed!")
exit()
# Request Shorten URL
shorten_response = requests.post(
"https://api-ssl.bitly.com/v4/shorten",
json={"group_guid": guid, "long_url": long_url},
headers=headers
)
if shorten_response.status_code == 200:
shorten_url = shorten_response.json()['link']
else:
print("Request Shorten URL Failed!")
exit()
print(f"Shorten URL : {shorten_url}")<file_sep>Using Bitly API
https://bitly.com/
|
da33b34db878b081b8675677b74cebdb38bf42d9
|
[
"Markdown",
"Python"
] | 2
|
Python
|
alfigufron/python-shortener-url
|
289fc787293a8dd93ab789de5279a928651dfabe
|
12c92e85bd6bbdf96920ffafbaeb8d83573d6849
|
refs/heads/master
|
<file_sep>package test
import (
http "github.com/gruntwork-io/terratest/modules/http-helper"
"github.com/gruntwork-io/terratest/modules/terraform"
"github.com/stretchr/testify/assert"
"log"
"testing"
"time"
)
func TestTerraformBasicExample(t *testing.T) {
// GIVEN the following tf resources
terraformOptions := infrastructureOptions(t)
// WHEN we apply them
terraform.InitAndApply(t, terraformOptions)
// THEN an http server returning hello world is provisioned
validateHttpServer(t, terraformOptions)
}
func infrastructureOptions(t *testing.T) *terraform.Options {
t.Parallel()
terraformOptions := &terraform.Options{
TerraformDir: "../main",
Vars: map[string]interface{}{},
VarFiles: []string{"varfile.tfvars"},
NoColor: true,
}
defer terraform.Destroy(t, terraformOptions)
return terraformOptions
}
func validateHttpServer(t *testing.T, opts *terraform.Options) {
const timeout = 5 * time.Second
assert.NotNil(t, terraform.Output(t, opts, "ip"))
url := "http://" + terraform.Output(t, opts, "ip") + ":8080"
http.HttpGetWithRetry(t, url, nil, 200,
"Hello, World", 10, timeout)
log.Print("Http server is up and running")
}
<file_sep>.PHONY: test
EXECUTABLES = terraform go config-lint
K := $(foreach exec,$(EXECUTABLES),\
$(if $(shell which $(exec)),some string,$(error "No $(exec) in PATH, please install before running make")))
build: init validate lint test
init :
cd main; terraform init .
format :
cd main; terraform fmt -recursive .
validate :
cd main; terraform validate . && terraform plan .
lint :
config-lint -terraform main/main.tf
test :
cd test; go test -v -timeout 30m
|
5d6d99553e75e5ff734593ec4fe9feefda370851
|
[
"Makefile",
"Go"
] | 2
|
Go
|
victorcosquithoughtworks/terraform-gcp-test
|
67d7d5bfde351fdef98885774eb50c38d5d0bcc8
|
84d4c79ba226761f3702b1367e3100581c3288e2
|
refs/heads/master
|
<repo_name>npololnskii/tt<file_sep>/src/main/java/ActionFactory.java
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
/**
* Created by nick on 31.07.16.
*/
public class ActionFactory
{
private Action act=null;
private static HashMap<String,Action> actions=new HashMap<String, Action>();
static
{
actions.put("GET/login",new LoginAction());
}
public static Action getAction(HttpServletRequest request) {
return actions.get(request.getMethod() + request.getPathInfo());
}
}
<file_sep>/deploy.sh
#!/bin/bash
rm -rf /opt/Tomcat8/webapps/tt*
mvn clean
mvn install
mvn clean tomcat7:deploy
|
71e4920e73ebce94abac691c32be32a52253adcd
|
[
"Java",
"Shell"
] | 2
|
Java
|
npololnskii/tt
|
b8d9bd387ba7ed875c9f2281d005ea330df05e78
|
efa4c64d12a6e678869414e306c0be78cda63718
|
refs/heads/main
|
<file_sep>package bgu.spl181.net.srv;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.concurrent.ConcurrentHashMap;
import bgu.spl181.net.srv.data.Database;
import bgu.spl181.net.srv.data.User;
public class MovieRentalServiceProtocol extends UserServiceTextbasedprotocol {
Database db;//data mangment .
ConcurrentHashMap<String, Integer> loggedinusers;//shared info .
public MovieRentalServiceProtocol(SharedProtocolData sharedata) {
super(sharedata);
db = new Database(sharedata);
this.loggedinusers = this.shareddata.getlogedinusers();
}
@Override
public void process(String message) {
String[] messagesplited = message.split(" ");
//login
if (messagesplited[0].equalsIgnoreCase("login")) {
this.shareddata.getuserlock().writeLock().lock();
db.clear();
db.readfromusers();
login(message.substring(6));
this.shareddata.getuserlock().writeLock().unlock();
}
///signout.
if (messagesplited[0].equalsIgnoreCase("SIGNOUT")) {
this.shareddata.getuserlock().writeLock().lock();
db.clear();
db.readfromusers();
signout(message.substring(7));
db.updateusers();
this.shareddata.getuserlock().writeLock().unlock();
}//reg.
if (messagesplited[0].equalsIgnoreCase("REGISTER")) {
this.shareddata.getuserlock().writeLock().lock();
db.clear();
db.readfromusers();
register(message.substring(9));
db.updateusers();
this.shareddata.getuserlock().writeLock().unlock();
}//balanceinfo.
if (message.equalsIgnoreCase("REQUEST balance info")) {
this.shareddata.getuserlock().readLock().lock();
db.clear();
db.readfromusers();
this.reqbalanceinf();
this.shareddata.getuserlock().readLock().unlock();
}//add balance.
if (messagesplited[0].equalsIgnoreCase("REQUEST") && messagesplited[1].equalsIgnoreCase("balance")
&& messagesplited[2].equalsIgnoreCase("add")) {
this.shareddata.getuserlock().writeLock().lock();
db.clear();
db.readfromusers();
if(messagesplited.length>3)
this.addbalance(messagesplited[3]);
db.updateusers();
this.shareddata.getuserlock().writeLock().unlock();
} // movie info.
if (messagesplited[0].equalsIgnoreCase("REQUEST") && messagesplited[1].equalsIgnoreCase("info")) {
this.shareddata.getmovieslock().readLock().lock();
this.shareddata.getuserlock().readLock().lock();
db.clear();
db.readfromusers();
db.readfrommovies();
if (messagesplited.length > 2) {
this.reqinfo(message.substring(message.indexOf('"') + 1, message.length() - 1));
} else {
this.reqinfo("");
}
this.shareddata.getuserlock().readLock().unlock();
this.shareddata.getmovieslock().readLock().unlock();
} // rent movie.
if (messagesplited[0].equalsIgnoreCase("REQUEST") && messagesplited[1].equalsIgnoreCase("rent")) {
this.shareddata.getmovieslock().writeLock().lock();
this.shareddata.getuserlock().writeLock().lock();
db.clear();
db.readfrommovies();
db.readfromusers();
this.rentmovi(message.substring(13));
db.updateusers();
db.updatemovies();
this.shareddata.getuserlock().writeLock().unlock();
this.shareddata.getmovieslock().writeLock().unlock();
} // return movei
if (messagesplited[0].equalsIgnoreCase("REQUEST") && messagesplited[1].equalsIgnoreCase("return")) {
this.shareddata.getmovieslock().writeLock().lock();
this.shareddata.getuserlock().writeLock().lock();
db.clear();
db.readfrommovies();
db.readfromusers();
this.returnmovie(message.substring(message.indexOf('"') + 1, message.length() - 1));
db.updateusers();
db.updatemovies();
this.shareddata.getuserlock().writeLock().unlock();
this.shareddata.getmovieslock().writeLock().unlock();
} // addmovie
if (messagesplited[0].equalsIgnoreCase("REQUEST") && messagesplited[1].equalsIgnoreCase("addmovie")) {
this.shareddata.getmovieslock().writeLock().lock();
this.shareddata.getuserlock().readLock().lock();
db.clear();
db.readfrommovies();
db.readfromusers();
message = message.substring(17);
this.addmovie(message);
db.updatemovies();
this.shareddata.getuserlock().readLock().unlock();
this.shareddata.getmovieslock().writeLock().unlock();
} // remmovie
if (messagesplited[0].equalsIgnoreCase("REQUEST") && messagesplited[1].equalsIgnoreCase("remmovie")) {
this.shareddata.getmovieslock().writeLock().lock();
this.shareddata.getuserlock().readLock().lock();
db.clear();
db.readfrommovies();
db.readfromusers();
message = message.substring(17);
this.removie(message);
db.updatemovies();
this.shareddata.getuserlock().readLock().unlock();
this.shareddata.getmovieslock().writeLock().unlock();
} // changeprice.
if (messagesplited[0].equalsIgnoreCase("REQUEST") && messagesplited[1].equalsIgnoreCase("changeprice")) {
this.shareddata.getmovieslock().writeLock().lock();
this.shareddata.getuserlock().readLock().lock();
db.clear();
db.readfrommovies();
db.readfromusers();
message = message.substring(20);
this.chnagemovieprice(message);
db.updatemovies();
this.shareddata.getuserlock().readLock().unlock();
this.shareddata.getmovieslock().writeLock().unlock();
}
}
@Override
public void register(String data) {//reg.
String username = "";
String pass = "";
String country = "";
boolean flag = false;
String[] message = data.split(" ");
if (message.length > 2) {
username = message[0];
pass = message[1];
country = message[2].substring(message[2].indexOf('"') + 1, message[2].length() - 1);
if (!(username.equals("") | pass.equals("") | country.equals("")))
if (!country.matches(".*\\d.*")) {
flag = db.adduser(username, pass, country);
}
if (flag) {
this.connections.send(connectionid, "ACK registration succeeded");
} else
this.connections.send(connectionid, "ERROR registration failed");
}else
this.connections.send(connectionid, "ERROR registration failed");
}
@Override
public void login(String data) {//login
String username = "";
String pass = "";
String[] dataarray = data.split(" ");
username = dataarray[0];
pass = dataarray[1];
User u = db.finduserwithname(username);
if (u != null && u.getpass().equals(pass) && !loggedinusers.containsKey(username) && !logedin) {
loggedinusers.put(username, connectionid);
logedin = true;
this.userName = username;
connections.send(connectionid, "ACK login succeeded");
} else
connections.send(connectionid, "ERROR login failed");
}
public void reqinfo(String message) {//movie info.
if (this.logedin)
this.connections.send(connectionid, db.movieinfo(message));
else
this.connections.send(connectionid, "ERROR request info failed");
}
public void reqbalanceinf() {//balanceinfo.
if (this.logedin) {
this.connections.send(connectionid, db.balanceinfo(userName));
} else
this.connections.send(connectionid, "ERROR request balance failed");
}
public void addbalance(String message) {//balance to add.
if (this.logedin) {
int amount = Integer.parseInt(message);
this.connections.send(connectionid, db.addamount(amount, this.userName));
} else
this.connections.send(connectionid, "ERROR request balance add failed");
}
public void rentmovi(String message) {//rent moveis.
String regex = Character.toString('"');
String[] messagesplt = message.split(regex);
message = messagesplt[1];
if (this.logedin) {
if (db.rentmovie(userName, message)) {
String ans = "ACK rent " + '"' + message + '"' + " success";
this.connections.send(connectionid, (ans));
this.BroadCast("BROADCAST movie " + '"' + message + '"' + " "
+ db.findmoviewithname(message).getavamount() + " " + db.findmoviewithname(message).getprice());
} else
this.connections.send(connectionid, "ERROR request rent failed");
} else
this.connections.send(connectionid, "ERROR request rent failed");
}
public void returnmovie(String message) {//return moveis.
if (this.logedin && db.returnmovie(message, userName)) {
this.connections.send(connectionid, "ACK return " + '"' + message + '"' + " success");
this.BroadCast("BROADCAST movie " + '"' + message + '"' + " " + db.findmoviewithname(message).getavamount()
+ " " + db.findmoviewithname(message).getprice());
} else
this.connections.send(connectionid, "ERROR request return failed");
}
/*admin commands*/
public void addmovie(String message) {
String moviename = "";
String regex = Character.toString('"');
String[] messagesplt = message.split(regex);
moviename = messagesplt[1];
String amount = messagesplt[2].substring(1);
amount = amount.substring(0, amount.indexOf(' '));
String price = messagesplt[2].substring(1);
if (messagesplt.length > 3) {
price = price.substring(price.indexOf(' ') + 1, price.length() - 1);
ArrayList<String> countries = new ArrayList<String>();
for (int i = 3; i < messagesplt.length; i = i + 2) {
countries.add(messagesplt[i]);
}
if (this.logedin
&& db.addmovie(userName, moviename, Integer.parseInt(price), Integer.parseInt(amount), countries)) {
this.connections.send(connectionid, "ACK addmovie " + '"' + moviename + '"' + " success");
this.BroadCast("BROADCAST movie " + '"' + moviename + '"' + " " + Integer.parseInt(amount) + " "
+ Integer.parseInt(price));
} else
this.connections.send(connectionid, "ERROR request addmovie failed");
} else {
price = price.substring(price.indexOf(' ') + 1);
if (this.logedin && db.addmovie(userName, moviename, Integer.parseInt(price), Integer.parseInt(amount),
new ArrayList<String>())) {
this.connections.send(connectionid, "ACK addmovie " + '"' + moviename + '"' + " success");
this.BroadCast("BROADCAST movie " + '"' + moviename + '"' + " " + Integer.parseInt(amount) + " "
+ Integer.parseInt(price));
} else
this.connections.send(connectionid, "ERROR request addmovie failed");
}
}
public void removie(String message) {
String movie = message.substring(1, message.length() - 1);
if (this.logedin && db.removie(userName, movie)) {
this.connections.send(connectionid, "ACK remmovie " + '"' + movie + '"' + " success");
this.BroadCast("BROADCAST movie " + '"' + movie + '"' + " removed");
} else
this.connections.send(connectionid, " ERROR request remmovie failed");
}
public void chnagemovieprice(String message) {
String regex = Character.toString('"');
String[] messagesplt = message.split(regex);
String movie = messagesplt[1];
String price = messagesplt[2].substring(1);
if (this.logedin && db.changeprice(this.userName, movie, Integer.parseInt(price))) {
this.connections.send(connectionid, "ACK changeprice " + '"' + movie + '"' + " success");
this.BroadCast("BROADCAST movie " + '"' + movie + '"' + " " + db.findmoviewithname(movie).getavamount()
+ " " + db.findmoviewithname(movie).getprice());
} else
this.connections.send(connectionid, "ERROR request changeprice failed");
}
}
<file_sep>package bgu.spl181.net.srv.data;
import java.io.Serializable;
import java.util.ArrayList;
public class Movie implements Serializable {
String id;
String name;
String price = "0";
ArrayList<String> bannedCountries;
String availableAmount = "0";
String totalAmount = "0";
public Movie(String Id, String Name, String Price, ArrayList<String> BannedCountries, String TotalAmount) {
this.availableAmount = TotalAmount;
this.bannedCountries = BannedCountries;
this.id = Id;
this.price = Price;
this.totalAmount = TotalAmount;
this.name = Name;
}
public void setavam(int availableAmount) {
this.availableAmount = Integer.toString(availableAmount);
}
public int getavamount() {
return Integer.parseInt(availableAmount);
}
public int getprice() {
return Integer.parseInt(price);
}
public void setprice(int newprice) {
this.price=Integer.toString(newprice);
}
public int gettotalAmount() {
return Integer.parseInt(totalAmount);
}
public String getname() {
return this.name;
}
public String getId() {
return this.id;
}
public ArrayList<String> getbanned() {
return this.bannedCountries;
}
}
<file_sep>package bgu.spl181.net.srv.data;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Writer;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.concurrent.ConcurrentHashMap;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import bgu.spl181.net.srv.SharedProtocolData;
/*data mangment object*/
public class Database {
final String Diruser = "Database/Users.json";// diricotries for the data
final String Dirmovie = "Database/Movies.json";
Users users;
movies movies;
FileWriter writer;
SharedProtocolData sharedata;
ConcurrentHashMap<String, Integer> loggedinusers;
public Database(SharedProtocolData sharedata) {
users = new Users(new ArrayList<User>());
movies = new movies(new ArrayList<Movie>());
this.sharedata = sharedata;
loggedinusers = new ConcurrentHashMap<String, Integer>();
}
public User finduserwithname(String s)//// to get the wanted user with its
//// objects that holdss all the
//// data.
{
ArrayList<User> userslist = users.getlist();
for (int i = 0; i < userslist.size(); i++) {
if (userslist.get(i).getUser().equals(s))
return userslist.get(i);
}
return null;
}
public Movie findmoviewithname(String s)////// to get the wanted movie with
////// its objects that holds all
////// the data.
{
ArrayList<Movie> movielist = movies.getlist();
for (int i = 0; i < movielist.size(); i++) {
if (movielist.get(i).getname().equals(s))
return movielist.get(i);
}
return null;
}
public String balanceinfo(String user)//// for the balance info command.
{
User u = this.finduserwithname(user);
if (u != null)
return "ACK balance " + u.getbalance();
else
return null;
}
public String addamount(int addedamount, String user)// for adding amout
// command .
{
User u = this.finduserwithname(user);
u.setbalance(u.getbalance() + addedamount);
return "ACK balance " + u.getbalance() + " added " + addedamount;
}
public String movieinfo(String moviename)// for the info about specific or
// all the movies.
{
ArrayList<Movie> movieslist = movies.getlist();
String ans = "ACK info ";
String ans2 = "ACK info ";
int i = 0;
if (moviename == "") {
for (i = 0; i < movieslist.size() - 1; i++) {
ans = ans + '"' + movieslist.get(i).getname() + '"' + " ";
}
ans = ans + '"' + movieslist.get(i).getname() + '"';
return ans;
} else {
Movie m = this.findmoviewithname(moviename);
if (m != null) {
ans2 = ans2 + '"' + m.getname() + '"' + " " + m.getavamount() + " " + m.getprice() + " ";
ArrayList<String> bannedcountries = m.getbanned();
if (!bannedcountries.isEmpty()) {
for (i = 0; i < bannedcountries.size() - 1; i++) {
ans2 = ans2 + '"' + bannedcountries.get(i) + '"' + " ";
}
ans2 = ans2 + '"' + bannedcountries.get(i) + '"';
}
return ans2;
} else
return "ERROR request info failed";
}
}
public boolean rentmovie(String username, String moviename)// for renting
// movie for
// user command.
{
Movie m = this.findmoviewithname(moviename);
User u = this.finduserwithname(username);
if (m == null | u == null)
return false;
if (u.getbalance() < m.getprice() | m.getavamount() == 0 | m.getbanned().contains(u.getcountry()))
return false;
ArrayList<MovieInUser> usermovies = u.getmovies();
for (int i = 0; i < usermovies.size(); i++) {
if (usermovies.get(i).getId().equals(m.getId()))
return false;
}
u.setbalance(u.getbalance() - m.getprice());
m.setavam(m.getavamount() - 1);
usermovies.add(new MovieInUser(m.getId(), moviename));
return true;
}
public boolean returnmovie(String moviename, String username)////// for
////// returning
////// the
////// movie
////// back
////// for
////// the
////// user
////// command
{
User u = this.finduserwithname(username);
Movie m = this.findmoviewithname(moviename);
boolean flag = false;
if (m == null)
return false;
ArrayList<MovieInUser> usermovies = u.getmovies();
for (int i = 0; i < usermovies.size() & !flag; i++) {
if (usermovies.get(i).getName().equals(moviename)) {
flag = true;
usermovies.remove(i);
m.setavam(m.getavamount() + 1);
}
}
return flag;
}
public boolean addmovie(String username, String moviename, int price, int totalamount,
ArrayList<String> bannedcountry)// adding new movie ////admin
// command.
{
User u = this.finduserwithname(username);
if (u == null || !u.gettype().equals("admin"))
return false;
if (price <= 0 | totalamount <= 0)
return false;
ArrayList<Movie> movieslist = movies.getlist();
for (int i = 0; i < movieslist.size(); i++) {
if (movieslist.get(i).getname().equals(moviename))
return false;
}
movieslist.add(new Movie(Integer.toString(this.getnextindex()), moviename, Integer.toString(price),
bannedcountry, Integer.toString(totalamount)));
return true;
}
public boolean removie(String username, String moviename)///// removing
///// movie
///// ///admin
///// command
{
User u = this.finduserwithname(username);
Movie m = this.findmoviewithname(moviename);
if (u == null || m == null || !u.gettype().equals("admin") || m.gettotalAmount() - m.getavamount() != 0)
return false;
movies.getlist().remove(m);
return true;
}
public boolean changeprice(String username, String moviename, int price)//// changing
//// price
//// of
//// a
//// movie
//// ///admin
//// command.
{
User u = this.finduserwithname(username);
Movie m = this.findmoviewithname(moviename);
if (u == null || m == null || !u.gettype().equalsIgnoreCase("admin") || price <= 0)
return false;
m.setprice(price);
return true;
}
public boolean adduser(String username, String pass, String country) {// adding
// users
// ..reg
// command.
if (this.finduserwithname(username) == null) {
users.getlist().add(new User(username, pass, "normal", country, new ArrayList<MovieInUser>(), "0"));
return true;
}
return false;
}
/* getter for fields if wanted */
public movies getmovies() {
return this.movies;
}
public Users getusers() {
return this.users;
}
public void clear() {
users.getlist().clear();
movies.getlist().clear();
}
public int getnextindex() {
int ans = 1;
for (int i = 0; i < movies.getlist().size(); i++)
if (Integer.parseInt(movies.getlist().get(i).getId()) > ans)
ans = Integer.parseInt(movies.getlist().get(i).getId());
return ans + 1;
}
public void updateusers() {////// for updating the json file database each
////// time data is changed in the server.
try {
writer = new FileWriter(Diruser);
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String s = gson.toJson(users, users.getClass());
writer.write(s);
writer.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void updatemovies() {////// for updating the json file database each
////// time data is changed in the server.
try {
Gson gson = new GsonBuilder().setPrettyPrinting().create();
writer = new FileWriter(Dirmovie);
gson = new GsonBuilder().setPrettyPrinting().create();
String s2 = gson.toJson(movies, movies.getClass());
writer.write(s2);
writer.flush();
} catch (
IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void readfromusers() {
JSONParser parser = new JSONParser();
try {
Reader reader = new InputStreamReader(new FileInputStream(Diruser));
JSONObject jo = (JSONObject) parser.parse(reader);
JSONArray jarr = (JSONArray) jo.get("users");
JSONArray jarr2;
JSONObject jo2;
ArrayList<User> userslist = users.getlist();
for (int i = 0; i < jarr.size(); i++) {
jo = (JSONObject) jarr.get(i);
String username = (String) jo.get("username");
String type = (String) jo.get("type");
String pass = (String) jo.get("password");
String country = (String) jo.get("country");
ArrayList<MovieInUser> movies = new ArrayList<MovieInUser>();
jarr2 = (JSONArray) jo.get("movies");
for (int j = 0; j < jarr2.size(); j++) {
jo2 = (JSONObject) jarr2.get(j);
String Id = (String) jo2.get("id");
String name = (String) jo2.get("name");
movies.add(new MovieInUser(Id, name));
}
String balance = (String) jo.get("balance");
userslist.add(new User(username, pass, type, country, movies, balance));
}
} catch (IOException | ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void readfrommovies() {
try {
InputStreamReader reader = new InputStreamReader(new FileInputStream(Dirmovie));
JSONParser parser = new JSONParser();
JSONObject jo;
jo = (JSONObject) parser.parse(reader);
JSONArray jarr = (JSONArray) jo.get("movies");
ArrayList<Movie> movieslist = movies.getlist();
for (int i = 0; i < jarr.size(); i++) {
jo = (JSONObject) jarr.get(i);
String id = (String) jo.get("id");
String name = (String) jo.get("name");
String price = (String) jo.get("price");
String availableAmount = (String) jo.get("availableAmount");
ArrayList<String> bannedCountries = new ArrayList<String>();
JSONArray jarr2 = (JSONArray) jo.get("bannedCountries");
for (int j = 0; j < jarr2.size(); j++) {
bannedCountries.add((String) jarr2.get(j));
}
String totalAmount = (String) jo.get("totalAmount");
movieslist.add(new Movie(id, name, price, bannedCountries, totalAmount));
movieslist.get(i).setavam(Integer.parseInt(availableAmount));
}
} catch (IOException | ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
<file_sep>/*
* BBclient.cpp
*
* Created on: Jan 7, 2018
* Author: awadi
*/
#include "../include/connectionHandler.h"
using namespace std;
#include <string>
#include <iostream>
#include <boost/asio.hpp>
#include <boost/thread.hpp>
using boost::asio::ip::tcp;
using std::cin;
using std::cout;
using std::cerr;
using std::endl;
using std::string;
static void readkeyboard(ConnectionHandler* connectionHandler) {
while (1) {
const short bufsize = 1024;
char buf[bufsize];
std::cin.getline(buf, bufsize);
std::string line(buf);
if (!connectionHandler->sendLine(line)) {
return;
}
// connectionHandler.sendLine(line) appends '\n' to the message. Therefor we send len+1 bytes.
}
}
void start(ConnectionHandler* conn) {
boost::thread readfromkeybaord(readkeyboard, conn);
std::string answer;
while (1) {
if (!conn->getLine(answer)) {
break;
}
int len = answer.length();
// A C string must end with a 0 char delimiter. When we filled the answer buffer from the socket
// we filled up to the \n char - we must make sure now that a 0 char is also present. So we truncate last character.
answer.resize(len - 1);
std::cout<<answer<<std::endl;
if (answer == "ACK signout succeeded") {
return;
}
answer = "";
}
return;
}
int main(int argc, char *argv[]) {
if (argc < 3) {
std::cerr << "Usage: " << argv[0] << " host port" << std::endl << std::endl;
return -1;
}
std::string host = argv[1];
short port = atoi(argv[2]);
ConnectionHandler* connectionHandler = new ConnectionHandler(
host,port);
if (!connectionHandler->connect()) {
return 1;
}
start(connectionHandler);
delete connectionHandler;
return 0;
}
<file_sep>package bgu.spl181.net.srv;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import bgu.spl181.net.api.bidi.BidiMessagingProtocol;
import bgu.spl181.net.api.bidi.Connections;
public class UserServiceTextbasedprotocol implements BidiMessagingProtocol<String> {
ConcurrentHashMap<String, Integer> loggedinusers;
int connectionid = 0;
Connections<String> connections;
Boolean Shouldterminate = false;
boolean logedin = false;
String userName = "";
SharedProtocolData shareddata;
ConcurrentHashMap<String, String> registered;
public UserServiceTextbasedprotocol(SharedProtocolData sharedata) {
this.shareddata = sharedata;
this.loggedinusers = this.shareddata.getlogedinusers();
this.registered = this.shareddata.getregusers();
}
@Override
public void start(int connectionId, Connections<String> connections) {
this.connectionid = connectionId;
this.connections = connections;
}
@Override
public void process(String message) {
if (message.substring(0, 6).equalsIgnoreCase("LOGIN")) {
login(message.substring(6, message.length()));
}
if (message.equalsIgnoreCase("SIGNOUT")) {
login(message.substring(6, message.length()));
}
}
@Override
public boolean shouldTerminate() {
return this.Shouldterminate;
}
public void signout(String data) {
if (this.logedin) {
connections.send(connectionid, "ACK signout succeeded");
this.logedin = false;
loggedinusers.remove(userName);
this.connections.disconnect(connectionid);
this.Shouldterminate=true;
} else
connections.send(connectionid, "ERROR signout failed");
}
public void BroadCast(String message) {
for (Map.Entry<String, Integer> entry : loggedinusers.entrySet())
this.connections.send(entry.getValue(), message);
}
public void login(String data) {
int i = data.indexOf(' ');
String username = data.substring(0, i);
data = data.substring(i + 1, data.length());
String pass = data.substring(i + 1);
if (registered.containsKey(username) && registered.get(username).equals(pass)) {
if (!loggedinusers.containsKey(username) & !this.logedin) {
this.logedin = true;
this.loggedinusers.put(username, connectionid);
this.userName = username;
connections.send(connectionid, "ACK login succeeded");
}
}
}
public void register(String data) {
String username;
String pass;
username = data.substring(0, data.indexOf(' '));
data = data.substring(data.indexOf(' ') + 1);
pass = data.substring(0, data.length());
if (pass.indexOf(' ') != -1) {
if (username != "" && pass != "" && !this.registered.contains(username) && !this.logedin) {
this.registered.put(username, pass);
this.connections.send(connectionid, "ACK registration succeeded");
}
else
this.connections.send(connectionid, "ERROR registration failed");
}else this.connections.send(connectionid, "ERROR registration failed");
}
}
<file_sep>package bgu.spl181.net.impl.BBreactor;
import bgu.spl181.net.srv.MessageEncoderDecoderImpl;
import bgu.spl181.net.srv.MovieRentalServiceProtocol;
import bgu.spl181.net.srv.Server;
import bgu.spl181.net.srv.SharedProtocolData;
public class ReactorMain {
public static void main(String[] args) {
SharedProtocolData sharedobject=new SharedProtocolData();
Server<String> Reactor= Server.reactor(5,
Integer.parseInt(args[0]),
()-> new MovieRentalServiceProtocol(sharedobject) ,
()->new MessageEncoderDecoderImpl()
);
Reactor.serve();
}
}
<file_sep>package bgu.spl181.net.impl.BBtpc;
import bgu.spl181.net.srv.MessageEncoderDecoderImpl;
import bgu.spl181.net.srv.MovieRentalServiceProtocol;
import bgu.spl181.net.srv.Server;
import bgu.spl181.net.srv.SharedProtocolData;
public class TPCMain {
public static void main(String[] args) {
SharedProtocolData sharedobject=new SharedProtocolData();
Server<String> TPC= Server.threadPerClient(
Integer.parseInt(args[0]),
()-> new MovieRentalServiceProtocol(sharedobject) ,
()->new MessageEncoderDecoderImpl()
);
TPC.serve();
}
}
<file_sep>package bgu.spl181.net.srv.data;
import java.io.Serializable;
public class MovieInUser implements Serializable {
String id;
String name;
public MovieInUser(String Id,String Name)
{
this.id=Id;
this.name=Name;
}
public String getId()
{
return id;
}
public String getName()
{
return name;
}
}
<file_sep># MovieRental
an online movie rental service, server and client.
Assignment specification listed in assignment3.pdf.
|
bc23bb66e793ac6613ddbbc2dd1524b7449c752d
|
[
"Markdown",
"Java",
"C++"
] | 9
|
Java
|
Awadibra/MovieRental
|
cd5a7878e4adf3ef30e386fbf5773e09b8c5a23a
|
8224d0ae16a3631e0efe7a1aa9a808c9d7689895
|
refs/heads/master
|
<repo_name>jihoshin28/sinatra-basic-routes-lab-sf-web-102819<file_sep>/app.rb
require_relative 'config/environment'
class App < Sinatra::Base
get '/name' do
"My name is <NAME>."
end
get '/hometown' do
"My hometown is Fremont, California."
end
get '/favorite-song' do
"My favorite song is Follow God by Kanye West."
end
end
|
16fc8178ddf3b7da7b751c0cf5aeafc01ea436ef
|
[
"Ruby"
] | 1
|
Ruby
|
jihoshin28/sinatra-basic-routes-lab-sf-web-102819
|
ae71ee050eda3792aa6e2dd53940e7873300981d
|
32d270043d127ea3f65e08f577f27ab6b5a6d2c8
|
refs/heads/master
|
<repo_name>umsu2/hacker_rank_practice<file_sep>/electronics_shop_question/main.go
package main
import (
"fmt"
"sort"
)
var array1 = []int{1, 4, 5, 1, 3, 2, 45, 6, 3, 4, 67, 7}
var array2 = []int{3, 4, 6, 7, 8, 39, 20, 34}
func main() {
v := findMaxValue(array1, array2, 4)
fmt.Println(v)
}
// finds the closest value to target but not greater than target
// if array1 is size N, array2 is size M, and if M > N, the overall speed is O(mLogn)
// m binary searches on array n O(mLogn) plus nLogn on sorting of the smaller array
func findMaxValue(array1, array2 []int, target int) int {
sortedArray := array1
iteratingArray := array2
if len(array1) < len(array2) {
sort.Ints(array1)
} else {
sortedArray = array2
iteratingArray = array1
sort.Ints(array2)
}
sum := -1
for _, v := range iteratingArray {
val := target - v
r := modifiedBinarySearch(sortedArray, val)
if r < 0 {
continue
}
s := r + v
if s == target {
return target
} else if s > sum {
sum = s
}
}
return sum
}
// modifiedBinarySearch attempts to find a value closest to val, but not greater than val, if no value is found, return -1
// assuming sorted ASC
func modifiedBinarySearch(sorted []int, val int) int {
// assuming nothing cost 0 dollars and you must buy two things.
// some small optimizations
if val <= 0 {
return -1
}
if len(sorted) == 0 {
return -1
}
left := 0
right := len(sorted) - 1
min := sorted[left]
max := sorted[right]
if val < min {
return -1
}
if val == min || val == max {
return val
}
// do binary search
for true {
middle := (left + right) / 2
if middle == left {
return sorted[left]
}
if sorted[middle] == val {
return val
} else if sorted[middle] > val {
right = middle
} else {
left = middle
}
}
return -1
}
|
b2b645e9c9a685be257591d3e1e28cbdcc6c648f
|
[
"Go"
] | 1
|
Go
|
umsu2/hacker_rank_practice
|
6cf5f4d7871dddbb3a050d8e00dccf20b0f81c34
|
58575cdc1b1905c30dbaab253b132c55c5419358
|
refs/heads/master
|
<repo_name>dgskinner/GameOfLife<file_sep>/play.rb
require_relative "board"
require_relative "game"
starting_coordinates = [
[[1, 1], [1, 2], [1, 3], [2, 2], [2, 3], [2, 4]],
[[2, 1], [1, 2], [1, 3], [2, 4], [3, 2], [3, 3]],
[[2, 1], [2, 2], [1, 2], [0, 1], [1, 3]]
]
Game.new(starting_coordinates.sample)
<file_sep>/README.md
# Game Of Life
Based on [Conway's Game Of Life](http://en.wikipedia.org/wiki/Conway%27s_Game_of_Life).
To play, run the following from the terminal:
ruby play.rb
Feel free to visit the link above for inspiration regarding initial conditions.
<file_sep>/board.rb
class Board
attr_reader :grid
def initialize(coord_pairs)
@grid = Array.new(10){ Array.new(10, 0) }
self.fill(coord_pairs)
end
def display
@grid.each do |row|
row_display = ""
row.each do |cell|
row_display += cell == 1 ? " \u25A0".encode("utf-8") : " \u25A1".encode("utf-8")
end
puts row_display
end
end
def fill(coord_pairs)
coord_pairs.each do |coords|
row, col = coords[0], coords[1]
@grid[row][col] = 1
end
end
end
<file_sep>/game.rb
class Game
DIRECTIONS = [[1,1], [1,0], [0,1], [1,-1], [-1,1], [-1,-1], [-1,0], [0,-1]]
attr_reader :board
def initialize(coord_pairs)
@board = Board.new(coord_pairs)
self.play
end
def count_neighbors(coord)
neighbors = 0
DIRECTIONS.each do |dir|
row, col = coord[0] + dir[0], coord[1] + dir[1]
if row >= 0 && col >= 0 && row < 10 && col < 10 && @board.grid[row][col] == 1
neighbors += 1
end
end
neighbors
end
def play
while true
@board.display
puts
dying, born = [], []
(0..9).each do |row|
(0..9).each do |col|
neighbors = self.count_neighbors([row, col])
if @board.grid[row][col] == 1
dying << [row, col] if (neighbors < 2 || neighbors > 3)
else
born << [row, col] if neighbors == 3
end
end
end
dying.each{ |coord| @board.grid[coord[0]][coord[1]] = 0 }
born.each{ |coord| @board.grid[coord[0]][coord[1]] = 1 }
sleep(1)
end
end
end
|
0c3b80acdcc426cd679c38c500624fae7512532a
|
[
"Markdown",
"Ruby"
] | 4
|
Ruby
|
dgskinner/GameOfLife
|
aedb9c09664172762dbb0b8c8320eddb36af8c23
|
bd2fbac19df69f76ce0512f74bc762cbd749011f
|
refs/heads/master
|
<file_sep>#!/bin/bash
set -e
ln -sf ~/.vim/vimrc ~/.vimrc
touch ~/.vimrc.local
mkdir -p ~/.vim_undodir
vim +PlugUpdate +qall
|
2934171eca89e052bdf0fcb69c64f958822b5250
|
[
"Shell"
] | 1
|
Shell
|
metti/dotvim
|
320eeffa2e0784619e04f9ce560fc3d8b0dd01f2
|
23af162f3e194bc2e83efb5785202467927db8ae
|
refs/heads/master
|
<file_sep>#функция, читающая данные из файла, которые нужно зашифровать
def readFile(fileName):
file = open(fileName)
return file.read()
#функция шифрующая данные по алгоритму простой замены.
#принимает на вход строку которую нужно зашифровать и таблицу правил преобраорваний
def getCryptChar(key, value, cryptT):
subList = cryptT.get(key)
valueCrypt = subList.get(value)
return valueCrypt
def replace(inputData, simbolT, cryptT):
outData = ""; key = ""; value = ""
i = 0
while i < len(inputData):
value = inputData[i]
key = simbolT.get(value)
outData += getCryptChar(key, value, cryptT)
i +=1
return outData
def createCryptWord(textD, textK):
cryptWord = {}
i = 0; j = 0;
charD = ""
charK = ""
while i < len(textD):
if(j >= len(textK)):
j=0
charD = textD[i]
charK = textK[j]
cryptWord[charD] = charK
i +=1
j +=1
return cryptWord
simbolTable = {
'a':{'a':'@','g':'!','m':'^','o':'*','p':'#','r':'@'},
'g':{'a':'!','g':'^','m':'*','o':'#','p':'@','r':'!'},
'm':{'a':'^','g':'*','m':'#','o':'@','p':'!','r':'^'},
'o':{'a':'*','g':'#','m':'@','o':'!','p':'^','r':'*'},
'p':{'a':'#','g':'@','m':'!','o':'^','p':'*','r':'#'},
'r':{'a':'@','g':'!','m':'^','o':'*','p':'#','r':'@'},
}
inputData = readFile("metaData.txt")
keyWord = readFile("key.txt")
print("key:\t" + keyWord)
print("No crypt text:\t"+inputData)
res = createCryptWord(inputData, keyWord)
print("Crypt text:\t"+replace(inputData, simbolTable, res))
|
bf0940b71c26fdbd0e3c33400856beba729c986f
|
[
"Python"
] | 1
|
Python
|
ptrIslam123/CryptPython
|
c8e54d9a62a95e91b9bda221bbe4bb8a66bf0b47
|
83fea108a6405548c8d901a83483b91392202df6
|
refs/heads/master
|
<file_sep>/**
* Basic firebase init for FabricElements
*/
(function() {
'use strict';
const firebase = window.firebase;
if (typeof firebase === 'undefined') {
throw new Error('hosting/init-error: Firebase SDK not detected.');
}
// Initialize Firebase
firebase.initializeApp({
apiKey: '<KEY>',
authDomain: 'fabricelements.firebaseapp.com',
databaseURL: 'https://fabricelements.firebaseio.com',
projectId: 'fabricelements',
storageBucket: 'fabricelements.appspot.com',
messagingSenderId: '908593247251',
});
// set data property on dom-bind
let autobind = document.querySelector('dom-bind');
if (autobind) {
firebase.auth().onAuthStateChanged((user) => {
autobind.user = user;
autobind.signedIn = !(!user);
});
}
})();
<file_sep>## Install
#### yarn
```ssh
yarn add @fabricelements/firebase-config --dev
```
#### npm
```ssh
npm i @fabricelements/firebase-config --save-dev
```
#### bower
```ssh
bower i FabricElements/firebase-config --save-dev
```
|
cc561e0e9bcdce9f7f5e85f4ec5dbe6254db3dff
|
[
"JavaScript",
"Markdown"
] | 2
|
JavaScript
|
FabricElements/firebase-config
|
c92cbbf62b00e37f2019d36c2a6945b3c6fc1804
|
6dd4506ef068ca471fb070efc83e9278421dee29
|
refs/heads/master
|
<file_sep>#include <iostream>
#include <cstdlib>
using namespace std;
char data[105][105];
bool used[105][105];
int m, n;
void dfs(int i, int j)
{
if (i - 1 >= 0 && j - 1 >= 0 && data[i-1][j-1] == '@' && used[i-1][j-1] == false)
{
used[i-1][j-1] = true;
dfs(i-1, j-1);
}
if (i - 1 >= 0 && data[i-1][j] == '@' && used[i-1][j] == false)
{
used[i-1][j] = true;
dfs(i-1, j);
}
if (i - 1 >= 0 && j + 1 < n && data[i-1][j+1] == '@' && used[i-1][j+1] == false)
{
used[i-1][j+1] = true;
dfs(i-1, j+1);
}
if (j - 1 >= 0 && data[i][j-1] == '@' && used[i][j-1] == false)
{
used[i][j-1] = true;
dfs(i, j-1);
}
if (j + 1 < n && data[i][j+1] == '@' && used[i][j+1] == false)
{
used[i][j+1] = true;
dfs(i, j+1);
}
if (i + 1 < m && j - 1 >= 0 && data[i+1][j-1] == '@' && used[i+1][j-1] == false)
{
used[i+1][j-1] = true;
dfs(i+1, j-1);
}
if (i + 1 < m && data[i+1][j] == '@' && used[i+1][j] == false)
{
used[i+1][j] = true;
dfs(i+1, j);
}
if (i + 1 < m && j + 1 < n && data[i+1][j+1] == '@' && used[i+1][j+1] == false)
{
used[i+1][j+1] = true;
dfs(i+1, j+1);
}
}
int main()
{
while (cin >> m >> n && m)
{
getchar();
for (int i = 0; i < m; i++)
gets(data[i]);
int sum = 0;
memset(used, false, sizeof(used));
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
{
if (used[i][j] == false && data[i][j] == '@')
{
used[i][j] = true;
sum++;
dfs(i, j);
}
}
cout << sum << endl;
}
return 0;
}
<file_sep>#include <iostream>
#include <cstdlib>
using namespace std;
int h, w;
char data[25][25];
int used[25][25];
int sum;
void dfs(int i, int j)
{
if (i-1 >= 0 && data[i-1][j] == '.' && used[i-1][j] == false)
{
sum++;
used[i-1][j] = true;
dfs(i-1, j);
}
if (j-1 >= 0 && data[i][j-1] == '.' && used[i][j-1] == false)
{
sum++;
used[i][j-1] = true;
dfs(i, j-1);
}
if (j+1 < w && data[i][j+1] == '.' && used[i][j+1] == false)
{
sum++;
used[i][j+1] = true;
dfs(i, j+1);
}
if (i+1 < h && data[i+1][j] == '.' && used[i+1][j] == false)
{
sum++;
used[i+1][j] = true;
dfs(i+1, j);
}
}
int main()
{
while (cin >> w >> h && h && w)
{
getchar();
int start_x = 0, start_y = 0;
for (int i = 0; i < h; i++)
{
gets(data[i]);
for (int j = 0; j < w; j++)
{
if (data[i][j] == '@')
{
start_x = i;
start_y = j;
}
}
}
memset(used, false, sizeof(used));
sum = 0;
dfs(start_x, start_y);
cout << sum + 1 << endl;
}
return 0;
}
<file_sep>#include <iostream>
using namespace std;
char ch[10][10];
int n, m, t;
int end_x, end_y;
int sign;
int move[4][2] = {-1, 0, 1, 0, 0, -1, 0, 1}; // up down left right
int abs(int a)
{
return a >= 0 ? a : -a;
}
void dfs(int x, int y, int level)
{
if (sign == 1)
return ;
if (level == t && x == end_x && y == end_y)
{
sign = 1;
return ;
}
int temp = t - level - abs(end_x - x) - abs(end_y - y); // need distance must be even
if (temp < 0 || temp%2 != 0)
{
return ;
}
for (int i = 0; i < 4; i++)
{
int a, b;
a = x + move[i][0];
b = y + move[i][1];
if (a >= 0 && a < n && b >= 0 && b < m && ch[a][b] != 'X')
{
ch[a][b] = 'X';
dfs(a, b, level+1);
if (sign) return ;
ch[a][b] = '.';
}
}
return ;
}
int main()
{
while (cin >> n >> m >> t && (n || m || t))
{
getchar();
int wall = 0;
int start_x, start_y;
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
{
cin >> ch[i][j];
if (ch[i][j] == 'S')
{
start_x = i;
start_y = j;
}
else
{
if (ch[i][j] == 'D')
{
end_x = i;
end_y = j;
}
else if (ch[i][j] == 'X')
wall++;
}
}
if (n * m - wall <= t)
{
cout << "NO" << endl;
continue;
}
sign = 0;
ch[start_x][start_y] = 'X';
dfs(start_x, start_y, 0);
if (sign == 0)
cout << "NO" << endl;
else cout << "YES" << endl;
}
return 0;
}
<file_sep>1.kmp---->getnextval
void getnextval()
{
int i = 0, j = -1;
next[0] = -1;
if (j == -1 || data[i] == data[j])
next[++i] = ++j;
else j = next[j];
}
using kmp:
int j = 0;
for (int i = 0; i < n; i++)
{
if (j == -1 || a[i] == data[j])
{ i++, j++; }
else j = next[j];
}
2.floyd
<file_sep>#include <iostream>
using namespace std;
int max(int a, int b)
{
if (a > b) return a;
else return b;
}
int w[1005][1005];
int main()
{
int t;
while (cin >> t)
{
while (t > 0)
{
int n, bagsize;
cin >> n >> bagsize;
int vol[1005] = { 0 }, val[1005] = { 0 };
int i, j;
for (i = 1; i <= n; i++)
cin >> val[i];
for (i = 1; i <= n; i++)
cin >> vol[i];
for (i = 1; i <= n; i++)
{
for (j = 0; j <= bagsize; j++)
{
if (vol[i] <= j && w[i-1][j] < w[i-1][j-vol[i]] + val[i])
w[i][j] = w[i-1][j-vol[i]] + val[i];
else w[i][j] = w[i-1][j];
}
}
cout << w[n][bagsize] << endl;
t--;
}
}
return 0;
}
<file_sep>#include <iostream>
#include <cstring>
#include <cstdio>
#include <cstdlib>
#include <map>
#include <algorithm>
#include <vector>
#include <list>
#include <climits>
using namespace std;
const int inf = 0x3fffffff;
int main()
{
freopen("in.txt", "r", stdin);
freopen("out.txt", "w", stdout);
int cases = 1;
int n, m, q;
while (cin >> n >> m >> q && n && m && q)
{
if (cases > 1) cout << endl;
cout << "Case " << cases++ <<":" << endl;
int dist[305][305];
bool marked[305];
int tmp_m = m;
memset(marked, false, sizeof(marked));
while(tmp_m --)
{
int x, y, c;
cin >> x >> y >> c;
if (c < dist[x][y]) dist[x][y] = c;
}
int tmp_q = q;
for (int i = 0; i < n; i++)
{
dist[i][j] = 0;
for (int j = i + 1; j < n; j++)
dist[i][j] = inf;
}
while (tmp_q --)
{
int op, x, y;
cin >> op;
if (op == 0)
{
cin >> x;
if (marked[x])
cout << "ERROR! At point " << x << endl;
else marked[x] = true;
continue;
}
if (op == 1)
{
cin >> x >> y;
if (!marked[x] || !marked[y])
cout <<"ERROR! At path " << x << " to " << y << endl;
else
{
if (marked[x] && marked[y])
{
int i, j, k;
for (k = 0; k < n; k++)
{
if (!marked[k]) continue;
for (i = 0; i < n; i++)
if (!marked[i]) continue;
for (j = 0; j < n; j++)
{
if (!marked[j]) continue;
if (dist[i][j] > dist[i][k] + dist[k][j])
dist[i][j] = dist[i][k] + dist[k][j];
}
}
if (dist[x][y] != inf)
cout << dist[x][y] << endl;
else cout << "No such path" << endl;
}
}
continue;
}
}
}
return 0;
}
<file_sep>#include <iostream>
#include <algorithm>
using namespace std;
bool search(__int64 a[], int low, int high, __int64 key)
{
while (low <= high)
{
int mid = (high + low) / 2;
if (a[mid] == key)
return true;
else if (key < a[mid])
high = mid - 1;
else low = mid + 1;
}
return false;
}
__int64 ab[505 * 505];
int main()
{
int L, N, M;
int sign = 1;
while (cin >> L >> N >> M)
{
__int64 a[505] = { 0 }, b[505] = { 0 }, c[505] = { 0 };
for (int i = 0; i < L; i++)
cin >> a[i];
for (int i = 0; i < N; i++)
cin >> b[i];
for (int i = 0; i < M; i++)
cin >> c[i];
int num = 0;
for (int i = 0; i < L; i++)
for (int j = 0; j < N; j++)
ab[num++] = a[i] + b[j];
sort(ab, ab+num);
sort(c, c+M);
int S;
__int64 x = 0, x_c = 0;
cin >> S;
cout << "Case " << sign << ":" << endl;
for (int i = 0; i < S; i++)
{
cin >> x;
if (x < (c[0] + ab[0]) || x > (c[M-1] + ab[num-1]))
cout << "NO" << endl;
else
{
int j;
for (j = 0; j < M; j++)
{
x_c = x - c[j];
if (search(ab, 0, num - 1, x_c))
{
cout << "YES" << endl;
break;
}
}
if (j == M) cout << "NO" << endl;
}
}
sign++;
}
return 0;
}
<file_sep>#include <iostream>
using namespace std;
int min(int a, int b)
{
return a > b ? b : a;
}
const int MAX = 1000000;
int main()
{
int t;
while (cin >> t)
{
while (t > 0)
{
int before, after;
cin >> before >> after;
int weight = after - before;
int p[505] = { 0 }, w[505] = { 0 };
int dp[10005];
for (int i = 1; i <= weight; i++)
dp[i] = MAX;
dp[0] = 0;// if weight is 0,then it is full
int n;
cin >> n;
for (int i = 1; i <= n; i++)
cin >> p[i] >> w[i];
for (int i = 1; i <= n; i++)
for (int j = w[i]; j <= weight; j++)
dp[j] = min(dp[j], dp[j-w[i]] + p[i]);
if (dp[weight] == MAX)
cout << "This is impossible." << endl;
else cout << "The minimum amount of money in the piggy-bank is " << dp[weight] << "." << endl;
t--;
}
}
return 0;
}
<file_sep>template<class T> inline T max(T x, T y) { return x > y : x ? y; }
template<class T> inline T min(T x, T y) { return x > y : y ? x; }
<file_sep>#include <iostream>
#include <queue>
using namespace std;
bool visited[205];
int data[205];
int n;
struct point
{
int now_floor, step;
};
int bfs(int start, int end)
{
point q1, q2;
queue<point> q;
q1.now_floor = start;
q1.step = 0;
q.push(q1);
visited[start] = true;
while (!q.empty())
{
q2 = q.front();
q.pop();
if (q2.now_floor == end)
return q2.step;
int tmp = q2.now_floor + data[q2.now_floor];
if (tmp <= n && !visited[tmp])
{
visited[tmp] = true;
q1.now_floor = tmp;
q1.step = q2.step + 1;
q.push(q1);
}
tmp = q2.now_floor - data[q2.now_floor];
if (tmp >= 0 && !visited[tmp])
{
visited[tmp] = true;
q1.now_floor = tmp;
q1.step = q2.step + 1;
q.push(q1);
}
}
return -1;
}
int main()
{
int a, b;
while (cin >> n >> a >> b && n)
{
memset(visited, false, sizeof(visited));
for (int i = 1; i <= n; i++)
cin >> data[i];
cout << bfs(a, b) << endl;
}
return 0;
}
<file_sep>#include <iostream>
#include <cstring>
#include <cstdio>
#include <cstdlib>
#include <map>
#include <algorithm>
#include <vector>
#include <list>
#include <climits>
using namespace std;
char data[100];
int next[100];
void getnextval()
{
int i = 0, j = -1;
next[0] = -1;
int len = strlen(data);
while (i < len)
{
if (j == -1 || data[i] == data[j])
{
i++;
j++;
next[i] = j;
}
else j = next[j];
}
}
int main()
{
while (scanf ("%s", data) != EOF)
{
getchar();
cout << "cin finish" << endl;
getnextval();
int len = strlen(data);
for (int i = 0; i < len; i++)
cout << data[i] << " ";
cout << endl;
for (int i = 1; i <= len; i++)
cout << i << " ";
cout << endl;
for (int i = 1; i <= len; i++)
cout << next[i] << " ";
cout << endl;
}
return 0;
}
<file_sep>#include <iostream>
#include <cstring>
#include <cstdio>
#include <cstdlib>
#include <map>
#include <algorithm>
#include <vector>
#include <list>
#include <climits>
using namespace std;
char keywords[10005][55];
char description[1000005];
int next[10005][55];
void getnextval(int index)
{
int i = 0, j = -1;
int len = strlen(keywords[index]);
next[index][0] = -1;
while (i < len)
{
if (j == -1 || keywords[index][i] == keywords[index][j])
{
i++;
j++;
next[index][i] = j;
}
else j = next[index][j];
}
}
int main()
{
int cases;
scanf ("%d", &cases);
while (cases--)
{
int n;
scanf ("%d", &n);
getchar();
for (int i = 0; i < n; i++)
{
scanf ("%s", keywords[i]);
getchar();
getnextval(i);
}
scanf ("%s", description);
int len1 = strlen(description);
int sum = 0;
for (int i = 0; i < n; i++)
{
//memset(next, 0, sizeof(next));
int len2 = strlen(keywords[i]);
//getnextval(i);
int j = 0, k = 0;
while (k < len1 && j < len2)
{
if (j == -1 || keywords[i][j] == description[k])
{
k++;
j++;
}
else j = next[i][j];
}
if (j == len2)
sum++;
}
cout << sum << endl;
//system("pause");
}
return 0;
}
<file_sep>#include <iostream>
#include <cstring>
#include <cstdio>
#include <cstdlib>
#include <map>
#include <algorithm>
#include <vector>
#include <list>
#include <climits>
using namespace std;
int main()
{
int n;
while (cin >> n)
{
int a[100];
memset(a, 100000, sizeof(a));
for (int i = 0; i < n; i++)
cout << a[i] << " ";
cout << endl;
}
return 0;
}
<file_sep>#include <iostream>
#include <climits>
using namespace std;
int data[100005];
int main()
{
int n;
while (cin >> n)
{
int tmp = n, count = 1;
while (n > 0)
{
int num;
cin >> num;
for (int i = 0; i < num; i++)
cin >> data[i];
int beg_pos = 0, end_pos = 0, tmp_pos = 0;
int max = INT_MIN;
int sum = 0;//data[0];
for (int i = 0; i < num; i++)
{
if (sum < 0)
{
sum = data[i];
tmp_pos = i;
}
else sum += data[i];
if (sum > max)
{
max = sum;
beg_pos = tmp_pos; //example:-12 -1 -12=>run it on the paper
end_pos = i;
}
}
cout << "Case " << count << ":" << endl;
cout << max << " " << beg_pos + 1 << " " << end_pos + 1 << endl;
if (count < tmp)
cout << endl;
count++;
n--;
}
}
return 0;
}
<file_sep>#include <iostream>
using namespace std;
//const int MAX = MAX_INT;
int max(int a, int b)
{
return a > b ? a : b;
}
int main()
{
int t;
while (cin >> t)
{
while (t > 0)
{
int numbers, volume;
cin >> numbers >> volume;
int val[1005], vol[1005], dp[1005];
memset(dp, 0, sizeof(dp));// not exactly full,so all is zero
memset(val, 0, sizeof(val));
memset(vol, 0, sizeof(vol));
for (int i = 1; i <= numbers; i++)
cin >> val[i];
for (int i = 1; i <= numbers; i++)
cin >> vol[i];
for (int i = 1; i <= numbers; i++)
for (int j = volume; j >= vol[i]; j--)
dp[j] = max(dp[j], dp[j-vol[i]] + val[i]);
cout << dp[volume] << endl;
t--;
}
}
return 0;
}
<file_sep>#include <iostream>
#include <cstdio>
#include <cmath>
using namespace std;
double f (double x)
{
return 42*pow(x,6) + 48*pow(x,5) + 21*pow(x,2) + 10*x;
}
double ff (double x, double y)
{
return 6*pow(x,7) + 8*pow(x,6) + 7*pow(x,3) + 5*pow(x,2) - y*x;
}
int main()
{
int t;
while (cin >> t)
{
while (t--)
{
double y;
cin >> y;
double low = 0.0, high = 100.0, mid = 0.0;
while (high - low > 1e-12)
{
mid = (high + low) / 2.0;
if (f(mid) > y)
high = mid;
else low = mid;
}
printf ("%.4lf\n", ff(mid, y));
}
}
return 0;
}
<file_sep>#define lson k<<1
#define rson k<<1|1
#define mid(x, Y) (((x)+(y))>>1)
<file_sep>#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
using namespace std;
#define lson k<<1
#define rson k<<1|1
const int N = 100005;
struct tree
{
int l, r;
int cols;
bool delay;
}tree[N<<2];
void build(int l, int r, int k)
{
tree[k].l = l;
tree[k].r = r;
tree[k].cols = 0;
tree[k].delay = false;
if (l == r)
{
tree[k].cols = 1;
return ;
}
int mid = (l + r) >> 1;
build(l, mid, lson);
build(mid+1, r, rson);
}
void update(int l, int r, int v, int k)
{
if (tree[k].l == l && tree[k].r == r)
{
tree[k].cols = v;
tree[k].delay = true;
return ;
}
if (tree[k].delay)
{
tree[lson].cols = tree[rson].cols = tree[k].cols;
tree[lson].delay = tree[rson].delay = true;
tree[k].delay = false;
}
int mid = (tree[k].l + tree[k].r) >> 1;
if (r <= mid)
update(l, r, v, lson);
else
{
if (l > mid)
update(l, r, v, rson);
else
{
update(l, mid, v, lson);
update(mid+1, r, v, rson);
}
}
}
int ans = 0;
bool sign[N<<2];
void query(int l, int r, int k)
{
if (tree[k].delay)
{
tree[lson].cols = tree[rson].cols = tree[k].cols;
tree[lson].delay = tree[rson].delay = true;
tree[k].delay = false;
}
if (!sign[tree[k].cols])
{
ans ++;
sign[tree[k].cols] = true;
return ;
}
if (tree[k].l == tree[k].r)
return ;
int mid = (tree[k].l + tree[k].r) >> 1;
if (r <= mid)
query(l, r, lson);
else
{
if (l > mid)
query(l, r, rson);
else
{
query(l, mid, lson);
query(mid+1, r, rson);
}
}
}
int main()
{
//freopen("d:\\test\\in.txt", "r", stdin);
//freopen("d:\\test\\out.txt", "w", stdout);
int l, t, o;
while (scanf("%d%d%d", &l, &t, &o) != EOF)
{
build(1, l, 1);
getchar();
char op;
int a, b, c;
for (int i = 0; i < o; i++)
{
scanf("%c", &op);
if (op == 'C')
{
scanf ("%d%d%d", &a, &b, &c);
update(a, b, c, 1);
}
if (op == 'P')
{ ans = 0;
scanf ("%d%d", &a, &b);
memset(sign, false, sizeof(sign));
sign[0] = true;
query (a, b, 1);
printf ("%d\n", ans);
}
getchar();
}
}
return 0;
}
<file_sep>#include <iostream>
#include <cstring>
#include <cstdio>
#include <cstdlib>
#include <map>
#include <algorithm>
#include <vector>
#include <list>
#include <climits>
using namespace std;
const int inf = 0x3fffffff;
int main()
{
//freopen("in.txt", "r", stdin);
//freopen("out.txt", "w", stdout);
int n;
while (cin >> n)
{
int count_i = 0;
int dist[15][15];
bool des[15];
for (int i = 0; i < 15; i++)
for (int j = 0; j < 15; j++)
dist[i][j] = inf;
memset(des, false, sizeof(des));
int tmp = n;
while (tmp --)
{
int mi, pi;
cin >> mi >> pi;
if (pi == 1)
des[count_i] = true; // near to sea
while (mi--)
{
int smi, lmi;
cin >> smi >> lmi;
dist[count_i][smi] = dist[smi][count_i] = lmi;
}
count_i ++;
}
int min = INT_MAX;
for (int k = 0; k < n; k++)
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
{
if (dist[i][k] + dist[k][j] < dist[i][j])
dist[i][j] = dist[i][k] + dist[k][j];
}
for (int i = 1; i < n; i++)
if (des[i] && dist[0][i] < min)
min = dist[0][i];
cout << min << endl;
}
return 0;
}
<file_sep>#include <iostream>
#include <cmath>
using namespace std;
bool prime[40];
int num[25];
int used[25];
void init_prime()
{
for (int i = 2; i < sqrt(40); i++)
if (!prime[i])
for (int j = i * i; j < 40; j+= i)
prime[j] = true;
}
void dfs(int value, int n, int t)
{
if (t > n && !prime[num[n] + num[1]])
{
for(int i = 1; i < n; i++)
cout << num[i] << " ";
cout << num[n] << endl;
}
else
{
for (int i = 1; i <= n; i++)
{
if (!prime[value+i] && !used[i])
{
num[t] = i;
used[i] = 1;
dfs(i, n, t+1);
used[i] = 0;
}
}
}
}
int main()
{
init_prime();
int n;
int time = 1;
while (cin >> n)
{
cout << "Case " << time << ":" << endl;
time++;
int t = 1;
used[1] = 1;
num[1] = 1;
dfs(1, n, 2);
cout << endl;
}
return 0;
}
<file_sep>one:3225_poj.cpp
g++ -g 3225_poj.cpp
del /q one 2>nul
ren a.exe one
<file_sep>#include <iostream>
#include <cstdlib>
using namespace std;
#define lson k<<1
#define rson k<<1|1
const int N = 100005;
struct tree
{
int l;
int r;
int sum;
int delay;
}tree[N*4];
void build(int l, int r, int k)
{
tree[k].l = l;
tree[k].r = r;
tree[k].sum = 0;
tree[k].delay = 0;
if (l == r)
{
tree[k].sum = 1;
return ;
}
int middle = (l + r) >> 1;
build(l, middle, k<<1);
build(middle+1, r, k<<1|1);
tree[k].sum = tree[k<<1].sum + tree[k<<1|1].sum;
}
void update(int p, int l, int r, int k)
{
if (l == tree[k].l && r == tree[k].r)
{
tree[k].delay = p;
tree[k].sum = (tree[k].r - tree[k].l + 1) * p;
return ;
}
if (tree[k].delay)
{
tree[lson].delay = tree[k].delay;
tree[lson].sum = (tree[lson].r - tree[lson].l + 1) * tree[k].delay;
tree[rson].delay = tree[k].delay;
tree[rson].sum = (tree[rson].r - tree[rson].l + 1) * tree[k].delay;
tree[k].delay = 0;
}
int mid = (tree[k].l + tree[k].r) >> 1;
if (l > mid)
update(p, l, r, rson);
else
{
if (r <= mid)
update(p, l, r, lson);
else
{
update(p, l, mid, lson);
update(p, mid+1, r, rson);
}
}
tree[k].sum = tree[lson].sum + tree[rson].sum;
}
int main()
{
int cases;
while (scanf ("%d", &cases) != EOF)
{
int t = 1;
while (cases--)
{
int n, q;
scanf ("%d%d", &n, &q);
build(1, n, 1);
for (int i = 0; i < q; i++)
{
int x, y, z;
scanf ("%d%d%d", &x, &y, &z);
update(z, x, y, 1);
}
printf ("Case %d: ", t++);
printf ("The total value of the hook is %d.\n", tree[1].sum);
}
}
return 0;
}
<file_sep>#include <iostream>
int data[1005][1005];
int main()
{
int n, m;
while (cin >> n >> m)
{
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
cin >> data[i][j];
int q;
cin >> q;
int x1 = 0, y1 = 0;
int x2 = 0, y2 = 0;
for (int i = 0; i < q; i++)
{
cin >> x1 >> y1;
cin >> x2 >> y2;
}
<file_sep>#include <iostream>
using namespace std;
const int N = 200005;
int h, w, n;
int MIN(int a, int b)
{
return a < b ? a : b;
}
int MAX(int a, int b)
{
return a > b ? a : b;
}
struct tree
{
int l;
int r;
int max;
}tree[N*4];
void build(int l, int r, int k)
{
tree[k].l = l;
tree[k].r = r;
tree[k].max = w;
if (l == r)
return ;
int mid = (l+r) >> 1;
build(l, mid, k<<1);
build(mid+1, r, k<<1|1);
}
int ans;
void search(int p, int k)
{
if (tree[k].max >= p)
{
if (tree[k].l == tree[k].r)
{
tree[k].max -= p;
ans = tree[k].l;
return ;
}
}
int kk = k << 1;
if (tree[kk].max >= p)
search(p, kk);
else
{
if (tree[kk+1].max >= p)
search(p, kk+1);
}
tree[k].max = MAX(tree[k<<1].max, tree[k<<1|1].max);
}
int main()
{
while (scanf("%d%d%d", &h, &w, &n) != EOF)
{
int m = MIN(h, n);
build(1, m, 1);
for (int i = 1; i <= n; i++)
{
int wi;
scanf ("%d", &wi);
ans = -1;
search(wi, 1);
printf ("%d\n", ans);
}
}
return 0;
}
<file_sep>#include <iostream>
#include <algorithm>
#include <cmath>
using namespace std;
const int MAX = 9999999;
bool prime[MAX];
void init_prime()
{
for (int i = 2; i <= sqrt(MAX); i++)
{
if (!prime[i])
for (int j = i * i; j < MAX; j += i)
prime[j] = true;
}
}
bool huiwen(int tmp)
{
int n = tmp;
int num[20] = { 0 };
int k = 0;
while (n)
{
num[k++] = n % 10;
n /= 10;
}
int count = 0;
for (int i = 0; i <= (k-1)/2; i++)
{
if (num[i] == num[k-1-i])
count++;
}
if (k == 1) return true;
if (count == (k+1)/2) return true;
else return false;
}
int main()
{
init_prime();
int a, b;
while (cin >> a >> b)
{
for (int i = a; i <= b; i++)
{
if (i >= 9999999)
continue;
if (!prime[i] && huiwen(i))
cout << i << endl;
}
cout << endl;
}
return 0;
}
<file_sep>#include <iostream>
using namespace std;
int main()
{
int n;
while (cin >> n)
{
while (n > 0)
{
int a, b;
cin >> a >> b;
int sum = a % 100 + b;
if (sum >= 100)
{
int one = sum % 10;
sum /= 10;
int two = sum % 10;
if (two == 0)
cout << one << endl;
else cout << two << one << endl;
}
else cout << sum << endl;
n--;
}
}
return 0;
}
<file_sep>#include <iostream>
#include <cstring>
#include <cstdio>
#include <cstdlib>
#include <map>
#include <algorithm>
#include <vector>
#include <list>
#include <climits>
using namespace std;
int main()
{
int n;
while (cin >> n)
{
cout << "enter here" << endl;
}
return 0;
}
<file_sep>#include <iostream>
#include <algorithm>
using namespace std;
#define lson k<<1
#define rson k<<1|1
int main()
{
freopen("d:\\debug\\in.txt", "w", stdin);
freopen("d:\\debug\\out.txt", "r", stdout);
int cases;
while (~scanf ("%d", &cases))
{
<file_sep>#include <iostream>
using namespace std;
int dp[1005][1005];
int max(int a, int b)
{
return a > b ? a : b;
}
int main()
{
char s1[10005], s2[10005];
s1[0] = '#';
s2[0] = '#';
while (cin >> s1+1 >> s2+1)
{
int len_a = strlen(s1) - 1, len_b = strlen(s2) - 1;
for (int i = 1; i <= len_a; i++)
{
for (int j = 1; j <= len_b; j++)
{
if (s1[i] == s2[j])
dp[i][j] = dp[i-1][j-1] + 1;
else dp[i][j] = max(dp[i-1][j], dp[i][j-1]);
}
}
cout << dp[len_a][len_b] << endl;
}
return 0;
}
<file_sep>#include <iostream>
#include <queue>
using namespace std;
int N;
char data[11][11][11];
bool visited[11][11][11];
int end_i, end_j, end_k;
int move[6][3] = {
{0, -1, 0},// up
{0, 1, 0}, // down
{0, 0, -1}, // left
{0, 0, 1}, // right
{1, 0, 0}, // forward
{-1, 0, 0} // back
};
bool sign;
struct point
{
int x;
int y;
int z;
int steps;
};
void bfs(int i, int j, int k)
{
point p1, p2;
queue<point> q;
p1.x = i;
p1.y = j;
p1.z = k;
p1.steps = 0;
q.push(p1);
while (!q.empty())
{
p2 = q.front();
q.pop();
if (p2.x == end_i && p2.y == end_j && p2.z == end_k)
{
sign = true;
cout << N << " " << p2.steps << endl;
return ;
}
for (int t = 0; t < 6; t++)
{
int x = p2.x + move[t][0],
y = p2.y + move[t][1],
z = p2.z + move[t][2];
if (x >= 0 && x < N && y >= 0 && y < N && z >= 0 && z < N)
{
if (!visited[x][y][z] && data[x][y][z] != 'X')
{
visited[x][y][z] = true;
p1.x = x;
p1.y = y;
p1.z = z;
p1.steps = p2.steps + 1;
if (p1.x == end_i && p1.y == end_j && p1.z == end_k)
{
sign = true;
cout << N << " " << p1.steps << endl;
return ;
}
q.push(p1);
}
}
}
}
}
int main()
{
string tmp;
while (cin >> tmp >> N)
{
getchar();
memset(visited, false, sizeof(visited));
for (int i = 0; i < N; i++)
for (int j = 0; j < N; j++)
for (int k = 0; k < N; k++)
{
cin >> data[i][j][k];
}
int start_i = 0, start_j = 0, start_k = 0;
cin >> start_i >> start_j >> start_k;
cin >> end_i >> end_j >> end_k;
data[end_i][end_j][end_k] = '0';
cin >> tmp;
visited[start_i][start_j][start_k] = true;
sign = false;
bfs(start_i, start_j, start_k);
if(!sign) cout << "NO ROUTE" << endl;
}
return 0;
}
<file_sep>#include <iostream>
#include <climits>
#include <string>
using namespace std;
int main()
{
int a, b, n;
while (cin >> a >> b >> n && (n&& a && b))
{
int f1 = 1, f2 = 1, f3, k = 3;
int value[100] = { 0, 1, 1, 0};
for (int i = 0; i < 100; i++)
{
f3 = (a * f2 + b * f1) % 7;
value[k++] = f3;
f1 = f2;
f2 = f3;
if ((f1 == 1) && (f2 == 1))
break;
}
value[0] = value[k-3];
cout << value[n % (k - 3)] << endl;
}
return 0;
}
<file_sep>#include <iostream>
using namespace std;
#define lson k<<1
#define rson k<<1|1
const int N = 100005;
struct tree
{
int l;
int r;
int lv;
int rv;
int zeros;
int lmax;
int rmax;
int max;
int delay;
}tree[N<<2];
void build(int l, int r, int k)
{
tree[k].l = l;
tree[k].r = r;
tree[k].lv = 0;
tree[k].rv = 0;
tree[k].lmax = 0;
tree[k].rmax = 0;
tree[k].max = 0;
tree[k].delay = -1;
if (l == r)
return ;
int mid = (l + r) >> 1;
build(l, mid, k<<1);
build(mid+1, r, k<<1|1);
}
void insert(int v, int p, int k)
{
if (tree[k].l == p && tree[k].r == p)
{
tree[k].lv = v;
tree[k].rv = v;
if (v == 1)
{
tree[k].lmax = 1;
tree[k].rmax = 1;
tree[k].max = 1;
}
return ;
}
int mid = (tree[k].l + tree[k].r) >> 1;
if (p <= mid) insert(v, p, lson);
else insert(v, p, rson);
}
void update(int sign, int l, int r, int k)
{
if (tree[k].l == l && tree[k].r == r)
{
switch(sign)
{
case 0:
tree[k].lmax = 0;
tree[k].rmax = 0;
tree[k].max = 0;
tree[k].lv = 0;
tree[k].rv = 0;
tree[k].delay = 0;
break;
case 1:
int tmp_len = r - l + 1;
tree[k].lmax = tmp_len;
tree[k].rmaxn = tmp_len;
tree[k].max = tmp_len;
tree[k].lv = 1;
tree[k].rv = 1;
tree[k].delay = 1;
break;
case 2:
}
}
int main()
{
int cases;
while (scanf ("%d", &cases) != EOF)
{
while (cases--)
{
int n, m;
scanf ("%d%d", &n, &m);
build(1, n, 1);
for (int i = 1; i <= n; i++)
{
int value;
scanf ("%d", &value);
insert(value, i, 1);
}
int op, a, b;
for (int i = 1; i <= m; i++)
{
cin >> op >> a >> b;
a++;
b++;
switch(op)
{
case 0:
update(0, a, b, 1);
break;
case 1:
update(1, a, b, 1);
break;
case 2:
update(2, a, b, 1);
break;
case 3:
break;
case 4:
break;
}
}
return 0;
}
<file_sep>#include<iostream>
using namespace std;
const int MAX=65536<<1;//65535<<1;改成65600<<1就不对了
struct T
{
int col;//表示颜色
int cnt;//表示取反的次数
int l,r,m;
}tree[MAX*3];
struct N
{
int x,y;
}node[MAX];//这里改成node[MAX*2]就不对了
int size=0;
void Build_tree(int root,int l,int r)//创建树
{
tree[root].l=l;
tree[root].r=r;
tree[root].m=(l+r)>>1;
tree[root].cnt=0;
if (l==r)
{
tree[root].col=0;
return;
}
tree[root].col=-1;
Build_tree(root<<1,l,tree[root].m);
Build_tree(root<<1|1,tree[root].m+1,r);
};
void Updata(int root,int l,int r,int k)
{
if(tree[root].l==l&&tree[root].r==r)
{
if(k==-1) tree[root].cnt++;
else
{
tree[root].col=k;
tree[root].cnt=0;
}
return ;
}
if(tree[root].col!=-1)
{
if (tree[root].cnt%2)
tree[root].col=!tree[root].col;
tree[root<<1].col=tree[root<<1|1].col=tree[root].col;
tree[root<<1].cnt=tree[root<<1|1].cnt=tree[root].cnt=0;
tree[root].col=-1;
}
if (tree[root].cnt%2)
{
tree[root<<1].cnt++;
tree[root<<1|1].cnt++;
tree[root].cnt=0;
}
if (r<=tree[root].m)//左子树
Updata(root<<1,l,r,k);
else if (l>tree[root].m)
Updata(root<<1|1,l,r,k);
else
{
Updata(root<<1,l,tree[root].m,k);
Updata(root<<1|1,tree[root].m+1,r,k);
}
}
void Query(int root)
{
if (tree[root].col!=-1)
{
if(tree[root].cnt%2)
tree[root].col=!tree[root].col;
if (tree[root].col)
{
node[size].x=tree[root].l;
node[size++].y=tree[root].r;
}
return ;
}
if(tree[root].cnt%2)
{
tree[root<<1].cnt++;
tree[root<<1|1].cnt++;
tree[root].cnt=0;
}
Query(root<<1);
Query(root<<1|1);
}
int main()
{
Build_tree(1,0,MAX);
char ch[4],ci,cj;
int a,b;
while(scanf("%s %c%d,%d%c",ch,&ci,&a,&b,&cj)!=EOF)
{
a=2*a;
b=2*b;
if (ci=='(')
a+=1;
if (cj==')')
b-=1;//这里[a,b]闭区间
switch(ch[0])
{
case 'U'://[a,b]全部变1(并)
if(a <= b)//过滤空集
Updata(1,a,b,1);
break;
case 'I'://(交)
if(a>0)
Updata(1,0,a-1,0);
Updata(1,b+1,MAX,0);
break;
case 'D'://(S-T)
if(a <= b)//过滤空集
Updata(1,a,b,0);
break;
case 'C':// (T-S)
if(a>0)
Updata(1,0,a-1,0);
Updata(1,b+1,MAX,0);
if(a<=b)//过滤空集
Updata(1,a,b,-1);//取反
break;
case 'S':
if(a<=b)//过滤空集
Updata(1,a,b,-1);//取反
break;
}
}
Query(1);
if(size==0)
printf("empty set");
else
for (int i=0;i<size;i++)
{
int st=node[i].x;
while (node[i].y==node[i+1].x-1) i++;
int en=node[i].y;
if(st%2)
printf("(%d,",st/2);
else
printf("[%d,",st/2);
if(en%2)
printf("%d) ",en/2+1);
else
printf("%d] ",en/2);
}
putchar('\n');
return 0;
}
<file_sep>#include <iostream>
#include <cstring>
#include <cstdio>
#include <cstdlib>
#include <map>
#include <algorithm>
#include <vector>
#include <list>
#include <climits>
using namespace std;
char word[10005];
char text[1000005];
int next[10005];
void getnextval()
{
int i = 0, j = -1;
int len = strlen(word);
next[0] = -1;
while (i < len)
{
if (j == -1 || word[i] == word[j])
{
i++;
j++;
next[i] = j;
}
else j = next[j];
}
}
int main()
{
int cases;
scanf ("%d", &cases);
getchar();
while (cases --)
{
scanf ("%s", word);
getchar();
scanf ("%s", text);
getchar();
getnextval();
int lenw = strlen(word);
int lent = strlen(text);
int i = 0, j = 0;
int sum = 0;
while (i < lent)
{
if (j == -1 || word[j] == text[i])
{
i++;
j++;
}
else j = next[j];
if (j == lenw)
{
j = next[j];
sum ++;
}
}
cout << sum << endl;
}
return 0;
}
<file_sep>#include <iostream>
using namespace std;
int max(int a, int b)
{
return a > b ? a : b;
}
int main()
{
int n;
while (cin >> n)
{
while (n > 0)
{
int num;
cin >> num;
int data[105][105] = { 0 };
for (int i = 1; i <= num; i++)
for (int j = 1; j <= i; j++)
cin >> data[i][j];
int dp[105][105] = { 0 };
int MAX = -1;
for (int i = 1; i <= num; i++)
for (int j = 1; j <= i; j++)
{
dp[i][j] = max(dp[i-1][j-1], dp[i-1][j]) + data[i][j];
if (dp[i][j] > MAX)
MAX = dp[i][j];
}
cout << MAX << endl;
n--;
}
}
return 0;
}
<file_sep>#include <iostream>
#include <cstring>
#include <cstdio>
#include <cstdlib>
#include <map>
#include <algorithm>
#include <vector>
#include <list>
#include <climits>
using namespace std;
char s1[200005];
char s2[100005];
int next[100005];
void getnextval()
{
int i = 0, j = -1;
int len = strlen(s2);
next[0] = -1;
while(i < len)
{
if (j == -1 || s2[i] == s2[j])
{
i++;
j++;
next[i] = j;
}
else j = next[j];
}
}
int main()
{
while (~scanf ("%s", s1))
{
getchar();
scanf ("%s", s2);
getchar();
getnextval();
int len1 = strlen(s1);
int len2 = strlen(s2);
if (len1 < len2)
{
puts("no");
continue;
}
for (int i = 0; i < len1; i++)
s1[len1+i] = s1[i];
int i = 0, j = 0;
while (i < 2 * len1 - 1 && j < len2)
{
if (j == -1 || s1[i] == s2[j])
{
i++;
j++;
}
else j = next[j];
}
if (j == len2)
puts("yes");
else puts("no");
}
return 0;
}
<file_sep>#include <iostream>
#include <string>
using namespace std;
int main()
{
int L, N, M;
int sign = 1;
while (cin >> L >> N >> M)
{
int array_A[505] = { 0 }, array_B[505] = { 0 }, array_C[505] = { 0 };
for (int i = 0; i < L; i++)
cin >> array_A[i];
for (int i = 0; i < N; i++)
cin >> array_B[i];
for (int i = 0; i < M; i++)
cin >> array_C[i];
int S, x[1005] = { 0 };
cin >> S;
string result[1005];
int count = 0;
for (int i = 0; i < S; i++)
{
cin >> x[i];
int mark = 0;
for (int j = 0; j < L; j++)
{
for (int k = 0; k < N; k++)
{
for (int t = 0; t < M; t++)
{
int tmp = array_A[j] + array_B[k] + array_C[t];
if (x[i] == tmp)
{
result[i] = "YES";
mark = 1;
break;
}
else result[i] = "NO";
}
if (mark == 1)
break;
}
if (mark == 1)
break;
}
}
cout << "Case " << sign << ":" << endl;
for (int i = 0; i < S; i++)
cout << result[i] << endl;
}
return 0;
}
<file_sep>#include <iostream>
#include <cstring>
#include <cstdio>
#include <cstdlib>
#include <map>
#include <algorithm>
#include <vector>
#include <list>
#include <climits>
using namespace std;
char data[1000005];
int next[1000005];
void getnextval()
{
int i = 0, j = -1;
next[0] = -1;
int len = strlen(data);
while (i < len)
{
if (j == -1 || data[i] == data[j])
next[++i] = ++j;
else j = next[j];
}
}
int main()
{
int n;
int cases = 1;
while (~scanf ("%d", &n))
{
if (n == 0) break;
getchar();
scanf ("%s", data);
getchar();
getnextval();
printf ("Test case #%d\n", cases++);
for (int i = 1; i <= n; i++)
{
int span = i - next[i];
if (i % span == 0 && i / span > 1)
printf ("%d %d\n", i, i / span);
}
printf ("\n");
}
return 0;
}
<file_sep>#include <iostream>
#include <cstring>
#include <string>
using namespace std;
int max(int a, int b)
{
return a > b ? a : b;
}
int main()
{
int c;
while (cin >> c)
{
while (c > 0)
{
int money, kinds;
cin >> money >> kinds;
int price[105], weight[105], numbers[105];
for (int i = 1; i <= kinds; i++)
cin >> price[i] >> weight[i] >> numbers[i];
int dp[105], count[105];
memset(dp, 0, sizeof(dp));
memset(count, 0, sizeof(count));
for (int i = 1; i <= kinds; i++)
{
for (int k = 1; k <= numbers[i]; k++)
for (int j = money; j >= price[i]; j--)
dp[j] = max(dp[j], dp[j-price[i]] + weight[i]);
}
cout << dp[money] << endl;
c--;
}
}
return 0;
}
<file_sep>#include <iostream>
using namespace std;
double min(double a, double b)
{
return a > b ? b : a;
}
int main()
{
int m, n;
while (cin >> n >> m && (n != 0 || m != 0))
{
int price[10005] = { 0 };
double probal[10005] = { 0.0 };
for (int i = 1; i <= m; i++)
cin >> price[i] >> probal[i];
double dp[10005];
for (int i = 0; i <= n; i++)
dp[i] = 1.0;
for (int i = 1; i <= m; i++)
for (int j = n; j >= price[i]; j--)
dp[j] = min(dp[j], dp[j-price[i]] * (1 - probal[i]));
printf("%.1lf%%\n", (1 - dp[n]) * 100.0);
}
return 0;
}
<file_sep>#include <iostream>
using namespace std;
int data[15];
int num[15];
bool used[15];
int t, n;
void dfs(int value, int level)
{
if ((level <= n || level - 1 == n) && value == t)
{
for (int i = 1; i < level; i++)
{
cout << num[i];
if (i < level - 1)
cout << "+";
}
cout << endl;
}
else
{
for (int i = 0; i < n; i++)
{
if (value + data[i] <= t && !used[i])
{
num[level] = data[i];
value += data[i];
used[i] = true;
dfs(value, level+1);
value -= data[i];
used[i] = false;
}
}
}
return ;
}
int main()
{
while (cin >> t >> n)
{
for (int i = 0; i < n; i++)
cin >> data[i];
for (int i = 0; i < n; i++)
{
if (i >= 1 && data[i] == data[i-1])
continue;
for (int j = 0; j < n; j++)
{
used[j] = false;
num[j] = 0;
}
num[1] = data[i];
used[i] = true;
dfs(data[i], 2);
}
}
return 0;
}
<file_sep>#include <cstdlib>
#include <cstdio>
#include <iostream>
using namespace std;
template <class T>
inline T MAX(T x, T y) { return x > y ? x : y; }
int main()
{
int a, b;
while (cin >> a >> b)
{
cout << "Max is " << MAX(a, b) << endl;
}
return 0;
}
<file_sep>//Memory Time
//21276K 547MS
#include<iostream>
#include<algorithm>
#include <cstdio>
#include <cstdlib>
using namespace std;
class LineTree_Node
{
public:
int s,e; //区间端点
int col; //区间颜色
LineTree_Node():s(0),e(0),col(0){}
};
class solve
{
public:
solve(int n):N(n)
{
Initial();
Input();
CreatLineTree(1,Maxp,1);
Solution();
}
~solve()
{
for(int i=1;i<=N;i++)
delete[] reg[i];
delete[] ep;
delete[] dis;
delete[] tagcol;
delete[] LT;
}
void Initial(void); //初始化并申请存储空间
void Input(void); //输入
void CreatLineTree(int sp,int tp,int p); //构造[sp,tp]线段树
void Solution(void); //插入区间,统计颜色
void Insert(int a,int b,int p,int color); //[a,b]:把区间[a,b]插入线段树
//p:当前所在线段树的位置
//color:当前区间的染色
void DFS(int p); //遍历线段树,计算线段树中不同颜色的个数
protected:
int N; //海报数(区间数)
int Maxp; //记录(压缩后的)最大端点,用于建造区间[1,Maxp]的线段树
LineTree_Node* LT; //线段树
int **reg; //顺序存储输入的区间(每张海报的宽度)
int *ep; //顺序存储输入的每个区间的2个端点
unsigned short *dis; //映射端点,压缩区间(离散化)
bool* tagcol; //标记能看见的颜色
int cnt; //计数器,记录线段树中能看见的不同的颜色数
};
void solve::Initial(void)
{
cnt=0;
reg=new int*[N+1];
for(int i=1;i<=N;i++)
reg[i]=new int[2];
ep = new int[2*N+1];
dis=new unsigned short[1e7+1];
memset(dis,0,sizeof(unsigned short)*(1e7+1));
tagcol=new bool[N+1];
memset(tagcol,false,sizeof(bool)*(N+1));
return;
}
void solve::Input(void)
{
int p=0;
for(int i=1;i<=N;i++)
{
scanf("%d %d",® [ i ][0],® [ i ][1]);
/*避免相通的端点重复映射到不同的值*/
/*也为了减少参与排序的元素个数,这里必须做标记*/
/*同时为了节约空间,本用于离散化的dis[]数组暂时用来标记端点*/
if(dis[reg[i][0]]==0)
{
ep[p++]=reg[i][0];
dis[reg[i][0]]=1;
}
if(dis[reg[i][1]]==0)
{
ep[p++]=reg[i][1];
dis[reg[i][1]]=1;
}
}
/*离散化*/
sort(ep,ep+p); //区间端点排序
unsigned short hash=0;
for(int j=0;j<p;j++)
dis[ep[j]]=++hash; //把排好序的端点依次映射到1,2,...,Maxp
Maxp=hash;
LT=new LineTree_Node[4*Maxp+1];
return;
}
void solve::CreatLineTree(int sp,int tp,int p)
{
LT[p].s=sp;
LT[p].e=tp;
if(sp==tp)
return;
/*注意线段树不一定都是完全二叉树*/
/*但是为了处理方便,加快搜索效率*/
/*我们完全可以把线段树以完全二叉树的形式进行构造、存储*/
int mid=(sp+tp)>>1;
CreatLineTree(sp,mid,p*2);
CreatLineTree(mid+1,tp,p*2+1);
return;
}
void solve::Solution(void)
{
for(int i=1;i<=N;i++)
Insert(dis[reg[i][0]],dis[reg[i][1]],1,i); //逐个区间(海报)对线段树染色
DFS(1);
printf("%d\n",cnt);
return;
}
void solve::Insert(int a,int b,int p,int color)
{
if(b<LT[p].s || a>LT[p].e) //[a,b]与[s,e]完全无交集
return; //说明[a,b]不被[s,e]所在的子树包含,无需向下搜索
if(a<=LT[p].s && b>=LT[p].e)//[a,b]完全覆盖[s,e]
{
LT[p].col=color;//[s,e]染单色,暂时无需对[s,e]的子树操作(这是由线段树的搜索机制决定的)
return; //因此直接返回
}
/*若能执行到这里,说明[a,b]部分覆盖[s,e]*/
if(LT[p].col>=0) //[s,e]本为无色或者单色
{ //由于不知道[a,b]覆盖了[s,e]多少
LT[p*2].col=LT[p*2+1].col=LT[p].col; //因此先由[s,e]的孩子继承[s,e]的单色
LT[p].col=-1; //[s,e]由于被部分覆盖,染色为多色
}
/*若能执行到这里,说明[s,e]为多色*/
/*细化处理[s,e]的孩子,确定[s,e]中哪部分的区间是什么颜色*/
Insert(a,b,p*2,color);
Insert(a,b,p*2+1,color);
return;
}
void solve::DFS(int p)
{
if(LT[p].col==0) //[s,e]为无色,其孩子也必为无色,无需继续搜索
return;
if(LT[p].col>0) //[s,e]为单色,则无需向下搜索
{ //因为其子区间必被[s,e]覆盖,能看见的只有[s,e]的颜色
if(!tagcol[LT[p].col])
{
tagcol[LT[p].col]=true;
cnt++;
}
return;
}
if(LT[p].col==-1) //[s,e]为多色,说明能在[s,e]看到集中颜色
{ //搜索其子区间具体有什么颜色
DFS(p*2);
DFS(p*2+1);
}
return;
}
int main(void)
{
int test;
scanf("%d",&test);
for(int t=1;t<=test;t++)
{
int n;
scanf("%d",&n);
solve poj2528(n);
}
return 0;
}
<file_sep>#include <iostream>
#include <cstring>
#include <cstdio>
#include <cstdlib>
#include <map>
#include <algorithm>
#include <vector>
#include <list>
#include <climits>
using namespace std;
#define lson k<<1
#define rson k<<1|1
#define mid(x, y) (((x)+(y))>>1)
template<class T>
inline T MAX(T x, T y) { return x > y ? x : y; }
const int N = 50005;
class Tree
{
public:
Tree():l(0), r(0), delay(false), lsum(0), rsum(0), sum(0){};
int l, r;
bool delay;
int col; // judge wether people can check in or not, [0 can , 1 can't]
int lsum, rsum, sum;
};
class Solve
{
public:
void build(int l, int r, int k);
void update(int l, int r, bool v, int k);
int query(int num, int k);
void pushup(int k);
void pushdown(int k);
~Solve()
{
delete[] data;
}
private:
Tree data[N<<2];
};
void Solve::pushup(int k)
{
data[k].lsum = data[lson].lsum;
data[k].rsum = data[rson].rsum;
data[k].sum = MAX(MAX(data[k].lsum, data[k].rsum),
data[lson].rsum + data[rson].lsum);
}
void Solve::pushdown(int k)
{
if (data[k].delay == true)
{
if (data[k].col == 0)
{
int ltmp = data[lson].r - data[lson].l + 1;
data[lson].lsum = data[lson].rsum = data[lson].sum = ltmp;
int rtmp = data[rson].r - data[rson].l + 1;
data[rson].lsum = data[rson].rsum = data[rson].sum = rtmp;
}
else // 0 represents clear rooms
{
data[lson].lsum = data[lson].rsum = data[lson].sum = 0;
data[rson].lsum = data[rson].rsum = data[rson].sum = 0;
}
data[lson].delay = true;
data[rson].delay = true;
data[lson].col = data[k].col;
data[rson].col = data[k].col;
}
}
void Solve::build(int l, int r, int k)
{
data[k].l = l;
data[k].r = r;
data[k].delay = false;
data[k].lsum = data[k].rsum = data[k].sum = r - l + 1;
data[k].col = 1;
if (l == r)
return ;
int m = mid(l, r);
build(l, m, k<<1);
build(m+1, r, k<<1|1);
}
void Solve::update(int l, int r, bool v, int k)
{
if (data[k].l == l && data[k].r == r)
{
if (v == 1) // clear, so fill 1, people can enter
data[k].lsum = data[k].rsum = data[k].sum = r - l + 1;
else data[k].lsum = data[k].rsum = data[k].sum = 0; // people entered, fill 0
data[k].delay = true;
data[k].col = v;
return ;
}
pushdown(k);
int m = mid(data[k].l, data[k].r);
if (r <= m)
update(l, m, v, lson);
else
{
if (l > m)
update(m+1, r, v, rson);
else
{
update(l, m, v, lson);
update(m+1, r, v, rson);
}
}
pushup(k);
}
int Solve::query(int num, int k)
{
if (data[k].lsum >= num)
{
return data[k].l;
}
pushdown(k);
if (data[k].sum >= num) // two conditions, one in middle, one in right son
{
if (data[k].sum != data[k].rsum) // in middle
return data[lson].r - data[lson].rsum + 1;
}
// in left or right son
if (data[lson].sum >= num)
return query(num, lson);
if (data[rson].sum >= num)
return query(num, rson);
return -1;
}
int main()
{
freopen("d:\\debug\\in.txt", "r", stdin);
freopen("d:\\debug\\out.txt", "w", stdout);
int n, m;
while (~scanf ("%d%d", &n, &m))
{
Solve solve;
solve.build(1, n, 1);
while (m--)
{
int op;
int num;
if (op == 1)
{
scanf ("%d", &num);
if (solve.query(num, 1) < 0)
printf ("0\n");
else
{
int result = solve.query(num, 1);
if (result > 0)
{
printf ("%d\n", result);
solve.update(result, result + num - 1, true, 1);
}
}
}
if (op == 2)
{
int l, r;
num = r - l + 1;
scanf ("%d%d", &l, &r);
if (l > r)
{
int tmp = l;
l = r;
r = tmp;
}
solve.update(l, r, false, 1);
}
}
}
return 0;
}
<file_sep>#include <iostream>
#include <map>
#include <string>
using namespace std;
int main()
{
int n;
while (cin >> n && n)
{
string tmp, color;
int max = -1;
map<string, int> count_word;
for (int i = 0; i < n; i++)
{
cin >> tmp;
++count_word[tmp];
if (count_word[tmp] > max)
{
max = count_word[tmp];
color = tmp;
}
}
cout << color << endl;
}
return 0;
}
<file_sep>#include <iostream>
#include <cmath>
using namespace std;
int main()
{
double x1, y1, x2, y2;
while (cin >> x1 >> y1 >> x2 >> y2)
{
printf ("%.2lf\n", sqrt((x2-x1)*(x2-x1) + (y2-y1)*(y2-y1)));
}
return 0;
}
<file_sep>#include <iostream>
#include <cstdlib>
using namespace std;
#define N 5005
struct tree
{
int l;
int r;
int sum;
}tree[4*N];
void build(int l, int r, int k)
{
tree[k].l = l;
tree[k].r = r;
tree[k].sum = 0;
if (l == r)
return ;
int middle = (tree[k].l + tree[k].r) >> 1;
build(l, middle, k<<1);
build(middle+1, r, k<<1|1);
}
void insert(int p, int l, int r, int k)
{
if (tree[k].l == p && tree[k].r == p)
{
tree[k].sum = 1;
return ;
}
int middle = (tree[k].l + tree[k].r) >> 1;
if (p <= middle)
insert(p, l, middle, k<<1);
else insert(p, middle+1, r, k<<1|1);
tree[k].sum = tree[k<<1].sum + tree[k<<1|1].sum;
}
int sums;
void search(int l, int r, int k)
{
if (tree[k].l == l && tree[k].r == r)
{
sums += tree[k].sum;
return ;
}
int middle = (tree[k].l + tree[k].r) >> 1;
if (r <= middle)
search(l, r, k<<1);
else
{
if (l > middle)
search(l, r, k<<1|1);
else
{
search(l, middle, k<<1);
search(middle+1, r, k<<1|1);
}
}
}
int main()
{
int n;
while (cin >> n)
{
build(0, n - 1, 1);
int sum = 0;
int num[N];
for (int i = 0; i < n; i++)
{
cin >> num[i];
sums = 0;
if (num[i] != n - 1)
{
search(num[i] + 1, n - 1, 1);
sum += sums;
}
insert(num[i], 0, n - 1, 1);
}
int ans = sum;
for (int i = 0; i < n; i++)
{
sum = sum + n - 2 * num[i] - 1;
if (sum < ans) ans = sum;
}
cout << ans << endl;
}
return 0;
}
<file_sep>//思路:对给出的每段涂色,结构体中记录的是色号,
//最后统计的时候只要看哪种色号存在那就存在几种颜色
//用线段树的意义是成段成段的不用更新或是统计的时候也是
//成段的统计,大大缩减了时间复杂度!!
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <cstring>
using namespace std;
#define lson k<<1
#define rson k<<1|1
const int N = 20005;
struct
{
int l, r;
int col;
}tree[N<<2];
int ans = 0;
bool colors[N];
void build(int l, int r, int k)
{
tree[k].l = l;
tree[k].r = r;
tree[k].col = 0;
if (l == r)
return ;
int mid = (l + r) >> 1;
build(l, mid, lson);
build(mid+1, r, rson);
}
void update(int l, int r, int k, int col)
{
if (tree[k].l == l && tree[k].r == r)
{
tree[k].col = col;
return ;//延迟,不用再更新了
}
if (tree[k].col > 0)
{
tree[lson].col = tree[k].col;
tree[rson].col = tree[k].col;
tree[k].col = 0;
}
int mid = (tree[k].l + tree[k].r) >> 1;
if (l > mid)
update(l, r, rson, col);
else
{
if (r <= mid)
update(l, r,lson, col);
else
{
update(l, mid, lson, col);
update(mid+1, r, rson, col);
}
}
}
void calc(int k)
{
if (tree[k].col > 0)
{
if (!colors[tree[k].col])//该色号存在
{
colors[tree[k].col] = true;//将该色号去除,下次再遇到不用再统计了
ans++;
}
}
else
{
calc(lson);
calc(rson);
}
}
int main()
{
int cases;
//freopen("D:\\debug\\in.txt", "r", stdin);
//freopen("D:\\debug\\out.txt", "w", stdout);
while (scanf ("%d", &cases) != EOF)
{
while (cases--)
{
int n;
scanf ("%d", &n);
int arra[N], arrb[N];
for (int i = 1; i <= 2*n; i++)
{
scanf ("%d", &arra[i]);
arrb[i] = arra[i];
}
sort(arrb+1, arrb+2*n+1);
int size = unique(arrb+1, arrb+2*n+1) - (arrb+1);
for (int i = 1; i <= 2*n; i++)
arra[i] = lower_bound(arrb, arrb+size, arra[i]) - arrb;
build(1, size, 1);
for (int i = 1; i <= n; i++)
update(arra[2*i-1], arra[2*i], 1, i);
memset(colors, false, sizeof(colors));
ans = 0;
calc(1);
cout << ans << endl;
}
}
return 0;
}
<file_sep>#include <iostream>
#include <cstdlib>
#include <cstdio>
using namespace std;
#define N 50005 * 3
#define left(x) ((x)<<1)
#define right(x) ((x)<<1|1)
#define MID(x) ((x)>>1)
struct tree
{
int l;
int r;
int num;
}tree[N];
int ans;
void buildTree(int l, int r, int k)
{
int mid;
if (l == r)
{
tree[k].l = tree[k].r = r;
tree[k].num = 0;
return ;
}
tree[k].l = l;
tree[k].r = r;
tree[k].num = 0;
if (l < r)
{
mid = MID(l + r);
buildTree(l, mid, left(k));
buildTree(mid+1, r, right(k));
}
}
void insert(int pos, int tmp_num, int k)
{
if (tree[k].l == tree[k].r && tree[k].l == pos)
{
tree[k].num += tmp_num;
return ;
}
int mid = MID(tree[k].l + tree[k].r);
if (pos <= mid)
insert(pos, tmp_num, left(k));
else insert(pos, tmp_num, right(k));
tree[k].num = tree[left(k)].num + tree[right(k)].num;
}
void query(int l, int r, int k)
{
if (tree[k].l == l && tree[k].r == r)
{
ans += tree[k].num;
return ;
}
int mid = MID(tree[k].l + tree[k].r);
if (r <= mid)
query(l, r, left(k));
else
{
if (l > mid)
query(l, r, right(k));
else
{
query(l, mid, left(k));
query(mid+1, r, right(k));
}
}
}
int main()
{
int T;
while (cin >> T)
{
int count = 1;
while (T--)
{
cout << "Case " << count++ << ":" << endl;
int n;
cin >> n;
buildTree(1, n, 1);
for (int i = 1; i <= n; i++)
{
int tmp;
scanf("%d", &tmp);
insert(i, tmp, 1);
}
getchar();
char require[20];
while (scanf ("%s", require))
{
if (strcmp(require, "End") == 0)
break;
int i, j;
//cin >> i >> j;
scanf("%d%d", &i, &j); //time
if (strcmp(require, "Query") == 0)
{
ans = 0;
query(i, j, 1);
printf("%d\n", ans);
//cout << ans << endl;
}
if (strcmp(require, "Add") == 0)
insert(i, j, 1);
if (strcmp(require, "Sub") == 0)
insert(i, -j, 1);
}
}
}
return 0;
}
<file_sep>#include <iostream>
using namespace std;
int main()
{
int kinds;
while (cin >> kinds && kinds > 0)
{
int value[55] = { 0 }, number[55] = { 0 };
for (int i = 1; i <= kinds; i++)
cin >> value[i] >> number[i];
int total_A[55] = 0, total_B[55] = 0;
int count_A = 1, count_B = 1;
for (int i = 1; i <= kinds; i++)
for (int j = 1; j <= number[i]; j++)
if (total_A[--count_1] >= total_B[--count_B] value[i])
total_B += value[i];
else total_A += value[i];
cout << total_A << " " << total_B << endl;
}
return 0;
}
<file_sep>#include <iostream>
using namespace std;
#define lson k<<1
#define rson k<<1|1
const int N = 100005;
int value[N];
struct tree
{
int lmax;
int rmax;
int max;
int l;
int r;
int lv;
int rv;
}tree[N<<2];
int MAX(int a, int b)
{
return a > b ? a : b;
}
int MIN(int a, int b)
{
return a < b ? a : b;
}
void build(int l, int r, int k)
{
tree[k].lmax = 0;
tree[k].rmax = 0;
tree[k].max = 0;
tree[k].l = l;
tree[k].r = r;
if (l == r)
{
tree[k].lmax = 1;
tree[k].rmax = 1;
tree[k].max = 1;
tree[k].lv = value[l];
tree[k].rv = value[l];
return ;
}
int mid = (l + r) >> 1;
build (l, mid, k<<1);
build (mid+1, r, k<<1|1);
}
void update(int a, int b, int k)
{
if (tree[k].l == a && tree[k].r == a)
{
tree[k].lv = b;
tree[k].rv = b;
return ;
}
int mid = (tree[k].l + tree[k].r) >> 1;
if (a <= mid)
update(a, b, lson);
else update(a, b, rson);
int llen = tree[lson].r - tree[lson].l + 1;
int rlen = tree[rson].r - tree[rson].l + 1;
if (tree[lson].rv < tree[rson].lv)
{
tree[k].lmax = (tree[lson].rmax == llen) ? (llen + tree[rson].lmax) : tree[lson].lmax;
tree[k].rmax = (tree[rson].lmax == rlen) ? (rlen + tree[lson].rmax) : tree[rson].rmax;
int tmp_max = tree[lson].rmax + tree[rson].lmax;
tree[k].max = MAX(tmp_max, MAX(tree[lson].max, tree[rson].max));
}
else
{
tree[k].lmax = tree[lson].max;
tree[k].rmax = tree[rson].max;
tree[k].max = MAX(tree[k].lmax, tree[k].rmax);
}
tree[k].lv = tree[lson].lv;
tree[k].rv = tree[rson].rv;
}
int ans;
int query(int l, int r, int k)
{
if (tree[k].l == l && tree[k].r == r)
return tree[k].max;
int mid = (tree[k].l + tree[k].r) >> 1;
if (l > mid)
return query(l, r, rson);
else
{
if (r <= mid)
return query(l, r, lson);
else
{
int lmax = query(l, mid, lson);
int rmax = query(mid+1, r, rson);
if (tree[lson].rv < tree[rson].lv)
{
//cout << "tree[lson].rv: " << tree[lson].rv << endl;
//cout << "tree[rson].lv: " << tree[rson].lv << endl;
int tmp_a = MIN(tree[lson].rmax, mid - l + 1);
tmp_a += MIN(tree[rson].lmax, r - (mid + 1) + 1);
return MAX(MAX(lmax, rmax), tmp_a);
}
}
}
}
int main()
{
int cases;
//freopen("debug\\in.txt", "r", stdin);
//freopen("debug\\out.txt", "w", stdout);
while (scanf ("%d", &cases) != EOF)
{
while (cases--)
{
int n, m;
scanf ("%d%d", &n, &m);
for (int i = 1; i <= n; i++)
scanf ("%d", &value[i]);
build(1, n, 1);
//cout << "tree[1].max: " << tree[1].max << endl;
// cout << "tree[2].rv: " << tree[2].rv << endl;
// cout << "tree[3].lv: " << tree[3].lv << endl;
// cout << "tree[5].max: " << tree[5].max << endl;
// cout << "tree[2].max: " << tree[2].max << endl;
// cout << "tree[3].lmax: " << tree[3].lmax << endl;
// cout << "tree[3].rmax: " << tree[3].rmax << endl;
for (int i = 0; i < m; i++)
{
char q[10];
int a, b;
scanf ("%s%d%d", &q, &a, &b);
if (q[0] == 'U')
{
update(a+1, b, 1);
//cout << "tree[1].max: " << tree[1].max << endl;
//cout << "tree[2].rmax: " << tree[2].rmax << endl;
}
else
printf ("%d\n", query(a+1, b+1, 1));
}
}
}
return 0;
}
<file_sep>//Method:
//SUT (a,b) set 1
//S¡ÉT (min, a-1), (b+1,max) reverse
//S-T (a,b) set 0
//T-S (a,b) reverse, (min,a-1), (b+1,max) set 0
//Symmetric Difference, (a,b) reverse
#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <algorithm>
#include <climits>
using namespace std;
#define lson k<<1
#define rson k<<1|1
const int N = 65540 * 2;
struct tree
{
int l, r;
int cols;
int cnt;
}tree[N<<2];
void build(int l, int r, int k)
{
tree[k].l = l;
tree[k].r = r;
tree[k].cols = -1;
tree[k].cnt = 0;
if (l == r)
return ;
int mid = (l + r) >> 1;
build(l, mid, lson);
build(mid+1, r, rson);
}
void update(int l, int r, int k, int v)
{
if (l > r || l < 0) return ;
if (tree[k].l == l && tree[k].r == r)
{
if (v == -1) tree[k].cnt++;//reverse
else
{
tree[k].cols = v;
tree[k].cnt = 0;
}
return ;
}
if (tree[k].cols != -1)//value changes
{
if (tree[k].cnt%2)
tree[k].cols = !tree[k].cols;
tree[lson].cols = tree[rson].cols = tree[k].cols;
tree[lson].cnt = tree[rson].cnt = tree[k].cnt = 0;
}
if (tree[k].cnt%2)//reverse
{
tree[lson].cnt++;
tree[rson].cnt++;
tree[k].cnt = 0;
}
int mid = (tree[k].l + tree[k].r) >> 1;
if (r <= mid)
update(l, r, lson, v);
else
{
if (l > mid)
update(l, r, rson, v);
else
{
update(l, mid, lson, v);
update(mid+1, r, rson, v);
}
}
}
int main()
{
freopen("D:\\debug\\in.txt", "r", stdin);
freopen("D:\\debug\\out.txt", "w", stdout);
build(1, N-1, 1);
char operators;
char lBracket, rBracket;
int lNum, rNum;
int min = MAX_INT, max = MIN_INT;
while (scanf ("%c %c%d,%d%c", &operators, &lBracket, &lNum, &rNum, &rBracket) != EOF)
{
getchar();
if(lNum == rNum) continue;
lNum << 1;
rNum << 1;
if (lBracket == '(')
lNum++;
if (rBracket == ')')
rNum--;
if (lNum < min)
min = lNum;
if (rNum > max)
max = rNUM;
switch(operators)
{
case 'U':// set true
update(lNum, rNum, 1, 1);
break;
case 'D':
update(lNum, rNum, 1, 0);
break;
case 'S':
update(lNum, rNum, 1, -1);
break;
case 'C':
update(lNum, rNum, 1, -1);
update(min, lNum-1, 1, 0);
update(rNum+1, max, 1, 0);
break;
case 'I':
update(min, lNum-1, 1, 0);
update(rNum+1, max, 1, 0);
break;
}
}
return 0;
}
<file_sep>#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
int main()
{
char ch[4];
while (cin >> ch)
{
sort(ch, ch+3);
cout << ch[0] << " " << ch[1] << " " << ch[2] << endl;
}
return 0;
}
<file_sep>#include <iostream>
#include <queue>
using namespace std;
int data[55][55][55];
bool visited[55][55][55];
int T;
int a, b, c;
bool sign;
int move[6][3] = {
{0, -1, 0},// up
{0, 1, 0}, // down
{0, 0, -1}, // left
{0, 0, 1}, // right
{1, 0, 0}, // forward
{-1, 0, 0} // back
};
struct point
{
int x;
int y;
int z;
int minutes;
};
void bfs()
{
sign = false;
point p1, p2;
queue<point> q;
p1.x = 0;
p1.y = 0;
p1.z = 0;
p1.minutes = 0;
q.push(p1);
while (!q.empty())
{
p1 = q.front();
q.pop();
if (p1.x == a-1 && p1.y == b-1 && p1.z == c-1 && p1.minutes <= T)
{
cout << p1.minutes << endl;
sign = true;
return ;
}
for (int i = 0; i < 6; i++)
{
int x = p1.x + move[i][0],
y = p1.y + move[i][1],
z = p1.z + move[i][2];
if (x >= 0 && y >= 0 && z >= 0 && x < a && y < b && z < c)
{
if (!visited[x][y][z] && data[x][y][z] == 0)
{
visited[x][y][z] = true;
p2.x = x;
p2.y = y;
p2.z = z;
p2.minutes = p1.minutes + 1;
if (x == a-1 && y == b-1 && z == c-1 && p2.minutes <= T)
{
cout << p2.minutes << endl;
sign = true;
return ;
}
q.push(p2);
}
}
}
}
}
int main()
{
int K;
while(cin >> K)
{
while (K--)
{
while (cin >> a >> b >> c >> T)
{
memset(visited, false, sizeof(visited));
for (int i = 0; i < a; i++)
for (int j = 0; j < b; j++)
for (int k = 0; k < c; k++)
scanf("%d", &data[i][j][k]);
visited[0][0][0] = true;
bfs();
if (!sign)
cout << "-1" << endl;
}
}
}
return 0;
}
<file_sep>#include <iostream>
using namespace std;
long min(long a, long b, long c, long d)
{
long tmp1 = a < b ? a : b;
long tmp2 = c < d ? c : d;
return tmp1 < tmp2 ? tmp1 : tmp2;
}
long data[5843] = { 0, 1 };
void calc()
{
data[1] = 1;
int f2, f3, f5, f7;
f2 = f3 = f5 = f7 = 1;
for (int i = 2; i <= 5842; i++)
{
data[i] = min(data[f2] * 2, data[f3] * 3, data[f5] * 5, data[f7] * 7);
if (data[i] == data[f2] * 2)
f2++;
if (data[i] == data[f3] * 3)
f3++;
if (data[i] == data[f5] * 5)
f5++;
if (data[i] == data[f7] * 7)
f7++;
}
}
int main()
{
calc();
int n;
while (cin >> n && n)
{
cout << "The " << n;
if (n % 100 != 11 && n % 10 == 1) cout << "st";
else if (n % 100 != 12 && n % 10 == 2) cout << "nd";
else if (n % 100 != 13 && n % 10 == 3) cout << "rd";
else cout << "th";
cout << " humble number is " << data[n] << "." << endl;
}
return 0;
}
<file_sep>#include <iostream>
#include <cstring>
#include <cstdio>
#include <cstdlib>
#include <map>
#include <algorithm>
#include <vector>
#include <list>
#include <climits>
using namespace std;
const int inf = 0x3fffffff;
int st[1005][1005];
int ns[1005];
int city[1005];
int main()
{
//freopen("in.txt", "r", stdin);
//freopen("out.txt", "w", stdout);
int t, s, d;
while (cin >> t >> s >> d)
{
int a, b, time, maxnode = -1;
for (int i = 0; i < 1005; i++)
for (int j = 0; j < 1005; j++)
st[i][j] = inf;
for (int i = 0; i < t; i++)
{
cin >> a >> b >> time;
maxnode = maxnode > a ? maxnode : a;
maxnode = maxnode > b ? maxnode : b;
st[a][b] = st[b][a] = st[a][b] > time ? time : st[a][b];
}
for (int i = 0; i < s; i++)
cin >> ns[i];
for (int i = 0; i < d; i++)
cin >> city[i];
int min = INT_MAX;
for (int k = 1; k <= maxnode; k++)
for (int i = 1; i <= maxnode; i++)
if (st[i][k] != inf)
{
for (int j = 1; j <= maxnode; j++)
{
if (st[i][k] + st[k][j] < st[i][j])
st[i][j] = st[i][k] + st[k][j];
}
}
for (int i = 0; i < s; i++)
for (int j = 0; j < d; j++)
{
if (st[ns[i]][city[j]] < min)
min = st[ns[i]][city[j]];
}
cout << min << endl;
}
return 0;
}
<file_sep>typedef vector<int> vi;
typedef vector<string> vs;
typedef unsigned int uint;
typedef unsigned lng ulng;
template<class T> inline void checkmax(T &x,T y){if(x<y) x=y;}
template<class T> inline void checkmin(T &x,T y){if(x>y) x=y;}
template<class T> inline T Min(T x,T y){return (x>y?y:x);}
template<class T> inline T Max(T x,T y){return (x<y?y:x);}
template<class T> T gcd(T a,T b){return (a%b)==0?b:gcd(b,a%b);}
template<class T> T lcm(T a,T b){return a*b/gcd(a,b);}
template<class T> T Abs(T a){return a>0?a:(-a);}
template<class T> inline T lowbit(T n){return (n^(n-1))&n;}
template<class T> inline int countbit(T n){return (n==0)?0:(1+countbit(n&(n-1)));}
template<class T> inline bool isPrimeNumber(T n)
{if(n<=1)return false;for (T i=2;i*i<=n;i++) if (n%i==0) return false;return true;}
<file_sep>#include <iostream>
#include <cstring>
#include <cstdio>
#include <cstdlib>
#include <map>
#include <algorithm>
#include <vector>
#include <list>
#include <climits>
using namespace std;
int a[1000005];
void getnextval(int *b, int m, int *next)
{
int i = 0, j = -1;
next[0] = -1;
while(i < m)
{
if (j == -1 || b[i] == b[j])
{
i++;
j++;
next[i] = j;
}
else j = next[j];
}
}
int main()
{
//freopen("in.txt", "r", stdin);
//freopen("out.txt", "w", stdout);
int cases;
scanf ("%d", &cases);
while (cases--)
{
int b[10005];
int n, m;
scanf ("%d%d", &n, &m);
int next[10005];
for (int i = 0; i < n; i++)
scanf ("%d", &a[i]);
for (int j = 0; j < m; j++)
scanf ("%d", &b[j]);
getnextval(b, m, next);
int i = 0, j = 0;
while (i < n && j < m)
{
if (j == -1 || a[i] == b[j])
{
i++;
j++;
}
else j = next[j];
}
if (j == m)
printf ("%d\n", i -m + 1);
else printf ("-1\n") ;
}
return 0;
}
<file_sep>//以时间为优先,而不是以步数为优先!!!!!!
#include <iostream>
#include <queue>
using namespace std;
struct point
{
int x, y;
int time;
friend bool operator < (point a, point b)
{
return a.time > b.time;
}
};
int n, m;
char data[205][205];
bool visited[205][205];
int end_i, end_j;
int move[4][2] = {-1, 0, 0, -1, 1, 0, 0, 1};
void bfs(int i, int j)
{
priority_queue<point> q;
point q1, q2;
q1.x = i;
q1.y = j;
q1.time = 0;
q.push(q1);
bool sign = false;
while (!q.empty())
{
q2 = q.top();
q.pop();
if (data[q2.x][q2.y] == 'r' && q2.time != 0)
{
sign = true;
cout << q2.time << endl;
}
for (int i = 0; i < 4; i++)
{
int a, b;
a = q2.x + move[i][0];
b = q2.y + move[i][1];
if (a >= 0 && a < n && b >= 0 && b < m)
{
if (!visited[a][b])
{
if (data[a][b] == '.' || data[a][b] == 'r')
{
q1.x = a;
q1.y = b;
q1.time = q2.time + 1;
q.push(q1);
visited[a][b] = true;
}
else
{
if (data[a][b] == 'x')
{
q1.x = a;
q1.y = b;
q1.time = q2.time + 2;
q.push(q1);
visited[a][b] = true;
}
}
}
}
}
}
if (!sign)
cout << "Poor ANGEL has to stay in the prison all his life." << endl;
}
int main()
{
while (cin >> n >> m)
{
getchar();
int start_i = 0, start_j = 0;
memset(visited, false, sizeof(visited));
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
{
cin >> data[i][j];
if (data[i][j] == 'a')
{
start_i = i;
start_j = j;
}
}
visited[start_i][start_j] = true;
bfs(start_i, start_j);
}
return 0;
}
<file_sep>#include <iostream>
#include <cstring>
#include <cstdio>
#include <cstdlib>
#include <map>
#include <algorithm>
#include <vector>
#include <list>
#include <climits>
using namespace std;
void getnextval(char* s, int* next)
{
int len = strlen(s);
int i = 0, j = -1;
next[0] = -1;
while (i < len)
{
if (j == -1 || s[i] == s[j])
{
i++;
j++;
next[i] = j;
}
else j = next[j];
}
}
int main()
{
char s1[1005], s2[1005];
while (cin >> s1)
{
if (strcmp(s1, "#") == 0)
break;
cin >> s2;
int next[1005];
getnextval(s2, next);
int len1 = strlen(s1);
int len2 = strlen(s2);
if (len1 < len2)
{
cout << "0" << endl;
break;
}
int i = 0;
int sum = 0;
while (i < len1)
{
int j = 0;
while (i < len1 && j < len2)
{
if (j == -1 || s1[i] == s2[j])
{
i++;
j++;
}
else j = next[j];
}
if (j == len2)
sum ++;
}
cout << sum << endl;
}
return 0;
}
<file_sep>#include <iostream>
#include <cmath>
#include <cstdio>
using namespace std;
double f(double x)
{
return 8*pow(x,4)+7*pow(x,3)+2*pow(x,2)+3*pow(x,1)+6;
}
int main()
{
int t;
while (cin >> t)
{
while(t--)
{
double y;
cin >> y;
double low = 0.0, high = 100.0, mid = 0.0;
if (y < f(low) || y > f(high))
{
cout << "No solution!" << endl;
continue;
}
else
{
while (high - low > 1e-7)
{
mid = (high + low) / 2;
if (f(mid) > y)
high = mid;
else low = mid;
}
printf("%.4lf\n", mid);
}
}
}
return 0;
}
<file_sep>#include <iostream>
using namespace std;
bool data[1005];
void calc()
{
for (int i = 100; i <= 1000; i++)
{
int tmp = i, count = 0, num;
while (tmp)
{
num = tmp % 10;
count += num * num * num;
tmp /= 10;
}
if (count == i)
data[i] = true;
else data[i] = false;
}
}
int main()
{
calc();
int beg, end;
while (cin >> beg >> end)
{
bool sign = true;
for (int i = beg; i <= end; i++)
{
if (data[i] == true)
if (sign)
{
sign = false;
cout << i;
}
else cout << " " << i;
}
if (sign) cout << "no";
cout << endl;
}
return 0;
}
<file_sep>#include <iostream>
using namespace std;
int t, n;
bool used[15];
int num[15];
int data[15];
int flag;
void dfs(int sum, int pos, int level)
{
if (sum == t)
{
for (int i = 1; i < level - 1; i++)
cout << num[i] << "+";
cout << num[level - 1] << endl;
flag = 1;
}
int last = -1;
for (int i = pos + 1; i < n; i++)
{
if (sum + data[i] <= t && !(last == data[i]) && !used[i])
{
num[level] = data[i];
used[i] = true;
last = data[i];
dfs(sum + data[i], i, level + 1);
used[i] = false;
}
}
}
int main()
{
while (cin >> t >> n && t && n)
{
for (int i = 0; i < n; i++)
cin >> data[i];
cout << "Sums of " << t << ":" << endl;
flag = 0;
dfs(0, -1, 1);
if (flag == 0)
cout << "NONE" << endl;
}
return 0;
}
<file_sep>#include <iostream>
using namespace std;
int h, w;
char data[105][105];
int used[105][105];
void dfs(int i, int j)
{
if (i-1 >= 0 && data[i-1][j] == '#' && used[i-1][j] == false)
{
used[i-1][j] = true;
dfs(i-1, j);
}
if (j-1 >= 0 && data[i][j-1] == '#' && used[i][j-1] == false)
{
used[i][j-1] = true;
dfs(i, j-1);
}
if (j+1 < w && data[i][j+1] == '#' && used[i][j+1] == false)
{
used[i][j+1] = true;
dfs(i, j+1);
}
if (i+1 < h && data[i+1][j] == '#' && used[i+1][j] == false)
{
used[i+1][j] = true;
dfs(i+1, j);
}
}
int main()
{
int t;
while (cin >> t)
{
while (t--)
{
cin >> h >> w;
getchar();
for (int i = 0; i < h; i++)
gets(data[i]);
memset(used, false, sizeof(used));
int sum = 0;
for (int i = 0 ; i < h; i++)
for (int j = 0; j < w; j++)
{
if (data[i][j] == '#' && used[i][j] == false)
{
sum ++;
used[i][j] = true;
dfs(i, j);
}
}
cout << sum << endl;
}
}
return 0;
}
<file_sep>#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
using namespace std;
#define lson k<<1
#define rson k<<1|1
typedef long long LL;
const int N = 100005;
struct
{
int l, r;
LL sum;
int delay;
}tree[N<<2];
void build(int l, int r, int k)
{
tree[k].l = l;
tree[k].r = r;
tree[k].sum = 0;
tree[k].delay = 0;
if (l == r)
return ;
int mid = (l + r) >> 1;
build(l, mid, lson);
build(mid+1, r, rson);
}
void insert(LL v, int p, int k)
{
if (tree[k].l == p && tree[k].r == p)
{
tree[k].sum = v;
return ;
}
int mid = (tree[k].l + tree[k].r) >> 1;
if (p <= mid)
insert(v, p, lson);
else insert(v, p, rson);
tree[k].sum = tree[lson].sum + tree[rson].sum;
}
int query(int l, int r, int k)
{
if (tree[k].l == l && tree[k].r == r)
return tree[k].sum;
if (tree[k].delay)
{
tree[lson].sum += (tree[lson].r - tree[lson].l + 1) * tree[k].delay;
tree[lson].delay = tree[k].delay;
tree[rson].sum += (tree[rson].r - tree[rson].l + 1) * tree[k].delay;
tree[rson].delay = tree[k].delay;
tree[k].delay = 0;
}
int mid = (tree[k].l + tree[k].r) >> 1;
if (r <= mid)
return query(l, r, lson);
else
{
if (l > mid)
return query(l, r, rson);
else
return query(l, mid, lson) + query(mid+1, r, rson);
}
tree[k].sum = tree[lson].sum + tree[rson].sum;
}
void update(LL v, int l, int r, int k)
{
if (tree[k].l == l && tree[k].r == r)
{
tree[k].sum += (r - l + 1) * v;
tree[k].delay = v;
return ;
}
if (tree[k].delay)
{
tree[lson].sum += (tree[lson].r - tree[lson].l + 1) * tree[k].delay;
tree[lson].delay = tree[k].delay;
tree[rson].sum += (tree[rson].r - tree[rson].l + 1) * tree[k].delay;
tree[rson].delay = tree[k].delay;
tree[k].delay = 0;
}
int mid = (tree[k].l + tree[k].r) >> 1;
if (r <= mid)
update(v, l, r, lson);
else
{
if (l > mid)
update(v, l, r, rson);
else
{
update(v, l, mid, lson);
update(v, mid+1, r, rson);
}
}
tree[k].sum = tree[lson].sum + tree[rson].sum;
}
int main()
{
int n, q;
freopen("D:\\debug\\in.txt", "r", stdin);
freopen("D:\\debug\\out.txt", "w", stdout);
while (scanf ("%d%d", &n, &q) != EOF)
{
build(1, n, 1);
int value;
for (int i = 1; i <= n; i++)
{
scanf ("%d", &value);
insert(value, i, 1);
}
char Q[10];
LL a, b, c;
for (int i = 0; i < q; i++)
{
scanf ("%s", Q);
switch(Q[0])
{
case 'Q':
scanf ("%d%d", &a, &b);
printf ("%d\n", query(a, b, 1));
break;
case 'C':
scanf ("%d%d%d", &a, &b, &c);
update(c, a, b, 1);
break;
}
}
}
return 0;
}
<file_sep>#include <iostream>
using namespace std;
int data[100005];
int end[100005];
int all[100005];
int max(int a, int b)
{
return a > b ? a : b;
}
int main()
{
int t;
while (cin >> t)
{
int tmp = t, count = 1;
while (t > 0)
{
int num;
cin >> num;
for (int i = 0; i < num; i++)
cin >> data[i];
end[0] = all[0] = data[0];
for (int i = 1; i < num; i++)
{
end[i] = max(end[i-1] + data[i], data[i]);
all[i] = max(end[i], all[i-1]);
}
cout << all[num-1] << endl;
t--;
}
}
return 0;
}
<file_sep>#include <iostream>
using namespace std;
#define SIZE 200005*4
#define LEFT(x) ((x)<<1)
#define RIGHT(x) ((x)<<1|1)
#define MID(x) ((x)>>1)
#define MAX(a,b) ((a) > (b) ? (a) : (b))
struct tree
{
int l;
int r;
int num;
}tree[SIZE];
int maxscore;
void buildTree(int l, int r, int k)
{
if (l == r)
{
tree[k].l = l;
tree[k].r = r;
tree[k].num = 0;
return ;
}
tree[k].l = l;
tree[k].r = r;
tree[k].num = 0;
int m = MID(l + r);
buildTree(l, m, LEFT(k));
buildTree(m+1, r, RIGHT(k));
}
void update(int pos, int tmp_num, int k)
{
if (tree[k].l == tree[k].r && tree[k].l == pos)
{
tree[k].num = tmp_num;
return ;
}
int m = MID(tree[k].l+tree[k].r);
if (pos <= m)
update(pos, tmp_num, LEFT(k));
else update(pos, tmp_num, RIGHT(k));
tree[k].num = MAX(tree[LEFT(k)].num, tree[RIGHT(k)].num);
}
void search(int l, int r, int k)
{
if (tree[k].l == l && tree[k].r == r)
{
maxscore = MAX(maxscore, tree[k].num);
return ;
}
int m = MID(tree[k].l + tree[k].r);
if (r <= m)
search(l, r, LEFT(k));
else
{
if (l > m)
search(l, r, RIGHT(k));
else
{
search(l, m, LEFT(k));
search(m+1, r, RIGHT(k));
}
}
}
int main()
{
int N, M;
while (cin >> N >> M)
{
buildTree(1, N, 1);
for (int i = 1; i <= N; i++)
{
int tmp;
scanf("%d", &tmp);
update(i, tmp, 1);
}
getchar();
for (int i = 1; i <=M; i++)
{
char sign;
int A, B;
scanf("%c%d%d", &sign, &A, &B);
getchar();
if (sign == 'Q')
{
maxscore = 0;
search(A, B, 1);
cout << maxscore << endl;
}
if (sign == 'U')
{
update(A, B, 1);
}
}
}
return 0;
}
<file_sep>#include <iostream>
#include <cstring>
using namespace std;
int main()
{
int n;
while (cin >> n)
{
int count = 1;
int tmp = n;
while (n > 0)
{
char add_one[1005] = { '\0' }, add_two[1005] = { '\0' };
cin >> add_one >> add_two;
int length_one = strlen(add_one), length_two = strlen(add_two);
int sum[1005];
memset(sum, 0, sizeof(sum));
int i = length_one -1, j = length_two - 1;
int k = 0;
while (i >= 0 && j >= 0)
{
sum[k] += (add_one[i] - 48) + (add_two[j] - 48);
if (sum[k] >= 10)
{
sum[k + 1]++;
sum[k] = sum[k] - 10;
}
k++;
i--;
j--;
}
while (i >= 0)
sum[k++] += add_one[i--] - 48;
while (j >= 0)
sum[k++] += add_two[j--] - 48;
cout << "Case " << count << ":" << endl;
cout << add_one << " + " << add_two << " = ";
if (sum[k] != 0)
cout << sum[k];
for (int i = k - 1; i >= 0; i--)
cout << sum[i];
cout << endl;
if (count < tmp)
cout << endl;
count++;
n--;
}
}
return 0;
}
|
e8c4d5a743450d2ee8f63e34f56f9bf0af74a8f8
|
[
"C",
"Makefile",
"C++"
] | 68
|
C++
|
xinali/acm
|
d019190664f247407e324d6a10751a5c9a93ae0f
|
62a66e43872eb63250b74a1a71b52fe4745b8b80
|
refs/heads/master
|
<repo_name>cchostak/ctk<file_sep>/kong-plugin-master/kong/plugins/ctk/handler.lua
local singletons = require "kong.singletons"
local BasePlugin = require "kong.plugins.base_plugin"
local responses = require "kong.tools.responses"
local constants = require "kong.constants"
local utils = require "kong.tools.utils"
local cjson = require "cjson"
local url = require "socket.url"
local http = require "socket.http"
local ipairs = ipairs
local CtkHandler = BasePlugin:extend()
CtkHandler.PRIORITY = 3505
CtkHandler.VERSION = "0.1.0"
function CtkHandler:new()
CtkHandler.super.new(self, "ctk")
end
function CtkHandler:access(conf)
CtkHandler.super.access(self)
uriRetrieved = ngx.var.uri
host = ngx.var.host
-- GET JWT FROM HEADER AND ASSIGN TO TOKEN VARIABLE
token = ngx.req.get_headers()["Authorization"]
-- CHECK WHETER THE JWT EXISTS OR NOT
if token == nil then
ngx.log(ngx.CRIT, "--- FORBIDDEN ---")
ngx.log(ngx.CRIT, token)
return responses.send_HTTP_FORBIDDEN("You cannot consume this service")
else
ngx.log(ngx.CRIT, "--- TOKEN ---")
ngx.log(ngx.CRIT, token)
-- SET THE URL THAT WILL BE USED TO VALIDADE THE JWT
-- CONF.URL RECEIVES THE URL USED UPON INSTALLATION OF THE PLUGIN
ura = conf.url .. token
-- THE HTTP REQUEST THAT TEST IF JWT IS VALID OR NOT
local data = ""
local function collect(chunk)
if chunk ~= nil then
data = data .. chunk
end
return true
end
local ok, statusCode, headers, statusText = http.request {
method = "POST",
url = ura,
sink = collect
}
-- THE STATUS CODE RETRIEVED FROM THE SERVICE
if statusCode == 200 then
ngx.log(ngx.CRIT, "### STATUS 200 OK ###")
ngx.log(ngx.CRIT, uriRetrieved)
else
ngx.log(ngx.CRIT, "### NÃO AUTORIZADO ###")
return responses.send_HTTP_FORBIDDEN("You cannot consume this service")
end
end
end
return CtkHandler<file_sep>/kong-plugin-master/kong/plugins/ctk/schema.lua
local utils = require "kong.tools.utils"
return {
no_consumer = true,
strip_path = true,
fields = {
key_names = {type = "array", required = true, default = {"ctk"}},
url = {type = "url", default = "", required = true}
},
}<file_sep>/kong-plugin-master/kong-plugin-ctk-1.0-1.rockspec
package = "kong-plugin-ctk"
version = "1.0-1"
local pluginName = package:match("^kong%-plugin%-(.+)$") -- "ctk"
supported_platforms = {"linux", "macosx"}
source = {
url = "https://github.com/cchostak/ctk"
}
description = {
summary = "Retrieve a JWT from header and confront it against another service.",
detailed = [[
Retrieves a JWT in the Authorization field of the header and send a request
to a known service that generated that JWT to check wheter or not it is
valid
]],
homepage = "https://github.com/cchostak/ctk2",
license = "MIT/X11"
}
dependencies = {
"lua >= 5.1, < 5.4"
}
build = {
type = "builtin",
modules = {
["kong.plugins."..pluginName..".handler"] = "kong/plugins/"..pluginName.."/handler.lua",
["kong.plugins."..pluginName..".schema"] = "kong/plugins/"..pluginName.."/schema.lua",
}
}
|
ad128016dadd7b62e02007dc67a7e4dab74335b8
|
[
"Lua"
] | 3
|
Lua
|
cchostak/ctk
|
dd2ddb536b6c180cbe60c8333c3ebf0b45fec300
|
94a96ae452aa780fffee18be5b06c66e5bbdded0
|
refs/heads/master
|
<repo_name>formrausch/spree-cash-on-delivery<file_sep>/app/models/spree/order_decorator.rb
Spree::Order.class_eval do
def cash_on_delivery_payment?
payments && payments.last.payment_method.is_a?(Spree::CashOnDelivery::PaymentMethod)
end
def cash_on_delivery_adjustment
if cash_on_delivery_payment?
adjustments.detect{|adj| adj.originator == payments.last.payment_method}
end
end
end
|
7455329bb95f895de2163b9ba3594a51ef09abd3
|
[
"Ruby"
] | 1
|
Ruby
|
formrausch/spree-cash-on-delivery
|
cca01a8434f6310e60b7bb379266a87ca35980f4
|
b05e1dd226e1bf8a2bc1117bdc0673706029da17
|
refs/heads/master
|
<repo_name>tublitzed/tublitzed<file_sep>/resources/assets/js/modules/loader/index.js
var $ = require('jquery');
var loader = {
CSS_CLASS: 'loader',
DEFAULT_TEXT: 'Loading...',
/**
* Hide loader
*/
hide: function() {
this.$el.hide();
},
/**
* Add loading indicator to DOM
* @param {string=} text
*/
add: function(text) {
this.$el = $('<div>').addClass(this.CSS_CLASS).text(text || this.DEFAULT_TEXT);
this.$el.prependTo($('body')).fadeIn('slow');
},
/**
* Show loading indicator
* @param {string=} text
*/
show: function(text) {
this.$el = $('.' + this.CSS_CLASS);
if (this.$el.length) {
this.$el.show();
} else {
this.add(text);
}
}
};
module.exports = loader;<file_sep>/resources/assets/js/modules/photo-fx/tests/index.test.js
let PhotoFx = require('../index.js');
describe("object 'constants'", function() {
it("should set correct ANIMATE_CLASS", function() {
assert.equal(PhotoFx.ANIMATE_CLASS, 'photo-list__item--animate');
});
it("should set correct ACTIVE_CLASS", function() {
assert.equal(PhotoFx.ACTIVE_CLASS, 'photo-list__item--over-active');
});
it("should set correct INACTIVE_CLASS", function() {
assert.equal(PhotoFx.INACTIVE_CLASS, 'photo-list__item--over-any');
});
});<file_sep>/gulpfile.js
var gulp = require('gulp');
var webpack = require('webpack');
var jshint = require('gulp-jshint');
var eslint = require('gulp-eslint');
var sass = require('gulp-sass');
var debug = require('gulp-debug');
var imagemin = require('gulp-imagemin');
var pngquant = require('imagemin-pngquant');
var jpegoptim = require('imagemin-jpegoptim');
var imageResize = require('gulp-image-resize');
var karmaServer = require('karma').Server;
var webpackConfig = require('./webpack.config.js');
gulp.task('test', function(done) {
server = new karmaServer({
configFile: __dirname + '/karma.conf.js',
singleRun: true
}, done).start();
});
gulp.task('img', function() {
var items = [{
srcGlob: [
'./resources/assets/img/src/**/*',
//'!./resources/assets/img/src/about/when.svg'
],
dest: './public/img'
}];
items.forEach(function(item) {
console.log('processing src: ' + item.srcGlob.join(', ') + ', dest: ' + item.dest);
return gulp.src(item.srcGlob)
// .pipe(debug({
// title: 'processing:'
// }))
.pipe(imagemin({
progressive: true,
svgoPlugins: [{
removeViewBox: false,
//cleanupIDs: false - doesn't work.
}],
use: [pngquant()]
}))
.pipe(jpegoptim({
progressive: true
})())
.pipe(gulp.dest(item.dest));
});
});
gulp.task('imgResizePhotos', function() {
gulp.src('./resources/assets/img/etc/photography/thumbs-orig-400x400/*.jpg')
.pipe(imageResize({
width: 199,
height: 199,
crop: true,
upscale: false
}))
.pipe(gulp.dest('./resources/assets/img/src/photography/thumbs/'));
//just move the files, this is silly.
gulp.src('./resources/assets/img/etc/photography/thumbs-orig-400x400/*.jpg')
.pipe(imageResize({
width: 400,
height: 400,
crop: true,
upscale: false
}))
.pipe(gulp.dest('./resources/assets/img/src/photography/thumbs-400x400/'));
});
gulp.task('imgResizePortfolio', function() {
var projects = [
'bronto-segment-builder',
'bronto-profiler',
'bronto-message-editor',
'ca-to-nc',
'cloudmark',
'cloudmark-desktop-one',
'cloudmark-desktop-one-setup',
'cloudmark-desktop-one-ui',
'cloudmark-eng-shirt',
'everyday',
'exhibyte',
'hi-lo',
'hooked-media-group',
'hooked-identity',
'hooked-style-guide',
'kinship',
'krachel-card',
'node',
'perspicuous',
'sztompka',
'sztompka-identity',
'triangle-assassin',
'welcome-hazeli'
//yoomee is not on this list because we use flash for the full version, and the thumbs are larger width.
];
projects.forEach(function(path) {
gulp.src('./resources/assets/img/src/portfolio/' + path + '/browser/full/*.jpg')
.pipe(imageResize({
width: 455,
}))
.pipe(gulp.dest('./resources/assets/img/src/portfolio/' + path + '/browser/thumbs/'));
});
});
gulp.task('sass', function() {
gulp.src('./resources/assets/scss/**/*.scss')
.pipe(sass({
outputStyle: 'compressed' //expanded
}).on('error', sass.logError))
.pipe(gulp.dest('./public/css'));
});
gulp.task('webpack', function(done) {
webpack(webpackConfig).run(function(err, stats) {
if (err) {
console.log('Error', err);
} else {
//console.log(stats.toString());
}
done();
});
});
gulp.task('eslint', function() {
return gulp.src([
'./resources/assets/js/**/**/*.js',
'webpack.config.js',
'gulpfile.js'
])
.pipe(debug({
title: 'debug:'
}))
.pipe(eslint())
.pipe(eslint.format())
.pipe(eslint.failOnError());
});
gulp.task('default', ['eslint', 'img', 'sass', 'webpack', 'test']);
gulp.task('w', function() {
gulp.watch('./resources/assets/scss/**/**/*.scss', ['sass']);
gulp.watch('./resources/assets/js/**/**/*.js', ['webpack']);
});<file_sep>/resources/assets/js/modules/portfolio/project-detail/chart.js
import Chartist from 'chartist';
import $ from "jquery";
import _ from "lodash";
import chart from "../../../modules/chart";
var Chart = {
/**
* Parse hidden input for details on lang splits.
* @return {object|null}
*/
getLangSplitsData: function() {
var $input = $('input[name="langSplits"]');
if (!$input.length) {
return null;
}
var langSplits = JSON.parse($input.val());
var data = {
series: [],
labels: []
};
_.each(langSplits, function(percentage, lang) {
var number = percentage.split('%')[0];
data.series.push(parseInt(number, 10));
data.labels.push(percentage + ' ' + lang);
});
return data;
},
/**
*/
init: function() {
var langSplitsData = this.getLangSplitsData();
if (!_.isNull(langSplitsData)) {
chart.renderPieChart(langSplitsData, '.lang-splits-chart-target');
}
}
};
module.exports = Chart;<file_sep>/app/Http/Controllers/PhotosController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use DB;
use Cache;
use Config;
class PhotosController extends Controller {
const SECTION = 'photos';
const SUBSECTION_INDEX = 'index';
const SUBSECTION_MAP = 'map';
const SUBSECTION_STATE = 'state';
const DEFAULT_STATE = 'ny';
const DEFAULT_LAYOUT = 'square';
const ALL_STATES = array(
'ny' => 'New York',
'nc' => 'North Carolina',
'ca' => 'California',
'fl' => 'Florida'
);
const ALL_LAYOUTS = array(
self::DEFAULT_LAYOUT,
'circle'
);
/**
* Photo list page.
*
* @param Request $request
*/
public function indexAction(Request $request) {
return view("photos/index", $this->getCommonViewData($request, self::SUBSECTION_INDEX));
}
/**
* Photos by map page.
*
* @param Request $request
*/
public function mapAction(Request $request) {
$viewData = $this->getCommonViewData($request, self::SUBSECTION_MAP);
$viewData['additionalJsFiles'] = array('photoMap.bundle.js');
$viewData['additionalCssFiles'] = array('photoMap.css');
$viewData['mapJson'] = file_get_contents(storage_path() . '/json/us-map.json');
return view("photos/map", $viewData);
}
/**
* Photos by state.
*
* @param Request $request
* @param [string=] $state
*/
public function stateAction(Request $request, $state = self::DEFAULT_STATE) {
if (!array_key_exists($state, self::ALL_STATES)) {
return redirect("photos/state");
}
return view("photos/state", $this->getCommonViewData($request, self::SUBSECTION_STATE, $state));
}
/**
* Builds data obj to pass down to template
*
* @param Request $request
* @param string $subsection
* @param string|null $state
*
* @return array
*/
private function getCommonViewData(Request $request, $subsection, $state = null) {
$page = $this->getPage();
$photos = $this->getPhotos($page, $state, $subsection === self::SUBSECTION_MAP);
$total = $this->getTotal($state);
$layout = $this->getLayout();
return array(
'section' => self::SECTION,
'pageHeaderInfo' => $this->getPageHeaderInfo($subsection, $state),
'subNavLinks' => $this->getSubNavLinks($subsection, $state) ,
'subsection' => $subsection,
'subsectionChild' => $state,
'photos' => $photos,
'layoutSwitcherData' => array(
'layouts' => self::ALL_LAYOUTS,
'activeLayout' => $layout,
'currentUrl' => $request->path() . '?p=' . $page,
'defaultLayout' => SELF::DEFAULT_LAYOUT
),
'paginationData' => array(
'total' => $total,
'perPage' => self::PHOTOS_PER_PAGE,
'page' => $page,
'appendQueryParams' => '&l=' . $layout
)
);
}
/**
* Current layout
*
* @return string
*/
private function getLayout() {
if (isset($_GET['l']) && array_search($_GET['l'], self::ALL_LAYOUTS)) {
return $_GET['l'];
}
return self::DEFAULT_LAYOUT;
}
/**
* Get total photos
* @param string|null $state
*
* @return int
*/
private function getTotal($state = null) {
if (is_null($state)) {
return count(DB::select('select * from photos where visible = ?', [1]));
}
return count(DB::select('select * from photos where visible = ? and state = ?', [1, $state]));
}
/**
* @param string $subsection
* @param string|null $state
*
* @return array
*/
private function getPageHeaderInfo($subsection, $state = null) {
$pageHeaderInfo = array(
'title' => 'Photos',
'section' => self::SECTION,
'subtitle' => 'In my spare time, I take a lot of pictures.'
);
if (!is_null($state)) {
$pageHeaderInfo['subtitle'] = self::ALL_STATES[$state];
} else if ($subsection === self::SUBSECTION_MAP) {
$pageHeaderInfo['subtitle'] = 'Click a state on the map to filter photos.';
}
return $pageHeaderInfo;
}
/**
* Add layout to state links to prevent page animation on load if we've
* already seen once
*/
private function addLayoutToStateSubnavLinks() {
$links = self::ALL_STATES;
$layout = $this->getLayout();
$linksWithLayout = array();
foreach($links as $path => $name) {
$linksWithLayout[$path . '?l=' . $layout] = $name;
}
return $linksWithLayout;
}
/**
* @param string $sectionKey
* @param string $subsectionKey
*
* @return array
*/
private function getSubNavLinks($sectionKey) {
return array(
array(
'label' => 'All',
'url' => url("/photos"),
'active' => $sectionKey == self::SUBSECTION_INDEX
),
array(
'label' => 'By State',
'url' => url("/photos/state"),
'active' => $sectionKey == self::SUBSECTION_STATE,
'items' => self::ALL_STATES
),
array(
'label' => 'Map View',
'url' => url("/photos/map"),
'active' => $sectionKey == self::SUBSECTION_MAP
)
);
}
}
<file_sep>/resources/assets/js/modules/scroll-fx/index.js
var $ = require('jquery');
var _ = require('lodash');
var scroll = require('../../util/scroll');
const fixedHeaderClass = 'main-header--fixed';
const fixedSidebarClass = 'page__sidebar--fixed';
let $body = $('body');
let mainHeaderHeight = $('.main-header').outerHeight();
let $sidebar = $('.page .page__sidebar');
let hasSidebar = $sidebar.find('.sub-nav').length > 0;
/**
* When scrolling, check if scrolling up and we're far enough down on the page
* to toggle on fixed header...and do so if needed. Turn off if scrolling down.
* Debounced for perf
*
* @param {event} event
*/
var onScroll = _.debounce(function(event) {
var direction = scroll.getDirection(event);
if (direction !== scroll.SCROLL_DOWN && direction !== scroll.SCROLL_UP) {
return; //we only care about vertical scrolling for now.
}
if ($body.hasClass('modal--visible')) {
return; //don't do any of this with a modal showing.
}
scrollFx._toggleFixedHeader(direction);
scrollFx._toggleFixedSidebar(direction);
}, 100);
var scrollFx = {
_toggleSidebarPos: null,
/**
* We'll stick the class on the body because this affects other elements.
* @param {string} direction
*/
_toggleFixedHeader: function(direction) {
var hasFixedClass = $body.hasClass(fixedHeaderClass);
if (direction == scroll.SCROLL_UP) {
var scrollTop = $(window).scrollTop();
$body.toggleClass(fixedHeaderClass, scrollTop > mainHeaderHeight);
} else if (hasFixedClass) {
$body.removeClass(fixedHeaderClass);
}
},
/**
* @param {string} direction
*/
_toggleFixedSidebar: function(direction) {
if (!this.toggleSidebarPos) {
return;
}
var scrollTop = $(window).scrollTop();
$sidebar.toggleClass(fixedSidebarClass, scrollTop > this.toggleSidebarPos);
},
/**
* Set the scrollY position at which we'll toggle the fixed sidebar.
*/
_setToggleSidebarPos: function() {
var $sidebarNav = $sidebar.find('.sub-nav');
this.toggleSidebarPos = $sidebarNav.outerHeight() + $sidebarNav.offset().top;
},
/**
* Init module
*/
init: function() {
$(window).on('wheel DOMMouseScroll', onScroll);
if (hasSidebar) {
this._setToggleSidebarPos();
this._toggleFixedSidebar();
}
}
};
module.exports = scrollFx;<file_sep>/resources/assets/js/modules/portfolio/project-detail/tests/chart.test.js
import $ from 'jquery';
let chart = require('../chart.js');
describe("getLangSplitsData", function() {
beforeEach(function() {
var val = '{"UI Design": "40%","JavaScript": "5%","CSS": "20%","HTML": "10%","PHP": "25%"}';
var $langSplits = $('<input name="langSplits">').val(val);
$('body').append($langSplits);
});
it("should return correct values", function() {
assert.deepEqual(chart.getLangSplitsData(), {
series: [40, 5, 20, 10, 25],
labels: ['40% UI Design', '5% JavaScript', '20% CSS', '10% HTML', '25% PHP']
});
});
afterEach(function() {
$('[name="langSplits"]').remove();
});
});<file_sep>/resources/views/partials/page-header.php
<header class="page-header">
<h1 class="page-header__title">
<?= $title; ?>
</h1>
<h2 class="page-header__subtitle<?php if (isset($subtitleClass)) { echo ' ' . $subtitleClass; } ?>"><?= $subtitle; ?></h2>
<?php if (isset($nextBtn)) { ?>
<a href="<?= $nextBtn['url']; ?>" class="page-header__next"><?= $nextBtn['title']; ?><span class="icon-right-big page-header__next--icon"></span></a>
<?php } ?>
</header><file_sep>/app/Http/Controllers/PortfolioController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use DB;
use Cache;
use Config;
use Log;
use Storage;
class PortfolioController extends Controller
{
const SECTION = 'portfolio';
const SUBSECTION_INDEX = 'index';
const SUBSECTION_CATEGORY = 'category';
const SUBSECTION_PROJECT = 'project';
const SUBSECTION_CHILD_GRAPHICS = 'graphics';
const SUBSECTION_CHILD_INTERACTIVE = 'interactive';
const DEFAULT_LAYOUT = 'circle';
const DEFAULT_BUCKET = 'all';
const ALL_LAYOUTS = array(
self::DEFAULT_LAYOUT,
'square'
);
const ALL_BUCKETS = array(
self::DEFAULT_BUCKET,
self::SUBSECTION_CHILD_GRAPHICS,
self::SUBSECTION_CHILD_INTERACTIVE
);
/**
* Index redirects to showing projects in the interactive category.
* @param Request $request
*/
public function indexAction(Request $request) {
return $this->categoryAction($request, self::SUBSECTION_CHILD_INTERACTIVE);
}
/**
* Show all projects, all categories.
* @param Request $request
*/
public function allAction(Request $request) {
return view("portfolio/index", $this->getCommonViewData($request, self::SUBSECTION_INDEX));
}
/**
* Since pt content renders via react, allow users to optionally disable JS and access this page instead.
*
* @param Request $request
*/
public function noJsAction(Request $request) {
$viewData = $this->getCommonViewData($request, self::SUBSECTION_INDEX);
$viewData['projects'] = $this->getProjects();
return view("portfolio/index-no-js", $viewData);
}
public function categoryAction(Request $request, $category) {
return view("portfolio/index", $this->getCommonViewData($request, self::SUBSECTION_CATEGORY, $category));
}
/**
* Load per project views
*
* @param string $projectPath
*/
public function projectAction(Request $request, $projectPath) {
$project = $this->getProject('path', $projectPath);
if (empty($project)) {
return redirect("/portfolio");
}
$viewData = array_merge_recursive($this->getCommonViewData($request, self::SUBSECTION_PROJECT, $projectPath), array('project' => $project));
return view("portfolio/project", $viewData);
}
/**
* Current layout
*
* @return string
*/
private function getLayout() {
if (isset($_GET['l']) && array_search($_GET['l'], self::ALL_LAYOUTS)) {
return $_GET['l'];
}
return self::DEFAULT_LAYOUT;
}
/**
* Current bucket, used for generating correct next/prev links
* on project page. Ie, next in graphics section will always go to next
* graphics project, skip over others, etc.
*
* @return string
*/
private function getBucket() {
if (isset($_GET['b']) && array_search($_GET['b'], self::ALL_BUCKETS)) {
return $_GET['b'];
}
return self::DEFAULT_BUCKET;
}
/**
* Return a single project by matching k/v pair, ie by path, or by id.
*
* @return null||object
*/
private function getProject($key, $value) {
$projects = $this->getProjects();
$match = null;
foreach ($projects as $project) {
if ($project->$key === $value) {
$match = $project;
break;
}
}
return $match;
}
/**
* Load projects via ajax.
*
* Accepts pages/categoryId send via get params (p/c)
*
* @return json
*/
public function loadProjectsAjaxAction() {
$page = isset($_GET['p']) ? $_GET['p']: 1;
$categoryName = isset($_GET['c']) ? $_GET['c'] : null;
$projects = $this->getProjects($page, $categoryName);
return json_encode($projects);
}
/**
* Returns view data used by all views in this section.
*
* @param string $subsection
* @param object= $project
*
* @return array
*/
private function getCommonViewData(Request $request, $subsection, $subsectionChild = null) {
$pageHeaderInfo = $this->getPageHeaderInfo($subsection, $subsectionChild);
$relatedProjectLinks = null;
if ($subsection === self::SUBSECTION_PROJECT) {
$relatedProjectLinks = $this->getRelatedProjectLinks($subsectionChild);
$project = $this->getProject('path', $subsectionChild);
if (!empty($project)) {
$pageHeaderInfo['subtitle'] = $project->name;
$pageHeaderInfo['subtitleClass'] = 'display-sm-below';
$pageHeaderInfo['nextBtn'] = array(
'url' => $relatedProjectLinks['next'],
'title' => 'Next Project'
);
}
}
$layout = $this->getLayout();
$page = $this->getPage();
$total = $this->getTotal($subsection, $subsectionChild);
return array(
'section' => self::SECTION,
'pageHeaderInfo' => $pageHeaderInfo,
'subNavLinks' => $this->getSubNavLinks($subsection, $subsectionChild),
'subsection' => $subsection,
'subsectionChild' => $subsectionChild,
'categoryName' => $subsectionChild,
'relatedProjectLinks' => $relatedProjectLinks,
'layoutSwitcherData' => array(
'layouts' => self::ALL_LAYOUTS,
'activeLayout' => $layout,
'currentUrl' => $request->path() . '?p=' . $page,
'defaultLayout' => SELF::DEFAULT_LAYOUT
),
'additionalJsFiles' => array(
'portfolio.bundle.js'
),
'paginationData' => array(
'total' => $total,
'perPage' => self::PROJECTS_PER_PAGE,
'page' => $page,
'appendQueryParams' => '&l=' . $layout
)
);
}
/**
* Get total projects
*
* @param string $subsection
* @param string $subsectionChild - all/int/gr
*
* @return int
*/
private function getTotal($subsection, $subsectionChild) {
if ($subsection === self::SUBSECTION_PROJECT) {
return 1;
}
return count($this->getProjects(null, $subsectionChild));
}
/**
* @return array
*/
private function getPageHeaderInfo($subsection, $subsectionChild) {
$headerInfo = array(
'title' => 'Portfolio',
'section' => self::SECTION,
'subtitle' => 'I design and build stuff on the web.'
);
if ($subsectionChild === self::SUBSECTION_CHILD_GRAPHICS) {
$headerInfo['subtitle'] = 'This is my graphic and UI only design work.';
}
return $headerInfo;
}
/**
* Returns the next and previous project path from links shown in the UI.
* If we're at the end of the list, returns first item for next. If at beginning, returns last for prev.
*
* @param string $currentProjectPath
* @return array ['next' => 'path-to-next', 'prev' => 'path-to-prev']
*/
private function getRelatedProjectLinks($currentProjectPath) {
//get links, filtered by current bucket.
$bucket = $this->getBucket();
$projectLinks = $this->getProjectLinks($bucket);
$total = count($projectLinks) - 1;
$currentPathIndex = array_search($currentProjectPath, array_keys($projectLinks));
//store next and prev paths in case we're at the end of the list.
$nextPath = null;
$prevPath = null;
$index = 0;
foreach($projectLinks as $path => $link) {
if ($index === 0) {
$firstPath = $path;
}
if ($index - 1 === $currentPathIndex) {
$prevPath = $path;
}
if ($index + 1 === $currentPathIndex) {
$nextPath = $path;
}
if ($index === $total) {
$lastPath = $path;
}
$index++;
}
$next = $nextPath ?: $lastPath;
$prev = $prevPath ?: $firstPath;
if ($bucket !== self::PROJECT_CATEGORY_ALL) {
$next .= '?b=' . $bucket;
$prev .= '?b=' . $bucket;
}
return array(
'next' => $next,
'prev' => $prev
);
}
/**
* Returns links
* @return array
*/
private function getCategoryLinks() {
$categories = $this->getCategories();
$links = array();
foreach($categories as $category) {
$links[$category->path] = $category->name;
}
return $links;
}
/**
* Returns all projects, packaged into just links and names.
*
* @param string|null $categoryName - optionally return only for category name.
* @return array
*/
private function getProjectLinks($categoryName = null) {
$projects = $this->getProjects(null, $categoryName);
$links = array();
foreach($projects as $project) {
$links[$project->path] = $project->name;
}
return $links;
}
/**
* @param string $sectionKey
* @param string|null $subsectionChild
*
* @return array
*/
private function getSubNavLinks($sectionKey, $subsectionChild = null) {
return array(
array(
'label' => 'By Category',
'url' => url("/portfolio/c"),
'active' => $sectionKey == self::SUBSECTION_CATEGORY,
'items' => $this->getCategoryLinks()
),
array(
'label' => 'All Projects',
'url' => url("/portfolio/all") ,
'active' => $sectionKey == self::SUBSECTION_INDEX
)
);
}
}
<file_sep>/resources/assets/js/modules/portfolio/project-row.js
import React from 'react';
import Project from './project.js';
var ProjectRow = React.createClass({
/**
*/
render: function() {
return (
<div className='project-row'>
{this.createProjects()}
</div>
);
},
/**
* Returns a collection of projects, or a loading indicator if none exist yet.
* @return {array.<ReactElement>}
*/
createProjects: function() {
return this.props.projects.map(function(project, index) {
return <Project
key={'pkey' + project.id}
name={project.name}
path={project.path}
id={project.id}
langSplits={project.lang_splits}
desc={project.description}
years={project.years}
index={index}
group={this.props.group}
onMouseOver={project.onMouseOverProject}
onMouseOut={project.onMouseOutProject}
category={this.props.category} />;
}, this);
},
});
module.exports = ProjectRow;<file_sep>/resources/assets/js/util/url/index.js
/**
* Url utils.
*/
var url = {
/**
* TODO: move to string util if/when you add one, that's all this is.
*
* Does a given query string key exist in url.
* @param {string} url
* @param {string} key
* @return {boolean}
*/
keyExistsInUrl: function(url, key) {
var patt = key + '=';
var re = new RegExp(patt, 'i');
return re.test(url)
},
/**
* Returns url param from query string.
* @param {string} str
* @return {string}
*/
getParam: function(key) {
var queryParams = window.location.search;
if (queryParams && this.keyExistsInUrl(queryParams, key)) {
var patt = key + '=([^&|\\s]+)';
var re = new RegExp(patt, 'i');
var match = queryParams.match(re);
return match[1] || null;
}
return null;
},
/**
* Add param to url string
* @param {[type]} key [description]
* @param {[type]} value [description]
* @param {[type]} existingStr [description]
*/
addParam: function(key, value, existingStr) {
var str = existingStr || '';
if (/(\?)/.test(str)) {
//already have query params, just not this one.
return str + '&' + key + '=' + value;
}
return str + '?' + key + '=' + value;
},
/**
* Replace param value in a url string.
*
* @param {string} key
* @param {string} value
* @param {str} url
* @return {str}
*/
replaceParam: function(key, value, url) {
var patt = '(' + key + '=[^&|\\s]+)';
var re = new RegExp(patt, 'i');
return url.replace(re, key + '=' + value);
},
/**
* Replace query string value if it exists. If the string does not exist in the url, it will be added.
*
* @param {string} key
* @param {string} value
* @param {existingStr=} optional search string, if not set use url.
*
* @return {string} - new url with value added/replaced
*/
addReplaceParam: function(key, value, existingStr) {
var str = existingStr || window.location.search;
if (!str) {
return this.addParam(key, value, str);
}
if (this.keyExistsInUrl(str, key)) {
return this.replaceParam(key, value, str);
}
return this.addParam(key, value, str);
},
};
module.exports = url;<file_sep>/app/Http/routes.php
<?php
Route::group(array("before" => "guest"), function () {
Route::any("/", array("uses" => "HomeController@indexAction"));
Route::any("/clear-cache", array("uses" => "HomeController@clearCacheAction"));
Route::any("/portfolio", array("uses" => "PortfolioController@indexAction"));
Route::any("/portfolio/index", array("uses" => "PortfolioController@indexAction"));
Route::any("/portfolio/all", array("uses" => "PortfolioController@allAction"));
Route::any("/portfolio/c", array("uses" => "PortfolioController@indexAction"));
Route::any("/portfolio/c/{category}", array("uses" => "PortfolioController@categoryAction"));
Route::any("/portfolio/p/{project}", array("uses" => "PortfolioController@projectAction"));
Route::any("/work", array("uses" => "PortfolioController@indexAction"));
Route::any("/portfolio/no-js", array("uses" => "PortfolioController@noJsAction"));
Route::get("/portfolio/load-projects-ajax", array("uses" => "PortfolioController@loadProjectsAjaxAction"));
Route::get("/portfolio/load-projects-ajax/{categoryId}", array("uses" => "PortfolioController@loadProjectsAjaxAction"));
Route::any("/photos", array("uses" => "PhotosController@indexAction"));
Route::any("/photos/index", array("uses" => "PhotosController@indexAction"));
Route::any("/photos/state", array("uses" => "PhotosController@stateAction"));
Route::any("/photos/state/{state}", array("uses" => "PhotosController@stateAction"));
Route::any("/photos/map", array("uses" => "PhotosController@mapAction"));
Route::any("/about", array("uses" => "AboutController@indexAction"));
Route::any("/about/team", array("uses" => "AboutController@teamAction"));
Route::any("/about/resume", array("uses" => "AboutController@resumeAction"));
Route::any("/contact", array("uses" => "ContactController@indexAction"));
Route::post("/contact/submit-ajax", array("uses" => "ContactController@submitAjaxAction"));
Route::any("/debug", array("uses" => "HomeController@debugAction"));
});
<file_sep>/resources/assets/js/modules/modal/tests/index.test.js
let modal = require('../index.js');
let $ = require('jquery');
describe("object defaults/'constants'", function() {
it("should set correct VISIBLE_CLASS", function() {
assert.equal(modal.VISIBLE_CLASS, 'modal--visible');
});
it("should set correct LOADING_CLASS", function() {
assert.equal(modal.LOADING_CLASS, 'modal--loading');
});
it("should set correct DEFAULT_TITLE", function() {
assert.equal(modal.DEFAULT_TITLE, 'Untitled');
});
it("should set correct OFFSET_TOP", function() {
assert.equal(modal.OFFSET_TOP, 0);
});
it("should set correct OFFSET_LEFT", function() {
assert.equal(modal.OFFSET_LEFT, 0);
});
});
describe("show", function() {
var $body = $('body');
beforeEach(function() {
modal.$body = $body;
modal.show();
});
it("should add correct class to modal.$body", function() {
assert.isTrue(modal.$body.hasClass(modal.VISIBLE_CLASS));
});
});
describe("hide", function() {
var $body = $('body');
beforeEach(function() {
modal.$body = $body;
modal.show();
modal.hide();
});
it("should remove correct class from modal.$body", function() {
assert.isFalse(modal.$body.hasClass(modal.VISIBLE_CLASS));
});
});
describe("getImg", function() {
var $result, url;
beforeEach(function() {
url = 'http://foo.bar';
$result = modal.getImg($('<span>').attr('data-media-url', url));
});
it("should return an image with the correct url", function() {
assert.equal($result.attr('src'), url);
});
});
describe("getTitle", function() {
it("should return default title if data-title attr not set", function() {
assert.equal(modal.getTitle($('<div>')), modal.DEFAULT_TITLE);
});
it("should return default title if data-title is falsy", function() {
assert.equal(modal.getTitle($('<div>').attr('data-title', '')), modal.DEFAULT_TITLE);
});
it("should return correct title based on data-title attr", function() {
assert.equal(modal.getTitle($('<div>').attr('data-title', 'foobar')), 'foobar');
});
});
describe("getIndex", function() {
var $html;
beforeEach(function() {
$html = $('<ul>').html('<li><a id="1" data-index="0"></a></li><li><a id="2" data-index="1"></a></li><li><a id="3" data-index="2"></a></li>');
});
it("should return correct index", function() {
assert.equal(modal.getIndex($html.find('#1')), 0);
});
it("should return correct index", function() {
assert.equal(modal.getIndex($html.find('#2')), 1);
});
it("should return correct index", function() {
assert.equal(modal.getIndex($html.find('#3')), 2);
});
});
describe("getValidIndex", function() {
var $html, fakeTriggers;
beforeEach(function() {
fakeTriggers = [];
for (var i = 0; i < 20; i++) {
fakeTriggers.push(i);
}
modal.$modalMediaThumbs = fakeTriggers;
modal.$modalMediaTriggers = fakeTriggers;
});
it("should return 0 if requested index is too high", function() {
assert.equal(modal.getValidIndex(54), 0);
});
it("should return correct index if requested index is valid", function() {
assert.equal(modal.getValidIndex(18), 18);
});
it("should return total if requested index is too low", function() {
assert.equal(modal.getValidIndex(-1), fakeTriggers.length - 1);
});
afterEach(function() {
modal.$modalMediaTriggers = [];
});
});<file_sep>/resources/assets/js/modules/chart/index.js
var Chartist = require('chartist');
var $ = require('jquery');
/**
* Misc chart related helpers.
*/
var chart = {
/**
* TODO: something that doesn't use SMIL
* and something that's not literally the example:)
*
* https://gionkunz.github.io/chartist-js/examples.html
* @param {object} data
*/
animatePieChart: function(data) {
if (data.type === 'slice') {
// Get the total path length in order to use for dash array animation
var pathLength = data.element._node.getTotalLength();
// Set a dasharray that matches the path length as prerequisite to animate dashoffset
data.element.attr({
'stroke-dasharray': pathLength + 'px ' + pathLength + 'px'
});
// Create animation definition while also assigning an ID to the animation for later sync usage
var animationDefinition = {
'stroke-dashoffset': {
id: 'anim' + data.index,
dur: 500,
from: -pathLength + 'px',
to: '0px',
easing: Chartist.Svg.Easing.easeInOutSine,
// We need to use `fill: 'freeze'` otherwise our animation will fall back to initial (not visible)
fill: 'freeze'
}
};
// If this was not the first slice, we need to time the animation so that it uses the end sync event of the previous animation
if (data.index !== 0) {
animationDefinition['stroke-dashoffset'].begin = 'anim' + (data.index - 1) + '.end';
}
// We need to set an initial value before the animation starts as we are not in guided mode which would do that for us
data.element.attr({
'stroke-dashoffset': -pathLength + 'px'
});
// We can't use guided mode as the animations need to rely on setting begin manually
// See http://gionkunz.github.io/chartist-js/api-documentation.html#chartistsvg-function-animate
data.element.animate(animationDefinition, false);
}
},
/**
* Render pie chart
*
* @param {object} data {series:[...], labels:[...]};
* @param {string} selector to use as chart target.
*/
renderPieChart: function(data, selector) {
var pieChart = new Chartist.Pie(selector, {
series: data.series,
labels: data.labels
}, {
donut: true,
donutWidth: 10,
chartPadding: 30,
total: _.reduce(data.series, function(total, percent) {
return total + percent;
}),
labelOffset: 20,
labelDirection: 'explode'
});
pieChart.on('draw', this.animatePieChart);
},
/**
* Init this module.
*/
init: function() {
var self = this;
$('.pie-chart-target').each(function(){
var $this = $(this);
var id = $this.prop('id');
var $chartConfig = $('[data-chart-target="' + id + '"]');
if ($chartConfig.length) {
self.renderPieChart($.parseJSON($chartConfig.val()), '#' + id);
}
});
}
};
module.exports = chart;<file_sep>/resources/assets/js/main.js
var $ = require('jquery');
require('./plugins/modernizr.js');
var modal = require('./modules/modal');
var scrollFx = require('./modules/scroll-fx');
var photoFx = require('./modules/photo-fx');
var form = require('./modules/form');
var layoutSwitcher = require('./modules/layout-switcher');
var chart = require('./modules/chart');
var clock = require('./modules/clock');
var laptop = require('./modules/laptop');
var nav = require('./modules/nav');
$(function() {
laptop.init();
nav.init();
modal.init();
form.init();
clock.init();
photoFx.init();
scrollFx.init();
layoutSwitcher.init();
chart.init();
var $body = $('body');
setTimeout(function() {
$body.addClass('body--animate-in');
}, 100);
$('.alert__close').on('click', function(event) {
event.preventDefault();
$(this).parent('.alert').slideUp('fast');
});
});<file_sep>/resources/assets/js/modules/portfolio/project-detail/images.js
import $ from "jquery";
import tooltipster from "jquery-tooltipster/js/jquery.tooltipster.js";
var Images = {
ACTIVE_THUMBNAIL_CLASS: 'thumbnail-image-list__item--active',
SEEN_TOOLTIP_STORAGE_KEY: 'tds.seenPortfolioThumbnailTooltip',
/**
* Swap out the browser image with the one clicked.
* @param {object} event
*/
onThumbnailClick: function(event) {
event.preventDefault();
var $el = $(event.currentTarget);
this.$thumbs.not($el).removeClass(this.ACTIVE_THUMBNAIL_CLASS);
$el.addClass(this.ACTIVE_THUMBNAIL_CLASS);
this.replaceImage($el);
this.showTooltip();
},
/**
* Replace the active image.
* @param {element} $thumbnail
*/
replaceImage: function($thumbnail) {
var title = $thumbnail.attr('data-title');
this.$activeImg.prop('src', $thumbnail.find('img').attr('src'));
this.$activeImg.prop('alt', title);
this.$activeImageLink.attr('data-title', title);
this.$activeImageLink.attr('data-index', $thumbnail.attr('data-index'));
this.$activeImageLink.attr('data-media-url', $thumbnail.attr('data-media-url'));
},
/**
* Show tooltip if it's enabled.
*/
showTooltip: function() {
if (this.isToolTipEnabled()) {
this.$activeImageLink.tooltipster('enable').tooltipster('show');
this.disableTooltip();
}
},
/**
* Use local storage to prevent tooltip from being shown again.
*/
disableTooltip: function() {
window.localStorage.setItem(this.SEEN_TOOLTIP_STORAGE_KEY, true);
},
/**
* Do we want to show a tooltip?
*/
isToolTipEnabled: function() {
return window.localStorage.getItem(this.SEEN_TOOLTIP_STORAGE_KEY) !== 'true';
},
/**
* Show a tooltip the first time a user clicks a thumb to let them know they can enlarge
* by clicking browser. Tooltip is bound to different element than the one used to trigger it's
* visibility, so hide it by default.
*
*/
initTooltip: function() {
this.$activeImageLink.tooltipster({
timer: 2000,
functionAfter: function() {
$(this).tooltipster('disable');
}
}).tooltipster('hide');
},
/**
* Init this module.
*/
init: function() {
this.$activeImageWrapper = $('.thumbnail-target');
this.$thumbs = $('.thumbnail-image-list__item');
this.$activeImg = this.$activeImageWrapper.find('.thumbnail-target__img');
this.$activeImageLink = this.$activeImageWrapper.find('.modal-media-trigger');
this.$thumbs.on('click', this.onThumbnailClick.bind(this));
if (this.isToolTipEnabled()) {
this.initTooltip();
}
}
};
module.exports = Images;<file_sep>/app/Http/Controllers/HomeController.php
<?php
namespace App\Http\Controllers;
use Cache;
use Log;
use Config;
class HomeController extends Controller
{
/**
* Homepage entry point.
*/
public function indexAction() {
return view("index", $this->buildViewData());
}
/**
* debug entry point.
*/
public function debugAction() {
//access denied if we're not in debug mode.
if (!Config::get('app.debug')) {
return redirect("/");
}
return view("debug/index", $this->buildViewData());
}
/**
* @return array
*/
private function buildViewData() {
$photos = $this->getPhotos(1);
$photos = array_slice($photos, 0, 12);
shuffle($photos);
return array(
'section' => 'home',
'projects' => $this->getProjects(null, null, true),
'photos' => $photos
);
}
/**
* Util endpoint to hit to clear all application caches
*
* /clear-cache
*/
public function clearCacheAction() {
Log::info('Clearing application cache...');
Cache::flush();
return redirect("/");
}
}
<file_sep>/resources/assets/js/modules/portfolio/project-detail/tests/images.test.js
let $ = require('jquery');
let Images = require('../images.js');
describe("object 'constants'", function() {
it("should set correct ACTIVE_THUMBNAIL_CLASS", function() {
assert.equal(Images.ACTIVE_THUMBNAIL_CLASS, 'thumbnail-image-list__item--active');
});
it("should set correct SEEN_TOOLTIP_STORAGE_KEY", function() {
assert.equal(Images.SEEN_TOOLTIP_STORAGE_KEY, 'tds.seenPortfolioThumbnailTooltip');
});
});
describe("replaceImage", function() {
var $activeImg, $activeImageLink, $thumbnail, tempId, title, thumbSrc, fullSrc, index;
beforeEach(function() {
index = 123;
title = 'dummy title';
thumbSrc = '/img/test.png';
fullSrc = '/img/test2.png';
tempId = 'dummylink123342r23r';
$activeImg = $('<img />');
$activeImageLink = $('<a id="' + tempId + '">').append($activeImg);
$thumbnail = $('<div data-title="' + title + '" data-media-url="' + fullSrc + '" data-index="' + index + '">').append('<img src="' + thumbSrc + '" />');
$('body').append($activeImageLink);
Images.$activeImg = $activeImg;
Images.$activeImageLink = $activeImageLink;
Images.replaceImage($thumbnail);
});
it("should set correct src on $activeImg", function() {
assert.equal(Images.$activeImg.attr('src'), thumbSrc);
});
it("should set correct alt on $activeImg", function() {
assert.equal(Images.$activeImg.attr('alt'), title);
});
it("should set correct data-title on $activeImageLink", function() {
assert.equal(Images.$activeImageLink.attr('data-title'), title);
});
it("should set correct data-index on $activeImageLink", function() {
assert.equal(Images.$activeImageLink.attr('data-index'), index);
});
it("should set correct data-media-url on $activeImageLink", function() {
assert.equal(Images.$activeImageLink.attr('data-media-url'), fullSrc);
});
afterEach(function() {
$('body').find('#' + tempId).remove();
Images.$activeImg = null;
Images.$activeImageLink = null;
});
});<file_sep>/app/Http/Controllers/AboutController.php
<?php
namespace App\Http\Controllers;
class AboutController extends Controller {
const SECTION = 'about';
const SUBSECTION_INDEX = 'index';
const SUBSECTION_RESUME = 'resume';
const SUBSECTION_TEAM = 'team';
/**
* Landing page
*/
public function indexAction() {
return view("about/index", $this->getCommonViewData(self::SUBSECTION_INDEX));
}
/**
* Team page.
*/
public function teamAction() {
return view("about/team", $this->getCommonViewData(self::SUBSECTION_TEAM));
}
/**
* Resume page
*/
public function resumeAction() {
$viewData = $this->getCommonViewData(self::SUBSECTION_RESUME);
$resume = json_decode(file_get_contents(storage_path() . '/json/resume.json'), true);
return view("about/resume", array_merge($viewData, array('resume' => $resume)));
}
/**
* Build array to send to all views in this section.
*
* @param string $subsection
* @return array
*/
private function getCommonViewData($subsection) {
return array(
'section' => self::SECTION,
'pageHeaderInfo' => $this->getPageHeaderInfo($subsection),
'subNavLinks' => $this->getSubNavLinks($subsection),
'chartData' => $this->getChartData()
);
}
/**
* Returns config object used for the chart in the "what"
* section.
*
* @return array
*/
private function getChartData() {
$chartData = array(
'what' => json_encode(array(
'labels' => array(
'40% Portfolio',
'40% Play',
'20% Insomnia'
),
'series' => array(40,40,20)
))
);
return $chartData;
}
/**
* @param string $subsection
* @return array
*/
private function getPageHeaderInfo($subsection) {
return array(
'title' => 'About',
'section' => self::SECTION,
'subtitle' => $this->getSubtitle($subsection)
);
}
/**
* Returns subtitle string specific to subsection.
*
* @param string $subsection
* @return string
*/
private function getSubtitle($subsection) {
switch ($subsection) {
case self::SUBSECTION_TEAM:
$title = "Meet the team. We're a dedicated bunch.";
break;
case self::SUBSECTION_RESUME:
$yearsExperience = date("Y") - 2008;
$title = "I'm <NAME>, a designer and front-end engineer with $yearsExperience years of professional experience.";
break;
default:
$title = "Tublitzed is the work and play of <NAME>.";
break;
}
return $title;
}
/**
* @param string $sectionKey
*
* @return array
*/
private function getSubNavLinks($sectionKey) {
return array(
array(
'label' => 'General Info',
'url' => url("/about") ,
'active' => $sectionKey == self::SUBSECTION_INDEX
),
array(
'label' => 'The Team',
'url' => url("/about/team") ,
'active' => $sectionKey == self::SUBSECTION_TEAM
),
array(
'label' => 'Resume',
'url' => url("/about/resume") ,
'active' => $sectionKey == self::SUBSECTION_RESUME
)
);
}
}
<file_sep>/resources/assets/js/modules/portfolio/tests/project.test.js
import React from 'react';
import _ from 'lodash';
import $ from 'jquery';
let Project = require('../project.js');
describe("getTemplateId", function() {
var project;
beforeEach(function() {
project = new Project();
});
it("should return 2 when group is 'a' and index is not 0", function() {
project.props = {
group: 'a',
index: 23
};
assert.equal(project.getTemplateId(), 2);
});
it("should return 4 when group is not 'a' and index is 1", function() {
project.props = {
group: 'foo',
index: 1
};
assert.equal(project.getTemplateId(), 4);
});
it("should return 3 when group is not a and index is not 1", function() {
project.props = {
group: 'foo',
index: 2
};
assert.equal(project.getTemplateId(), 3);
});
});
describe("buildProjectLink", function() {
var project;
beforeEach(function() {
project = new Project();
});
it("should return category as 'b' query param if category exists", function() {
project.props = {
path: 'a',
category: 'foo'
};
assert.equal(project.buildProjectLink(), '/portfolio/p/a?b=foo');
});
it("should return return link with no query params for empty category", function() {
project.props = {
path: 'a',
category: ''
};
assert.equal(project.buildProjectLink(), '/portfolio/p/a');
});
it("should return return link with no query params for null category", function() {
project.props = {
path: 'a'
};
assert.equal(project.buildProjectLink(), '/portfolio/p/a');
});
});
<file_sep>/resources/assets/js/modules/portfolio/project-list.js
import React from 'react';
import Project from './project.js';
import ProjectRow from './project-row.js';
import $ from 'jquery';
import _ from 'lodash';
/**
* A project list houses a bunch of....you got it. projects.
*/
var ProjectList = React.createClass({
/**
*/
getInitialState: function() {
return {
projects: []
}
},
/**
*/
componentDidMount: function() {
var self = this;
var request = new XMLHttpRequest();
request.open('GET', this.buildUrl(), true);
request.onload = function() {
if (request.status >= 200 && request.status < 400) {
self.setState({
projects: _.toArray(JSON.parse(request.responseText))
});
}
};
request.onerror = function() {
// There was a connection error of some sort
};
request.send();
},
/**
* Build url used to pull down projects.
* @return string url
*/
buildUrl: function() {
var url = '/portfolio/load-projects-ajax';
var querySeparator = '?';
if (this.props.category) {
url += querySeparator + 'c=' + this.props.category;
querySeparator = '&';
}
url += querySeparator + 'p=' + this.getPage();
return url;
},
/**
*/
render: function() {
return (
<div>
{this.createProjectRows()}
</div>
);
},
/**
* @return {array.<ProjectRow>}
*/
createProjectRows: function() {
if (!this.state.projects.length) {
return <div className="loader">loading...</div>;
}
var odd = [];
var even = [];
var self = this;
this.state.projects.forEach(function(project, index) {
if (index % 2 == 0) {
even.push(project);
} else {
odd.push(project);
}
});
return even.map(function(project, index) {
var projects = [project];
var projectGroup = 'a';
if (odd[index]) {
projects.push(odd[index]);
}
return <ProjectRow key={'prowkey' + project.id} projects={projects} group={this.getProjectGroup(index)} category={this.props.category} />
}, this);
},
/**
* 2 group types, each group block has 4 projects.
* @param {number} index - row index
* @return {string}
*/
getProjectGroup: function(index) {
if ((index % 2) > 0) {
return 'b';
}
return 'a';
},
/**
* Returns page based on hidden input value. If not present, defaults to 1.
* @return {number}
*/
getPage: function() {
var $pageNumber = $('.pagination').find('[name="current-page"]');
if ($pageNumber.length) {
return $pageNumber.val();
}
return 1;
}
});
module.exports = ProjectList;<file_sep>/resources/assets/js/modules/form/index.js
var $ = require('jquery');
var _ = require('lodash');
var alert = require('../alert');
/**
* Generic forms module used for JS validation and submitting forms/handling responses via ajax.
*/
var form = {
ERROR_LABEL_CLASS: 'form-field-error',
ERROR_FIELD_CLASS: 'form-field--has-error',
FORM_DIRTY_CLASS: 'form--is-dirty', //ie, did user try to submit once already (ie, trigger inline messages)
DEFAULT_ERROR_MESSAGE: 'This field is required.',
/**
* Get JSON object containing required field errors.
* @param {object} $form
*/
getRequiredFieldErrors: function($form) {
var $required = $form.find('[name="required-field-errors"]');
if (!$required.length) {
return {};
}
return $.parseJSON($required.attr('data-value'));
},
/**
* Check a form to see if required fields are filled in.
* @param {object} $form
* @return {Boolean}
*/
hasRequiredFields: function($form) {
var requiredFieldErrors = this.getRequiredFieldErrors($form);
var self = this;
var errors = [];
$form.find('[data-required="true"]').each(function() {
var $field = $(this);
if (_.isEmpty($field.val())) {
var fieldName = $field.attr('name');
var errorMessage = requiredFieldErrors[fieldName];
errors.push({
fieldName: fieldName,
message: errorMessage || self.DEFAULT_ERROR_MESSAGE
});
}
});
if (errors.length) {
return errors;
}
return true;
},
/**
* Show errors for a form
*
* @param {object} $form
* @param {array} errors [{fieldName: string, message: string}]
*/
showErrors: function($form, errors) {
errors.forEach((error) => {
this.showError($form.find('[name="' + error.fieldName + '"]'), error.message);
});
//focus problem field
var firstWithError = errors.shift();
$form.find('[name="' + firstWithError.fieldName + '"]').focus();
},
/**
* Hide field error
* @param {object} $field
*/
hideError: function($field) {
$field.removeClass(this.ERROR_FIELD_CLASS);
$field.parent('li').find('.' + this.ERROR_LABEL_CLASS).hide();
},
/**
* Show field level error
* @param {object} $field
* @param {string=} errorMessage - optional message
*/
showError: function($field, errorMessage) {
var $fieldParent = $field.parent('li');
var $error = $fieldParent.find('.' + this.ERROR_LABEL_CLASS);
$field.addClass(this.ERROR_FIELD_CLASS);
if ($error.length) {
$error.show();
} else {
$fieldParent.append('<label class="' + this.ERROR_LABEL_CLASS + '">' + errorMessage || this.DEFAULT_ERROR_MESSAGE + '</label>');
}
},
/**
* Validate form
*
* @param {object} $form
*/
validate: function($form) {
$form.addClass(this.FORM_DIRTY_CLASS);
var validOrErrors = this.hasRequiredFields($form);
if (validOrErrors === true) {
this.submit($form);
} else {
this.showErrors($form, validOrErrors);
}
},
/**
* Submit form via ajax
*
* @param {object} $form
*/
submit: function($form) {
var self = this;
$.ajax({
data: $form.serialize(),
url: $form.attr('data-ajax-action'),
method: $form.attr('method'),
headers: {
'X-CSRF-Token': $form.find('[name="csrf-token"]').attr('data-value'),
},
success: function(json) {
var data = $.parseJSON(json);
var alertType = data.status === true ? alert.TYPE_SUCCESS : alert.TYPE_ERROR;
alert.show(data.message, alertType);
if (data.status === true) {
self.clearFields($form);
}
},
error: function() {
alert.show('Unable to process form.', alert.TYPE_ERROR);
}
});
},
/**
* Clear form fields. Only wired for what's in use now; add the other
* field types as needed.
*
* @param {object} $form
*/
clearFields: function($form) {
$form.find('.form-field').each(function(){
var $this = $(this);
if ($this.is('input') || $this.is('textarea')) {
$this.val('');
}
});
},
/**
* Init form module
*/
init: function() {
var $defaultFocusField = $('.form-field--default-focus');
if ($defaultFocusField.length) {
$defaultFocusField.focus();
}
var $validationForm = $('form[data-use-validation="true"]');
if ($validationForm.length) {
var self = this;
$validationForm.on('submit', function(event) {
event.preventDefault();
self.validate($(this));
});
$validationForm.find('[data-required="true"]').on('keyup change', function() {
if (!$validationForm.hasClass(self.FORM_DIRTY_CLASS)) {
return;
}
var $field = $(this);
if (!_.isEmpty($field.val())) {
self.hideError($field);
} else {
self.showError($field);
}
});
}
}
};
module.exports = form;<file_sep>/resources/assets/js/util/scroll/tests/index.test.js
let scroll = require('../index.js');
describe("getDirection", function() {
var DOMMouseScrollEventUp, DOMMouseScrollEventDown, wheelUp, wheelDown, wheelRight, wheelLeft, unsupported;
beforeEach(function() {
DOMMouseScrollEventUp = {
type: 'DOMMouseScroll',
detail: -1
};
DOMMouseScrollEventDown = {
type: 'DOMMouseScroll',
detail: 0
};
wheelUp = {
type: 'wheel',
wheelDeltaX: 0,
wheelDeltaY: 1
};
wheelDown = {
type: 'wheel',
wheelDeltaX: 0,
wheelDeltaY: -1
};
wheelRight = {
type: 'wheel',
wheelDeltaX: -3,
wheelDeltaY: 0
};
wheelLeft = {
type: 'wheel',
wheelDeltaX: 3,
wheelDeltaY: 0
};
unsupported = {
foo: 'bar'
};
});
it("should return correct value for DOMMouseScroll up", function() {
assert.equal(scroll.getDirection(DOMMouseScrollEventUp), scroll.SCROLL_UP);
});
it("should return correct value for DOMMouseScroll down", function() {
assert.equal(scroll.getDirection(DOMMouseScrollEventDown), scroll.SCROLL_DOWN);
});
it("should return correct value for DOMMouseScroll up wrapped in originalEvent", function() {
assert.equal(scroll.getDirection({
originalEvent: DOMMouseScrollEventUp
}), scroll.SCROLL_UP);
});
it("should return correct value for DOMMouseScroll down wrapped in originalEvent", function() {
assert.equal(scroll.getDirection({
originalEvent: DOMMouseScrollEventDown
}), scroll.SCROLL_DOWN);
});
it("should return correct value for wheelUp", function() {
assert.equal(scroll.getDirection(wheelUp), scroll.SCROLL_UP);
});
it("should return correct value for wheelDown", function() {
assert.equal(scroll.getDirection(wheelDown), scroll.SCROLL_DOWN);
});
it("should return correct value for wheelRight", function() {
assert.equal(scroll.getDirection(wheelRight), scroll.SCROLL_RIGHT);
});
it("should return correct value for wheelLeft", function() {
assert.equal(scroll.getDirection(wheelLeft), scroll.SCROLL_LEFT);
});
it("should return correct value for wheelLeft wrapped in originalEvent", function() {
assert.equal(scroll.getDirection({
originalEvent: wheelLeft
}), scroll.SCROLL_LEFT);
});
it("should return correct value for wheelDown wrapped in originalEvent", function() {
assert.equal(scroll.getDirection({
originalEvent: wheelDown
}), scroll.SCROLL_DOWN);
});
it("should return correct value for wheelRight wrapped in originalEvent", function() {
assert.equal(scroll.getDirection({
originalEvent: wheelRight
}), scroll.SCROLL_RIGHT);
});
it("should return correct value for wheelLeft wrapped in originalEvent", function() {
assert.equal(scroll.getDirection({
originalEvent: wheelLeft
}), scroll.SCROLL_LEFT);
});
it("should return null", function() {
assert.isNull(scroll.getDirection(unsupported));
});
});<file_sep>/resources/assets/js/modules/laptop/index.js
var $ = require('jquery');
//webpack hack for Snap
//https://github.com/adobe-webplatform/Snap.svg/issues/341
var Snap = require("imports-loader?this=>window,fix=>module.exports=0!snapsvg/dist/snap.svg.js");
var laptop = {
CHAR_FADEIN_DELAY: 300,
textAttrs: {
fill: '#FFF',
"font-size": "200%",
opacity: '0.75'
},
fadeIn: function(el) {
Snap.animate(0, 1, function(value) {
el.attr({
opacity: value
});
}, 100);
},
/**
* Adds a hidden text group, with each character split into separate tspans.
*
* @param {string} text - use this string for text items.
* @param {number} x - x coords
* @param {number} y - y coords
*
* @return {array}
*/
addTextGroup: function(text, x, y) {
var group = this.s.g().attr(this.textAttrs);
return group
.text(x, y, text.split(''))
.selectAll("tspan").attr({
opacity: 0
});
},
/**
* Add animated text to svg el.
*/
animateSvg: function() {
this.s = Snap('.laptop__screen svg');
var self = this;
var designGroupEls = this.addTextGroup('DESIGN', 145, 210);
var codeGroupEls = this.addTextGroup('CODE', 445, 255);
designGroupEls.forEach(function(el, index) {
setTimeout(function() {
self.fadeIn(el);
}, index * self.CHAR_FADEIN_DELAY);
});
setTimeout(function() {
codeGroupEls.forEach(function(el, index) {
setTimeout(function() {
self.fadeIn(el);
}, index * self.CHAR_FADEIN_DELAY);
});
}, designGroupEls.length * self.CHAR_FADEIN_DELAY);
},
/**
* If we've got a laptop el, start the animation.
*/
init: function() {
this.$wrapper = $('.laptop__screen');
if ($('body').hasClass('body--home') && this.$wrapper.length) {
this.animateSvg();
}
}
};
module.exports = laptop;<file_sep>/public/js/app.bundle.js
webpackJsonp([0],[
/* 0 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $ = __webpack_require__(1);
__webpack_require__(2);
var modal = __webpack_require__(3);
var scrollFx = __webpack_require__(6);
var photoFx = __webpack_require__(10);
var form = __webpack_require__(11);
var layoutSwitcher = __webpack_require__(13);
var chart = __webpack_require__(15);
var clock = __webpack_require__(17);
var laptop = __webpack_require__(19);
var nav = __webpack_require__(20);
$(function () {
laptop.init();
nav.init();
modal.init();
form.init();
clock.init();
photoFx.init();
scrollFx.init();
layoutSwitcher.init();
chart.init();
var $body = $('body');
setTimeout(function () {
$body.addClass('body--animate-in');
}, 100);
$('.alert__close').on('click', function (event) {
event.preventDefault();
$(this).parent('.alert').slideUp('fast');
});
});
/***/ },
/* 1 */,
/* 2 */
/***/ function(module, exports) {
/*! modernizr 3.2.0 (Custom Build) | MIT *
* http://modernizr.com/download/?-cssvmaxunit-setclasses !*/
"use strict";
!(function (e, n, t) {
function o(e, n) {
return typeof e === n;
}function s() {
var e, n, t, s, i, a, r;for (var l in c) if (c.hasOwnProperty(l)) {
if ((e = [], n = c[l], n.name && (e.push(n.name.toLowerCase()), n.options && n.options.aliases && n.options.aliases.length))) for (t = 0; t < n.options.aliases.length; t++) e.push(n.options.aliases[t].toLowerCase());for (s = o(n.fn, "function") ? n.fn() : n.fn, i = 0; i < e.length; i++) a = e[i], r = a.split("."), 1 === r.length ? Modernizr[r[0]] = s : (!Modernizr[r[0]] || Modernizr[r[0]] instanceof Boolean || (Modernizr[r[0]] = new Boolean(Modernizr[r[0]])), Modernizr[r[0]][r[1]] = s), f.push((s ? "" : "no-") + r.join("-"));
}
}function i(e) {
var n = u.className,
t = Modernizr._config.classPrefix || "";if ((h && (n = n.baseVal), Modernizr._config.enableJSClass)) {
var o = new RegExp("(^|\\s)" + t + "no-js(\\s|$)");n = n.replace(o, "$1" + t + "js$2");
}Modernizr._config.enableClasses && (n += " " + t + e.join(" " + t), h ? u.className.baseVal = n : u.className = n);
}function a(e, n) {
return e - 1 === n || e === n || e + 1 === n;
}function r() {
return "function" != typeof n.createElement ? n.createElement(arguments[0]) : h ? n.createElementNS.call(n, "http://www.w3.org/2000/svg", arguments[0]) : n.createElement.apply(n, arguments);
}function l() {
var e = n.body;return (e || (e = r(h ? "svg" : "body"), e.fake = !0), e);
}function d(e, t, o, s) {
var i,
a,
d,
f,
c = "modernizr",
p = r("div"),
h = l();if (parseInt(o, 10)) for (; o--;) d = r("div"), d.id = s ? s[o] : c + (o + 1), p.appendChild(d);return (i = r("style"), i.type = "text/css", i.id = "s" + c, (h.fake ? h : p).appendChild(i), h.appendChild(p), i.styleSheet ? i.styleSheet.cssText = e : i.appendChild(n.createTextNode(e)), p.id = c, h.fake && (h.style.background = "", h.style.overflow = "hidden", f = u.style.overflow, u.style.overflow = "hidden", u.appendChild(h)), a = t(p, e), h.fake ? (h.parentNode.removeChild(h), u.style.overflow = f, u.offsetHeight) : p.parentNode.removeChild(p), !!a);
}var f = [],
c = [],
p = { _version: "3.2.0", _config: { classPrefix: "", enableClasses: !0, enableJSClass: !0, usePrefixes: !0 }, _q: [], on: function on(e, n) {
var t = this;setTimeout(function () {
n(t[e]);
}, 0);
}, addTest: function addTest(e, n, t) {
c.push({ name: e, fn: n, options: t });
}, addAsyncTest: function addAsyncTest(e) {
c.push({ name: null, fn: e });
} },
Modernizr = function Modernizr() {};Modernizr.prototype = p, Modernizr = new Modernizr();var u = n.documentElement,
h = "svg" === u.nodeName.toLowerCase(),
m = p.testStyles = d;m("#modernizr1{width: 50vmax}#modernizr2{width:50px;height:50px;overflow:scroll}#modernizr3{position:fixed;top:0;left:0;bottom:0;right:0}", function (n) {
var t = n.childNodes[2],
o = n.childNodes[1],
s = n.childNodes[0],
i = parseInt((o.offsetWidth - o.clientWidth) / 2, 10),
r = s.clientWidth / 100,
l = s.clientHeight / 100,
d = parseInt(50 * Math.max(r, l), 10),
f = parseInt((e.getComputedStyle ? getComputedStyle(t, null) : t.currentStyle).width, 10);Modernizr.addTest("cssvmaxunit", a(d, f) || a(d, f - i));
}, 3), s(), i(f), delete p.addTest, delete p.addAsyncTest;for (var v = 0; v < Modernizr._q.length; v++) Modernizr._q[v]();e.Modernizr = Modernizr;
})(window, document);
/***/ },
/* 3 */
/***/ function(module, exports, __webpack_require__) {
/* MODALS */
'use strict';
var $ = __webpack_require__(1);
var tooltipster = __webpack_require__(4);
var loader = __webpack_require__(5);
var modal = {
ERROR_CLASS: 'modal--error',
ERROR_MESSAGE_CLASS: 'modal__error-mssg',
VISIBLE_CLASS: 'modal--visible',
LOADING_CLASS: 'modal--loading',
DISABLE_MODAL_NAV_CLASS: 'modal--disable-nav',
DEFAULT_TITLE: 'Untitled',
TYPE_FLASH: 'flash',
TYPE_IMG: 'img',
OFFSET_TOP: 0,
OFFSET_LEFT: 0,
HEADER_HEIGHT: 0,
ANIMATE_IN: 200,
DEFAULT_HEIGHT: 500,
/**
* Loads an image into the DOM to first measure size before inserting into modal window.
*
* @param {object} $trigger
* @param {boolean=} disableModalNav
*/
showImgModal: function showImgModal($trigger, disableModalNav) {
loader.show();
var $img = this.getImg($trigger);
var title = this.getTitle($trigger);
var index = this.getIndex($trigger);
var disableNav = disableModalNav || false;
this.$body.addClass(this.LOADING_CLASS).append($img);
var self = this;
$img.load(function () {
loader.hide();
var $this = $(this);
var height = $this.height() + self.OFFSET_TOP;
var width = $this.width();
if (!disableNav) {
//the offset here is to account for the nav, so only add if needed.
width += self.OFFSET_LEFT;
}
self.$body.toggleClass(self.DISABLE_MODAL_NAV_CLASS, disableNav);
self.$modalBody.animate({
width: width,
height: height
}, self.ANIMATE_IN, function () {
self.$modal.attr('data-index', index);
if (disableNav) {
self.$modal.find('.btn--modal-nav').hide();
} else {
self.$modal.find('.btn--modal-nav').show().height(height - self.HEADER_HEIGHT);
}
self.clearModal();
$this.attr('alt', title).appendTo(self.$modalTarget);
self.$body.removeClass(self.LOADING_CLASS + ' ' + self.ERROR_CLASS);
self.$modalTitle.html(title);
self.show();
});
});
$img.error(self.onImageLoadError.bind(self));
},
/**
* Handle errors loading images.
*/
onImageLoadError: function onImageLoadError() {
loader.hide();
this.clearModal();
this.$modal.find('.btn--modal-nav').height(200);
this.$modalTitle.html('Something went wrong!');
$('<p>').addClass(this.ERROR_MESSAGE_CLASS).text('Error loading image.').appendTo(this.$modalTarget);
this.$body.removeClass(this.LOADING_CLASS).addClass(this.ERROR_CLASS);
this.show();
},
/**
* Clear contents in modal
*/
clearModal: function clearModal() {
this.$modalTitle.html('');
this.$modalTarget.find('img, object, .' + this.ERROR_MESSAGE_CLASS).remove();
},
/**
* Show flash modal.
* @param {object} $trigger
*/
showFlashModal: function showFlashModal($trigger) {
var width = parseInt($trigger.attr('data-flash-width'), 10);
var height = parseInt($trigger.attr('data-flash-height'), 10);
var path = '/swf/' + $trigger.attr('data-flash-name');
var flashHtml = this.getFlashHtml(width, height, path);
var title = this.getTitle($trigger);
var index = this.getIndex($trigger);
var self = this;
this.$modalBody.animate({
width: width + self.OFFSET_LEFT,
height: height + self.OFFSET_TOP
}, self.ANIMATE_IN, function () {
self.$modal.attr('data-index', index);
self.$modal.find('.btn--modal-nav').height(height - 2);
self.$modalTarget.find('img, object').remove();
self.$modalTarget.html(flashHtml);
self.$body.removeClass(self.LOADING_CLASS);
self.$modalTitle.html(title);
self.show();
});
},
/**
* Build html object string for flash items in modals.
*
* @param {number} width
* @param {number} height
* @param {path} path
*
* @return {string}
*/
getFlashHtml: function getFlashHtml(width, height, path) {
var html = '<object width="' + width + '" height="' + height + '">';
html += '<param value="true" name="allowfullscreen">';
html += '<param value="opaque" name="wmode">';
html += '<param value="never" name="allowscriptaccess">';
html += '<param value="' + path + '" name="movie">';
html += '<embed width="' + width + '" height="' + height + '" allowscriptaccess="never" wmode="opaque" allowfullscreen="true" type="application/x-shockwave-flash" src="' + path + '">';
return html;
},
/**
* Create image element for modal
* @param {object} $trigger
* @return {object}
*/
getImg: function getImg($trigger) {
return $('<img />').attr('src', $trigger.attr('data-media-url'));
},
/**
* Builds title for modal
* @param {object} $trigger
* @return string title
*/
getTitle: function getTitle($trigger) {
var title = $trigger.attr('data-title');
return title || this.DEFAULT_TITLE;
},
/**
* Return the item's index
* @param {object} $trigger
* @return {number}
*/
getIndex: function getIndex($trigger) {
return $trigger.attr('data-index');
},
/**
* Show modal
*/
show: function show() {
this.$body.addClass(this.VISIBLE_CLASS);
},
/**
* Hide modal
*/
hide: function hide() {
this.$body.removeClass(this.VISIBLE_CLASS);
},
/**
* Return a valid index so that we can keep looping through all items
* on the page if we hit a boundary at either the first or last item.
*
* @param {number} index - target index
* @return {number} index - adjusted index
*/
getValidIndex: function getValidIndex(index) {
var total = this.$modalMediaThumbs.length - 1;
if (index < 0) {
return total;
}
if (index > total) {
return 0;
}
return index;
},
/**
* Load an item into modal by target index.
* @param {number} targetIndex
*/
loadByIndex: function loadByIndex(targetIndex, modalType) {
targetIndex = this.getValidIndex(targetIndex);
if (this.modalType === this.TYPE_FLASH) {
this.showFlashModal($(this.$modalMediaThumbs[targetIndex]));
} else {
this.showImgModal($(this.$modalMediaThumbs[targetIndex]));
}
},
/**
* Return modal type.
* **Note: only works if all types on page are same. Change/improve if needed,
* however since flash is a one off thing, should be fine.
*
* @return {string}
*/
getModalType: function getModalType() {
if (this.$modalMediaTriggers.attr('data-flash')) {
return this.TYPE_FLASH;
}
return this.TYPE_IMG;
},
/**
* Return current index of item in modal
* @return {number}
*/
getCurrentIndex: function getCurrentIndex() {
return parseInt(this.$modal.attr('data-index'), 10) || 0;
},
/**
*/
bindEventHandlers: function bindEventHandlers() {
var self = this;
self.$modalMediaTriggers.on('click', function (event) {
event.preventDefault();
var $this = $(this);
if ($this.hasClass('tooltipstered')) {
$this.tooltipster('hide');
}
if (self.modalType === self.TYPE_FLASH) {
self.showFlashModal($(event.currentTarget));
} else {
self.showImgModal($(event.currentTarget));
}
});
self.$soloModalMediaTriggers.on('click', function (event) {
event.preventDefault();
self.showImgModal($(event.currentTarget), true);
});
this.$modal.find('.modal__bg').on('click', self.hide.bind(self));
this.$modal.find('.modal__close').on('click', function (event) {
event.preventDefault();
self.hide();
});
this.$modalTarget.on('click', function () {
self.loadByIndex(self.getCurrentIndex() + 1);
});
this.$modal.find('.btn--modal-nav').on('click', function (event) {
event.preventDefault();
var adjustIndex = $(this).attr('data-direction') === 'prev' ? -1 : 1;
self.loadByIndex(self.getCurrentIndex() + adjustIndex);
});
this.$html.on('keydown', 'body.' + self.VISIBLE_CLASS, function (event) {
var keyCode = event.keyCode;
var disableNav = self.$body.hasClass(self.DISABLE_MODAL_NAV_CLASS);
if (keyCode === 39 && !disableNav) {
//right arrow
self.loadByIndex(self.getCurrentIndex() + 1);
} else if (keyCode === 37 && !disableNav) {
//left arrow
self.loadByIndex(self.getCurrentIndex() - 1);
} else if (keyCode === 27) {
//esc
self.hide();
}
});
},
/**
* Adjust sizing slightly of modal based on nav/header element sizing.
* Cache header height which is used in sizing modal properly.
*/
storePositions: function storePositions() {
this.HEADER_HEIGHT = this.$modal.find('.modal__header').outerHeight();
this.OFFSET_LEFT = this.$modal.find('.btn--modal-nav:first').outerWidth() * 2;
this.OFFSET_TOP = this.HEADER_HEIGHT + 20; //TODO: fix this, it's quite right.
},
/**
* Cache some elements and bind event handlers for modals
*/
init: function init() {
this.$modalMediaTriggers = $('.modal-media-trigger');
// solo functions the same as the $modalMediaTrigger except that there's no modal nav.
this.$soloModalMediaTriggers = $('.solo-modal-media-trigger');
this.$modalMediaThumbs = $('.modal-media-thumb').length ? $('.modal-media-thumb') : this.$modalMediaTriggers;
this.$modal = $('.modal');
this.$modalTarget = this.$modal.find('.modal__body-content');
this.$modalBody = this.$modal.find('.modal__content');
this.$modalTitle = this.$modal.find('.modal__title');
this.$body = $('body');
this.$html = $('html');
this.modalType = this.getModalType();
this.storePositions();
this.bindEventHandlers();
}
};
module.exports = modal;
/***/ },
/* 4 */
/***/ function(module, exports, __webpack_require__) {
/*
Tooltipster 3.3.0 | 2014-11-08
A rockin' custom tooltip jQuery plugin
Developed by <NAME> under the MIT license http://opensource.org/licenses/MIT
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
var jQuery;
if (window.jQuery) jQuery = window.jQuery;
else jQuery = __webpack_require__(1);
~function ($, window, document) {
var pluginName = "tooltipster",
defaults = {
animation: 'fade',
arrow: true,
arrowColor: '',
autoClose: true,
content: null,
contentAsHTML: false,
contentCloning: true,
debug: true,
delay: 200,
minWidth: 0,
maxWidth: null,
functionInit: function(origin, content) {},
functionBefore: function(origin, continueTooltip) {
continueTooltip();
},
functionReady: function(origin, tooltip) {},
functionAfter: function(origin) {},
hideOnClick: false,
icon: '(?)',
iconCloning: true,
iconDesktop: false,
iconTouch: false,
iconTheme: 'tooltipster-icon',
interactive: false,
interactiveTolerance: 350,
multiple: false,
offsetX: 0,
offsetY: 0,
onlyOne: false,
position: 'top',
positionTracker: false,
positionTrackerCallback: function(origin){
// the default tracker callback will close the tooltip when the trigger is
// 'hover' (see https://github.com/iamceege/tooltipster/pull/253)
if(this.option('trigger') == 'hover' && this.option('autoClose')) {
this.hide();
}
},
restoration: 'current',
speed: 350,
timer: 0,
theme: 'tooltipster-default',
touchDevices: true,
trigger: 'hover',
updateAnimation: true
};
function Plugin(element, options) {
// list of instance variables
this.bodyOverflowX;
// stack of custom callbacks provided as parameters to API methods
this.callbacks = {
hide: [],
show: []
};
this.checkInterval = null;
// this will be the user content shown in the tooltip. A capital "C" is used because there is also a method called content()
this.Content;
// this is the original element which is being applied the tooltipster plugin
this.$el = $(element);
// this will be the element which triggers the appearance of the tooltip on hover/click/custom events.
// it will be the same as this.$el if icons are not used (see in the options), otherwise it will correspond to the created icon
this.$elProxy;
this.elProxyPosition;
this.enabled = true;
this.options = $.extend({}, defaults, options);
this.mouseIsOverProxy = false;
// a unique namespace per instance, for easy selective unbinding
this.namespace = 'tooltipster-'+ Math.round(Math.random()*100000);
// Status (capital S) can be either : appearing, shown, disappearing, hidden
this.Status = 'hidden';
this.timerHide = null;
this.timerShow = null;
// this will be the tooltip element (jQuery wrapped HTML element)
this.$tooltip;
// for backward compatibility
this.options.iconTheme = this.options.iconTheme.replace('.', '');
this.options.theme = this.options.theme.replace('.', '');
// launch
this._init();
}
Plugin.prototype = {
_init: function() {
var self = this;
// disable the plugin on old browsers (including IE7 and lower)
if (document.querySelector) {
// note : the content is null (empty) by default and can stay that way if the plugin remains initialized but not fed any content. The tooltip will just not appear.
// let's save the initial value of the title attribute for later restoration if need be.
var initialTitle = null;
// it will already have been saved in case of multiple tooltips
if (self.$el.data('tooltipster-initialTitle') === undefined) {
initialTitle = self.$el.attr('title');
// we do not want initialTitle to have the value "undefined" because of how jQuery's .data() method works
if (initialTitle === undefined) initialTitle = null;
self.$el.data('tooltipster-initialTitle', initialTitle);
}
// if content is provided in the options, its has precedence over the title attribute.
// Note : an empty string is considered content, only 'null' represents the absence of content.
// Also, an existing title="" attribute will result in an empty string content
if (self.options.content !== null){
self._content_set(self.options.content);
}
else {
self._content_set(initialTitle);
}
var c = self.options.functionInit.call(self.$el, self.$el, self.Content);
if(typeof c !== 'undefined') self._content_set(c);
self.$el
// strip the title off of the element to prevent the default tooltips from popping up
.removeAttr('title')
// to be able to find all instances on the page later (upon window events in particular)
.addClass('tooltipstered');
// detect if we're changing the tooltip origin to an icon
// note about this condition : if the device has touch capability and self.options.iconTouch is false, you'll have no icons event though you may consider your device as a desktop if it also has a mouse. Not sure why someone would have this use case though.
if ((!deviceHasTouchCapability && self.options.iconDesktop) || (deviceHasTouchCapability && self.options.iconTouch)) {
// TODO : the tooltip should be automatically be given an absolute position to be near the origin. Otherwise, when the origin is floating or what, it's going to be nowhere near it and disturb the position flow of the page elements. It will imply that the icon also detects when its origin moves, to follow it : not trivial.
// Until it's done, the icon feature does not really make sense since the user still has most of the work to do by himself
// if the icon provided is in the form of a string
if(typeof self.options.icon === 'string'){
// wrap it in a span with the icon class
self.$elProxy = $('<span class="'+ self.options.iconTheme +'"></span>');
self.$elProxy.text(self.options.icon);
}
// if it is an object (sensible choice)
else {
// (deep) clone the object if iconCloning == true, to make sure every instance has its own proxy. We use the icon without wrapping, no need to. We do not give it a class either, as the user will undoubtedly style the object on his own and since our css properties may conflict with his own
if (self.options.iconCloning) self.$elProxy = self.options.icon.clone(true);
else self.$elProxy = self.options.icon;
}
self.$elProxy.insertAfter(self.$el);
}
else {
self.$elProxy = self.$el;
}
// for 'click' and 'hover' triggers : bind on events to open the tooltip. Closing is now handled in _showNow() because of its bindings.
// Notes about touch events :
// - mouseenter, mouseleave and clicks happen even on pure touch devices because they are emulated. deviceIsPureTouch() is a simple attempt to detect them.
// - on hybrid devices, we do not prevent touch gesture from opening tooltips. It would be too complex to differentiate real mouse events from emulated ones.
// - we check deviceIsPureTouch() at each event rather than prior to binding because the situation may change during browsing
if (self.options.trigger == 'hover') {
// these binding are for mouse interaction only
self.$elProxy
.on('mouseenter.'+ self.namespace, function() {
if (!deviceIsPureTouch() || self.options.touchDevices) {
self.mouseIsOverProxy = true;
self._show();
}
})
.on('mouseleave.'+ self.namespace, function() {
if (!deviceIsPureTouch() || self.options.touchDevices) {
self.mouseIsOverProxy = false;
}
});
// for touch interaction only
if (deviceHasTouchCapability && self.options.touchDevices) {
// for touch devices, we immediately display the tooltip because we cannot rely on mouseleave to handle the delay
self.$elProxy.on('touchstart.'+ self.namespace, function() {
self._showNow();
});
}
}
else if (self.options.trigger == 'click') {
// note : for touch devices, we do not bind on touchstart, we only rely on the emulated clicks (triggered by taps)
self.$elProxy.on('click.'+ self.namespace, function() {
if (!deviceIsPureTouch() || self.options.touchDevices) {
self._show();
}
});
}
}
},
// this function will schedule the opening of the tooltip after the delay, if there is one
_show: function() {
var self = this;
if (self.Status != 'shown' && self.Status != 'appearing') {
if (self.options.delay) {
self.timerShow = setTimeout(function(){
// for hover trigger, we check if the mouse is still over the proxy, otherwise we do not show anything
if (self.options.trigger == 'click' || (self.options.trigger == 'hover' && self.mouseIsOverProxy)) {
self._showNow();
}
}, self.options.delay);
}
else self._showNow();
}
},
// this function will open the tooltip right away
_showNow: function(callback) {
var self = this;
// call our constructor custom function before continuing
self.options.functionBefore.call(self.$el, self.$el, function() {
// continue only if the tooltip is enabled and has any content
if (self.enabled && self.Content !== null) {
// save the method callback and cancel hide method callbacks
if (callback) self.callbacks.show.push(callback);
self.callbacks.hide = [];
//get rid of any appearance timer
clearTimeout(self.timerShow);
self.timerShow = null;
clearTimeout(self.timerHide);
self.timerHide = null;
// if we only want one tooltip open at a time, close all auto-closing tooltips currently open and not already disappearing
if (self.options.onlyOne) {
$('.tooltipstered').not(self.$el).each(function(i,el) {
var $el = $(el),
nss = $el.data('tooltipster-ns');
// iterate on all tooltips of the element
$.each(nss, function(i, ns){
var instance = $el.data(ns),
// we have to use the public methods here
s = instance.status(),
ac = instance.option('autoClose');
if (s !== 'hidden' && s !== 'disappearing' && ac) {
instance.hide();
}
});
});
}
var finish = function() {
self.Status = 'shown';
// trigger any show method custom callbacks and reset them
$.each(self.callbacks.show, function(i,c) { c.call(self.$el); });
self.callbacks.show = [];
};
// if this origin already has its tooltip open
if (self.Status !== 'hidden') {
// the timer (if any) will start (or restart) right now
var extraTime = 0;
// if it was disappearing, cancel that
if (self.Status === 'disappearing') {
self.Status = 'appearing';
if (supportsTransitions()) {
self.$tooltip
.clearQueue()
.removeClass('tooltipster-dying')
.addClass('tooltipster-'+ self.options.animation +'-show');
if (self.options.speed > 0) self.$tooltip.delay(self.options.speed);
self.$tooltip.queue(finish);
}
else {
// in case the tooltip was currently fading out, bring it back to life
self.$tooltip
.stop()
.fadeIn(finish);
}
}
// if the tooltip is already open, we still need to trigger the method custom callback
else if(self.Status === 'shown') {
finish();
}
}
// if the tooltip isn't already open, open that sucker up!
else {
self.Status = 'appearing';
// the timer (if any) will start when the tooltip has fully appeared after its transition
var extraTime = self.options.speed;
// disable horizontal scrollbar to keep overflowing tooltips from jacking with it and then restore it to its previous value
self.bodyOverflowX = $('body').css('overflow-x');
$('body').css('overflow-x', 'hidden');
// get some other settings related to building the tooltip
var animation = 'tooltipster-' + self.options.animation,
animationSpeed = '-webkit-transition-duration: '+ self.options.speed +'ms; -webkit-animation-duration: '+ self.options.speed +'ms; -moz-transition-duration: '+ self.options.speed +'ms; -moz-animation-duration: '+ self.options.speed +'ms; -o-transition-duration: '+ self.options.speed +'ms; -o-animation-duration: '+ self.options.speed +'ms; -ms-transition-duration: '+ self.options.speed +'ms; -ms-animation-duration: '+ self.options.speed +'ms; transition-duration: '+ self.options.speed +'ms; animation-duration: '+ self.options.speed +'ms;',
minWidth = self.options.minWidth ? 'min-width:'+ Math.round(self.options.minWidth) +'px;' : '',
maxWidth = self.options.maxWidth ? 'max-width:'+ Math.round(self.options.maxWidth) +'px;' : '',
pointerEvents = self.options.interactive ? 'pointer-events: auto;' : '';
// build the base of our tooltip
self.$tooltip = $('<div class="tooltipster-base '+ self.options.theme +'" style="'+ minWidth +' '+ maxWidth +' '+ pointerEvents +' '+ animationSpeed +'"><div class="tooltipster-content"></div></div>');
// only add the animation class if the user has a browser that supports animations
if (supportsTransitions()) self.$tooltip.addClass(animation);
// insert the content
self._content_insert();
// attach
self.$tooltip.appendTo('body');
// do all the crazy calculations and positioning
self.reposition();
// call our custom callback since the content of the tooltip is now part of the DOM
self.options.functionReady.call(self.$el, self.$el, self.$tooltip);
// animate in the tooltip
if (supportsTransitions()) {
self.$tooltip.addClass(animation + '-show');
if(self.options.speed > 0) self.$tooltip.delay(self.options.speed);
self.$tooltip.queue(finish);
}
else {
self.$tooltip.css('display', 'none').fadeIn(self.options.speed, finish);
}
// will check if our tooltip origin is removed while the tooltip is shown
self._interval_set();
// reposition on scroll (otherwise position:fixed element's tooltips will move away form their origin) and on resize (in case position can/has to be changed)
$(window).on('scroll.'+ self.namespace +' resize.'+ self.namespace, function() {
self.reposition();
});
// auto-close bindings
if (self.options.autoClose) {
// in case a listener is already bound for autoclosing (mouse or touch, hover or click), unbind it first
$('body').off('.'+ self.namespace);
// here we'll have to set different sets of bindings for both touch and mouse
if (self.options.trigger == 'hover') {
// if the user touches the body, hide
if (deviceHasTouchCapability) {
// timeout 0 : explanation below in click section
setTimeout(function() {
// we don't want to bind on click here because the initial touchstart event has not yet triggered its click event, which is thus about to happen
$('body').on('touchstart.'+ self.namespace, function() {
self.hide();
});
}, 0);
}
// if we have to allow interaction
if (self.options.interactive) {
// touch events inside the tooltip must not close it
if (deviceHasTouchCapability) {
self.$tooltip.on('touchstart.'+ self.namespace, function(event) {
event.stopPropagation();
});
}
// as for mouse interaction, we get rid of the tooltip only after the mouse has spent some time out of it
var tolerance = null;
self.$elProxy.add(self.$tooltip)
// hide after some time out of the proxy and the tooltip
.on('mouseleave.'+ self.namespace + '-autoClose', function() {
clearTimeout(tolerance);
tolerance = setTimeout(function(){
self.hide();
}, self.options.interactiveTolerance);
})
// suspend timeout when the mouse is over the proxy or the tooltip
.on('mouseenter.'+ self.namespace + '-autoClose', function() {
clearTimeout(tolerance);
});
}
// if this is a non-interactive tooltip, get rid of it if the mouse leaves
else {
self.$elProxy.on('mouseleave.'+ self.namespace + '-autoClose', function() {
self.hide();
});
}
// close the tooltip when the proxy gets a click (common behavior of native tooltips)
if (self.options.hideOnClick) {
self.$elProxy.on('click.'+ self.namespace + '-autoClose', function() {
self.hide();
});
}
}
// here we'll set the same bindings for both clicks and touch on the body to hide the tooltip
else if(self.options.trigger == 'click'){
// use a timeout to prevent immediate closing if the method was called on a click event and if options.delay == 0 (because of bubbling)
setTimeout(function() {
$('body').on('click.'+ self.namespace +' touchstart.'+ self.namespace, function() {
self.hide();
});
}, 0);
// if interactive, we'll stop the events that were emitted from inside the tooltip to stop autoClosing
if (self.options.interactive) {
// note : the touch events will just not be used if the plugin is not enabled on touch devices
self.$tooltip.on('click.'+ self.namespace +' touchstart.'+ self.namespace, function(event) {
event.stopPropagation();
});
}
}
}
}
// if we have a timer set, let the countdown begin
if (self.options.timer > 0) {
self.timerHide = setTimeout(function() {
self.timerHide = null;
self.hide();
}, self.options.timer + extraTime);
}
}
});
},
_interval_set: function() {
var self = this;
self.checkInterval = setInterval(function() {
// if the tooltip and/or its interval should be stopped
if (
// if the origin has been removed
$('body').find(self.$el).length === 0
// if the elProxy has been removed
|| $('body').find(self.$elProxy).length === 0
// if the tooltip has been closed
|| self.Status == 'hidden'
// if the tooltip has somehow been removed
|| $('body').find(self.$tooltip).length === 0
) {
// remove the tooltip if it's still here
if (self.Status == 'shown' || self.Status == 'appearing') self.hide();
// clear this interval as it is no longer necessary
self._interval_cancel();
}
// if everything is alright
else {
// compare the former and current positions of the elProxy to reposition the tooltip if need be
if(self.options.positionTracker){
var p = self._repositionInfo(self.$elProxy),
identical = false;
// compare size first (a change requires repositioning too)
if(areEqual(p.dimension, self.elProxyPosition.dimension)){
// for elements with a fixed position, we track the top and left properties (relative to window)
if(self.$elProxy.css('position') === 'fixed'){
if(areEqual(p.position, self.elProxyPosition.position)) identical = true;
}
// otherwise, track total offset (relative to document)
else {
if(areEqual(p.offset, self.elProxyPosition.offset)) identical = true;
}
}
if(!identical){
self.reposition();
self.options.positionTrackerCallback.call(self, self.$el);
}
}
}
}, 200);
},
_interval_cancel: function() {
clearInterval(this.checkInterval);
// clean delete
this.checkInterval = null;
},
_content_set: function(content) {
// clone if asked. Cloning the object makes sure that each instance has its own version of the content (in case a same object were provided for several instances)
// reminder : typeof null === object
if (typeof content === 'object' && content !== null && this.options.contentCloning) {
content = content.clone(true);
}
this.Content = content;
},
_content_insert: function() {
var self = this,
$d = this.$tooltip.find('.tooltipster-content');
if (typeof self.Content === 'string' && !self.options.contentAsHTML) {
$d.text(self.Content);
}
else {
$d
.empty()
.append(self.Content);
}
},
_update: function(content) {
var self = this;
// change the content
self._content_set(content);
if (self.Content !== null) {
// update the tooltip if it is open
if (self.Status !== 'hidden') {
// reset the content in the tooltip
self._content_insert();
// reposition and resize the tooltip
self.reposition();
// if we want to play a little animation showing the content changed
if (self.options.updateAnimation) {
if (supportsTransitions()) {
self.$tooltip.css({
'width': '',
'-webkit-transition': 'all ' + self.options.speed + 'ms, width 0ms, height 0ms, left 0ms, top 0ms',
'-moz-transition': 'all ' + self.options.speed + 'ms, width 0ms, height 0ms, left 0ms, top 0ms',
'-o-transition': 'all ' + self.options.speed + 'ms, width 0ms, height 0ms, left 0ms, top 0ms',
'-ms-transition': 'all ' + self.options.speed + 'ms, width 0ms, height 0ms, left 0ms, top 0ms',
'transition': 'all ' + self.options.speed + 'ms, width 0ms, height 0ms, left 0ms, top 0ms'
}).addClass('tooltipster-content-changing');
// reset the CSS transitions and finish the change animation
setTimeout(function() {
if(self.Status != 'hidden'){
self.$tooltip.removeClass('tooltipster-content-changing');
// after the changing animation has completed, reset the CSS transitions
setTimeout(function() {
if(self.Status !== 'hidden'){
self.$tooltip.css({
'-webkit-transition': self.options.speed + 'ms',
'-moz-transition': self.options.speed + 'ms',
'-o-transition': self.options.speed + 'ms',
'-ms-transition': self.options.speed + 'ms',
'transition': self.options.speed + 'ms'
});
}
}, self.options.speed);
}
}, self.options.speed);
}
else {
self.$tooltip.fadeTo(self.options.speed, 0.5, function() {
if(self.Status != 'hidden'){
self.$tooltip.fadeTo(self.options.speed, 1);
}
});
}
}
}
}
else {
self.hide();
}
},
_repositionInfo: function($el) {
return {
dimension: {
height: $el.outerHeight(false),
width: $el.outerWidth(false)
},
offset: $el.offset(),
position: {
left: parseInt($el.css('left')),
top: parseInt($el.css('top'))
}
};
},
hide: function(callback) {
var self = this;
// save the method custom callback and cancel any show method custom callbacks
if (callback) self.callbacks.hide.push(callback);
self.callbacks.show = [];
// get rid of any appearance timeout
clearTimeout(self.timerShow);
self.timerShow = null;
clearTimeout(self.timerHide);
self.timerHide = null;
var finishCallbacks = function() {
// trigger any hide method custom callbacks and reset them
$.each(self.callbacks.hide, function(i,c) { c.call(self.$el); });
self.callbacks.hide = [];
};
// hide
if (self.Status == 'shown' || self.Status == 'appearing') {
self.Status = 'disappearing';
var finish = function() {
self.Status = 'hidden';
// detach our content object first, so the next jQuery's remove() call does not unbind its event handlers
if (typeof self.Content == 'object' && self.Content !== null) {
self.Content.detach();
}
self.$tooltip.remove();
self.$tooltip = null;
// unbind orientationchange, scroll and resize listeners
$(window).off('.'+ self.namespace);
$('body')
// unbind any auto-closing click/touch listeners
.off('.'+ self.namespace)
.css('overflow-x', self.bodyOverflowX);
// unbind any auto-closing click/touch listeners
$('body').off('.'+ self.namespace);
// unbind any auto-closing hover listeners
self.$elProxy.off('.'+ self.namespace + '-autoClose');
// call our constructor custom callback function
self.options.functionAfter.call(self.$el, self.$el);
// call our method custom callbacks functions
finishCallbacks();
};
if (supportsTransitions()) {
self.$tooltip
.clearQueue()
.removeClass('tooltipster-' + self.options.animation + '-show')
// for transitions only
.addClass('tooltipster-dying');
if(self.options.speed > 0) self.$tooltip.delay(self.options.speed);
self.$tooltip.queue(finish);
}
else {
self.$tooltip
.stop()
.fadeOut(self.options.speed, finish);
}
}
// if the tooltip is already hidden, we still need to trigger the method custom callback
else if(self.Status == 'hidden') {
finishCallbacks();
}
return self;
},
// the public show() method is actually an alias for the private showNow() method
show: function(callback) {
this._showNow(callback);
return this;
},
// 'update' is deprecated in favor of 'content' but is kept for backward compatibility
update: function(c) {
return this.content(c);
},
content: function(c) {
// getter method
if(typeof c === 'undefined'){
return this.Content;
}
// setter method
else {
this._update(c);
return this;
}
},
reposition: function() {
var self = this;
// in case the tooltip has been removed from DOM manually
if ($('body').find(self.$tooltip).length !== 0) {
// reset width
self.$tooltip.css('width', '');
// find variables to determine placement
self.elProxyPosition = self._repositionInfo(self.$elProxy);
var arrowReposition = null,
windowWidth = $(window).width(),
// shorthand
proxy = self.elProxyPosition,
tooltipWidth = self.$tooltip.outerWidth(false),
tooltipInnerWidth = self.$tooltip.innerWidth() + 1, // this +1 stops FireFox from sometimes forcing an additional text line
tooltipHeight = self.$tooltip.outerHeight(false);
// if this is an <area> tag inside a <map>, all hell breaks loose. Recalculate all the measurements based on coordinates
if (self.$elProxy.is('area')) {
var areaShape = self.$elProxy.attr('shape'),
mapName = self.$elProxy.parent().attr('name'),
map = $('img[usemap="#'+ mapName +'"]'),
mapOffsetLeft = map.offset().left,
mapOffsetTop = map.offset().top,
areaMeasurements = self.$elProxy.attr('coords') !== undefined ? self.$elProxy.attr('coords').split(',') : undefined;
if (areaShape == 'circle') {
var areaLeft = parseInt(areaMeasurements[0]),
areaTop = parseInt(areaMeasurements[1]),
areaWidth = parseInt(areaMeasurements[2]);
proxy.dimension.height = areaWidth * 2;
proxy.dimension.width = areaWidth * 2;
proxy.offset.top = mapOffsetTop + areaTop - areaWidth;
proxy.offset.left = mapOffsetLeft + areaLeft - areaWidth;
}
else if (areaShape == 'rect') {
var areaLeft = parseInt(areaMeasurements[0]),
areaTop = parseInt(areaMeasurements[1]),
areaRight = parseInt(areaMeasurements[2]),
areaBottom = parseInt(areaMeasurements[3]);
proxy.dimension.height = areaBottom - areaTop;
proxy.dimension.width = areaRight - areaLeft;
proxy.offset.top = mapOffsetTop + areaTop;
proxy.offset.left = mapOffsetLeft + areaLeft;
}
else if (areaShape == 'poly') {
var areaXs = [],
areaYs = [],
areaSmallestX = 0,
areaSmallestY = 0,
areaGreatestX = 0,
areaGreatestY = 0,
arrayAlternate = 'even';
for (var i = 0; i < areaMeasurements.length; i++) {
var areaNumber = parseInt(areaMeasurements[i]);
if (arrayAlternate == 'even') {
if (areaNumber > areaGreatestX) {
areaGreatestX = areaNumber;
if (i === 0) {
areaSmallestX = areaGreatestX;
}
}
if (areaNumber < areaSmallestX) {
areaSmallestX = areaNumber;
}
arrayAlternate = 'odd';
}
else {
if (areaNumber > areaGreatestY) {
areaGreatestY = areaNumber;
if (i == 1) {
areaSmallestY = areaGreatestY;
}
}
if (areaNumber < areaSmallestY) {
areaSmallestY = areaNumber;
}
arrayAlternate = 'even';
}
}
proxy.dimension.height = areaGreatestY - areaSmallestY;
proxy.dimension.width = areaGreatestX - areaSmallestX;
proxy.offset.top = mapOffsetTop + areaSmallestY;
proxy.offset.left = mapOffsetLeft + areaSmallestX;
}
else {
proxy.dimension.height = map.outerHeight(false);
proxy.dimension.width = map.outerWidth(false);
proxy.offset.top = mapOffsetTop;
proxy.offset.left = mapOffsetLeft;
}
}
// our function and global vars for positioning our tooltip
var myLeft = 0,
myLeftMirror = 0,
myTop = 0,
offsetY = parseInt(self.options.offsetY),
offsetX = parseInt(self.options.offsetX),
// this is the arrow position that will eventually be used. It may differ from the position option if the tooltip cannot be displayed in this position
practicalPosition = self.options.position;
// a function to detect if the tooltip is going off the screen horizontally. If so, reposition the crap out of it!
function dontGoOffScreenX() {
var windowLeft = $(window).scrollLeft();
// if the tooltip goes off the left side of the screen, line it up with the left side of the window
if((myLeft - windowLeft) < 0) {
arrowReposition = myLeft - windowLeft;
myLeft = windowLeft;
}
// if the tooltip goes off the right of the screen, line it up with the right side of the window
if (((myLeft + tooltipWidth) - windowLeft) > windowWidth) {
arrowReposition = myLeft - ((windowWidth + windowLeft) - tooltipWidth);
myLeft = (windowWidth + windowLeft) - tooltipWidth;
}
}
// a function to detect if the tooltip is going off the screen vertically. If so, switch to the opposite!
function dontGoOffScreenY(switchTo, switchFrom) {
// if it goes off the top off the page
if(((proxy.offset.top - $(window).scrollTop() - tooltipHeight - offsetY - 12) < 0) && (switchFrom.indexOf('top') > -1)) {
practicalPosition = switchTo;
}
// if it goes off the bottom of the page
if (((proxy.offset.top + proxy.dimension.height + tooltipHeight + 12 + offsetY) > ($(window).scrollTop() + $(window).height())) && (switchFrom.indexOf('bottom') > -1)) {
practicalPosition = switchTo;
myTop = (proxy.offset.top - tooltipHeight) - offsetY - 12;
}
}
if(practicalPosition == 'top') {
var leftDifference = (proxy.offset.left + tooltipWidth) - (proxy.offset.left + proxy.dimension.width);
myLeft = (proxy.offset.left + offsetX) - (leftDifference / 2);
myTop = (proxy.offset.top - tooltipHeight) - offsetY - 12;
dontGoOffScreenX();
dontGoOffScreenY('bottom', 'top');
}
if(practicalPosition == 'top-left') {
myLeft = proxy.offset.left + offsetX;
myTop = (proxy.offset.top - tooltipHeight) - offsetY - 12;
dontGoOffScreenX();
dontGoOffScreenY('bottom-left', 'top-left');
}
if(practicalPosition == 'top-right') {
myLeft = (proxy.offset.left + proxy.dimension.width + offsetX) - tooltipWidth;
myTop = (proxy.offset.top - tooltipHeight) - offsetY - 12;
dontGoOffScreenX();
dontGoOffScreenY('bottom-right', 'top-right');
}
if(practicalPosition == 'bottom') {
var leftDifference = (proxy.offset.left + tooltipWidth) - (proxy.offset.left + proxy.dimension.width);
myLeft = proxy.offset.left - (leftDifference / 2) + offsetX;
myTop = (proxy.offset.top + proxy.dimension.height) + offsetY + 12;
dontGoOffScreenX();
dontGoOffScreenY('top', 'bottom');
}
if(practicalPosition == 'bottom-left') {
myLeft = proxy.offset.left + offsetX;
myTop = (proxy.offset.top + proxy.dimension.height) + offsetY + 12;
dontGoOffScreenX();
dontGoOffScreenY('top-left', 'bottom-left');
}
if(practicalPosition == 'bottom-right') {
myLeft = (proxy.offset.left + proxy.dimension.width + offsetX) - tooltipWidth;
myTop = (proxy.offset.top + proxy.dimension.height) + offsetY + 12;
dontGoOffScreenX();
dontGoOffScreenY('top-right', 'bottom-right');
}
if(practicalPosition == 'left') {
myLeft = proxy.offset.left - offsetX - tooltipWidth - 12;
myLeftMirror = proxy.offset.left + offsetX + proxy.dimension.width + 12;
var topDifference = (proxy.offset.top + tooltipHeight) - (proxy.offset.top + proxy.dimension.height);
myTop = proxy.offset.top - (topDifference / 2) - offsetY;
// if the tooltip goes off boths sides of the page
if((myLeft < 0) && ((myLeftMirror + tooltipWidth) > windowWidth)) {
var borderWidth = parseFloat(self.$tooltip.css('border-width')) * 2,
newWidth = (tooltipWidth + myLeft) - borderWidth;
self.$tooltip.css('width', newWidth + 'px');
tooltipHeight = self.$tooltip.outerHeight(false);
myLeft = proxy.offset.left - offsetX - newWidth - 12 - borderWidth;
topDifference = (proxy.offset.top + tooltipHeight) - (proxy.offset.top + proxy.dimension.height);
myTop = proxy.offset.top - (topDifference / 2) - offsetY;
}
// if it only goes off one side, flip it to the other side
else if(myLeft < 0) {
myLeft = proxy.offset.left + offsetX + proxy.dimension.width + 12;
arrowReposition = 'left';
}
}
if(practicalPosition == 'right') {
myLeft = proxy.offset.left + offsetX + proxy.dimension.width + 12;
myLeftMirror = proxy.offset.left - offsetX - tooltipWidth - 12;
var topDifference = (proxy.offset.top + tooltipHeight) - (proxy.offset.top + proxy.dimension.height);
myTop = proxy.offset.top - (topDifference / 2) - offsetY;
// if the tooltip goes off boths sides of the page
if(((myLeft + tooltipWidth) > windowWidth) && (myLeftMirror < 0)) {
var borderWidth = parseFloat(self.$tooltip.css('border-width')) * 2,
newWidth = (windowWidth - myLeft) - borderWidth;
self.$tooltip.css('width', newWidth + 'px');
tooltipHeight = self.$tooltip.outerHeight(false);
topDifference = (proxy.offset.top + tooltipHeight) - (proxy.offset.top + proxy.dimension.height);
myTop = proxy.offset.top - (topDifference / 2) - offsetY;
}
// if it only goes off one side, flip it to the other side
else if((myLeft + tooltipWidth) > windowWidth) {
myLeft = proxy.offset.left - offsetX - tooltipWidth - 12;
arrowReposition = 'right';
}
}
// if arrow is set true, style it and append it
if (self.options.arrow) {
var arrowClass = 'tooltipster-arrow-' + practicalPosition;
// set color of the arrow
if(self.options.arrowColor.length < 1) {
var arrowColor = self.$tooltip.css('background-color');
}
else {
var arrowColor = self.options.arrowColor;
}
// if the tooltip was going off the page and had to re-adjust, we need to update the arrow's position
if (!arrowReposition) {
arrowReposition = '';
}
else if (arrowReposition == 'left') {
arrowClass = 'tooltipster-arrow-right';
arrowReposition = '';
}
else if (arrowReposition == 'right') {
arrowClass = 'tooltipster-arrow-left';
arrowReposition = '';
}
else {
arrowReposition = 'left:'+ Math.round(arrowReposition) +'px;';
}
// building the logic to create the border around the arrow of the tooltip
if ((practicalPosition == 'top') || (practicalPosition == 'top-left') || (practicalPosition == 'top-right')) {
var tooltipBorderWidth = parseFloat(self.$tooltip.css('border-bottom-width')),
tooltipBorderColor = self.$tooltip.css('border-bottom-color');
}
else if ((practicalPosition == 'bottom') || (practicalPosition == 'bottom-left') || (practicalPosition == 'bottom-right')) {
var tooltipBorderWidth = parseFloat(self.$tooltip.css('border-top-width')),
tooltipBorderColor = self.$tooltip.css('border-top-color');
}
else if (practicalPosition == 'left') {
var tooltipBorderWidth = parseFloat(self.$tooltip.css('border-right-width')),
tooltipBorderColor = self.$tooltip.css('border-right-color');
}
else if (practicalPosition == 'right') {
var tooltipBorderWidth = parseFloat(self.$tooltip.css('border-left-width')),
tooltipBorderColor = self.$tooltip.css('border-left-color');
}
else {
var tooltipBorderWidth = parseFloat(self.$tooltip.css('border-bottom-width')),
tooltipBorderColor = self.$tooltip.css('border-bottom-color');
}
if (tooltipBorderWidth > 1) {
tooltipBorderWidth++;
}
var arrowBorder = '';
if (tooltipBorderWidth !== 0) {
var arrowBorderSize = '',
arrowBorderColor = 'border-color: '+ tooltipBorderColor +';';
if (arrowClass.indexOf('bottom') !== -1) {
arrowBorderSize = 'margin-top: -'+ Math.round(tooltipBorderWidth) +'px;';
}
else if (arrowClass.indexOf('top') !== -1) {
arrowBorderSize = 'margin-bottom: -'+ Math.round(tooltipBorderWidth) +'px;';
}
else if (arrowClass.indexOf('left') !== -1) {
arrowBorderSize = 'margin-right: -'+ Math.round(tooltipBorderWidth) +'px;';
}
else if (arrowClass.indexOf('right') !== -1) {
arrowBorderSize = 'margin-left: -'+ Math.round(tooltipBorderWidth) +'px;';
}
arrowBorder = '<span class="tooltipster-arrow-border" style="'+ arrowBorderSize +' '+ arrowBorderColor +';"></span>';
}
// if the arrow already exists, remove and replace it
self.$tooltip.find('.tooltipster-arrow').remove();
// build out the arrow and append it
var arrowConstruct = '<div class="'+ arrowClass +' tooltipster-arrow" style="'+ arrowReposition +'">'+ arrowBorder +'<span style="border-color:'+ arrowColor +';"></span></div>';
self.$tooltip.append(arrowConstruct);
}
// position the tooltip
self.$tooltip.css({'top': Math.round(myTop) + 'px', 'left': Math.round(myLeft) + 'px'});
}
return self;
},
enable: function() {
this.enabled = true;
return this;
},
disable: function() {
// hide first, in case the tooltip would not disappear on its own (autoClose false)
this.hide();
this.enabled = false;
return this;
},
destroy: function() {
var self = this;
self.hide();
// remove the icon, if any
if (self.$el[0] !== self.$elProxy[0]) {
self.$elProxy.remove();
}
self.$el
.removeData(self.namespace)
.off('.'+ self.namespace);
var ns = self.$el.data('tooltipster-ns');
// if there are no more tooltips on this element
if(ns.length === 1){
// optional restoration of a title attribute
var title = null;
if (self.options.restoration === 'previous'){
title = self.$el.data('tooltipster-initialTitle');
}
else if(self.options.restoration === 'current'){
// old school technique to stringify when outerHTML is not supported
title =
(typeof self.Content === 'string') ?
self.Content :
$('<div></div>').append(self.Content).html();
}
if (title) {
self.$el.attr('title', title);
}
// final cleaning
self.$el
.removeClass('tooltipstered')
.removeData('tooltipster-ns')
.removeData('tooltipster-initialTitle');
}
else {
// remove the instance namespace from the list of namespaces of tooltips present on the element
ns = $.grep(ns, function(el, i){
return el !== self.namespace;
});
self.$el.data('tooltipster-ns', ns);
}
return self;
},
elementIcon: function() {
return (this.$el[0] !== this.$elProxy[0]) ? this.$elProxy[0] : undefined;
},
elementTooltip: function() {
return this.$tooltip ? this.$tooltip[0] : undefined;
},
// public methods but for internal use only
// getter if val is ommitted, setter otherwise
option: function(o, val) {
if (typeof val == 'undefined') return this.options[o];
else {
this.options[o] = val;
return this;
}
},
status: function() {
return this.Status;
}
};
$.fn[pluginName] = function () {
// for using in closures
var args = arguments;
// if we are not in the context of jQuery wrapped HTML element(s) :
// this happens when calling static methods in the form $.fn.tooltipster('methodName'), or when calling $(sel).tooltipster('methodName or options') where $(sel) does not match anything
if (this.length === 0) {
// if the first argument is a method name
if (typeof args[0] === 'string') {
var methodIsStatic = true;
// list static methods here (usable by calling $.fn.tooltipster('methodName');)
switch (args[0]) {
case 'setDefaults':
// change default options for all future instances
$.extend(defaults, args[1]);
break;
default:
methodIsStatic = false;
break;
}
// $.fn.tooltipster('methodName') calls will return true
if (methodIsStatic) return true;
// $(sel).tooltipster('methodName') calls will return the list of objects event though it's empty because chaining should work on empty lists
else return this;
}
// the first argument is undefined or an object of options : we are initalizing but there is no element matched by selector
else {
// still chainable : same as above
return this;
}
}
// this happens when calling $(sel).tooltipster('methodName or options') where $(sel) matches one or more elements
else {
// method calls
if (typeof args[0] === 'string') {
var v = '#*$~&';
this.each(function() {
// retrieve the namepaces of the tooltip(s) that exist on that element. We will interact with the first tooltip only.
var ns = $(this).data('tooltipster-ns'),
// self represents the instance of the first tooltipster plugin associated to the current HTML object of the loop
self = ns ? $(this).data(ns[0]) : null;
// if the current element holds a tooltipster instance
if (self) {
if (typeof self[args[0]] === 'function') {
// note : args[1] and args[2] may not be defined
var resp = self[args[0]](args[1], args[2]);
}
else {
throw new Error('Unknown method .tooltipster("' + args[0] + '")');
}
// if the function returned anything other than the instance itself (which implies chaining)
if (resp !== self){
v = resp;
// return false to stop .each iteration on the first element matched by the selector
return false;
}
}
else {
throw new Error('You called Tooltipster\'s "' + args[0] + '" method on an uninitialized element');
}
});
return (v !== '#*$~&') ? v : this;
}
// first argument is undefined or an object : the tooltip is initializing
else {
var instances = [],
// is there a defined value for the multiple option in the options object ?
multipleIsSet = args[0] && typeof args[0].multiple !== 'undefined',
// if the multiple option is set to true, or if it's not defined but set to true in the defaults
multiple = (multipleIsSet && args[0].multiple) || (!multipleIsSet && defaults.multiple),
// same for debug
debugIsSet = args[0] && typeof args[0].debug !== 'undefined',
debug = (debugIsSet && args[0].debug) || (!debugIsSet && defaults.debug);
// initialize a tooltipster instance for each element if it doesn't already have one or if the multiple option is set, and attach the object to it
this.each(function () {
var go = false,
ns = $(this).data('tooltipster-ns'),
instance = null;
if (!ns) {
go = true;
}
else if (multiple) {
go = true;
}
else if (debug) {
console.log('Tooltipster: one or more tooltips are already attached to this element: ignoring. Use the "multiple" option to attach more tooltips.');
}
if (go) {
instance = new Plugin(this, args[0]);
// save the reference of the new instance
if (!ns) ns = [];
ns.push(instance.namespace);
$(this).data('tooltipster-ns', ns)
// save the instance itself
$(this).data(instance.namespace, instance);
}
instances.push(instance);
});
if (multiple) return instances;
else return this;
}
}
};
// quick & dirty compare function (not bijective nor multidimensional)
function areEqual(a,b) {
var same = true;
$.each(a, function(i, el){
if(typeof b[i] === 'undefined' || a[i] !== b[i]){
same = false;
return false;
}
});
return same;
}
// detect if this device can trigger touch events
var deviceHasTouchCapability = !!('ontouchstart' in window);
// we'll assume the device has no mouse until we detect any mouse movement
var deviceHasMouse = false;
$('body').one('mousemove', function() {
deviceHasMouse = true;
});
function deviceIsPureTouch() {
return (!deviceHasMouse && deviceHasTouchCapability);
}
// detecting support for CSS transitions
function supportsTransitions() {
var b = document.body || document.documentElement,
s = b.style,
p = 'transition';
if(typeof s[p] == 'string') {return true; }
v = ['Moz', 'Webkit', 'Khtml', 'O', 'ms'],
p = p.charAt(0).toUpperCase() + p.substr(1);
for(var i=0; i<v.length; i++) {
if(typeof s[v[i] + p] == 'string') { return true; }
}
return false;
}
}( jQuery, window, document );
module.exports = jQuery
/***/ },
/* 5 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $ = __webpack_require__(1);
var loader = {
CSS_CLASS: 'loader',
DEFAULT_TEXT: 'Loading...',
/**
* Hide loader
*/
hide: function hide() {
this.$el.hide();
},
/**
* Add loading indicator to DOM
* @param {string=} text
*/
add: function add(text) {
this.$el = $('<div>').addClass(this.CSS_CLASS).text(text || this.DEFAULT_TEXT);
this.$el.prependTo($('body')).fadeIn('slow');
},
/**
* Show loading indicator
* @param {string=} text
*/
show: function show(text) {
this.$el = $('.' + this.CSS_CLASS);
if (this.$el.length) {
this.$el.show();
} else {
this.add(text);
}
}
};
module.exports = loader;
/***/ },
/* 6 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $ = __webpack_require__(1);
var _ = __webpack_require__(7);
var scroll = __webpack_require__(9);
var fixedHeaderClass = 'main-header--fixed';
var fixedSidebarClass = 'page__sidebar--fixed';
var $body = $('body');
var mainHeaderHeight = $('.main-header').outerHeight();
var $sidebar = $('.page .page__sidebar');
var hasSidebar = $sidebar.find('.sub-nav').length > 0;
/**
* When scrolling, check if scrolling up and we're far enough down on the page
* to toggle on fixed header...and do so if needed. Turn off if scrolling down.
* Debounced for perf
*
* @param {event} event
*/
var onScroll = _.debounce(function (event) {
var direction = scroll.getDirection(event);
if (direction !== scroll.SCROLL_DOWN && direction !== scroll.SCROLL_UP) {
return; //we only care about vertical scrolling for now.
}
if ($body.hasClass('modal--visible')) {
return; //don't do any of this with a modal showing.
}
scrollFx._toggleFixedHeader(direction);
scrollFx._toggleFixedSidebar(direction);
}, 100);
var scrollFx = {
_toggleSidebarPos: null,
/**
* We'll stick the class on the body because this affects other elements.
* @param {string} direction
*/
_toggleFixedHeader: function _toggleFixedHeader(direction) {
var hasFixedClass = $body.hasClass(fixedHeaderClass);
if (direction == scroll.SCROLL_UP) {
var scrollTop = $(window).scrollTop();
$body.toggleClass(fixedHeaderClass, scrollTop > mainHeaderHeight);
} else if (hasFixedClass) {
$body.removeClass(fixedHeaderClass);
}
},
/**
* @param {string} direction
*/
_toggleFixedSidebar: function _toggleFixedSidebar(direction) {
if (!this.toggleSidebarPos) {
return;
}
var scrollTop = $(window).scrollTop();
$sidebar.toggleClass(fixedSidebarClass, scrollTop > this.toggleSidebarPos);
},
/**
* Set the scrollY position at which we'll toggle the fixed sidebar.
*/
_setToggleSidebarPos: function _setToggleSidebarPos() {
var $sidebarNav = $sidebar.find('.sub-nav');
this.toggleSidebarPos = $sidebarNav.outerHeight() + $sidebarNav.offset().top;
},
/**
* Init module
*/
init: function init() {
$(window).on('wheel DOMMouseScroll', onScroll);
if (hasSidebar) {
this._setToggleSidebarPos();
this._toggleFixedSidebar();
}
}
};
module.exports = scrollFx;
/***/ },
/* 7 */,
/* 8 */,
/* 9 */
/***/ function(module, exports) {
/**
* Various scroll related utils.
*/
'use strict';
var scroll = {
SCROLL_UP: 'up',
SCROLL_DOWN: 'down',
SCROLL_LEFT: 'left',
SCROLL_RIGHT: 'right',
/**
* @param {event.<DOMMouseScroll>} event
* @return {string}
*/
getDirectionDOMMouseScroll: function getDirectionDOMMouseScroll(event) {
if (event.detail < 0) {
return this.SCROLL_UP;
}
return this.SCROLL_DOWN;
},
/**
* @param {event.<wheel>} event
* @return {string}
*/
getDirectionMousewheel: function getDirectionMousewheel(event) {
if (event.wheelDeltaX) {
return event.wheelDeltaX > 0 ? this.SCROLL_LEFT : this.SCROLL_RIGHT;
}
return event.wheelDeltaY > 0 ? this.SCROLL_UP : this.SCROLL_DOWN;
},
/**
* Get scroll direction
* @param {event.<DOMMouseScroll>|event.<wheel>} event
* @return {string|null}
*/
getDirection: function getDirection(event) {
var e = event.originalEvent || event; //support binding via vanilla||jquery
if (e.type === 'DOMMouseScroll') {
return this.getDirectionDOMMouseScroll(e);
} else if (e.type === 'wheel') {
return this.getDirectionMousewheel(e);
}
return null;
}
};
module.exports = scroll;
/***/ },
/* 10 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $ = __webpack_require__(1);
var _ = __webpack_require__(7);
var tooltipster = __webpack_require__(4);
var photoFx = {
ANIMATE_CLASS: 'photo-list__item--animate',
ACTIVE_CLASS: 'photo-list__item--over-active',
INACTIVE_CLASS: 'photo-list__item--over-any',
HOVER_CLASS: 'photo-list__item--hover',
/**
* Toggle animation class on a specific
* indexed photo, then remove after specific time.
*
* @param {number} index
*/
toggleClass: function toggleClass(index) {
var self = this;
var $li = this.$photos.eq(index);
$li.addClass(this.ANIMATE_CLASS);
setTimeout(function () {
$li.removeClass(self.ANIMATE_CLASS);
}, 500);
},
/**
* Returns a shuffled array of photo indexes, cut in half.
* @return array
*/
getShuffledIndexes: function getShuffledIndexes() {
var total = this.$photos.length;
return _.chain(this.$photos).map(function (node, index) {
return index;
}).shuffle().slice(0, Math.floor(total / 2)).value();
},
/**
* Init page animation for photos
*/
initAnimations: function initAnimations() {
var photoIndices = this.getShuffledIndexes();
var counter = 0;
var self = this;
var animateInterval = setInterval(function () {
if (typeof photoIndices[counter] === 'undefined') {
clearInterval(animateInterval);
} else {
self.toggleClass(photoIndices[counter]);
}
counter++;
}, 400);
//kill the animation if we're interacting with the page.
this.$photoList.on('mouseover', function () {
clearInterval(animateInterval);
});
},
/**
* Toggle classes on mouseover
*/
initMouseoverFx: function initMouseoverFx() {
var self = this;
this.$photos.on('mouseover', function () {
var $this = $(this);
$this.addClass(self.HOVER_CLASS);
//delay to determine hover intent
setTimeout(function () {
if ($this.hasClass(self.HOVER_CLASS)) {
self.$photos.not($this).addClass(self.INACTIVE_CLASS);
$this.addClass(self.ACTIVE_CLASS);
}
}, 200);
}).on('mouseout', function () {
self.$photos.removeClass(self.ACTIVE_CLASS + ' ' + self.INACTIVE_CLASS + ' ' + self.HOVER_CLASS);
});
},
/**
* Cache a few DOM items and init FX
*/
init: function init() {
this.$photoList = $('.photo-list');
if (!this.$photoList.length) {
return;
}
this.$photos = this.$photoList.find('.photo-list__item');
this.initAnimations();
this.initMouseoverFx();
this.$photos.find('.modal-media-trigger').tooltipster({
offsetX: 100
});
}
};
module.exports = photoFx;
/***/ },
/* 11 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $ = __webpack_require__(1);
var _ = __webpack_require__(7);
var alert = __webpack_require__(12);
/**
* Generic forms module used for JS validation and submitting forms/handling responses via ajax.
*/
var form = {
ERROR_LABEL_CLASS: 'form-field-error',
ERROR_FIELD_CLASS: 'form-field--has-error',
FORM_DIRTY_CLASS: 'form--is-dirty', //ie, did user try to submit once already (ie, trigger inline messages)
DEFAULT_ERROR_MESSAGE: 'This field is required.',
/**
* Get JSON object containing required field errors.
* @param {object} $form
*/
getRequiredFieldErrors: function getRequiredFieldErrors($form) {
var $required = $form.find('[name="required-field-errors"]');
if (!$required.length) {
return {};
}
return $.parseJSON($required.attr('data-value'));
},
/**
* Check a form to see if required fields are filled in.
* @param {object} $form
* @return {Boolean}
*/
hasRequiredFields: function hasRequiredFields($form) {
var requiredFieldErrors = this.getRequiredFieldErrors($form);
var self = this;
var errors = [];
$form.find('[data-required="true"]').each(function () {
var $field = $(this);
if (_.isEmpty($field.val())) {
var fieldName = $field.attr('name');
var errorMessage = requiredFieldErrors[fieldName];
errors.push({
fieldName: fieldName,
message: errorMessage || self.DEFAULT_ERROR_MESSAGE
});
}
});
if (errors.length) {
return errors;
}
return true;
},
/**
* Show errors for a form
*
* @param {object} $form
* @param {array} errors [{fieldName: string, message: string}]
*/
showErrors: function showErrors($form, errors) {
var _this = this;
errors.forEach(function (error) {
_this.showError($form.find('[name="' + error.fieldName + '"]'), error.message);
});
//focus problem field
var firstWithError = errors.shift();
$form.find('[name="' + firstWithError.fieldName + '"]').focus();
},
/**
* Hide field error
* @param {object} $field
*/
hideError: function hideError($field) {
$field.removeClass(this.ERROR_FIELD_CLASS);
$field.parent('li').find('.' + this.ERROR_LABEL_CLASS).hide();
},
/**
* Show field level error
* @param {object} $field
* @param {string=} errorMessage - optional message
*/
showError: function showError($field, errorMessage) {
var $fieldParent = $field.parent('li');
var $error = $fieldParent.find('.' + this.ERROR_LABEL_CLASS);
$field.addClass(this.ERROR_FIELD_CLASS);
if ($error.length) {
$error.show();
} else {
$fieldParent.append('<label class="' + this.ERROR_LABEL_CLASS + '">' + errorMessage || this.DEFAULT_ERROR_MESSAGE + '</label>');
}
},
/**
* Validate form
*
* @param {object} $form
*/
validate: function validate($form) {
$form.addClass(this.FORM_DIRTY_CLASS);
var validOrErrors = this.hasRequiredFields($form);
if (validOrErrors === true) {
this.submit($form);
} else {
this.showErrors($form, validOrErrors);
}
},
/**
* Submit form via ajax
*
* @param {object} $form
*/
submit: function submit($form) {
var self = this;
$.ajax({
data: $form.serialize(),
url: $form.attr('data-ajax-action'),
method: $form.attr('method'),
headers: {
'X-CSRF-Token': $form.find('[name="csrf-token"]').attr('data-value')
},
success: function success(json) {
var data = $.parseJSON(json);
var alertType = data.status === true ? alert.TYPE_SUCCESS : alert.TYPE_ERROR;
alert.show(data.message, alertType);
if (data.status === true) {
self.clearFields($form);
}
},
error: function error() {
alert.show('Unable to process form.', alert.TYPE_ERROR);
}
});
},
/**
* Clear form fields. Only wired for what's in use now; add the other
* field types as needed.
*
* @param {object} $form
*/
clearFields: function clearFields($form) {
$form.find('.form-field').each(function () {
var $this = $(this);
if ($this.is('input') || $this.is('textarea')) {
$this.val('');
}
});
},
/**
* Init form module
*/
init: function init() {
var $defaultFocusField = $('.form-field--default-focus');
if ($defaultFocusField.length) {
$defaultFocusField.focus();
}
var $validationForm = $('form[data-use-validation="true"]');
if ($validationForm.length) {
var self = this;
$validationForm.on('submit', function (event) {
event.preventDefault();
self.validate($(this));
});
$validationForm.find('[data-required="true"]').on('keyup change', function () {
if (!$validationForm.hasClass(self.FORM_DIRTY_CLASS)) {
return;
}
var $field = $(this);
if (!_.isEmpty($field.val())) {
self.hideError($field);
} else {
self.showError($field);
}
});
}
}
};
module.exports = form;
/***/ },
/* 12 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $ = __webpack_require__(1);
var alert = {
TYPE_SUCCESS: 'success',
TYPE_ERROR: 'error',
/**
* Build alert to insert into the DOM
* @return {object}
*/
buildAlert: function buildAlert() {
var $alert = $('<div>').addClass('alert');
$alert.append($('<strong>').addClass('alert__title'));
$alert.append($('<p>').addClass('alert__message'));
$alert.append($('<a>').addClass('alert__close icon-cancel'));
return $alert;
},
/**
* Return title for alert based on type
* @param {string} alertType
* @return {string}
*/
getTitle: function getTitle(alertType) {
if (alertType === this.TYPE_SUCCESS) {
return 'Success!';
}
return 'There was a problem!';
},
/**
* Show an alert. Only one per page, so if one exists already in the DOM, we'll
* replace the contents. Otherwise build a new one.
*
* @param {string} message
* @param {string|null} alertType
*/
show: function show(message, alertType) {
var self = this;
var type = alertType || this.TYPE_SUCCESS;
var $alert = $('.alert');
if (!$alert.length) {
$alert = this.buildAlert();
$alert.prependTo($('.page .page__content')).hide();
}
$alert.find('.alert__title').html(this.getTitle(type));
$alert.find('.alert__message').html(message);
$alert.fadeIn();
$alert.find('.alert__close').one('click', self.hide.bind(self));
},
/**
* Hide alert
*/
hide: function hide() {
var $alert = $('.alert');
if ($alert.length) {
$alert.hide();
}
}
};
module.exports = alert;
/***/ },
/* 13 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $ = __webpack_require__(1);
var urlUtil = __webpack_require__(14);
var layoutSwitcher = {
ACTIVE_CLASS: 'layout-switcher__link--active',
ENABLE_LAYOUT_TRANSITION_CLASS: 'body--layout-transition-enabled',
PREF_STORAGE_KEY: 'tds.layoutPref',
/**
* Toggle between layouts based on layout link clicked
* @param {object} $link
*/
switchLayout: function switchLayout($link) {
var $parent = $link.parent('.layout-switcher');
var layout = $link.attr('data-layout');
if (layout !== this.getActiveLayout()) {
$parent.find('.layout-switcher__link').not($link).removeClass(this.ACTIVE_CLASS);
$link.addClass(this.ACTIVE_CLASS);
this.removeLayoutClasses(this.$body);
this.$body.addClass('body-layout--' + layout);
this.adjustUrl(layout);
this.adjustPaginationLinks(layout);
this.saveLayoutState(layout);
}
},
/**
* When layout changes adjust param in pagination links.
* @param {string} layout
*/
adjustPaginationLinks: function adjustPaginationLinks(layout) {
$('a.pagination__link').each(function () {
var $this = $(this);
var url = $this.prop('href');
$this.prop('href', urlUtil.addReplaceParam('l', layout, url));
});
},
/**
* Based on new layout, adjust url
* @param {string} layout
*/
adjustUrl: function adjustUrl(layout) {
var path = document.location.pathname;
var newSearchString = urlUtil.addReplaceParam('l', layout);
if (newSearchString) {
path += newSearchString;
}
window.history.pushState(null, window.document.title, path);
},
/**
* Save state to localStorage.
* @param {string} layout
*/
saveLayoutState: function saveLayoutState(layout) {
window.localStorage.setItem(this.PREF_STORAGE_KEY + '.' + this.appSection, layout);
},
/**
* Remove existing layout classes.
* @param {object} $el
*/
removeLayoutClasses: function removeLayoutClasses($el) {
$el.removeClass(function (index, css) {
return (css.match(/(^|\s)body-layout--\S+/g) || []).join(' ');
});
},
/**
* Get stored layout pref: specific to app section, ie pref could be square for portfolio, circle for pics.
* @return {string}
*/
getLayoutPref: function getLayoutPref() {
return window.localStorage.getItem(this.PREF_STORAGE_KEY + '.' + this.appSection);
},
/**
* Get the current active layout if one exists.
*/
getActiveLayout: function getActiveLayout() {
return urlUtil.getParam('l');
},
/**
* In the event that the current layout does not match stored preference, switch it.
*/
correctLayout: function correctLayout() {
var layout = this.getActiveLayout();
var layoutPref = this.getLayoutPref();
if (!_.isNull(layoutPref) && layoutPref !== layout) {
this.switchLayout(this.$layoutSwitcher.find('.layout-switcher__link[data-layout="' + layoutPref + '"]'));
} else {
//the active class is not added by default in the DOM to handle cases where we needed to
//correct layout above(causes noticeable flash in UI). In the event that we did not switch layouts, we'll
//need to add class.
var activeLayout = layout || this.defaultLayout;
this.$layoutSwitcher.find('.layout-switcher__link[data-layout="' + activeLayout + '"]').addClass(this.ACTIVE_CLASS);
}
},
/**
* Bind event handlers for module.
*/
bindEventHandlers: function bindEventHandlers() {
var self = this;
this.$layoutSwitcher.find('.layout-switcher__link').on('click', function (event) {
event.preventDefault();
self.$body.addClass(self.ENABLE_LAYOUT_TRANSITION_CLASS);
self.switchLayout.call(self, $(this), true);
});
},
/**
* Init module
*
* @param {string} defaultLayout
*/
init: function init(defaultLayout) {
this.$layoutSwitcher = $('.layout-switcher');
if (!this.$layoutSwitcher.length) {
return;
}
this.defaultLayout = this.$layoutSwitcher.attr('data-default-layout');
this.$body = $('body');
this.appSection = this.$layoutSwitcher.attr('data-app-section');
this.bindEventHandlers();
this.correctLayout();
}
};
module.exports = layoutSwitcher;
/***/ },
/* 14 */
/***/ function(module, exports) {
/**
* Url utils.
*/
'use strict';
var url = {
/**
* TODO: move to string util if/when you add one, that's all this is.
*
* Does a given query string key exist in url.
* @param {string} url
* @param {string} key
* @return {boolean}
*/
keyExistsInUrl: function keyExistsInUrl(url, key) {
var patt = key + '=';
var re = new RegExp(patt, 'i');
return re.test(url);
},
/**
* Returns url param from query string.
* @param {string} str
* @return {string}
*/
getParam: function getParam(key) {
var queryParams = window.location.search;
if (queryParams && this.keyExistsInUrl(queryParams, key)) {
var patt = key + '=([^&|\\s]+)';
var re = new RegExp(patt, 'i');
var match = queryParams.match(re);
return match[1] || null;
}
return null;
},
/**
* Add param to url string
* @param {[type]} key [description]
* @param {[type]} value [description]
* @param {[type]} existingStr [description]
*/
addParam: function addParam(key, value, existingStr) {
var str = existingStr || '';
if (/(\?)/.test(str)) {
//already have query params, just not this one.
return str + '&' + key + '=' + value;
}
return str + '?' + key + '=' + value;
},
/**
* Replace param value in a url string.
*
* @param {string} key
* @param {string} value
* @param {str} url
* @return {str}
*/
replaceParam: function replaceParam(key, value, url) {
var patt = '(' + key + '=[^&|\\s]+)';
var re = new RegExp(patt, 'i');
return url.replace(re, key + '=' + value);
},
/**
* Replace query string value if it exists. If the string does not exist in the url, it will be added.
*
* @param {string} key
* @param {string} value
* @param {existingStr=} optional search string, if not set use url.
*
* @return {string} - new url with value added/replaced
*/
addReplaceParam: function addReplaceParam(key, value, existingStr) {
var str = existingStr || window.location.search;
if (!str) {
return this.addParam(key, value, str);
}
if (this.keyExistsInUrl(str, key)) {
return this.replaceParam(key, value, str);
}
return this.addParam(key, value, str);
}
};
module.exports = url;
/***/ },
/* 15 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var Chartist = __webpack_require__(16);
var $ = __webpack_require__(1);
/**
* Misc chart related helpers.
*/
var chart = {
/**
* TODO: something that doesn't use SMIL
* and something that's not literally the example:)
*
* https://gionkunz.github.io/chartist-js/examples.html
* @param {object} data
*/
animatePieChart: function animatePieChart(data) {
if (data.type === 'slice') {
// Get the total path length in order to use for dash array animation
var pathLength = data.element._node.getTotalLength();
// Set a dasharray that matches the path length as prerequisite to animate dashoffset
data.element.attr({
'stroke-dasharray': pathLength + 'px ' + pathLength + 'px'
});
// Create animation definition while also assigning an ID to the animation for later sync usage
var animationDefinition = {
'stroke-dashoffset': {
id: 'anim' + data.index,
dur: 500,
from: -pathLength + 'px',
to: '0px',
easing: Chartist.Svg.Easing.easeInOutSine,
// We need to use `fill: 'freeze'` otherwise our animation will fall back to initial (not visible)
fill: 'freeze'
}
};
// If this was not the first slice, we need to time the animation so that it uses the end sync event of the previous animation
if (data.index !== 0) {
animationDefinition['stroke-dashoffset'].begin = 'anim' + (data.index - 1) + '.end';
}
// We need to set an initial value before the animation starts as we are not in guided mode which would do that for us
data.element.attr({
'stroke-dashoffset': -pathLength + 'px'
});
// We can't use guided mode as the animations need to rely on setting begin manually
// See http://gionkunz.github.io/chartist-js/api-documentation.html#chartistsvg-function-animate
data.element.animate(animationDefinition, false);
}
},
/**
* Render pie chart
*
* @param {object} data {series:[...], labels:[...]};
* @param {string} selector to use as chart target.
*/
renderPieChart: function renderPieChart(data, selector) {
var pieChart = new Chartist.Pie(selector, {
series: data.series,
labels: data.labels
}, {
donut: true,
donutWidth: 10,
chartPadding: 30,
total: _.reduce(data.series, function (total, percent) {
return total + percent;
}),
labelOffset: 20,
labelDirection: 'explode'
});
pieChart.on('draw', this.animatePieChart);
},
/**
* Init this module.
*/
init: function init() {
var self = this;
$('.pie-chart-target').each(function () {
var $this = $(this);
var id = $this.prop('id');
var $chartConfig = $('[data-chart-target="' + id + '"]');
if ($chartConfig.length) {
self.renderPieChart($.parseJSON($chartConfig.val()), '#' + id);
}
});
}
};
module.exports = chart;
/***/ },
/* 16 */,
/* 17 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $ = __webpack_require__(1);
//webpack hack for Snap
//https://github.com/adobe-webplatform/Snap.svg/issues/341
var Snap = __webpack_require__(18);
var clock = {
STOPPED_CLASS: '--stopped',
ANIMATION_TIME: 500,
hours: null,
minutes: null,
/**
* Get angle to set for minute/second hand.
*
* @param {number} minutesOrSeconds
* @return {number}
*/
getMinuteSecondHandAngle: function getMinuteSecondHandAngle(minutesOrSeconds) {
return 360 / 60 * minutesOrSeconds;
},
/**
* Get angle to set for hour hand.
*
* @param {number} hours
* @return {number}
*/
getHourHandAngle: function getHourHandAngle(hours) {
if (hours >= 12) {
hours = hours - 12;
}
return 360 / 12 * hours;
},
/**
* Updating time.
*/
updateTime: function updateTime() {
var time = new Date();
var seconds = time.getSeconds();
var minutes = time.getMinutes();
var hours = time.getHours();
var secondsMatrix = new Snap.Matrix();
secondsMatrix.rotate(this.getMinuteSecondHandAngle(seconds), this.cx, this.cy);
this.secondHand.animate({
transform: secondsMatrix
}, this.ANIMATION_TIME, mina.elastic);
//only update minutes/hours if they've changed.
if (this.minutes !== minutes) {
var minutesMatrix = new Snap.Matrix();
minutesMatrix.rotate(this.getMinuteSecondHandAngle(minutes), this.cx + this.adjustCenters, this.cy);
this.minuteHand.animate({
transform: minutesMatrix
}, this.ANIMATION_TIME, mina.elastic);
this.minutes = minutes;
}
if (this.hours !== hours) {
var hoursMatrix = new Snap.Matrix();
hoursMatrix.rotate(this.getHourHandAngle(hours), this.cx + this.adjustCenters, this.cy);
this.hourHand.animate({
transform: hoursMatrix
}, this.ANIMATION_TIME, mina.elastic);
this.hours = hours;
}
},
/**
* Draw a new clock.
*/
drawClock: function drawClock() {
this.clock = Snap('.svg-clock');
this.clock.attr({
viewBox: '0 0 ' + this.cx * 2 + ' ' + this.cy * 2
});
//cx,cy,r
this.clock.circle(this.cx, this.cy, this.r).attr({
fill: '#EEE',
stroke: '#71A097',
'stroke-width': '3px'
});
// x,y,width,height [rx]. [ry]
this.secondHand = this.clock.rect(this.cx, 18, 2, 130, 2).attr({
fill: "#DCDCDC"
});
this.minuteHand = this.clock.rect(this.cx, 35, this.handWidth, 115, 3).attr({
fill: "#35544D"
});
this.hourHand = this.clock.rect(this.cx, 80, this.handWidth, 75, 3).attr({
fill: "#35544D"
});
this.clock.circle(this.cx, this.cy, 10).attr({
fill: '#35544D'
});
},
/**
* Bind handlers for stop/start btn.
*/
bindEventHandlers: function bindEventHandlers() {
var self = this;
$('.stop-btn--clock').on('click', function (event) {
event.preventDefault();
var $this = $(this);
if ($this.hasClass(self.STOPPED_CLASS)) {
$this.text('Stop');
self.startClock();
} else {
$this.text('Start');
clearInterval(self.clockInterval);
}
$this.toggleClass(self.STOPPED_CLASS);
});
},
/**
* Update time once per second.
*/
startClock: function startClock() {
var _this = this;
this.clockInterval = setInterval(function () {
_this.updateTime();
}, 1000);
},
/**
* Set some clock sizes which we'll refer to when animating hands.
*/
setSizes: function setSizes() {
//set cx/cy for main clock circle (x/y coordinates of center of circle vs. r)
this.cx = 150;
this.cy = 150;
//circle r
this.r = 140;
this.handWidth = 6;
this.adjustCenters = 3; //cx,cy for transforms on min/hour hands get adjusted based on hand widths.
},
/**
* Init module. If we've got a clock wrapper DOM element, draw clock and start it.
*/
init: function init() {
if ($('.svg-clock').length) {
this.setSizes();
this.drawClock();
this.updateTime();
this.bindEventHandlers();
this.startClock();
}
}
};
module.exports = clock;
/***/ },
/* 18 */
/***/ function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_LOCAL_MODULE_0__;/*** IMPORTS FROM imports-loader ***/
(function() {
var fix = module.exports=0;
// Snap.svg 0.4.0
//
// Copyright (c) 2013 – 2015 Adobe Systems Incorporated. All rights reserved.
//
// 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.
//
// build: 2015-04-07
// Copyright (c) 2013 Adobe Systems Incorporated. All rights reserved.
//
// 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.
// ┌────────────────────────────────────────────────────────────┐ \\
// │ Eve 0.4.2 - JavaScript Events Library │ \\
// ├────────────────────────────────────────────────────────────┤ \\
// │ Author <NAME> (http://dmitry.baranovskiy.com/) │ \\
// └────────────────────────────────────────────────────────────┘ \\
(function (glob) {
var version = "0.4.2",
has = "hasOwnProperty",
separator = /[\.\/]/,
comaseparator = /\s*,\s*/,
wildcard = "*",
fun = function () {},
numsort = function (a, b) {
return a - b;
},
current_event,
stop,
events = {n: {}},
firstDefined = function () {
for (var i = 0, ii = this.length; i < ii; i++) {
if (typeof this[i] != "undefined") {
return this[i];
}
}
},
lastDefined = function () {
var i = this.length;
while (--i) {
if (typeof this[i] != "undefined") {
return this[i];
}
}
},
/*\
* eve
[ method ]
* Fires event with given `name`, given scope and other parameters.
> Arguments
- name (string) name of the *event*, dot (`.`) or slash (`/`) separated
- scope (object) context for the event handlers
- varargs (...) the rest of arguments will be sent to event handlers
= (object) array of returned values from the listeners. Array has two methods `.firstDefined()` and `.lastDefined()` to get first or last not `undefined` value.
\*/
eve = function (name, scope) {
name = String(name);
var e = events,
oldstop = stop,
args = Array.prototype.slice.call(arguments, 2),
listeners = eve.listeners(name),
z = 0,
f = false,
l,
indexed = [],
queue = {},
out = [],
ce = current_event,
errors = [];
out.firstDefined = firstDefined;
out.lastDefined = lastDefined;
current_event = name;
stop = 0;
for (var i = 0, ii = listeners.length; i < ii; i++) if ("zIndex" in listeners[i]) {
indexed.push(listeners[i].zIndex);
if (listeners[i].zIndex < 0) {
queue[listeners[i].zIndex] = listeners[i];
}
}
indexed.sort(numsort);
while (indexed[z] < 0) {
l = queue[indexed[z++]];
out.push(l.apply(scope, args));
if (stop) {
stop = oldstop;
return out;
}
}
for (i = 0; i < ii; i++) {
l = listeners[i];
if ("zIndex" in l) {
if (l.zIndex == indexed[z]) {
out.push(l.apply(scope, args));
if (stop) {
break;
}
do {
z++;
l = queue[indexed[z]];
l && out.push(l.apply(scope, args));
if (stop) {
break;
}
} while (l)
} else {
queue[l.zIndex] = l;
}
} else {
out.push(l.apply(scope, args));
if (stop) {
break;
}
}
}
stop = oldstop;
current_event = ce;
return out;
};
// Undocumented. Debug only.
eve._events = events;
/*\
* eve.listeners
[ method ]
* Internal method which gives you array of all event handlers that will be triggered by the given `name`.
> Arguments
- name (string) name of the event, dot (`.`) or slash (`/`) separated
= (array) array of event handlers
\*/
eve.listeners = function (name) {
var names = name.split(separator),
e = events,
item,
items,
k,
i,
ii,
j,
jj,
nes,
es = [e],
out = [];
for (i = 0, ii = names.length; i < ii; i++) {
nes = [];
for (j = 0, jj = es.length; j < jj; j++) {
e = es[j].n;
items = [e[names[i]], e[wildcard]];
k = 2;
while (k--) {
item = items[k];
if (item) {
nes.push(item);
out = out.concat(item.f || []);
}
}
}
es = nes;
}
return out;
};
/*\
* eve.on
[ method ]
**
* Binds given event handler with a given name. You can use wildcards “`*`” for the names:
| eve.on("*.under.*", f);
| eve("mouse.under.floor"); // triggers f
* Use @eve to trigger the listener.
**
> Arguments
**
- name (string) name of the event, dot (`.`) or slash (`/`) separated, with optional wildcards
- f (function) event handler function
**
= (function) returned function accepts a single numeric parameter that represents z-index of the handler. It is an optional feature and only used when you need to ensure that some subset of handlers will be invoked in a given order, despite of the order of assignment.
> Example:
| eve.on("mouse", eatIt)(2);
| eve.on("mouse", scream);
| eve.on("mouse", catchIt)(1);
* This will ensure that `catchIt` function will be called before `eatIt`.
*
* If you want to put your handler before non-indexed handlers, specify a negative value.
* Note: I assume most of the time you don’t need to worry about z-index, but it’s nice to have this feature “just in case”.
\*/
eve.on = function (name, f) {
name = String(name);
if (typeof f != "function") {
return function () {};
}
var names = name.split(comaseparator);
for (var i = 0, ii = names.length; i < ii; i++) {
(function (name) {
var names = name.split(separator),
e = events,
exist;
for (var i = 0, ii = names.length; i < ii; i++) {
e = e.n;
e = e.hasOwnProperty(names[i]) && e[names[i]] || (e[names[i]] = {n: {}});
}
e.f = e.f || [];
for (i = 0, ii = e.f.length; i < ii; i++) if (e.f[i] == f) {
exist = true;
break;
}
!exist && e.f.push(f);
}(names[i]));
}
return function (zIndex) {
if (+zIndex == +zIndex) {
f.zIndex = +zIndex;
}
};
};
/*\
* eve.f
[ method ]
**
* Returns function that will fire given event with optional arguments.
* Arguments that will be passed to the result function will be also
* concated to the list of final arguments.
| el.onclick = eve.f("click", 1, 2);
| eve.on("click", function (a, b, c) {
| console.log(a, b, c); // 1, 2, [event object]
| });
> Arguments
- event (string) event name
- varargs (…) and any other arguments
= (function) possible event handler function
\*/
eve.f = function (event) {
var attrs = [].slice.call(arguments, 1);
return function () {
eve.apply(null, [event, null].concat(attrs).concat([].slice.call(arguments, 0)));
};
};
/*\
* eve.stop
[ method ]
**
* Is used inside an event handler to stop the event, preventing any subsequent listeners from firing.
\*/
eve.stop = function () {
stop = 1;
};
/*\
* eve.nt
[ method ]
**
* Could be used inside event handler to figure out actual name of the event.
**
> Arguments
**
- subname (string) #optional subname of the event
**
= (string) name of the event, if `subname` is not specified
* or
= (boolean) `true`, if current event’s name contains `subname`
\*/
eve.nt = function (subname) {
if (subname) {
return new RegExp("(?:\\.|\\/|^)" + subname + "(?:\\.|\\/|$)").test(current_event);
}
return current_event;
};
/*\
* eve.nts
[ method ]
**
* Could be used inside event handler to figure out actual name of the event.
**
**
= (array) names of the event
\*/
eve.nts = function () {
return current_event.split(separator);
};
/*\
* eve.off
[ method ]
**
* Removes given function from the list of event listeners assigned to given name.
* If no arguments specified all the events will be cleared.
**
> Arguments
**
- name (string) name of the event, dot (`.`) or slash (`/`) separated, with optional wildcards
- f (function) event handler function
\*/
/*\
* eve.unbind
[ method ]
**
* See @eve.off
\*/
eve.off = eve.unbind = function (name, f) {
if (!name) {
eve._events = events = {n: {}};
return;
}
var names = name.split(comaseparator);
if (names.length > 1) {
for (var i = 0, ii = names.length; i < ii; i++) {
eve.off(names[i], f);
}
return;
}
names = name.split(separator);
var e,
key,
splice,
i, ii, j, jj,
cur = [events];
for (i = 0, ii = names.length; i < ii; i++) {
for (j = 0; j < cur.length; j += splice.length - 2) {
splice = [j, 1];
e = cur[j].n;
if (names[i] != wildcard) {
if (e[names[i]]) {
splice.push(e[names[i]]);
}
} else {
for (key in e) if (e[has](key)) {
splice.push(e[key]);
}
}
cur.splice.apply(cur, splice);
}
}
for (i = 0, ii = cur.length; i < ii; i++) {
e = cur[i];
while (e.n) {
if (f) {
if (e.f) {
for (j = 0, jj = e.f.length; j < jj; j++) if (e.f[j] == f) {
e.f.splice(j, 1);
break;
}
!e.f.length && delete e.f;
}
for (key in e.n) if (e.n[has](key) && e.n[key].f) {
var funcs = e.n[key].f;
for (j = 0, jj = funcs.length; j < jj; j++) if (funcs[j] == f) {
funcs.splice(j, 1);
break;
}
!funcs.length && delete e.n[key].f;
}
} else {
delete e.f;
for (key in e.n) if (e.n[has](key) && e.n[key].f) {
delete e.n[key].f;
}
}
e = e.n;
}
}
};
/*\
* eve.once
[ method ]
**
* Binds given event handler with a given name to only run once then unbind itself.
| eve.once("login", f);
| eve("login"); // triggers f
| eve("login"); // no listeners
* Use @eve to trigger the listener.
**
> Arguments
**
- name (string) name of the event, dot (`.`) or slash (`/`) separated, with optional wildcards
- f (function) event handler function
**
= (function) same return function as @eve.on
\*/
eve.once = function (name, f) {
var f2 = function () {
eve.unbind(name, f2);
return f.apply(this, arguments);
};
return eve.on(name, f2);
};
/*\
* eve.version
[ property (string) ]
**
* Current version of the library.
\*/
eve.version = version;
eve.toString = function () {
return "You are running Eve " + version;
};
(typeof module != "undefined" && module.exports) ? (module.exports = eve) : ( true ? (!(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_LOCAL_MODULE_0__ = (function() { return eve; }.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)))) : (glob.eve = eve));
})(this);
(function (glob, factory) {
// AMD support
if (true) {
// Define as an anonymous module
!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__WEBPACK_LOCAL_MODULE_0__], __WEBPACK_AMD_DEFINE_RESULT__ = function (eve) {
return factory(glob, eve);
}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
} else if (typeof exports != 'undefined') {
// Next for Node.js or CommonJS
var eve = require('eve');
module.exports = factory(glob, eve);
} else {
// Browser globals (glob is window)
// Snap adds itself to window
factory(glob, glob.eve);
}
}(window || this, function (window, eve) {
// Copyright (c) 2013 Adobe Systems Incorporated. All rights reserved.
//
// 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.
var mina = (function (eve) {
var animations = {},
requestAnimFrame = window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function (callback) {
setTimeout(callback, 16);
},
isArray = Array.isArray || function (a) {
return a instanceof Array ||
Object.prototype.toString.call(a) == "[object Array]";
},
idgen = 0,
idprefix = "M" + (+new Date).toString(36),
ID = function () {
return idprefix + (idgen++).toString(36);
},
diff = function (a, b, A, B) {
if (isArray(a)) {
res = [];
for (var i = 0, ii = a.length; i < ii; i++) {
res[i] = diff(a[i], b, A[i], B);
}
return res;
}
var dif = (A - a) / (B - b);
return function (bb) {
return a + dif * (bb - b);
};
},
timer = Date.now || function () {
return +new Date;
},
sta = function (val) {
var a = this;
if (val == null) {
return a.s;
}
var ds = a.s - val;
a.b += a.dur * ds;
a.B += a.dur * ds;
a.s = val;
},
speed = function (val) {
var a = this;
if (val == null) {
return a.spd;
}
a.spd = val;
},
duration = function (val) {
var a = this;
if (val == null) {
return a.dur;
}
a.s = a.s * val / a.dur;
a.dur = val;
},
stopit = function () {
var a = this;
delete animations[a.id];
a.update();
eve("mina.stop." + a.id, a);
},
pause = function () {
var a = this;
if (a.pdif) {
return;
}
delete animations[a.id];
a.update();
a.pdif = a.get() - a.b;
},
resume = function () {
var a = this;
if (!a.pdif) {
return;
}
a.b = a.get() - a.pdif;
delete a.pdif;
animations[a.id] = a;
},
update = function () {
var a = this,
res;
if (isArray(a.start)) {
res = [];
for (var j = 0, jj = a.start.length; j < jj; j++) {
res[j] = +a.start[j] +
(a.end[j] - a.start[j]) * a.easing(a.s);
}
} else {
res = +a.start + (a.end - a.start) * a.easing(a.s);
}
a.set(res);
},
frame = function () {
var len = 0;
for (var i in animations) if (animations.hasOwnProperty(i)) {
var a = animations[i],
b = a.get(),
res;
len++;
a.s = (b - a.b) / (a.dur / a.spd);
if (a.s >= 1) {
delete animations[i];
a.s = 1;
len--;
(function (a) {
setTimeout(function () {
eve("mina.finish." + a.id, a);
});
}(a));
}
a.update();
}
len && requestAnimFrame(frame);
},
/*\
* mina
[ method ]
**
* Generic animation of numbers
**
- a (number) start _slave_ number
- A (number) end _slave_ number
- b (number) start _master_ number (start time in general case)
- B (number) end _master_ number (end time in gereal case)
- get (function) getter of _master_ number (see @mina.time)
- set (function) setter of _slave_ number
- easing (function) #optional easing function, default is @mina.linear
= (object) animation descriptor
o {
o id (string) animation id,
o start (number) start _slave_ number,
o end (number) end _slave_ number,
o b (number) start _master_ number,
o s (number) animation status (0..1),
o dur (number) animation duration,
o spd (number) animation speed,
o get (function) getter of _master_ number (see @mina.time),
o set (function) setter of _slave_ number,
o easing (function) easing function, default is @mina.linear,
o status (function) status getter/setter,
o speed (function) speed getter/setter,
o duration (function) duration getter/setter,
o stop (function) animation stopper
o pause (function) pauses the animation
o resume (function) resumes the animation
o update (function) calles setter with the right value of the animation
o }
\*/
mina = function (a, A, b, B, get, set, easing) {
var anim = {
id: ID(),
start: a,
end: A,
b: b,
s: 0,
dur: B - b,
spd: 1,
get: get,
set: set,
easing: easing || mina.linear,
status: sta,
speed: speed,
duration: duration,
stop: stopit,
pause: pause,
resume: resume,
update: update
};
animations[anim.id] = anim;
var len = 0, i;
for (i in animations) if (animations.hasOwnProperty(i)) {
len++;
if (len == 2) {
break;
}
}
len == 1 && requestAnimFrame(frame);
return anim;
};
/*\
* mina.time
[ method ]
**
* Returns the current time. Equivalent to:
| function () {
| return (new Date).getTime();
| }
\*/
mina.time = timer;
/*\
* mina.getById
[ method ]
**
* Returns an animation by its id
- id (string) animation's id
= (object) See @mina
\*/
mina.getById = function (id) {
return animations[id] || null;
};
/*\
* mina.linear
[ method ]
**
* Default linear easing
- n (number) input 0..1
= (number) output 0..1
\*/
mina.linear = function (n) {
return n;
};
/*\
* mina.easeout
[ method ]
**
* Easeout easing
- n (number) input 0..1
= (number) output 0..1
\*/
mina.easeout = function (n) {
return Math.pow(n, 1.7);
};
/*\
* mina.easein
[ method ]
**
* Easein easing
- n (number) input 0..1
= (number) output 0..1
\*/
mina.easein = function (n) {
return Math.pow(n, .48);
};
/*\
* mina.easeinout
[ method ]
**
* Easeinout easing
- n (number) input 0..1
= (number) output 0..1
\*/
mina.easeinout = function (n) {
if (n == 1) {
return 1;
}
if (n == 0) {
return 0;
}
var q = .48 - n / 1.04,
Q = Math.sqrt(.1734 + q * q),
x = Q - q,
X = Math.pow(Math.abs(x), 1 / 3) * (x < 0 ? -1 : 1),
y = -Q - q,
Y = Math.pow(Math.abs(y), 1 / 3) * (y < 0 ? -1 : 1),
t = X + Y + .5;
return (1 - t) * 3 * t * t + t * t * t;
};
/*\
* mina.backin
[ method ]
**
* Backin easing
- n (number) input 0..1
= (number) output 0..1
\*/
mina.backin = function (n) {
if (n == 1) {
return 1;
}
var s = 1.70158;
return n * n * ((s + 1) * n - s);
};
/*\
* mina.backout
[ method ]
**
* Backout easing
- n (number) input 0..1
= (number) output 0..1
\*/
mina.backout = function (n) {
if (n == 0) {
return 0;
}
n = n - 1;
var s = 1.70158;
return n * n * ((s + 1) * n + s) + 1;
};
/*\
* mina.elastic
[ method ]
**
* Elastic easing
- n (number) input 0..1
= (number) output 0..1
\*/
mina.elastic = function (n) {
if (n == !!n) {
return n;
}
return Math.pow(2, -10 * n) * Math.sin((n - .075) *
(2 * Math.PI) / .3) + 1;
};
/*\
* mina.bounce
[ method ]
**
* Bounce easing
- n (number) input 0..1
= (number) output 0..1
\*/
mina.bounce = function (n) {
var s = 7.5625,
p = 2.75,
l;
if (n < (1 / p)) {
l = s * n * n;
} else {
if (n < (2 / p)) {
n -= (1.5 / p);
l = s * n * n + .75;
} else {
if (n < (2.5 / p)) {
n -= (2.25 / p);
l = s * n * n + .9375;
} else {
n -= (2.625 / p);
l = s * n * n + .984375;
}
}
}
return l;
};
window.mina = mina;
return mina;
})(typeof eve == "undefined" ? function () {} : eve);
// Copyright (c) 2013 - 2015 Adobe Systems Incorporated. All rights reserved.
//
// 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.
var Snap = (function(root) {
Snap.version = "0.4.0";
/*\
* Snap
[ method ]
**
* Creates a drawing surface or wraps existing SVG element.
**
- width (number|string) width of surface
- height (number|string) height of surface
* or
- DOM (SVGElement) element to be wrapped into Snap structure
* or
- array (array) array of elements (will return set of elements)
* or
- query (string) CSS query selector
= (object) @Element
\*/
function Snap(w, h) {
if (w) {
if (w.nodeType) {
return wrap(w);
}
if (is(w, "array") && Snap.set) {
return Snap.set.apply(Snap, w);
}
if (w instanceof Element) {
return w;
}
if (h == null) {
w = glob.doc.querySelector(String(w));
return wrap(w);
}
}
w = w == null ? "100%" : w;
h = h == null ? "100%" : h;
return new Paper(w, h);
}
Snap.toString = function () {
return "Snap v" + this.version;
};
Snap._ = {};
var glob = {
win: root.window,
doc: root.window.document
};
Snap._.glob = glob;
var has = "hasOwnProperty",
Str = String,
toFloat = parseFloat,
toInt = parseInt,
math = Math,
mmax = math.max,
mmin = math.min,
abs = math.abs,
pow = math.pow,
PI = math.PI,
round = math.round,
E = "",
S = " ",
objectToString = Object.prototype.toString,
ISURL = /^url\(['"]?([^\)]+?)['"]?\)$/i,
colourRegExp = /^\s*((#[a-f\d]{6})|(#[a-f\d]{3})|rgba?\(\s*([\d\.]+%?\s*,\s*[\d\.]+%?\s*,\s*[\d\.]+%?(?:\s*,\s*[\d\.]+%?)?)\s*\)|hsba?\(\s*([\d\.]+(?:deg|\xb0|%)?\s*,\s*[\d\.]+%?\s*,\s*[\d\.]+(?:%?\s*,\s*[\d\.]+)?%?)\s*\)|hsla?\(\s*([\d\.]+(?:deg|\xb0|%)?\s*,\s*[\d\.]+%?\s*,\s*[\d\.]+(?:%?\s*,\s*[\d\.]+)?%?)\s*\))\s*$/i,
bezierrg = /^(?:cubic-)?bezier\(([^,]+),([^,]+),([^,]+),([^\)]+)\)/,
reURLValue = /^url\(#?([^)]+)\)$/,
separator = Snap._.separator = /[,\s]+/,
whitespace = /[\s]/g,
commaSpaces = /[\s]*,[\s]*/,
hsrg = {hs: 1, rg: 1},
pathCommand = /([a-z])[\s,]*((-?\d*\.?\d*(?:e[\-+]?\d+)?[\s]*,?[\s]*)+)/ig,
tCommand = /([rstm])[\s,]*((-?\d*\.?\d*(?:e[\-+]?\d+)?[\s]*,?[\s]*)+)/ig,
pathValues = /(-?\d*\.?\d*(?:e[\-+]?\\d+)?)[\s]*,?[\s]*/ig,
idgen = 0,
idprefix = "S" + (+new Date).toString(36),
ID = function (el) {
return (el && el.type ? el.type : E) + idprefix + (idgen++).toString(36);
},
xlink = "http://www.w3.org/1999/xlink",
xmlns = "http://www.w3.org/2000/svg",
hub = {},
URL = Snap.url = function (url) {
return "url('#" + url + "')";
};
function $(el, attr) {
if (attr) {
if (el == "#text") {
el = glob.doc.createTextNode(attr.text || attr["#text"] || "");
}
if (el == "#comment") {
el = glob.doc.createComment(attr.text || attr["#text"] || "");
}
if (typeof el == "string") {
el = $(el);
}
if (typeof attr == "string") {
if (el.nodeType == 1) {
if (attr.substring(0, 6) == "xlink:") {
return el.getAttributeNS(xlink, attr.substring(6));
}
if (attr.substring(0, 4) == "xml:") {
return el.getAttributeNS(xmlns, attr.substring(4));
}
return el.getAttribute(attr);
} else if (attr == "text") {
return el.nodeValue;
} else {
return null;
}
}
if (el.nodeType == 1) {
for (var key in attr) if (attr[has](key)) {
var val = Str(attr[key]);
if (val) {
if (key.substring(0, 6) == "xlink:") {
el.setAttributeNS(xlink, key.substring(6), val);
} else if (key.substring(0, 4) == "xml:") {
el.setAttributeNS(xmlns, key.substring(4), val);
} else {
el.setAttribute(key, val);
}
} else {
el.removeAttribute(key);
}
}
} else if ("text" in attr) {
el.nodeValue = attr.text;
}
} else {
el = glob.doc.createElementNS(xmlns, el);
}
return el;
}
Snap._.$ = $;
Snap._.id = ID;
function getAttrs(el) {
var attrs = el.attributes,
name,
out = {};
for (var i = 0; i < attrs.length; i++) {
if (attrs[i].namespaceURI == xlink) {
name = "xlink:";
} else {
name = "";
}
name += attrs[i].name;
out[name] = attrs[i].textContent;
}
return out;
}
function is(o, type) {
type = Str.prototype.toLowerCase.call(type);
if (type == "finite") {
return isFinite(o);
}
if (type == "array" &&
(o instanceof Array || Array.isArray && Array.isArray(o))) {
return true;
}
return (type == "null" && o === null) ||
(type == typeof o && o !== null) ||
(type == "object" && o === Object(o)) ||
objectToString.call(o).slice(8, -1).toLowerCase() == type;
}
/*\
* Snap.format
[ method ]
**
* Replaces construction of type `{<name>}` to the corresponding argument
**
- token (string) string to format
- json (object) object which properties are used as a replacement
= (string) formatted string
> Usage
| // this draws a rectangular shape equivalent to "M10,20h40v50h-40z"
| paper.path(Snap.format("M{x},{y}h{dim.width}v{dim.height}h{dim['negative width']}z", {
| x: 10,
| y: 20,
| dim: {
| width: 40,
| height: 50,
| "negative width": -40
| }
| }));
\*/
Snap.format = (function () {
var tokenRegex = /\{([^\}]+)\}/g,
objNotationRegex = /(?:(?:^|\.)(.+?)(?=\[|\.|$|\()|\[('|")(.+?)\2\])(\(\))?/g, // matches .xxxxx or ["xxxxx"] to run over object properties
replacer = function (all, key, obj) {
var res = obj;
key.replace(objNotationRegex, function (all, name, quote, quotedName, isFunc) {
name = name || quotedName;
if (res) {
if (name in res) {
res = res[name];
}
typeof res == "function" && isFunc && (res = res());
}
});
res = (res == null || res == obj ? all : res) + "";
return res;
};
return function (str, obj) {
return Str(str).replace(tokenRegex, function (all, key) {
return replacer(all, key, obj);
});
};
})();
function clone(obj) {
if (typeof obj == "function" || Object(obj) !== obj) {
return obj;
}
var res = new obj.constructor;
for (var key in obj) if (obj[has](key)) {
res[key] = clone(obj[key]);
}
return res;
}
Snap._.clone = clone;
function repush(array, item) {
for (var i = 0, ii = array.length; i < ii; i++) if (array[i] === item) {
return array.push(array.splice(i, 1)[0]);
}
}
function cacher(f, scope, postprocessor) {
function newf() {
var arg = Array.prototype.slice.call(arguments, 0),
args = arg.join("\u2400"),
cache = newf.cache = newf.cache || {},
count = newf.count = newf.count || [];
if (cache[has](args)) {
repush(count, args);
return postprocessor ? postprocessor(cache[args]) : cache[args];
}
count.length >= 1e3 && delete cache[count.shift()];
count.push(args);
cache[args] = f.apply(scope, arg);
return postprocessor ? postprocessor(cache[args]) : cache[args];
}
return newf;
}
Snap._.cacher = cacher;
function angle(x1, y1, x2, y2, x3, y3) {
if (x3 == null) {
var x = x1 - x2,
y = y1 - y2;
if (!x && !y) {
return 0;
}
return (180 + math.atan2(-y, -x) * 180 / PI + 360) % 360;
} else {
return angle(x1, y1, x3, y3) - angle(x2, y2, x3, y3);
}
}
function rad(deg) {
return deg % 360 * PI / 180;
}
function deg(rad) {
return rad * 180 / PI % 360;
}
function x_y() {
return this.x + S + this.y;
}
function x_y_w_h() {
return this.x + S + this.y + S + this.width + " \xd7 " + this.height;
}
/*\
* Snap.rad
[ method ]
**
* Transform angle to radians
- deg (number) angle in degrees
= (number) angle in radians
\*/
Snap.rad = rad;
/*\
* Snap.deg
[ method ]
**
* Transform angle to degrees
- rad (number) angle in radians
= (number) angle in degrees
\*/
Snap.deg = deg;
/*\
* Snap.sin
[ method ]
**
* Equivalent to `Math.sin()` only works with degrees, not radians.
- angle (number) angle in degrees
= (number) sin
\*/
Snap.sin = function (angle) {
return math.sin(Snap.rad(angle));
};
/*\
* Snap.tan
[ method ]
**
* Equivalent to `Math.tan()` only works with degrees, not radians.
- angle (number) angle in degrees
= (number) tan
\*/
Snap.tan = function (angle) {
return math.tan(Snap.rad(angle));
};
/*\
* Snap.cos
[ method ]
**
* Equivalent to `Math.cos()` only works with degrees, not radians.
- angle (number) angle in degrees
= (number) cos
\*/
Snap.cos = function (angle) {
return math.cos(Snap.rad(angle));
};
/*\
* Snap.asin
[ method ]
**
* Equivalent to `Math.asin()` only works with degrees, not radians.
- num (number) value
= (number) asin in degrees
\*/
Snap.asin = function (num) {
return Snap.deg(math.asin(num));
};
/*\
* Snap.acos
[ method ]
**
* Equivalent to `Math.acos()` only works with degrees, not radians.
- num (number) value
= (number) acos in degrees
\*/
Snap.acos = function (num) {
return Snap.deg(math.acos(num));
};
/*\
* Snap.atan
[ method ]
**
* Equivalent to `Math.atan()` only works with degrees, not radians.
- num (number) value
= (number) atan in degrees
\*/
Snap.atan = function (num) {
return Snap.deg(math.atan(num));
};
/*\
* Snap.atan2
[ method ]
**
* Equivalent to `Math.atan2()` only works with degrees, not radians.
- num (number) value
= (number) atan2 in degrees
\*/
Snap.atan2 = function (num) {
return Snap.deg(math.atan2(num));
};
/*\
* Snap.angle
[ method ]
**
* Returns an angle between two or three points
> Parameters
- x1 (number) x coord of first point
- y1 (number) y coord of first point
- x2 (number) x coord of second point
- y2 (number) y coord of second point
- x3 (number) #optional x coord of third point
- y3 (number) #optional y coord of third point
= (number) angle in degrees
\*/
Snap.angle = angle;
/*\
* Snap.len
[ method ]
**
* Returns distance between two points
> Parameters
- x1 (number) x coord of first point
- y1 (number) y coord of first point
- x2 (number) x coord of second point
- y2 (number) y coord of second point
= (number) distance
\*/
Snap.len = function (x1, y1, x2, y2) {
return Math.sqrt(Snap.len2(x1, y1, x2, y2));
};
/*\
* Snap.len2
[ method ]
**
* Returns squared distance between two points
> Parameters
- x1 (number) x coord of first point
- y1 (number) y coord of first point
- x2 (number) x coord of second point
- y2 (number) y coord of second point
= (number) distance
\*/
Snap.len2 = function (x1, y1, x2, y2) {
return (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2);
};
/*\
* Snap.closestPoint
[ method ]
**
* Returns closest point to a given one on a given path.
> Parameters
- path (Element) path element
- x (number) x coord of a point
- y (number) y coord of a point
= (object) in format
{
x (number) x coord of the point on the path
y (number) y coord of the point on the path
length (number) length of the path to the point
distance (number) distance from the given point to the path
}
\*/
// Copied from http://bl.ocks.org/mbostock/8027637
Snap.closestPoint = function (path, x, y) {
function distance2(p) {
var dx = p.x - x,
dy = p.y - y;
return dx * dx + dy * dy;
}
var pathNode = path.node,
pathLength = pathNode.getTotalLength(),
precision = pathLength / pathNode.pathSegList.numberOfItems * .125,
best,
bestLength,
bestDistance = Infinity;
// linear scan for coarse approximation
for (var scan, scanLength = 0, scanDistance; scanLength <= pathLength; scanLength += precision) {
if ((scanDistance = distance2(scan = pathNode.getPointAtLength(scanLength))) < bestDistance) {
best = scan, bestLength = scanLength, bestDistance = scanDistance;
}
}
// binary search for precise estimate
precision *= .5;
while (precision > .5) {
var before,
after,
beforeLength,
afterLength,
beforeDistance,
afterDistance;
if ((beforeLength = bestLength - precision) >= 0 && (beforeDistance = distance2(before = pathNode.getPointAtLength(beforeLength))) < bestDistance) {
best = before, bestLength = beforeLength, bestDistance = beforeDistance;
} else if ((afterLength = bestLength + precision) <= pathLength && (afterDistance = distance2(after = pathNode.getPointAtLength(afterLength))) < bestDistance) {
best = after, bestLength = afterLength, bestDistance = afterDistance;
} else {
precision *= .5;
}
}
best = {
x: best.x,
y: best.y,
length: bestLength,
distance: Math.sqrt(bestDistance)
};
return best;
}
/*\
* Snap.is
[ method ]
**
* Handy replacement for the `typeof` operator
- o (…) any object or primitive
- type (string) name of the type, e.g., `string`, `function`, `number`, etc.
= (boolean) `true` if given value is of given type
\*/
Snap.is = is;
/*\
* Snap.snapTo
[ method ]
**
* Snaps given value to given grid
- values (array|number) given array of values or step of the grid
- value (number) value to adjust
- tolerance (number) #optional maximum distance to the target value that would trigger the snap. Default is `10`.
= (number) adjusted value
\*/
Snap.snapTo = function (values, value, tolerance) {
tolerance = is(tolerance, "finite") ? tolerance : 10;
if (is(values, "array")) {
var i = values.length;
while (i--) if (abs(values[i] - value) <= tolerance) {
return values[i];
}
} else {
values = +values;
var rem = value % values;
if (rem < tolerance) {
return value - rem;
}
if (rem > values - tolerance) {
return value - rem + values;
}
}
return value;
};
// Colour
/*\
* Snap.getRGB
[ method ]
**
* Parses color string as RGB object
- color (string) color string in one of the following formats:
# <ul>
# <li>Color name (<code>red</code>, <code>green</code>, <code>cornflowerblue</code>, etc)</li>
# <li>#••• — shortened HTML color: (<code>#000</code>, <code>#fc0</code>, etc.)</li>
# <li>#•••••• — full length HTML color: (<code>#000000</code>, <code>#bd2300</code>)</li>
# <li>rgb(•••, •••, •••) — red, green and blue channels values: (<code>rgb(200, 100, 0)</code>)</li>
# <li>rgba(•••, •••, •••, •••) — also with opacity</li>
# <li>rgb(•••%, •••%, •••%) — same as above, but in %: (<code>rgb(100%, 175%, 0%)</code>)</li>
# <li>rgba(•••%, •••%, •••%, •••%) — also with opacity</li>
# <li>hsb(•••, •••, •••) — hue, saturation and brightness values: (<code>hsb(0.5, 0.25, 1)</code>)</li>
# <li>hsba(•••, •••, •••, •••) — also with opacity</li>
# <li>hsb(•••%, •••%, •••%) — same as above, but in %</li>
# <li>hsba(•••%, •••%, •••%, •••%) — also with opacity</li>
# <li>hsl(•••, •••, •••) — hue, saturation and luminosity values: (<code>hsb(0.5, 0.25, 0.5)</code>)</li>
# <li>hsla(•••, •••, •••, •••) — also with opacity</li>
# <li>hsl(•••%, •••%, •••%) — same as above, but in %</li>
# <li>hsla(•••%, •••%, •••%, •••%) — also with opacity</li>
# </ul>
* Note that `%` can be used any time: `rgb(20%, 255, 50%)`.
= (object) RGB object in the following format:
o {
o r (number) red,
o g (number) green,
o b (number) blue,
o hex (string) color in HTML/CSS format: #••••••,
o error (boolean) true if string can't be parsed
o }
\*/
Snap.getRGB = cacher(function (colour) {
if (!colour || !!((colour = Str(colour)).indexOf("-") + 1)) {
return {r: -1, g: -1, b: -1, hex: "none", error: 1, toString: rgbtoString};
}
if (colour == "none") {
return {r: -1, g: -1, b: -1, hex: "none", toString: rgbtoString};
}
!(hsrg[has](colour.toLowerCase().substring(0, 2)) || colour.charAt() == "#") && (colour = toHex(colour));
if (!colour) {
return {r: -1, g: -1, b: -1, hex: "none", error: 1, toString: rgbtoString};
}
var res,
red,
green,
blue,
opacity,
t,
values,
rgb = colour.match(colourRegExp);
if (rgb) {
if (rgb[2]) {
blue = toInt(rgb[2].substring(5), 16);
green = toInt(rgb[2].substring(3, 5), 16);
red = toInt(rgb[2].substring(1, 3), 16);
}
if (rgb[3]) {
blue = toInt((t = rgb[3].charAt(3)) + t, 16);
green = toInt((t = rgb[3].charAt(2)) + t, 16);
red = toInt((t = rgb[3].charAt(1)) + t, 16);
}
if (rgb[4]) {
values = rgb[4].split(commaSpaces);
red = toFloat(values[0]);
values[0].slice(-1) == "%" && (red *= 2.55);
green = toFloat(values[1]);
values[1].slice(-1) == "%" && (green *= 2.55);
blue = toFloat(values[2]);
values[2].slice(-1) == "%" && (blue *= 2.55);
rgb[1].toLowerCase().slice(0, 4) == "rgba" && (opacity = toFloat(values[3]));
values[3] && values[3].slice(-1) == "%" && (opacity /= 100);
}
if (rgb[5]) {
values = rgb[5].split(commaSpaces);
red = toFloat(values[0]);
values[0].slice(-1) == "%" && (red /= 100);
green = toFloat(values[1]);
values[1].slice(-1) == "%" && (green /= 100);
blue = toFloat(values[2]);
values[2].slice(-1) == "%" && (blue /= 100);
(values[0].slice(-3) == "deg" || values[0].slice(-1) == "\xb0") && (red /= 360);
rgb[1].toLowerCase().slice(0, 4) == "hsba" && (opacity = toFloat(values[3]));
values[3] && values[3].slice(-1) == "%" && (opacity /= 100);
return Snap.hsb2rgb(red, green, blue, opacity);
}
if (rgb[6]) {
values = rgb[6].split(commaSpaces);
red = toFloat(values[0]);
values[0].slice(-1) == "%" && (red /= 100);
green = toFloat(values[1]);
values[1].slice(-1) == "%" && (green /= 100);
blue = toFloat(values[2]);
values[2].slice(-1) == "%" && (blue /= 100);
(values[0].slice(-3) == "deg" || values[0].slice(-1) == "\xb0") && (red /= 360);
rgb[1].toLowerCase().slice(0, 4) == "hsla" && (opacity = toFloat(values[3]));
values[3] && values[3].slice(-1) == "%" && (opacity /= 100);
return Snap.hsl2rgb(red, green, blue, opacity);
}
red = mmin(math.round(red), 255);
green = mmin(math.round(green), 255);
blue = mmin(math.round(blue), 255);
opacity = mmin(mmax(opacity, 0), 1);
rgb = {r: red, g: green, b: blue, toString: rgbtoString};
rgb.hex = "#" + (16777216 | blue | (green << 8) | (red << 16)).toString(16).slice(1);
rgb.opacity = is(opacity, "finite") ? opacity : 1;
return rgb;
}
return {r: -1, g: -1, b: -1, hex: "none", error: 1, toString: rgbtoString};
}, Snap);
/*\
* Snap.hsb
[ method ]
**
* Converts HSB values to a hex representation of the color
- h (number) hue
- s (number) saturation
- b (number) value or brightness
= (string) hex representation of the color
\*/
Snap.hsb = cacher(function (h, s, b) {
return Snap.hsb2rgb(h, s, b).hex;
});
/*\
* Snap.hsl
[ method ]
**
* Converts HSL values to a hex representation of the color
- h (number) hue
- s (number) saturation
- l (number) luminosity
= (string) hex representation of the color
\*/
Snap.hsl = cacher(function (h, s, l) {
return Snap.hsl2rgb(h, s, l).hex;
});
/*\
* Snap.rgb
[ method ]
**
* Converts RGB values to a hex representation of the color
- r (number) red
- g (number) green
- b (number) blue
= (string) hex representation of the color
\*/
Snap.rgb = cacher(function (r, g, b, o) {
if (is(o, "finite")) {
var round = math.round;
return "rgba(" + [round(r), round(g), round(b), +o.toFixed(2)] + ")";
}
return "#" + (16777216 | b | (g << 8) | (r << 16)).toString(16).slice(1);
});
var toHex = function (color) {
var i = glob.doc.getElementsByTagName("head")[0] || glob.doc.getElementsByTagName("svg")[0],
red = "rgb(255, 0, 0)";
toHex = cacher(function (color) {
if (color.toLowerCase() == "red") {
return red;
}
i.style.color = red;
i.style.color = color;
var out = glob.doc.defaultView.getComputedStyle(i, E).getPropertyValue("color");
return out == red ? null : out;
});
return toHex(color);
},
hsbtoString = function () {
return "hsb(" + [this.h, this.s, this.b] + ")";
},
hsltoString = function () {
return "hsl(" + [this.h, this.s, this.l] + ")";
},
rgbtoString = function () {
return this.opacity == 1 || this.opacity == null ?
this.hex :
"rgba(" + [this.r, this.g, this.b, this.opacity] + ")";
},
prepareRGB = function (r, g, b) {
if (g == null && is(r, "object") && "r" in r && "g" in r && "b" in r) {
b = r.b;
g = r.g;
r = r.r;
}
if (g == null && is(r, string)) {
var clr = Snap.getRGB(r);
r = clr.r;
g = clr.g;
b = clr.b;
}
if (r > 1 || g > 1 || b > 1) {
r /= 255;
g /= 255;
b /= 255;
}
return [r, g, b];
},
packageRGB = function (r, g, b, o) {
r = math.round(r * 255);
g = math.round(g * 255);
b = math.round(b * 255);
var rgb = {
r: r,
g: g,
b: b,
opacity: is(o, "finite") ? o : 1,
hex: Snap.rgb(r, g, b),
toString: rgbtoString
};
is(o, "finite") && (rgb.opacity = o);
return rgb;
};
/*\
* Snap.color
[ method ]
**
* Parses the color string and returns an object featuring the color's component values
- clr (string) color string in one of the supported formats (see @Snap.getRGB)
= (object) Combined RGB/HSB object in the following format:
o {
o r (number) red,
o g (number) green,
o b (number) blue,
o hex (string) color in HTML/CSS format: #••••••,
o error (boolean) `true` if string can't be parsed,
o h (number) hue,
o s (number) saturation,
o v (number) value (brightness),
o l (number) lightness
o }
\*/
Snap.color = function (clr) {
var rgb;
if (is(clr, "object") && "h" in clr && "s" in clr && "b" in clr) {
rgb = Snap.hsb2rgb(clr);
clr.r = rgb.r;
clr.g = rgb.g;
clr.b = rgb.b;
clr.opacity = 1;
clr.hex = rgb.hex;
} else if (is(clr, "object") && "h" in clr && "s" in clr && "l" in clr) {
rgb = Snap.hsl2rgb(clr);
clr.r = rgb.r;
clr.g = rgb.g;
clr.b = rgb.b;
clr.opacity = 1;
clr.hex = rgb.hex;
} else {
if (is(clr, "string")) {
clr = Snap.getRGB(clr);
}
if (is(clr, "object") && "r" in clr && "g" in clr && "b" in clr && !("error" in clr)) {
rgb = Snap.rgb2hsl(clr);
clr.h = rgb.h;
clr.s = rgb.s;
clr.l = rgb.l;
rgb = Snap.rgb2hsb(clr);
clr.v = rgb.b;
} else {
clr = {hex: "none"};
clr.r = clr.g = clr.b = clr.h = clr.s = clr.v = clr.l = -1;
clr.error = 1;
}
}
clr.toString = rgbtoString;
return clr;
};
/*\
* Snap.hsb2rgb
[ method ]
**
* Converts HSB values to an RGB object
- h (number) hue
- s (number) saturation
- v (number) value or brightness
= (object) RGB object in the following format:
o {
o r (number) red,
o g (number) green,
o b (number) blue,
o hex (string) color in HTML/CSS format: #••••••
o }
\*/
Snap.hsb2rgb = function (h, s, v, o) {
if (is(h, "object") && "h" in h && "s" in h && "b" in h) {
v = h.b;
s = h.s;
o = h.o;
h = h.h;
}
h *= 360;
var R, G, B, X, C;
h = (h % 360) / 60;
C = v * s;
X = C * (1 - abs(h % 2 - 1));
R = G = B = v - C;
h = ~~h;
R += [C, X, 0, 0, X, C][h];
G += [X, C, C, X, 0, 0][h];
B += [0, 0, X, C, C, X][h];
return packageRGB(R, G, B, o);
};
/*\
* Snap.hsl2rgb
[ method ]
**
* Converts HSL values to an RGB object
- h (number) hue
- s (number) saturation
- l (number) luminosity
= (object) RGB object in the following format:
o {
o r (number) red,
o g (number) green,
o b (number) blue,
o hex (string) color in HTML/CSS format: #••••••
o }
\*/
Snap.hsl2rgb = function (h, s, l, o) {
if (is(h, "object") && "h" in h && "s" in h && "l" in h) {
l = h.l;
s = h.s;
h = h.h;
}
if (h > 1 || s > 1 || l > 1) {
h /= 360;
s /= 100;
l /= 100;
}
h *= 360;
var R, G, B, X, C;
h = (h % 360) / 60;
C = 2 * s * (l < .5 ? l : 1 - l);
X = C * (1 - abs(h % 2 - 1));
R = G = B = l - C / 2;
h = ~~h;
R += [C, X, 0, 0, X, C][h];
G += [X, C, C, X, 0, 0][h];
B += [0, 0, X, C, C, X][h];
return packageRGB(R, G, B, o);
};
/*\
* Snap.rgb2hsb
[ method ]
**
* Converts RGB values to an HSB object
- r (number) red
- g (number) green
- b (number) blue
= (object) HSB object in the following format:
o {
o h (number) hue,
o s (number) saturation,
o b (number) brightness
o }
\*/
Snap.rgb2hsb = function (r, g, b) {
b = prepareRGB(r, g, b);
r = b[0];
g = b[1];
b = b[2];
var H, S, V, C;
V = mmax(r, g, b);
C = V - mmin(r, g, b);
H = (C == 0 ? null :
V == r ? (g - b) / C :
V == g ? (b - r) / C + 2 :
(r - g) / C + 4
);
H = ((H + 360) % 6) * 60 / 360;
S = C == 0 ? 0 : C / V;
return {h: H, s: S, b: V, toString: hsbtoString};
};
/*\
* Snap.rgb2hsl
[ method ]
**
* Converts RGB values to an HSL object
- r (number) red
- g (number) green
- b (number) blue
= (object) HSL object in the following format:
o {
o h (number) hue,
o s (number) saturation,
o l (number) luminosity
o }
\*/
Snap.rgb2hsl = function (r, g, b) {
b = prepareRGB(r, g, b);
r = b[0];
g = b[1];
b = b[2];
var H, S, L, M, m, C;
M = mmax(r, g, b);
m = mmin(r, g, b);
C = M - m;
H = (C == 0 ? null :
M == r ? (g - b) / C :
M == g ? (b - r) / C + 2 :
(r - g) / C + 4);
H = ((H + 360) % 6) * 60 / 360;
L = (M + m) / 2;
S = (C == 0 ? 0 :
L < .5 ? C / (2 * L) :
C / (2 - 2 * L));
return {h: H, s: S, l: L, toString: hsltoString};
};
// Transformations
/*\
* Snap.parsePathString
[ method ]
**
* Utility method
**
* Parses given path string into an array of arrays of path segments
- pathString (string|array) path string or array of segments (in the last case it is returned straight away)
= (array) array of segments
\*/
Snap.parsePathString = function (pathString) {
if (!pathString) {
return null;
}
var pth = Snap.path(pathString);
if (pth.arr) {
return Snap.path.clone(pth.arr);
}
var paramCounts = {a: 7, c: 6, o: 2, h: 1, l: 2, m: 2, r: 4, q: 4, s: 4, t: 2, v: 1, u: 3, z: 0},
data = [];
if (is(pathString, "array") && is(pathString[0], "array")) { // rough assumption
data = Snap.path.clone(pathString);
}
if (!data.length) {
Str(pathString).replace(pathCommand, function (a, b, c) {
var params = [],
name = b.toLowerCase();
c.replace(pathValues, function (a, b) {
b && params.push(+b);
});
if (name == "m" && params.length > 2) {
data.push([b].concat(params.splice(0, 2)));
name = "l";
b = b == "m" ? "l" : "L";
}
if (name == "o" && params.length == 1) {
data.push([b, params[0]]);
}
if (name == "r") {
data.push([b].concat(params));
} else while (params.length >= paramCounts[name]) {
data.push([b].concat(params.splice(0, paramCounts[name])));
if (!paramCounts[name]) {
break;
}
}
});
}
data.toString = Snap.path.toString;
pth.arr = Snap.path.clone(data);
return data;
};
/*\
* Snap.parseTransformString
[ method ]
**
* Utility method
**
* Parses given transform string into an array of transformations
- TString (string|array) transform string or array of transformations (in the last case it is returned straight away)
= (array) array of transformations
\*/
var parseTransformString = Snap.parseTransformString = function (TString) {
if (!TString) {
return null;
}
var paramCounts = {r: 3, s: 4, t: 2, m: 6},
data = [];
if (is(TString, "array") && is(TString[0], "array")) { // rough assumption
data = Snap.path.clone(TString);
}
if (!data.length) {
Str(TString).replace(tCommand, function (a, b, c) {
var params = [],
name = b.toLowerCase();
c.replace(pathValues, function (a, b) {
b && params.push(+b);
});
data.push([b].concat(params));
});
}
data.toString = Snap.path.toString;
return data;
};
function svgTransform2string(tstr) {
var res = [];
tstr = tstr.replace(/(?:^|\s)(\w+)\(([^)]+)\)/g, function (all, name, params) {
params = params.split(/\s*,\s*|\s+/);
if (name == "rotate" && params.length == 1) {
params.push(0, 0);
}
if (name == "scale") {
if (params.length > 2) {
params = params.slice(0, 2);
} else if (params.length == 2) {
params.push(0, 0);
}
if (params.length == 1) {
params.push(params[0], 0, 0);
}
}
if (name == "skewX") {
res.push(["m", 1, 0, math.tan(rad(params[0])), 1, 0, 0]);
} else if (name == "skewY") {
res.push(["m", 1, math.tan(rad(params[0])), 0, 1, 0, 0]);
} else {
res.push([name.charAt(0)].concat(params));
}
return all;
});
return res;
}
Snap._.svgTransform2string = svgTransform2string;
Snap._.rgTransform = /^[a-z][\s]*-?\.?\d/i;
function transform2matrix(tstr, bbox) {
var tdata = parseTransformString(tstr),
m = new Snap.Matrix;
if (tdata) {
for (var i = 0, ii = tdata.length; i < ii; i++) {
var t = tdata[i],
tlen = t.length,
command = Str(t[0]).toLowerCase(),
absolute = t[0] != command,
inver = absolute ? m.invert() : 0,
x1,
y1,
x2,
y2,
bb;
if (command == "t" && tlen == 2){
m.translate(t[1], 0);
} else if (command == "t" && tlen == 3) {
if (absolute) {
x1 = inver.x(0, 0);
y1 = inver.y(0, 0);
x2 = inver.x(t[1], t[2]);
y2 = inver.y(t[1], t[2]);
m.translate(x2 - x1, y2 - y1);
} else {
m.translate(t[1], t[2]);
}
} else if (command == "r") {
if (tlen == 2) {
bb = bb || bbox;
m.rotate(t[1], bb.x + bb.width / 2, bb.y + bb.height / 2);
} else if (tlen == 4) {
if (absolute) {
x2 = inver.x(t[2], t[3]);
y2 = inver.y(t[2], t[3]);
m.rotate(t[1], x2, y2);
} else {
m.rotate(t[1], t[2], t[3]);
}
}
} else if (command == "s") {
if (tlen == 2 || tlen == 3) {
bb = bb || bbox;
m.scale(t[1], t[tlen - 1], bb.x + bb.width / 2, bb.y + bb.height / 2);
} else if (tlen == 4) {
if (absolute) {
x2 = inver.x(t[2], t[3]);
y2 = inver.y(t[2], t[3]);
m.scale(t[1], t[1], x2, y2);
} else {
m.scale(t[1], t[1], t[2], t[3]);
}
} else if (tlen == 5) {
if (absolute) {
x2 = inver.x(t[3], t[4]);
y2 = inver.y(t[3], t[4]);
m.scale(t[1], t[2], x2, y2);
} else {
m.scale(t[1], t[2], t[3], t[4]);
}
}
} else if (command == "m" && tlen == 7) {
m.add(t[1], t[2], t[3], t[4], t[5], t[6]);
}
}
}
return m;
}
Snap._.transform2matrix = transform2matrix;
Snap._unit2px = unit2px;
var contains = glob.doc.contains || glob.doc.compareDocumentPosition ?
function (a, b) {
var adown = a.nodeType == 9 ? a.documentElement : a,
bup = b && b.parentNode;
return a == bup || !!(bup && bup.nodeType == 1 && (
adown.contains ?
adown.contains(bup) :
a.compareDocumentPosition && a.compareDocumentPosition(bup) & 16
));
} :
function (a, b) {
if (b) {
while (b) {
b = b.parentNode;
if (b == a) {
return true;
}
}
}
return false;
};
function getSomeDefs(el) {
var p = (el.node.ownerSVGElement && wrap(el.node.ownerSVGElement)) ||
(el.node.parentNode && wrap(el.node.parentNode)) ||
Snap.select("svg") ||
Snap(0, 0),
pdefs = p.select("defs"),
defs = pdefs == null ? false : pdefs.node;
if (!defs) {
defs = make("defs", p.node).node;
}
return defs;
}
function getSomeSVG(el) {
return el.node.ownerSVGElement && wrap(el.node.ownerSVGElement) || Snap.select("svg");
}
Snap._.getSomeDefs = getSomeDefs;
Snap._.getSomeSVG = getSomeSVG;
function unit2px(el, name, value) {
var svg = getSomeSVG(el).node,
out = {},
mgr = svg.querySelector(".svg---mgr");
if (!mgr) {
mgr = $("rect");
$(mgr, {x: -9e9, y: -9e9, width: 10, height: 10, "class": "svg---mgr", fill: "none"});
svg.appendChild(mgr);
}
function getW(val) {
if (val == null) {
return E;
}
if (val == +val) {
return val;
}
$(mgr, {width: val});
try {
return mgr.getBBox().width;
} catch (e) {
return 0;
}
}
function getH(val) {
if (val == null) {
return E;
}
if (val == +val) {
return val;
}
$(mgr, {height: val});
try {
return mgr.getBBox().height;
} catch (e) {
return 0;
}
}
function set(nam, f) {
if (name == null) {
out[nam] = f(el.attr(nam) || 0);
} else if (nam == name) {
out = f(value == null ? el.attr(nam) || 0 : value);
}
}
switch (el.type) {
case "rect":
set("rx", getW);
set("ry", getH);
case "image":
set("width", getW);
set("height", getH);
case "text":
set("x", getW);
set("y", getH);
break;
case "circle":
set("cx", getW);
set("cy", getH);
set("r", getW);
break;
case "ellipse":
set("cx", getW);
set("cy", getH);
set("rx", getW);
set("ry", getH);
break;
case "line":
set("x1", getW);
set("x2", getW);
set("y1", getH);
set("y2", getH);
break;
case "marker":
set("refX", getW);
set("markerWidth", getW);
set("refY", getH);
set("markerHeight", getH);
break;
case "radialGradient":
set("fx", getW);
set("fy", getH);
break;
case "tspan":
set("dx", getW);
set("dy", getH);
break;
default:
set(name, getW);
}
svg.removeChild(mgr);
return out;
}
/*\
* Snap.select
[ method ]
**
* Wraps a DOM element specified by CSS selector as @Element
- query (string) CSS selector of the element
= (Element) the current element
\*/
Snap.select = function (query) {
query = Str(query).replace(/([^\\]):/g, "$1\\:");
return wrap(glob.doc.querySelector(query));
};
/*\
* Snap.selectAll
[ method ]
**
* Wraps DOM elements specified by CSS selector as set or array of @Element
- query (string) CSS selector of the element
= (Element) the current element
\*/
Snap.selectAll = function (query) {
var nodelist = glob.doc.querySelectorAll(query),
set = (Snap.set || Array)();
for (var i = 0; i < nodelist.length; i++) {
set.push(wrap(nodelist[i]));
}
return set;
};
function add2group(list) {
if (!is(list, "array")) {
list = Array.prototype.slice.call(arguments, 0);
}
var i = 0,
j = 0,
node = this.node;
while (this[i]) delete this[i++];
for (i = 0; i < list.length; i++) {
if (list[i].type == "set") {
list[i].forEach(function (el) {
node.appendChild(el.node);
});
} else {
node.appendChild(list[i].node);
}
}
var children = node.childNodes;
for (i = 0; i < children.length; i++) {
this[j++] = wrap(children[i]);
}
return this;
}
// Hub garbage collector every 10s
setInterval(function () {
for (var key in hub) if (hub[has](key)) {
var el = hub[key],
node = el.node;
if (el.type != "svg" && !node.ownerSVGElement || el.type == "svg" && (!node.parentNode || "ownerSVGElement" in node.parentNode && !node.ownerSVGElement)) {
delete hub[key];
}
}
}, 1e4);
function Element(el) {
if (el.snap in hub) {
return hub[el.snap];
}
var svg;
try {
svg = el.ownerSVGElement;
} catch(e) {}
/*\
* Element.node
[ property (object) ]
**
* Gives you a reference to the DOM object, so you can assign event handlers or just mess around.
> Usage
| // draw a circle at coordinate 10,10 with radius of 10
| var c = paper.circle(10, 10, 10);
| c.node.onclick = function () {
| c.attr("fill", "red");
| };
\*/
this.node = el;
if (svg) {
this.paper = new Paper(svg);
}
/*\
* Element.type
[ property (string) ]
**
* SVG tag name of the given element.
\*/
this.type = el.tagName || el.nodeName;
var id = this.id = ID(this);
this.anims = {};
this._ = {
transform: []
};
el.snap = id;
hub[id] = this;
if (this.type == "g") {
this.add = add2group;
}
if (this.type in {g: 1, mask: 1, pattern: 1, symbol: 1}) {
for (var method in Paper.prototype) if (Paper.prototype[has](method)) {
this[method] = Paper.prototype[method];
}
}
}
/*\
* Element.attr
[ method ]
**
* Gets or sets given attributes of the element.
**
- params (object) contains key-value pairs of attributes you want to set
* or
- param (string) name of the attribute
= (Element) the current element
* or
= (string) value of attribute
> Usage
| el.attr({
| fill: "#fc0",
| stroke: "#000",
| strokeWidth: 2, // CamelCase...
| "fill-opacity": 0.5, // or dash-separated names
| width: "*=2" // prefixed values
| });
| console.log(el.attr("fill")); // #fc0
* Prefixed values in format `"+=10"` supported. All four operations
* (`+`, `-`, `*` and `/`) could be used. Optionally you can use units for `+`
* and `-`: `"+=2em"`.
\*/
Element.prototype.attr = function (params, value) {
var el = this,
node = el.node;
if (!params) {
if (node.nodeType != 1) {
return {
text: node.nodeValue
};
}
var attr = node.attributes,
out = {};
for (var i = 0, ii = attr.length; i < ii; i++) {
out[attr[i].nodeName] = attr[i].nodeValue;
}
return out;
}
if (is(params, "string")) {
if (arguments.length > 1) {
var json = {};
json[params] = value;
params = json;
} else {
return eve("snap.util.getattr." + params, el).firstDefined();
}
}
for (var att in params) {
if (params[has](att)) {
eve("snap.util.attr." + att, el, params[att]);
}
}
return el;
};
/*\
* Snap.parse
[ method ]
**
* Parses SVG fragment and converts it into a @Fragment
**
- svg (string) SVG string
= (Fragment) the @Fragment
\*/
Snap.parse = function (svg) {
var f = glob.doc.createDocumentFragment(),
full = true,
div = glob.doc.createElement("div");
svg = Str(svg);
if (!svg.match(/^\s*<\s*svg(?:\s|>)/)) {
svg = "<svg>" + svg + "</svg>";
full = false;
}
div.innerHTML = svg;
svg = div.getElementsByTagName("svg")[0];
if (svg) {
if (full) {
f = svg;
} else {
while (svg.firstChild) {
f.appendChild(svg.firstChild);
}
}
}
return new Fragment(f);
};
function Fragment(frag) {
this.node = frag;
}
/*\
* Snap.fragment
[ method ]
**
* Creates a DOM fragment from a given list of elements or strings
**
- varargs (…) SVG string
= (Fragment) the @Fragment
\*/
Snap.fragment = function () {
var args = Array.prototype.slice.call(arguments, 0),
f = glob.doc.createDocumentFragment();
for (var i = 0, ii = args.length; i < ii; i++) {
var item = args[i];
if (item.node && item.node.nodeType) {
f.appendChild(item.node);
}
if (item.nodeType) {
f.appendChild(item);
}
if (typeof item == "string") {
f.appendChild(Snap.parse(item).node);
}
}
return new Fragment(f);
};
function make(name, parent) {
var res = $(name);
parent.appendChild(res);
var el = wrap(res);
return el;
}
function Paper(w, h) {
var res,
desc,
defs,
proto = Paper.prototype;
if (w && w.tagName == "svg") {
if (w.snap in hub) {
return hub[w.snap];
}
var doc = w.ownerDocument;
res = new Element(w);
desc = w.getElementsByTagName("desc")[0];
defs = w.getElementsByTagName("defs")[0];
if (!desc) {
desc = $("desc");
desc.appendChild(doc.createTextNode("Created with Snap"));
res.node.appendChild(desc);
}
if (!defs) {
defs = $("defs");
res.node.appendChild(defs);
}
res.defs = defs;
for (var key in proto) if (proto[has](key)) {
res[key] = proto[key];
}
res.paper = res.root = res;
} else {
res = make("svg", glob.doc.body);
$(res.node, {
height: h,
version: 1.1,
width: w,
xmlns: xmlns
});
}
return res;
}
function wrap(dom) {
if (!dom) {
return dom;
}
if (dom instanceof Element || dom instanceof Fragment) {
return dom;
}
if (dom.tagName && dom.tagName.toLowerCase() == "svg") {
return new Paper(dom);
}
if (dom.tagName && dom.tagName.toLowerCase() == "object" && dom.type == "image/svg+xml") {
return new Paper(dom.contentDocument.getElementsByTagName("svg")[0]);
}
return new Element(dom);
}
Snap._.make = make;
Snap._.wrap = wrap;
/*\
* Paper.el
[ method ]
**
* Creates an element on paper with a given name and no attributes
**
- name (string) tag name
- attr (object) attributes
= (Element) the current element
> Usage
| var c = paper.circle(10, 10, 10); // is the same as...
| var c = paper.el("circle").attr({
| cx: 10,
| cy: 10,
| r: 10
| });
| // and the same as
| var c = paper.el("circle", {
| cx: 10,
| cy: 10,
| r: 10
| });
\*/
Paper.prototype.el = function (name, attr) {
var el = make(name, this.node);
attr && el.attr(attr);
return el;
};
/*\
* Element.children
[ method ]
**
* Returns array of all the children of the element.
= (array) array of Elements
\*/
Element.prototype.children = function () {
var out = [],
ch = this.node.childNodes;
for (var i = 0, ii = ch.length; i < ii; i++) {
out[i] = Snap(ch[i]);
}
return out;
};
function jsonFiller(root, o) {
for (var i = 0, ii = root.length; i < ii; i++) {
var item = {
type: root[i].type,
attr: root[i].attr()
},
children = root[i].children();
o.push(item);
if (children.length) {
jsonFiller(children, item.childNodes = []);
}
}
}
/*\
* Element.toJSON
[ method ]
**
* Returns object representation of the given element and all its children.
= (object) in format
o {
o type (string) this.type,
o attr (object) attributes map,
o childNodes (array) optional array of children in the same format
o }
\*/
Element.prototype.toJSON = function () {
var out = [];
jsonFiller([this], out);
return out[0];
};
// default
eve.on("snap.util.getattr", function () {
var att = eve.nt();
att = att.substring(att.lastIndexOf(".") + 1);
var css = att.replace(/[A-Z]/g, function (letter) {
return "-" + letter.toLowerCase();
});
if (cssAttr[has](css)) {
return this.node.ownerDocument.defaultView.getComputedStyle(this.node, null).getPropertyValue(css);
} else {
return $(this.node, att);
}
});
var cssAttr = {
"alignment-baseline": 0,
"baseline-shift": 0,
"clip": 0,
"clip-path": 0,
"clip-rule": 0,
"color": 0,
"color-interpolation": 0,
"color-interpolation-filters": 0,
"color-profile": 0,
"color-rendering": 0,
"cursor": 0,
"direction": 0,
"display": 0,
"dominant-baseline": 0,
"enable-background": 0,
"fill": 0,
"fill-opacity": 0,
"fill-rule": 0,
"filter": 0,
"flood-color": 0,
"flood-opacity": 0,
"font": 0,
"font-family": 0,
"font-size": 0,
"font-size-adjust": 0,
"font-stretch": 0,
"font-style": 0,
"font-variant": 0,
"font-weight": 0,
"glyph-orientation-horizontal": 0,
"glyph-orientation-vertical": 0,
"image-rendering": 0,
"kerning": 0,
"letter-spacing": 0,
"lighting-color": 0,
"marker": 0,
"marker-end": 0,
"marker-mid": 0,
"marker-start": 0,
"mask": 0,
"opacity": 0,
"overflow": 0,
"pointer-events": 0,
"shape-rendering": 0,
"stop-color": 0,
"stop-opacity": 0,
"stroke": 0,
"stroke-dasharray": 0,
"stroke-dashoffset": 0,
"stroke-linecap": 0,
"stroke-linejoin": 0,
"stroke-miterlimit": 0,
"stroke-opacity": 0,
"stroke-width": 0,
"text-anchor": 0,
"text-decoration": 0,
"text-rendering": 0,
"unicode-bidi": 0,
"visibility": 0,
"word-spacing": 0,
"writing-mode": 0
};
eve.on("snap.util.attr", function (value) {
var att = eve.nt(),
attr = {};
att = att.substring(att.lastIndexOf(".") + 1);
attr[att] = value;
var style = att.replace(/-(\w)/gi, function (all, letter) {
return letter.toUpperCase();
}),
css = att.replace(/[A-Z]/g, function (letter) {
return "-" + letter.toLowerCase();
});
if (cssAttr[has](css)) {
this.node.style[style] = value == null ? E : value;
} else {
$(this.node, attr);
}
});
(function (proto) {}(Paper.prototype));
// simple ajax
/*\
* Snap.ajax
[ method ]
**
* Simple implementation of Ajax
**
- url (string) URL
- postData (object|string) data for post request
- callback (function) callback
- scope (object) #optional scope of callback
* or
- url (string) URL
- callback (function) callback
- scope (object) #optional scope of callback
= (XMLHttpRequest) the XMLHttpRequest object, just in case
\*/
Snap.ajax = function (url, postData, callback, scope){
var req = new XMLHttpRequest,
id = ID();
if (req) {
if (is(postData, "function")) {
scope = callback;
callback = postData;
postData = null;
} else if (is(postData, "object")) {
var pd = [];
for (var key in postData) if (postData.hasOwnProperty(key)) {
pd.push(encodeURIComponent(key) + "=" + encodeURIComponent(postData[key]));
}
postData = pd.join("&");
}
req.open((postData ? "POST" : "GET"), url, true);
if (postData) {
req.setRequestHeader("X-Requested-With", "XMLHttpRequest");
req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
}
if (callback) {
eve.once("snap.ajax." + id + ".0", callback);
eve.once("snap.ajax." + id + ".200", callback);
eve.once("snap.ajax." + id + ".304", callback);
}
req.onreadystatechange = function() {
if (req.readyState != 4) return;
eve("snap.ajax." + id + "." + req.status, scope, req);
};
if (req.readyState == 4) {
return req;
}
req.send(postData);
return req;
}
};
/*\
* Snap.load
[ method ]
**
* Loads external SVG file as a @Fragment (see @Snap.ajax for more advanced AJAX)
**
- url (string) URL
- callback (function) callback
- scope (object) #optional scope of callback
\*/
Snap.load = function (url, callback, scope) {
Snap.ajax(url, function (req) {
var f = Snap.parse(req.responseText);
scope ? callback.call(scope, f) : callback(f);
});
};
var getOffset = function (elem) {
var box = elem.getBoundingClientRect(),
doc = elem.ownerDocument,
body = doc.body,
docElem = doc.documentElement,
clientTop = docElem.clientTop || body.clientTop || 0, clientLeft = docElem.clientLeft || body.clientLeft || 0,
top = box.top + (g.win.pageYOffset || docElem.scrollTop || body.scrollTop ) - clientTop,
left = box.left + (g.win.pageXOffset || docElem.scrollLeft || body.scrollLeft) - clientLeft;
return {
y: top,
x: left
};
};
/*\
* Snap.getElementByPoint
[ method ]
**
* Returns you topmost element under given point.
**
= (object) Snap element object
- x (number) x coordinate from the top left corner of the window
- y (number) y coordinate from the top left corner of the window
> Usage
| Snap.getElementByPoint(mouseX, mouseY).attr({stroke: "#f00"});
\*/
Snap.getElementByPoint = function (x, y) {
var paper = this,
svg = paper.canvas,
target = glob.doc.elementFromPoint(x, y);
if (glob.win.opera && target.tagName == "svg") {
var so = getOffset(target),
sr = target.createSVGRect();
sr.x = x - so.x;
sr.y = y - so.y;
sr.width = sr.height = 1;
var hits = target.getIntersectionList(sr, null);
if (hits.length) {
target = hits[hits.length - 1];
}
}
if (!target) {
return null;
}
return wrap(target);
};
/*\
* Snap.plugin
[ method ]
**
* Let you write plugins. You pass in a function with five arguments, like this:
| Snap.plugin(function (Snap, Element, Paper, global, Fragment) {
| Snap.newmethod = function () {};
| Element.prototype.newmethod = function () {};
| Paper.prototype.newmethod = function () {};
| });
* Inside the function you have access to all main objects (and their
* prototypes). This allow you to extend anything you want.
**
- f (function) your plugin body
\*/
Snap.plugin = function (f) {
f(Snap, Element, Paper, glob, Fragment);
};
glob.win.Snap = Snap;
return Snap;
}(window || this));
// Copyright (c) 2013 Adobe Systems Incorporated. All rights reserved.
//
// 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.
Snap.plugin(function (Snap, Element, Paper, glob, Fragment) {
var elproto = Element.prototype,
is = Snap.is,
Str = String,
unit2px = Snap._unit2px,
$ = Snap._.$,
make = Snap._.make,
getSomeDefs = Snap._.getSomeDefs,
has = "hasOwnProperty",
wrap = Snap._.wrap;
/*\
* Element.getBBox
[ method ]
**
* Returns the bounding box descriptor for the given element
**
= (object) bounding box descriptor:
o {
o cx: (number) x of the center,
o cy: (number) x of the center,
o h: (number) height,
o height: (number) height,
o path: (string) path command for the box,
o r0: (number) radius of a circle that fully encloses the box,
o r1: (number) radius of the smallest circle that can be enclosed,
o r2: (number) radius of the largest circle that can be enclosed,
o vb: (string) box as a viewbox command,
o w: (number) width,
o width: (number) width,
o x2: (number) x of the right side,
o x: (number) x of the left side,
o y2: (number) y of the bottom edge,
o y: (number) y of the top edge
o }
\*/
elproto.getBBox = function (isWithoutTransform) {
if (!Snap.Matrix || !Snap.path) {
return this.node.getBBox();
}
var el = this,
m = new Snap.Matrix;
if (el.removed) {
return Snap._.box();
}
while (el.type == "use") {
if (!isWithoutTransform) {
m = m.add(el.transform().localMatrix.translate(el.attr("x") || 0, el.attr("y") || 0));
}
if (el.original) {
el = el.original;
} else {
var href = el.attr("xlink:href");
el = el.original = el.node.ownerDocument.getElementById(href.substring(href.indexOf("#") + 1));
}
}
var _ = el._,
pathfinder = Snap.path.get[el.type] || Snap.path.get.deflt;
try {
if (isWithoutTransform) {
_.bboxwt = pathfinder ? Snap.path.getBBox(el.realPath = pathfinder(el)) : Snap._.box(el.node.getBBox());
return Snap._.box(_.bboxwt);
} else {
el.realPath = pathfinder(el);
el.matrix = el.transform().localMatrix;
_.bbox = Snap.path.getBBox(Snap.path.map(el.realPath, m.add(el.matrix)));
return Snap._.box(_.bbox);
}
} catch (e) {
// Firefox doesn’t give you bbox of hidden element
return Snap._.box();
}
};
var propString = function () {
return this.string;
};
function extractTransform(el, tstr) {
if (tstr == null) {
var doReturn = true;
if (el.type == "linearGradient" || el.type == "radialGradient") {
tstr = el.node.getAttribute("gradientTransform");
} else if (el.type == "pattern") {
tstr = el.node.getAttribute("patternTransform");
} else {
tstr = el.node.getAttribute("transform");
}
if (!tstr) {
return new Snap.Matrix;
}
tstr = Snap._.svgTransform2string(tstr);
} else {
if (!Snap._.rgTransform.test(tstr)) {
tstr = Snap._.svgTransform2string(tstr);
} else {
tstr = Str(tstr).replace(/\.{3}|\u2026/g, el._.transform || E);
}
if (is(tstr, "array")) {
tstr = Snap.path ? Snap.path.toString.call(tstr) : Str(tstr);
}
el._.transform = tstr;
}
var m = Snap._.transform2matrix(tstr, el.getBBox(1));
if (doReturn) {
return m;
} else {
el.matrix = m;
}
}
/*\
* Element.transform
[ method ]
**
* Gets or sets transformation of the element
**
- tstr (string) transform string in Snap or SVG format
= (Element) the current element
* or
= (object) transformation descriptor:
o {
o string (string) transform string,
o globalMatrix (Matrix) matrix of all transformations applied to element or its parents,
o localMatrix (Matrix) matrix of transformations applied only to the element,
o diffMatrix (Matrix) matrix of difference between global and local transformations,
o global (string) global transformation as string,
o local (string) local transformation as string,
o toString (function) returns `string` property
o }
\*/
elproto.transform = function (tstr) {
var _ = this._;
if (tstr == null) {
var papa = this,
global = new Snap.Matrix(this.node.getCTM()),
local = extractTransform(this),
ms = [local],
m = new Snap.Matrix,
i,
localString = local.toTransformString(),
string = Str(local) == Str(this.matrix) ?
Str(_.transform) : localString;
while (papa.type != "svg" && (papa = papa.parent())) {
ms.push(extractTransform(papa));
}
i = ms.length;
while (i--) {
m.add(ms[i]);
}
return {
string: string,
globalMatrix: global,
totalMatrix: m,
localMatrix: local,
diffMatrix: global.clone().add(local.invert()),
global: global.toTransformString(),
total: m.toTransformString(),
local: localString,
toString: propString
};
}
if (tstr instanceof Snap.Matrix) {
this.matrix = tstr;
this._.transform = tstr.toTransformString();
} else {
extractTransform(this, tstr);
}
if (this.node) {
if (this.type == "linearGradient" || this.type == "radialGradient") {
$(this.node, {gradientTransform: this.matrix});
} else if (this.type == "pattern") {
$(this.node, {patternTransform: this.matrix});
} else {
$(this.node, {transform: this.matrix});
}
}
return this;
};
/*\
* Element.parent
[ method ]
**
* Returns the element's parent
**
= (Element) the parent element
\*/
elproto.parent = function () {
return wrap(this.node.parentNode);
};
/*\
* Element.append
[ method ]
**
* Appends the given element to current one
**
- el (Element|Set) element to append
= (Element) the parent element
\*/
/*\
* Element.add
[ method ]
**
* See @Element.append
\*/
elproto.append = elproto.add = function (el) {
if (el) {
if (el.type == "set") {
var it = this;
el.forEach(function (el) {
it.add(el);
});
return this;
}
el = wrap(el);
this.node.appendChild(el.node);
el.paper = this.paper;
}
return this;
};
/*\
* Element.appendTo
[ method ]
**
* Appends the current element to the given one
**
- el (Element) parent element to append to
= (Element) the child element
\*/
elproto.appendTo = function (el) {
if (el) {
el = wrap(el);
el.append(this);
}
return this;
};
/*\
* Element.prepend
[ method ]
**
* Prepends the given element to the current one
**
- el (Element) element to prepend
= (Element) the parent element
\*/
elproto.prepend = function (el) {
if (el) {
if (el.type == "set") {
var it = this,
first;
el.forEach(function (el) {
if (first) {
first.after(el);
} else {
it.prepend(el);
}
first = el;
});
return this;
}
el = wrap(el);
var parent = el.parent();
this.node.insertBefore(el.node, this.node.firstChild);
this.add && this.add();
el.paper = this.paper;
this.parent() && this.parent().add();
parent && parent.add();
}
return this;
};
/*\
* Element.prependTo
[ method ]
**
* Prepends the current element to the given one
**
- el (Element) parent element to prepend to
= (Element) the child element
\*/
elproto.prependTo = function (el) {
el = wrap(el);
el.prepend(this);
return this;
};
/*\
* Element.before
[ method ]
**
* Inserts given element before the current one
**
- el (Element) element to insert
= (Element) the parent element
\*/
elproto.before = function (el) {
if (el.type == "set") {
var it = this;
el.forEach(function (el) {
var parent = el.parent();
it.node.parentNode.insertBefore(el.node, it.node);
parent && parent.add();
});
this.parent().add();
return this;
}
el = wrap(el);
var parent = el.parent();
this.node.parentNode.insertBefore(el.node, this.node);
this.parent() && this.parent().add();
parent && parent.add();
el.paper = this.paper;
return this;
};
/*\
* Element.after
[ method ]
**
* Inserts given element after the current one
**
- el (Element) element to insert
= (Element) the parent element
\*/
elproto.after = function (el) {
el = wrap(el);
var parent = el.parent();
if (this.node.nextSibling) {
this.node.parentNode.insertBefore(el.node, this.node.nextSibling);
} else {
this.node.parentNode.appendChild(el.node);
}
this.parent() && this.parent().add();
parent && parent.add();
el.paper = this.paper;
return this;
};
/*\
* Element.insertBefore
[ method ]
**
* Inserts the element after the given one
**
- el (Element) element next to whom insert to
= (Element) the parent element
\*/
elproto.insertBefore = function (el) {
el = wrap(el);
var parent = this.parent();
el.node.parentNode.insertBefore(this.node, el.node);
this.paper = el.paper;
parent && parent.add();
el.parent() && el.parent().add();
return this;
};
/*\
* Element.insertAfter
[ method ]
**
* Inserts the element after the given one
**
- el (Element) element next to whom insert to
= (Element) the parent element
\*/
elproto.insertAfter = function (el) {
el = wrap(el);
var parent = this.parent();
el.node.parentNode.insertBefore(this.node, el.node.nextSibling);
this.paper = el.paper;
parent && parent.add();
el.parent() && el.parent().add();
return this;
};
/*\
* Element.remove
[ method ]
**
* Removes element from the DOM
= (Element) the detached element
\*/
elproto.remove = function () {
var parent = this.parent();
this.node.parentNode && this.node.parentNode.removeChild(this.node);
delete this.paper;
this.removed = true;
parent && parent.add();
return this;
};
/*\
* Element.select
[ method ]
**
* Gathers the nested @Element matching the given set of CSS selectors
**
- query (string) CSS selector
= (Element) result of query selection
\*/
elproto.select = function (query) {
query = Str(query).replace(/([^\\]):/g, "$1\\:");
return wrap(this.node.querySelector(query));
};
/*\
* Element.selectAll
[ method ]
**
* Gathers nested @Element objects matching the given set of CSS selectors
**
- query (string) CSS selector
= (Set|array) result of query selection
\*/
elproto.selectAll = function (query) {
var nodelist = this.node.querySelectorAll(query),
set = (Snap.set || Array)();
for (var i = 0; i < nodelist.length; i++) {
set.push(wrap(nodelist[i]));
}
return set;
};
/*\
* Element.asPX
[ method ]
**
* Returns given attribute of the element as a `px` value (not %, em, etc.)
**
- attr (string) attribute name
- value (string) #optional attribute value
= (Element) result of query selection
\*/
elproto.asPX = function (attr, value) {
if (value == null) {
value = this.attr(attr);
}
return +unit2px(this, attr, value);
};
// SIERRA Element.use(): I suggest adding a note about how to access the original element the returned <use> instantiates. It's a part of SVG with which ordinary web developers may be least familiar.
/*\
* Element.use
[ method ]
**
* Creates a `<use>` element linked to the current element
**
= (Element) the `<use>` element
\*/
elproto.use = function () {
var use,
id = this.node.id;
if (!id) {
id = this.id;
$(this.node, {
id: id
});
}
if (this.type == "linearGradient" || this.type == "radialGradient" ||
this.type == "pattern") {
use = make(this.type, this.node.parentNode);
} else {
use = make("use", this.node.parentNode);
}
$(use.node, {
"xlink:href": "#" + id
});
use.original = this;
return use;
};
function fixids(el) {
var els = el.selectAll("*"),
it,
url = /^\s*url\(("|'|)(.*)\1\)\s*$/,
ids = [],
uses = {};
function urltest(it, name) {
var val = $(it.node, name);
val = val && val.match(url);
val = val && val[2];
if (val && val.charAt() == "#") {
val = val.substring(1);
} else {
return;
}
if (val) {
uses[val] = (uses[val] || []).concat(function (id) {
var attr = {};
attr[name] = URL(id);
$(it.node, attr);
});
}
}
function linktest(it) {
var val = $(it.node, "xlink:href");
if (val && val.charAt() == "#") {
val = val.substring(1);
} else {
return;
}
if (val) {
uses[val] = (uses[val] || []).concat(function (id) {
it.attr("xlink:href", "#" + id);
});
}
}
for (var i = 0, ii = els.length; i < ii; i++) {
it = els[i];
urltest(it, "fill");
urltest(it, "stroke");
urltest(it, "filter");
urltest(it, "mask");
urltest(it, "clip-path");
linktest(it);
var oldid = $(it.node, "id");
if (oldid) {
$(it.node, {id: it.id});
ids.push({
old: oldid,
id: it.id
});
}
}
for (i = 0, ii = ids.length; i < ii; i++) {
var fs = uses[ids[i].old];
if (fs) {
for (var j = 0, jj = fs.length; j < jj; j++) {
fs[j](ids[i].id);
}
}
}
}
/*\
* Element.clone
[ method ]
**
* Creates a clone of the element and inserts it after the element
**
= (Element) the clone
\*/
elproto.clone = function () {
var clone = wrap(this.node.cloneNode(true));
if ($(clone.node, "id")) {
$(clone.node, {id: clone.id});
}
fixids(clone);
clone.insertAfter(this);
return clone;
};
/*\
* Element.toDefs
[ method ]
**
* Moves element to the shared `<defs>` area
**
= (Element) the element
\*/
elproto.toDefs = function () {
var defs = getSomeDefs(this);
defs.appendChild(this.node);
return this;
};
/*\
* Element.toPattern
[ method ]
**
* Creates a `<pattern>` element from the current element
**
* To create a pattern you have to specify the pattern rect:
- x (string|number)
- y (string|number)
- width (string|number)
- height (string|number)
= (Element) the `<pattern>` element
* You can use pattern later on as an argument for `fill` attribute:
| var p = paper.path("M10-5-10,15M15,0,0,15M0-5-20,15").attr({
| fill: "none",
| stroke: "#bada55",
| strokeWidth: 5
| }).pattern(0, 0, 10, 10),
| c = paper.circle(200, 200, 100);
| c.attr({
| fill: p
| });
\*/
elproto.pattern = elproto.toPattern = function (x, y, width, height) {
var p = make("pattern", getSomeDefs(this));
if (x == null) {
x = this.getBBox();
}
if (is(x, "object") && "x" in x) {
y = x.y;
width = x.width;
height = x.height;
x = x.x;
}
$(p.node, {
x: x,
y: y,
width: width,
height: height,
patternUnits: "userSpaceOnUse",
id: p.id,
viewBox: [x, y, width, height].join(" ")
});
p.node.appendChild(this.node);
return p;
};
// SIERRA Element.marker(): clarify what a reference point is. E.g., helps you offset the object from its edge such as when centering it over a path.
// SIERRA Element.marker(): I suggest the method should accept default reference point values. Perhaps centered with (refX = width/2) and (refY = height/2)? Also, couldn't it assume the element's current _width_ and _height_? And please specify what _x_ and _y_ mean: offsets? If so, from where? Couldn't they also be assigned default values?
/*\
* Element.marker
[ method ]
**
* Creates a `<marker>` element from the current element
**
* To create a marker you have to specify the bounding rect and reference point:
- x (number)
- y (number)
- width (number)
- height (number)
- refX (number)
- refY (number)
= (Element) the `<marker>` element
* You can specify the marker later as an argument for `marker-start`, `marker-end`, `marker-mid`, and `marker` attributes. The `marker` attribute places the marker at every point along the path, and `marker-mid` places them at every point except the start and end.
\*/
// TODO add usage for markers
elproto.marker = function (x, y, width, height, refX, refY) {
var p = make("marker", getSomeDefs(this));
if (x == null) {
x = this.getBBox();
}
if (is(x, "object") && "x" in x) {
y = x.y;
width = x.width;
height = x.height;
refX = x.refX || x.cx;
refY = x.refY || x.cy;
x = x.x;
}
$(p.node, {
viewBox: [x, y, width, height].join(" "),
markerWidth: width,
markerHeight: height,
orient: "auto",
refX: refX || 0,
refY: refY || 0,
id: p.id
});
p.node.appendChild(this.node);
return p;
};
// animation
function slice(from, to, f) {
return function (arr) {
var res = arr.slice(from, to);
if (res.length == 1) {
res = res[0];
}
return f ? f(res) : res;
};
}
var Animation = function (attr, ms, easing, callback) {
if (typeof easing == "function" && !easing.length) {
callback = easing;
easing = mina.linear;
}
this.attr = attr;
this.dur = ms;
easing && (this.easing = easing);
callback && (this.callback = callback);
};
Snap._.Animation = Animation;
/*\
* Snap.animation
[ method ]
**
* Creates an animation object
**
- attr (object) attributes of final destination
- duration (number) duration of the animation, in milliseconds
- easing (function) #optional one of easing functions of @mina or custom one
- callback (function) #optional callback function that fires when animation ends
= (object) animation object
\*/
Snap.animation = function (attr, ms, easing, callback) {
return new Animation(attr, ms, easing, callback);
};
/*\
* Element.inAnim
[ method ]
**
* Returns a set of animations that may be able to manipulate the current element
**
= (object) in format:
o {
o anim (object) animation object,
o mina (object) @mina object,
o curStatus (number) 0..1 — status of the animation: 0 — just started, 1 — just finished,
o status (function) gets or sets the status of the animation,
o stop (function) stops the animation
o }
\*/
elproto.inAnim = function () {
var el = this,
res = [];
for (var id in el.anims) if (el.anims[has](id)) {
(function (a) {
res.push({
anim: new Animation(a._attrs, a.dur, a.easing, a._callback),
mina: a,
curStatus: a.status(),
status: function (val) {
return a.status(val);
},
stop: function () {
a.stop();
}
});
}(el.anims[id]));
}
return res;
};
/*\
* Snap.animate
[ method ]
**
* Runs generic animation of one number into another with a caring function
**
- from (number|array) number or array of numbers
- to (number|array) number or array of numbers
- setter (function) caring function that accepts one number argument
- duration (number) duration, in milliseconds
- easing (function) #optional easing function from @mina or custom
- callback (function) #optional callback function to execute when animation ends
= (object) animation object in @mina format
o {
o id (string) animation id, consider it read-only,
o duration (function) gets or sets the duration of the animation,
o easing (function) easing,
o speed (function) gets or sets the speed of the animation,
o status (function) gets or sets the status of the animation,
o stop (function) stops the animation
o }
| var rect = Snap().rect(0, 0, 10, 10);
| Snap.animate(0, 10, function (val) {
| rect.attr({
| x: val
| });
| }, 1000);
| // in given context is equivalent to
| rect.animate({x: 10}, 1000);
\*/
Snap.animate = function (from, to, setter, ms, easing, callback) {
if (typeof easing == "function" && !easing.length) {
callback = easing;
easing = mina.linear;
}
var now = mina.time(),
anim = mina(from, to, now, now + ms, mina.time, setter, easing);
callback && eve.once("mina.finish." + anim.id, callback);
return anim;
};
/*\
* Element.stop
[ method ]
**
* Stops all the animations for the current element
**
= (Element) the current element
\*/
elproto.stop = function () {
var anims = this.inAnim();
for (var i = 0, ii = anims.length; i < ii; i++) {
anims[i].stop();
}
return this;
};
/*\
* Element.animate
[ method ]
**
* Animates the given attributes of the element
**
- attrs (object) key-value pairs of destination attributes
- duration (number) duration of the animation in milliseconds
- easing (function) #optional easing function from @mina or custom
- callback (function) #optional callback function that executes when the animation ends
= (Element) the current element
\*/
elproto.animate = function (attrs, ms, easing, callback) {
if (typeof easing == "function" && !easing.length) {
callback = easing;
easing = mina.linear;
}
if (attrs instanceof Animation) {
callback = attrs.callback;
easing = attrs.easing;
ms = easing.dur;
attrs = attrs.attr;
}
var fkeys = [], tkeys = [], keys = {}, from, to, f, eq,
el = this;
for (var key in attrs) if (attrs[has](key)) {
if (el.equal) {
eq = el.equal(key, Str(attrs[key]));
from = eq.from;
to = eq.to;
f = eq.f;
} else {
from = +el.attr(key);
to = +attrs[key];
}
var len = is(from, "array") ? from.length : 1;
keys[key] = slice(fkeys.length, fkeys.length + len, f);
fkeys = fkeys.concat(from);
tkeys = tkeys.concat(to);
}
var now = mina.time(),
anim = mina(fkeys, tkeys, now, now + ms, mina.time, function (val) {
var attr = {};
for (var key in keys) if (keys[has](key)) {
attr[key] = keys[key](val);
}
el.attr(attr);
}, easing);
el.anims[anim.id] = anim;
anim._attrs = attrs;
anim._callback = callback;
eve("snap.animcreated." + el.id, anim);
eve.once("mina.finish." + anim.id, function () {
delete el.anims[anim.id];
callback && callback.call(el);
});
eve.once("mina.stop." + anim.id, function () {
delete el.anims[anim.id];
});
return el;
};
var eldata = {};
/*\
* Element.data
[ method ]
**
* Adds or retrieves given value associated with given key. (Don’t confuse
* with `data-` attributes)
*
* See also @Element.removeData
- key (string) key to store data
- value (any) #optional value to store
= (object) @Element
* or, if value is not specified:
= (any) value
> Usage
| for (var i = 0, i < 5, i++) {
| paper.circle(10 + 15 * i, 10, 10)
| .attr({fill: "#000"})
| .data("i", i)
| .click(function () {
| alert(this.data("i"));
| });
| }
\*/
elproto.data = function (key, value) {
var data = eldata[this.id] = eldata[this.id] || {};
if (arguments.length == 0){
eve("snap.data.get." + this.id, this, data, null);
return data;
}
if (arguments.length == 1) {
if (Snap.is(key, "object")) {
for (var i in key) if (key[has](i)) {
this.data(i, key[i]);
}
return this;
}
eve("snap.data.get." + this.id, this, data[key], key);
return data[key];
}
data[key] = value;
eve("snap.data.set." + this.id, this, value, key);
return this;
};
/*\
* Element.removeData
[ method ]
**
* Removes value associated with an element by given key.
* If key is not provided, removes all the data of the element.
- key (string) #optional key
= (object) @Element
\*/
elproto.removeData = function (key) {
if (key == null) {
eldata[this.id] = {};
} else {
eldata[this.id] && delete eldata[this.id][key];
}
return this;
};
/*\
* Element.outerSVG
[ method ]
**
* Returns SVG code for the element, equivalent to HTML's `outerHTML`.
*
* See also @Element.innerSVG
= (string) SVG code for the element
\*/
/*\
* Element.toString
[ method ]
**
* See @Element.outerSVG
\*/
elproto.outerSVG = elproto.toString = toString(1);
/*\
* Element.innerSVG
[ method ]
**
* Returns SVG code for the element's contents, equivalent to HTML's `innerHTML`
= (string) SVG code for the element
\*/
elproto.innerSVG = toString();
function toString(type) {
return function () {
var res = type ? "<" + this.type : "",
attr = this.node.attributes,
chld = this.node.childNodes;
if (type) {
for (var i = 0, ii = attr.length; i < ii; i++) {
res += " " + attr[i].name + '="' +
attr[i].value.replace(/"/g, '\\"') + '"';
}
}
if (chld.length) {
type && (res += ">");
for (i = 0, ii = chld.length; i < ii; i++) {
if (chld[i].nodeType == 3) {
res += chld[i].nodeValue;
} else if (chld[i].nodeType == 1) {
res += wrap(chld[i]).toString();
}
}
type && (res += "</" + this.type + ">");
} else {
type && (res += "/>");
}
return res;
};
}
elproto.toDataURL = function () {
if (window && window.btoa) {
var bb = this.getBBox(),
svg = Snap.format('<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="{width}" height="{height}" viewBox="{x} {y} {width} {height}">{contents}</svg>', {
x: +bb.x.toFixed(3),
y: +bb.y.toFixed(3),
width: +bb.width.toFixed(3),
height: +bb.height.toFixed(3),
contents: this.outerSVG()
});
return "data:image/svg+xml;base64," + btoa(unescape(encodeURIComponent(svg)));
}
};
/*\
* Fragment.select
[ method ]
**
* See @Element.select
\*/
Fragment.prototype.select = elproto.select;
/*\
* Fragment.selectAll
[ method ]
**
* See @Element.selectAll
\*/
Fragment.prototype.selectAll = elproto.selectAll;
});
// Copyright (c) 2013 Adobe Systems Incorporated. All rights reserved.
//
// 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.
Snap.plugin(function (Snap, Element, Paper, glob, Fragment) {
var objectToString = Object.prototype.toString,
Str = String,
math = Math,
E = "";
function Matrix(a, b, c, d, e, f) {
if (b == null && objectToString.call(a) == "[object SVGMatrix]") {
this.a = a.a;
this.b = a.b;
this.c = a.c;
this.d = a.d;
this.e = a.e;
this.f = a.f;
return;
}
if (a != null) {
this.a = +a;
this.b = +b;
this.c = +c;
this.d = +d;
this.e = +e;
this.f = +f;
} else {
this.a = 1;
this.b = 0;
this.c = 0;
this.d = 1;
this.e = 0;
this.f = 0;
}
}
(function (matrixproto) {
/*\
* Matrix.add
[ method ]
**
* Adds the given matrix to existing one
- a (number)
- b (number)
- c (number)
- d (number)
- e (number)
- f (number)
* or
- matrix (object) @Matrix
\*/
matrixproto.add = function (a, b, c, d, e, f) {
var out = [[], [], []],
m = [[this.a, this.c, this.e], [this.b, this.d, this.f], [0, 0, 1]],
matrix = [[a, c, e], [b, d, f], [0, 0, 1]],
x, y, z, res;
if (a && a instanceof Matrix) {
matrix = [[a.a, a.c, a.e], [a.b, a.d, a.f], [0, 0, 1]];
}
for (x = 0; x < 3; x++) {
for (y = 0; y < 3; y++) {
res = 0;
for (z = 0; z < 3; z++) {
res += m[x][z] * matrix[z][y];
}
out[x][y] = res;
}
}
this.a = out[0][0];
this.b = out[1][0];
this.c = out[0][1];
this.d = out[1][1];
this.e = out[0][2];
this.f = out[1][2];
return this;
};
/*\
* Matrix.invert
[ method ]
**
* Returns an inverted version of the matrix
= (object) @Matrix
\*/
matrixproto.invert = function () {
var me = this,
x = me.a * me.d - me.b * me.c;
return new Matrix(me.d / x, -me.b / x, -me.c / x, me.a / x, (me.c * me.f - me.d * me.e) / x, (me.b * me.e - me.a * me.f) / x);
};
/*\
* Matrix.clone
[ method ]
**
* Returns a copy of the matrix
= (object) @Matrix
\*/
matrixproto.clone = function () {
return new Matrix(this.a, this.b, this.c, this.d, this.e, this.f);
};
/*\
* Matrix.translate
[ method ]
**
* Translate the matrix
- x (number) horizontal offset distance
- y (number) vertical offset distance
\*/
matrixproto.translate = function (x, y) {
return this.add(1, 0, 0, 1, x, y);
};
/*\
* Matrix.scale
[ method ]
**
* Scales the matrix
- x (number) amount to be scaled, with `1` resulting in no change
- y (number) #optional amount to scale along the vertical axis. (Otherwise `x` applies to both axes.)
- cx (number) #optional horizontal origin point from which to scale
- cy (number) #optional vertical origin point from which to scale
* Default cx, cy is the middle point of the element.
\*/
matrixproto.scale = function (x, y, cx, cy) {
y == null && (y = x);
(cx || cy) && this.add(1, 0, 0, 1, cx, cy);
this.add(x, 0, 0, y, 0, 0);
(cx || cy) && this.add(1, 0, 0, 1, -cx, -cy);
return this;
};
/*\
* Matrix.rotate
[ method ]
**
* Rotates the matrix
- a (number) angle of rotation, in degrees
- x (number) horizontal origin point from which to rotate
- y (number) vertical origin point from which to rotate
\*/
matrixproto.rotate = function (a, x, y) {
a = Snap.rad(a);
x = x || 0;
y = y || 0;
var cos = +math.cos(a).toFixed(9),
sin = +math.sin(a).toFixed(9);
this.add(cos, sin, -sin, cos, x, y);
return this.add(1, 0, 0, 1, -x, -y);
};
/*\
* Matrix.x
[ method ]
**
* Returns x coordinate for given point after transformation described by the matrix. See also @Matrix.y
- x (number)
- y (number)
= (number) x
\*/
matrixproto.x = function (x, y) {
return x * this.a + y * this.c + this.e;
};
/*\
* Matrix.y
[ method ]
**
* Returns y coordinate for given point after transformation described by the matrix. See also @Matrix.x
- x (number)
- y (number)
= (number) y
\*/
matrixproto.y = function (x, y) {
return x * this.b + y * this.d + this.f;
};
matrixproto.get = function (i) {
return +this[Str.fromCharCode(97 + i)].toFixed(4);
};
matrixproto.toString = function () {
return "matrix(" + [this.get(0), this.get(1), this.get(2), this.get(3), this.get(4), this.get(5)].join() + ")";
};
matrixproto.offset = function () {
return [this.e.toFixed(4), this.f.toFixed(4)];
};
function norm(a) {
return a[0] * a[0] + a[1] * a[1];
}
function normalize(a) {
var mag = math.sqrt(norm(a));
a[0] && (a[0] /= mag);
a[1] && (a[1] /= mag);
}
/*\
* Matrix.determinant
[ method ]
**
* Finds determinant of the given matrix.
= (number) determinant
\*/
matrixproto.determinant = function () {
return this.a * this.d - this.b * this.c;
};
/*\
* Matrix.split
[ method ]
**
* Splits matrix into primitive transformations
= (object) in format:
o dx (number) translation by x
o dy (number) translation by y
o scalex (number) scale by x
o scaley (number) scale by y
o shear (number) shear
o rotate (number) rotation in deg
o isSimple (boolean) could it be represented via simple transformations
\*/
matrixproto.split = function () {
var out = {};
// translation
out.dx = this.e;
out.dy = this.f;
// scale and shear
var row = [[this.a, this.c], [this.b, this.d]];
out.scalex = math.sqrt(norm(row[0]));
normalize(row[0]);
out.shear = row[0][0] * row[1][0] + row[0][1] * row[1][1];
row[1] = [row[1][0] - row[0][0] * out.shear, row[1][1] - row[0][1] * out.shear];
out.scaley = math.sqrt(norm(row[1]));
normalize(row[1]);
out.shear /= out.scaley;
if (this.determinant() < 0) {
out.scalex = -out.scalex;
}
// rotation
var sin = -row[0][1],
cos = row[1][1];
if (cos < 0) {
out.rotate = Snap.deg(math.acos(cos));
if (sin < 0) {
out.rotate = 360 - out.rotate;
}
} else {
out.rotate = Snap.deg(math.asin(sin));
}
out.isSimple = !+out.shear.toFixed(9) && (out.scalex.toFixed(9) == out.scaley.toFixed(9) || !out.rotate);
out.isSuperSimple = !+out.shear.toFixed(9) && out.scalex.toFixed(9) == out.scaley.toFixed(9) && !out.rotate;
out.noRotation = !+out.shear.toFixed(9) && !out.rotate;
return out;
};
/*\
* Matrix.toTransformString
[ method ]
**
* Returns transform string that represents given matrix
= (string) transform string
\*/
matrixproto.toTransformString = function (shorter) {
var s = shorter || this.split();
if (!+s.shear.toFixed(9)) {
s.scalex = +s.scalex.toFixed(4);
s.scaley = +s.scaley.toFixed(4);
s.rotate = +s.rotate.toFixed(4);
return (s.dx || s.dy ? "t" + [+s.dx.toFixed(4), +s.dy.toFixed(4)] : E) +
(s.scalex != 1 || s.scaley != 1 ? "s" + [s.scalex, s.scaley, 0, 0] : E) +
(s.rotate ? "r" + [+s.rotate.toFixed(4), 0, 0] : E);
} else {
return "m" + [this.get(0), this.get(1), this.get(2), this.get(3), this.get(4), this.get(5)];
}
};
})(Matrix.prototype);
/*\
* Snap.Matrix
[ method ]
**
* Matrix constructor, extend on your own risk.
* To create matrices use @Snap.matrix.
\*/
Snap.Matrix = Matrix;
/*\
* Snap.matrix
[ method ]
**
* Utility method
**
* Returns a matrix based on the given parameters
- a (number)
- b (number)
- c (number)
- d (number)
- e (number)
- f (number)
* or
- svgMatrix (SVGMatrix)
= (object) @Matrix
\*/
Snap.matrix = function (a, b, c, d, e, f) {
return new Matrix(a, b, c, d, e, f);
};
});
// Copyright (c) 2013 Adobe Systems Incorporated. All rights reserved.
//
// 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.
Snap.plugin(function (Snap, Element, Paper, glob, Fragment) {
var has = "hasOwnProperty",
make = Snap._.make,
wrap = Snap._.wrap,
is = Snap.is,
getSomeDefs = Snap._.getSomeDefs,
reURLValue = /^url\(#?([^)]+)\)$/,
$ = Snap._.$,
URL = Snap.url,
Str = String,
separator = Snap._.separator,
E = "";
// Attributes event handlers
eve.on("snap.util.attr.mask", function (value) {
if (value instanceof Element || value instanceof Fragment) {
eve.stop();
if (value instanceof Fragment && value.node.childNodes.length == 1) {
value = value.node.firstChild;
getSomeDefs(this).appendChild(value);
value = wrap(value);
}
if (value.type == "mask") {
var mask = value;
} else {
mask = make("mask", getSomeDefs(this));
mask.node.appendChild(value.node);
}
!mask.node.id && $(mask.node, {
id: mask.id
});
$(this.node, {
mask: URL(mask.id)
});
}
});
(function (clipIt) {
eve.on("snap.util.attr.clip", clipIt);
eve.on("snap.util.attr.clip-path", clipIt);
eve.on("snap.util.attr.clipPath", clipIt);
}(function (value) {
if (value instanceof Element || value instanceof Fragment) {
eve.stop();
if (value.type == "clipPath") {
var clip = value;
} else {
clip = make("clipPath", getSomeDefs(this));
clip.node.appendChild(value.node);
!clip.node.id && $(clip.node, {
id: clip.id
});
}
$(this.node, {
"clip-path": URL(clip.node.id || clip.id)
});
}
}));
function fillStroke(name) {
return function (value) {
eve.stop();
if (value instanceof Fragment && value.node.childNodes.length == 1 &&
(value.node.firstChild.tagName == "radialGradient" ||
value.node.firstChild.tagName == "linearGradient" ||
value.node.firstChild.tagName == "pattern")) {
value = value.node.firstChild;
getSomeDefs(this).appendChild(value);
value = wrap(value);
}
if (value instanceof Element) {
if (value.type == "radialGradient" || value.type == "linearGradient"
|| value.type == "pattern") {
if (!value.node.id) {
$(value.node, {
id: value.id
});
}
var fill = URL(value.node.id);
} else {
fill = value.attr(name);
}
} else {
fill = Snap.color(value);
if (fill.error) {
var grad = Snap(getSomeDefs(this).ownerSVGElement).gradient(value);
if (grad) {
if (!grad.node.id) {
$(grad.node, {
id: grad.id
});
}
fill = URL(grad.node.id);
} else {
fill = value;
}
} else {
fill = Str(fill);
}
}
var attrs = {};
attrs[name] = fill;
$(this.node, attrs);
this.node.style[name] = E;
};
}
eve.on("snap.util.attr.fill", fillStroke("fill"));
eve.on("snap.util.attr.stroke", fillStroke("stroke"));
var gradrg = /^([lr])(?:\(([^)]*)\))?(.*)$/i;
eve.on("snap.util.grad.parse", function parseGrad(string) {
string = Str(string);
var tokens = string.match(gradrg);
if (!tokens) {
return null;
}
var type = tokens[1],
params = tokens[2],
stops = tokens[3];
params = params.split(/\s*,\s*/).map(function (el) {
return +el == el ? +el : el;
});
if (params.length == 1 && params[0] == 0) {
params = [];
}
stops = stops.split("-");
stops = stops.map(function (el) {
el = el.split(":");
var out = {
color: el[0]
};
if (el[1]) {
out.offset = parseFloat(el[1]);
}
return out;
});
return {
type: type,
params: params,
stops: stops
};
});
eve.on("snap.util.attr.d", function (value) {
eve.stop();
if (is(value, "array") && is(value[0], "array")) {
value = Snap.path.toString.call(value);
}
value = Str(value);
if (value.match(/[ruo]/i)) {
value = Snap.path.toAbsolute(value);
}
$(this.node, {d: value});
})(-1);
eve.on("snap.util.attr.#text", function (value) {
eve.stop();
value = Str(value);
var txt = glob.doc.createTextNode(value);
while (this.node.firstChild) {
this.node.removeChild(this.node.firstChild);
}
this.node.appendChild(txt);
})(-1);
eve.on("snap.util.attr.path", function (value) {
eve.stop();
this.attr({d: value});
})(-1);
eve.on("snap.util.attr.class", function (value) {
eve.stop();
this.node.className.baseVal = value;
})(-1);
eve.on("snap.util.attr.viewBox", function (value) {
var vb;
if (is(value, "object") && "x" in value) {
vb = [value.x, value.y, value.width, value.height].join(" ");
} else if (is(value, "array")) {
vb = value.join(" ");
} else {
vb = value;
}
$(this.node, {
viewBox: vb
});
eve.stop();
})(-1);
eve.on("snap.util.attr.transform", function (value) {
this.transform(value);
eve.stop();
})(-1);
eve.on("snap.util.attr.r", function (value) {
if (this.type == "rect") {
eve.stop();
$(this.node, {
rx: value,
ry: value
});
}
})(-1);
eve.on("snap.util.attr.textpath", function (value) {
eve.stop();
if (this.type == "text") {
var id, tp, node;
if (!value && this.textPath) {
tp = this.textPath;
while (tp.node.firstChild) {
this.node.appendChild(tp.node.firstChild);
}
tp.remove();
delete this.textPath;
return;
}
if (is(value, "string")) {
var defs = getSomeDefs(this),
path = wrap(defs.parentNode).path(value);
defs.appendChild(path.node);
id = path.id;
path.attr({id: id});
} else {
value = wrap(value);
if (value instanceof Element) {
id = value.attr("id");
if (!id) {
id = value.id;
value.attr({id: id});
}
}
}
if (id) {
tp = this.textPath;
node = this.node;
if (tp) {
tp.attr({"xlink:href": "#" + id});
} else {
tp = $("textPath", {
"xlink:href": "#" + id
});
while (node.firstChild) {
tp.appendChild(node.firstChild);
}
node.appendChild(tp);
this.textPath = wrap(tp);
}
}
}
})(-1);
eve.on("snap.util.attr.text", function (value) {
if (this.type == "text") {
var i = 0,
node = this.node,
tuner = function (chunk) {
var out = $("tspan");
if (is(chunk, "array")) {
for (var i = 0; i < chunk.length; i++) {
out.appendChild(tuner(chunk[i]));
}
} else {
out.appendChild(glob.doc.createTextNode(chunk));
}
out.normalize && out.normalize();
return out;
};
while (node.firstChild) {
node.removeChild(node.firstChild);
}
var tuned = tuner(value);
while (tuned.firstChild) {
node.appendChild(tuned.firstChild);
}
}
eve.stop();
})(-1);
function setFontSize(value) {
eve.stop();
if (value == +value) {
value += "px";
}
this.node.style.fontSize = value;
}
eve.on("snap.util.attr.fontSize", setFontSize)(-1);
eve.on("snap.util.attr.font-size", setFontSize)(-1);
eve.on("snap.util.getattr.transform", function () {
eve.stop();
return this.transform();
})(-1);
eve.on("snap.util.getattr.textpath", function () {
eve.stop();
return this.textPath;
})(-1);
// Markers
(function () {
function getter(end) {
return function () {
eve.stop();
var style = glob.doc.defaultView.getComputedStyle(this.node, null).getPropertyValue("marker-" + end);
if (style == "none") {
return style;
} else {
return Snap(glob.doc.getElementById(style.match(reURLValue)[1]));
}
};
}
function setter(end) {
return function (value) {
eve.stop();
var name = "marker" + end.charAt(0).toUpperCase() + end.substring(1);
if (value == "" || !value) {
this.node.style[name] = "none";
return;
}
if (value.type == "marker") {
var id = value.node.id;
if (!id) {
$(value.node, {id: value.id});
}
this.node.style[name] = URL(id);
return;
}
};
}
eve.on("snap.util.getattr.marker-end", getter("end"))(-1);
eve.on("snap.util.getattr.markerEnd", getter("end"))(-1);
eve.on("snap.util.getattr.marker-start", getter("start"))(-1);
eve.on("snap.util.getattr.markerStart", getter("start"))(-1);
eve.on("snap.util.getattr.marker-mid", getter("mid"))(-1);
eve.on("snap.util.getattr.markerMid", getter("mid"))(-1);
eve.on("snap.util.attr.marker-end", setter("end"))(-1);
eve.on("snap.util.attr.markerEnd", setter("end"))(-1);
eve.on("snap.util.attr.marker-start", setter("start"))(-1);
eve.on("snap.util.attr.markerStart", setter("start"))(-1);
eve.on("snap.util.attr.marker-mid", setter("mid"))(-1);
eve.on("snap.util.attr.markerMid", setter("mid"))(-1);
}());
eve.on("snap.util.getattr.r", function () {
if (this.type == "rect" && $(this.node, "rx") == $(this.node, "ry")) {
eve.stop();
return $(this.node, "rx");
}
})(-1);
function textExtract(node) {
var out = [];
var children = node.childNodes;
for (var i = 0, ii = children.length; i < ii; i++) {
var chi = children[i];
if (chi.nodeType == 3) {
out.push(chi.nodeValue);
}
if (chi.tagName == "tspan") {
if (chi.childNodes.length == 1 && chi.firstChild.nodeType == 3) {
out.push(chi.firstChild.nodeValue);
} else {
out.push(textExtract(chi));
}
}
}
return out;
}
eve.on("snap.util.getattr.text", function () {
if (this.type == "text" || this.type == "tspan") {
eve.stop();
var out = textExtract(this.node);
return out.length == 1 ? out[0] : out;
}
})(-1);
eve.on("snap.util.getattr.#text", function () {
return this.node.textContent;
})(-1);
eve.on("snap.util.getattr.viewBox", function () {
eve.stop();
var vb = $(this.node, "viewBox");
if (vb) {
vb = vb.split(separator);
return Snap._.box(+vb[0], +vb[1], +vb[2], +vb[3]);
} else {
return;
}
})(-1);
eve.on("snap.util.getattr.points", function () {
var p = $(this.node, "points");
eve.stop();
if (p) {
return p.split(separator);
} else {
return;
}
})(-1);
eve.on("snap.util.getattr.path", function () {
var p = $(this.node, "d");
eve.stop();
return p;
})(-1);
eve.on("snap.util.getattr.class", function () {
return this.node.className.baseVal;
})(-1);
function getFontSize() {
eve.stop();
return this.node.style.fontSize;
}
eve.on("snap.util.getattr.fontSize", getFontSize)(-1);
eve.on("snap.util.getattr.font-size", getFontSize)(-1);
});
// Copyright (c) 2014 Adobe Systems Incorporated. All rights reserved.
//
// 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.
Snap.plugin(function (Snap, Element, Paper, glob, Fragment) {
var rgNotSpace = /\S+/g,
rgBadSpace = /[\t\r\n\f]/g,
rgTrim = /(^\s+|\s+$)/g,
Str = String,
elproto = Element.prototype;
/*\
* Element.addClass
[ method ]
**
* Adds given class name or list of class names to the element.
- value (string) class name or space separated list of class names
**
= (Element) original element.
\*/
elproto.addClass = function (value) {
var classes = Str(value || "").match(rgNotSpace) || [],
elem = this.node,
className = elem.className.baseVal,
curClasses = className.match(rgNotSpace) || [],
j,
pos,
clazz,
finalValue;
if (classes.length) {
j = 0;
while ((clazz = classes[j++])) {
pos = curClasses.indexOf(clazz);
if (!~pos) {
curClasses.push(clazz);
}
}
finalValue = curClasses.join(" ");
if (className != finalValue) {
elem.className.baseVal = finalValue;
}
}
return this;
};
/*\
* Element.removeClass
[ method ]
**
* Removes given class name or list of class names from the element.
- value (string) class name or space separated list of class names
**
= (Element) original element.
\*/
elproto.removeClass = function (value) {
var classes = Str(value || "").match(rgNotSpace) || [],
elem = this.node,
className = elem.className.baseVal,
curClasses = className.match(rgNotSpace) || [],
j,
pos,
clazz,
finalValue;
if (curClasses.length) {
j = 0;
while ((clazz = classes[j++])) {
pos = curClasses.indexOf(clazz);
if (~pos) {
curClasses.splice(pos, 1);
}
}
finalValue = curClasses.join(" ");
if (className != finalValue) {
elem.className.baseVal = finalValue;
}
}
return this;
};
/*\
* Element.hasClass
[ method ]
**
* Checks if the element has a given class name in the list of class names applied to it.
- value (string) class name
**
= (boolean) `true` if the element has given class
\*/
elproto.hasClass = function (value) {
var elem = this.node,
className = elem.className.baseVal,
curClasses = className.match(rgNotSpace) || [];
return !!~curClasses.indexOf(value);
};
/*\
* Element.toggleClass
[ method ]
**
* Add or remove one or more classes from the element, depending on either
* the class’s presence or the value of the `flag` argument.
- value (string) class name or space separated list of class names
- flag (boolean) value to determine whether the class should be added or removed
**
= (Element) original element.
\*/
elproto.toggleClass = function (value, flag) {
if (flag != null) {
if (flag) {
return this.addClass(value);
} else {
return this.removeClass(value);
}
}
var classes = (value || "").match(rgNotSpace) || [],
elem = this.node,
className = elem.className.baseVal,
curClasses = className.match(rgNotSpace) || [],
j,
pos,
clazz,
finalValue;
j = 0;
while ((clazz = classes[j++])) {
pos = curClasses.indexOf(clazz);
if (~pos) {
curClasses.splice(pos, 1);
} else {
curClasses.push(clazz);
}
}
finalValue = curClasses.join(" ");
if (className != finalValue) {
elem.className.baseVal = finalValue;
}
return this;
};
});
// Copyright (c) 2013 Adobe Systems Incorporated. All rights reserved.
//
// 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.
Snap.plugin(function (Snap, Element, Paper, glob, Fragment) {
var operators = {
"+": function (x, y) {
return x + y;
},
"-": function (x, y) {
return x - y;
},
"/": function (x, y) {
return x / y;
},
"*": function (x, y) {
return x * y;
}
},
Str = String,
reUnit = /[a-z]+$/i,
reAddon = /^\s*([+\-\/*])\s*=\s*([\d.eE+\-]+)\s*([^\d\s]+)?\s*$/;
function getNumber(val) {
return val;
}
function getUnit(unit) {
return function (val) {
return +val.toFixed(3) + unit;
};
}
eve.on("snap.util.attr", function (val) {
var plus = Str(val).match(reAddon);
if (plus) {
var evnt = eve.nt(),
name = evnt.substring(evnt.lastIndexOf(".") + 1),
a = this.attr(name),
atr = {};
eve.stop();
var unit = plus[3] || "",
aUnit = a.match(reUnit),
op = operators[plus[1]];
if (aUnit && aUnit == unit) {
val = op(parseFloat(a), +plus[2]);
} else {
a = this.asPX(name);
val = op(this.asPX(name), this.asPX(name, plus[2] + unit));
}
if (isNaN(a) || isNaN(val)) {
return;
}
atr[name] = val;
this.attr(atr);
}
})(-10);
eve.on("snap.util.equal", function (name, b) {
var A, B, a = Str(this.attr(name) || ""),
el = this,
bplus = Str(b).match(reAddon);
if (bplus) {
eve.stop();
var unit = bplus[3] || "",
aUnit = a.match(reUnit),
op = operators[bplus[1]];
if (aUnit && aUnit == unit) {
return {
from: parseFloat(a),
to: op(parseFloat(a), +bplus[2]),
f: getUnit(aUnit)
};
} else {
a = this.asPX(name);
return {
from: a,
to: op(a, this.asPX(name, bplus[2] + unit)),
f: getNumber
};
}
}
})(-10);
});
// Copyright (c) 2013 Adobe Systems Incorporated. All rights reserved.
//
// 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.
Snap.plugin(function (Snap, Element, Paper, glob, Fragment) {
var proto = Paper.prototype,
is = Snap.is;
/*\
* Paper.rect
[ method ]
*
* Draws a rectangle
**
- x (number) x coordinate of the top left corner
- y (number) y coordinate of the top left corner
- width (number) width
- height (number) height
- rx (number) #optional horizontal radius for rounded corners, default is 0
- ry (number) #optional vertical radius for rounded corners, default is rx or 0
= (object) the `rect` element
**
> Usage
| // regular rectangle
| var c = paper.rect(10, 10, 50, 50);
| // rectangle with rounded corners
| var c = paper.rect(40, 40, 50, 50, 10);
\*/
proto.rect = function (x, y, w, h, rx, ry) {
var attr;
if (ry == null) {
ry = rx;
}
if (is(x, "object") && x == "[object Object]") {
attr = x;
} else if (x != null) {
attr = {
x: x,
y: y,
width: w,
height: h
};
if (rx != null) {
attr.rx = rx;
attr.ry = ry;
}
}
return this.el("rect", attr);
};
/*\
* Paper.circle
[ method ]
**
* Draws a circle
**
- x (number) x coordinate of the centre
- y (number) y coordinate of the centre
- r (number) radius
= (object) the `circle` element
**
> Usage
| var c = paper.circle(50, 50, 40);
\*/
proto.circle = function (cx, cy, r) {
var attr;
if (is(cx, "object") && cx == "[object Object]") {
attr = cx;
} else if (cx != null) {
attr = {
cx: cx,
cy: cy,
r: r
};
}
return this.el("circle", attr);
};
var preload = (function () {
function onerror() {
this.parentNode.removeChild(this);
}
return function (src, f) {
var img = glob.doc.createElement("img"),
body = glob.doc.body;
img.style.cssText = "position:absolute;left:-9999em;top:-9999em";
img.onload = function () {
f.call(img);
img.onload = img.onerror = null;
body.removeChild(img);
};
img.onerror = onerror;
body.appendChild(img);
img.src = src;
};
}());
/*\
* Paper.image
[ method ]
**
* Places an image on the surface
**
- src (string) URI of the source image
- x (number) x offset position
- y (number) y offset position
- width (number) width of the image
- height (number) height of the image
= (object) the `image` element
* or
= (object) Snap element object with type `image`
**
> Usage
| var c = paper.image("apple.png", 10, 10, 80, 80);
\*/
proto.image = function (src, x, y, width, height) {
var el = this.el("image");
if (is(src, "object") && "src" in src) {
el.attr(src);
} else if (src != null) {
var set = {
"xlink:href": src,
preserveAspectRatio: "none"
};
if (x != null && y != null) {
set.x = x;
set.y = y;
}
if (width != null && height != null) {
set.width = width;
set.height = height;
} else {
preload(src, function () {
Snap._.$(el.node, {
width: this.offsetWidth,
height: this.offsetHeight
});
});
}
Snap._.$(el.node, set);
}
return el;
};
/*\
* Paper.ellipse
[ method ]
**
* Draws an ellipse
**
- x (number) x coordinate of the centre
- y (number) y coordinate of the centre
- rx (number) horizontal radius
- ry (number) vertical radius
= (object) the `ellipse` element
**
> Usage
| var c = paper.ellipse(50, 50, 40, 20);
\*/
proto.ellipse = function (cx, cy, rx, ry) {
var attr;
if (is(cx, "object") && cx == "[object Object]") {
attr = cx;
} else if (cx != null) {
attr ={
cx: cx,
cy: cy,
rx: rx,
ry: ry
};
}
return this.el("ellipse", attr);
};
// SIERRA Paper.path(): Unclear from the link what a Catmull-Rom curveto is, and why it would make life any easier.
/*\
* Paper.path
[ method ]
**
* Creates a `<path>` element using the given string as the path's definition
- pathString (string) #optional path string in SVG format
* Path string consists of one-letter commands, followed by comma seprarated arguments in numerical form. Example:
| "M10,20L30,40"
* This example features two commands: `M`, with arguments `(10, 20)` and `L` with arguments `(30, 40)`. Uppercase letter commands express coordinates in absolute terms, while lowercase commands express them in relative terms from the most recently declared coordinates.
*
# <p>Here is short list of commands available, for more details see <a href="http://www.w3.org/TR/SVG/paths.html#PathData" title="Details of a path's data attribute's format are described in the SVG specification.">SVG path string format</a> or <a href="https://developer.mozilla.org/en/SVG/Tutorial/Paths">article about path strings at MDN</a>.</p>
# <table><thead><tr><th>Command</th><th>Name</th><th>Parameters</th></tr></thead><tbody>
# <tr><td>M</td><td>moveto</td><td>(x y)+</td></tr>
# <tr><td>Z</td><td>closepath</td><td>(none)</td></tr>
# <tr><td>L</td><td>lineto</td><td>(x y)+</td></tr>
# <tr><td>H</td><td>horizontal lineto</td><td>x+</td></tr>
# <tr><td>V</td><td>vertical lineto</td><td>y+</td></tr>
# <tr><td>C</td><td>curveto</td><td>(x1 y1 x2 y2 x y)+</td></tr>
# <tr><td>S</td><td>smooth curveto</td><td>(x2 y2 x y)+</td></tr>
# <tr><td>Q</td><td>quadratic Bézier curveto</td><td>(x1 y1 x y)+</td></tr>
# <tr><td>T</td><td>smooth quadratic Bézier curveto</td><td>(x y)+</td></tr>
# <tr><td>A</td><td>elliptical arc</td><td>(rx ry x-axis-rotation large-arc-flag sweep-flag x y)+</td></tr>
# <tr><td>R</td><td><a href="http://en.wikipedia.org/wiki/Catmull–Rom_spline#Catmull.E2.80.93Rom_spline">Catmull-Rom curveto</a>*</td><td>x1 y1 (x y)+</td></tr></tbody></table>
* * _Catmull-Rom curveto_ is a not standard SVG command and added to make life easier.
* Note: there is a special case when a path consists of only three commands: `M10,10R…z`. In this case the path connects back to its starting point.
> Usage
| var c = paper.path("M10 10L90 90");
| // draw a diagonal line:
| // move to 10,10, line to 90,90
\*/
proto.path = function (d) {
var attr;
if (is(d, "object") && !is(d, "array")) {
attr = d;
} else if (d) {
attr = {d: d};
}
return this.el("path", attr);
};
/*\
* Paper.g
[ method ]
**
* Creates a group element
**
- varargs (…) #optional elements to nest within the group
= (object) the `g` element
**
> Usage
| var c1 = paper.circle(),
| c2 = paper.rect(),
| g = paper.g(c2, c1); // note that the order of elements is different
* or
| var c1 = paper.circle(),
| c2 = paper.rect(),
| g = paper.g();
| g.add(c2, c1);
\*/
/*\
* Paper.group
[ method ]
**
* See @Paper.g
\*/
proto.group = proto.g = function (first) {
var attr,
el = this.el("g");
if (arguments.length == 1 && first && !first.type) {
el.attr(first);
} else if (arguments.length) {
el.add(Array.prototype.slice.call(arguments, 0));
}
return el;
};
/*\
* Paper.svg
[ method ]
**
* Creates a nested SVG element.
- x (number) @optional X of the element
- y (number) @optional Y of the element
- width (number) @optional width of the element
- height (number) @optional height of the element
- vbx (number) @optional viewbox X
- vby (number) @optional viewbox Y
- vbw (number) @optional viewbox width
- vbh (number) @optional viewbox height
**
= (object) the `svg` element
**
\*/
proto.svg = function (x, y, width, height, vbx, vby, vbw, vbh) {
var attrs = {};
if (is(x, "object") && y == null) {
attrs = x;
} else {
if (x != null) {
attrs.x = x;
}
if (y != null) {
attrs.y = y;
}
if (width != null) {
attrs.width = width;
}
if (height != null) {
attrs.height = height;
}
if (vbx != null && vby != null && vbw != null && vbh != null) {
attrs.viewBox = [vbx, vby, vbw, vbh];
}
}
return this.el("svg", attrs);
};
/*\
* Paper.mask
[ method ]
**
* Equivalent in behaviour to @Paper.g, except it’s a mask.
**
= (object) the `mask` element
**
\*/
proto.mask = function (first) {
var attr,
el = this.el("mask");
if (arguments.length == 1 && first && !first.type) {
el.attr(first);
} else if (arguments.length) {
el.add(Array.prototype.slice.call(arguments, 0));
}
return el;
};
/*\
* Paper.ptrn
[ method ]
**
* Equivalent in behaviour to @Paper.g, except it’s a pattern.
- x (number) @optional X of the element
- y (number) @optional Y of the element
- width (number) @optional width of the element
- height (number) @optional height of the element
- vbx (number) @optional viewbox X
- vby (number) @optional viewbox Y
- vbw (number) @optional viewbox width
- vbh (number) @optional viewbox height
**
= (object) the `pattern` element
**
\*/
proto.ptrn = function (x, y, width, height, vx, vy, vw, vh) {
if (is(x, "object")) {
var attr = x;
} else {
attr = {patternUnits: "userSpaceOnUse"};
if (x) {
attr.x = x;
}
if (y) {
attr.y = y;
}
if (width != null) {
attr.width = width;
}
if (height != null) {
attr.height = height;
}
if (vx != null && vy != null && vw != null && vh != null) {
attr.viewBox = [vx, vy, vw, vh];
} else {
attr.viewBox = [x || 0, y || 0, width || 0, height || 0];
}
}
return this.el("pattern", attr);
};
/*\
* Paper.use
[ method ]
**
* Creates a <use> element.
- id (string) @optional id of element to link
* or
- id (Element) @optional element to link
**
= (object) the `use` element
**
\*/
proto.use = function (id) {
if (id != null) {
if (id instanceof Element) {
if (!id.attr("id")) {
id.attr({id: Snap._.id(id)});
}
id = id.attr("id");
}
if (String(id).charAt() == "#") {
id = id.substring(1);
}
return this.el("use", {"xlink:href": "#" + id});
} else {
return Element.prototype.use.call(this);
}
};
/*\
* Paper.symbol
[ method ]
**
* Creates a <symbol> element.
- vbx (number) @optional viewbox X
- vby (number) @optional viewbox Y
- vbw (number) @optional viewbox width
- vbh (number) @optional viewbox height
= (object) the `symbol` element
**
\*/
proto.symbol = function (vx, vy, vw, vh) {
var attr = {};
if (vx != null && vy != null && vw != null && vh != null) {
attr.viewBox = [vx, vy, vw, vh];
}
return this.el("symbol", attr);
};
/*\
* Paper.text
[ method ]
**
* Draws a text string
**
- x (number) x coordinate position
- y (number) y coordinate position
- text (string|array) The text string to draw or array of strings to nest within separate `<tspan>` elements
= (object) the `text` element
**
> Usage
| var t1 = paper.text(50, 50, "Snap");
| var t2 = paper.text(50, 50, ["S","n","a","p"]);
| // Text path usage
| t1.attr({textpath: "M10,10L100,100"});
| // or
| var pth = paper.path("M10,10L100,100");
| t1.attr({textpath: pth});
\*/
proto.text = function (x, y, text) {
var attr = {};
if (is(x, "object")) {
attr = x;
} else if (x != null) {
attr = {
x: x,
y: y,
text: text || ""
};
}
return this.el("text", attr);
};
/*\
* Paper.line
[ method ]
**
* Draws a line
**
- x1 (number) x coordinate position of the start
- y1 (number) y coordinate position of the start
- x2 (number) x coordinate position of the end
- y2 (number) y coordinate position of the end
= (object) the `line` element
**
> Usage
| var t1 = paper.line(50, 50, 100, 100);
\*/
proto.line = function (x1, y1, x2, y2) {
var attr = {};
if (is(x1, "object")) {
attr = x1;
} else if (x1 != null) {
attr = {
x1: x1,
x2: x2,
y1: y1,
y2: y2
};
}
return this.el("line", attr);
};
/*\
* Paper.polyline
[ method ]
**
* Draws a polyline
**
- points (array) array of points
* or
- varargs (…) points
= (object) the `polyline` element
**
> Usage
| var p1 = paper.polyline([10, 10, 100, 100]);
| var p2 = paper.polyline(10, 10, 100, 100);
\*/
proto.polyline = function (points) {
if (arguments.length > 1) {
points = Array.prototype.slice.call(arguments, 0);
}
var attr = {};
if (is(points, "object") && !is(points, "array")) {
attr = points;
} else if (points != null) {
attr = {points: points};
}
return this.el("polyline", attr);
};
/*\
* Paper.polygon
[ method ]
**
* Draws a polygon. See @Paper.polyline
\*/
proto.polygon = function (points) {
if (arguments.length > 1) {
points = Array.prototype.slice.call(arguments, 0);
}
var attr = {};
if (is(points, "object") && !is(points, "array")) {
attr = points;
} else if (points != null) {
attr = {points: points};
}
return this.el("polygon", attr);
};
// gradients
(function () {
var $ = Snap._.$;
// gradients' helpers
function Gstops() {
return this.selectAll("stop");
}
function GaddStop(color, offset) {
var stop = $("stop"),
attr = {
offset: +offset + "%"
};
color = Snap.color(color);
attr["stop-color"] = color.hex;
if (color.opacity < 1) {
attr["stop-opacity"] = color.opacity;
}
$(stop, attr);
this.node.appendChild(stop);
return this;
}
function GgetBBox() {
if (this.type == "linearGradient") {
var x1 = $(this.node, "x1") || 0,
x2 = $(this.node, "x2") || 1,
y1 = $(this.node, "y1") || 0,
y2 = $(this.node, "y2") || 0;
return Snap._.box(x1, y1, math.abs(x2 - x1), math.abs(y2 - y1));
} else {
var cx = this.node.cx || .5,
cy = this.node.cy || .5,
r = this.node.r || 0;
return Snap._.box(cx - r, cy - r, r * 2, r * 2);
}
}
function gradient(defs, str) {
var grad = eve("snap.util.grad.parse", null, str).firstDefined(),
el;
if (!grad) {
return null;
}
grad.params.unshift(defs);
if (grad.type.toLowerCase() == "l") {
el = gradientLinear.apply(0, grad.params);
} else {
el = gradientRadial.apply(0, grad.params);
}
if (grad.type != grad.type.toLowerCase()) {
$(el.node, {
gradientUnits: "userSpaceOnUse"
});
}
var stops = grad.stops,
len = stops.length,
start = 0,
j = 0;
function seed(i, end) {
var step = (end - start) / (i - j);
for (var k = j; k < i; k++) {
stops[k].offset = +(+start + step * (k - j)).toFixed(2);
}
j = i;
start = end;
}
len--;
for (var i = 0; i < len; i++) if ("offset" in stops[i]) {
seed(i, stops[i].offset);
}
stops[len].offset = stops[len].offset || 100;
seed(len, stops[len].offset);
for (i = 0; i <= len; i++) {
var stop = stops[i];
el.addStop(stop.color, stop.offset);
}
return el;
}
function gradientLinear(defs, x1, y1, x2, y2) {
var el = Snap._.make("linearGradient", defs);
el.stops = Gstops;
el.addStop = GaddStop;
el.getBBox = GgetBBox;
if (x1 != null) {
$(el.node, {
x1: x1,
y1: y1,
x2: x2,
y2: y2
});
}
return el;
}
function gradientRadial(defs, cx, cy, r, fx, fy) {
var el = Snap._.make("radialGradient", defs);
el.stops = Gstops;
el.addStop = GaddStop;
el.getBBox = GgetBBox;
if (cx != null) {
$(el.node, {
cx: cx,
cy: cy,
r: r
});
}
if (fx != null && fy != null) {
$(el.node, {
fx: fx,
fy: fy
});
}
return el;
}
/*\
* Paper.gradient
[ method ]
**
* Creates a gradient element
**
- gradient (string) gradient descriptor
> Gradient Descriptor
* The gradient descriptor is an expression formatted as
* follows: `<type>(<coords>)<colors>`. The `<type>` can be
* either linear or radial. The uppercase `L` or `R` letters
* indicate absolute coordinates offset from the SVG surface.
* Lowercase `l` or `r` letters indicate coordinates
* calculated relative to the element to which the gradient is
* applied. Coordinates specify a linear gradient vector as
* `x1`, `y1`, `x2`, `y2`, or a radial gradient as `cx`, `cy`,
* `r` and optional `fx`, `fy` specifying a focal point away
* from the center of the circle. Specify `<colors>` as a list
* of dash-separated CSS color values. Each color may be
* followed by a custom offset value, separated with a colon
* character.
> Examples
* Linear gradient, relative from top-left corner to bottom-right
* corner, from black through red to white:
| var g = paper.gradient("l(0, 0, 1, 1)#000-#f00-#fff");
* Linear gradient, absolute from (0, 0) to (100, 100), from black
* through red at 25% to white:
| var g = paper.gradient("L(0, 0, 100, 100)#000-#f00:25-#fff");
* Radial gradient, relative from the center of the element with radius
* half the width, from black to white:
| var g = paper.gradient("r(0.5, 0.5, 0.5)#000-#fff");
* To apply the gradient:
| paper.circle(50, 50, 40).attr({
| fill: g
| });
= (object) the `gradient` element
\*/
proto.gradient = function (str) {
return gradient(this.defs, str);
};
proto.gradientLinear = function (x1, y1, x2, y2) {
return gradientLinear(this.defs, x1, y1, x2, y2);
};
proto.gradientRadial = function (cx, cy, r, fx, fy) {
return gradientRadial(this.defs, cx, cy, r, fx, fy);
};
/*\
* Paper.toString
[ method ]
**
* Returns SVG code for the @Paper
= (string) SVG code for the @Paper
\*/
proto.toString = function () {
var doc = this.node.ownerDocument,
f = doc.createDocumentFragment(),
d = doc.createElement("div"),
svg = this.node.cloneNode(true),
res;
f.appendChild(d);
d.appendChild(svg);
Snap._.$(svg, {xmlns: "http://www.w3.org/2000/svg"});
res = d.innerHTML;
f.removeChild(f.firstChild);
return res;
};
/*\
* Paper.toDataURL
[ method ]
**
* Returns SVG code for the @Paper as Data URI string.
= (string) Data URI string
\*/
proto.toDataURL = function () {
if (window && window.btoa) {
return "data:image/svg+xml;base64," + btoa(unescape(encodeURIComponent(this)));
}
};
/*\
* Paper.clear
[ method ]
**
* Removes all child nodes of the paper, except <defs>.
\*/
proto.clear = function () {
var node = this.node.firstChild,
next;
while (node) {
next = node.nextSibling;
if (node.tagName != "defs") {
node.parentNode.removeChild(node);
} else {
proto.clear.call({node: node});
}
node = next;
}
};
}());
});
// Copyright (c) 2013 Adobe Systems Incorporated. All rights reserved.
//
// 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.
Snap.plugin(function (Snap, Element, Paper, glob) {
var elproto = Element.prototype,
is = Snap.is,
clone = Snap._.clone,
has = "hasOwnProperty",
p2s = /,?([a-z]),?/gi,
toFloat = parseFloat,
math = Math,
PI = math.PI,
mmin = math.min,
mmax = math.max,
pow = math.pow,
abs = math.abs;
function paths(ps) {
var p = paths.ps = paths.ps || {};
if (p[ps]) {
p[ps].sleep = 100;
} else {
p[ps] = {
sleep: 100
};
}
setTimeout(function () {
for (var key in p) if (p[has](key) && key != ps) {
p[key].sleep--;
!p[key].sleep && delete p[key];
}
});
return p[ps];
}
function box(x, y, width, height) {
if (x == null) {
x = y = width = height = 0;
}
if (y == null) {
y = x.y;
width = x.width;
height = x.height;
x = x.x;
}
return {
x: x,
y: y,
width: width,
w: width,
height: height,
h: height,
x2: x + width,
y2: y + height,
cx: x + width / 2,
cy: y + height / 2,
r1: math.min(width, height) / 2,
r2: math.max(width, height) / 2,
r0: math.sqrt(width * width + height * height) / 2,
path: rectPath(x, y, width, height),
vb: [x, y, width, height].join(" ")
};
}
function toString() {
return this.join(",").replace(p2s, "$1");
}
function pathClone(pathArray) {
var res = clone(pathArray);
res.toString = toString;
return res;
}
function getPointAtSegmentLength(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, length) {
if (length == null) {
return bezlen(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y);
} else {
return findDotsAtSegment(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y,
getTotLen(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, length));
}
}
function getLengthFactory(istotal, subpath) {
function O(val) {
return +(+val).toFixed(3);
}
return Snap._.cacher(function (path, length, onlystart) {
if (path instanceof Element) {
path = path.attr("d");
}
path = path2curve(path);
var x, y, p, l, sp = "", subpaths = {}, point,
len = 0;
for (var i = 0, ii = path.length; i < ii; i++) {
p = path[i];
if (p[0] == "M") {
x = +p[1];
y = +p[2];
} else {
l = getPointAtSegmentLength(x, y, p[1], p[2], p[3], p[4], p[5], p[6]);
if (len + l > length) {
if (subpath && !subpaths.start) {
point = getPointAtSegmentLength(x, y, p[1], p[2], p[3], p[4], p[5], p[6], length - len);
sp += [
"C" + O(point.start.x),
O(point.start.y),
O(point.m.x),
O(point.m.y),
O(point.x),
O(point.y)
];
if (onlystart) {return sp;}
subpaths.start = sp;
sp = [
"M" + O(point.x),
O(point.y) + "C" + O(point.n.x),
O(point.n.y),
O(point.end.x),
O(point.end.y),
O(p[5]),
O(p[6])
].join();
len += l;
x = +p[5];
y = +p[6];
continue;
}
if (!istotal && !subpath) {
point = getPointAtSegmentLength(x, y, p[1], p[2], p[3], p[4], p[5], p[6], length - len);
return point;
}
}
len += l;
x = +p[5];
y = +p[6];
}
sp += p.shift() + p;
}
subpaths.end = sp;
point = istotal ? len : subpath ? subpaths : findDotsAtSegment(x, y, p[0], p[1], p[2], p[3], p[4], p[5], 1);
return point;
}, null, Snap._.clone);
}
var getTotalLength = getLengthFactory(1),
getPointAtLength = getLengthFactory(),
getSubpathsAtLength = getLengthFactory(0, 1);
function findDotsAtSegment(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t) {
var t1 = 1 - t,
t13 = pow(t1, 3),
t12 = pow(t1, 2),
t2 = t * t,
t3 = t2 * t,
x = t13 * p1x + t12 * 3 * t * c1x + t1 * 3 * t * t * c2x + t3 * p2x,
y = t13 * p1y + t12 * 3 * t * c1y + t1 * 3 * t * t * c2y + t3 * p2y,
mx = p1x + 2 * t * (c1x - p1x) + t2 * (c2x - 2 * c1x + p1x),
my = p1y + 2 * t * (c1y - p1y) + t2 * (c2y - 2 * c1y + p1y),
nx = c1x + 2 * t * (c2x - c1x) + t2 * (p2x - 2 * c2x + c1x),
ny = c1y + 2 * t * (c2y - c1y) + t2 * (p2y - 2 * c2y + c1y),
ax = t1 * p1x + t * c1x,
ay = t1 * p1y + t * c1y,
cx = t1 * c2x + t * p2x,
cy = t1 * c2y + t * p2y,
alpha = (90 - math.atan2(mx - nx, my - ny) * 180 / PI);
// (mx > nx || my < ny) && (alpha += 180);
return {
x: x,
y: y,
m: {x: mx, y: my},
n: {x: nx, y: ny},
start: {x: ax, y: ay},
end: {x: cx, y: cy},
alpha: alpha
};
}
function bezierBBox(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y) {
if (!Snap.is(p1x, "array")) {
p1x = [p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y];
}
var bbox = curveDim.apply(null, p1x);
return box(
bbox.min.x,
bbox.min.y,
bbox.max.x - bbox.min.x,
bbox.max.y - bbox.min.y
);
}
function isPointInsideBBox(bbox, x, y) {
return x >= bbox.x &&
x <= bbox.x + bbox.width &&
y >= bbox.y &&
y <= bbox.y + bbox.height;
}
function isBBoxIntersect(bbox1, bbox2) {
bbox1 = box(bbox1);
bbox2 = box(bbox2);
return isPointInsideBBox(bbox2, bbox1.x, bbox1.y)
|| isPointInsideBBox(bbox2, bbox1.x2, bbox1.y)
|| isPointInsideBBox(bbox2, bbox1.x, bbox1.y2)
|| isPointInsideBBox(bbox2, bbox1.x2, bbox1.y2)
|| isPointInsideBBox(bbox1, bbox2.x, bbox2.y)
|| isPointInsideBBox(bbox1, bbox2.x2, bbox2.y)
|| isPointInsideBBox(bbox1, bbox2.x, bbox2.y2)
|| isPointInsideBBox(bbox1, bbox2.x2, bbox2.y2)
|| (bbox1.x < bbox2.x2 && bbox1.x > bbox2.x
|| bbox2.x < bbox1.x2 && bbox2.x > bbox1.x)
&& (bbox1.y < bbox2.y2 && bbox1.y > bbox2.y
|| bbox2.y < bbox1.y2 && bbox2.y > bbox1.y);
}
function base3(t, p1, p2, p3, p4) {
var t1 = -3 * p1 + 9 * p2 - 9 * p3 + 3 * p4,
t2 = t * t1 + 6 * p1 - 12 * p2 + 6 * p3;
return t * t2 - 3 * p1 + 3 * p2;
}
function bezlen(x1, y1, x2, y2, x3, y3, x4, y4, z) {
if (z == null) {
z = 1;
}
z = z > 1 ? 1 : z < 0 ? 0 : z;
var z2 = z / 2,
n = 12,
Tvalues = [-.1252,.1252,-.3678,.3678,-.5873,.5873,-.7699,.7699,-.9041,.9041,-.9816,.9816],
Cvalues = [0.2491,0.2491,0.2335,0.2335,0.2032,0.2032,0.1601,0.1601,0.1069,0.1069,0.0472,0.0472],
sum = 0;
for (var i = 0; i < n; i++) {
var ct = z2 * Tvalues[i] + z2,
xbase = base3(ct, x1, x2, x3, x4),
ybase = base3(ct, y1, y2, y3, y4),
comb = xbase * xbase + ybase * ybase;
sum += Cvalues[i] * math.sqrt(comb);
}
return z2 * sum;
}
function getTotLen(x1, y1, x2, y2, x3, y3, x4, y4, ll) {
if (ll < 0 || bezlen(x1, y1, x2, y2, x3, y3, x4, y4) < ll) {
return;
}
var t = 1,
step = t / 2,
t2 = t - step,
l,
e = .01;
l = bezlen(x1, y1, x2, y2, x3, y3, x4, y4, t2);
while (abs(l - ll) > e) {
step /= 2;
t2 += (l < ll ? 1 : -1) * step;
l = bezlen(x1, y1, x2, y2, x3, y3, x4, y4, t2);
}
return t2;
}
function intersect(x1, y1, x2, y2, x3, y3, x4, y4) {
if (
mmax(x1, x2) < mmin(x3, x4) ||
mmin(x1, x2) > mmax(x3, x4) ||
mmax(y1, y2) < mmin(y3, y4) ||
mmin(y1, y2) > mmax(y3, y4)
) {
return;
}
var nx = (x1 * y2 - y1 * x2) * (x3 - x4) - (x1 - x2) * (x3 * y4 - y3 * x4),
ny = (x1 * y2 - y1 * x2) * (y3 - y4) - (y1 - y2) * (x3 * y4 - y3 * x4),
denominator = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4);
if (!denominator) {
return;
}
var px = nx / denominator,
py = ny / denominator,
px2 = +px.toFixed(2),
py2 = +py.toFixed(2);
if (
px2 < +mmin(x1, x2).toFixed(2) ||
px2 > +mmax(x1, x2).toFixed(2) ||
px2 < +mmin(x3, x4).toFixed(2) ||
px2 > +mmax(x3, x4).toFixed(2) ||
py2 < +mmin(y1, y2).toFixed(2) ||
py2 > +mmax(y1, y2).toFixed(2) ||
py2 < +mmin(y3, y4).toFixed(2) ||
py2 > +mmax(y3, y4).toFixed(2)
) {
return;
}
return {x: px, y: py};
}
function inter(bez1, bez2) {
return interHelper(bez1, bez2);
}
function interCount(bez1, bez2) {
return interHelper(bez1, bez2, 1);
}
function interHelper(bez1, bez2, justCount) {
var bbox1 = bezierBBox(bez1),
bbox2 = bezierBBox(bez2);
if (!isBBoxIntersect(bbox1, bbox2)) {
return justCount ? 0 : [];
}
var l1 = bezlen.apply(0, bez1),
l2 = bezlen.apply(0, bez2),
n1 = ~~(l1 / 8),
n2 = ~~(l2 / 8),
dots1 = [],
dots2 = [],
xy = {},
res = justCount ? 0 : [];
for (var i = 0; i < n1 + 1; i++) {
var p = findDotsAtSegment.apply(0, bez1.concat(i / n1));
dots1.push({x: p.x, y: p.y, t: i / n1});
}
for (i = 0; i < n2 + 1; i++) {
p = findDotsAtSegment.apply(0, bez2.concat(i / n2));
dots2.push({x: p.x, y: p.y, t: i / n2});
}
for (i = 0; i < n1; i++) {
for (var j = 0; j < n2; j++) {
var di = dots1[i],
di1 = dots1[i + 1],
dj = dots2[j],
dj1 = dots2[j + 1],
ci = abs(di1.x - di.x) < .001 ? "y" : "x",
cj = abs(dj1.x - dj.x) < .001 ? "y" : "x",
is = intersect(di.x, di.y, di1.x, di1.y, dj.x, dj.y, dj1.x, dj1.y);
if (is) {
if (xy[is.x.toFixed(4)] == is.y.toFixed(4)) {
continue;
}
xy[is.x.toFixed(4)] = is.y.toFixed(4);
var t1 = di.t + abs((is[ci] - di[ci]) / (di1[ci] - di[ci])) * (di1.t - di.t),
t2 = dj.t + abs((is[cj] - dj[cj]) / (dj1[cj] - dj[cj])) * (dj1.t - dj.t);
if (t1 >= 0 && t1 <= 1 && t2 >= 0 && t2 <= 1) {
if (justCount) {
res++;
} else {
res.push({
x: is.x,
y: is.y,
t1: t1,
t2: t2
});
}
}
}
}
}
return res;
}
function pathIntersection(path1, path2) {
return interPathHelper(path1, path2);
}
function pathIntersectionNumber(path1, path2) {
return interPathHelper(path1, path2, 1);
}
function interPathHelper(path1, path2, justCount) {
path1 = path2curve(path1);
path2 = path2curve(path2);
var x1, y1, x2, y2, x1m, y1m, x2m, y2m, bez1, bez2,
res = justCount ? 0 : [];
for (var i = 0, ii = path1.length; i < ii; i++) {
var pi = path1[i];
if (pi[0] == "M") {
x1 = x1m = pi[1];
y1 = y1m = pi[2];
} else {
if (pi[0] == "C") {
bez1 = [x1, y1].concat(pi.slice(1));
x1 = bez1[6];
y1 = bez1[7];
} else {
bez1 = [x1, y1, x1, y1, x1m, y1m, x1m, y1m];
x1 = x1m;
y1 = y1m;
}
for (var j = 0, jj = path2.length; j < jj; j++) {
var pj = path2[j];
if (pj[0] == "M") {
x2 = x2m = pj[1];
y2 = y2m = pj[2];
} else {
if (pj[0] == "C") {
bez2 = [x2, y2].concat(pj.slice(1));
x2 = bez2[6];
y2 = bez2[7];
} else {
bez2 = [x2, y2, x2, y2, x2m, y2m, x2m, y2m];
x2 = x2m;
y2 = y2m;
}
var intr = interHelper(bez1, bez2, justCount);
if (justCount) {
res += intr;
} else {
for (var k = 0, kk = intr.length; k < kk; k++) {
intr[k].segment1 = i;
intr[k].segment2 = j;
intr[k].bez1 = bez1;
intr[k].bez2 = bez2;
}
res = res.concat(intr);
}
}
}
}
}
return res;
}
function isPointInsidePath(path, x, y) {
var bbox = pathBBox(path);
return isPointInsideBBox(bbox, x, y) &&
interPathHelper(path, [["M", x, y], ["H", bbox.x2 + 10]], 1) % 2 == 1;
}
function pathBBox(path) {
var pth = paths(path);
if (pth.bbox) {
return clone(pth.bbox);
}
if (!path) {
return box();
}
path = path2curve(path);
var x = 0,
y = 0,
X = [],
Y = [],
p;
for (var i = 0, ii = path.length; i < ii; i++) {
p = path[i];
if (p[0] == "M") {
x = p[1];
y = p[2];
X.push(x);
Y.push(y);
} else {
var dim = curveDim(x, y, p[1], p[2], p[3], p[4], p[5], p[6]);
X = X.concat(dim.min.x, dim.max.x);
Y = Y.concat(dim.min.y, dim.max.y);
x = p[5];
y = p[6];
}
}
var xmin = mmin.apply(0, X),
ymin = mmin.apply(0, Y),
xmax = mmax.apply(0, X),
ymax = mmax.apply(0, Y),
bb = box(xmin, ymin, xmax - xmin, ymax - ymin);
pth.bbox = clone(bb);
return bb;
}
function rectPath(x, y, w, h, r) {
if (r) {
return [
["M", +x + (+r), y],
["l", w - r * 2, 0],
["a", r, r, 0, 0, 1, r, r],
["l", 0, h - r * 2],
["a", r, r, 0, 0, 1, -r, r],
["l", r * 2 - w, 0],
["a", r, r, 0, 0, 1, -r, -r],
["l", 0, r * 2 - h],
["a", r, r, 0, 0, 1, r, -r],
["z"]
];
}
var res = [["M", x, y], ["l", w, 0], ["l", 0, h], ["l", -w, 0], ["z"]];
res.toString = toString;
return res;
}
function ellipsePath(x, y, rx, ry, a) {
if (a == null && ry == null) {
ry = rx;
}
x = +x;
y = +y;
rx = +rx;
ry = +ry;
if (a != null) {
var rad = Math.PI / 180,
x1 = x + rx * Math.cos(-ry * rad),
x2 = x + rx * Math.cos(-a * rad),
y1 = y + rx * Math.sin(-ry * rad),
y2 = y + rx * Math.sin(-a * rad),
res = [["M", x1, y1], ["A", rx, rx, 0, +(a - ry > 180), 0, x2, y2]];
} else {
res = [
["M", x, y],
["m", 0, -ry],
["a", rx, ry, 0, 1, 1, 0, 2 * ry],
["a", rx, ry, 0, 1, 1, 0, -2 * ry],
["z"]
];
}
res.toString = toString;
return res;
}
var unit2px = Snap._unit2px,
getPath = {
path: function (el) {
return el.attr("path");
},
circle: function (el) {
var attr = unit2px(el);
return ellipsePath(attr.cx, attr.cy, attr.r);
},
ellipse: function (el) {
var attr = unit2px(el);
return ellipsePath(attr.cx || 0, attr.cy || 0, attr.rx, attr.ry);
},
rect: function (el) {
var attr = unit2px(el);
return rectPath(attr.x || 0, attr.y || 0, attr.width, attr.height, attr.rx, attr.ry);
},
image: function (el) {
var attr = unit2px(el);
return rectPath(attr.x || 0, attr.y || 0, attr.width, attr.height);
},
line: function (el) {
return "M" + [el.attr("x1") || 0, el.attr("y1") || 0, el.attr("x2"), el.attr("y2")];
},
polyline: function (el) {
return "M" + el.attr("points");
},
polygon: function (el) {
return "M" + el.attr("points") + "z";
},
deflt: function (el) {
var bbox = el.node.getBBox();
return rectPath(bbox.x, bbox.y, bbox.width, bbox.height);
}
};
function pathToRelative(pathArray) {
var pth = paths(pathArray),
lowerCase = String.prototype.toLowerCase;
if (pth.rel) {
return pathClone(pth.rel);
}
if (!Snap.is(pathArray, "array") || !Snap.is(pathArray && pathArray[0], "array")) {
pathArray = Snap.parsePathString(pathArray);
}
var res = [],
x = 0,
y = 0,
mx = 0,
my = 0,
start = 0;
if (pathArray[0][0] == "M") {
x = pathArray[0][1];
y = pathArray[0][2];
mx = x;
my = y;
start++;
res.push(["M", x, y]);
}
for (var i = start, ii = pathArray.length; i < ii; i++) {
var r = res[i] = [],
pa = pathArray[i];
if (pa[0] != lowerCase.call(pa[0])) {
r[0] = lowerCase.call(pa[0]);
switch (r[0]) {
case "a":
r[1] = pa[1];
r[2] = pa[2];
r[3] = pa[3];
r[4] = pa[4];
r[5] = pa[5];
r[6] = +(pa[6] - x).toFixed(3);
r[7] = +(pa[7] - y).toFixed(3);
break;
case "v":
r[1] = +(pa[1] - y).toFixed(3);
break;
case "m":
mx = pa[1];
my = pa[2];
default:
for (var j = 1, jj = pa.length; j < jj; j++) {
r[j] = +(pa[j] - ((j % 2) ? x : y)).toFixed(3);
}
}
} else {
r = res[i] = [];
if (pa[0] == "m") {
mx = pa[1] + x;
my = pa[2] + y;
}
for (var k = 0, kk = pa.length; k < kk; k++) {
res[i][k] = pa[k];
}
}
var len = res[i].length;
switch (res[i][0]) {
case "z":
x = mx;
y = my;
break;
case "h":
x += +res[i][len - 1];
break;
case "v":
y += +res[i][len - 1];
break;
default:
x += +res[i][len - 2];
y += +res[i][len - 1];
}
}
res.toString = toString;
pth.rel = pathClone(res);
return res;
}
function pathToAbsolute(pathArray) {
var pth = paths(pathArray);
if (pth.abs) {
return pathClone(pth.abs);
}
if (!is(pathArray, "array") || !is(pathArray && pathArray[0], "array")) { // rough assumption
pathArray = Snap.parsePathString(pathArray);
}
if (!pathArray || !pathArray.length) {
return [["M", 0, 0]];
}
var res = [],
x = 0,
y = 0,
mx = 0,
my = 0,
start = 0,
pa0;
if (pathArray[0][0] == "M") {
x = +pathArray[0][1];
y = +pathArray[0][2];
mx = x;
my = y;
start++;
res[0] = ["M", x, y];
}
var crz = pathArray.length == 3 &&
pathArray[0][0] == "M" &&
pathArray[1][0].toUpperCase() == "R" &&
pathArray[2][0].toUpperCase() == "Z";
for (var r, pa, i = start, ii = pathArray.length; i < ii; i++) {
res.push(r = []);
pa = pathArray[i];
pa0 = pa[0];
if (pa0 != pa0.toUpperCase()) {
r[0] = pa0.toUpperCase();
switch (r[0]) {
case "A":
r[1] = pa[1];
r[2] = pa[2];
r[3] = pa[3];
r[4] = pa[4];
r[5] = pa[5];
r[6] = +pa[6] + x;
r[7] = +pa[7] + y;
break;
case "V":
r[1] = +pa[1] + y;
break;
case "H":
r[1] = +pa[1] + x;
break;
case "R":
var dots = [x, y].concat(pa.slice(1));
for (var j = 2, jj = dots.length; j < jj; j++) {
dots[j] = +dots[j] + x;
dots[++j] = +dots[j] + y;
}
res.pop();
res = res.concat(catmullRom2bezier(dots, crz));
break;
case "O":
res.pop();
dots = ellipsePath(x, y, pa[1], pa[2]);
dots.push(dots[0]);
res = res.concat(dots);
break;
case "U":
res.pop();
res = res.concat(ellipsePath(x, y, pa[1], pa[2], pa[3]));
r = ["U"].concat(res[res.length - 1].slice(-2));
break;
case "M":
mx = +pa[1] + x;
my = +pa[2] + y;
default:
for (j = 1, jj = pa.length; j < jj; j++) {
r[j] = +pa[j] + ((j % 2) ? x : y);
}
}
} else if (pa0 == "R") {
dots = [x, y].concat(pa.slice(1));
res.pop();
res = res.concat(catmullRom2bezier(dots, crz));
r = ["R"].concat(pa.slice(-2));
} else if (pa0 == "O") {
res.pop();
dots = ellipsePath(x, y, pa[1], pa[2]);
dots.push(dots[0]);
res = res.concat(dots);
} else if (pa0 == "U") {
res.pop();
res = res.concat(ellipsePath(x, y, pa[1], pa[2], pa[3]));
r = ["U"].concat(res[res.length - 1].slice(-2));
} else {
for (var k = 0, kk = pa.length; k < kk; k++) {
r[k] = pa[k];
}
}
pa0 = pa0.toUpperCase();
if (pa0 != "O") {
switch (r[0]) {
case "Z":
x = +mx;
y = +my;
break;
case "H":
x = r[1];
break;
case "V":
y = r[1];
break;
case "M":
mx = r[r.length - 2];
my = r[r.length - 1];
default:
x = r[r.length - 2];
y = r[r.length - 1];
}
}
}
res.toString = toString;
pth.abs = pathClone(res);
return res;
}
function l2c(x1, y1, x2, y2) {
return [x1, y1, x2, y2, x2, y2];
}
function q2c(x1, y1, ax, ay, x2, y2) {
var _13 = 1 / 3,
_23 = 2 / 3;
return [
_13 * x1 + _23 * ax,
_13 * y1 + _23 * ay,
_13 * x2 + _23 * ax,
_13 * y2 + _23 * ay,
x2,
y2
];
}
function a2c(x1, y1, rx, ry, angle, large_arc_flag, sweep_flag, x2, y2, recursive) {
// for more information of where this math came from visit:
// http://www.w3.org/TR/SVG11/implnote.html#ArcImplementationNotes
var _120 = PI * 120 / 180,
rad = PI / 180 * (+angle || 0),
res = [],
xy,
rotate = Snap._.cacher(function (x, y, rad) {
var X = x * math.cos(rad) - y * math.sin(rad),
Y = x * math.sin(rad) + y * math.cos(rad);
return {x: X, y: Y};
});
if (!recursive) {
xy = rotate(x1, y1, -rad);
x1 = xy.x;
y1 = xy.y;
xy = rotate(x2, y2, -rad);
x2 = xy.x;
y2 = xy.y;
var cos = math.cos(PI / 180 * angle),
sin = math.sin(PI / 180 * angle),
x = (x1 - x2) / 2,
y = (y1 - y2) / 2;
var h = (x * x) / (rx * rx) + (y * y) / (ry * ry);
if (h > 1) {
h = math.sqrt(h);
rx = h * rx;
ry = h * ry;
}
var rx2 = rx * rx,
ry2 = ry * ry,
k = (large_arc_flag == sweep_flag ? -1 : 1) *
math.sqrt(abs((rx2 * ry2 - rx2 * y * y - ry2 * x * x) / (rx2 * y * y + ry2 * x * x))),
cx = k * rx * y / ry + (x1 + x2) / 2,
cy = k * -ry * x / rx + (y1 + y2) / 2,
f1 = math.asin(((y1 - cy) / ry).toFixed(9)),
f2 = math.asin(((y2 - cy) / ry).toFixed(9));
f1 = x1 < cx ? PI - f1 : f1;
f2 = x2 < cx ? PI - f2 : f2;
f1 < 0 && (f1 = PI * 2 + f1);
f2 < 0 && (f2 = PI * 2 + f2);
if (sweep_flag && f1 > f2) {
f1 = f1 - PI * 2;
}
if (!sweep_flag && f2 > f1) {
f2 = f2 - PI * 2;
}
} else {
f1 = recursive[0];
f2 = recursive[1];
cx = recursive[2];
cy = recursive[3];
}
var df = f2 - f1;
if (abs(df) > _120) {
var f2old = f2,
x2old = x2,
y2old = y2;
f2 = f1 + _120 * (sweep_flag && f2 > f1 ? 1 : -1);
x2 = cx + rx * math.cos(f2);
y2 = cy + ry * math.sin(f2);
res = a2c(x2, y2, rx, ry, angle, 0, sweep_flag, x2old, y2old, [f2, f2old, cx, cy]);
}
df = f2 - f1;
var c1 = math.cos(f1),
s1 = math.sin(f1),
c2 = math.cos(f2),
s2 = math.sin(f2),
t = math.tan(df / 4),
hx = 4 / 3 * rx * t,
hy = 4 / 3 * ry * t,
m1 = [x1, y1],
m2 = [x1 + hx * s1, y1 - hy * c1],
m3 = [x2 + hx * s2, y2 - hy * c2],
m4 = [x2, y2];
m2[0] = 2 * m1[0] - m2[0];
m2[1] = 2 * m1[1] - m2[1];
if (recursive) {
return [m2, m3, m4].concat(res);
} else {
res = [m2, m3, m4].concat(res).join().split(",");
var newres = [];
for (var i = 0, ii = res.length; i < ii; i++) {
newres[i] = i % 2 ? rotate(res[i - 1], res[i], rad).y : rotate(res[i], res[i + 1], rad).x;
}
return newres;
}
}
function findDotAtSegment(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t) {
var t1 = 1 - t;
return {
x: pow(t1, 3) * p1x + pow(t1, 2) * 3 * t * c1x + t1 * 3 * t * t * c2x + pow(t, 3) * p2x,
y: pow(t1, 3) * p1y + pow(t1, 2) * 3 * t * c1y + t1 * 3 * t * t * c2y + pow(t, 3) * p2y
};
}
// Returns bounding box of cubic bezier curve.
// Source: http://blog.hackers-cafe.net/2009/06/how-to-calculate-bezier-curves-bounding.html
// Original version: <NAME>
// Modifications: https://github.com/timo22345
function curveDim(x0, y0, x1, y1, x2, y2, x3, y3) {
var tvalues = [],
bounds = [[], []],
a, b, c, t, t1, t2, b2ac, sqrtb2ac;
for (var i = 0; i < 2; ++i) {
if (i == 0) {
b = 6 * x0 - 12 * x1 + 6 * x2;
a = -3 * x0 + 9 * x1 - 9 * x2 + 3 * x3;
c = 3 * x1 - 3 * x0;
} else {
b = 6 * y0 - 12 * y1 + 6 * y2;
a = -3 * y0 + 9 * y1 - 9 * y2 + 3 * y3;
c = 3 * y1 - 3 * y0;
}
if (abs(a) < 1e-12) {
if (abs(b) < 1e-12) {
continue;
}
t = -c / b;
if (0 < t && t < 1) {
tvalues.push(t);
}
continue;
}
b2ac = b * b - 4 * c * a;
sqrtb2ac = math.sqrt(b2ac);
if (b2ac < 0) {
continue;
}
t1 = (-b + sqrtb2ac) / (2 * a);
if (0 < t1 && t1 < 1) {
tvalues.push(t1);
}
t2 = (-b - sqrtb2ac) / (2 * a);
if (0 < t2 && t2 < 1) {
tvalues.push(t2);
}
}
var x, y, j = tvalues.length,
jlen = j,
mt;
while (j--) {
t = tvalues[j];
mt = 1 - t;
bounds[0][j] = (mt * mt * mt * x0) + (3 * mt * mt * t * x1) + (3 * mt * t * t * x2) + (t * t * t * x3);
bounds[1][j] = (mt * mt * mt * y0) + (3 * mt * mt * t * y1) + (3 * mt * t * t * y2) + (t * t * t * y3);
}
bounds[0][jlen] = x0;
bounds[1][jlen] = y0;
bounds[0][jlen + 1] = x3;
bounds[1][jlen + 1] = y3;
bounds[0].length = bounds[1].length = jlen + 2;
return {
min: {x: mmin.apply(0, bounds[0]), y: mmin.apply(0, bounds[1])},
max: {x: mmax.apply(0, bounds[0]), y: mmax.apply(0, bounds[1])}
};
}
function path2curve(path, path2) {
var pth = !path2 && paths(path);
if (!path2 && pth.curve) {
return pathClone(pth.curve);
}
var p = pathToAbsolute(path),
p2 = path2 && pathToAbsolute(path2),
attrs = {x: 0, y: 0, bx: 0, by: 0, X: 0, Y: 0, qx: null, qy: null},
attrs2 = {x: 0, y: 0, bx: 0, by: 0, X: 0, Y: 0, qx: null, qy: null},
processPath = function (path, d, pcom) {
var nx, ny;
if (!path) {
return ["C", d.x, d.y, d.x, d.y, d.x, d.y];
}
!(path[0] in {T: 1, Q: 1}) && (d.qx = d.qy = null);
switch (path[0]) {
case "M":
d.X = path[1];
d.Y = path[2];
break;
case "A":
path = ["C"].concat(a2c.apply(0, [d.x, d.y].concat(path.slice(1))));
break;
case "S":
if (pcom == "C" || pcom == "S") { // In "S" case we have to take into account, if the previous command is C/S.
nx = d.x * 2 - d.bx; // And reflect the previous
ny = d.y * 2 - d.by; // command's control point relative to the current point.
}
else { // or some else or nothing
nx = d.x;
ny = d.y;
}
path = ["C", nx, ny].concat(path.slice(1));
break;
case "T":
if (pcom == "Q" || pcom == "T") { // In "T" case we have to take into account, if the previous command is Q/T.
d.qx = d.x * 2 - d.qx; // And make a reflection similar
d.qy = d.y * 2 - d.qy; // to case "S".
}
else { // or something else or nothing
d.qx = d.x;
d.qy = d.y;
}
path = ["C"].concat(q2c(d.x, d.y, d.qx, d.qy, path[1], path[2]));
break;
case "Q":
d.qx = path[1];
d.qy = path[2];
path = ["C"].concat(q2c(d.x, d.y, path[1], path[2], path[3], path[4]));
break;
case "L":
path = ["C"].concat(l2c(d.x, d.y, path[1], path[2]));
break;
case "H":
path = ["C"].concat(l2c(d.x, d.y, path[1], d.y));
break;
case "V":
path = ["C"].concat(l2c(d.x, d.y, d.x, path[1]));
break;
case "Z":
path = ["C"].concat(l2c(d.x, d.y, d.X, d.Y));
break;
}
return path;
},
fixArc = function (pp, i) {
if (pp[i].length > 7) {
pp[i].shift();
var pi = pp[i];
while (pi.length) {
pcoms1[i] = "A"; // if created multiple C:s, their original seg is saved
p2 && (pcoms2[i] = "A"); // the same as above
pp.splice(i++, 0, ["C"].concat(pi.splice(0, 6)));
}
pp.splice(i, 1);
ii = mmax(p.length, p2 && p2.length || 0);
}
},
fixM = function (path1, path2, a1, a2, i) {
if (path1 && path2 && path1[i][0] == "M" && path2[i][0] != "M") {
path2.splice(i, 0, ["M", a2.x, a2.y]);
a1.bx = 0;
a1.by = 0;
a1.x = path1[i][1];
a1.y = path1[i][2];
ii = mmax(p.length, p2 && p2.length || 0);
}
},
pcoms1 = [], // path commands of original path p
pcoms2 = [], // path commands of original path p2
pfirst = "", // temporary holder for original path command
pcom = ""; // holder for previous path command of original path
for (var i = 0, ii = mmax(p.length, p2 && p2.length || 0); i < ii; i++) {
p[i] && (pfirst = p[i][0]); // save current path command
if (pfirst != "C") // C is not saved yet, because it may be result of conversion
{
pcoms1[i] = pfirst; // Save current path command
i && ( pcom = pcoms1[i - 1]); // Get previous path command pcom
}
p[i] = processPath(p[i], attrs, pcom); // Previous path command is inputted to processPath
if (pcoms1[i] != "A" && pfirst == "C") pcoms1[i] = "C"; // A is the only command
// which may produce multiple C:s
// so we have to make sure that C is also C in original path
fixArc(p, i); // fixArc adds also the right amount of A:s to pcoms1
if (p2) { // the same procedures is done to p2
p2[i] && (pfirst = p2[i][0]);
if (pfirst != "C") {
pcoms2[i] = pfirst;
i && (pcom = pcoms2[i - 1]);
}
p2[i] = processPath(p2[i], attrs2, pcom);
if (pcoms2[i] != "A" && pfirst == "C") {
pcoms2[i] = "C";
}
fixArc(p2, i);
}
fixM(p, p2, attrs, attrs2, i);
fixM(p2, p, attrs2, attrs, i);
var seg = p[i],
seg2 = p2 && p2[i],
seglen = seg.length,
seg2len = p2 && seg2.length;
attrs.x = seg[seglen - 2];
attrs.y = seg[seglen - 1];
attrs.bx = toFloat(seg[seglen - 4]) || attrs.x;
attrs.by = toFloat(seg[seglen - 3]) || attrs.y;
attrs2.bx = p2 && (toFloat(seg2[seg2len - 4]) || attrs2.x);
attrs2.by = p2 && (toFloat(seg2[seg2len - 3]) || attrs2.y);
attrs2.x = p2 && seg2[seg2len - 2];
attrs2.y = p2 && seg2[seg2len - 1];
}
if (!p2) {
pth.curve = pathClone(p);
}
return p2 ? [p, p2] : p;
}
function mapPath(path, matrix) {
if (!matrix) {
return path;
}
var x, y, i, j, ii, jj, pathi;
path = path2curve(path);
for (i = 0, ii = path.length; i < ii; i++) {
pathi = path[i];
for (j = 1, jj = pathi.length; j < jj; j += 2) {
x = matrix.x(pathi[j], pathi[j + 1]);
y = matrix.y(pathi[j], pathi[j + 1]);
pathi[j] = x;
pathi[j + 1] = y;
}
}
return path;
}
// http://schepers.cc/getting-to-the-point
function catmullRom2bezier(crp, z) {
var d = [];
for (var i = 0, iLen = crp.length; iLen - 2 * !z > i; i += 2) {
var p = [
{x: +crp[i - 2], y: +crp[i - 1]},
{x: +crp[i], y: +crp[i + 1]},
{x: +crp[i + 2], y: +crp[i + 3]},
{x: +crp[i + 4], y: +crp[i + 5]}
];
if (z) {
if (!i) {
p[0] = {x: +crp[iLen - 2], y: +crp[iLen - 1]};
} else if (iLen - 4 == i) {
p[3] = {x: +crp[0], y: +crp[1]};
} else if (iLen - 2 == i) {
p[2] = {x: +crp[0], y: +crp[1]};
p[3] = {x: +crp[2], y: +crp[3]};
}
} else {
if (iLen - 4 == i) {
p[3] = p[2];
} else if (!i) {
p[0] = {x: +crp[i], y: +crp[i + 1]};
}
}
d.push(["C",
(-p[0].x + 6 * p[1].x + p[2].x) / 6,
(-p[0].y + 6 * p[1].y + p[2].y) / 6,
(p[1].x + 6 * p[2].x - p[3].x) / 6,
(p[1].y + 6*p[2].y - p[3].y) / 6,
p[2].x,
p[2].y
]);
}
return d;
}
// export
Snap.path = paths;
/*\
* Snap.path.getTotalLength
[ method ]
**
* Returns the length of the given path in pixels
**
- path (string) SVG path string
**
= (number) length
\*/
Snap.path.getTotalLength = getTotalLength;
/*\
* Snap.path.getPointAtLength
[ method ]
**
* Returns the coordinates of the point located at the given length along the given path
**
- path (string) SVG path string
- length (number) length, in pixels, from the start of the path, excluding non-rendering jumps
**
= (object) representation of the point:
o {
o x: (number) x coordinate,
o y: (number) y coordinate,
o alpha: (number) angle of derivative
o }
\*/
Snap.path.getPointAtLength = getPointAtLength;
/*\
* Snap.path.getSubpath
[ method ]
**
* Returns the subpath of a given path between given start and end lengths
**
- path (string) SVG path string
- from (number) length, in pixels, from the start of the path to the start of the segment
- to (number) length, in pixels, from the start of the path to the end of the segment
**
= (string) path string definition for the segment
\*/
Snap.path.getSubpath = function (path, from, to) {
if (this.getTotalLength(path) - to < 1e-6) {
return getSubpathsAtLength(path, from).end;
}
var a = getSubpathsAtLength(path, to, 1);
return from ? getSubpathsAtLength(a, from).end : a;
};
/*\
* Element.getTotalLength
[ method ]
**
* Returns the length of the path in pixels (only works for `path` elements)
= (number) length
\*/
elproto.getTotalLength = function () {
if (this.node.getTotalLength) {
return this.node.getTotalLength();
}
};
// SIERRA Element.getPointAtLength()/Element.getTotalLength(): If a <path> is broken into different segments, is the jump distance to the new coordinates set by the _M_ or _m_ commands calculated as part of the path's total length?
/*\
* Element.getPointAtLength
[ method ]
**
* Returns coordinates of the point located at the given length on the given path (only works for `path` elements)
**
- length (number) length, in pixels, from the start of the path, excluding non-rendering jumps
**
= (object) representation of the point:
o {
o x: (number) x coordinate,
o y: (number) y coordinate,
o alpha: (number) angle of derivative
o }
\*/
elproto.getPointAtLength = function (length) {
return getPointAtLength(this.attr("d"), length);
};
// SIERRA Element.getSubpath(): Similar to the problem for Element.getPointAtLength(). Unclear how this would work for a segmented path. Overall, the concept of _subpath_ and what I'm calling a _segment_ (series of non-_M_ or _Z_ commands) is unclear.
/*\
* Element.getSubpath
[ method ]
**
* Returns subpath of a given element from given start and end lengths (only works for `path` elements)
**
- from (number) length, in pixels, from the start of the path to the start of the segment
- to (number) length, in pixels, from the start of the path to the end of the segment
**
= (string) path string definition for the segment
\*/
elproto.getSubpath = function (from, to) {
return Snap.path.getSubpath(this.attr("d"), from, to);
};
Snap._.box = box;
/*\
* Snap.path.findDotsAtSegment
[ method ]
**
* Utility method
**
* Finds dot coordinates on the given cubic beziér curve at the given t
- p1x (number) x of the first point of the curve
- p1y (number) y of the first point of the curve
- c1x (number) x of the first anchor of the curve
- c1y (number) y of the first anchor of the curve
- c2x (number) x of the second anchor of the curve
- c2y (number) y of the second anchor of the curve
- p2x (number) x of the second point of the curve
- p2y (number) y of the second point of the curve
- t (number) position on the curve (0..1)
= (object) point information in format:
o {
o x: (number) x coordinate of the point,
o y: (number) y coordinate of the point,
o m: {
o x: (number) x coordinate of the left anchor,
o y: (number) y coordinate of the left anchor
o },
o n: {
o x: (number) x coordinate of the right anchor,
o y: (number) y coordinate of the right anchor
o },
o start: {
o x: (number) x coordinate of the start of the curve,
o y: (number) y coordinate of the start of the curve
o },
o end: {
o x: (number) x coordinate of the end of the curve,
o y: (number) y coordinate of the end of the curve
o },
o alpha: (number) angle of the curve derivative at the point
o }
\*/
Snap.path.findDotsAtSegment = findDotsAtSegment;
/*\
* Snap.path.bezierBBox
[ method ]
**
* Utility method
**
* Returns the bounding box of a given cubic beziér curve
- p1x (number) x of the first point of the curve
- p1y (number) y of the first point of the curve
- c1x (number) x of the first anchor of the curve
- c1y (number) y of the first anchor of the curve
- c2x (number) x of the second anchor of the curve
- c2y (number) y of the second anchor of the curve
- p2x (number) x of the second point of the curve
- p2y (number) y of the second point of the curve
* or
- bez (array) array of six points for beziér curve
= (object) bounding box
o {
o x: (number) x coordinate of the left top point of the box,
o y: (number) y coordinate of the left top point of the box,
o x2: (number) x coordinate of the right bottom point of the box,
o y2: (number) y coordinate of the right bottom point of the box,
o width: (number) width of the box,
o height: (number) height of the box
o }
\*/
Snap.path.bezierBBox = bezierBBox;
/*\
* Snap.path.isPointInsideBBox
[ method ]
**
* Utility method
**
* Returns `true` if given point is inside bounding box
- bbox (string) bounding box
- x (string) x coordinate of the point
- y (string) y coordinate of the point
= (boolean) `true` if point is inside
\*/
Snap.path.isPointInsideBBox = isPointInsideBBox;
Snap.closest = function (x, y, X, Y) {
var r = 100,
b = box(x - r / 2, y - r / 2, r, r),
inside = [],
getter = X[0].hasOwnProperty("x") ? function (i) {
return {
x: X[i].x,
y: X[i].y
};
} : function (i) {
return {
x: X[i],
y: Y[i]
};
},
found = 0;
while (r <= 1e6 && !found) {
for (var i = 0, ii = X.length; i < ii; i++) {
var xy = getter(i);
if (isPointInsideBBox(b, xy.x, xy.y)) {
found++;
inside.push(xy);
break;
}
}
if (!found) {
r *= 2;
b = box(x - r / 2, y - r / 2, r, r)
}
}
if (r == 1e6) {
return;
}
var len = Infinity,
res;
for (i = 0, ii = inside.length; i < ii; i++) {
var l = Snap.len(x, y, inside[i].x, inside[i].y);
if (len > l) {
len = l;
inside[i].len = l;
res = inside[i];
}
}
return res;
};
/*\
* Snap.path.isBBoxIntersect
[ method ]
**
* Utility method
**
* Returns `true` if two bounding boxes intersect
- bbox1 (string) first bounding box
- bbox2 (string) second bounding box
= (boolean) `true` if bounding boxes intersect
\*/
Snap.path.isBBoxIntersect = isBBoxIntersect;
/*\
* Snap.path.intersection
[ method ]
**
* Utility method
**
* Finds intersections of two paths
- path1 (string) path string
- path2 (string) path string
= (array) dots of intersection
o [
o {
o x: (number) x coordinate of the point,
o y: (number) y coordinate of the point,
o t1: (number) t value for segment of path1,
o t2: (number) t value for segment of path2,
o segment1: (number) order number for segment of path1,
o segment2: (number) order number for segment of path2,
o bez1: (array) eight coordinates representing beziér curve for the segment of path1,
o bez2: (array) eight coordinates representing beziér curve for the segment of path2
o }
o ]
\*/
Snap.path.intersection = pathIntersection;
Snap.path.intersectionNumber = pathIntersectionNumber;
/*\
* Snap.path.isPointInside
[ method ]
**
* Utility method
**
* Returns `true` if given point is inside a given closed path.
*
* Note: fill mode doesn’t affect the result of this method.
- path (string) path string
- x (number) x of the point
- y (number) y of the point
= (boolean) `true` if point is inside the path
\*/
Snap.path.isPointInside = isPointInsidePath;
/*\
* Snap.path.getBBox
[ method ]
**
* Utility method
**
* Returns the bounding box of a given path
- path (string) path string
= (object) bounding box
o {
o x: (number) x coordinate of the left top point of the box,
o y: (number) y coordinate of the left top point of the box,
o x2: (number) x coordinate of the right bottom point of the box,
o y2: (number) y coordinate of the right bottom point of the box,
o width: (number) width of the box,
o height: (number) height of the box
o }
\*/
Snap.path.getBBox = pathBBox;
Snap.path.get = getPath;
/*\
* Snap.path.toRelative
[ method ]
**
* Utility method
**
* Converts path coordinates into relative values
- path (string) path string
= (array) path string
\*/
Snap.path.toRelative = pathToRelative;
/*\
* Snap.path.toAbsolute
[ method ]
**
* Utility method
**
* Converts path coordinates into absolute values
- path (string) path string
= (array) path string
\*/
Snap.path.toAbsolute = pathToAbsolute;
/*\
* Snap.path.toCubic
[ method ]
**
* Utility method
**
* Converts path to a new path where all segments are cubic beziér curves
- pathString (string|array) path string or array of segments
= (array) array of segments
\*/
Snap.path.toCubic = path2curve;
/*\
* Snap.path.map
[ method ]
**
* Transform the path string with the given matrix
- path (string) path string
- matrix (object) see @Matrix
= (string) transformed path string
\*/
Snap.path.map = mapPath;
Snap.path.toString = toString;
Snap.path.clone = pathClone;
});
// Copyright (c) 2013 Adobe Systems Incorporated. All rights reserved.
//
// 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.
Snap.plugin(function (Snap, Element, Paper, glob) {
var mmax = Math.max,
mmin = Math.min;
// Set
var Set = function (items) {
this.items = [];
this.bindings = {};
this.length = 0;
this.type = "set";
if (items) {
for (var i = 0, ii = items.length; i < ii; i++) {
if (items[i]) {
this[this.items.length] = this.items[this.items.length] = items[i];
this.length++;
}
}
}
},
setproto = Set.prototype;
/*\
* Set.push
[ method ]
**
* Adds each argument to the current set
= (object) original element
\*/
setproto.push = function () {
var item,
len;
for (var i = 0, ii = arguments.length; i < ii; i++) {
item = arguments[i];
if (item) {
len = this.items.length;
this[len] = this.items[len] = item;
this.length++;
}
}
return this;
};
/*\
* Set.pop
[ method ]
**
* Removes last element and returns it
= (object) element
\*/
setproto.pop = function () {
this.length && delete this[this.length--];
return this.items.pop();
};
/*\
* Set.forEach
[ method ]
**
* Executes given function for each element in the set
*
* If the function returns `false`, the loop stops running.
**
- callback (function) function to run
- thisArg (object) context object for the callback
= (object) Set object
\*/
setproto.forEach = function (callback, thisArg) {
for (var i = 0, ii = this.items.length; i < ii; i++) {
if (callback.call(thisArg, this.items[i], i) === false) {
return this;
}
}
return this;
};
/*\
* Set.animate
[ method ]
**
* Animates each element in set in sync.
*
**
- attrs (object) key-value pairs of destination attributes
- duration (number) duration of the animation in milliseconds
- easing (function) #optional easing function from @mina or custom
- callback (function) #optional callback function that executes when the animation ends
* or
- animation (array) array of animation parameter for each element in set in format `[attrs, duration, easing, callback]`
> Usage
| // animate all elements in set to radius 10
| set.animate({r: 10}, 500, mina.easein);
| // or
| // animate first element to radius 10, but second to radius 20 and in different time
| set.animate([{r: 10}, 500, mina.easein], [{r: 20}, 1500, mina.easein]);
= (Element) the current element
\*/
setproto.animate = function (attrs, ms, easing, callback) {
if (typeof easing == "function" && !easing.length) {
callback = easing;
easing = mina.linear;
}
if (attrs instanceof Snap._.Animation) {
callback = attrs.callback;
easing = attrs.easing;
ms = easing.dur;
attrs = attrs.attr;
}
var args = arguments;
if (Snap.is(attrs, "array") && Snap.is(args[args.length - 1], "array")) {
var each = true;
}
var begin,
handler = function () {
if (begin) {
this.b = begin;
} else {
begin = this.b;
}
},
cb = 0,
set = this,
callbacker = callback && function () {
if (++cb == set.length) {
callback.call(this);
}
};
return this.forEach(function (el, i) {
eve.once("snap.animcreated." + el.id, handler);
if (each) {
args[i] && el.animate.apply(el, args[i]);
} else {
el.animate(attrs, ms, easing, callbacker);
}
});
};
setproto.remove = function () {
while (this.length) {
this.pop().remove();
}
return this;
};
/*\
* Set.bind
[ method ]
**
* Specifies how to handle a specific attribute when applied
* to a set.
*
**
- attr (string) attribute name
- callback (function) function to run
* or
- attr (string) attribute name
- element (Element) specific element in the set to apply the attribute to
* or
- attr (string) attribute name
- element (Element) specific element in the set to apply the attribute to
- eattr (string) attribute on the element to bind the attribute to
= (object) Set object
\*/
setproto.bind = function (attr, a, b) {
var data = {};
if (typeof a == "function") {
this.bindings[attr] = a;
} else {
var aname = b || attr;
this.bindings[attr] = function (v) {
data[aname] = v;
a.attr(data);
};
}
return this;
};
setproto.attr = function (value) {
var unbound = {};
for (var k in value) {
if (this.bindings[k]) {
this.bindings[k](value[k]);
} else {
unbound[k] = value[k];
}
}
for (var i = 0, ii = this.items.length; i < ii; i++) {
this.items[i].attr(unbound);
}
return this;
};
/*\
* Set.clear
[ method ]
**
* Removes all elements from the set
\*/
setproto.clear = function () {
while (this.length) {
this.pop();
}
};
/*\
* Set.splice
[ method ]
**
* Removes range of elements from the set
**
- index (number) position of the deletion
- count (number) number of element to remove
- insertion… (object) #optional elements to insert
= (object) set elements that were deleted
\*/
setproto.splice = function (index, count, insertion) {
index = index < 0 ? mmax(this.length + index, 0) : index;
count = mmax(0, mmin(this.length - index, count));
var tail = [],
todel = [],
args = [],
i;
for (i = 2; i < arguments.length; i++) {
args.push(arguments[i]);
}
for (i = 0; i < count; i++) {
todel.push(this[index + i]);
}
for (; i < this.length - index; i++) {
tail.push(this[index + i]);
}
var arglen = args.length;
for (i = 0; i < arglen + tail.length; i++) {
this.items[index + i] = this[index + i] = i < arglen ? args[i] : tail[i - arglen];
}
i = this.items.length = this.length -= count - arglen;
while (this[i]) {
delete this[i++];
}
return new Set(todel);
};
/*\
* Set.exclude
[ method ]
**
* Removes given element from the set
**
- element (object) element to remove
= (boolean) `true` if object was found and removed from the set
\*/
setproto.exclude = function (el) {
for (var i = 0, ii = this.length; i < ii; i++) if (this[i] == el) {
this.splice(i, 1);
return true;
}
return false;
};
setproto.insertAfter = function (el) {
var i = this.items.length;
while (i--) {
this.items[i].insertAfter(el);
}
return this;
};
setproto.getBBox = function () {
var x = [],
y = [],
x2 = [],
y2 = [];
for (var i = this.items.length; i--;) if (!this.items[i].removed) {
var box = this.items[i].getBBox();
x.push(box.x);
y.push(box.y);
x2.push(box.x + box.width);
y2.push(box.y + box.height);
}
x = mmin.apply(0, x);
y = mmin.apply(0, y);
x2 = mmax.apply(0, x2);
y2 = mmax.apply(0, y2);
return {
x: x,
y: y,
x2: x2,
y2: y2,
width: x2 - x,
height: y2 - y,
cx: x + (x2 - x) / 2,
cy: y + (y2 - y) / 2
};
};
setproto.clone = function (s) {
s = new Set;
for (var i = 0, ii = this.items.length; i < ii; i++) {
s.push(this.items[i].clone());
}
return s;
};
setproto.toString = function () {
return "Snap\u2018s set";
};
setproto.type = "set";
// export
Snap.Set = Set;
Snap.set = function () {
var set = new Set;
if (arguments.length) {
set.push.apply(set, Array.prototype.slice.call(arguments, 0));
}
return set;
};
});
// Copyright (c) 2013 Adobe Systems Incorporated. All rights reserved.
//
// 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.
Snap.plugin(function (Snap, Element, Paper, glob) {
var names = {},
reUnit = /[a-z]+$/i,
Str = String;
names.stroke = names.fill = "colour";
function getEmpty(item) {
var l = item[0];
switch (l.toLowerCase()) {
case "t": return [l, 0, 0];
case "m": return [l, 1, 0, 0, 1, 0, 0];
case "r": if (item.length == 4) {
return [l, 0, item[2], item[3]];
} else {
return [l, 0];
}
case "s": if (item.length == 5) {
return [l, 1, 1, item[3], item[4]];
} else if (item.length == 3) {
return [l, 1, 1];
} else {
return [l, 1];
}
}
}
function equaliseTransform(t1, t2, getBBox) {
t2 = Str(t2).replace(/\.{3}|\u2026/g, t1);
t1 = Snap.parseTransformString(t1) || [];
t2 = Snap.parseTransformString(t2) || [];
var maxlength = Math.max(t1.length, t2.length),
from = [],
to = [],
i = 0, j, jj,
tt1, tt2;
for (; i < maxlength; i++) {
tt1 = t1[i] || getEmpty(t2[i]);
tt2 = t2[i] || getEmpty(tt1);
if ((tt1[0] != tt2[0]) ||
(tt1[0].toLowerCase() == "r" && (tt1[2] != tt2[2] || tt1[3] != tt2[3])) ||
(tt1[0].toLowerCase() == "s" && (tt1[3] != tt2[3] || tt1[4] != tt2[4]))
) {
t1 = Snap._.transform2matrix(t1, getBBox());
t2 = Snap._.transform2matrix(t2, getBBox());
from = [["m", t1.a, t1.b, t1.c, t1.d, t1.e, t1.f]];
to = [["m", t2.a, t2.b, t2.c, t2.d, t2.e, t2.f]];
break;
}
from[i] = [];
to[i] = [];
for (j = 0, jj = Math.max(tt1.length, tt2.length); j < jj; j++) {
j in tt1 && (from[i][j] = tt1[j]);
j in tt2 && (to[i][j] = tt2[j]);
}
}
return {
from: path2array(from),
to: path2array(to),
f: getPath(from)
};
}
function getNumber(val) {
return val;
}
function getUnit(unit) {
return function (val) {
return +val.toFixed(3) + unit;
};
}
function getViewBox(val) {
return val.join(" ");
}
function getColour(clr) {
return Snap.rgb(clr[0], clr[1], clr[2]);
}
function getPath(path) {
var k = 0, i, ii, j, jj, out, a, b = [];
for (i = 0, ii = path.length; i < ii; i++) {
out = "[";
a = ['"' + path[i][0] + '"'];
for (j = 1, jj = path[i].length; j < jj; j++) {
a[j] = "val[" + (k++) + "]";
}
out += a + "]";
b[i] = out;
}
return Function("val", "return Snap.path.toString.call([" + b + "])");
}
function path2array(path) {
var out = [];
for (var i = 0, ii = path.length; i < ii; i++) {
for (var j = 1, jj = path[i].length; j < jj; j++) {
out.push(path[i][j]);
}
}
return out;
}
function isNumeric(obj) {
return isFinite(parseFloat(obj));
}
function arrayEqual(arr1, arr2) {
if (!Snap.is(arr1, "array") || !Snap.is(arr2, "array")) {
return false;
}
return arr1.toString() == arr2.toString();
}
Element.prototype.equal = function (name, b) {
return eve("snap.util.equal", this, name, b).firstDefined();
};
eve.on("snap.util.equal", function (name, b) {
var A, B, a = Str(this.attr(name) || ""),
el = this;
if (isNumeric(a) && isNumeric(b)) {
return {
from: parseFloat(a),
to: parseFloat(b),
f: getNumber
};
}
if (names[name] == "colour") {
A = Snap.color(a);
B = Snap.color(b);
return {
from: [A.r, A.g, A.b, A.opacity],
to: [B.r, B.g, B.b, B.opacity],
f: getColour
};
}
if (name == "viewBox") {
A = this.attr(name).vb.split(" ").map(Number);
B = b.split(" ").map(Number);
return {
from: A,
to: B,
f: getViewBox
};
}
if (name == "transform" || name == "gradientTransform" || name == "patternTransform") {
if (b instanceof Snap.Matrix) {
b = b.toTransformString();
}
if (!Snap._.rgTransform.test(b)) {
b = Snap._.svgTransform2string(b);
}
return equaliseTransform(a, b, function () {
return el.getBBox(1);
});
}
if (name == "d" || name == "path") {
A = Snap.path.toCubic(a, b);
return {
from: path2array(A[0]),
to: path2array(A[1]),
f: getPath(A[0])
};
}
if (name == "points") {
A = Str(a).split(Snap._.separator);
B = Str(b).split(Snap._.separator);
return {
from: A,
to: B,
f: function (val) { return val; }
};
}
var aUnit = a.match(reUnit),
bUnit = Str(b).match(reUnit);
if (aUnit && arrayEqual(aUnit, bUnit)) {
return {
from: parseFloat(a),
to: parseFloat(b),
f: getUnit(aUnit)
};
} else {
return {
from: this.asPX(name),
to: this.asPX(name, b),
f: getNumber
};
}
});
});
// Copyright (c) 2013 Adobe Systems Incorporated. All rights reserved.
//
// 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.
Snap.plugin(function (Snap, Element, Paper, glob) {
var elproto = Element.prototype,
has = "hasOwnProperty",
supportsTouch = "createTouch" in glob.doc,
events = [
"click", "dblclick", "mousedown", "mousemove", "mouseout",
"mouseover", "mouseup", "touchstart", "touchmove", "touchend",
"touchcancel"
],
touchMap = {
mousedown: "touchstart",
mousemove: "touchmove",
mouseup: "touchend"
},
getScroll = function (xy, el) {
var name = xy == "y" ? "scrollTop" : "scrollLeft",
doc = el && el.node ? el.node.ownerDocument : glob.doc;
return doc[name in doc.documentElement ? "documentElement" : "body"][name];
},
preventDefault = function () {
this.returnValue = false;
},
preventTouch = function () {
return this.originalEvent.preventDefault();
},
stopPropagation = function () {
this.cancelBubble = true;
},
stopTouch = function () {
return this.originalEvent.stopPropagation();
},
addEvent = function (obj, type, fn, element) {
var realName = supportsTouch && touchMap[type] ? touchMap[type] : type,
f = function (e) {
var scrollY = getScroll("y", element),
scrollX = getScroll("x", element);
if (supportsTouch && touchMap[has](type)) {
for (var i = 0, ii = e.targetTouches && e.targetTouches.length; i < ii; i++) {
if (e.targetTouches[i].target == obj || obj.contains(e.targetTouches[i].target)) {
var olde = e;
e = e.targetTouches[i];
e.originalEvent = olde;
e.preventDefault = preventTouch;
e.stopPropagation = stopTouch;
break;
}
}
}
var x = e.clientX + scrollX,
y = e.clientY + scrollY;
return fn.call(element, e, x, y);
};
if (type !== realName) {
obj.addEventListener(type, f, false);
}
obj.addEventListener(realName, f, false);
return function () {
if (type !== realName) {
obj.removeEventListener(type, f, false);
}
obj.removeEventListener(realName, f, false);
return true;
};
},
drag = [],
dragMove = function (e) {
var x = e.clientX,
y = e.clientY,
scrollY = getScroll("y"),
scrollX = getScroll("x"),
dragi,
j = drag.length;
while (j--) {
dragi = drag[j];
if (supportsTouch) {
var i = e.touches && e.touches.length,
touch;
while (i--) {
touch = e.touches[i];
if (touch.identifier == dragi.el._drag.id || dragi.el.node.contains(touch.target)) {
x = touch.clientX;
y = touch.clientY;
(e.originalEvent ? e.originalEvent : e).preventDefault();
break;
}
}
} else {
e.preventDefault();
}
var node = dragi.el.node,
o,
next = node.nextSibling,
parent = node.parentNode,
display = node.style.display;
// glob.win.opera && parent.removeChild(node);
// node.style.display = "none";
// o = dragi.el.paper.getElementByPoint(x, y);
// node.style.display = display;
// glob.win.opera && (next ? parent.insertBefore(node, next) : parent.appendChild(node));
// o && eve("snap.drag.over." + dragi.el.id, dragi.el, o);
x += scrollX;
y += scrollY;
eve("snap.drag.move." + dragi.el.id, dragi.move_scope || dragi.el, x - dragi.el._drag.x, y - dragi.el._drag.y, x, y, e);
}
},
dragUp = function (e) {
Snap.unmousemove(dragMove).unmouseup(dragUp);
var i = drag.length,
dragi;
while (i--) {
dragi = drag[i];
dragi.el._drag = {};
eve("snap.drag.end." + dragi.el.id, dragi.end_scope || dragi.start_scope || dragi.move_scope || dragi.el, e);
eve.off("snap.drag.*." + dragi.el.id);
}
drag = [];
};
/*\
* Element.click
[ method ]
**
* Adds a click event handler to the element
- handler (function) handler for the event
= (object) @Element
\*/
/*\
* Element.unclick
[ method ]
**
* Removes a click event handler from the element
- handler (function) handler for the event
= (object) @Element
\*/
/*\
* Element.dblclick
[ method ]
**
* Adds a double click event handler to the element
- handler (function) handler for the event
= (object) @Element
\*/
/*\
* Element.undblclick
[ method ]
**
* Removes a double click event handler from the element
- handler (function) handler for the event
= (object) @Element
\*/
/*\
* Element.mousedown
[ method ]
**
* Adds a mousedown event handler to the element
- handler (function) handler for the event
= (object) @Element
\*/
/*\
* Element.unmousedown
[ method ]
**
* Removes a mousedown event handler from the element
- handler (function) handler for the event
= (object) @Element
\*/
/*\
* Element.mousemove
[ method ]
**
* Adds a mousemove event handler to the element
- handler (function) handler for the event
= (object) @Element
\*/
/*\
* Element.unmousemove
[ method ]
**
* Removes a mousemove event handler from the element
- handler (function) handler for the event
= (object) @Element
\*/
/*\
* Element.mouseout
[ method ]
**
* Adds a mouseout event handler to the element
- handler (function) handler for the event
= (object) @Element
\*/
/*\
* Element.unmouseout
[ method ]
**
* Removes a mouseout event handler from the element
- handler (function) handler for the event
= (object) @Element
\*/
/*\
* Element.mouseover
[ method ]
**
* Adds a mouseover event handler to the element
- handler (function) handler for the event
= (object) @Element
\*/
/*\
* Element.unmouseover
[ method ]
**
* Removes a mouseover event handler from the element
- handler (function) handler for the event
= (object) @Element
\*/
/*\
* Element.mouseup
[ method ]
**
* Adds a mouseup event handler to the element
- handler (function) handler for the event
= (object) @Element
\*/
/*\
* Element.unmouseup
[ method ]
**
* Removes a mouseup event handler from the element
- handler (function) handler for the event
= (object) @Element
\*/
/*\
* Element.touchstart
[ method ]
**
* Adds a touchstart event handler to the element
- handler (function) handler for the event
= (object) @Element
\*/
/*\
* Element.untouchstart
[ method ]
**
* Removes a touchstart event handler from the element
- handler (function) handler for the event
= (object) @Element
\*/
/*\
* Element.touchmove
[ method ]
**
* Adds a touchmove event handler to the element
- handler (function) handler for the event
= (object) @Element
\*/
/*\
* Element.untouchmove
[ method ]
**
* Removes a touchmove event handler from the element
- handler (function) handler for the event
= (object) @Element
\*/
/*\
* Element.touchend
[ method ]
**
* Adds a touchend event handler to the element
- handler (function) handler for the event
= (object) @Element
\*/
/*\
* Element.untouchend
[ method ]
**
* Removes a touchend event handler from the element
- handler (function) handler for the event
= (object) @Element
\*/
/*\
* Element.touchcancel
[ method ]
**
* Adds a touchcancel event handler to the element
- handler (function) handler for the event
= (object) @Element
\*/
/*\
* Element.untouchcancel
[ method ]
**
* Removes a touchcancel event handler from the element
- handler (function) handler for the event
= (object) @Element
\*/
for (var i = events.length; i--;) {
(function (eventName) {
Snap[eventName] = elproto[eventName] = function (fn, scope) {
if (Snap.is(fn, "function")) {
this.events = this.events || [];
this.events.push({
name: eventName,
f: fn,
unbind: addEvent(this.node || document, eventName, fn, scope || this)
});
} else {
for (var i = 0, ii = this.events.length; i < ii; i++) if (this.events[i].name == eventName) {
try {
this.events[i].f.call(this);
} catch (e) {}
}
}
return this;
};
Snap["un" + eventName] =
elproto["un" + eventName] = function (fn) {
var events = this.events || [],
l = events.length;
while (l--) if (events[l].name == eventName &&
(events[l].f == fn || !fn)) {
events[l].unbind();
events.splice(l, 1);
!events.length && delete this.events;
return this;
}
return this;
};
})(events[i]);
}
/*\
* Element.hover
[ method ]
**
* Adds hover event handlers to the element
- f_in (function) handler for hover in
- f_out (function) handler for hover out
- icontext (object) #optional context for hover in handler
- ocontext (object) #optional context for hover out handler
= (object) @Element
\*/
elproto.hover = function (f_in, f_out, scope_in, scope_out) {
return this.mouseover(f_in, scope_in).mouseout(f_out, scope_out || scope_in);
};
/*\
* Element.unhover
[ method ]
**
* Removes hover event handlers from the element
- f_in (function) handler for hover in
- f_out (function) handler for hover out
= (object) @Element
\*/
elproto.unhover = function (f_in, f_out) {
return this.unmouseover(f_in).unmouseout(f_out);
};
var draggable = [];
// SIERRA unclear what _context_ refers to for starting, ending, moving the drag gesture.
// SIERRA Element.drag(): _x position of the mouse_: Where are the x/y values offset from?
// SIERRA Element.drag(): much of this member's doc appears to be duplicated for some reason.
// SIERRA Unclear about this sentence: _Additionally following drag events will be triggered: drag.start.<id> on start, drag.end.<id> on end and drag.move.<id> on every move._ Is there a global _drag_ object to which you can assign handlers keyed by an element's ID?
/*\
* Element.drag
[ method ]
**
* Adds event handlers for an element's drag gesture
**
- onmove (function) handler for moving
- onstart (function) handler for drag start
- onend (function) handler for drag end
- mcontext (object) #optional context for moving handler
- scontext (object) #optional context for drag start handler
- econtext (object) #optional context for drag end handler
* Additionaly following `drag` events are triggered: `drag.start.<id>` on start,
* `drag.end.<id>` on end and `drag.move.<id>` on every move. When element is dragged over another element
* `drag.over.<id>` fires as well.
*
* Start event and start handler are called in specified context or in context of the element with following parameters:
o x (number) x position of the mouse
o y (number) y position of the mouse
o event (object) DOM event object
* Move event and move handler are called in specified context or in context of the element with following parameters:
o dx (number) shift by x from the start point
o dy (number) shift by y from the start point
o x (number) x position of the mouse
o y (number) y position of the mouse
o event (object) DOM event object
* End event and end handler are called in specified context or in context of the element with following parameters:
o event (object) DOM event object
= (object) @Element
\*/
elproto.drag = function (onmove, onstart, onend, move_scope, start_scope, end_scope) {
var el = this;
if (!arguments.length) {
var origTransform;
return el.drag(function (dx, dy) {
this.attr({
transform: origTransform + (origTransform ? "T" : "t") + [dx, dy]
});
}, function () {
origTransform = this.transform().local;
});
}
function start(e, x, y) {
(e.originalEvent || e).preventDefault();
el._drag.x = x;
el._drag.y = y;
el._drag.id = e.identifier;
!drag.length && Snap.mousemove(dragMove).mouseup(dragUp);
drag.push({el: el, move_scope: move_scope, start_scope: start_scope, end_scope: end_scope});
onstart && eve.on("snap.drag.start." + el.id, onstart);
onmove && eve.on("snap.drag.move." + el.id, onmove);
onend && eve.on("snap.drag.end." + el.id, onend);
eve("snap.drag.start." + el.id, start_scope || move_scope || el, x, y, e);
}
function init(e, x, y) {
eve("snap.draginit." + el.id, el, e, x, y);
}
eve.on("snap.draginit." + el.id, start);
el._drag = {};
draggable.push({el: el, start: start, init: init});
el.mousedown(init);
return el;
};
/*
* Element.onDragOver
[ method ]
**
* Shortcut to assign event handler for `drag.over.<id>` event, where `id` is the element's `id` (see @Element.id)
- f (function) handler for event, first argument would be the element you are dragging over
\*/
// elproto.onDragOver = function (f) {
// f ? eve.on("snap.drag.over." + this.id, f) : eve.unbind("snap.drag.over." + this.id);
// };
/*\
* Element.undrag
[ method ]
**
* Removes all drag event handlers from the given element
\*/
elproto.undrag = function () {
var i = draggable.length;
while (i--) if (draggable[i].el == this) {
this.unmousedown(draggable[i].init);
draggable.splice(i, 1);
eve.unbind("snap.drag.*." + this.id);
eve.unbind("snap.draginit." + this.id);
}
!draggable.length && Snap.unmousemove(dragMove).unmouseup(dragUp);
return this;
};
});
// Copyright (c) 2013 Adobe Systems Incorporated. All rights reserved.
//
// 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.
Snap.plugin(function (Snap, Element, Paper, glob) {
var elproto = Element.prototype,
pproto = Paper.prototype,
rgurl = /^\s*url\((.+)\)/,
Str = String,
$ = Snap._.$;
Snap.filter = {};
/*\
* Paper.filter
[ method ]
**
* Creates a `<filter>` element
**
- filstr (string) SVG fragment of filter provided as a string
= (object) @Element
* Note: It is recommended to use filters embedded into the page inside an empty SVG element.
> Usage
| var f = paper.filter('<feGaussianBlur stdDeviation="2"/>'),
| c = paper.circle(10, 10, 10).attr({
| filter: f
| });
\*/
pproto.filter = function (filstr) {
var paper = this;
if (paper.type != "svg") {
paper = paper.paper;
}
var f = Snap.parse(Str(filstr)),
id = Snap._.id(),
width = paper.node.offsetWidth,
height = paper.node.offsetHeight,
filter = $("filter");
$(filter, {
id: id,
filterUnits: "userSpaceOnUse"
});
filter.appendChild(f.node);
paper.defs.appendChild(filter);
return new Element(filter);
};
eve.on("snap.util.getattr.filter", function () {
eve.stop();
var p = $(this.node, "filter");
if (p) {
var match = Str(p).match(rgurl);
return match && Snap.select(match[1]);
}
});
eve.on("snap.util.attr.filter", function (value) {
if (value instanceof Element && value.type == "filter") {
eve.stop();
var id = value.node.id;
if (!id) {
$(value.node, {id: value.id});
id = value.id;
}
$(this.node, {
filter: Snap.url(id)
});
}
if (!value || value == "none") {
eve.stop();
this.node.removeAttribute("filter");
}
});
/*\
* Snap.filter.blur
[ method ]
**
* Returns an SVG markup string for the blur filter
**
- x (number) amount of horizontal blur, in pixels
- y (number) #optional amount of vertical blur, in pixels
= (string) filter representation
> Usage
| var f = paper.filter(Snap.filter.blur(5, 10)),
| c = paper.circle(10, 10, 10).attr({
| filter: f
| });
\*/
Snap.filter.blur = function (x, y) {
if (x == null) {
x = 2;
}
var def = y == null ? x : [x, y];
return Snap.format('\<feGaussianBlur stdDeviation="{def}"/>', {
def: def
});
};
Snap.filter.blur.toString = function () {
return this();
};
/*\
* Snap.filter.shadow
[ method ]
**
* Returns an SVG markup string for the shadow filter
**
- dx (number) #optional horizontal shift of the shadow, in pixels
- dy (number) #optional vertical shift of the shadow, in pixels
- blur (number) #optional amount of blur
- color (string) #optional color of the shadow
- opacity (number) #optional `0..1` opacity of the shadow
* or
- dx (number) #optional horizontal shift of the shadow, in pixels
- dy (number) #optional vertical shift of the shadow, in pixels
- color (string) #optional color of the shadow
- opacity (number) #optional `0..1` opacity of the shadow
* which makes blur default to `4`. Or
- dx (number) #optional horizontal shift of the shadow, in pixels
- dy (number) #optional vertical shift of the shadow, in pixels
- opacity (number) #optional `0..1` opacity of the shadow
= (string) filter representation
> Usage
| var f = paper.filter(Snap.filter.shadow(0, 2, 3)),
| c = paper.circle(10, 10, 10).attr({
| filter: f
| });
\*/
Snap.filter.shadow = function (dx, dy, blur, color, opacity) {
if (typeof blur == "string") {
color = blur;
opacity = color;
blur = 4;
}
if (typeof color != "string") {
opacity = color;
color = "#000";
}
color = color || "#000";
if (blur == null) {
blur = 4;
}
if (opacity == null) {
opacity = 1;
}
if (dx == null) {
dx = 0;
dy = 2;
}
if (dy == null) {
dy = dx;
}
color = Snap.color(color);
return Snap.format('<feGaussianBlur in="SourceAlpha" stdDeviation="{blur}"/><feOffset dx="{dx}" dy="{dy}" result="offsetblur"/><feFlood flood-color="{color}"/><feComposite in2="offsetblur" operator="in"/><feComponentTransfer><feFuncA type="linear" slope="{opacity}"/></feComponentTransfer><feMerge><feMergeNode/><feMergeNode in="SourceGraphic"/></feMerge>', {
color: color,
dx: dx,
dy: dy,
blur: blur,
opacity: opacity
});
};
Snap.filter.shadow.toString = function () {
return this();
};
/*\
* Snap.filter.grayscale
[ method ]
**
* Returns an SVG markup string for the grayscale filter
**
- amount (number) amount of filter (`0..1`)
= (string) filter representation
\*/
Snap.filter.grayscale = function (amount) {
if (amount == null) {
amount = 1;
}
return Snap.format('<feColorMatrix type="matrix" values="{a} {b} {c} 0 0 {d} {e} {f} 0 0 {g} {b} {h} 0 0 0 0 0 1 0"/>', {
a: 0.2126 + 0.7874 * (1 - amount),
b: 0.7152 - 0.7152 * (1 - amount),
c: 0.0722 - 0.0722 * (1 - amount),
d: 0.2126 - 0.2126 * (1 - amount),
e: 0.7152 + 0.2848 * (1 - amount),
f: 0.0722 - 0.0722 * (1 - amount),
g: 0.2126 - 0.2126 * (1 - amount),
h: 0.0722 + 0.9278 * (1 - amount)
});
};
Snap.filter.grayscale.toString = function () {
return this();
};
/*\
* Snap.filter.sepia
[ method ]
**
* Returns an SVG markup string for the sepia filter
**
- amount (number) amount of filter (`0..1`)
= (string) filter representation
\*/
Snap.filter.sepia = function (amount) {
if (amount == null) {
amount = 1;
}
return Snap.format('<feColorMatrix type="matrix" values="{a} {b} {c} 0 0 {d} {e} {f} 0 0 {g} {h} {i} 0 0 0 0 0 1 0"/>', {
a: 0.393 + 0.607 * (1 - amount),
b: 0.769 - 0.769 * (1 - amount),
c: 0.189 - 0.189 * (1 - amount),
d: 0.349 - 0.349 * (1 - amount),
e: 0.686 + 0.314 * (1 - amount),
f: 0.168 - 0.168 * (1 - amount),
g: 0.272 - 0.272 * (1 - amount),
h: 0.534 - 0.534 * (1 - amount),
i: 0.131 + 0.869 * (1 - amount)
});
};
Snap.filter.sepia.toString = function () {
return this();
};
/*\
* Snap.filter.saturate
[ method ]
**
* Returns an SVG markup string for the saturate filter
**
- amount (number) amount of filter (`0..1`)
= (string) filter representation
\*/
Snap.filter.saturate = function (amount) {
if (amount == null) {
amount = 1;
}
return Snap.format('<feColorMatrix type="saturate" values="{amount}"/>', {
amount: 1 - amount
});
};
Snap.filter.saturate.toString = function () {
return this();
};
/*\
* Snap.filter.hueRotate
[ method ]
**
* Returns an SVG markup string for the hue-rotate filter
**
- angle (number) angle of rotation
= (string) filter representation
\*/
Snap.filter.hueRotate = function (angle) {
angle = angle || 0;
return Snap.format('<feColorMatrix type="hueRotate" values="{angle}"/>', {
angle: angle
});
};
Snap.filter.hueRotate.toString = function () {
return this();
};
/*\
* Snap.filter.invert
[ method ]
**
* Returns an SVG markup string for the invert filter
**
- amount (number) amount of filter (`0..1`)
= (string) filter representation
\*/
Snap.filter.invert = function (amount) {
if (amount == null) {
amount = 1;
}
// <feColorMatrix type="matrix" values="-1 0 0 0 1 0 -1 0 0 1 0 0 -1 0 1 0 0 0 1 0" color-interpolation-filters="sRGB"/>
return Snap.format('<feComponentTransfer><feFuncR type="table" tableValues="{amount} {amount2}"/><feFuncG type="table" tableValues="{amount} {amount2}"/><feFuncB type="table" tableValues="{amount} {amount2}"/></feComponentTransfer>', {
amount: amount,
amount2: 1 - amount
});
};
Snap.filter.invert.toString = function () {
return this();
};
/*\
* Snap.filter.brightness
[ method ]
**
* Returns an SVG markup string for the brightness filter
**
- amount (number) amount of filter (`0..1`)
= (string) filter representation
\*/
Snap.filter.brightness = function (amount) {
if (amount == null) {
amount = 1;
}
return Snap.format('<feComponentTransfer><feFuncR type="linear" slope="{amount}"/><feFuncG type="linear" slope="{amount}"/><feFuncB type="linear" slope="{amount}"/></feComponentTransfer>', {
amount: amount
});
};
Snap.filter.brightness.toString = function () {
return this();
};
/*\
* Snap.filter.contrast
[ method ]
**
* Returns an SVG markup string for the contrast filter
**
- amount (number) amount of filter (`0..1`)
= (string) filter representation
\*/
Snap.filter.contrast = function (amount) {
if (amount == null) {
amount = 1;
}
return Snap.format('<feComponentTransfer><feFuncR type="linear" slope="{amount}" intercept="{amount2}"/><feFuncG type="linear" slope="{amount}" intercept="{amount2}"/><feFuncB type="linear" slope="{amount}" intercept="{amount2}"/></feComponentTransfer>', {
amount: amount,
amount2: .5 - amount / 2
});
};
Snap.filter.contrast.toString = function () {
return this();
};
});
// Copyright (c) 2014 Adobe Systems Incorporated. All rights reserved.
//
// 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.
Snap.plugin(function (Snap, Element, Paper, glob, Fragment) {
var box = Snap._.box,
is = Snap.is,
firstLetter = /^[^a-z]*([tbmlrc])/i,
toString = function () {
return "T" + this.dx + "," + this.dy;
};
/*\
* Element.getAlign
[ method ]
**
* Returns shift needed to align the element relatively to given element.
* If no elements specified, parent `<svg>` container will be used.
- el (object) @optional alignment element
- way (string) one of six values: `"top"`, `"middle"`, `"bottom"`, `"left"`, `"center"`, `"right"`
= (object|string) Object in format `{dx: , dy: }` also has a string representation as a transformation string
> Usage
| el.transform(el.getAlign(el2, "top"));
* or
| var dy = el.getAlign(el2, "top").dy;
\*/
Element.prototype.getAlign = function (el, way) {
if (way == null && is(el, "string")) {
way = el;
el = null;
}
el = el || this.paper;
var bx = el.getBBox ? el.getBBox() : box(el),
bb = this.getBBox(),
out = {};
way = way && way.match(firstLetter);
way = way ? way[1].toLowerCase() : "c";
switch (way) {
case "t":
out.dx = 0;
out.dy = bx.y - bb.y;
break;
case "b":
out.dx = 0;
out.dy = bx.y2 - bb.y2;
break;
case "m":
out.dx = 0;
out.dy = bx.cy - bb.cy;
break;
case "l":
out.dx = bx.x - bb.x;
out.dy = 0;
break;
case "r":
out.dx = bx.x2 - bb.x2;
out.dy = 0;
break;
default:
out.dx = bx.cx - bb.cx;
out.dy = 0;
break;
}
out.toString = toString;
return out;
};
/*\
* Element.align
[ method ]
**
* Aligns the element relatively to given one via transformation.
* If no elements specified, parent `<svg>` container will be used.
- el (object) @optional alignment element
- way (string) one of six values: `"top"`, `"middle"`, `"bottom"`, `"left"`, `"center"`, `"right"`
= (object) this element
> Usage
| el.align(el2, "top");
* or
| el.align("middle");
\*/
Element.prototype.align = function (el, way) {
return this.transform("..." + this.getAlign(el, way));
};
});
return Snap;
}));
}.call(window));
/***/ },
/* 19 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $ = __webpack_require__(1);
//webpack hack for Snap
//https://github.com/adobe-webplatform/Snap.svg/issues/341
var Snap = __webpack_require__(18);
var laptop = {
CHAR_FADEIN_DELAY: 300,
textAttrs: {
fill: '#FFF',
"font-size": "200%",
opacity: '0.75'
},
fadeIn: function fadeIn(el) {
Snap.animate(0, 1, function (value) {
el.attr({
opacity: value
});
}, 100);
},
/**
* Adds a hidden text group, with each character split into separate tspans.
*
* @param {string} text - use this string for text items.
* @param {number} x - x coords
* @param {number} y - y coords
*
* @return {array}
*/
addTextGroup: function addTextGroup(text, x, y) {
var group = this.s.g().attr(this.textAttrs);
return group.text(x, y, text.split('')).selectAll("tspan").attr({
opacity: 0
});
},
/**
* Add animated text to svg el.
*/
animateSvg: function animateSvg() {
this.s = Snap('.laptop__screen svg');
var self = this;
var designGroupEls = this.addTextGroup('DESIGN', 145, 210);
var codeGroupEls = this.addTextGroup('CODE', 445, 255);
designGroupEls.forEach(function (el, index) {
setTimeout(function () {
self.fadeIn(el);
}, index * self.CHAR_FADEIN_DELAY);
});
setTimeout(function () {
codeGroupEls.forEach(function (el, index) {
setTimeout(function () {
self.fadeIn(el);
}, index * self.CHAR_FADEIN_DELAY);
});
}, designGroupEls.length * self.CHAR_FADEIN_DELAY);
},
/**
* If we've got a laptop el, start the animation.
*/
init: function init() {
this.$wrapper = $('.laptop__screen');
if ($('body').hasClass('body--home') && this.$wrapper.length) {
this.animateSvg();
}
}
};
module.exports = laptop;
/***/ },
/* 20 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $ = __webpack_require__(1);
/**
* Misc nav related items.
*/
var nav = {
/**
* Toggle subnav dropdowns
* @param {object} $el
*/
toggleSubnav: function toggleSubnav($el) {
$el.toggleClass('sub-nav__link--dropdown--open');
$el.next('.sub-nav__dropdown').toggleClass('sub-nav__dropdown--open');
},
/**
*/
bindEventHandlers: function bindEventHandlers() {
var self = this;
$('.sub-nav__link--dropdown').on('click', function (event) {
event.preventDefault();
self.toggleSubnav($(this));
});
var $body = $('body');
var hoverNavClass = 'body--animate-header';
$('.nav__link').on('mouseover', function () {
if (!$(this).hasClass('nav__link--active')) {
$body.addClass(hoverNavClass);
}
}).on('mouseout', function () {
$body.removeClass(hoverNavClass);
});
},
/**
* By default, the subnavs are loaded in their open state to support JS being disabled.
* If we're here, JS is enabled; if it's a smaller device, close the nav on initial load.
*/
closeSubnavOnSmallerDevices: function closeSubnavOnSmallerDevices() {
var width = $('body').outerWidth();
if (width <= 1000) {
var self = this;
$('.sub-nav__link--dropdown--open').each(function () {
self.toggleSubnav($(this));
});
}
},
/**
* Init module
*/
init: function init() {
this.bindEventHandlers();
this.closeSubnavOnSmallerDevices();
}
};
module.exports = nav;
/***/ }
]);<file_sep>/resources/views/partials/pagination.php
<?php
$pages = ceil($total/$perPage);
$offsetStart = 1;
$offsetEnd = $perPage < $total ? $perPage : $total;
if ($page !== 1) {
$prevPage = $page - 1;
$offsetStart = ($perPage * $prevPage) + $prevPage;
$offsetEnd = $offsetStart + $perPage;
if ($offsetEnd > $total) {
$offsetEnd = $total;
}
}
?>
<div class="pagination<?php if (isset($cssClass)) {?> <?= $cssClass; ?><?php } ?>">
<label class="pagination__label"><?= $offsetStart; ?> - <?= $offsetEnd; ?> of <?= $total; ?>.</label>
<?php if ($pages > 1) { ?>
<ul>
<?php for($i = 1; $i <= $pages; $i++) { ?>
<?php
$url = "/{$section}/{$subsection}";
if (isset($subsectionChild)) {
$url .= "/{$subsectionChild}";
}
$url .= "?p={$i}";
if (isset($appendQueryParams)) {
$url .= $appendQueryParams;
}
?>
<li class="pagination__page<?php if ($i === $page) { ?> pagination__page--active<?php } ?>">
<?php if ($i === $page) { ?>
<span class="pagination__link">
<?= $i; ?>
</span>
<?php } else { ?>
<a class="pagination__link" href="<?= url($url); ?>">
<?= $i; ?>
</a>
<?php } ?>
</li>
<?php } ?>
</ul>
<?php } ?>
<input type="hidden" value="<?= $page; ?>" name="current-page" />
</div><file_sep>/app/Http/Controllers/ContactController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Mail;
use Log;
class ContactController extends Controller {
const SECTION = 'contact';
public static $requiredFieldErrors = array(
"name" => "What, no name?",
"message" => "What, no message?",
"email" => "No spam, I promise."
);
/**
* @param Request $request
*/
public function indexAction(Request $request) {
if ($request->isMethod('post')) {
$results = $this->submitContactForm($request);
if ($results['status']) {
return redirect('/contact')->with('messsage', array('value' => $results['message'], 'title' => 'Success!'));
} else {
$viewData = $this->getViewData();
if (isset($results['errorFields'])) {
$viewData = array_merge_recursive($this->getViewData(), array('errorFields' => $results['errorFields']));
}
return view("contact/index", $viewData)->with('messsage', array('value' => $results['message'], 'title' => 'Success!'));
}
}
return view("contact/index", $this->getViewData());
}
/**
* @param Request $request
*/
public function submitAjaxAction(Request $request) {
echo json_encode($this->submitContactForm($request));
}
/**
* Submit contact form
*
* @param Request $request
*
* @return array['status' => boolean, 'message' => string]
*/
private function submitContactForm(Request $request) {
$errorFields = array();
$requiredFields = array('name','email','message');
$results = array(
'status' => false,
'message' => 'Unable to submit form, please try again later.'
);
foreach ($requiredFields as $field) {
if (!$request->has($field)) {
$errorFields[$field] = $this->getRequiredFieldError($field);
}
else if ($field == 'email' && !filter_var($request->get('email'), FILTER_VALIDATE_EMAIL)) {
$errorFields[$field] = 'Please enter a valid email address, ie <EMAIL>.';
}
}
if (!empty($errorFields)) {
$results['errorFields'] = $errorFields;
$results['message'] = 'Missing required fields.';
return $results;
}
$name = filter_var($request->get('name'), FILTER_SANITIZE_SPECIAL_CHARS);
$email = filter_var($request->get('email'), FILTER_SANITIZE_SPECIAL_CHARS);
$message = filter_var($request->get('message'), FILTER_SANITIZE_SPECIAL_CHARS);
$body = 'Name: ' . $name . "\n" . 'Email: ' . $email . "\n" . 'Message: ' . $message . "\n";
try {
Mail::raw($body, function($message) use ($email) {
$message->to('<EMAIL>');
$message->from($email);
$message->subject('Contact from tublitzed.com...');
});
$message = "Thanks for getting in touch, $name! Your message been sent, and I'll get back to you shortly.";
$results['status'] = true;
$results['message'] = $message;
} catch(Exception $e) {
Log::error("Failed email send: {$body}");
Log::error($e);
}
return $results;
}
/**
* Returns specific required field strings for contact form based on field type.
*
* @param string $field
*
* @return string
*/
private function getRequiredFieldError($field) {
if (array_key_exists($field, self::$requiredFieldErrors)) {
return self::$requiredFieldErrors[$field];
}
return 'This field is required.';
}
/**
* Builds view data array
*
* @return array
*/
private function getViewData() {
return array(
'section' => self::SECTION,
'pageHeaderInfo' => $this->getPageHeaderInfo(),
'sidebarPartialPath' => 'contact/partials/sidebar-list',
'requiredFieldErrors' => self::$requiredFieldErrors
);
}
/**
* Builds page header array
*
* @return array
*/
private function getPageHeaderInfo() {
return array(
'title' => 'Contact',
'section' => self::SECTION,
'subtitle' => "If you tell good jokes, I'd love to hear from you."
);
}
}
<file_sep>/app/Http/Controllers/Controller.php
<?php
namespace App\Http\Controllers;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Http\Request;
use DB;
use Cache;
use Config;
abstract class Controller extends BaseController
{
use DispatchesJobs, ValidatesRequests;
const PROJECT_CATEGORY_ALL = 'all';
const PROJECT_TYPE_FEATURED = 'featured';
const PROJECTS_PER_PAGE = 50;
const PHOTOS_PER_PAGE = 21;
/**
* Return projects, either from cache or DB.
*
* @param int|null $page - if set, only return projects for specific page
* @param string|null $categoryString - if set, only return projects for specific category string.
* @param boolean $featured - if true, filter to return only featured work
*
* @return array
*/
protected function getProjects($page = null, $categoryString = null, $featured = false) {
$cacheName = 'projects';
$categoryId = null;
if ($categoryString && $categoryString !== self::PROJECT_CATEGORY_ALL) {
$categoryId = $this->getProjectCategoryIdByPath($categoryString);
$cacheName .= '.' . $categoryId;
} else if($featured) {
$cacheName .= '.' . self::PROJECT_TYPE_FEATURED;
} else {
$cacheName .= '.' . self::PROJECT_CATEGORY_ALL;
}
if ($page) {
$cacheName .= '.' . $page;
}
return Cache::remember($cacheName, Config::get('app.cacheTimeoutMinutes'), function() use ($page, $categoryId, $featured) {
$query = DB::table('projects')
->select('*')
->orderBy('end_date', 'desc')
->where('visible', '=', 1);
if ($categoryId) {
$query->where('category_id', '=', $categoryId);
}
if ($featured) {
$query->where('featured', '=', 1);
}
if ($page) {
$query->skip(($page - 1) * self::PROJECTS_PER_PAGE)
->take(self::PROJECTS_PER_PAGE);
}
$projects = $query->get();
foreach ($projects as $project) {
$project->years = $this->formatProjectDate($project->start_date, $project->end_date);
$project->images = $this->formatProjectImages($project);
if ($project->path === 'yoomee') {
$project = $this->addYooMeeProjectMetadata($project);
}
}
return $projects;
});
}
/**
* Return categories, either from cache or DB
*
* @return array
*/
protected function getCategories() {
return Cache::remember('project_categories', Config::get('app.cacheTimeoutMinutes'), function() {
return DB::table('project_categories')
->select('*')
->get();
});
}
/**
* Return category id for path. Defaults to 1 if none found.
*
* @param string $path
* @return int
*/
private function getProjectCategoryIdByPath($path) {
$categories = $this->getCategories();
$id = null;
foreach($categories as $category) {
if ($category->path === $path) {
$id = $category->id;
break;
}
}
return $id;
}
/**
* Returns only years based on date in YYYY-MM-DD format. If same year, return only that year.
* Ie, 2012-xx-xx, 2014-xx-xx => 2012-14. or 2015-xx-xx, 2015-xx-xx => 2015.
*
* @param string $startDate [description]
* @param string $endDate [description]
* @return string
*/
private function formatProjectDate($startDate, $endDate) {
$startYear = explode('-', $startDate)[0];
$endYear = explode('-', $endDate)[0];
if ($startYear === $endYear) {
return $endYear;
}
return $startYear . '-' . substr($endYear, 2);
}
/**
* The one and only flash project gets a few extra hardcoded values.
* Not building in support for flash stuff overall since well...flash is dead.
*
* @param object $project
*/
private function addYooMeeProjectMetadata($project) {
$project->flashData = array(
array(
'width' => 960,
'height' => 250,
'name' => 'ymMarquee_960_250.swf'
),
array(
'width' => 430,
'height' => 350,
'name' => 'ymUHP_430_350.swf'
),
array(
'width' => 300,
'height' => 250,
'name' => 'ymUHP_300_250.swf'
)
);
return $project;
}
/**
* Get image array for specific project
* @param object $project
*
* @return array
*/
private function formatProjectImages($project) {
$formatted = array();
$baseImgUrl = Config::get('app.imgUrl');
$images = json_decode($project->images, true);
if (is_array($images)) {
foreach($images as $index => $title) {
$formatted[] = array(
'title' => $title,
'thumb' => $baseImgUrl . 'portfolio/' . $project->path . '/browser/thumbs/' . $index . '.jpg',
'full' => $baseImgUrl . 'portfolio/' . $project->path . '/browser/full/' . $index . '.jpg'
);
}
}
return $formatted;
}
/**
* Current page
*
* @return int
*/
protected function getPage() {
return isset($_GET['p']) ? (int)$_GET['p'] : 1;
}
/**
* Returns photos based on current page and PHOTOS_PER_PAGE
*
* @param int $page
* @param string|null $state optionally filter by state
* @param boolean= $bypassPagination if set, ignore page, load all.
*
* @return array
*/
protected function getPhotos($page, $state = null, $bypassPagination = false) {
$cacheName = 'photos.' . $page;
if (!is_null($state)) {
$cacheName .= '.' . $state;
}
return Cache::remember($cacheName, Config::get('app.cacheTimeoutMinutes'), function() use ($state, $page, $bypassPagination) {
$query = DB::table('photos');
if (!is_null($state)) {
$query->where('state', '=', $state);
}
$query
->select('*')
->where('visible', '=', 1)
->orderBy('featured', 'desc');
if (!$bypassPagination) {
$query->skip(($page - 1) * self::PHOTOS_PER_PAGE);
$query->take(self::PHOTOS_PER_PAGE);
}
$photos = $query->get();
foreach ($photos as $photo) {
$photo->modalTitle = $this->buildPhotoModalTitle($photo);
}
return $photos;
});
}
/**
* Build extended modal photo title based on existing metadata.
* The existing 'title' is used as a title for thumbnails.
*
* @param object $photo
* @return string
*/
private function buildPhotoModalTitle($photo) {
$location = '';
if ($photo->city && $photo->state) {
$location .= $photo->city . ', ' . $photo->state;
} else if ($photo->state) {
$location .= $photo->state;
} else if ($photo->country) {
$location .= $photo->country;
}
$year = explode('-', $photo->date)[0];
if (!empty($location)) {
return $location . ' - ' . $year . '.';
}
return $year . '.';
}
}
<file_sep>/resources/assets/js/util/scroll/index.js
/**
* Various scroll related utils.
*/
var scroll = {
SCROLL_UP: 'up',
SCROLL_DOWN: 'down',
SCROLL_LEFT: 'left',
SCROLL_RIGHT: 'right',
/**
* @param {event.<DOMMouseScroll>} event
* @return {string}
*/
getDirectionDOMMouseScroll: function(event) {
if (event.detail < 0) {
return this.SCROLL_UP;
}
return this.SCROLL_DOWN;
},
/**
* @param {event.<wheel>} event
* @return {string}
*/
getDirectionMousewheel: function(event) {
if (event.wheelDeltaX) {
return event.wheelDeltaX > 0 ? this.SCROLL_LEFT : this.SCROLL_RIGHT;
}
return event.wheelDeltaY > 0 ? this.SCROLL_UP : this.SCROLL_DOWN;
},
/**
* Get scroll direction
* @param {event.<DOMMouseScroll>|event.<wheel>} event
* @return {string|null}
*/
getDirection: function(event) {
var e = event.originalEvent || event; //support binding via vanilla||jquery
if (e.type === 'DOMMouseScroll') {
return this.getDirectionDOMMouseScroll(e);
} else if (e.type === 'wheel') {
return this.getDirectionMousewheel(e);
}
return null;
}
};
module.exports = scroll;<file_sep>/resources/assets/js/modules/modal/index.js
/* MODALS */
var $ = require('jquery');
var tooltipster = require('jquery-tooltipster/js/jquery.tooltipster.js');
var loader = require('../loader');
var modal = {
ERROR_CLASS: 'modal--error',
ERROR_MESSAGE_CLASS: 'modal__error-mssg',
VISIBLE_CLASS: 'modal--visible',
LOADING_CLASS: 'modal--loading',
DISABLE_MODAL_NAV_CLASS: 'modal--disable-nav',
DEFAULT_TITLE: 'Untitled',
TYPE_FLASH: 'flash',
TYPE_IMG: 'img',
OFFSET_TOP: 0,
OFFSET_LEFT: 0,
HEADER_HEIGHT: 0,
ANIMATE_IN: 200,
DEFAULT_HEIGHT: 500,
/**
* Loads an image into the DOM to first measure size before inserting into modal window.
*
* @param {object} $trigger
* @param {boolean=} disableModalNav
*/
showImgModal: function($trigger, disableModalNav) {
loader.show();
var $img = this.getImg($trigger);
var title = this.getTitle($trigger);
var index = this.getIndex($trigger);
var disableNav = disableModalNav || false;
this.$body.addClass(this.LOADING_CLASS).append($img);
var self = this;
$img.load(function() {
loader.hide();
var $this = $(this);
var height = $this.height() + self.OFFSET_TOP;
var width = $this.width();
if (!disableNav) {
//the offset here is to account for the nav, so only add if needed.
width += self.OFFSET_LEFT;
}
self.$body.toggleClass(self.DISABLE_MODAL_NAV_CLASS, disableNav);
self.$modalBody.animate({
width: width,
height: height
}, self.ANIMATE_IN, function() {
self.$modal.attr('data-index', index);
if (disableNav) {
self.$modal.find('.btn--modal-nav').hide();
} else {
self.$modal.find('.btn--modal-nav').show().height(height - self.HEADER_HEIGHT);
}
self.clearModal();
$this.attr('alt', title).appendTo(self.$modalTarget);
self.$body.removeClass(self.LOADING_CLASS + ' ' + self.ERROR_CLASS);
self.$modalTitle.html(title);
self.show();
});
});
$img.error(self.onImageLoadError.bind(self));
},
/**
* Handle errors loading images.
*/
onImageLoadError: function() {
loader.hide();
this.clearModal();
this.$modal.find('.btn--modal-nav').height(200);
this.$modalTitle.html('Something went wrong!');
$('<p>').addClass(this.ERROR_MESSAGE_CLASS).text('Error loading image.').appendTo(this.$modalTarget);
this.$body.removeClass(this.LOADING_CLASS).addClass(this.ERROR_CLASS);
this.show();
},
/**
* Clear contents in modal
*/
clearModal: function() {
this.$modalTitle.html('');
this.$modalTarget.find('img, object, .' + this.ERROR_MESSAGE_CLASS).remove();
},
/**
* Show flash modal.
* @param {object} $trigger
*/
showFlashModal: function($trigger) {
var width = parseInt($trigger.attr('data-flash-width'), 10);
var height = parseInt($trigger.attr('data-flash-height'), 10);
var path = '/swf/' + $trigger.attr('data-flash-name');
var flashHtml = this.getFlashHtml(width, height, path);
var title = this.getTitle($trigger);
var index = this.getIndex($trigger);
var self = this;
this.$modalBody.animate({
width: width + self.OFFSET_LEFT,
height: height + self.OFFSET_TOP
}, self.ANIMATE_IN, function() {
self.$modal.attr('data-index', index);
self.$modal.find('.btn--modal-nav').height(height - 2);
self.$modalTarget.find('img, object').remove();
self.$modalTarget.html(flashHtml);
self.$body.removeClass(self.LOADING_CLASS);
self.$modalTitle.html(title);
self.show();
});
},
/**
* Build html object string for flash items in modals.
*
* @param {number} width
* @param {number} height
* @param {path} path
*
* @return {string}
*/
getFlashHtml: function(width, height, path) {
var html = '<object width="' + width + '" height="' + height + '">';
html += '<param value="true" name="allowfullscreen">';
html += '<param value="opaque" name="wmode">';
html += '<param value="never" name="allowscriptaccess">';
html += '<param value="' + path + '" name="movie">';
html += '<embed width="' + width + '" height="' + height + '" allowscriptaccess="never" wmode="opaque" allowfullscreen="true" type="application/x-shockwave-flash" src="' + path + '">';
return html;
},
/**
* Create image element for modal
* @param {object} $trigger
* @return {object}
*/
getImg: function($trigger) {
return $('<img />').attr('src', $trigger.attr('data-media-url'));
},
/**
* Builds title for modal
* @param {object} $trigger
* @return string title
*/
getTitle: function($trigger) {
var title = $trigger.attr('data-title');
return title || this.DEFAULT_TITLE;
},
/**
* Return the item's index
* @param {object} $trigger
* @return {number}
*/
getIndex: function($trigger) {
return $trigger.attr('data-index');
},
/**
* Show modal
*/
show: function() {
this.$body.addClass(this.VISIBLE_CLASS);
},
/**
* Hide modal
*/
hide: function() {
this.$body.removeClass(this.VISIBLE_CLASS);
},
/**
* Return a valid index so that we can keep looping through all items
* on the page if we hit a boundary at either the first or last item.
*
* @param {number} index - target index
* @return {number} index - adjusted index
*/
getValidIndex: function(index) {
var total = this.$modalMediaThumbs.length - 1;
if (index < 0) {
return total;
}
if (index > total) {
return 0;
}
return index;
},
/**
* Load an item into modal by target index.
* @param {number} targetIndex
*/
loadByIndex: function(targetIndex, modalType) {
targetIndex = this.getValidIndex(targetIndex);
if (this.modalType === this.TYPE_FLASH) {
this.showFlashModal($(this.$modalMediaThumbs[targetIndex]));
} else {
this.showImgModal($(this.$modalMediaThumbs[targetIndex]));
}
},
/**
* Return modal type.
* **Note: only works if all types on page are same. Change/improve if needed,
* however since flash is a one off thing, should be fine.
*
* @return {string}
*/
getModalType: function() {
if (this.$modalMediaTriggers.attr('data-flash')) {
return this.TYPE_FLASH;
}
return this.TYPE_IMG;
},
/**
* Return current index of item in modal
* @return {number}
*/
getCurrentIndex: function() {
return parseInt(this.$modal.attr('data-index'), 10) || 0;
},
/**
*/
bindEventHandlers: function() {
var self = this;
self.$modalMediaTriggers.on('click', function(event) {
event.preventDefault();
var $this = $(this);
if ($this.hasClass('tooltipstered')) {
$this.tooltipster('hide');
}
if (self.modalType === self.TYPE_FLASH) {
self.showFlashModal($(event.currentTarget));
} else {
self.showImgModal($(event.currentTarget));
}
});
self.$soloModalMediaTriggers.on('click', function(event) {
event.preventDefault();
self.showImgModal($(event.currentTarget), true);
});
this.$modal.find('.modal__bg').on('click', self.hide.bind(self));
this.$modal.find('.modal__close').on('click', function(event) {
event.preventDefault();
self.hide();
});
this.$modalTarget.on('click', function() {
self.loadByIndex(self.getCurrentIndex() + 1);
});
this.$modal.find('.btn--modal-nav').on('click', function(event) {
event.preventDefault();
var adjustIndex = $(this).attr('data-direction') === 'prev' ? -1 : 1;
self.loadByIndex(self.getCurrentIndex() + adjustIndex);
});
this.$html.on('keydown', 'body.' + self.VISIBLE_CLASS, function(event) {
var keyCode = event.keyCode;
var disableNav = self.$body.hasClass(self.DISABLE_MODAL_NAV_CLASS);
if (keyCode === 39 && !disableNav) {
//right arrow
self.loadByIndex(self.getCurrentIndex() + 1);
} else if (keyCode === 37 && !disableNav) {
//left arrow
self.loadByIndex(self.getCurrentIndex() - 1);
} else if (keyCode === 27) {
//esc
self.hide();
}
});
},
/**
* Adjust sizing slightly of modal based on nav/header element sizing.
* Cache header height which is used in sizing modal properly.
*/
storePositions: function() {
this.HEADER_HEIGHT = this.$modal.find('.modal__header').outerHeight();
this.OFFSET_LEFT = this.$modal.find('.btn--modal-nav:first').outerWidth() * 2;
this.OFFSET_TOP = this.HEADER_HEIGHT + 20; //TODO: fix this, it's quite right.
},
/**
* Cache some elements and bind event handlers for modals
*/
init: function() {
this.$modalMediaTriggers = $('.modal-media-trigger');
// solo functions the same as the $modalMediaTrigger except that there's no modal nav.
this.$soloModalMediaTriggers = $('.solo-modal-media-trigger');
this.$modalMediaThumbs = $('.modal-media-thumb').length ? $('.modal-media-thumb') : this.$modalMediaTriggers;
this.$modal = $('.modal');
this.$modalTarget = this.$modal.find('.modal__body-content');
this.$modalBody = this.$modal.find('.modal__content');
this.$modalTitle = this.$modal.find('.modal__title');
this.$body = $('body');
this.$html = $('html');
this.modalType = this.getModalType();
this.storePositions();
this.bindEventHandlers();
}
};
module.exports = modal;<file_sep>/resources/assets/js/modules/nav/index.js
var $ = require('jquery');
/**
* Misc nav related items.
*/
var nav = {
/**
* Toggle subnav dropdowns
* @param {object} $el
*/
toggleSubnav: function($el) {
$el.toggleClass('sub-nav__link--dropdown--open');
$el.next('.sub-nav__dropdown').toggleClass('sub-nav__dropdown--open');
},
/**
*/
bindEventHandlers: function() {
var self = this;
$('.sub-nav__link--dropdown').on('click', function(event) {
event.preventDefault();
self.toggleSubnav($(this));
});
var $body = $('body');
var hoverNavClass = 'body--animate-header';
$('.nav__link').on('mouseover', function() {
if (!$(this).hasClass('nav__link--active')) {
$body.addClass(hoverNavClass);
}
}).on('mouseout', function() {
$body.removeClass(hoverNavClass);
});
},
/**
* By default, the subnavs are loaded in their open state to support JS being disabled.
* If we're here, JS is enabled; if it's a smaller device, close the nav on initial load.
*/
closeSubnavOnSmallerDevices: function() {
var width = $('body').outerWidth();
if (width <= 1000) {
var self = this;
$('.sub-nav__link--dropdown--open').each(function() {
self.toggleSubnav($(this));
});
}
},
/**
* Init module
*/
init: function() {
this.bindEventHandlers();
this.closeSubnavOnSmallerDevices();
}
};
module.exports = nav;<file_sep>/resources/assets/js/modules/layout-switcher/index.js
var $ = require('jquery');
var urlUtil = require('../../util/url');
var layoutSwitcher = {
ACTIVE_CLASS: 'layout-switcher__link--active',
ENABLE_LAYOUT_TRANSITION_CLASS: 'body--layout-transition-enabled',
PREF_STORAGE_KEY: 'tds.layoutPref',
/**
* Toggle between layouts based on layout link clicked
* @param {object} $link
*/
switchLayout: function($link) {
var $parent = $link.parent('.layout-switcher');
var layout = $link.attr('data-layout');
if (layout !== this.getActiveLayout()) {
$parent.find('.layout-switcher__link').not($link).removeClass(this.ACTIVE_CLASS);
$link.addClass(this.ACTIVE_CLASS);
this.removeLayoutClasses(this.$body);
this.$body.addClass('body-layout--' + layout);
this.adjustUrl(layout);
this.adjustPaginationLinks(layout);
this.saveLayoutState(layout);
}
},
/**
* When layout changes adjust param in pagination links.
* @param {string} layout
*/
adjustPaginationLinks: function(layout) {
$('a.pagination__link').each(function() {
var $this = $(this);
var url = $this.prop('href');
$this.prop('href', urlUtil.addReplaceParam('l', layout, url));
});
},
/**
* Based on new layout, adjust url
* @param {string} layout
*/
adjustUrl: function(layout) {
var path = document.location.pathname;
var newSearchString = urlUtil.addReplaceParam('l', layout);
if (newSearchString) {
path += newSearchString;
}
window.history.pushState(null, window.document.title, path);
},
/**
* Save state to localStorage.
* @param {string} layout
*/
saveLayoutState: function(layout) {
window.localStorage.setItem(this.PREF_STORAGE_KEY + '.' + this.appSection, layout);
},
/**
* Remove existing layout classes.
* @param {object} $el
*/
removeLayoutClasses: function($el) {
$el.removeClass(function(index, css) {
return (css.match(/(^|\s)body-layout--\S+/g) || []).join(' ');
});
},
/**
* Get stored layout pref: specific to app section, ie pref could be square for portfolio, circle for pics.
* @return {string}
*/
getLayoutPref: function() {
return window.localStorage.getItem(this.PREF_STORAGE_KEY + '.' + this.appSection);
},
/**
* Get the current active layout if one exists.
*/
getActiveLayout: function() {
return urlUtil.getParam('l');
},
/**
* In the event that the current layout does not match stored preference, switch it.
*/
correctLayout: function() {
var layout = this.getActiveLayout();
var layoutPref = this.getLayoutPref();
if (!_.isNull(layoutPref) && layoutPref !== layout) {
this.switchLayout(this.$layoutSwitcher.find('.layout-switcher__link[data-layout="' + layoutPref + '"]'));
} else {
//the active class is not added by default in the DOM to handle cases where we needed to
//correct layout above(causes noticeable flash in UI). In the event that we did not switch layouts, we'll
//need to add class.
var activeLayout = layout || this.defaultLayout;
this.$layoutSwitcher.find('.layout-switcher__link[data-layout="' + activeLayout + '"]').addClass(this.ACTIVE_CLASS);
}
},
/**
* Bind event handlers for module.
*/
bindEventHandlers: function() {
var self = this;
this.$layoutSwitcher.find('.layout-switcher__link').on('click', function(event) {
event.preventDefault();
self.$body.addClass(self.ENABLE_LAYOUT_TRANSITION_CLASS);
self.switchLayout.call(self, $(this), true);
});
},
/**
* Init module
*
* @param {string} defaultLayout
*/
init: function(defaultLayout) {
this.$layoutSwitcher = $('.layout-switcher');
if (!this.$layoutSwitcher.length) {
return;
}
this.defaultLayout = this.$layoutSwitcher.attr('data-default-layout');
this.$body = $('body');
this.appSection = this.$layoutSwitcher.attr('data-app-section');
this.bindEventHandlers();
this.correctLayout();
}
};
module.exports = layoutSwitcher;<file_sep>/resources/assets/js/modules/portfolio/project.js
import React from 'react';
import _ from 'lodash';
import $ from 'jquery';
import tooltipster from "jquery-tooltipster/js/jquery.tooltipster.js";
const ACTIVE_CLASS = 'project--over-active';
const INACTIVE_CLASS = 'project--over-any';
const HOVER_CLASS = 'project--hover';
/**
* A project lives in a project list.
*/
var Project = React.createClass({
/**
*/
componentDidMount: function() {
this.$el = $(this.getDOMNode());
this.initTooltip();
},
/**
*/
render: function() {
return (
<div className={'project project--template-' + this.getTemplateId() + ' project--key-' + this.props.path}>
<a href={this.buildProjectLink()} className="project__anchor" onMouseOver={this.onMouseOver} onMouseOut={this.onMouseOut}>
<div className="project__img" style={{'backgroundImage': 'url(' + this.getImageUrl() + ')'}}></div>
<label className="project__title" title={this.props.desc + ' Click or touch to view details.'}>{this.props.name}</label>
<div className="project__date">{this.props.years}</div>
</a>
</div>
);
},
/**
* Build project link, pass along current category as bucket param if exists.
* @return {string}
*/
buildProjectLink: function() {
var link = '/portfolio/p/' + this.props.path;
if (!_.isEmpty(this.props.category)) {
link += '?b=' + this.props.category;
}
return link;
},
/**
* Init tooltip, bound to the title, triggered when hovering over entire project.
*/
initTooltip: function() {
this.$el.find('.project__title').tooltipster({
//looks bad on the right at smaller screen sizes.
position: window.innerWidth > 600 ? 'right' : 'bottom',
maxWidth: 300
}).tooltipster('disable');
},
/**
*/
showTooltip: function() {
this.$el.find('.project__title').tooltipster('enable').tooltipster('show');
},
/**
*/
hideTooltip: function() {
this.$el.find('.project__title').tooltipster('hide').tooltipster('disable');
},
/**
* Returns thumbnail image path
* @return string
*/
getImageUrl: function() {
return '/img/portfolio/' + this.props.path + '/main.jpg';
},
/**
* 4 templates per group
* @return {Number}
*/
getTemplateId: function() {
if (this.props.group == 'a') {
if (this.props.index == 0) {
return 1;
}
return 2;
} else if (this.props.index == 1) {
return 4;
}
return 3;
},
/**
* Toggle classes
*/
onMouseOver: function() {
var $project = $('.project--key-' + this.props.path);
$project.addClass(HOVER_CLASS);
var self = this;
//set a slight delay in case it's just a quick over and out.
setTimeout(function() {
if ($project.hasClass(HOVER_CLASS)) {
$('.project').not('.project--key-' + self.props.path).addClass(INACTIVE_CLASS);
$project.addClass(ACTIVE_CLASS);
self.showTooltip();
}
}, 200);
},
/**
* Toggle class
*/
onMouseOut: function() {
$('.project').removeClass(INACTIVE_CLASS + ' ' + ACTIVE_CLASS + ' ' + HOVER_CLASS);
this.hideTooltip();
}
});
module.exports = Project;<file_sep>/README.md
## Tublitzed.com
Tublitzed is the personal portfolio website for <NAME>, living over at [tublitzed.com](http://tublitzed.com/).
## System Requirements
The site is built on top of [Laravel](http://laravel.com/). Before working with this site, you should have the following installed on your local machine:
* [Composer](https://getcomposer.org/)
* [node](https://nodejs.org/en/download/)
* [npm](https://www.npmjs.com/package/npm)
## Installation
1. Add your local .env file. This application uses the [phpdotenv](https://github.com/vlucas/phpdotenv) library.
```javascript
$ cp .env.example .env
```
2. Install PHP dependencies via Composer
```javascript
$ composer install
```
3. Install JavaScript dependencies via NPM
```javascript
$ npm install
```
## Tasks
Watch CSS/JS files and rebuild
```javascript
$ gulp w
```
Run unit tests
```javascript
$ gulp test
```
See gulpfile.js for complete task list.
<file_sep>/.env.example
#GLOBAL-----------------------
APP_KEY=#
APP_CIPHER=#
TWILIO_SID=#
TWILIO_AUTH_TOKEN=#
TWILIO_NUMBER=#
#ENV SPECIFIC-----------------------
APP_URL="#"
APP_DEBUG=#
APP_ENV=#
DB_DATABASE=#
DB_HOST=#
DB_USERNAME=#
DB_PASSWORD=#<file_sep>/app/Http/Controllers/LabsController.php
<?php
namespace App\Http\Controllers;
class LabsController extends Controller
{
public function indexAction() {
$viewData = array(
'section' => 'labs'
);
return view("labs/index", $viewData);
}
}
<file_sep>/resources/assets/js/modules/portfolio/tests/project-list.test.js
import React from 'react';
import _ from 'lodash';
import $ from 'jquery';
let ProjectList = require('../project-list.js');
describe("getPage - no input", function() {
var projectList;
beforeEach(function() {
projectList = new ProjectList();
});
it("should return 1", function() {
assert.equal(projectList.getPage(), 1);
});
});
describe("getPage - with input", function() {
var projectList;
beforeEach(function() {
$('<div>').addClass('pagination').html('<input name="current-page" value="5">').appendTo($('body'));
projectList = new ProjectList();
});
it("should return 5", function() {
assert.equal(projectList.getPage(), 5);
});
afterEach(function() {
$('.pagination').remove();
});
});
describe("buildUrl", function() {
//TODO
});
|
9734e2d771793d65efb49bc85546b5178f56e7c0
|
[
"JavaScript",
"Markdown",
"PHP",
"Shell"
] | 37
|
JavaScript
|
tublitzed/tublitzed
|
74fccd12565df19e64104af7d878045f1ecf5d2c
|
a980d9340b8649edb5e5560dd7d60e255d1fc9f7
|
refs/heads/master
|
<file_sep>#!/bin/bash
cd iudx-api-server
mvn package
cp target/java -jar iudx-api-server-0.0.1-SNAPSHOT-fat.jar .
tmux new-session -d -s vertx 'java -jar iudx-api-server-0.0.1-SNAPSHOT-fat.jar'
<file_sep>#!/bin/bash
directory=`dirname $0`
cd $directory
docker-compose start
docker exec postgres ./scripts/pgsql_start.sh
docker exec broker ./scripts/broker_start.sh
docker exec vertx ./scripts/vertx_start.sh
<file_sep>#!/bin/bash
rm -r /tmp/tmux-* > /dev/null 2>&1
fuser -k 8443/tcp
cd iudx-api-server
mvn package
cp target/iudx-api-server-0.0.1-SNAPSHOT-fat.jar .
tmux new-session -d -s vertx 'java -jar iudx-api-server-0.0.1-SNAPSHOT-fat.jar'
|
76a9130934d94514e7481b193d03b8bd73bc576c
|
[
"Shell"
] | 3
|
Shell
|
HankHannah/iudx
|
24ae9d09068dada04cb48afd7474b47abb641d90
|
08139fea19d628b8ddb0c55a18214ae9466a5f48
|
refs/heads/master
|
<file_sep># simple-temperature-app
A simple temperature app practices on EJS view layer with Express/NodeJS backend
# How to run
git clone https://github.com/ploratran/temperature-app-ejs.git
npm install
npm start
Open on browser: http://localhost:3006<file_sep>$(function() {
var $h1 = $("h1");
var $zip = $("input[name='zip']");
$("form").on("submit", function(event) {
event.preventDefault();
var zipCode = $.trim($zip.val());
$h1.text("Loading...");
$.ajax({
url: "/" + zipCode,
dataType: "json"
})
.done(function(data) {
var temperature = data.temperature;
$h1.html("The current temperature at " + data.zipcode + " is " + temperature + "°F.");
})
.fail(function() {
$h1.html("Error!");
});
});
});
|
afc258d9cbd17e61d0fb1b4c9a04c51a04d7708c
|
[
"Markdown",
"JavaScript"
] | 2
|
Markdown
|
ploratran/temperature-app-ejs
|
3d604232e49b319a31bc3dabf43c7cd84dea80c7
|
042d060d68a29f1f00f68a2f2c1cadfa8ac530e4
|
refs/heads/master
|
<file_sep>package com.dapavlov16.jobsgithubclient;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.Html;
import android.widget.TextView;
import com.dapavlov16.jobsgithubclient.model.Vacancy;
public class VacancyActivity extends AppCompatActivity {
private TextView title;
private TextView company;
private TextView description;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_vacancy);
title = findViewById(R.id.vacancyTitle);
company = findViewById(R.id.vacancyCompany);
description = findViewById(R.id.vacancyDescription);
onIntentReceived(getIntent().getExtras());
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
onIntentReceived(intent.getExtras());
}
private void onIntentReceived(Bundle bundle) {
if (bundle == null || !bundle.containsKey(MainActivity.KEY_VACANCY)) {
throw new IllegalArgumentException("bundle is null or vacancy data is null");
}
Vacancy vacancy = (Vacancy) bundle.getSerializable(MainActivity.KEY_VACANCY);
title.setText(vacancy.getTitle());
company.setText(vacancy.getCompany());
description.setText(Html.fromHtml(vacancy.getDescription()).toString());
}
}
<file_sep>package com.dapavlov16.jobsgithubclient.network;
import com.dapavlov16.jobsgithubclient.RecyclerViewAdapter;
import com.dapavlov16.jobsgithubclient.model.Vacancy;
import java.util.List;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.observers.DisposableSingleObserver;
import io.reactivex.schedulers.Schedulers;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
public class NetworkUtils {
public static void setData(int page, final RecyclerViewAdapter adapter, final boolean isRefresh){
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://jobs.github.com/")
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build();
ApiJobs apiJobs = retrofit.create(ApiJobs.class);
apiJobs.vacancies(page)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new DisposableSingleObserver<List<Vacancy>>() {
@Override
public void onSuccess(final List<Vacancy> vacancyList) {
adapter.setItems(vacancyList, isRefresh);
adapter.notifyDataSetChanged();
/* Пытаюсь записать лист в базу
Completable.fromAction(new Action() {
@Override
public void run() throws Exception {
db.getVacancyDao().insertAll(vacancyList);
}
}).subscribe(new CompletableObserver() {
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onComplete() {
}
@Override
public void onError(Throwable e) {
}
});*/
}
@Override
public void onError(Throwable e) {
e.printStackTrace();
}
});
}
}
<file_sep>package com.dapavlov16.jobsgithubclient;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import com.dapavlov16.jobsgithubclient.database.VacancyDatabase;
import com.dapavlov16.jobsgithubclient.model.Vacancy;
import static com.dapavlov16.jobsgithubclient.network.NetworkUtils.setData;
public class MainActivity extends AppCompatActivity {
private SwipeRefreshLayout swipeRefreshLayout;
private RecyclerView recyclerView;
private RecyclerViewAdapter adapter;
private VacancyDatabase db;
private int page = 1;
public static final String KEY_VACANCY = "VACANCY";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.recyclerView);
swipeRefreshLayout = findViewById(R.id.swiperefresh);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
adapter = new RecyclerViewAdapter(new RecyclerViewAdapter.OnItemClickListener() {
@Override
public void onItemClick(Vacancy item) {
Intent intent = new Intent(MainActivity.this, VacancyActivity.class);
Bundle args = new Bundle();
args.putSerializable(KEY_VACANCY, item);
intent.putExtras(args);
MainActivity.this.startActivity(intent);
}
}, recyclerView);
recyclerView.setAdapter(adapter);
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
swipeRefreshLayout.setRefreshing(true);
page = 1;
setData(page, adapter, true);
swipeRefreshLayout.setRefreshing(false);
}
});
setData(page, adapter, false);
adapter.setOnLoadMoreListener(new RecyclerViewAdapter.OnLoadMoreListener() {
@Override
public void onLoadMore() {
page++;
setData(page, adapter, false);
}
});
}
}
<file_sep>package com.dapavlov16.jobsgithubclient;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.dapavlov16.jobsgithubclient.model.Vacancy;
import java.util.ArrayList;
import java.util.List;
public class RecyclerViewAdapter extends RecyclerView.Adapter<VacancyHolder> {
private List<Vacancy> vacancyList = new ArrayList<>();
private OnItemClickListener onItemClickListener;
private OnLoadMoreListener onLoadMoreListener;
private int totalItemCount;
private int lastVisibleItem;
private int visibleThreshold = 10;
public RecyclerViewAdapter(OnItemClickListener onItemClickListener, RecyclerView recyclerView) {
if (onItemClickListener == null) {
throw new IllegalArgumentException("onItemClickListener can't be null");
}
this.onItemClickListener = onItemClickListener;
final LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
totalItemCount = layoutManager.getItemCount();
lastVisibleItem = layoutManager.findLastVisibleItemPosition();
if(totalItemCount <= (lastVisibleItem + visibleThreshold)){
if (onLoadMoreListener != null){
onLoadMoreListener.onLoadMore();
}
}
}
});
}
public void setItems(List<Vacancy> vacancyList, boolean refresh){
if (refresh){
this.vacancyList.clear();
}
this.vacancyList.addAll(vacancyList);
}
@NonNull
@Override
public VacancyHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
LayoutInflater inflater = LayoutInflater.from(viewGroup.getContext());
View view = inflater.inflate(R.layout.item_vacancy, viewGroup, false);
return new VacancyHolder(view);
}
@Override
public void onBindViewHolder(@NonNull VacancyHolder vacancyHolder, int i) {
vacancyHolder.bind(vacancyList.get(i), onItemClickListener);
}
@Override
public int getItemCount() {
return vacancyList.size();
}
public interface OnItemClickListener {
void onItemClick(Vacancy item);
}
public interface OnLoadMoreListener {
void onLoadMore();
}
public void setOnLoadMoreListener(OnLoadMoreListener onLoadMoreListener){
this.onLoadMoreListener = onLoadMoreListener;
}
}
|
576ac88da435f24669589842735375a31d1f00dd
|
[
"Java"
] | 4
|
Java
|
dapavlov16/JobsGithubClient
|
ba310fd69e644dcbeb2bfb707f2c14573bb28a83
|
111b1b480b38c8a4766653e4b66d4f24a8bd41a3
|
refs/heads/master
|
<file_sep>#include <Windows.h>
#include <XInput.h>
#pragma comment(lib, "xinput.lib")
int main(){
XINPUT_VIBRATION vibration;
vibration.wLeftMotorSpeed = 0xFFFF;
vibration.wRightMotorSpeed = 0;
XInputSetState(0, &vibration);
Sleep(10000);
vibration.wLeftMotorSpeed = 0;
vibration.wRightMotorSpeed = 0;
XInputSetState(0, &vibration);
return 0;
}<file_sep>#include <Windows.h>
#define SCREEN_X 120
#define SCREEN_Y 30
HANDLE frontBuffer, backBuffer;
void swapBuffer() {
HANDLE temp;
temp = frontBuffer;
frontBuffer = backBuffer;
backBuffer = temp;
SetConsoleActiveScreenBuffer(frontBuffer);
}
int main(){
COORD pos = {0, 0}, size = {SCREEN_X, SCREEN_Y};
SMALL_RECT region = {0, 0, SCREEN_X, SCREEN_Y};
CHAR_INFO *bitmap;
frontBuffer = CreateConsoleScreenBuffer(
GENERIC_WRITE, FILE_SHARE_WRITE, NULL, CONSOLE_TEXTMODE_BUFFER, NULL);
backBuffer = CreateConsoleScreenBuffer(
GENERIC_WRITE, FILE_SHARE_WRITE, NULL, CONSOLE_TEXTMODE_BUFFER, NULL);
SetConsoleActiveScreenBuffer(backBuffer);
bitmap = (CHAR_INFO *)malloc(sizeof(CHAR_INFO) * SCREEN_X * SCREEN_Y);
// Main loop
while(true) {
for(int i=0; i<SCREEN_X * SCREEN_Y; i++) {
bitmap[i].Char.AsciiChar = (char)' ';
bitmap[i].Attributes = 0b0111;
}
WriteConsoleOutput(backBuffer, bitmap, size, pos, ®ion);
swapBuffer();
}
return 0;
}<file_sep>#include <Windows.h>
#include <math.h>
#define NUM 1000
#define TWOPI (2 * 3.14159)
#define SCREEN_X 640
#define SCREEN_Y 480
#define CONSOLE_X 120
#define CONSOLE_Y 90
#define CONVERT_0BGR_TO_0RGB(crColor) (0b00000000 | (crColor & 0x0800) >> 9 | (crColor & 0x0080) >> 6 | (crColor & 0x0008) >> 3)
#pragma comment(lib, "user32.lib")
#pragma comment(lib, "gdi32.lib")
HANDLE consoleBuffer;
CHAR_INFO *charBuffer;
COORD pos = {0, 0}, size = {CONSOLE_X, CONSOLE_Y};
SMALL_RECT region = {0, 0, CONSOLE_X, CONSOLE_Y};
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR szCmdLine, int iCmdShow) {
static TCHAR szAppName[] = TEXT("SineWave");
HWND hwnd;
MSG msg;
WNDCLASS wndclass;
wndclass.style = CS_HREDRAW | CS_VREDRAW;
wndclass.lpfnWndProc = WndProc;
wndclass.cbClsExtra = 0;
wndclass.cbWndExtra = 0;
wndclass.hInstance = hInstance;
wndclass.hIcon = LoadIcon(NULL, IDI_APPLICATION);
wndclass.hCursor = LoadCursor(NULL, IDC_ARROW);
wndclass.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
wndclass.lpszMenuName = NULL;
wndclass.lpszClassName = szAppName;
// Prepare console
AllocConsole();
consoleBuffer = CreateConsoleScreenBuffer(GENERIC_WRITE, FILE_SHARE_WRITE, NULL, CONSOLE_TEXTMODE_BUFFER, NULL);
SetConsoleActiveScreenBuffer(consoleBuffer);
charBuffer = (CHAR_INFO *)malloc(sizeof(CHAR_INFO) * CONSOLE_X * CONSOLE_Y);
if(!RegisterClass(&wndclass)) {
MessageBox(NULL, TEXT("Program requires Windows NT."), szAppName, MB_ICONERROR);
return 0;
}
hwnd = CreateWindow(szAppName, TEXT("Sine Wave Using Polyline"),
WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, CW_USEDEFAULT, SCREEN_X, SCREEN_Y,
NULL, NULL, hInstance, NULL);
ShowWindow(hwnd, iCmdShow);
UpdateWindow(hwnd);
while(GetMessage(&msg, NULL, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return msg.wParam;
return 0;
}
LRESULT CALLBACK WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) {
static int cxClient, cyClient;
HDC hdc;
PAINTSTRUCT ps;
POINT apt[NUM];
static HBITMAP hbmpBMP, hbmpOld;
static HDC hdcBMP;
static BITMAPINFO biBMP;
static LPDWORD lpdwPixel;
int i, j;
switch(message) {
case WM_CREATE:
ZeroMemory(&biBMP, sizeof(biBMP));
biBMP.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
biBMP.bmiHeader.biBitCount = 32;
biBMP.bmiHeader.biPlanes = 1;
biBMP.bmiHeader.biWidth = CONSOLE_X;
biBMP.bmiHeader.biHeight = -CONSOLE_Y;
hbmpBMP = CreateDIBSection(NULL, &biBMP, DIB_RGB_COLORS, (void **)(&lpdwPixel), NULL, 0);
hdc = GetDC(hwnd);
hdcBMP = CreateCompatibleDC(hdc);
ReleaseDC(hwnd, hdc);
hbmpOld = (HBITMAP)SelectObject(hdcBMP, hbmpBMP);
case WM_SIZE:
cxClient = LOWORD(lParam);
cyClient = HIWORD(lParam);
return 0;
case WM_PAINT:
hdc = BeginPaint(hwnd, &ps);
for(i=0; i<CONSOLE_X * CONSOLE_Y; i++) {
lpdwPixel[i] = 0x00FFFFFF;
}
MoveToEx(hdc, 0, cyClient / 2, NULL);
LineTo(hdc, cxClient, cyClient / 2);
for(i=0; i<NUM; i++) {
apt[i].x = i * cxClient / NUM;
apt[i].y = (int)(cyClient / 2 * (1 - sin(TWOPI * i / NUM)));
}
Polyline(hdc, apt, NUM);
StretchBlt(hdcBMP, 0, 0, CONSOLE_X, CONSOLE_Y, hdc, 0, 0, cxClient, cyClient, SRCCOPY);
// Draw to console buffer
COLORREF crColor;
for(int i=0; i<CONSOLE_X * CONSOLE_Y; i++) {
crColor = lpdwPixel[i];
charBuffer[i].Char.AsciiChar = (char)' ';
charBuffer[i].Attributes = CONVERT_0BGR_TO_0RGB(crColor) << 4;
}
WriteConsoleOutput(consoleBuffer, charBuffer, size, pos, ®ion);
EndPaint(hwnd, &ps);
return 0;
case WM_DESTROY:
PostQuitMessage(0);
SelectObject(hdcBMP, hbmpOld);
DeleteObject(hbmpBMP);
DeleteDC(hdcBMP);
return 0;
}
return DefWindowProc(hwnd, message, wParam, lParam);
}<file_sep>#include <Windows.h>
#include <math.h>
#define NUM 1000
#define TWOPI (2 * 3.14159)
#pragma comment(lib, "user32.lib")
#pragma comment(lib, "gdi32.lib")
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR szCmdLine, int iCmdShow) {
static TCHAR szAppName[] = TEXT("SineWave");
HWND hwnd;
MSG msg;
WNDCLASS wndclass;
wndclass.style = CS_HREDRAW | CS_VREDRAW;
wndclass.lpfnWndProc = WndProc;
wndclass.cbClsExtra = 0;
wndclass.cbWndExtra = 0;
wndclass.hInstance = hInstance;
wndclass.hIcon = LoadIcon(NULL, IDI_APPLICATION);
wndclass.hCursor = LoadCursor(NULL, IDC_ARROW);
wndclass.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
wndclass.lpszMenuName = NULL;
wndclass.lpszClassName = szAppName;
if(!RegisterClass(&wndclass)) {
MessageBox(NULL, TEXT("Program requires Windows NT."), szAppName, MB_ICONERROR);
return 0;
}
hwnd = CreateWindow(szAppName, TEXT("Sine Wave Using Polyline"),
WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, CW_USEDEFAULT, 128, 128,
NULL, NULL, hInstance, NULL);
ShowWindow(hwnd, iCmdShow);
UpdateWindow(hwnd);
while(GetMessage(&msg, NULL, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return msg.wParam;
return 0;
}
LRESULT CALLBACK WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) {
static int cxClient, cyClient;
HDC hdc;
int i;
PAINTSTRUCT ps;
POINT apt[NUM];
switch(message) {
case WM_SIZE:
cxClient = LOWORD(lParam);
cyClient = HIWORD(lParam);
return 0;
case WM_PAINT:
hdc = BeginPaint(hwnd, &ps);
MoveToEx(hdc, 0, cyClient / 2, NULL);
LineTo(hdc, cxClient, cyClient / 2);
for(i=0; i<NUM; i++) {
apt[i].x = i * cxClient / NUM;
apt[i].y = (int)(cyClient / 2 * (1 - sin(TWOPI * i / NUM)));
}
Polyline(hdc, apt, NUM);
return 0;
case WM_DESTROY:
PostQuitMessage(0);
return 0;
}
return DefWindowProc(hwnd, message, wParam, lParam);
}<file_sep># practice
練習とか実験とか
多分ほとんど cl でコンパイルできる<file_sep>#include <Windows.h>
#include <math.h>
#include <string.h>
#include <Eigen/Core>
#include <Eigen/Geometry>
#define SCREEN_X 128
#define SCREEN_Y 128
#define CHAR_ON 'W'
#define CHAR_OFF ' '
HANDLE frontBuffer, backBuffer;
void swapBuffer() {
HANDLE temp;
temp = frontBuffer;
frontBuffer = backBuffer;
backBuffer = temp;
SetConsoleActiveScreenBuffer(frontBuffer);
}
void rotate(CHAR_INFO *matrix, CHAR_INFO *rotated, Eigen::Vector3d vRadian) {
for(int i=0; i<SCREEN_X; i++) {
for(int j=0; j<SCREEN_Y; j++) {
rotated[i*SCREEN_X + j].Char.UnicodeChar = CHAR_OFF;
rotated[i*SCREEN_X + j].Attributes = 0b0111;
}
}
Eigen::Vector2d v1;
Eigen::Vector2d vCenter(SCREEN_X / 2, SCREEN_Y / 2);
Eigen::Matrix2d mRotateX;
Eigen::Matrix2d mRotateY;
Eigen::Matrix2d mRotateZ;
Eigen::Matrix2d mRotate;
mRotateX << 1, 0,
0, 1;
mRotateY << cos(vRadian.y()), 0,
0, 1;
mRotateZ << cos(vRadian.z()), -1 * sin(vRadian.z()),
sin(vRadian.z()), cos(vRadian.z());
mRotate = mRotateZ * mRotateY * mRotateX;
Eigen::Vector2d vRotated;
for(int i=0; i<SCREEN_Y; i++) {
for(int j=0; j<SCREEN_X; j++) {
int x, y;
v1.x() = j;
v1.y() = i;
v1 -= vCenter;
vRotated = mRotate * v1;
vRotated += vCenter;
x = vRotated.x();
y = vRotated.y();
if(x>0 && x<SCREEN_X && y>0 && y<SCREEN_Y) {
memcpy(&rotated[y*SCREEN_X+x], &matrix[i*SCREEN_X+j], sizeof(CHAR_INFO));
}
}
}
}
int main(){
COORD pos = {0, 0}, size = {SCREEN_X, SCREEN_Y};
SMALL_RECT region = {0, 0, SCREEN_X, SCREEN_Y};
CHAR_INFO *matrix, *rotated;
Eigen::Vector3d vRotation(0, 0, 0);
frontBuffer = CreateConsoleScreenBuffer(
GENERIC_WRITE, FILE_SHARE_WRITE, NULL, CONSOLE_TEXTMODE_BUFFER, NULL);
backBuffer = CreateConsoleScreenBuffer(
GENERIC_WRITE, FILE_SHARE_WRITE, NULL, CONSOLE_TEXTMODE_BUFFER, NULL);
SetConsoleActiveScreenBuffer(backBuffer);
matrix = (CHAR_INFO *)malloc(sizeof(CHAR_INFO) * (SCREEN_X * SCREEN_Y));
rotated = (CHAR_INFO *)malloc(sizeof(CHAR_INFO) * (SCREEN_X * SCREEN_Y));
// Generate image
for(int i=0; i<SCREEN_X; i++) {
for(int j=0; j<SCREEN_Y; j++) {
WCHAR temp;
if((i>SCREEN_Y/4 && i<SCREEN_Y/4*3) && (j>SCREEN_X/4 && j<SCREEN_X/4*3)) {
matrix[i*SCREEN_X + j].Char.UnicodeChar = CHAR_ON;
if(i<SCREEN_Y/2) {
if(j<SCREEN_X/2) {
matrix[i*SCREEN_X + j].Attributes = 0b0100;
}
if(j>=SCREEN_X/2) {
matrix[i*SCREEN_X + j].Attributes = 0b0010;
}
}
if(i>=SCREEN_Y/2) {
if(j<SCREEN_X/2) {
matrix[i*SCREEN_X + j].Attributes = 0b0001;
}
if(j>=SCREEN_X/2) {
matrix[i*SCREEN_X + j].Attributes = 0b0110;
}
}
}
else {
matrix[i*SCREEN_X + j].Char.UnicodeChar = CHAR_OFF;
matrix[i*SCREEN_X + j].Attributes = 0b0111;
}
}
}
// Main loop
while(true) {
rotate(matrix, rotated, vRotation);
// 適当に回す
vRotation.x() += (3.1415926535 * 2) / 720;
vRotation.y() += (2.1415926535 * 2) / 320;
vRotation.z() += (3.1415926535 * 2) / 520;
WriteConsoleOutput(backBuffer, rotated, size, pos, ®ion);
// Sleep(1000/60);
swapBuffer();
}
return 0;
}
|
e7d29e83e05e952e3d2d8a6337d3b9d1199dbc92
|
[
"Markdown",
"C++"
] | 6
|
C++
|
mucho613/practice
|
9d4dc57f07a55bb879940dac63e63b7c4188f49c
|
cdd94434cdd2eea4a3c13408a409053fad54892c
|
refs/heads/master
|
<repo_name>DeKinci/budding-jack<file_sep>/src/test/com/dekinci/contest/game/tactics/ConnectMinesTacticsTest.kt
package com.dekinci.contest.game.tactics
import com.dekinci.contest.connectedMap
import org.junit.jupiter.api.Test
internal class ConnectMinesTacticsTest {
@Test
fun isFinished() {
}
@Test
fun isSuccessful() {
}
@Test
fun hasNext() {
}
@Test
operator fun next() {
val tactics = ConnectMinesTactics(0, connectedMap(), 3, 5)
while (tactics.hasNext())
println(tactics.next())
}
}<file_sep>/src/main/kotlin/com/dekinci/contest/game/minimax/MinimaxRunner.kt
package com.dekinci.contest.game.minimax
import com.dekinci.contest.entities.StatedRiver
import java.util.concurrent.Executors
import java.util.concurrent.Future
class MinimaxRunner(val minimax: Minimax) {
private val executor = Executors.newSingleThreadExecutor()
private var task: Future<*>? = null
fun update(river: StatedRiver) {
minimax.update(river)
}
}<file_sep>/src/main/kotlin/com/dekinci/contest/game/map/GameMap.kt
package com.dekinci.contest.game.map
import com.dekinci.contest.entities.BasicMap
import com.dekinci.contest.entities.RiverStateID
import com.dekinci.contest.entities.StatedRiver
import com.dekinci.contest.game.map.graph.AdjacencyList
import com.dekinci.contest.game.map.graph.AdjacencyMatrix
import com.dekinci.contest.game.map.metric.ConnectionsMetrics
import com.dekinci.contest.game.map.metric.DistanceMetrics
import java.util.*
import kotlin.collections.HashMap
import kotlin.collections.HashSet
class GameMap(val basicMap: BasicMap) {
data class Island(val cost: Int, val sites: Set<Int>, val mines: Set<Int>)
private val adjMatrix = AdjacencyMatrix(basicMap.size, basicMap.rivers)
private val adjList = AdjacencyList(basicMap.size, basicMap.rivers)
private val freeAdjList = AdjacencyList(basicMap.size, basicMap.rivers)
val islands: Set<Island>
val squareMetrics = DistanceMetrics(basicMap.size, adjList, basicMap.mines) { it * it }
val linearMetrics = DistanceMetrics(basicMap.size, adjList, basicMap.mines) { it }
val connectionsMetrics = ConnectionsMetrics(basicMap.size, adjList)
init {
squareMetrics.calculate()
linearMetrics.calculate()
islands = initIslands()
}
private fun initIslands(): Set<Island> {
data class TempIsland(var cost: Int, val sites: HashSet<Int> = HashSet())
val islandMap = HashMap<Set<Int>, TempIsland>()
(0 until basicMap.size).forEach {
val connectedMines = squareMetrics.getJointMines(it)
islandMap.getOrPut(connectedMines) { TempIsland(0) }.apply {
cost += squareMetrics.costHavingMines(it, connectedMines)
sites.add(it)
}
}
return islandMap.entries.map { Island(it.value.cost, it.value.sites, it.key) }.toHashSet()
}
fun update(statedRiver: StatedRiver) {
adjMatrix[statedRiver.source, statedRiver.target] = statedRiver.state
freeAdjList.removeEdge(statedRiver.source, statedRiver.target)
connectionsMetrics.update(statedRiver.source)
connectionsMetrics.update(statedRiver.target)
}
fun hasFreeConnections(site: Int): Boolean = freeAdjList.countConnections(site) != 0
fun isSiteConnectedWithAny(first: Int, others: Collection<Int>) = !Collections.disjoint(adjList[first], others)
fun isSiteConnectedWith(first: Int, second: Int) = adjList.list[first].contains(second)
fun getConnections(site: Int) = adjList[site]
fun isSiteConnectedToTaken(site: Int): Boolean {
val connections = getConnections(site)
for (c in connections)
if (adjMatrix[site, c] != RiverStateID.NEUTRAL)
return true
return false
}
fun getFreeConnections(site: Int): Collection<Int> = freeAdjList[site]
fun getAvailableConnections(site: Int, punter: Int): Collection<Int> =
getConnections(site).filter { adjMatrix[site, it] == RiverStateID.NEUTRAL || adjMatrix[site, it] == punter }
}<file_sep>/src/main/kotlin/com/dekinci/contest/common/Utils.kt
package com.dekinci.contest.common
import com.dekinci.contest.entities.River
import com.dekinci.contest.entities.StatedRiver
fun riversToSiteSet(rivers: Iterable<River>): HashSet<Int> {
val res = HashSet<Int>()
rivers.forEach {
res.add(it.source)
res.add(it.target)
}
return res
}
fun statedRiversToSiteSet(rivers: Iterable<StatedRiver>): HashSet<Int> {
val res = HashSet<Int>()
rivers.forEach {
res.add(it.source)
res.add(it.target)
}
return res
}<file_sep>/src/test/com/dekinci/contest/game/map/DistanceMetricsTest.kt
package com.dekinci.contest.game.map
import com.dekinci.contest.disconnectedMap
import com.dekinci.contest.entities.River
import com.dekinci.contest.microMap
import com.dekinci.contest.nanoMap
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Test
internal class DistanceMetricsTest {
@Test
fun mineCost() {
val nano = nanoMap().squareMetrics
assertEquals(1, nano.mineCost(0))
val micro = microMap().squareMetrics
assertEquals(9, micro.mineCost(0))
assertEquals(9, micro.mineCost(2))
val disco = disconnectedMap().squareMetrics
assertEquals(1, disco.mineCost(5))
assertEquals(23, disco.mineCost(3))
assertEquals(23, disco.mineCost(2))
}
@Test
fun siteCost() {
val micro = microMap().squareMetrics
assertEquals(4, micro.siteCost(0))
assertEquals(2, micro.siteCost(1))
}
@Test
fun getJointMines() {
val micro = microMap().squareMetrics
assertEquals(setOf(0, 2), micro.getJointMines(1))
val disco = disconnectedMap().squareMetrics
assertEquals(setOf(2, 3), disco.getJointMines(4))
assertEquals(setOf(2, 3), disco.getJointMines(2))
assertEquals(setOf(5), disco.getJointMines(8))
}
@Test
fun costHavingMines() {
val disco = disconnectedMap().squareMetrics
assertEquals(1, disco.costHavingMines(4, setOf(2)))
assertEquals(0, disco.costHavingMines(2, setOf(2)))
assertEquals(9, disco.costHavingMines(2, setOf(2, 3)))
assertEquals(8, disco.costHavingMines(7, setOf(2, 3)))
assertEquals(0, disco.costHavingMines(7, setOf(5)))
}
@Test
fun costHavingSites() {
val disco = disconnectedMap().squareMetrics
assertEquals(1, disco.costHavingSites(2, setOf(4)))
assertEquals(5, disco.costHavingSites(2, setOf(4, 7)))
assertEquals(0, disco.costHavingSites(2, setOf(5, 8)))
assertEquals(1, disco.costHavingSites(5, setOf(5, 8)))
assertEquals(0, disco.costHavingSites(3, setOf(3)))
}
@Test
fun costHaving() {
val disco = disconnectedMap().squareMetrics
assertEquals(1, disco.costHaving(setOf(2, 4)))
assertEquals(33, disco.costHaving(setOf(0, 1, 2, 3, 4)))
assertEquals(1, disco.costHaving(setOf(5, 8, 6, 0, 1)))
assertEquals(0, disco.costHaving(setOf(7, 8, 0)))
assertEquals(0, disco.costHaving(setOf(3)))
}
@Test
fun costHavingRivers() {
val disco = disconnectedMap().squareMetrics
assertEquals(0, disco.costHavingRivers(setOf(River(1, 4))))
assertEquals(1, disco.costHavingRivers(setOf(River(2, 4))))
assertEquals(2, disco.costHavingRivers(setOf(River(2, 4), River(3, 0))))
assertEquals(5, disco.costHavingRivers(setOf(River(2, 4), River(4, 0))))
assertEquals(28, disco.costHavingRivers(setOf(
River(2, 4),
River(4, 0),
River(3, 0))))
assertEquals(29, disco.costHavingRivers(setOf(
River(2, 4),
River(4, 0),
River(3, 0),
River(5, 8))))
}
@Test
fun get() {
val disco = disconnectedMap().squareMetrics
assertEquals(0, disco[2, 2])
assertEquals(9, disco[2, 3])
assertEquals(-1, disco[3, 8])
assertEquals(4, disco[3, 4])
}
}<file_sep>/src/main/kotlin/com/dekinci/contest/protocol/Messages.kt
package com.dekinci.contest.protocol
import com.dekinci.contest.entities.River
import com.fasterxml.jackson.annotation.JsonCreator
import com.fasterxml.jackson.annotation.JsonIgnoreProperties
import com.fasterxml.jackson.databind.JsonNode
data class HandshakeRequest(val me: String)
data class HandshakeResponse(val you: String)
@JsonIgnoreProperties(ignoreUnknown = true)
data class Site(val id: Int)
data class Map(val sites: List<Site>, val rivers: List<River>, val mines: List<Int>)
data class Setup(val punter: Int, val punters: Int, val map: Map, val settings: JsonNode?)
data class Ready(val ready: Int)
data class Pass(val punter: Int)
data class Claim(val punter: Int, val source: Int, val target: Int)
data class PassMove(val pass: Pass): Move()
data class ClaimMove(val claim: Claim): Move()
sealed class Move {
companion object {
@JvmStatic
@JsonCreator
fun factory(map: kotlin.collections.Map<String, Any>): Move {
return when {
"pass" in map -> objectMapper.convertValue(map, PassMove::class.java)
"claim" in map -> objectMapper.convertValue(map, ClaimMove::class.java)
else -> throw IllegalArgumentException()
}
}
}
}
data class GameTurn(val moves: List<Move>)
data class GameTurnMessage(val move: GameTurn): ServerMessage()
data class Score(val punter: Int, val score: Int)
data class GameStop(val moves: List<Move>, val scores: List<Score>)
data class GameResult(val stop: GameStop): ServerMessage()
data class Timeout(val timeout: Double): ServerMessage()
@JsonIgnoreProperties(ignoreUnknown = true)
class Staff: ServerMessage()
sealed class ServerMessage {
companion object {
@JvmStatic
@Synchronized
@JsonCreator
fun factory(map: kotlin.collections.Map<String, Any>): ServerMessage {
return when {
"move" in map -> objectMapper.convertValue(map, GameTurnMessage::class.java)
"stop" in map -> objectMapper.convertValue(map, GameResult::class.java)
"timeout" in map -> objectMapper.convertValue(map, Timeout::class.java)
"map" in map -> objectMapper.convertValue(map, Staff::class.java)
else -> throw IllegalArgumentException()
}
}
}
}
<file_sep>/src/test/com/dekinci/contest/game/minimax/ConnectionsTest.kt
package com.dekinci.contest.game.minimax
import com.dekinci.contest.disconnectedMap
import com.dekinci.contest.entities.River
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
internal class ConnectionsTest {
private var connections = Connections(emptySet())
@BeforeEach
fun setCons() {
connections = Connections(setOf(1, 2, 6))
}
@Test
fun addRiver() {
val newC = connections
.addRiver(River(4, 1))
.addRiver(River(7, 10))
.addRiver(River(4, 6))
println(newC)
println(newC.addRiver(River(6, 7)))
}
@Test
fun cost() {
val gm = disconnectedMap()
val newC = Connections(gm.basicMap.mines)
.addRiver(River(3, 0))
.addRiver(River(0, 1))
.addRiver(River(3, 6))
.addRiver(River(4, 7))
.addRiver(River(5, 8))
assertEquals(7, newC.cost(gm.squareMetrics))
}
}<file_sep>/src/main/kotlin/com/dekinci/contest/game/strategy/BuildEmpireStrategy.kt
package com.dekinci.contest.game.strategy
import com.dekinci.contest.common.Log.debug
import com.dekinci.contest.common.Log.err
import com.dekinci.contest.common.Log.trace
import com.dekinci.contest.common.Log.warn
import com.dekinci.contest.entities.StatedRiver
import com.dekinci.contest.game.GameState
import com.dekinci.contest.game.map.GameMap
import com.dekinci.contest.game.tactics.ConnectMinesTactics
import com.dekinci.contest.game.tactics.PassTactics
import com.dekinci.contest.game.tactics.PathFinder
import com.dekinci.contest.game.tactics.Tactics
import kotlin.math.min
class BuildEmpireStrategy(private val gameState: GameState) : Strategy {
private var tactics: Tactics = PassTactics()
private var island: GameMap.Island? = null
init {
chooseIsland()
chooseTactics()
}
override fun isFinished() = tactics is PassTactics
override fun isSuccessful(): Boolean {
return true
}
override fun next(): StatedRiver? {
if (hasNext())
return tactics.next()
return null
}
override fun hasNext(): Boolean {
if (tactics is PassTactics)
return false
var counter = 3
while (!tactics.hasNext() && counter > 0) {
if(!chooseTactics())
return false
counter--
}
return tactics.hasNext()
}
private fun chooseIsland() {
for (isl in gameState.gameMap.islands)
if (island == null || isl.cost > island!!.cost)
island = isl
debug("Chosen island cost: ${island!!.cost}, mines: ${island!!.mines}")
}
private fun chooseTactics(): Boolean {
val cities = island!!.mines
.map { it to gameState.gameMap.squareMetrics.mineCost(it).toDouble() }
.sortedBy { it.second }.reversed()
trace("Chosen possible cities: $cities")
var possibleCities = cities
// .filter { !gameState.gameMap.ourSites.contains(it.first) } TODO
if (possibleCities.isEmpty()) {
tactics = PassTactics()
warn("No possible cities")
return false
}
if (possibleCities.size < 2)
possibleCities += cities.subtract(possibleCities).take(1)
trace("Chosen possible cities: $possibleCities")
val bestCity = possibleCities.maxBy { it.second }
if (bestCity == null) {
err("Could not find best city")
tactics = PassTactics()
return false
}
trace("best city is ${bestCity.first} with a score ${bestCity.second}")
val fancyScore = bestCity.second * 0.9
val fancyCities = possibleCities.filter { it.second >= fancyScore }.toMutableList()
if (fancyCities.size < 2)
fancyCities.add(possibleCities.subList(1, possibleCities.size).first())
trace("Chosen fancy cities: $fancyCities")
var first = -1
var second = -1
var maxMetric = -1.0
for (a in 0 until fancyCities.size)
for (b in 0 until a) {
val metric = (fancyCities[a].second + fancyCities[b].second) /
(1.1 - 1 / Math.pow(estimateK(fancyCities[a].first, fancyCities[b].first).toDouble(), 2.0))
trace("Metric for ${fancyCities[a].first} to ${fancyCities[b].first} is $metric")
if (metric > maxMetric) {
maxMetric = metric
first = fancyCities[a].first
second = fancyCities[b].first
}
}
debug("Chosen cities: $first, $second")
tactics = ConnectMinesTactics(gameState.punter, gameState.gameMap, first, second)
return true
}
private fun estimateK(from: Int, to: Int): Int {
val pf = PathFinder(gameState.gameMap)
val threshold = min(
gameState.gameMap.getAvailableConnections(from, gameState.punter).size,
gameState.gameMap.getAvailableConnections(to, gameState.punter).size)
val listPaths = ArrayList<List<Int>>()
while (listPaths.size <= threshold) {
val path = pf.findPath(from, to, gameState.punter, listPaths)
if (!path.isEmpty())
listPaths.add(listOf(from) + path)
else
break
}
trace("Estimated K from $from to $to is ${listPaths.size}")
return listPaths.size
}
}<file_sep>/src/main/kotlin/com/dekinci/contest/game/map/graph/Dijkstra.kt
package com.dekinci.contest.game.map.graph
import java.util.*
class Dijkstra(private val vertexAmount: Int, private val adjacencyList: AdjacencyList) {
private val INF = Integer.MAX_VALUE / 2
fun sparse(start: Int): IntArray {
val queue = LinkedList<Int>()
val dist = IntArray(vertexAmount) { INF }
dist[start] = 0
queue.add(start)
while (!queue.isEmpty()) {
val from = queue.first()
queue.remove(from)
for (to in adjacencyList[from])
if (dist[from] + 1 < dist[to]) {
queue.remove(to)
queue.addLast(to)
dist[to] = dist[from] + 1
}
}
for (i in 0 until dist.size)
if (dist[i] == INF)
dist[i] = -1
return dist
}
}<file_sep>/src/main/kotlin/com/dekinci/contest/game/player/PlayersManager.kt
package com.dekinci.contest.game.player
import com.dekinci.contest.game.GameState
class PlayersManager(gameState: GameState, playersAmount: Int) {
private val players = ArrayList<Player>(playersAmount)
init {
for (i in 0 until playersAmount)
players.add(Player(gameState.gameMap))
}
fun claimSite() {
TODO()
}
}<file_sep>/src/test/com/dekinci/contest/game/map/GameMapTest.kt
package com.dekinci.contest.game.map
import com.dekinci.contest.connectedMap
import com.dekinci.contest.disconnectedMap
import com.dekinci.contest.entities.StatedRiver
import com.dekinci.contest.microMap
import com.dekinci.contest.nanoMap
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.Assertions.*
internal class GameMapTest {
//TODO
@Test
fun getIslands() {
assertEquals(2, disconnectedMap().islands.size)
assertEquals(1, connectedMap().islands.size)
assertEquals(1, nanoMap().islands.size)
}
@Test
fun update() {
val gm = nanoMap()
gm.update(StatedRiver(0, 1, 0))
assertFalse(gm.hasFreeConnections(0))
assertFalse(gm.hasFreeConnections(1))
}
@Test
fun hasFreeConnections() {
val gm = microMap()
gm.update(StatedRiver(0, 1, 0))
assertTrue(gm.hasFreeConnections(1))
assertTrue(gm.hasFreeConnections(2))
assertTrue(gm.hasFreeConnections(3))
assertFalse(gm.hasFreeConnections(0))
}
@Test
fun isSiteConnectedWithAny() {
val gm = microMap()
assertFalse(gm.isSiteConnectedWithAny(0, setOf(2, 3)))
assertTrue(gm.isSiteConnectedWithAny(0, setOf(1)))
assertTrue(gm.isSiteConnectedWithAny(0, setOf(1, 2, 3)))
}
@Test
fun isSiteConnectedWith() {
val gm = microMap()
assertFalse(gm.isSiteConnectedWith(0, 2))
assertTrue(gm.isSiteConnectedWith(0, 1))
}
@Test
fun getConnections() {
val gm = microMap()
gm.update(StatedRiver(0, 1, 0))
assertEquals(setOf(1), gm.getConnections(0))
assertEquals(setOf(0, 2, 3), gm.getConnections(1))
}
@Test
fun isSiteConnectedToTaken() {
val gm = microMap()
gm.update(StatedRiver(0, 1, 0))
assertTrue(gm.isSiteConnectedToTaken(0))
assertFalse(gm.isSiteConnectedToTaken(2))
}
@Test
fun getFreeConnections() {
val gm = microMap()
gm.update(StatedRiver(0, 1, 0))
assertEquals(emptyList<Int>(), gm.getFreeConnections(0))
assertEquals(listOf(2, 3), gm.getFreeConnections(1))
assertEquals(listOf(1), gm.getFreeConnections(2))
}
@Test
fun getAvailableConnections() {
val gm = microMap()
gm.update(StatedRiver(0, 1, 0))
gm.update(StatedRiver(2, 1, 1))
assertEquals(listOf(1), gm.getAvailableConnections(0, 0))
assertEquals(emptyList<Int>(), gm.getAvailableConnections(0, 1))
assertEquals(listOf(0, 3), gm.getAvailableConnections(1, 0))
assertEquals(listOf(2, 3), gm.getAvailableConnections(1, 1))
assertEquals(emptyList<Int>(), gm.getAvailableConnections(2, 0))
assertEquals(listOf(1), gm.getAvailableConnections(2, 1))
}
}<file_sep>/src/main/kotlin/com/dekinci/contest/game/minimax/Connections.kt
package com.dekinci.contest.game.minimax
import com.dekinci.contest.entities.River
import com.dekinci.contest.game.map.metric.DistanceMetrics
import java.util.*
import kotlin.collections.HashSet
class Connections(private val allMines: Set<Int>) {
private inner class ConnectionGroup(
val mines: MutableSet<Int> = HashSet(),
val sites: MutableSet<Int> = HashSet()
) {
fun fits(river: River) = river.target in sites || river.source in sites
fun add(river: River) {
if (river.source in allMines)
mines.add(river.source)
if (river.target in allMines)
mines.add(river.target)
sites.add(river.source)
sites.add(river.target)
}
fun merge(other: ConnectionGroup) {
mines.addAll(other.mines)
sites.addAll(other.sites)
}
}
private constructor(allMines: Set<Int>, groups: Set<ConnectionGroup>) : this(allMines) {
this.groups.addAll(groups)
}
private val groups = Collections.newSetFromMap(IdentityHashMap<ConnectionGroup, Boolean>())
fun addRiver(river: River): Connections {
val result = Connections(allMines, groups)
if (result.groups.isEmpty()) {
result.newGroupFrom(river)
}
val toMerge = result.groups.filter { it.fits(river) }
when {
toMerge.isEmpty() -> result.newGroupFrom(river)
toMerge.size == 1 -> toMerge.first().add(river)
else -> {
val base = toMerge.first()
toMerge.forEach {
if (it !== base)
base.merge(it)
}
base.add(river)
result.groups.removeAll(toMerge)
result.groups.add(base)
}
}
return result
}
private fun newGroupFrom(river: River) {
val ncg = ConnectionGroup()
ncg.add(river)
groups.add(ncg)
}
fun cost(metrics: DistanceMetrics): Int {
var result = 0
for (group in groups) {
result += group.mines.sumBy { metrics.costHavingSites(it, group.sites) }
}
return result
}
override fun toString(): String {
return groups.joinToString("\n") { "${it.mines} : ${it.sites}" } + "\n"
}
}<file_sep>/src/main/kotlin/com/dekinci/contest/Start.kt
package com.dekinci.contest
import com.dekinci.contest.bot.BotFactory
import com.dekinci.contest.bot.BotImpl
import com.dekinci.contest.bot.BotRunner
import com.dekinci.contest.bot.MathBot
import com.dekinci.contest.common.Log.info
import com.dekinci.contest.entities.BasicMap
import com.dekinci.contest.game.minimax.Stat
import org.kohsuke.args4j.CmdLineParser
import org.kohsuke.args4j.Option
import com.dekinci.contest.protocol.ServerConnection
object Arguments {
@Option(name = "-u", usage = "Specify server url")
var url: String = ""
@Option(name = "-p", usage = "Specify server port")
var port: Int = -1
fun use(args: Array<String>): Arguments =
CmdLineParser(this).parseArgument(*args).let { this }
}
fun main(args: Array<String>) {
Arguments.use(args)
info("Starting on ${Arguments.url} : ${Arguments.port}")
val connection = ServerConnection(Arguments.url, Arguments.port)
val br = BotRunner()
Runtime.getRuntime().addShutdownHook(Thread { info(Stat.toString()) })
br.runBot(connection, MatBoiFactory()).get()
br.shutdown()
}
class MinimaxFactory : BotFactory {
override fun getBotName() = "Test"
override fun makeBot(punter: Int, punters: Int, map: BasicMap) = BotImpl(getBotName(), punter, punters, map)
}
class MatBoiFactory : BotFactory {
override fun getBotName() = "Math boi"
override fun makeBot(punter: Int, punters: Int, map: BasicMap) = MathBot(getBotName(), punter, punters, map)
}<file_sep>/src/main/kotlin/com/dekinci/contest/game/map/metric/DistanceMetrics.kt
package com.dekinci.contest.game.map.metric
import com.dekinci.contest.common.Log.debug
import com.dekinci.contest.entities.River
import com.dekinci.contest.game.map.Cons
import com.dekinci.contest.game.map.graph.AdjacencyList
import com.dekinci.contest.game.map.graph.Dijkstra
import kotlinx.coroutines.async
import kotlinx.coroutines.runBlocking
import java.util.concurrent.ConcurrentHashMap
class DistanceMetrics(
private val sitesAmount: Int,
private val totalList: AdjacencyList,
private val mines: Set<Int>,
private val operation: (Int) -> Int
) {
private val weights = ConcurrentHashMap<Int, IntArray>(mines.size)
fun calculate() {
debug("metrics started")
val timestamp = System.currentTimeMillis()
runBlocking {
mines.map { async { calculateMineRelatedMetrics(it) } }
.forEach { it.await() }
}
debug("metrics created for: ${(System.currentTimeMillis() - timestamp).toDouble() / 1000}")
}
private fun calculateMineRelatedMetrics(mine: Int) {
weights[mine] = IntArray(sitesAmount) { -1 }
val dijkstra = Dijkstra(sitesAmount, totalList)
val metricsRelatedToMine = dijkstra.sparse(mine)
metricsRelatedToMine.forEachIndexed { site, weight ->
if (weight != -1)
weights[mine]!![site] = operation.invoke(weight)
}
}
fun mineCost(mine: Int) = weights[mine]!!.sumBy { if (it >= 0) it else 0 }
fun siteCost(site: Int) = mines.sumBy {
val weight = weights[it]!![site]
if (weight >= 0) weight else 0
}
fun minSiteCost(site: Int) = mines.minBy {
val weight = weights[it]!![site]
if (weight >= 0) weight else Int.MAX_VALUE
}
fun maxSiteCost(site: Int) = mines.maxBy {
val weight = weights[it]!![site]
if (weight >= 0) weight else Int.MIN_VALUE
}
fun getJointMines(site: Int): Set<Int> = mines.filter { weights[it]!![site] > -1 }.toHashSet()
fun costHavingMines(site: Int, mines: Collection<Int>): Int =
mines.filter { weights[it]!![site] > -1 }.sumBy { weights[it]!![site] }
fun costHavingSites(mine: Int, sites: Collection<Int>): Int =
sites.sumBy { if (weights[mine]!![it] > -1) weights[mine]!![it] else 0 }
fun costHaving(sites: Set<Int>): Int {
val havingMines = sites.intersect(mines)
return havingMines.sumBy { costHavingSites(it, sites) }
}
fun costHavingRivers(rivers: Set<River>): Int {
val ownedMines = HashSet<Int>()
rivers.forEach {
if (mines.contains(it.target))
ownedMines.add(it.target)
if (mines.contains(it.source))
ownedMines.add(it.source)
}
val cons = Cons(ownedMines, rivers)
var result = 0
runBlocking {
result = cons.getGroups().map { group ->
group.getMines().map {
async { costHavingSites(it, group.getSites()) }
}
}.flatten().map { it.await() }.sum()
}
return result
}
operator fun get(mine: Int, site: Int) = weights[mine]!![site]
}<file_sep>/src/main/kotlin/com/dekinci/contest/entities/River.kt
package com.dekinci.contest.entities
import com.fasterxml.jackson.annotation.JsonIgnoreProperties
import com.dekinci.contest.protocol.Claim
import java.lang.IllegalStateException
@JsonIgnoreProperties(ignoreUnknown = true)
open class River(val source: Int, val target: Int) {
constructor(claim: Claim) : this(claim.source, claim.target)
fun has(site: Int) = source == site || target == site
fun another(site: Int) = if (source == site) target else if (target == site) source else throw IllegalStateException("No $site")
override fun equals(other: Any?) = other is River &&
(source == other.source && target == other.target || source == other.target && target == other.source)
override fun hashCode() = source.hashCode() xor target.hashCode()
override fun toString(): String = "($source, $target)"
fun stated(state: Int) = StatedRiver(source, target, state)
}<file_sep>/src/main/kotlin/com/dekinci/contest/game/tactics/Tactics.kt
package com.dekinci.contest.game.tactics
import com.dekinci.contest.entities.StatedRiver
/**
* Tactics is a consequence of taking concrete points.
* In different position contest may need different tactics
* e.g. building mines net, spreading or aggression,
* so tactics mechanism implements a finite-state machine
* for choosing concrete behavior.
*/
interface Tactics : Iterator<StatedRiver?> {
/**
* Returns true if tactics finished (WAS NOT INTERRUPTED).
*/
fun isFinished(): Boolean
/**
* Returns true if tactics has a possibility to succeed.
*/
fun isSuccessful(): Boolean
/**
* Updates tactics.
* Returns next step of tactics.
* Usable as iterator.
*/
override fun next(): StatedRiver?
/**
* True if tactics has an idea to continue.
* Usable as iterator.
*/
override fun hasNext(): Boolean
}<file_sep>/src/main/kotlin/com/dekinci/contest/game/minimax/Turn.kt
package com.dekinci.contest.game.minimax
import com.dekinci.contest.entities.StatedRiver
import java.lang.ref.SoftReference
import java.lang.ref.WeakReference
class Turn private constructor(
val deltaRiver: StatedRiver?,
val score: Int,
val id: String,
parentInit: Turn? = null
) {
private val siblings = HashSet<Turn>()
private val longHash: Long
private val parent = WeakReference<Turn>(parentInit)
private var riverSet: SoftReference<Set<StatedRiver>>? = null
init {
var result = 0L
riverSet().forEach { result = result * 31 + it.hashCode() }
longHash = result
}
fun next(newRiver: StatedRiver, score: Int, id: String): Turn {
val next = Turn(newRiver, score, id, this)
siblings.add(next)
return next
}
fun replaceBy(turn: Turn) {
parent.get()?.siblings?.remove(this)
parent.get()?.siblings?.add(turn)
}
fun skeleton(newRiver: StatedRiver) = Turn(newRiver, 0, "", this)
fun siblings(): Set<Turn> = siblings
fun riverSet(): Set<StatedRiver> {
if (riverSet?.get() != null)
return riverSet!!.get()!!
Stat.start("river set calculation")
val set = HashSet<StatedRiver>()
deltaRiver?.let { set.add(it) }
var parentTurn = parent.get()
while (parentTurn != null) {
parentTurn.deltaRiver?.let { set.add(it) }
parentTurn = parentTurn.parent.get()
}
riverSet = SoftReference(set)
Stat.end("river set calculation")
return set
}
fun firstTurnFor(player: Int, root: Turn): Turn? {
var result : Turn? = null
var currentTurn: Turn? = this
while (currentTurn != null && currentTurn != root) {
if (currentTurn.deltaRiver?.state == player)
result = currentTurn
currentTurn = currentTurn.parent.get()
}
return result
}
fun prevTurnOf(player: Int): Turn {
var prevTurn: Turn = root()
var parentTurn: Turn? = this
while (parentTurn != null) {
if (parentTurn.deltaRiver?.state == player) {
prevTurn = parentTurn
break
}
else if (parentTurn.parent.get() == null) {
prevTurn = parentTurn
break
}
parentTurn = parentTurn.parent.get()
}
return prevTurn
}
override fun equals(other: Any?): Boolean {
if (other === this)
return true
return other is Turn && longHash == other.longHash && riverSet() == other.riverSet()
}
override fun hashCode(): Int {
return longHash.hashCode()
}
override fun toString(): String {
return "${parent.get()?.toString() ?: ""}; $deltaRiver"
}
companion object {
fun root() = Turn(null, 0, "0", null)
}
}<file_sep>/src/main/kotlin/com/dekinci/contest/game/map/graph/AdjacencyMatrix.kt
package com.dekinci.contest.game.map.graph
import com.dekinci.contest.common.Log
import com.dekinci.contest.entities.River
import com.dekinci.contest.entities.RiverStateID
import java.util.*
class AdjacencyMatrix (private val size: Int, rivers: Array<River>) {
private val matrix = Array(size) { IntArray(size) }
init {
for (river in rivers) {
val row = river.source
val cell = river.target
matrix[row][cell] = RiverStateID.NEUTRAL
matrix[cell][row] = RiverStateID.NEUTRAL
}
Log.debug("adj matrix created and filled with rivers...")
}
fun getConnections(site: Int): Collection<Int> {
val connections = HashSet<Int>()
for (i in 0 until matrix.size) {
if (matrix[site][i] != RiverStateID.DEFUNCT)
connections.add(i)
if (matrix[i][site] != RiverStateID.DEFUNCT)
connections.add(i)
}
return connections
}
fun hasFreeConnections(site: Int): Boolean {
for (i in 0 until size) {
if (matrix[site][i] == RiverStateID.NEUTRAL)
return true
if (matrix[i][site] == RiverStateID.NEUTRAL)
return true
}
return false
}
operator fun set(from: Int, to: Int, state: Int) {
matrix[from][to] = state
matrix[to][from] = state
}
operator fun get(from: Int, to: Int): Int = matrix[from][to]
}<file_sep>/src/main/kotlin/com/dekinci/contest/game/strategy/PatheticStrategy.kt
package com.dekinci.contest.game.strategy
class PatheticStrategy : Strategy {
override fun isFinished() = false
override fun isSuccessful() = false
override fun next(): Nothing? = null
override fun hasNext() = true
}<file_sep>/src/test/com/dekinci/contest/game/minimax/TurnTest.kt
package com.dekinci.contest.game.minimax
import com.dekinci.contest.entities.StatedRiver
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.Assertions.*
internal class TurnTest {
@Test
operator fun next() {
}
@Test
fun replaceBy() {
}
@Test
fun skeleton() {
}
@Test
fun siblings() {
}
@Test
fun riverSet() {
}
@Test
fun firstTurnFor() {
}
@Test
fun prevTurnOf() {
}
}<file_sep>/src/main/kotlin/com/dekinci/contest/game/strategy/Strategy.kt
package com.dekinci.contest.game.strategy
import com.dekinci.contest.entities.StatedRiver
/**
* Strategy is a decision-making mechanism of the contest.
* It has a possibility to invoke transition of the tactics machine.
*
* Strategy does not says, which rivers to take, but it defines the
* general behavior of the contest.
* It is a finite-state machine.
*/
interface Strategy : Iterator<StatedRiver?> {
fun isFinished(): Boolean
fun isSuccessful(): Boolean
override fun next(): StatedRiver?
override fun hasNext(): Boolean
}<file_sep>/src/test/com/dekinci/contest/game/map/ConsTest.kt
package com.dekinci.contest.game.map
import com.dekinci.contest.disconnectedMap
import com.dekinci.contest.entities.River
import com.dekinci.contest.nanoMap
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.Assertions.*
internal class ConsTest {
@Test
fun getGroupsNano() {
val gm = nanoMap()
val c = Cons(gm.basicMap.mines, gm.basicMap.rivers.asList())
assertEquals(1, c.getGroups().size)
assertEquals(1, c.getGroups().size)
assertNotNull(c.getGroups().find { it.getSites() == setOf(1, 0) })
}
@Test
fun getGroupsDisco() {
val c = Cons(hashSetOf(2, 3), setOf(
River(3, 6),
River(7, 6),
River(2, 1),
River(0, 1)
))
assertEquals(2, c.getGroups().size)
assertNotNull(c.getGroups().find { it.getSites() == setOf(3, 6, 7) })
assertNotNull(c.getGroups().find { it.getSites() == setOf(2, 1, 0) })
}
}<file_sep>/src/main/kotlin/com/dekinci/contest/bot/BotImpl.kt
package com.dekinci.contest.bot
import com.dekinci.contest.entities.BasicMap
import com.dekinci.contest.entities.StatedRiver
import com.dekinci.contest.game.GameState
import com.dekinci.contest.game.Intellect
class BotImpl(override val name: String, punter: Int, punters: Int, map: BasicMap) : Bot {
private val gameState = GameState(punter, punters, map)
private val intellect = Intellect(gameState)
override fun onUpdate(statedRiver: StatedRiver) {
gameState.update(statedRiver)
intellect.update(statedRiver)
}
override fun getMove(): StatedRiver? {
return intellect.getRiver()
}
override fun onFinish() {
intellect.finish()
}
}<file_sep>/src/test/com/dekinci/contest/entities/StatedRiverTest.kt
package com.dekinci.contest.entities
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertNotEquals
import org.junit.jupiter.api.Test
import java.lang.IllegalStateException
internal class StatedRiverTest {
@Test
fun has() {
val r = StatedRiver(5, 10)
Assertions.assertTrue(r.has(5))
Assertions.assertTrue(r.has(10))
Assertions.assertFalse(r.has(7))
}
@Test
fun another() {
val r = StatedRiver(5, 10)
assertEquals(10, r.another(5))
assertEquals(5, r.another(10))
Assertions.assertThrows(IllegalStateException::class.java) { r.another(7) }
}
@Test
fun equalsTest() {
val r1 = StatedRiver(5, 10)
val r2 = StatedRiver(10, 5)
val r3 = StatedRiver(10, 5, 1)
assertEquals(r1, r2)
assertEquals(r2, r1)
assertNotEquals(r1, r3)
assertNotEquals(r2, r3)
}
@Test
fun hashCodeTest() {
val r1 = StatedRiver(5, 10)
val r2 = StatedRiver(10, 5)
val r3 = StatedRiver(10, 5, 1)
assertEquals(r1.hashCode(), r2.hashCode())
assertNotEquals(r1.hashCode(), r3.hashCode())
assertNotEquals(r2.hashCode(), r3.hashCode())
}
}<file_sep>/src/test/com/dekinci/contest/Maps.kt
package com.dekinci.contest
import com.dekinci.contest.entities.BasicMap
import com.dekinci.contest.entities.Rectifier
import com.dekinci.contest.entities.River
import com.dekinci.contest.game.map.GameMap
/**
* 0---1---2!
* | \ | / |
* !3 4 5
* | / | \ |
* 6---7---8
*/
fun connectedMap(): GameMap {
val size = 9
val mines = setOf(3, 2)
val rivers = riversFromString("0,1 1,2 0,3 0,4 1,4 4,2 2,5 3,6 6,4 7,4 4,8 8,5 6,7 7,8")
return gameMapFrom(rivers, mines, size)
}
/**
* 0---1---2!
* | \ | /
* !3 4 5!
* | / | |
* 6---7 8
*/
fun disconnectedMap(): GameMap {
val size = 9
val mines = setOf(3, 2, 5)
val rivers = riversFromString("0,1 1,2 0,3 0,4 1,4 2,4 3,6 4,7 4,6 5,8 6,7")
return gameMapFrom(rivers, mines, size)
}
/**
* !0---1---2!
* |
* 3
*/
fun microMap(): GameMap {
val size = 4
val mines = setOf(0, 2)
val rivers = riversFromString("0,1 1,2 1,3")
return gameMapFrom(rivers, mines, size)
}
/**
* !0---1
*/
fun nanoMap() = GameMap(BasicMap(arrayOf(River(0, 1)), setOf(0), 2))
fun fromDirtyMap(rivers: Iterable<River>, mines: Iterable<Int>): GameMap {
val rectifier = Rectifier(rivers, mines)
return GameMap(rectifier.asMap())
}
fun gameMapFrom(rivers: Iterable<River>, mines: Iterable<Int>, size: Int) =
GameMap(BasicMap(rivers.toList().toTypedArray(), mines.toHashSet(), size))
private fun riversFromString(s: String) = s.split(" ")
.map { River(it.split(",")[0].toInt(), it.split(",")[1].toInt()) }<file_sep>/src/main/kotlin/com/dekinci/contest/game/tactics/ConnectMinesTactics.kt
package com.dekinci.contest.game.tactics
import com.dekinci.contest.common.Log.trace
import com.dekinci.contest.entities.StatedRiver
import com.dekinci.contest.game.map.GameMap
class ConnectMinesTactics(
private val punter: Int,
gameMap: GameMap,
private val from: Int,
private val to: Int
) : Tactics {
private val aStar = PathFinder(gameMap)
private var sites = aStar.findPath(from, to, punter)
private var prevStep = 0
private var currentSite = from
override fun isFinished(): Boolean = prevStep == sites.size
override fun isSuccessful(): Boolean = !sites.isEmpty()
override fun hasNext() = prevStep < (sites.size)
override fun next(): StatedRiver? {
val newSites = aStar.findPath(from, to, punter)
if (sites != newSites) {
trace("path changed from $sites")
trace("path changed to $newSites")
trace("prevstep changed from $prevStep")
prevStep = sites.commonUntil(newSites)
trace("prevstep changed to $prevStep")
sites = newSites
}
if (!hasNext())
return null
val nextSite = sites[prevStep++]
val river = StatedRiver(currentSite, nextSite, punter)
currentSite = nextSite
return river
}
private fun <E> List<E>.commonUntil(other: List<E>): Int {
val limit = if (size > other.size) other.size else size
return (0 until limit).firstOrNull { this[it] != other[it] } ?: limit
}
}
<file_sep>/src/main/kotlin/com/dekinci/contest/common/HashCachingHashSet.kt
package com.dekinci.contest.common
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.atomic.AtomicInteger
class HashCachingHashSet<T> : HashSet<T> {
constructor() : super()
constructor(c: Collection<T>) : super() {
addAll(c)
}
constructor(initialCapacity: Int, loadFactor: Float) : super(initialCapacity, loadFactor)
constructor(initialCapacity: Int) : super(initialCapacity)
private val hash = AtomicInteger(0)
private val isValid = AtomicBoolean(false)
override fun hashCode(): Int {
if (!isValid.get()) {
hash.set(super.hashCode())
isValid.set(true)
}
return hash.get()
}
override fun equals(other: Any?): Boolean {
return super.equals(other)
}
override fun clear() {
isValid.set(false)
super.clear()
}
override fun remove(element: T): Boolean {
isValid.set(false)
return super.remove(element)
}
override fun add(element: T): Boolean {
isValid.set(false)
return super.add(element)
}
}<file_sep>/src/test/com/dekinci/contest/game/minimax/MinimaxTest.kt
package com.dekinci.contest.game.minimax
import com.dekinci.contest.disconnectedMap
import com.dekinci.contest.entities.River
import com.dekinci.contest.entities.StatedRiver
import com.dekinci.contest.nanoMap
import org.junit.jupiter.api.Test
internal class MinimaxTest {
@Test
fun test() {
val map = disconnectedMap()
val pa = 2
val depth = 15
val mms = Array(pa) { Minimax(pa, map, it, depth) }
var i = 0
mms[i].mineSolution()
var next = mms[i].getBest(i)
var counter = 0
while (next != null) {
println("$i: Taking ${next.source} ${next.target}")
counter++
map.update(StatedRiver(next.source, next.target, next.state))
mms.forEach { it.update(next!!.stated(i)) }
i++
i %= pa
mms[i].mineSolution()
next = mms[i].getBest(i)
}
println(Stat)
println(counter)
}
@Test
fun testSmall() {
val map = nanoMap()
val pa = 2
val depth = 40
val mms = Array(pa) { Minimax(pa, map, it, depth) }
var i = 0
mms[i].mineSolution()
var next = mms[i].getBest(i)
while (next != null) {
println("$i: Taking ${next.source} ${next.target}")
map.update(StatedRiver(next.source, next.target, next.state))
mms.forEach { it.update(next!!.stated(i)) }
i++
i %= pa
mms[i].mineSolution()
next = mms[i].getBest(i)
}
println(Stat)
}
@Test
fun siteChange() {
// val map = disconnectedMap()
// val mm = Minimax(1, map, 1, 0)
val rivers = hashSetOf<River>()
// map.basicMap.mines.forEach{ mm.siteChange(rivers, it) }
// println(rivers)
// map.update(StatedRiver(0, 3, 1000))
// mm.riverChange(rivers, River(0, 3))
// println(rivers)
// map.update(StatedRiver(0, 4, 1000))
// mm.riverChange(rivers, River(0, 4))
println(rivers)
}
@Test
fun getFancyRivers() {
val map = disconnectedMap()
val mm = Minimax(1, map, 0, 0)
println(mm.getFancyRivers(setOf(StatedRiver(3, 0, 0)), 0))
}
}<file_sep>/src/test/com/dekinci/contest/bot/MathBotTest.kt
package com.dekinci.contest.bot
import com.dekinci.contest.disconnectedMap
import com.dekinci.contest.entities.StatedRiver
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.Assertions.*
internal class MathBotTest {
@Test
fun test() {
val map = disconnectedMap()
val bot = MathBot("", 0, 1, map.basicMap)
var next: StatedRiver? = bot.getMove()
while (next != null) {
bot.onUpdate(next)
println(next)
next = bot.getMove()
}
}
@Test
fun testCo() {
val p = 4
val map = disconnectedMap()
val bots = Array<Bot>(p) { MathBot("", it, p, map.basicMap) }
var i = 0
var next: StatedRiver? = bots[i].getMove()
while (next != null) {
println(next)
bots.forEachIndexed { ind, b -> if (ind != i) b.onUpdate(next!!) }
i = ++i % p
next = bots[i].getMove()
}
}
}<file_sep>/src/main/kotlin/com/dekinci/contest/game/minimax/Minimax.kt
package com.dekinci.contest.game.minimax
import com.dekinci.contest.common.Log.debug
import com.dekinci.contest.common.Log.trace
import com.dekinci.contest.common.newWeakHashSet
import com.dekinci.contest.entities.River
import com.dekinci.contest.entities.StatedRiver
import com.dekinci.contest.game.map.GameMap
import java.util.*
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.atomic.AtomicInteger
import java.util.concurrent.atomic.AtomicReference
import kotlin.collections.HashSet
class Minimax(
private val playersAmount: Int,
private val gameMap: GameMap,
private val targetPlayer: Int,
private val depth: Int
) {
private val adultTurns = newWeakHashSet<Turn>()
private val matchedTurns = HashMap<Int, MutableSet<Turn>>()
private var rootTurn = AtomicReference<Turn>(Turn.root())
private val ancientRiverSet = HashSet<StatedRiver>()
private var bestNextTurn: AtomicReference<Turn> = AtomicReference(rootTurn.get())
private var idCounter = AtomicInteger()
private val interrupted = AtomicBoolean(false)
fun getBest(targetPlayer: Int): StatedRiver? {
return bestNextTurn.get().firstTurnFor(targetPlayer, rootTurn.get())?.deltaRiver
}
fun interrupt() {
interrupted.set(true)
}
fun update(river: StatedRiver) {
Stat.start("update")
interrupted.set(false)
val skeleton = rootTurn.get().skeleton(river)
val found = findBySkeleton(skeleton)
rootTurn.get().deltaRiver?.let { ancientRiverSet.add(it) }
if (found != null)
rootTurn.set(found)
else {
trace("no turn")
val rt = rootTurn.get()
rootTurn.set (nextTurn(rt, river.stateless(), river.state))
}
bestNextTurn.set(Turn.root())
System.gc()
Stat.end("update")
}
private fun findBySkeleton(skeleton: Turn): Turn? = if (adultTurns.contains(skeleton))
matchedTurns[skeleton.hashCode()]!!.find { it == skeleton }!!
else null
fun mineSolution() {
Stat.start("cycle")
var depthCounter = 0
var nextTurns = setOf(rootTurn.get())
for (i in 0 .. depth) {
if (interrupted.get())
break
nextTurns = nextRound(nextTurns)
depthCounter++
if (nextTurns.isEmpty())
break
}
debug("Depth: $depthCounter")
Stat.end("cycle")
}
private fun nextRound(turnSet: Set<Turn>): Set<Turn> {
var turns = turnSet
for (i in 0 until playersAmount) {
if (interrupted.get())
break
turns = turn(turns)
turns = reduce(turns)
val roundBest = turns.filter { it.deltaRiver?.state == targetPlayer }.maxBy { it.score } ?: Turn.root()
if (roundBest.score > bestNextTurn.get().score)
bestNextTurn.set(roundBest)
}
return turns
}
private fun turn(turnSet: Set<Turn>): Set<Turn> {
val children = HashSet<Turn>()
Stat.start("turn")
for (turn in turnSet) {
if (interrupted.get())
break
val playerN = (turn.deltaRiver?.state ?: targetPlayer) + 1
val siblings = findSiblings(turn, playerN % playersAmount)
children.addAll(siblings)
}
Stat.end("turn")
return children
}
private fun findSiblings(turn: Turn, playerN: Int): Set<Turn> {
return if (turn !in adultTurns) {
if (doSiblingsAndFindBest(turn, playerN))
makeAdult(turn)
turn.siblings()
} else {
val matched = findBySkeleton(turn)!!
turn.replaceBy(matched)
matched.siblings()
}
}
private fun makeAdult(turn: Turn) {
adultTurns.add(turn)
matchedTurns.getOrPut(turn.hashCode()) { newWeakHashSet() }.add(turn)
}
private fun doSiblingsAndFindBest(parent: Turn, playerN: Int): Boolean {
val fr = getFancyRivers(parent.riverSet() + ancientRiverSet, playerN)
for (river in fr) {
if (interrupted.get())
return false
nextTurn(parent, river, playerN)
}
return true
}
internal fun getFancyRivers(allRivers: Set<StatedRiver>, playerN: Int): Set<River> {
val result = HashSet<River>()
gameMap.basicMap.mines.forEach { mine ->
gameMap.getFreeConnections(mine).forEach {
result.add(River(mine, it))
}
}
val rivers = allRivers.filter { it.state == playerN }
rivers.forEach { river ->
gameMap.getFreeConnections(river.source).forEach {
result.add(River(it, river.source))
}
gameMap.getFreeConnections(river.target).forEach {
result.add(River(it, river.target))
}
}
return result.minus(allRivers.map { it.stateless() })
}
private fun reduce(turns: Set<Turn>): Set<Turn> {
val best = turns.maxBy { it.score }
return best?.let { _ -> turns.filter { best.score == it.score }.toHashSet() } ?: emptySet()
}
private fun nextTurn(parent: Turn, river: River, playerN: Int): Turn {
val skeleton = parent.skeleton(river.stated(playerN))
if (parent.siblings().contains(skeleton))
return parent.siblings().find { it == skeleton }!!
Stat.start("nextTurn")
val nextId = idCounter.incrementAndGet().toString()
val allRivers = (parent.riverSet() + ancientRiverSet).filter { it.state == playerN }.map { it.stateless() }.toHashSet()
allRivers.add(river)
val next = parent.next(river.stated(playerN), gameMap.squareMetrics.costHavingRivers(allRivers), nextId)
Stat.end("nextTurn")
return next
}
}<file_sep>/src/main/kotlin/com/dekinci/contest/bot/Bot.kt
package com.dekinci.contest.bot
import com.dekinci.contest.common.Log.warn
import com.dekinci.contest.entities.StatedRiver
interface Bot {
val name: String
fun onTimeout() {}
fun onUpdate(statedRiver: StatedRiver)
fun getMove(): StatedRiver?
fun onFinish() {}
}<file_sep>/src/main/kotlin/com/dekinci/contest/bot/BotMaster.kt
package com.dekinci.contest.bot
import com.dekinci.contest.common.Log.debug
import com.dekinci.contest.common.Log.err
import com.dekinci.contest.common.Log.info
import com.dekinci.contest.common.Log.trace
import com.dekinci.contest.common.Log.warn
import com.dekinci.contest.entities.Rectifier
import com.dekinci.contest.entities.StatedRiver
import com.dekinci.contest.protocol.*
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.atomic.AtomicInteger
class BotMaster(connection: ServerConnection, botFactory: BotFactory) {
private val protocol = Protocol(connection)
private val rectifier: Rectifier
private val playingFlag = AtomicBoolean()
private val passStreak = AtomicInteger()
private val bot: Bot
init {
info("Hi, I am ${botFactory.getBotName()}, the ultimate punter!")
protocol.handShake(botFactory.getBotName())
val setupData = protocol.setup()
info(("setup passed with " +
"${setupData.map.sites.size} nodes, " +
"${setupData.map.rivers.size} rivers and " +
"${setupData.map.mines.size} mines").trimMargin())
rectifier = Rectifier(setupData.map.rivers, setupData.map.mines)
bot = botFactory.makeBot(setupData.punter, setupData.punters, rectifier.asMap())
protocol.ready()
playingFlag.set(true)
info("Received id = ${setupData.punter}")
}
fun play() {
debug("${bot.name} started")
gameCycle@ while (playingFlag.get()) {
trace("Game iteration")
val message = protocol.serverMessage()
handleMessage(message)
if (!playingFlag.get())
break@gameCycle
makeAMove()
}
bot.onFinish()
debug("${bot.name} finished")
}
private fun makeAMove() {
val move = bot.getMove()
debug("Move: $move")
if (move == null)
handlePass()
else {
val polMove = rectifier.pollute(move)
protocol.claimMove(polMove.target, polMove.source)
}
}
private fun handleMessage(message: ServerMessage) {
when (message) {
is GameTurnMessage -> handleTurn(message)
is Timeout -> handleTimeout()
is GameResult -> handleResult(message)
else -> warn("Strange message: $message")
}
}
private fun handleTurn(move: GameTurnMessage) {
trace("Turn: ${move.move}")
passStreak.set(0)
move.move.moves
.filterIsInstance<ClaimMove>()
.map { rectifier.purify(StatedRiver(it.claim)) }
.forEach { bot.onUpdate(it) }
}
private fun handleTimeout() {
err("Timeout")
handlePass()
bot.onTimeout()
}
private fun handlePass() {
warn("Pass move")
if (passStreak.incrementAndGet() > 11)
playingFlag.set(false)
}
private fun handleResult(result: GameResult) {
val myScore = result.stop.scores[protocol.myId]
info("The game is over!")
info("${bot.name} scored ${myScore.score} points!")
playingFlag.set(false)
}
}<file_sep>/src/main/kotlin/com/dekinci/contest/common/WeakLayeredHashSet.kt
package com.dekinci.contest.common
import java.util.*
class WeakLayeredHashSet<T, K>(initial: Set<T> = emptySet()) : AbstractMutableSet<T>() {
private data class ImmaterialKeyToPair<T, K>(val key: K, val pair: Pair<HashSet<T>, HashSet<T>>) {
override fun equals(other: Any?): Boolean {
return other is ImmaterialKeyToPair<*, *> && other.pair == pair
}
override fun hashCode(): Int {
return pair.hashCode()
}
}
private val base = HashSet(initial)
private val positiveLayers = WeakHashMap<K?, HashSet<T>>()
private val negativeLayers = WeakHashMap<K?, HashSet<T>>()
private var defaultKey: K? = null
init {
positiveLayers[null] = HashCachingHashSet()
negativeLayers[null] = HashCachingHashSet()
}
fun clearLayers() {
positiveLayers.clear()
negativeLayers.clear()
positiveLayers[null] = HashCachingHashSet()
negativeLayers[null] = HashCachingHashSet()
}
fun setDefault(key: K? = null) {
defaultKey = key
}
fun addLayer(key: K, additions: Set<T> = emptySet(), deletions: Set<T> = emptySet()): MutableSet<T> {
positiveLayers[key] = HashCachingHashSet(additions)
negativeLayers[key] = HashCachingHashSet(deletions)
return PartialSet(key)
}
fun get(key: K?): MutableSet<T> = PartialSet(key)
fun removeLayer(key: K) {
positiveLayers.remove(key)
negativeLayers.remove(key)
}
fun mergeLayer(key: K?) {
base.removeAll(negativeLayers[key]!!)
base.addAll(positiveLayers[key]!!)
positiveLayers[key]!!.clear()
negativeLayers[key]!!.clear()
}
fun mergeRemoveLayer(key: K) {
base.addAll(positiveLayers[key]!!)
base.removeAll(negativeLayers[key]!!)
positiveLayers.remove(key)
negativeLayers.remove(key)
}
fun extendLayer(parent: K?, key: K): MutableSet<T> {
addLayer(key, positiveLayers[parent]!!, negativeLayers[parent]!!)
return PartialSet(key)
}
fun rotateToLayer(key: K?) {
val positives = positiveLayers[key]!!
val negatives = negativeLayers[key]!!
negativeLayers.forEach { it.value.addAll(positives.subtract(positiveLayers[it.key]!!)) }
positiveLayers.forEach { it.value.addAll(negatives.subtract(negativeLayers[it.key]!!)) }
mergeLayer(key)
}
fun layersEqual(first: K, second: K) = positiveLayers[first] == positiveLayers[second] &&
negativeLayers[first] == negativeLayers[second]
fun distinct(): Set<K> {
val set = HashSet<ImmaterialKeyToPair<T, K?>>()
for (key in positiveLayers.keys)
set.add(ImmaterialKeyToPair(key, positiveLayers[key]!! to negativeLayers[key]!!))
set.add(ImmaterialKeyToPair(null, positiveLayers[null]!! to negativeLayers[null]!!))
positiveLayers.clear()
negativeLayers.clear()
val keys = HashSet<K>()
for (ktp in set) {
ktp.key?.let { keys.add(it) }
positiveLayers[ktp.key] = ktp.pair.first
negativeLayers[ktp.key] = ktp.pair.second
}
return keys
}
override val size: Int
get() = size(defaultKey)
fun size(key: K?) = base.union(positiveLayers[key]!!).subtract(negativeLayers[key]!!).size
val baseSize: Int
get() = base.size
override fun add(element: T) = add(element, defaultKey)
fun add(element: T, key: K?): Boolean {
if (!negativeLayers[key]!!.remove(element))
return if (!base.contains(element)) positiveLayers[key]!!.add(element) else false
return true
}
fun baseAdd(element: T): Boolean {
positiveLayers.values.forEach { it.remove(element) }
return base.add(element)
}
fun baseGet(): MutableSet<T> = base
override fun remove(element: T) = remove(element, defaultKey)
fun remove(element: T, key: K?): Boolean {
if (!positiveLayers[key]!!.remove(element))
return if (base.contains(element))
negativeLayers[key]!!.add(element)
else false
return true
}
fun baseRemove(element: T): Boolean {
negativeLayers.values.forEach { it.remove(element) }
return base.remove(element)
}
override fun contains(element: T) = contains(element, defaultKey)
fun contains(element: T, key: K?): Boolean {
return element in positiveLayers[key]!! || (element !in negativeLayers[key]!! && element in base)
}
fun baseContains(element: T) = base.contains(element)
override fun clear() {
clearLayer(defaultKey)
}
fun clearLayer(key: K?) {
positiveLayers[key]!!.clear()
negativeLayers[key]!!.clear()
negativeLayers[key]!!.addAll(base)
}
fun clearBase() {
base.clear()
}
override fun isEmpty() = size == 0
fun isEmpty(key: K?) = size(key) == 0
fun baseIsEmpty() = base.isEmpty()
override fun iterator(): MutableIterator<T> = iterator(defaultKey)
fun iterator(key: K?): MutableIterator<T> =
base.union(positiveLayers[key]!!).subtract(negativeLayers[key]!!).toMutableSet().iterator()
fun baseIterator() = base.toSet().iterator()
fun keysIterator() = positiveLayers.keys.filter { it != null }.iterator()
private inner class PartialSet(private val key: K?) : AbstractMutableSet<T>() {
override val size: Int
get() = size(key)
override fun add(element: T) = add(element, key)
override fun iterator() = iterator(key)
override fun clear() {
clearLayer(key)
}
override fun contains(element: T) = contains(element, key)
override fun remove(element: T) = remove(element, key)
}
}<file_sep>/src/main/kotlin/com/dekinci/contest/game/map/graph/AdjacencyList.kt
package com.dekinci.contest.game.map.graph
import com.dekinci.contest.entities.River
class AdjacencyList(vertexAmount: Int, rivers: Array<River>) {
val list: Array<HashSet<Int>> = Array(vertexAmount) { HashSet<Int>() }
init {
rivers.forEach { river ->
addEdge(river.source, river.target)
}
}
fun addEdge(from: Int, to: Int) {
list[from].add(to)
list[to].add(from)
}
fun removeEdge(from: Int, to: Int) {
list[from].remove(to)
list[to].remove(from)
}
fun countConnections(site: Int) = list[site].size
operator fun get(from: Int): Collection<Int> = list[from]
}<file_sep>/src/main/kotlin/com/dekinci/contest/bot/MathBot.kt
package com.dekinci.contest.bot
import com.dekinci.contest.entities.BasicMap
import com.dekinci.contest.entities.River
import com.dekinci.contest.entities.StatedRiver
import com.dekinci.contest.game.GameState
import com.dekinci.contest.game.map.Cons
import com.dekinci.contest.game.map.FancyRivers
import kotlin.math.roundToInt
class MathBot(override val name: String, punter: Int, punters: Int, map: BasicMap) : Bot {
private enum class Time {
GATHER,
SCATTER
}
private val gameState = GameState(punter, punters, map)
private val gm = gameState.gameMap
private val fr = FancyRivers(gm)
private val cons = Cons(gm.basicMap.mines)
private var time = Time.GATHER
override fun onUpdate(statedRiver: StatedRiver) {
if (statedRiver.state != gameState.punter) {
gameState.update(statedRiver)
fr.remove(statedRiver.stateless())
}
}
override fun getMove(): StatedRiver? {
val c = getComp()
val max = fr.getRivers().maxWith(c)
if (max != null) {
val maxes = fr.getRivers().filter { c.compare(it, max) == 0 }
val move = maxes.random().stated(gameState.punter)
niceMove(move)
return move
}
return null
}
private fun getComp(): Comparator<River> {
return if (time == Time.GATHER && cons.getGroups().size > gm.islands.size) {
time = Time.SCATTER
ScatterComparator()
} else
GatherComparator()
}
private fun niceMove(statedRiver: StatedRiver) {
gameState.update(statedRiver)
fr.update(statedRiver.stateless())
cons.addRiver(statedRiver.stateless())
}
private inner class GatherComparator : Comparator<River> {
private val comps = listOf(
Comparator.comparing<River, Int> {
val delta = Math.abs(gm.squareMetrics.siteCost(it.source) - gm.squareMetrics.siteCost(it.target))
if (delta == 0)
Int.MAX_VALUE
else
delta
}.reversed(),
Comparator.comparing<River, Int> {
Math.min(gm.connectionsMetrics[it.source], gm.connectionsMetrics[it.target])
}.reversed()
)
override fun compare(o1: River, o2: River): Int {
for (comp in comps) {
val result = comp.compare(o1, o2)
if (result != 0)
return result
}
return 0
}
}
private inner class ScatterComparator : Comparator<River> {
private val comps = listOf(
Comparator.comparing<River, Int> {
Math.abs(gm.squareMetrics.siteCost(it.source) - gm.squareMetrics.siteCost(it.target))
},
Comparator.comparing<River, Int> {
Math.min(gm.connectionsMetrics[it.source], gm.connectionsMetrics[it.target])
}.reversed()
)
override fun compare(o1: River, o2: River): Int {
for (comp in comps) {
val result = comp.compare(o1, o2)
if (result != 0)
return result
}
return 0
}
}
}<file_sep>/src/main/kotlin/com/dekinci/contest/entities/RiverStateID.kt
package com.dekinci.contest.entities
object RiverStateID {
/**
* -2 - DEFUNCT - if there is no river
* -1 - NEUTRAL - if this river is not claimed yet
* other - ID of the player, who claimed the river
*/
const val DEFUNCT = -2
const val NEUTRAL = -1
}<file_sep>/src/main/kotlin/com/dekinci/contest/game/map/metric/ConnectionsMetrics.kt
package com.dekinci.contest.game.map.metric
import com.dekinci.contest.game.map.graph.AdjacencyList
class ConnectionsMetrics(
sitesAmount: Int,
private val freeAdjList: AdjacencyList
) {
private val connections = IntArray(sitesAmount) { freeAdjList.countConnections(it) }
fun update(site: Int) {
connections[site] = freeAdjList.countConnections(site)
}
operator fun get(site: Int) = connections[site]
}<file_sep>/src/main/kotlin/com/dekinci/contest/game/player/Player.kt
package com.dekinci.contest.game.player
import com.dekinci.contest.game.map.GameMap
class Player(
private val map: GameMap,
val sites: MutableSet<Int> = HashSet(),
val mines: MutableSet<Int> = HashSet()) {
var score = 0
private fun claim(site: Int): Int {
if (site in map.basicMap.mines)
mines.add(site)
if (sites.add(site))
return recount()
return 0
}
private fun recount(): Int {
val oldScore = score
score = map.squareMetrics.costHaving(sites.union(mines))
return score - oldScore
}
}<file_sep>/src/main/kotlin/com/dekinci/contest/game/map/metric/PotentialMetrics.kt
package com.dekinci.contest.game.map.metric
class PotentialMetrics(
sitesAmount: Int,
private val distanceMetrics: DistanceMetrics
) {
private val weights = IntArray(sitesAmount) { distanceMetrics.siteCost(it) }
fun update(site: Int) {
weights[site] = distanceMetrics.siteCost(site)
}
operator fun get(site: Int) = weights[site]
}<file_sep>/src/main/kotlin/com/dekinci/contest/game/GameState.kt
package com.dekinci.contest.game
import com.dekinci.contest.entities.BasicMap
import com.dekinci.contest.entities.StatedRiver
import com.dekinci.contest.game.map.GameMap
class GameState(val punter: Int, val playersAmount: Int, basicMap: BasicMap) {
val gameMap = GameMap(basicMap)
fun update(statedRiver: StatedRiver) {
gameMap.update(statedRiver)
}
}<file_sep>/src/main/kotlin/com/dekinci/contest/game/map/metric/SquareMetric.kt
package com.dekinci.contest.game.map.metric
class SquareMetric(private val lm: DistanceMetrics) {
}<file_sep>/src/main/kotlin/com/dekinci/contest/common/Colls.kt
package com.dekinci.contest.common
import java.util.*
fun <T> newWeakHashSet(): MutableSet<T> = Collections.newSetFromMap(WeakHashMap<T, Boolean>())
fun <T> newWeakHashSet(element: T): MutableSet<T> = Collections.newSetFromMap(WeakHashMap<T, Boolean>()).also { it.add(element) }
fun <T> newWeakHashSet(iterable: Iterable<T>): MutableSet<T> = Collections.newSetFromMap(WeakHashMap<T, Boolean>()).also { it.addAll(iterable) }<file_sep>/src/main/kotlin/com/dekinci/contest/game/tactics/PathFinder.kt
package com.dekinci.contest.game.tactics
import com.dekinci.contest.common.Log.trace
import com.dekinci.contest.game.map.GameMap
import java.util.*
import kotlin.collections.HashSet
class PathFinder(private val map: GameMap) {
private data class TwoWayPath(val a: Int, val b: Int) {
override fun equals(other: Any?): Boolean {
if (this === other)
return true
if (other !is TwoWayPath)
return false
return other.a == b && other.b == a || other.a == a && other.b == b
}
override fun hashCode() = a.hashCode() xor b.hashCode()
}
private val parentMap = HashMap<Int, Int>()
fun findPath(start: Int, finish: Int, punter: Int, excludePaths: List<List<Int>> = emptyList()): List<Int> {
trace("Finding path from $start to $finish")
val openList = PriorityQueue<Int>()
val closedList = LinkedList<Int>()
val excludedTwoWayPaths = HashSet<TwoWayPath>()
for (path in excludePaths) {
if (path.isNotEmpty())
for (i in 1 until path.size)
excludedTwoWayPaths.add(TwoWayPath(path[i - 1], path[i]))
}
parentMap[start] = -1
openList.add(start)
while (!openList.isEmpty()) {
val node = openList.remove()
if (node == finish)
return constructPath(finish)
val neighbors = map.getAvailableConnections(node, punter)
for (neighbor in neighbors) {
val isOpen = openList.contains(neighbor)
val isClosed = closedList.contains(neighbor)
if (!isOpen && !isClosed &&
map.squareMetrics[start, node] < map.squareMetrics[start, neighbor] &&
!excludedTwoWayPaths.contains(TwoWayPath(node, neighbor))) {
parentMap[neighbor] = node
if (isClosed)
closedList.remove(neighbor)
if (!isOpen)
openList.add(neighbor)
}
}
closedList.add(node)
}
return emptyList()
}
private fun constructPath(node: Int): List<Int> {
var varNode = node
val path = LinkedList<Int>()
while (parentMap[varNode] != -1) {
path.addFirst(varNode)
varNode = parentMap[varNode]!!
}
trace("Path found: $path")
return path
}
}<file_sep>/src/main/kotlin/com/dekinci/contest/game/minimax/Stat.kt
package com.dekinci.contest.game.minimax
import java.util.concurrent.ConcurrentHashMap
object Stat {
private val timeMap = ConcurrentHashMap<String, Long>()
fun start(tag: String) {
timeMap.compute(tag) { _, v -> (v ?: 0) - System.currentTimeMillis() }
}
fun end(tag: String) {
timeMap.computeIfPresent(tag) { _, v -> v + System.currentTimeMillis() }
}
override fun toString(): String {
return timeMap.entries.joinToString("\n") { "${it.key}: ${it.value}" }
}
}<file_sep>/README.md
# <NAME> (aka budding jack)
A mighty punter
Likes a lot of POWEEEERRRR!!!! (Eats everything what you have, asks for more and when you don't give it to him dies from starvation (on big maps))
A bot for icfp-2017 challenge
<file_sep>/src/main/kotlin/com/dekinci/contest/bot/BotRunner.kt
package com.dekinci.contest.bot
import com.dekinci.contest.common.Log.debug
import com.dekinci.contest.protocol.ServerConnection
import java.util.concurrent.Executors
import java.util.concurrent.Future
class BotRunner {
private val executor = Executors.newSingleThreadExecutor()
fun runBot(connection: ServerConnection, botFactory: BotFactory): Future<*> {
debug("Starting executor")
return executor.submit { BotMaster(connection, botFactory).play() }
}
fun shutdown() {
debug("Shutting down")
executor.shutdown()
}
}<file_sep>/src/main/kotlin/com/dekinci/contest/game/map/Cons.kt
package com.dekinci.contest.game.map
import com.dekinci.contest.entities.River
import java.util.*
class Cons(private val allMines: Set<Int>, rivers: Iterable<River> = emptySet()) {
inner class Group {
private val mines = HashSet<Int>()
private val sites = HashSet<Int>()
internal fun merge(other: Group) {
mines.addAll(other.mines)
sites.addAll(other.sites)
}
fun getMines(): Set<Int> = mines
fun getSites(): Set<Int> = sites
internal fun fits(river: River) = sites.contains(river.source) || sites.contains(river.target)
internal fun add(river: River) {
val source = river.source
val target = river.target
if (allMines.contains(source))
mines.add(source)
if (allMines.contains(target))
mines.add(target)
sites.add(river.target)
sites.add(river.source)
}
}
private val groups = Collections.newSetFromMap(HashMap<Group, Boolean>())
init {
rivers.forEach {
addRiver(it)
}
}
fun addRiver(river: River) {
val toMerge = groups.filter { it.fits(river) }
when {
toMerge.isEmpty() -> newGroupFrom(river)
toMerge.size == 1 -> toMerge.first().add(river)
else -> mergeOn(river, toMerge)
}
}
fun getGroups(): Set<Group> = groups
private fun mergeOn(river: River, toMerge: List<Group>) {
val base = toMerge.first()
toMerge.forEach {
if (it !== base)
base.merge(it)
}
base.add(river)
groups.removeAll(toMerge)
groups.add(base)
}
private fun newGroupFrom(river: River) {
val con = Group()
con.add(river)
groups.add(con)
}
}<file_sep>/src/test/com/dekinci/contest/game/tactics/PathFinderTest.kt
import com.dekinci.contest.connectedMap
import com.dekinci.contest.disconnectedMap
import com.dekinci.contest.entities.River
import com.dekinci.contest.fromDirtyMap
import com.dekinci.contest.game.tactics.PathFinder
import org.junit.jupiter.api.Test
import java.util.*
import kotlin.collections.ArrayList
class PathFinderTest {
@Test
fun test() {
val map = connectedMap()
val start = 3
val path = listOf(start) + PathFinder(map).findPath(start, 2, 0, listOf(listOf(3, 0, 1, 2), listOf(7, 8), listOf(2, 5)))
println(path)
}
@Test
fun test3() {
val map = disconnectedMap()
val start = 3
val path = PathFinder(map).findPath(start, 2, 0, listOf(listOf(3, 0, 1, 2)))
println(path)
val listPaths = ArrayList<List<Int>>()
while (true) {
val possiblePath = PathFinder(map).findPath(start, 2, 0, listPaths)
if (!possiblePath.isEmpty())
listPaths.add(listOf(start) + possiblePath)
else
break
}
println("k is " + listPaths.size)
println()
println(map.islands.size.toString() + ":")
for (isl in map.islands) {
println("cost " + isl.cost)
println("mines" + isl.mines)
println()
}
}
@Test
fun randomTest() {
for (k in 0..0) {
val size = 1000
val mines = hashSetOf<Int>()
val r = Random()
for (i in 0..5)
mines.add(r.nextInt(size))
val rivers = hashSetOf<River>()
for (i in 0..3 * size) {
val first = r.nextInt(size)
var second = r.nextInt(size)
while (first == second)
second = r.nextInt(size)
rivers.add(River(first, second))
}
val map = fromDirtyMap(rivers, mines)
println(map.islands.size)
val start = mines.random()
val finish = mines.random()
val listPaths = ArrayList<List<Int>>()
while (true) {
val path = PathFinder(map).findPath(start, finish, 0, listPaths)
if (!path.isEmpty())
listPaths.add(listOf(start) + path)
else
break
}
println(listPaths.size)
}
}
}<file_sep>/src/main/kotlin/com/dekinci/contest/game/Intellect.kt
package com.dekinci.contest.game
import com.dekinci.contest.common.Log.debug
import com.dekinci.contest.common.Log.warn
import com.dekinci.contest.entities.StatedRiver
import com.dekinci.contest.game.minimax.Minimax
import java.util.concurrent.Executors
class Intellect(private val gameState: GameState) {
private val maxRef = Minimax(gameState.playersAmount, gameState.gameMap, gameState.punter, Int.MAX_VALUE)
private val maxRunner = Executors.newSingleThreadExecutor { runnable ->
Executors.defaultThreadFactory().newThread(runnable).also { it.isDaemon = true }
}
init {
maxRunner.submit {
maxRef.mineSolution()
}
}
fun getRiver(): StatedRiver? {
val move = chooseBest()
debug("Move is: $move")
return move
}
private fun chooseBest(): StatedRiver? {
Thread.sleep(400)
val river = maxRef.getBest(gameState.punter)
if (river == null) {
warn("PassMove returned!")
return null
}
gameState.update(river)
update(river.stated(gameState.punter))
return river
}
fun update(river: StatedRiver) {
maxRef.interrupt()
maxRunner.submit {
maxRef.update(river)
maxRef.mineSolution()
}
}
fun finish() {
maxRef.interrupt()
}
}<file_sep>/src/main/kotlin/com/dekinci/contest/common/Log.kt
package com.dekinci.contest.common
import org.apache.logging.log4j.LogManager
import org.apache.logging.log4j.Logger
object Log {
val logger: Logger = LogManager.getLogger()
fun trace(any: Any) {
logger.trace(any.toString())
}
fun debug(any: Any) {
logger.debug(any.toString())
}
fun info(any: Any) {
logger.info(any.toString())
}
fun warn(any: Any) {
logger.warn(any.toString())
}
fun err(any: Any) {
logger.error(any.toString())
}
fun fatal(any: Any) {
logger.fatal(any.toString())
}
}<file_sep>/src/main/kotlin/com/dekinci/contest/game/riversaresites/RiversAreSites.kt
package com.dekinci.contest.game.riversaresites
import com.dekinci.contest.entities.River
import com.dekinci.contest.game.map.graph.AdjacencyList
class RiversAreSites(
private val sitesAmount: Int,
private val totalList: AdjacencyList,
private val rivers: Array<River>,
private val mines: Set<Int>
) {
private val adjList: Array<HashSet<Int>> = Array(rivers.size) { HashSet<Int>() }
}<file_sep>/src/main/kotlin/com/dekinci/contest/bot/BotFactory.kt
package com.dekinci.contest.bot
import com.dekinci.contest.entities.BasicMap
interface BotFactory {
fun getBotName(): String
fun makeBot(punter: Int, punters: Int, map: BasicMap): Bot
}<file_sep>/src/main/kotlin/com/dekinci/contest/entities/Rectifier.kt
package com.dekinci.contest.entities
import java.util.*
data class BasicMap(val rivers: Array<River>, val mines: Set<Int>, val size: Int) {
override fun equals(other: Any?) = this === other || (other is BasicMap &&
size == other.size &&
mines == other.mines &&
rivers.contentEquals(other.rivers))
override fun hashCode() = rivers.contentHashCode() * 31 + Objects.hash(mines, size)
}
class Rectifier(dirtyRivers: Iterable<River>, dirtyMines: Iterable<Int>) {
private val distinctRivers = dirtyRivers.distinct()
private val distinctMines = dirtyMines.distinct()
private val cleanToDirty: IntArray
private val dirtyToClean: IntArray
init {
val sites = HashSet<Int>()
distinctRivers.forEach {
sites.add(it.target)
sites.add(it.source)
}
cleanToDirty = IntArray(sites.size)
sites.forEachIndexed { index, site -> cleanToDirty[index] = site }
val maxDirty = sites.max()!!
dirtyToClean = IntArray(maxDirty + 1)
sites.forEachIndexed { index, site -> dirtyToClean[site] = index }
}
fun asMap(): BasicMap {
val rivers = Array(distinctRivers.size) {
purify(distinctRivers[it])
}
val mines = distinctMines.map { purify(it) }.toHashSet()
return BasicMap(rivers, mines, cleanToDirty.size)
}
fun purify(dirtySite: Int) = dirtyToClean[dirtySite]
fun pollute(cleanSite: Int) = cleanToDirty[cleanSite]
fun purify(dirtyRiver: River) = River(
purify(dirtyRiver.target),
purify(dirtyRiver.source))
fun purify(dirtyRiver: StatedRiver) = StatedRiver(
purify(dirtyRiver.target),
purify(dirtyRiver.source),
dirtyRiver.state)
fun pollute(dirtyRiver: River) = River(
pollute(dirtyRiver.target),
pollute(dirtyRiver.source))
fun pollute(dirtyRiver: StatedRiver) = StatedRiver(
pollute(dirtyRiver.target),
pollute(dirtyRiver.source),
dirtyRiver.state)
}<file_sep>/src/test/com/dekinci/contest/entities/RectifierTest.kt
package com.dekinci.contest.entities
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
internal class RectifierTest {
private var r = Rectifier(setOf(River(0, 1)), setOf(0))
@BeforeEach
fun setUp() {
r = Rectifier(listOf(
River(1, 2),
River(2, 3),
River(2, 7)
), listOf(1, 3))
}
@Test
fun asMap() {
val expected = BasicMap(
arrayOf(River(1, 0), River(2, 1), River(3, 1)),
setOf(0, 2), 4)
assertEquals(expected, r.asMap())
}
@Test
fun purify() {
assertEquals(0, r.purify(1))
assertEquals(River(3, 1), r.purify(River(2, 7)))
}
@Test
fun pollute() {
assertEquals(1, r.pollute(0))
assertEquals(River(2, 7), r.pollute(River(3, 1)))
}
}<file_sep>/src/main/kotlin/com/dekinci/contest/game/map/FancyRivers.kt
package com.dekinci.contest.game.map
import com.dekinci.contest.entities.River
class FancyRivers(private val gameMap: GameMap) {
private val rivers = HashSet<River>()
init {
gameMap.basicMap.mines.forEach { siteChange(it) }
}
fun update(river: River) {
rivers.remove(river)
siteChange(river.target)
siteChange(river.source)
}
fun remove(river: River) {
rivers.remove(river)
}
private fun siteChange(site: Int) {
val connections = gameMap.getFreeConnections(site)
if (connections.isEmpty())
rivers.removeAll { it.has(site) }
else
rivers.addAll(connections.map { River(site, it) })
}
fun getRivers(): Set<River> = rivers
}<file_sep>/src/main/kotlin/com/dekinci/contest/game/tactics/PassTactics.kt
package com.dekinci.contest.game.tactics
class PassTactics : Tactics {
override fun isFinished() = false
override fun isSuccessful() = false
override fun next(): Nothing? = null
override fun hasNext() = true
}<file_sep>/src/main/kotlin/com/dekinci/contest/game/tactics/GreedyTactics.kt
package com.dekinci.contest.game.tactics
import com.dekinci.contest.entities.StatedRiver
import com.dekinci.contest.game.GameState
class GreedyTactics(private val gameState: GameState) : Tactics {
private var isFinished = false
private var isSuccessful = false
override fun isFinished() = isFinished
override fun isSuccessful() = isSuccessful
override fun next(): StatedRiver? {
TODO()
}
override fun hasNext(): Boolean {
return false
}
}<file_sep>/src/test/com/dekinci/contest/game/map/graph/DijkstraTest.kt
import com.dekinci.contest.connectedMap
import com.dekinci.contest.disconnectedMap
import com.dekinci.contest.entities.River
import com.dekinci.contest.game.map.GameMap
import com.dekinci.contest.game.map.graph.AdjacencyList
import com.dekinci.contest.game.map.graph.Dijkstra
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Test
import java.util.*
class DijkstraTest {
@Test
fun test() {
val d = dFromMap(connectedMap())
assertEquals(intArrayOf(0, 1, 2, 1, 1, 3, 2, 2, 2).toList(), d.sparse(0).toList())
assertEquals(intArrayOf(1, 1, 1, 2, 0, 2, 1, 1, 1).toList(), d.sparse(4).toList())
}
@Test
fun testDiv() {
val d = dFromMap(disconnectedMap())
assertEquals(intArrayOf(-1, -1, -1, -1, -1, 0, -1, -1, 1).toList(), d.sparse(5).toList())
assertEquals(intArrayOf(0, 1, 2, 1, 1, -1, 2, 2, -1).toList(), d.sparse(0).toList())
}
private fun dFromMap(map: GameMap): Dijkstra {
val adjList = AdjacencyList(map.basicMap.size, map.basicMap.rivers)
return Dijkstra(map.basicMap.size, adjList)
}
}<file_sep>/src/test/com/dekinci/contest/common/QuantumTreeTest.kt
package com.dekinci.contest.common
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.Test
import java.lang.ref.PhantomReference
import java.lang.ref.Reference
import java.lang.ref.ReferenceQueue
import java.util.*
internal class QuantumTreeTest {
/**
* 2
* /
* 1
* \ 4
* 3
* 5
*/
@Test
fun test() {
val qt = QuantumTree(1.toString())
val n22 = qt.root.next(3.toString())
n22.next(4.toString())
n22.next(5.toString())
val rq = ReferenceQueue<QuantumTree<String>.Node>()
val r1 = PhantomReference<QuantumTree<String>.Node>(qt.root, rq)
val r2 = PhantomReference<QuantumTree<String>.Node>(qt.root.next(2.toString()), rq)
qt.root = n22
System.gc()
val expectedSet = setOf<Reference<out QuantumTree<String>.Node>?>(r1, r2)
val actualSet = HashSet<Reference<out QuantumTree<String>.Node>>()
var ref: Reference<out QuantumTree<String>.Node>? = rq.remove(100)
while (ref != null) {
actualSet.add(ref)
ref = rq.remove(100)
}
assertEquals(expectedSet, actualSet)
}
/**
* 4
* 2
* / 5
* 1
* \ 5
* 3
* 6
*/
@Test
fun quantumTest() {
val qt = QuantumTree(1.toString())
val n21: QuantumTree<String>.Node = qt.root.next(2.toString())
n21.next(4.toString())
val first = n21.next(5.toString())
val n22: QuantumTree<String>.Node = qt.root.next(3.toString())
val second = n22.next(5.toString())
n22.next(6.toString())
assertTrue(first === second)
}
}
fun main(args: Array<String>) {
}<file_sep>/src/main/kotlin/com/dekinci/contest/entities/StatedRiver.kt
package com.dekinci.contest.entities
import com.dekinci.contest.protocol.Claim
import java.lang.IllegalStateException
class StatedRiver(val source: Int, val target: Int, val state: Int = RiverStateID.NEUTRAL) {
constructor(claim: Claim) : this(claim.source, claim.target, claim.punter)
fun stateless() = River(source, target)
fun has(site: Int) = source == site || target == site
fun another(site: Int) = if (source == site) target else if (target == site) source else throw IllegalStateException("No $site")
override fun equals(other: Any?) = (other is StatedRiver &&
(source == other.source && target == other.target ||
source == other.target && target == other.source) && other.state == state) ||
(other is River &&
(source == other.source && target == other.target ||
source == other.target && target == other.source))
override fun hashCode() = (source.hashCode() xor target.hashCode()) + 31 * (state + 1)
override fun toString(): String = "$source $target $state"
fun stated(state: Int) = StatedRiver(source, target, state)
}<file_sep>/src/main/kotlin/com/dekinci/contest/protocol/ServerConnection.kt
package com.dekinci.contest.protocol
import java.io.BufferedReader
import java.io.InputStreamReader
import java.io.PrintWriter
import java.net.Socket
class ServerConnection(url: String, port: Int) {
private var socket = Socket(url, port)
var sin = BufferedReader(InputStreamReader(socket.getInputStream()))
var sout = PrintWriter(socket.getOutputStream(), true)
init {
socket.setSoLinger(true, 10)
}
fun <T> sendJson(json: T) {
val jsonString = objectMapper.writeValueAsString(json)
sout.println("${jsonString.length}:${jsonString}")
sout.flush()
}
inline fun <reified T> receiveJson(): T {
val lengthChars = mutableListOf<Char>()
var ch = '0'
while (ch != ':') {
lengthChars += ch
ch = sin.read().toChar()
}
val length = lengthChars.joinToString("").trim().toInt()
// Чтение из Reader нужно делать очень аккуратно
val contentAsArray = CharArray(length)
var start = 0
// Операция read не гарантирует нам, что вернулось именно нужное количество символов
// Поэтому её нужно делать в цикле
while (start < length) {
val read = sin.read(contentAsArray, start, length - start)
start += read
}
return objectMapper.readValue(String(contentAsArray), T::class.java)
}
}
<file_sep>/src/test/com/dekinci/contest/game/IntellectTest.kt
package com.dekinci.contest.game
import com.dekinci.contest.disconnectedMap
import org.junit.jupiter.api.Test
internal class IntellectTest {
fun createState(): GameState {
return GameState(0, 1, disconnectedMap().basicMap)
}
@Test
fun chooseMove() {
val int = Intellect(createState())
for (i in 0 .. 12)
println(int.getRiver())
int.finish()
}
}<file_sep>/src/main/kotlin/com/dekinci/contest/common/QuantumTree.kt
package com.dekinci.contest.common
class QuantumTree<T>(rootElement: T) {
private val nodes = newWeakHashSet<Node>()
inner class Node(val data: T, parent: Node? = null) {
private val parents = newWeakHashSet<Node>()
private val children = HashSet<Node>()
init {
parent?.let { parents.add(it) }
}
fun next(data: T): Node {
var next = Node(data, this)
val found = nodes.find { it == next }
if (found != null) {
next = found
next.parents.add(this)
}
else
nodes.add(next)
children.add(next)
return next
}
fun anyLastMatchingOrRoot(predicate: (T) -> Boolean): Node {
var parents = newWeakHashSet<Node>(parents)
while (parents.isNotEmpty()) {
val nextParents = newWeakHashSet<Node>()
for (parent in parents) {
if (predicate.invoke(parent.data))
return parent
nextParents.addAll(parent.children)
}
parents = nextParents
}
return this
}
override fun equals(other: Any?): Boolean {
return other === this || (other is QuantumTree<*>.Node && other.data == data )
}
override fun hashCode(): Int {
return data.hashCode()
}
override fun toString(): String {
return data.toString()
}
}
var root = Node(rootElement)
init {
nodes.add(root)
}
}<file_sep>/src/test/com/dekinci/contest/entities/RiverTest.kt
package com.dekinci.contest.entities
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.Assertions.*
import java.lang.IllegalStateException
internal class RiverTest {
@Test
fun has() {
val r = River(5, 10)
assertTrue(r.has(5))
assertTrue(r.has(10))
assertFalse(r.has(7))
}
@Test
fun another() {
val r = River(5, 10)
assertEquals(10, r.another(5))
assertEquals(5, r.another(10))
assertThrows(IllegalStateException::class.java) { r.another(7) }
}
@Test
fun equalsTest() {
val r1 = River(5, 10)
val r2 = River(10, 5)
assertEquals(r1, r2)
assertEquals(r2, r1)
}
@Test
fun hashCodeTest() {
val r1 = River(5, 10)
val r2 = River(10, 5)
assertEquals(r1.hashCode(), r2.hashCode())
}
@Test
fun stated() {
val sr = StatedRiver(5, 10, 0)
val r = River(10, 5)
assertEquals(sr, r.stated(0))
}
}<file_sep>/src/test/com/dekinci/contest/common/LayeredHashSetTest.kt
package com.dekinci.contest.common
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.Assertions.*
import org.junit.jupiter.api.BeforeEach
internal class LayeredHashSetTest {
var set = LayeredHashSet<Int, Int>()
@BeforeEach
fun setup() {
set = LayeredHashSet()
}
@Test
fun test() {
}
@Test
fun setDefault() {
}
@Test
fun addLayer() {
}
@Test
fun removeLayer() {
}
@Test
fun mergeLayer() {
}
@Test
fun mergeRemoveLayer() {
}
@Test
fun rotateToLayer() {
set.baseAdd(1)
set.baseAdd(2)
set.baseAdd(5)
set.addLayer(0)
val first = set.get(0)
set.addLayer(1)
val second = set.get(1)
first.add(3)
first.remove(1)
second.add(4)
second.add(3)
second.remove(5)
set.rotateToLayer(0)
assertEquals(setOf(2, 3, 5), first)
assertEquals(setOf(1, 2, 3, 4), second)
assertEquals(setOf(2, 3, 5), set.baseGet())
}
@Test
fun getSize() {
}
@Test
fun size() {
}
@Test
fun getBaseSize() {
}
@Test
fun add() {
set.add(1)
assertEquals(1, set.size)
assertTrue(set.contains(1))
}
@Test
fun add1() {
set.addLayer(0)
set.add(1, 0)
assertEquals(1, set.size(0))
assertEquals(0, set.size)
assertTrue(set.contains(1, 0))
}
@Test
fun baseAdd() {
set.baseAdd(1)
assertEquals(1, set.size)
assertEquals(1, set.baseSize)
assertTrue(set.contains(1))
assertTrue(set.baseContains(1))
}
@Test
fun remove() {
set.add(1)
set.remove(1)
assertEquals(0, set.size)
assertFalse(set.contains(1))
assertTrue(set.isEmpty())
}
@Test
fun remove1() {
set.addLayer(0)
set.add(1, 0)
set.remove(1, 0)
assertEquals(0, set.size)
assertFalse(set.contains(1, 0))
assertTrue(set.isEmpty(0))
}
@Test
fun baseRemove() {
set.baseAdd(1)
set.baseRemove(1)
assertEquals(0, set.size)
assertEquals(0, set.baseSize)
assertFalse(set.contains(1))
assertFalse(set.baseContains(1))
}
@Test
fun contains() {
}
@Test
fun contains1() {
}
@Test
fun baseContains() {
}
@Test
fun clearLayer() {
}
@Test
fun clearBase() {
}
}
|
a7c4253b2a5d3e6a031116f8a1cc71668954ee4a
|
[
"Markdown",
"Kotlin"
] | 65
|
Kotlin
|
DeKinci/budding-jack
|
7a190f29f7504caad0432f153b13ab97b97115dc
|
04b6f44a939eb72f44a08580c7919b3b8776471c
|
refs/heads/master
|
<file_sep>/* nml: continents of the world */
"use strict";
module.exports = {
"confil" : [
{
"continent": "Africa"
},
{
"continent": "Antarctica"
},
{
"continent": "Asia"
},
{
"continent": "Europe"
},
{
"continent": "North America"
},
{
"continent": "Oceania"
},
{
"continent": "South America"
}
]
}
|
8d7d5481fa81b012b6f15dc1296bcdba6f410b93
|
[
"JavaScript"
] | 1
|
JavaScript
|
Usbeck95/nodeVII
|
c194c8c4d2d73bf3db73fbc404a12e5709dfc6d7
|
7c76f6eb7d261946cf264d9457e24b023395bb2e
|
refs/heads/master
|
<repo_name>JimmyDinSpace/LITTLEscript<file_sep>/iwait_then_sync
#!/bin/bash
# Detect file changes and copy-and-paste to TARGET dir
# for web project develop
# Important to add slash to pwd, means rsync would copy
# > the content of directory
SOURCE_DIR=$(pwd)/
TARGET_DIR=$1
read -e -p "Enter target directory: " TARGET_DIR
while [ ! -d $TARGET_DIR ]
do
echo "$TARGET_DIR is not a valid directory!"
read -e -p "Enter target directory: " TARGET_DIR
done
# TODO test the file with tilde (~) fix
EXCLUDE_PATTERN="^[.]"
inotifywait -mr --timefmt '%d/%m/%y %H:%M' --format '%T %w %f' \
-e close_write --exclude $EXCLUDE_PATTERN $SOURCE_DIR | while read date time dir file; do
rsync --update -alvr --exclude '*/.*' --exclude "*/WEB-INF" --exclude "*~" $SOURCE_DIR $TARGET_DIR
done
|
49404f09895050b02d89e28bbad39789fcdf9097
|
[
"Shell"
] | 1
|
Shell
|
JimmyDinSpace/LITTLEscript
|
69fd3ef5428d949ad668ee1d447fc7ce0470a657
|
9882646f36d865a8801b6922214bfc1b6440ea3e
|
refs/heads/master
|
<repo_name>monsenhordivisorias/monsenhordivisorias.github.io<file_sep>/js/angularapp.js
(function () {
'use strict';
var baseURL = 'https://monsenhordivisorias.github.io';
$('.button-collapse').sideNav();
var app = angular.module("app", ["ngRoute"]);
app.config(function ($routeProvider, $locationProvider) {
$locationProvider.html5Mode(true);
$locationProvider.hashPrefix('');
$routeProvider
.when('/', {
templateUrl: baseURL + '/templates/home.html',
controller: 'MainController'
})
.when('/contato', {
templateUrl: baseURL + '/templates/contato.html',
controller: 'ContatoController'
})
.when('/empresa', {
templateUrl: baseURL + '/templates/empresa.html',
controller: 'EmpresaController'
})
.when('/servicos', {
templateUrl: baseURL + '/templates/servicos.html',
controller: 'ServicosController'
})
.otherwise({
redirectTo: '/'
});
});
app.controller("MainController", function ($scope) {
$scope.sliders = [{image: "https://depilacaoaraxa.github.io/images/slider1.png", title: "Alta qualidade"},
{image: "https://depilacaoaraxa.github.io/images/slider2.jpg", title: "Conserto de roupas"},
{image: "https://depilacaoaraxa.github.io/images/slider3.jpg", title: "Customização"}];
$scope.sections = [{icon: "flash_on", title: "Processo rápido", body: "Muitos anos anos de experiência, garantem um serviço com qualidade e no menor tempo possível"},
{icon: "group", title: "Atenção com as demandas dos clientes", body: "Buscamos que o cliente se sinta realizado em sua individualidade e gosto."},
{icon: "settings", title: "Precisão", body: "Buscamos o melhor acabamento, qualidade e durabilidade."}];
$('.slider').slider();
});
app.controller("NavController", function ($scope, $location) {
$('.button-collapse').sideNav({ closeOnClick: true });
$scope.isActive = function (viewLocation) {
return viewLocation === $location.path();
}
});
app.controller("FooterController", function ($scope) {
});
app.controller("ServicosController", function ($scope) {
$scope.servicos = [{image: "flash_on", title: "Entrega rápida", body: ""},
{image: "group", title: "Trabalhamos para lhe atender no menor tempo possível.", body: ""},
{image: "settings", title: "Customização", body: ""}];
});
app.controller("EmpresaController", function ($scope) {
});
app.directive('navbar', function () {
return {
restrict: 'A',
controller: 'NavController',
controllerAs: 'ctrl',
templateUrl: baseURL + '/templates/navbar.html'
};
});
app.directive('footer', function () {
return {
restrict: 'A',
controller: 'FooterController',
controllerAs: 'ctrl',
templateUrl: baseURL + '/templates/footer.html'
};
});
app.controller("ContatoController", function ($scope, $location) {
$scope.mail = { nome: "", email: "", telefone: "", asunto: "", mensagem: "" };
$scope.submit = function (event) {
event.preventDefault();
$.ajax({
url: "https://formspree.io/<EMAIL>ias@<EMAIL>",
method: "POST",
data: {
message: "Nome: " + $scope.mail.nome + "\n" +
"Email: " + $scope.mail.email + "\n" +
"Telefone: " + $scope.mail.telefone + "\n" +
"Asunto: " + $scope.mail.asunto + "\n" +
"Mensagem: " + $scope.mail.mensagem, _replyto: $scope.mail.email
},
dataType: "json"
}).done(function (resp) {
console.log("success");
$scope.$apply(function () {
$location.path("/");
});
}).fail(function (error) {
console.log("fail");
});
};
});
})();
<file_sep>/README.md
# mrdmcostura.github.io
Meu site
|
0afb50f620b263f9212758d14b9292ca5c77adaf
|
[
"JavaScript",
"Markdown"
] | 2
|
JavaScript
|
monsenhordivisorias/monsenhordivisorias.github.io
|
df135a13834f6c765d2991628a66d78bd9a9ed1e
|
1ba6952c5ee57669568b49ccc844af845d5b8950
|
refs/heads/master
|
<repo_name>SimonePDA/VidorPeripherals<file_sep>/src/VidorUART.cpp
/*
Copyright (c) 2015 Arduino LLC. All right reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library 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 Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "VidorUART.h"
#include "Arduino.h"
VidorUart::VidorUart(int _idx,int _tx,int _rx,int _cts,int _rts,int _dtr,int _dsr)
{
index = idx;
idx=_idx;
tx=_tx;
rx=_rx;
cts=_cts;
rts=_rts;
dtr=_dtr;
dsr=_dsr;
}
void VidorUart::begin(unsigned long baudrate)
{
begin(baudrate, SERIAL_8N1);
}
void VidorUart::begin(unsigned long baudrate, uint16_t config)
{
VidorIO::enableUART(tx,rx);
VidorIO::setUART(index, baudrate, config);
}
void VidorUart::end()
{
VidorIO::disableUART(index);
rxBuffer.clear();
txBuffer.clear();
}
void VidorUart::flush()
{
while(txBuffer.available()); // wait until TX buffer is empty
VidorIO::flushUART(index);
}
int VidorUart::available()
{
int ret = VidorIO::availableUART(index);
if (ret > 0) {
// Workaround until we have interrupt capabilities
onInterrupt();
}
return ret;
}
void VidorUart::onInterrupt()
{
int available = VidorIO::availableUART(index);
while (available-- > 0) {
rxBuffer.store_char(VidorIO::readUART(index));
}
}
int VidorUart::availableForWrite()
{
return txBuffer.availableForStore();
}
int VidorUart::peek()
{
return rxBuffer.peek();
}
int VidorUart::read()
{
return VidorIO::readUART(index);
}
size_t VidorUart::write(const uint8_t data)
{
VidorIO::writeUART(index, data);
return 1;
}
size_t VidorUart::write(const uint8_t* data, size_t len)
{
VidorIO::writeUART(index, (uint8_t*)data, len);
return len;
}
int VidorUart::enableFlowControl(void)
{
if(rts>=0 && cts>=0 && dtr>=0 && dsr>=0 ) {
VidorIO::enableUART(rts,cts);
VidorIO::enableUART(dtr,dsr);
return 1;
}
return 0;
}
#if FPGA_UART_INTERFACES_COUNT > 0
VidorUart SerialFPGA0(0, A0, A1, -1, -1, -1, -1);
#if FPGA_UART_INTERFACES_COUNT > 1
VidorUart SerialFPGA1(1, A2, A3, A0, A1, -1, -1);
#if FPGA_UART_INTERFACES_COUNT > 2
VidorUart SerialFPGA2(2, A4, A5, -1, -1, -1, -1);
#if FPGA_UART_INTERFACES_COUNT > 3
VidorUart SerialFPGA3(3, A6, 0, A4, A5, A3, A2);
#if FPGA_UART_INTERFACES_COUNT > 4
VidorUart SerialFPGA4(4, 1, 2, -1, -1, -1, -1);
#if FPGA_UART_INTERFACES_COUNT > 5
VidorUart SerialFPGA5(5, 3, 4, 1, 2, 0, A6);
#if FPGA_UART_INTERFACES_COUNT > 6
VidorUart SerialFPGA6(6, 5, 6, -1, -1, -1, -1);
#if FPGA_UART_INTERFACES_COUNT > 7
VidorUart SerialFPGA7(7, 7, 8, 5, 6, 4, 3);
#endif
#endif
#endif
#endif
#endif
#endif
#endif
#endif<file_sep>/src/defines.h
#include "common.h"
#ifndef __DEFINES_VIDOR_H__
#define __DEFINES_VIDOR_H__
#define FPGA_SPI_INTERFACES_COUNT 4
#define FPGA_I2C_INTERFACES_COUNT 4
#define FPGA_UART_INTERFACES_COUNT 8
#define FPGA_ENCODERS_COUNT 11
#define FPGA_NEOPIXEL_COUNT 4
#define FPGA_CAMERA_COUNT 0
#define FPGA_GFX_COUNT 0
#define FPGA_QR_COUNT 0
#define GPIO_NUM_OFFSET 100
#define IRQ_PIN 33
#define NEOPIXEL_PIN_0 A6
#define NEOPIXEL_PIN_1 0
#define NEOPIXEL_PIN_2 7
#define NEOPIXEL_PIN_3 8
#define NEOPIXEL_PIN_4 12
#define NEOPIXEL_PINMUX 5
#endif<file_sep>/library.properties
name=VidorBase
version=1.0.0
author=<NAME> <<EMAIL>>
maintainer=<NAME> <<EMAIL>>
sentence=Provides extended IO functionalities and interfaces
paragraph=Provides extended IO functionalities and interfaces
category=Data Processing
url=https://github.com/arduino/VidorLibs
architectures=samd,samd_beta
<file_sep>/src/VidorBase.cpp
#include "VidorPeripherals.h"
VidorBase FPGA;
#if 1
__attribute__ ((used, section(".fpga_bitstream_signature")))
const unsigned char signatures[4096] = {
//#include "signature.ttf"
NO_BOOTLOADER,
0x00, 0x00, 0x08, 0x00,
0xA9, 0x6F, 0x1F, 0x00,
0x6f, 0x90, 0x25, 0x62, 0xb4, 0xec, 0xae, 0x0a, 0xa7, 0x28, 0x22, 0xc6, 0x91, 0xbf, 0x61, 0x65, 0xef, 0x0d, 0x9d, 0x7c, 0x04, 0x19, 0x82, 0x3b, 0x0a, 0xf1, 0x4e, 0x00, 0x00, 0xff, 0xf0, 0x0f,
0x01, 0x00, 0x00, 0x00, /* TAG 1 == USER BITSTREAM */
0x00, 0x00, 0x00, 0x00, // Don't force
NO_USER_DATA,
};
__attribute__ ((used, section(".fpga_bitstream")))
const unsigned char bitstream[] = {
#include "app.ttf"
};
#endif
void VidorBase::onInterrupt() {
// TODO: do be implemented
}
#if 0
// This strong implementation allows booting the FPGA without external intervention
extern "C" void startFPGA() {
FPGA.begin();
}
#endif
|
b1d2b87c098da1889274b415b5948e6d4d870fc5
|
[
"C",
"C++",
"INI"
] | 4
|
C++
|
SimonePDA/VidorPeripherals
|
87fd3d8ec371c545d0ef2302e59e2ecdcca7500f
|
0a6c7eed07898089033778c86e3d831348a923d9
|
refs/heads/main
|
<file_sep>#install necessary packages if required
#install.packages(c("matrixStats", "Hmisc", "splines", "foreach", "doParallel", "fastcluster", "dynamicTreeCut", "survival"))
BiocManager::install((c("GO.db", "preprocessCore", "impute")))
BiocManager::install('WGCNA')
#load packages
library(robustHD)
# from https://gist.github.com/stevenworthington/3178163
ipak <- function(pkg){
new.pkg <- pkg[!(pkg %in% installed.packages()[, "Package"])]
if (length(new.pkg))
install.packages(new.pkg, dependencies = TRUE, repos = "http://cran.r-project.org")
sapply(pkg, require, character.only = TRUE)
}
# usage
packages <- c("ggplot2", "gplots", "lattice", "plyr", "reshape2",
"RColorBrewer", "grid", "gridExtra", "igraph", "igraphdata")
suppressMessages(ipak(packages))
#load more packages
library(WGCNA);
options(stringsAsFactors = FALSE)
(.packages())
#load Arivale metabolomics data
LC_data = read.csv("mets_arivale_baseline_no_impute.csv");
# Take a quick look at what is in the data set:
dim(LC_data)
head(LC_data)
LC_data=as.data.frame(LC_data)
dim(LC_data)
rownames(LC_data)<-LC_data$public_client_id
num_df<-LC_data[,2:1297]
dim(num_df)
#remove metabolites with more than 50% missing values as well as samples with too many missing values (default parameters)
gsg = goodSamplesGenes(num_df, verbose = 3);
gsg$allOK
if (!gsg$allOK)
{
# Optionally, print the gene and sample names that were removed:
if (sum(!gsg$goodGenes)>0)
printFlush(paste("Removing genes:", paste(names(num_df)[!gsg$goodGenes], collapse = ", ")));
if (sum(!gsg$goodSamples)>0)
printFlush(paste("Removing samples:", paste(rownames(num_df)[!gsg$goodSamples], collapse = ", ")));
# Remove the offending genes and samples from the data:
num_df = num_df[gsg$goodSamples, gsg$goodGenes]
}
# Choose a set of soft-thresholding powers
powers = c(c(1:10), seq(from = 11, to=15, by=1))
# Call the network topology analysis function
sft = pickSoftThreshold(num_df, powerVector = powers, verbose = 5,corOptions=c(use='p',method='spearman'), networkType='signed')
# Plot the results:
#sizeGrWindow(9, 5)
par(mfrow = c(1,2));
cex1 = 0.8;
# Scale-free topology fit index as a function of the soft-thresholding power
plot(sft$fitIndices[,1], -sign(sft$fitIndices[,3])*sft$fitIndices[,2],
xlab="Soft Threshold (power)",ylab="Scale Free Topology Model Fit,signed R^2",type="n",
main = paste("Scale independence"));
text(sft$fitIndices[,1], -sign(sft$fitIndices[,3])*sft$fitIndices[,2],
labels=powers,cex=cex1,col="red");
# this line corresponds to using an R^2 cut-off of h
abline(h=0.80,col="red")
# Mean connectivity as a function of the soft-thresholding power
plot(sft$fitIndices[,1], sft$fitIndices[,5],
xlab="Soft Threshold (power)",ylab="Mean Connectivity", type="n",
main = paste("Mean connectivity"))
text(sft$fitIndices[,1], sft$fitIndices[,5], labels=powers, cex=cex1,col="red")
#based on the prior threshold search, we choose the one that best approximates a scale free topology while still maintaining high level of connectivity
#in the network
softPower =11;
#Generate an adjacency matrix
adjacency = adjacency(num_df, power = softPower,corOptions=list(use='p',method='spearman'),type = "signed" );
# Turn adjacency into topological overlap
TOM = TOMsimilarity(adjacency,TOMType = "signed");
dissTOM = 1-TOM
# Call the hierarchical clustering function
geneTree = hclust(as.dist(dissTOM), method = "average");
# Plot the resulting clustering tree (dendrogram)
#sizeGrWindow(12,9)
plot(geneTree, xlab="", sub="", main = "Gene clustering on TOM-based dissimilarity",
labels = FALSE, hang = 0.04);
#We like large modules, so we set the minimum module size relatively high:
minModuleSize = 20;
# Module identification using dynamic tree cut:
dynamicMods = cutreeDynamic(dendro = geneTree, distM = dissTOM,
deepSplit = 3, pamRespectsDendro = FALSE,
minClusterSize = minModuleSize);
table(dynamicMods)
# Convert numeric lables into colors
dynamicColors = labels2colors(dynamicMods)
table(dynamicColors)
# Plot the dendrogram and colors underneath
#sizeGrWindow(8,6)
plotDendroAndColors(geneTree, dynamicColors, "Dynamic Tree Cut",
dendroLabels = FALSE, hang = 0.03,
addGuide = TRUE, guideHang = 0.05,
main = "Gene dendrogram and module colors")
# Calculate eigengenes
MEList = moduleEigengenes(num_df, colors = dynamicColors,nPC = 2)
MEs = MEList$eigengenes
# Calculate dissimilarity of module eigengenes
MEDiss = 1-cor(MEs);
# Cluster module eigengenes
METree = hclust(as.dist(MEDiss), method = "average");
# Plot the result
#sizeGrWindow(7, 6)
plot(METree, main = "Clustering of module eigengenes",
xlab = "", sub = "")
MEDissThres = .3
abline(h=MEDissThres, col = "red")
# Call an automatic merging function
merge = mergeCloseModules(num_df, dynamicColors, cutHeight = MEDissThres, verbose = 3)
# The merged module colors
mergedColors = merge$colors;
# Eigengenes of the new merged modules:
mergedMEs = merge$newMEs;
#pdf(file = "Plots/geneDendro-3.pdf", wi = 9, he = 6)
plotDendroAndColors(geneTree, cbind(dynamicColors, mergedColors),
c("Dynamic Tree Cut", "Merged dynamic"),
dendroLabels = FALSE, hang = 0.03,
addGuide = TRUE, guideHang = 0.05)
# Plot the cut line into the dendrogram
#dev.off()
#Set the diagonal of the dissimilarity to NA
#diag(dissTOM) = NA;
#Visualize the Tom plot. Raise the dissimilarity matrix to a power to bring out the module structure
#sizeGrWindow(7,7)
# Open a graphical window
myheatcol = colorpanel(225,'red',"orange",'lemonchiffon')
#, col=myheatcol
TOMplot(dissTOM^12, geneTree, as.character(mergedColors),main = "Network heatmap plot, all genes",color=myheatcol)
# Rename to moduleColors
moduleColors = mergedColors
# Construct numerical labels corresponding to the colors
colorOrder = c("grey", standardColors(50));
moduleLabels = match(moduleColors, colorOrder)-1;
MEs = mergedMEs;
head(MEs)
write.csv(MEs,'Module_eigenvalues_Arivale_mets_09_27_2021.csv')
# Further correlation of metabolites and eigenvalues for identification of hub mets
nGenes = ncol(num_df);
nSamples = nrow(num_df);
geneModuleMembership = as.data.frame(cor(num_df, MEs, use = "p"));
MMPvalue = as.data.frame(corPvalueStudent(as.matrix(geneModuleMembership), nSamples));
MMPvalue
mets=read.csv('met_names.csv')
mets$X0[1:10]
genes<-t(num_df)
d<-as.data.frame(moduleColors)
d$gene<-colnames(num_df)
write.csv(d,'module_assignments_arivale.csv')
<file_sep># WGCNA-Metabolon-Code
The code provided runs through the steps of generating a weighted gene co-expression network using Metabolon, Inc. data from the Arivale cohort.
The code is written in R and was originally run on a Jupyter Notebook.
Metabolite values in the Arivale cohort were median scaled within each batch (run), such that the median value for each metabolite was 1. To adjust for possible batch effects, further normalization across batches was performed by dividing the median-scaled value of each metabolite by the corresponding average value for the same metabolite in quality control samples of the same batch. No imputation or further normalization steps were taken prior to running WGCNA. WGCNA has its own set of filtering parameters to exclude samples and analytes with high number of missing values.
|
fc7ad2ad43a670a73f7ceeef6b240e70cba84d8a
|
[
"Markdown",
"R"
] | 2
|
R
|
PriceLab/WGCNA-Metabolon-Code
|
6ca0b22550f980d48f5f9a7034a12bfb90d8c12c
|
6332b6178d77d56825e7a892a6706b59bc8be8fe
|
refs/heads/master
|
<repo_name>Ryudas/CG-OpenGL-Demo<file_sep>/include/gl/texture.h
#pragma once
#include "disable_all_warnings.h"
DISABLE_WARNINGS_PUSH()
#include <GL/glew.h>
#include <glm/vec3.hpp>
DISABLE_WARNINGS_POP()
#include <exception>
#include <filesystem>
#include <memory>
struct ImageLoadingException : public std::runtime_error {
using std::runtime_error::runtime_error;
};
class Framebuffer;
class Texture {
protected:
std::shared_ptr<GLuint> m_texture = nullptr;
public:
Texture() = default;
Texture(const Texture&) = default;
Texture(GLsizei width, GLsizei height, GLenum internalFormat);
Texture(std::filesystem::path filePath);
virtual void bind(GLint textureSlot) const;
virtual void set(GLenum parameter, GLint setting);
friend Framebuffer;
virtual ~Texture() = default;
};
<file_sep>/include/util3D/basic_geometry.h
#pragma once
#include "disable_all_warnings.h"
DISABLE_WARNINGS_PUSH()
#include <GL/glew.h>
#include <glm/vec2.hpp>
#include <glm/vec3.hpp>
DISABLE_WARNINGS_POP()
#include <memory>
#include <exception>
#include <filesystem>
#include <vector>
#include "gl/shader_stage.h"
#include "util3D/geometry.h"
class BasicGeometry :public Geometry{
private:
GLsizei m_numIndices { 0 };
bool m_hasTextureCoords { false };
std::shared_ptr<GLuint> m_ibo = nullptr;
std::shared_ptr<GLuint> m_vbo = nullptr;
std::shared_ptr<GLuint> m_vao = nullptr;
VertexShader vertex_shader, xray_vertex_shader;
public:
BasicGeometry() = default;
BasicGeometry(const BasicGeometry&) = default;
BasicGeometry(std::filesystem::path filePath);
bool hasTextureCoords() const;
const VertexShader& getVertexShader() const override;
void setVertexShader(std::filesystem::path filePath);
// Bind VAO and call glDrawElements.
void draw() const;
virtual const void* getUniformData() const;
virtual GLsizeiptr getUniformDataSize() const;
virtual ~BasicGeometry() = default;
};
<file_sep>/include/util3D/light.h
#pragma once
#include <memory>
#include <functional>
#include <GL/glew.h>
#include <glm/glm.hpp>
#include "util3D/transformable.h"
typedef struct alignas(16) _LightUniformData {
glm::mat4 light_mvp;
glm::vec3 light_color;
float __pad__;
glm::vec3 light_position;
uint32_t casts_shadow;
} LightUniformData;
class Light {
protected:
std::unique_ptr<GLuint, std::function<void(GLuint*)>> ubo;
LightUniformData data;
public:
Light();
void updateUniformData() const;
virtual void bind();
virtual ~Light() = default;
};<file_sep>/src/util3D/light.cpp
#include "util3D/light.h"
#include <functional>
Light::Light() {
ubo = std::unique_ptr<GLuint, std::function<void(GLuint*)>>(new GLuint(), [](GLuint* p){
glDeleteBuffers(1, p);
delete p;
});
glCreateBuffers(1, ubo.get());
}
void Light::updateUniformData() const {
glBindBuffer(GL_UNIFORM_BUFFER, *ubo);
glBufferData(GL_UNIFORM_BUFFER,sizeof(LightUniformData), &data, GL_DYNAMIC_DRAW);
glBindBuffer(GL_UNIFORM_BUFFER, 0);
}
void Light::bind() {
glBindBufferBase(GL_UNIFORM_BUFFER, 2, *ubo);
}<file_sep>/include/prospective_camera.h
//
// Created by erik on 5/25/20.
//
#pragma once
#include "disable_all_warnings.h"
#include<glm/glm.hpp>
#include "util3D/camera.h"
#include "gl/framebuffer.h"
#include "gl/texture.h"
#include "util3D/basic_geometry.h"
class Camera;
class ProspectiveCamera : public Camera
{
private:
BasicGeometry quad;
std::vector<std::shared_ptr<Shader>> postFxShaders = {};
double sensitivity = 0.005;
float movementMul = 0.1f;
glm::mat4 prospectiveMatrix;
Framebuffer framebuffer[2];
Texture depthTexture[2], colorTexture[2];
unsigned short targetBuffer = 0, sourceBuffer = 1;
void flipBuffers();
bool useXRay = false;
public:
ProspectiveCamera();
void updateViewMatrix();
void mouseRotate(double, double);
const glm::mat4& getProjectionMatrix() const;
void prerender();
void renderMesh(const Scene& scene, const Mesh& mesh) const override;
void postrender() override;
void addPostShader(std::shared_ptr<Shader> shader);
void clearAllBuffers();
void toggleXRay();
};<file_sep>/include/gl/cube_texture.h
#pragma once
#include "texture.h"
class CubeTexture : public Texture
{
public:
CubeTexture() = default;
CubeTexture(const CubeTexture&) = default;
CubeTexture(std::filesystem::path filePath);
void bind(GLint textureSlot) const override;
};<file_sep>/src/util3D/basic_geometry.cpp
#include <iostream>
#include <stack>
#include <vector>
#include <filesystem>
#include "disable_all_warnings.h"
DISABLE_WARNINGS_PUSH()
#include <assimp/Importer.hpp>
#include <assimp/postprocess.h>
#include <assimp/scene.h>
#include <fmt/format.h>
#include <glm/gtc/matrix_inverse.hpp>
#include <glm/mat3x3.hpp>
#include <glm/mat4x4.hpp>
#include <glm/vec4.hpp>
#include <gsl/span>
DISABLE_WARNINGS_POP()
#include "util3D/basic_geometry.h"
static glm::mat4 assimpMatrix(const aiMatrix4x4& m);
static glm::vec3 assimpVec(const aiVector3D& v);
BasicGeometry::BasicGeometry(std::filesystem::path filePath) {
vertex_shader = VertexShader("shaders/default.vert.glsl");
if (!std::filesystem::exists(filePath))
throw GeometryLoadingException(fmt::format("File {} does not exist", filePath.string().c_str()));
Assimp::Importer importer;
const aiScene* scene = importer.ReadFile(filePath.string().data(), aiProcess_GenSmoothNormals | aiProcess_Triangulate);
if (scene == nullptr || scene->mRootNode == nullptr || scene->mFlags == AI_SCENE_FLAGS_INCOMPLETE) {
throw GeometryLoadingException(fmt::format("Assimp failed to load mesh file {}", filePath.string().c_str()));
}
std::vector<Vertex> vertices;
std::vector<unsigned> indices;
std::stack<std::tuple<aiNode*, glm::mat4>> stack;
stack.push({ scene->mRootNode, assimpMatrix(scene->mRootNode->mTransformation) });
while (!stack.empty()) {
auto [node, matrix] = stack.top();
stack.pop();
matrix *= assimpMatrix(node->mTransformation);
const glm::mat3 normalMatrix = glm::inverseTranspose(glm::mat3(matrix));
for (unsigned i = 0; i < node->mNumMeshes; i++) {
// Process subMesh
const aiMesh* mesh = scene->mMeshes[node->mMeshes[i]];
if (mesh->mNumVertices == 0 || mesh->mNumFaces == 0)
std::cerr << "Empty mesh encountered" << std::endl;
// Triangles
const size_t indexOffset = vertices.size();
for (unsigned j = 0; j < mesh->mNumFaces; j++) {
const aiFace& face = mesh->mFaces[j];
if (face.mNumIndices != 3) {
std::cerr << "Found a face which is not a triangle, discarding!" << std::endl;
}
auto aiIndices = face.mIndices;
indices.push_back(static_cast<unsigned>(aiIndices[0] + indexOffset));
indices.push_back(static_cast<unsigned>(aiIndices[1] + indexOffset));
indices.push_back(static_cast<unsigned>(aiIndices[2] + indexOffset));
}
// Vertices
for (unsigned j = 0; j < mesh->mNumVertices; j++) {
const glm::vec3 pos = matrix * glm::vec4(assimpVec(mesh->mVertices[j]), 1.0f);
const glm::vec3 normal = normalMatrix * assimpVec(mesh->mNormals[j]);
glm::vec2 texCoord { 0 };
if (mesh->HasTextureCoords(0)) {
texCoord = glm::vec2(assimpVec(mesh->mTextureCoords[0][j]));
m_hasTextureCoords = true;
}
vertices.push_back(Vertex { pos, normal, texCoord });
}
}
for (unsigned i = 0; i < node->mNumChildren; i++) {
stack.push({ node->mChildren[i], matrix });
}
}
importer.FreeScene();
// Create Element(/Index) Buffer Objects and Vertex Buffer Object.
m_ibo = std::shared_ptr<GLuint>(new GLuint(), [](GLuint *p) {
glDeleteBuffers(1, p);
delete p;
});
glCreateBuffers(1, m_ibo.get());
glNamedBufferStorage(*m_ibo, static_cast<GLsizeiptr>(indices.size() * sizeof(decltype(indices)::value_type)), indices.data(), 0);
m_vbo = std::shared_ptr<GLuint>(new GLuint(), [](GLuint *p) {
glDeleteBuffers(1, p);
});
glCreateBuffers(1, m_vbo.get());
glNamedBufferStorage(*m_vbo, static_cast<GLsizeiptr>(vertices.size() * sizeof(Vertex)), vertices.data(), 0);
// Bind vertex data to shader inputs using their index (location).
// These bindings are stored in the Vertex Array Object.
m_vao = std::shared_ptr<GLuint>(new GLuint(), [](GLuint *p) {
glDeleteVertexArrays(1, p);
delete p;
});
glCreateVertexArrays(1, m_vao.get());
// The indicies (pointing to vertices) should be read from the index buffer.
glVertexArrayElementBuffer(*m_vao, *m_ibo);
// The position and normal vectors should be retrieved from the specified Vertex Buffer Object.
// The stride is the distance in bytes between vertices. We use the offset to point to the normals
// instead of the positions.
glVertexArrayVertexBuffer(*m_vao, 0, *m_vbo, offsetof(Vertex, pos), sizeof(Vertex));
glVertexArrayVertexBuffer(*m_vao, 1, *m_vbo, offsetof(Vertex, normal), sizeof(Vertex));
glVertexArrayVertexBuffer(*m_vao, 2, *m_vbo, offsetof(Vertex, texCoord), sizeof(Vertex));
glEnableVertexArrayAttrib(*m_vao, 0);
glEnableVertexArrayAttrib(*m_vao, 1);
glEnableVertexArrayAttrib(*m_vao, 2);
m_numIndices = static_cast<GLsizei>(indices.size());
}
const VertexShader& BasicGeometry::getVertexShader() const {
return vertex_shader;
}
void BasicGeometry::draw() const
{
glBindVertexArray(*m_vao);
glDrawElements(GL_TRIANGLES, m_numIndices, GL_UNSIGNED_INT, nullptr);
}
const void* BasicGeometry::getUniformData() const {
return nullptr;
}
GLsizeiptr BasicGeometry::getUniformDataSize() const {
return 0;
}
void BasicGeometry::setVertexShader(std::filesystem::path filePath)
{
vertex_shader = VertexShader(filePath);
}
static glm::mat4 assimpMatrix(const aiMatrix4x4& m)
{
//float values[3][4] = {};
glm::mat4 matrix;
matrix[0][0] = m.a1;
matrix[0][1] = m.b1;
matrix[0][2] = m.c1;
matrix[0][3] = m.d1;
matrix[1][0] = m.a2;
matrix[1][1] = m.b2;
matrix[1][2] = m.c2;
matrix[1][3] = m.d2;
matrix[2][0] = m.a3;
matrix[2][1] = m.b3;
matrix[2][2] = m.c3;
matrix[2][3] = m.d3;
matrix[3][0] = m.a4;
matrix[3][1] = m.b4;
matrix[3][2] = m.c4;
matrix[3][3] = m.d4;
return matrix;
}
static glm::vec3 assimpVec(const aiVector3D& v)
{
return glm::vec3(v.x, v.y, v.z);
}
<file_sep>/CMakeLists.txt
cmake_minimum_required(VERSION 3.14 FATAL_ERROR)
project(ComputerGraphics CXX)
# Slightly modified versions of the files from the cpp-starter-project by <NAME>:
# https://github.com/lefticus/cpp_starter_project/
include("cmake/CompilerWarnings.cmake") # Enable almost all compiler warnings and CMake option to enable -Werror.
include("cmake/Sanitizers.cmake") # CMake options to enable address, memory, UB and thread sanitizers.
include("cmake/StaticAnalyzers.cmake") # CMake options to enable clang-tidy or cpp-check.
# Use pmm to download and install (to temp directory) the vcpkg package manager.
# Then invoke vcpkg (through pmm) to install (download & compile) freeglut.
include("cmake/pmm.cmake")
pmm(VERBOSE VCPKG
REVISION acff7d4aa6e18355585ba52c1eba789c02ed3fef
REQUIRES glfw3 glew glm ms-gsl fmt stb assimp)
set(OpenGL_GL_PREFERENCE GLVND) # Prevent CMake warning about legacy fallback on Linux.
find_package(OpenGL REQUIRED)
find_package(GLEW REQUIRED)
find_package(glfw3 CONFIG REQUIRED)
find_package(glm CONFIG REQUIRED)
find_package(Microsoft.GSL CONFIG REQUIRED)
find_package(fmt CONFIG REQUIRED)
# NOTE: stb does not support find_package. Just gotta hope that CMake or the compiler picks up the header file.
find_package(assimp CONFIG REQUIRED)
set(PLATFORM_SPECIFIC_PACKAGES "")
if (UNIX)
# Some older versions of libstdc++ (like g++8) require explicit linking against std::filesystem.
# The custom Findfilesystem.cmake file located in the cmake folder was copied from:
# https://github.com/inviwo/inviwo/blob/master/cmake/modules/FindFilesystem.cmake
set(CMAKE_MODULE_PATH "${CMAKE_CURRENT_LIST_DIR}/cmake/")
find_package(filesystem REQUIRED)
# Issue with assimps CMake files (assimps fault, not vcpkg) not linking to all the required libraries.
# Seems to only affect Linux users...
find_library(ASSIMP_ZLIB_LIBRARY z)
find_library(ASSIMP_IRRXML_LIBRARY IrrXML)
set(PLATFORM_SPECIFIC_PACKAGES std::filesystem ${ASSIMP_ZLIB_LIBRARY} ${ASSIMP_IRRXML_LIBRARY})
endif()
include_directories("include/")
add_executable(FinalProject
"src/prospective_camera.cpp"
"src/application.cpp"
"src/window.cpp"
"src/stb_image.cpp"
"src/materials/solid_color_material.cpp"
"src/materials/blinn_phong_material.cpp"
"src/gl/texture.cpp"
"src/gl/shader.cpp"
"src/gl/framebuffer.cpp"
"src/gl/shader_stage.cpp"
"src/util3D/geometry.cpp"
"src/util3D/basic_geometry.cpp"
"src/util3D/animated_geometry.cpp"
"src/util3D/material.cpp"
"src/util3D/mesh.cpp"
"src/util3D/camera.cpp"
"src/util3D/transformable.cpp"
"src/util3D/animated_geometry.cpp"
"src/util3D/light.cpp"
"src/util3D/point_light.cpp"
"src/util3D/directional_light.cpp"
"src/util3D/scene.cpp"
"src/gl/cube_texture.cpp" src/materials/skybox_material.cpp src/materials/chrome_material.cpp src/materials/water_material.cpp src/materials/ground_material.cpp src/materials/toon_material.cpp)
target_compile_features(FinalProject PRIVATE cxx_std_17)
target_link_libraries(FinalProject PRIVATE
OpenGL::GL GLEW::GLEW
glfw
glm
Microsoft.GSL::GSL
assimp::assimp
fmt::fmt
${PLATFORM_SPECIFIC_PACKAGES})
enable_sanitizers(FinalProject)
set_project_warnings(FinalProject)
# Copy all files in the resources folder to the build directory after every successful build.
add_custom_command(TARGET FinalProject POST_BUILD
COMMAND ${CMAKE_COMMAND} -E copy_directory
"${CMAKE_CURRENT_LIST_DIR}/resources/" "$<TARGET_FILE_DIR:FinalProject>/resources/")
# We would like to copy the files when they changed. Even if no *.cpp files were modified (and
# thus no build is triggered). We tell CMake that the executable depends on the shader files in
# the build directory. We also tell it how to generate those files (by copying them from the
# shaders folder in this directory). The gather all glsl files in the shaders folder when CMake
# is configured. So if you were to add a shader file then you need to configure CMake again.
file(MAKE_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/shaders/")
set(shader_copies "")
file(GLOB shader_sources "${CMAKE_CURRENT_LIST_DIR}/shaders/*")
foreach (shader_file IN LISTS shader_sources)
get_filename_component(file_name ${shader_file} NAME)
message("shader_file: ${file_name}")
add_custom_command(
OUTPUT "${CMAKE_BINARY_DIR}/shaders/${file_name}"
COMMAND ${CMAKE_COMMAND} -E copy
"${CMAKE_CURRENT_LIST_DIR}/shaders/${file_name}"
"${CMAKE_BINARY_DIR}/shaders/${file_name}"
DEPENDS "${CMAKE_CURRENT_LIST_DIR}/shaders/${file_name}"
)
LIST(APPEND shader_copies "${CMAKE_BINARY_DIR}/shaders/${file_name}")
endforeach()
add_custom_target(copy_shaders DEPENDS ${shader_copies})
add_dependencies(FinalProject copy_shaders)
<file_sep>/src/util3D/geometry.cpp
#include <iostream>
#include <stack>
#include <vector>
#include "disable_all_warnings.h"
DISABLE_WARNINGS_PUSH()
#include <assimp/Importer.hpp>
#include <assimp/postprocess.h>
#include <assimp/scene.h>
#include <fmt/format.h>
#include <glm/gtc/matrix_inverse.hpp>
#include <glm/mat3x3.hpp>
#include <glm/mat4x4.hpp>
#include <glm/vec4.hpp>
#include <gsl/span>
DISABLE_WARNINGS_POP()
#include "util3D/geometry.h"
Geometry::Geometry() {
ubo = std::shared_ptr<GLuint>(new GLuint(),[](GLuint *p){
glDeleteBuffers(1,p);
delete p;
});
glCreateBuffers(1, ubo.get());
}
void Geometry::initUniformBuffer() const {
glBindBuffer(GL_UNIFORM_BUFFER, *ubo);
glBufferData(GL_UNIFORM_BUFFER, getUniformDataSize(), getUniformData(), GL_STATIC_DRAW);
glBindBuffer(GL_UNIFORM_BUFFER, 0);
}
void Geometry::updateUniformData() const {
glBindBuffer(GL_UNIFORM_BUFFER, *ubo);
glBufferSubData(GL_UNIFORM_BUFFER,
0,
getUniformDataSize(),
getUniformData());
glBindBuffer(GL_UNIFORM_BUFFER, 0);
}
void Geometry::bind() const {
glBindBufferBase(GL_UNIFORM_BUFFER, 3, *ubo);
}
<file_sep>/src/materials/ground_material.cpp
#include "materials/ground_material.h"
#include "materials/water_material.h"
#include "util3D/geometry.h"
GroundMaterial::GroundMaterial(glm::vec3 ks, float shininess, glm::vec3 kd, std::shared_ptr<Texture> _tex, std::shared_ptr<Texture> _toonTex)
{
fragment_shader = FragmentShader("shaders/ground.frag.glsl");
xray_shader = FragmentShader("shaders/xtoon.frag.glsl");
xray_cull_shader = FragmentShader("shaders/ground.frag.glsl");
ground_material_uniform.ks = ks;
ground_material_uniform.shininess = shininess;
ground_material_uniform.kd = kd;
initUniformBuffer();
texture = _tex;
toonTexture = _toonTex;
}
const FragmentShader& GroundMaterial::getFragmentShader() {
return fragment_shader;
}
const FragmentShader& GroundMaterial::getXrayCullShader() {
return xray_cull_shader;
}
const FragmentShader& GroundMaterial::getXrayShader() {
return xray_shader;
}
const void* GroundMaterial::getUniformData() const {
return static_cast<const void*>(&ground_material_uniform);
}
GLsizeiptr GroundMaterial::getUniformDataSize() const {
return sizeof(GroundMaterialUnifromData);
}
void GroundMaterial::draw(const Scene& scene, const Geometry& geometry) const {
glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); // Enable color writes.
glDepthMask(GL_FALSE); // Disable depth writes.
glDepthFunc(GL_EQUAL); // Only draw a pixel if it's depth matches the value stored in the depth buffer.
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE); // Additive blending.
for(std::shared_ptr<Light> light : scene.getLights()) {
light -> bind();
geometry.draw();
}
glDepthFunc(GL_LEQUAL);
glDepthMask(GL_TRUE);
glDisable(GL_BLEND);
}
void GroundMaterial::bind() const {
Material::bind();
texture->bind(4);
glUniform1i(4, 4);
toonTexture->bind(5);
glUniform1i(5, 5);
}
<file_sep>/include/util3D/scene.h
#pragma once
#include <map>
#include <memory>
#include "util3D/transformable.h"
#include "util3D/light.h"
#include "util3D/camera.h"
#include "util3D/mesh.h"
class Light;
class PointLight;
class DirectionalLight;
class Mesh;
class Scene: public Transformable
{
private:
std::vector<std::shared_ptr<DirectionalLight>> directional_lights;
std::vector<std::shared_ptr<Light>> lights;
std::vector<std::shared_ptr<Mesh>> meshes;
public:
Scene();
const std::vector<std::shared_ptr<Light>>& getLights() const;
const std::vector<std::shared_ptr<Mesh>>& getMeshes() const;
using Transformable::update;
void update();
friend Mesh;
friend PointLight;
friend DirectionalLight;
};<file_sep>/include/util3D/mesh.h
#pragma once
#include <memory>
#include <glm/glm.hpp>
#include "util3D/transformable.h"
#include "gl/shader.h"
class Material;
class Geometry;
typedef struct alignas(16) _WorldTransformationUniformData {
glm::mat4 world_transform;
glm::mat3x4 normal_transform;
} WorldTransformationUniformData;
class Mesh : public Transformable {
private:
WorldTransformationUniformData data;
std::unique_ptr<GLuint, std::function<void(GLuint*)>> ubo;
std::shared_ptr<Geometry> geometry;
std::shared_ptr<Material> material;
Shader shader, xray_shader;
Shader depthShader, xray_cull_shader;
public:
Mesh(const Mesh& mesh);
Mesh(const std::shared_ptr<Geometry>& _geometry,const std::shared_ptr<Material>& material);
const Geometry& getGeometry() const;
const Material& getMaterial() const;
const Shader& getShader() const;
const Shader& getDepthShader() const;
const Shader& getXrayCullShader() const;
const Shader& getXrayShader() const;
void addedToScene(Scene& _scene, std::shared_ptr<Transformable>& self) override;
void update(const glm::mat4& transform) override;
void bind() const;
};<file_sep>/src/util3D/directional_light.cpp
#include "util3D/directional_light.h"
#include "util3D/scene.h"
#include "util3D/mesh.h"
#include "util3D/geometry.h"
DirectionalLight::DirectionalLight(const glm::mat4& _projectionMatrix, const glm::vec3& _color, const glm::ivec2& _dimensions) {
projectionMatrix = _projectionMatrix;
Light::data.light_color = glm::vec4(_color, 0.5);
dimensions = _dimensions;
Light::updateUniformData();
texture = Texture(dimensions.x, dimensions.y, GL_DEPTH_COMPONENT32F);
texture.set(GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
texture.set(GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
texture.set(GL_TEXTURE_MIN_FILTER, GL_NEAREST);
texture.set(GL_TEXTURE_MAG_FILTER, GL_NEAREST);
texture.set(GL_TEXTURE_COMPARE_MODE, GL_COMPARE_REF_TO_TEXTURE);
texture.set(GL_TEXTURE_COMPARE_FUNC, GL_LEQUAL);
framebuffer = Framebuffer(texture, GL_DEPTH_ATTACHMENT);
}
void DirectionalLight::update(const glm::mat4& transform) {
Camera::update(transform);
Light::data.light_position = getWorldPosition();
Light::data.light_mvp = getProjectionMatrix() * getInverseWorldTransform();
Light::updateUniformData();
}
const glm::mat4& DirectionalLight::getProjectionMatrix() const {
return projectionMatrix;
}
void DirectionalLight::addedToScene(Scene& _scene, std::shared_ptr<Transformable>& self) {
Transformable::addedToScene(_scene, self);
std::shared_ptr<DirectionalLight> light = std::dynamic_pointer_cast<DirectionalLight>(self);
_scene.lights.push_back(light);
_scene.directional_lights.push_back(light);
}
void DirectionalLight::renderMesh(const Scene& _scene, const Mesh& mesh) const {
mesh.getDepthShader().bind();
mesh.bind();
mesh.getGeometry().bind();
mesh.getGeometry().draw();
}
void DirectionalLight::prerender() {
framebuffer.bind();
glClearDepth(1.0);
glClear(GL_DEPTH_BUFFER_BIT);
glEnable(GL_DEPTH_TEST);
glViewport(0, 0, dimensions.x, dimensions.y);
}
void DirectionalLight::postrender() {
framebuffer.unbind();
}
void DirectionalLight::bind() {
Light::bind();
texture.bind(1);
glUniform1i(3, 1);
}<file_sep>/src/materials/chrome_material.cpp
#include "materials/chrome_material.h"
#include "util3D/geometry.h"
ChromeMaterial::ChromeMaterial(std::shared_ptr<CubeTexture> _tex, std::shared_ptr<Texture> _toonTex)
{
fragment_shader = FragmentShader("shaders/chrome.frag.glsl");
xray_shader = FragmentShader("shaders/xtoon.frag.glsl");
xray_cull_shader = FragmentShader("shaders/xray.frag.glsl");
texture = _tex;
toonTexture = _toonTex;
}
const FragmentShader& ChromeMaterial::getFragmentShader() {
return fragment_shader;
}
const FragmentShader& ChromeMaterial::getXrayCullShader() {
return xray_cull_shader;
}
const FragmentShader& ChromeMaterial::getXrayShader() {
return xray_shader;
}
const void* ChromeMaterial::getUniformData() const {
return nullptr;
}
GLsizeiptr ChromeMaterial::getUniformDataSize() const {
return 0;
}
void ChromeMaterial::draw(const Scene& scene, const Geometry& geometry) const {
glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); // Enable color writes.
glDepthMask(GL_FALSE); // Disable depth writes.
glDepthFunc(GL_EQUAL); // Only draw a pixel if it's depth matches the value stored in the depth buffer.
glDisable(GL_BLEND); // Blending temporarily disabled
glBlendFunc(GL_SRC_ALPHA, GL_ONE); // Additive blending.
//for chrome we're going to ignore lights.
geometry.draw();
glDepthFunc(GL_LEQUAL);
glDepthMask(GL_TRUE);
}
void ChromeMaterial::bind() const {
Material::bind();
texture->bind(4);
glUniform1i(4, 4);
toonTexture->bind(5);
glUniform1i(5, 5);
}<file_sep>/include/icamera.h
#pragma once
#include "drawable.h"
class ICamera : public Drawable
{
public:
virtual void prerender();
void render(const Scene&);
virtual void postrender();
void draw(const Camera&, const Scene& scene, const DrawableLight &light) const;
void drawDepth(const Camera& cam, const Scene& scene) const;
virtual glm::mat4 getProjectionMatrix() const = 0;
virtual ~ICamera();
};<file_sep>/include/util3D/geometry.h
#pragma once
#include "disable_all_warnings.h"
DISABLE_WARNINGS_PUSH()
#include <GL/glew.h>
#include <glm/vec2.hpp>
#include <glm/vec3.hpp>
DISABLE_WARNINGS_POP()
#include <memory>
#include <exception>
#include <filesystem>
#include <vector>
#include "gl/shader_stage.h"
#include "util3D/geometry.h"
class Scene;
class Transformable;
class Camera;
struct GeometryLoadingException : public std::runtime_error {
using std::runtime_error::runtime_error;
};
struct Vertex {
glm::vec3 pos;
glm::vec3 normal;
glm::vec2 texCoord;
};
class Geometry {
private:
std::shared_ptr<GLuint> ubo;
public:
Geometry();
virtual const VertexShader& getVertexShader() const = 0;
// Bind VAO and call glDrawElements.
virtual void draw() const = 0;
virtual const void* getUniformData() const = 0;
virtual GLsizeiptr getUniformDataSize() const = 0;
void initUniformBuffer() const;
void updateUniformData() const;
void bind() const;
virtual ~Geometry() = default;
};
<file_sep>/src/util3D/mesh.cpp
#include <glm/gtc/matrix_inverse.hpp>
#include "util3D/mesh.h"
#include "util3D/scene.h"
#include "util3D/geometry.h"
#include "util3D/material.h"
Mesh::Mesh(const Mesh& mesh) : Transformable(mesh) {
geometry = mesh.geometry;
material = mesh.material;
shader = mesh.shader;
depthShader = mesh.depthShader;
data = mesh.data;
ubo = std::unique_ptr<GLuint, std::function<void(GLuint*)>>(new GLuint(), [](GLuint* p){
glDeleteBuffers(1, p);
delete p;
});
glCreateBuffers(1, ubo.get());
glBindBuffer(GL_UNIFORM_BUFFER, *ubo);
glBufferData(GL_UNIFORM_BUFFER, sizeof(WorldTransformationUniformData), &data, GL_DYNAMIC_DRAW);
glBindBuffer(GL_UNIFORM_BUFFER, 0);
}
Mesh::Mesh(const std::shared_ptr<Geometry>& _geometry,const std::shared_ptr<Material>& _material) {
ubo = std::unique_ptr<GLuint, std::function<void(GLuint*)>>(new GLuint(), [](GLuint* p){
glDeleteBuffers(1, p);
delete p;
});
glCreateBuffers(1, ubo.get());
glBindBuffer(GL_UNIFORM_BUFFER, *ubo);
glBufferData(GL_UNIFORM_BUFFER, sizeof(WorldTransformationUniformData), &data, GL_DYNAMIC_DRAW);
glBindBuffer(GL_UNIFORM_BUFFER, 0);
geometry = _geometry;
material = _material;
shader = Shader(geometry->getVertexShader(), material -> getFragmentShader());
depthShader = Shader(geometry->getVertexShader());
xray_cull_shader = Shader(geometry->getVertexShader(), material->getXrayCullShader());
xray_shader = Shader(geometry->getVertexShader(), material->getXrayShader());
}
const Geometry& Mesh::getGeometry() const {
return *geometry;
}
const Material& Mesh::getMaterial() const {
return *material;
}
const Shader& Mesh::getShader() const {
return shader;
}
const Shader& Mesh::getDepthShader() const {
return depthShader;
}
const Shader& Mesh::getXrayCullShader() const {
return xray_cull_shader;
}
const Shader& Mesh::getXrayShader() const {
return xray_shader;
}
void Mesh::addedToScene(Scene& _scene, std::shared_ptr<Transformable>& self) {
Transformable::addedToScene(_scene, self);
_scene.meshes.push_back(std::dynamic_pointer_cast<Mesh>(self));
}
//#include <iostream>
//#include <glm/gtx/string_cast.hpp>
void Mesh::update(const glm::mat4& transform) {
Transformable::update(transform);
data.world_transform = getWorldTransform();
data.normal_transform = glm::mat3x4(glm::inverseTranspose(glm::mat3(data.world_transform)));
//std::cout << glm::to_string(data.normal_transform) << std::endl;
glBindBuffer(GL_UNIFORM_BUFFER, *ubo);
glBufferSubData(
GL_UNIFORM_BUFFER,
0,
sizeof(WorldTransformationUniformData),
static_cast<const void*>(&data));
glBindBuffer(GL_UNIFORM_BUFFER, 0);
}
void Mesh::bind() const {
glBindBufferBase(GL_UNIFORM_BUFFER, 1, *ubo);
}<file_sep>/include/util3D/camera.h
#pragma once
#include <memory>
#include <functional>
#include <glm/glm.hpp>
#include <GL/glew.h>
#include "transformable.h"
class Mesh;
typedef struct alignas(16) _CameraUniformData {
glm::mat4 mvp;
glm::vec3 camera_position;
} CameraUniformData;
class Camera : public Transformable
{
private:
CameraUniformData data;
std::unique_ptr<GLuint, std::function<void(GLuint*)>> ubo;
public:
Camera();
virtual void prerender() = 0;
void render();
virtual void renderMesh(const Scene& scene, const Mesh& mesh) const = 0;
virtual void postrender();
virtual const glm::mat4& getProjectionMatrix() const = 0;
void update(const glm::mat4& transform) override;
void bindCamera() const;
virtual ~Camera() = default;
};<file_sep>/include/drawable.h
#pragma once
#include <stdint.h>
#include <vector>
#include <memory>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtx/euler_angles.hpp>
class Camera;
class Scene;
class DrawableLight;
class Drawable {
private:
glm::vec3 translation;
glm::vec3 rotation;
glm::vec3 scale;
void render(std::vector<bool> visited,
const glm::mat4& transform
);
protected:
std::vector<std::shared_ptr<Drawable>> children;
public:
bool has_parent;
glm::mat4 world_transform;
int index;
Drawable();
Drawable(const Drawable& drawable);
void translate(const glm::vec3& translation);
void rotate(const glm::vec3& rotation);
void scaling(const glm::vec3& scale);
virtual void setTranslation(const glm::vec3& translation);
virtual void setRotation(const glm::vec3& rotation);
virtual void setScale(const glm::vec3& scale);
glm::vec3 getTranslation() const;
glm::vec3 getRotation() const;
glm::vec3 getScale() const;
glm::vec3 getWorldPosition() const;
void add(std::shared_ptr<Drawable> child);
virtual void draw(const Camera& projection, const Scene& scene, const DrawableLight &light) const = 0;
virtual void drawDepth(const Camera &projection, const Scene &scene) const = 0;
virtual void drawShadowMap(const Scene &scene, const DrawableLight &light) const;
virtual void drawXRayCull(const Camera &camera, const Scene &scene) const;
void render(const Camera &camera, const Scene& scene, const DrawableLight &light) const;
void renderShadow(const Scene&, const DrawableLight&) const;
virtual void update(const glm::mat4& transform, Scene& scene);
glm::mat4 getTransform() const;
glm::mat4 getInverseTransform() const;
glm::mat4 getInverseWorldTransform() const;
virtual ~Drawable();
friend Camera;
void renderDepth(const Camera &camera, const Scene &scene) const;
void xRayCull(const Camera &camera, const Scene &scene) const;
};
#include "scene.h"
<file_sep>/src/application.cpp
//#include "Image.h"
#include "window.h"
// Always include window first (because it includes glfw, which includes GL which needs to be included AFTER glew).
// Can't wait for modules to fix this stuff...
#include "disable_all_warnings.h"
#include "gl/shader.h"
#include "gl/texture.h"
#include "gl/cube_texture.h"
#include "prospective_camera.h"
#include "util3D/basic_geometry.h"
#include "util3D/animated_geometry.h"
#include "util3D/scene.h"
#include "util3D/mesh.h"
#include "util3D/group.h"
#include "util3D/directional_light.h"
#include "materials/solid_color_material.h"
#include "materials/blinn_phong_material.h"
#include "materials/skybox_material.h"
#include "materials/chrome_material.h"
#include "materials/water_material.h"
#include "materials/ground_material.h"
#include "materials/toon_material.h"
DISABLE_WARNINGS_PUSH()
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_inverse.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <glm/mat4x4.hpp>
#include <glm/gtx/string_cast.hpp>
DISABLE_WARNINGS_POP()
#include <functional>
#include <iostream>
#include <vector>
#include <thread>
#include <chrono>
class Application {
private:
int terrain_toggle = 0;
Window m_window;
// Shader for default rendering and for depth rendering
enum mouse_status {MOUSE_DISABLED, MOUSE_REENABLED, MOUSE_ACTIVE};
mouse_status mouse_movement = MOUSE_DISABLED;
glm::dvec2 oldCPos;
Scene scene;
std::shared_ptr<ProspectiveCamera> camera;
std::shared_ptr<Transformable> group;
std::shared_ptr<AnimatedGeometry> skin_arachnid;
std::shared_ptr<AnimatedGeometry> sea;
std::shared_ptr<AnimatedGeometry> terrain;
std::shared_ptr<Transformable> gymbal_outer[4];
std::shared_ptr<Transformable> gymbal_mid[4];
std::shared_ptr<Transformable> gymbal_inner[4];
std::shared_ptr<Transformable> eve_group;
std::shared_ptr<Transformable> _group, rotategroup;
public:
Application()
: m_window(glm::ivec2(1024, 1024), "Final Project", false),
oldCPos(0)
{
m_window.registerKeyCallback([this](int key, int scancode, int action, int mods) {
if (action == GLFW_PRESS || action == GLFW_REPEAT)
onKeyPressed(key, mods, action);
else if (action == GLFW_RELEASE)
onKeyReleased(key, mods);
});
m_window.registerMouseMoveCallback(std::bind(&Application::onMouseMove, this, std::placeholders::_1));
m_window.registerMouseButtonCallback([this](int button, int action, int mods) {
if (action == GLFW_PRESS)
onMouseClicked(button, mods);
else if (action == GLFW_RELEASE)
onMouseReleased(button, mods);
});
std::cout << "size:" << sizeof(LightUniformData) << std::endl;
std::cout << "offset:" << offsetof(LightUniformData, light_color) << std::endl;
auto checkerboardtex = std::make_shared<Texture>("resources/textures/checkerboard.png");
auto toontex = std::make_shared<Texture>("resources/textures/toon_map.png");
auto toontex_1 = std::make_shared<Texture>("resources/textures/toon_map_blue.png");
auto toontex_2 = std::make_shared<Texture>("resources/textures/toon_map_bw.png");
auto toontex_3 = std::make_shared<Texture>("resources/textures/toon_map_carmine.png");
auto toontex_4 = std::make_shared<Texture>("resources/textures/toon_map_db.png");
auto toontex_5 = std::make_shared<Texture>("resources/textures/toon_map_grass.png");
auto toontex_6 = std::make_shared<Texture>("resources/textures/toon_map_green.png");
auto toontex_7 = std::make_shared<Texture>("resources/textures/toon_map_grun.png");
auto toontex_8 = std::make_shared<Texture>("resources/textures/toon_map_lblue.png");
auto toontex_9 = std::make_shared<Texture>("resources/textures/toon_map_red.png");
auto toontex_10 = std::make_shared<Texture>("resources/textures/toon_map_sandy.png");
auto toontex_11 = std::make_shared<Texture>("resources/textures/toon_map_sandy_b.png");
auto toontex_12 = std::make_shared<Texture>("resources/textures/toon_map_sun.png");
auto cube_tex = std::make_shared<CubeTexture>("resources/textures/skyboxes/skybox/");
auto ground_tex = std::make_shared<Texture>("resources/textures/terrain_grad_g2.png");
auto skybox_material = std::make_shared<SkyboxMaterial>(cube_tex, cube_tex);
auto box_geometry = std::make_shared<BasicGeometry>("resources/skybox.obj");
auto skybox_geometry = std::make_shared<BasicGeometry>("resources/skybox.obj");
skybox_geometry->setVertexShader("shaders/skybox.vert.glsl");
auto skybox = std::make_shared<Mesh>(skybox_geometry, skybox_material);
std::shared_ptr<Geometry> dragon_geometry = std::make_shared<BasicGeometry>("resources/dragon.obj");
// MATERIALS
std::shared_ptr<Material> solid_material = std::make_shared<SolidColorMaterial>(glm::vec3(1.0f,0.0f,0.0f));
std::shared_ptr<Material> blinn_phong_material = std::make_shared<BlinnPhongMaterial>(glm::vec3(0.5, 0.5, 0.5),
10.0f,
glm::vec3(0.8, 0.8, 0.8),
checkerboardtex,
toontex
);
std::shared_ptr<Material> blinn_phong_material_1 = std::make_shared<BlinnPhongMaterial>(glm::vec3(0.5, 0.5, 0.5),
10.0f,
glm::vec3(0.8, 0.8, 0.8),
checkerboardtex,
toontex_1
);
std::shared_ptr<Material> blinn_phong_material_2 = std::make_shared<BlinnPhongMaterial>(glm::vec3(0.5, 0.5, 0.5),
10.0f,
glm::vec3(0.8, 0.8, 0.8),
checkerboardtex,
toontex_2
);
std::shared_ptr<Material> blinn_phong_material_3 = std::make_shared<BlinnPhongMaterial>(glm::vec3(0.5, 0.5, 0.5),
10.0f,
glm::vec3(0.8, 0.8, 0.8),
checkerboardtex,
toontex_3
);
std::shared_ptr<Material> blinn_phong_material_4 = std::make_shared<BlinnPhongMaterial>(glm::vec3(0.5, 0.5, 0.5),
10.0f,
glm::vec3(0.8, 0.8, 0.8),
checkerboardtex,
toontex_4
);
std::shared_ptr<Material> blinn_phong_material_5 = std::make_shared<BlinnPhongMaterial>(glm::vec3(0.5, 0.5, 0.5),
10.0f,
glm::vec3(0.8, 0.8, 0.8),
checkerboardtex,
toontex_5
);
std::shared_ptr<Material> blinn_phong_material_6 = std::make_shared<BlinnPhongMaterial>(glm::vec3(0.5, 0.5, 0.5),
10.0f,
glm::vec3(0.8, 0.8, 0.8),
checkerboardtex,
toontex_6
);
std::shared_ptr<Material> blinn_phong_material_7 = std::make_shared<BlinnPhongMaterial>(glm::vec3(0.5, 0.5, 0.5),
10.0f,
glm::vec3(0.8, 0.8, 0.8),
checkerboardtex,
toontex_7
);
std::shared_ptr<Material> blinn_phong_material_8 = std::make_shared<BlinnPhongMaterial>(glm::vec3(0.5, 0.5, 0.5),
10.0f,
glm::vec3(0.8, 0.8, 0.8),
checkerboardtex,
toontex_8
);
std::shared_ptr<Material> blinn_phong_material_9 = std::make_shared<BlinnPhongMaterial>(glm::vec3(0.5, 0.5, 0.5),
10.0f,
glm::vec3(0.8, 0.8, 0.8),
checkerboardtex,
toontex_9
);
std::shared_ptr<Material> blinn_phong_material_10 = std::make_shared<BlinnPhongMaterial>(glm::vec3(0.5, 0.5, 0.5),
10.0f,
glm::vec3(0.8, 0.8, 0.8),
checkerboardtex,
toontex_10
);
std::shared_ptr<Material> toon_material_11 = std::make_shared<ToonMaterial>(glm::vec3(0.5, 0.5, 0.5),
10.0f,
glm::vec3(0.8, 0.8, 0.8),
toontex_11,
toontex
);
std::shared_ptr<Material> blinn_phong_material_12 = std::make_shared<BlinnPhongMaterial>(glm::vec3(0.5, 0.5, 0.5),
10.0f,
glm::vec3(0.8, 0.8, 0.8),
checkerboardtex,
toontex_12
);
std::shared_ptr<Material> arachnid_material = std::make_shared<BlinnPhongMaterial>(glm::vec3(1.0, 1.0, 1.0),
479.818576f,
glm::vec3(0.870858, 1.0, 0.988407),
checkerboardtex,
toontex
);
std::shared_ptr<Material> water_material = std::make_shared<WaterMaterial>(glm::vec3(0.976190, 0.976190, 0.976190),
900.0f,
glm::vec3(0.106332, 0.555170, 0.800000),
checkerboardtex,
toontex
);
auto ground_material = std::make_shared<GroundMaterial>(glm::vec3(0.05, 0.2, 0.0),
5.0f,
glm::vec3(0.106332, 0.555170, 0.020000),
ground_tex, toontex);
auto chrome_material = std::make_shared<ChromeMaterial>(cube_tex, toontex);
auto eve_material = std::make_shared<ToonMaterial>(glm::vec3(0.5, 0.5, 0.5),
10.0f,
glm::vec3(0.8, 0.8, 0.8)
,toontex_4, toontex);
auto post_dof = std::make_shared<Shader>(VertexShader("shaders/postfx.vert.glsl"), FragmentShader("shaders/postfxDOF.frag.glsl"));
// load eve
std::shared_ptr<Mesh> eve_head = std::make_shared<Mesh>(
std::make_shared<BasicGeometry>("resources/eve/eve_head.obj"),
eve_material
);
std::shared_ptr<Mesh> eve_arms = std::make_shared<Mesh>(
std::make_shared<BasicGeometry>("resources/eve/eve_arms.obj"),
eve_material
);
std::shared_ptr<Mesh> eve_body = std::make_shared<Mesh>(
std::make_shared<BasicGeometry>("resources/eve/eve_body.obj"),
eve_material
);
// load temple
std::shared_ptr<Mesh> temple = std::make_shared<Mesh>(
std::make_shared<BasicGeometry>("resources/temple/temple.obj"),
chrome_material
);
// load gymbal
for(int i = 0; i < 4; i++)
{
gymbal_inner[i] = std::make_shared<Mesh>(
std::make_shared<BasicGeometry>("resources/gymbal/gymbal_inner.obj"),
chrome_material
);
gymbal_mid[i] = std::make_shared<Mesh>(
std::make_shared<BasicGeometry>("resources/gymbal/gymbal_mid.obj"),
chrome_material
);
gymbal_outer[i] = std::make_shared<Mesh>(
std::make_shared<BasicGeometry>("resources/gymbal/gymbal_outer.obj"),
chrome_material
);
}
//Load skinned meshes
skin_arachnid = std::make_shared<AnimatedGeometry>("resources/skin_arachnid");
std::shared_ptr<Mesh> spidery_bub = std::make_shared<Mesh>(
skin_arachnid,
arachnid_material
);
sea = std::make_shared<AnimatedGeometry>("resources/skin_sea");
std::shared_ptr<Mesh> sea_mesh = std::make_shared<Mesh>(
sea,
water_material
);
sea_mesh->scaling(glm::vec3(2, 1, 2));
// load terrain
terrain = std::make_shared<AnimatedGeometry>("resources/terrain");
std::shared_ptr<Mesh> terrain_meshes = std::make_shared<Mesh>(
terrain,
ground_material
);
// load temple construction
// load floaters
std::shared_ptr<Mesh> floater_top = std::make_shared<Mesh>(
std::make_shared<BasicGeometry>("resources/floaters/floater_top.obj"),
blinn_phong_material
);
std::shared_ptr<Mesh> floater_mid = std::make_shared<Mesh>(
std::make_shared<BasicGeometry>("resources/floaters/floater_mid.obj"),
blinn_phong_material
);
std::shared_ptr<Mesh> floater_bottom = std::make_shared<Mesh>(
std::make_shared<BasicGeometry>("resources/floaters/floater_bottom.obj"),
blinn_phong_material
);
// SCENE SETUP
// add terrain depending on toggle // this does not currently update (need to have scene remove or make insisible?
scene.add(terrain_meshes);
scene.add(sea_mesh);
// Cameras and Lights
camera = std::make_shared<ProspectiveCamera>();
group = std::make_shared<Group>();
auto campers = glm::perspective(glm::radians(80.0f), 1.0f, 0.1f, 500.0f);
auto sun = std::make_shared<DirectionalLight>(campers, glm::vec3(1, 1, .8), glm::ivec2(1024, 1024));
auto light2 = std::make_shared<DirectionalLight>(campers, glm::vec3(.5, .5, .5), glm::ivec2(1024, 1024));
auto light = std::make_shared<DirectionalLight>(campers,glm::vec3(.5, .5, .5), glm::ivec2(1024, 1024));
auto light3 = std::make_shared<DirectionalLight>(campers,glm::vec3(.5, .5, .5), glm::ivec2(1024, 1024));
auto light4 = std::make_shared<DirectionalLight>(campers,glm::vec3(.5, .5, .5), glm::ivec2(1024, 1024));
auto light5 = std::make_shared<DirectionalLight>(campers,glm::vec3(.5, .5, .5), glm::ivec2(1024, 1024));
sun->translate(glm::vec3( 782.599548, 394.078827, 180.064880));
sun->rotate(glm::vec3(-0.445000, 0.000000, -4.965050));
scene.add(sun);
light->translate(glm::vec3( -2.088730, 113.248100 ,2.967190));
light->rotate(glm::vec3(-1.675000, 0.000000 ,-10.060158));
scene.add(light);
light2->translate(glm::vec3( -9.525551, 143.769882, 42.835293));
light2->rotate(glm::vec3(-0.725001, 0.000000, -9.725164));
scene.add(light2);
light3->translate(glm::vec3( 34.916309, 136.132141, 6.175010));
light3->rotate(glm::vec3(-0.605001, 0.000000, -7.895120));
scene.add(light3);
light4->translate(glm::vec3( -9.821439, 133.884598, -35.387333));
light4->rotate(glm::vec3(-0.530001, 0.000000, -6.095026));
scene.add(light4);
light5->translate(glm::vec3( -42.900272, 135.240005, -0.399847));
light5->rotate(glm::vec3(-0.690001, 0.000000 ,-4.745024));
scene.add(light5);
//camera -> add(light);
spidery_bub->rotate(glm::vec3(0, 0, 1.5));
spidery_bub->translate(glm::vec3(-1, -4, -4));
camera ->add(spidery_bub);
auto _subgroup = std::make_shared<Group>();
//subgroup -> add(dragon);
temple->translate(glm::vec3(0, 100, 0));
gymbal_outer[0]->add(gymbal_mid[0]);
gymbal_mid[0]->add(gymbal_inner[0]);
gymbal_outer[0]->scaling(glm::vec3(1.f));
gymbal_outer[0]->translate(glm::vec3(0, 190,0));
gymbal_outer[1]->add(gymbal_mid[1]);
gymbal_mid[1]->add(gymbal_inner[1]);
gymbal_outer[1]->scaling(glm::vec3(2.f));
gymbal_outer[1]->translate(glm::vec3(0, 70,0));
group->add(gymbal_outer[1]);
group->add(temple);
group->add(gymbal_outer[0]);
scene.add(group);
// eve loading
eve_group = std::make_shared<Group>();
eve_group->add(eve_head);
eve_group->add(eve_body);
eve_group->add(eve_arms);
eve_group->scaling(glm::vec3(4));
eve_group->rotate(glm::vec3(0, -1.5, 1.5));
eve_group->translate(glm::vec3(50, 0, 50));
rotategroup = std::make_shared<Group>();
rotategroup->add(eve_group);
rotategroup->translate(glm::vec3(0, 20, 0));
temple->add(rotategroup);
camera->add(skybox);
scene.add(camera);
camera->addPostShader(post_dof);
scene.update();
}
void update()
{
// This is your game loop
// Put your real-time logic and rendering in here
std::chrono::time_point expected_next_frame = std::chrono::system_clock::now();
std::chrono::milliseconds update_interval(int(round(1000.0f/30.0f)));
while (!m_window.shouldClose()) {
m_window.updateInput();
// animations
for(int i = 0; i < 4; i++)
{
gymbal_inner[i]->rotate(glm::vec3(0.04, 0, 0));
gymbal_mid[i]->rotate(glm::vec3(0, 0.01, 0));
gymbal_outer[i]->rotate(glm::vec3(0.01, 0, 0));
}
rotategroup->rotate(glm::vec3(0, 0,0.1));
scene.update();
camera -> render();
skin_arachnid -> updateFrame();
sea->updateFrame();
// Processes input and swaps the window buffer
m_window.swapBuffers();
std::chrono::milliseconds delta = std::chrono::duration_cast<std::chrono::milliseconds>(expected_next_frame - std::chrono::system_clock::now());
if (delta > std::chrono::milliseconds(0)) {
std::this_thread::sleep_for(delta);
expected_next_frame += update_interval;
} else {
expected_next_frame = std::chrono::system_clock::now() + update_interval;
}
}
}
// In here you can handle key presses
// key - Integer that corresponds to numbers in https://www.glfw.org/docs/latest/group__keys.html
// mods - Any modifier keys pressed, like shift or control
void onKeyPressed(int key, int mods, int action)
{
switch (key) {
case GLFW_KEY_ESCAPE:
if(action == GLFW_PRESS)
{
mouse_movement = mouse_movement == MOUSE_DISABLED ? MOUSE_REENABLED : MOUSE_DISABLED;
m_window.setMouseCapture();
}
break;
case GLFW_KEY_W:
camera -> translate(glm::orientate3(camera -> getRotation())*glm::vec3(0,0,-2));
break;
case GLFW_KEY_D:
camera -> translate(glm::orientate3(camera -> getRotation())*glm::vec3(2,0,0));
break;
case GLFW_KEY_A:
camera -> translate(glm::orientate3(camera -> getRotation())*glm::vec3(-2,0,0));
break;
case GLFW_KEY_S:
camera -> translate(glm::orientate3(camera -> getRotation())*glm::vec3(0,0,2));
break;
case GLFW_KEY_Q:
camera -> translate(glm::vec3(0,1,0));
break;
case GLFW_KEY_Z:
camera -> translate(glm::vec3(0,-1,0));
break;
case GLFW_KEY_X:
camera->toggleXRay();
break;
case GLFW_KEY_T:
terrain->updateFrame();
break;
case GLFW_KEY_P:
glm::vec3 pos = camera->getWorldPosition();
printf("%f %f %f\n", pos.x, pos.y, pos.z);
glm::vec3 rotation = camera->getRotation();
printf("%f %f %f\n", rotation.x, rotation.y, rotation.z);
}
//std::cout << "Key pressed: " << key << std::endl;
}
// In here you can handle key releases
// key - Integer that corresponds to numbers in https://www.glfw.org/docs/latest/group__keys.html
// mods - Any modifier keys pressed, like shift or control
void onKeyReleased(int key, int mods)
{
//std::cout << "Key released: " << key << std::endl;
}
// If the mouse is moved this function will be called with the x, y screen-coordinates of the mouse
void onMouseMove(const glm::dvec2& cursorPos)
{
if(mouse_movement == MOUSE_DISABLED) return;
else if(mouse_movement == MOUSE_REENABLED)
{
mouse_movement = MOUSE_ACTIVE;
oldCPos = cursorPos;
return;
}
else
{
glm::dvec2 delta = cursorPos - oldCPos;
oldCPos = cursorPos;
camera -> mouseRotate(delta.x, delta.y);
}
}
// If one of the mouse buttons is pressed this function will be called
// button - Integer that corresponds to numbers in https://www.glfw.org/docs/latest/group__buttons.html
// mods - Any modifier buttons pressed
void onMouseClicked(int button, int mods)
{
// std::cout << "Pressed mouse button: " << button << std::endl;
}
// If one of the mouse buttons is released this function will be called
// button - Integer that corresponds to numbers in https://www.glfw.org/docs/latest/group__buttons.html
// mods - Any modifier buttons pressed
void onMouseReleased(int button, int mods)
{
// std::cout << "Released mouse button: " << button << std::endl;
}
};
int main()
{
Application app;
app.update();
return 0;
}
<file_sep>/src/materials/skybox_material.cpp
//
// Created by erik on 7/1/20.
//
#include "materials/skybox_material.h"
#include "util3D/geometry.h"
SkyboxMaterial::SkyboxMaterial(std::shared_ptr<CubeTexture> _tex, std::shared_ptr<CubeTexture> _toonTex)
{
fragment_shader = FragmentShader("shaders/skybox.frag.glsl");
xray_shader = FragmentShader("shaders/skybox.frag.glsl");
xray_cull_shader = FragmentShader("shaders/skybox.frag.glsl");
initUniformBuffer();
texture = _tex;
toonTexture = _toonTex;
}
const FragmentShader& SkyboxMaterial::getFragmentShader() {
return fragment_shader;
}
const FragmentShader& SkyboxMaterial::getXrayCullShader() {
return fragment_shader;
}
const FragmentShader& SkyboxMaterial::getXrayShader() {
return xray_shader;
}
const void* SkyboxMaterial::getUniformData() const {
return nullptr;
}
GLsizeiptr SkyboxMaterial::getUniformDataSize() const {
return 0;
}
void SkyboxMaterial::draw(const Scene& scene, const Geometry& geometry) const {
glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); // Enable color writes.
glDepthFunc(GL_LEQUAL); // Only draw a pixel if it's depth matches the value stored in the depth buffer.
glDisable(GL_BLEND); // disable blending.
glDisable(GL_CULL_FACE);
geometry.draw();
glEnable(GL_CULL_FACE);
}
void SkyboxMaterial::bind() const {
Material::bind();
texture->bind(4);
glUniform1i(4, 4);
}<file_sep>/include/scene.h
#pragma once
#include <map>
#include <memory>
#include <GL/glew.h>
#include "drawable.h"
#include "group.h"
#include "shader.h"
class DrawableLight;
class Camera;
class Scene: public Drawable
{
private:
//define statics for quad, probably should make this an object later
const static int quadTriCount = 2;
constexpr static unsigned int quadTriList[] = {0, 1, 2, 2, 1, 3};
constexpr static float quadVerts[] = {-1.0, -1.0, 0, 1.0, -1.0,0, -1.0, 1.0, 0, 1.0, 1.0, 0};
//constexpr static float quadVerts[] = {-1.0, -1.0, 1.0, -1.0, -1.0, 1.0, 1.0, 1.0};
GLuint ibo, vbo, vao;
std::vector<std::shared_ptr<DrawableLight>> lightData;
GLuint framebuffers[2], depthtextures[2], colortextures[2];
int TEX_WIDTH, TEX_HEIGHT;
std::vector<std::shared_ptr<Shader>> postShaders = {};
public:
bool useXRay = true;
int samples = 0;
Scene(int, int);
const std::vector<std::shared_ptr<DrawableLight>>& getLightData() const;
void addLight(const std::shared_ptr<DrawableLight>& light);
void draw(const Camera& camera, const Scene& scene, const DrawableLight& light) const;
void drawDepth(const Camera& camera,const Scene& scene) const;
using Drawable::update;
void update();
void render(Camera& camera) const;
void toggleXRay();
void addPostShader(const std::shared_ptr<Shader> &shader);
};<file_sep>/include/drawable_mesh.h
#pragma once
#include <glm/glm.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <glm/gtx/string_cast.hpp>
#include <glm/gtc/matrix_inverse.hpp>
#include "drawable.h"
#include "mesh.h"
#include "shader.h"
#include "texture.h"
#include "drawable_light.h"
class Camera;
class DrawableMesh : public Drawable {
private:
Mesh mesh;
Shader shader;
Texture texture;
Shader vertexShader;
Shader xRayShader;
Texture xToonTex;
Shader xRayCullShader;
public:
DrawableMesh(const Mesh& _mesh, const Shader& _shader, const Shader& _vertexShader, const Texture& _texture, const Shader& xRayShader, const Texture&, const Shader&);
void draw(const Camera& camera, const Scene& scene, const DrawableLight &light) const;
void drawDepth(const Camera &camera, const Scene &scene) const;
void drawShadowMap(const Scene &scene, const DrawableLight &light) const;
void drawXRayCull(const Camera &camera, const Scene &scene) const;
};<file_sep>/src/util3D/animated_geometry.cpp
#include <iostream>
#include <stack>
#include <vector>
#include <filesystem>
#include "disable_all_warnings.h"
DISABLE_WARNINGS_PUSH()
#include <assimp/Importer.hpp>
#include <assimp/postprocess.h>
#include <assimp/scene.h>
#include <fmt/format.h>
#include <glm/gtc/matrix_inverse.hpp>
#include <glm/mat3x3.hpp>
#include <glm/mat4x4.hpp>
#include <glm/vec4.hpp>
#include <gsl/span>
DISABLE_WARNINGS_POP()
#include "util3D/animated_geometry.h"
static glm::mat4 assimpMatrix(const aiMatrix4x4& m);
static glm::vec3 assimpVec(const aiVector3D& v);
void AnimatedGeometry::load(std::filesystem::path path) {
if (!std::filesystem::exists(path))
throw GeometryLoadingException(fmt::format("File {} does not exist", path.string().c_str()));
Assimp::Importer importer;
const aiScene* scene = importer.ReadFile(path.string().data(), aiProcess_GenSmoothNormals | aiProcess_Triangulate);
if (scene == nullptr || scene->mRootNode == nullptr || scene->mFlags == AI_SCENE_FLAGS_INCOMPLETE) {
throw GeometryLoadingException(fmt::format("Assimp failed to load mesh file {}", path.string().c_str()));
}
std::vector<Vertex> vertices;
std::vector<unsigned> indices;
std::stack<std::tuple<aiNode*, glm::mat4>> stack;
stack.push({ scene->mRootNode, assimpMatrix(scene->mRootNode->mTransformation) });
while (!stack.empty()) {
auto [node, matrix] = stack.top();
stack.pop();
matrix *= assimpMatrix(node->mTransformation);
const glm::mat3 normalMatrix = glm::inverseTranspose(glm::mat3(matrix));
for (unsigned i = 0; i < node->mNumMeshes; i++) {
// Process subMesh
const aiMesh* mesh = scene->mMeshes[node->mMeshes[i]];
if (mesh->mNumVertices == 0 || mesh->mNumFaces == 0)
std::cerr << "Empty mesh encountered" << std::endl;
// Triangles
const size_t indexOffset = vertices.size();
for (unsigned j = 0; j < mesh->mNumFaces; j++) {
const aiFace& face = mesh->mFaces[j];
if (face.mNumIndices != 3) {
std::cerr << "Found a face which is not a triangle, discarding!" << std::endl;
}
auto aiIndices = face.mIndices;
indices.push_back(static_cast<unsigned>(aiIndices[0] + indexOffset));
indices.push_back(static_cast<unsigned>(aiIndices[1] + indexOffset));
indices.push_back(static_cast<unsigned>(aiIndices[2] + indexOffset));
}
// Vertices
for (unsigned j = 0; j < mesh->mNumVertices; j++) {
const glm::vec3 pos = matrix * glm::vec4(assimpVec(mesh->mVertices[j]), 1.0f);
const glm::vec3 normal = normalMatrix * assimpVec(mesh->mNormals[j]);
glm::vec2 texCoord { 0 };
if (mesh->HasTextureCoords(0)) {
texCoord = glm::vec2(assimpVec(mesh->mTextureCoords[0][j]));
m_hasTextureCoords = true;
}
vertices.push_back(Vertex { pos, normal, texCoord });
}
}
for (unsigned i = 0; i < node->mNumChildren; i++) {
stack.push({ node->mChildren[i], matrix });
}
}
importer.FreeScene();
// Create Element(/Index) Buffer Objects and Vertex Buffer Object.
m_ibo -> push_back(GLuint());
glCreateBuffers(1, &(m_ibo->back()));
glNamedBufferStorage(m_ibo->back(), static_cast<GLsizeiptr>(indices.size() * sizeof(decltype(indices)::value_type)), indices.data(), 0);
m_vbo -> push_back(GLuint());
glCreateBuffers(1, &(m_vbo->back()));
glNamedBufferStorage(m_vbo->back(), static_cast<GLsizeiptr>(vertices.size() * sizeof(Vertex)), vertices.data(), 0);
// Bind vertex data to shader inputs using their index (location).
// These bindings are stored in the Vertex Array Object.
m_vao -> push_back(GLuint());
glCreateVertexArrays(1, &(m_vao -> back()));
// The indicies (pointing to vertices) should be read from the index buffer.
glVertexArrayElementBuffer(m_vao -> back(), m_ibo -> back());
// The position and normal vectors should be retrieved from the specified Vertex Buffer Object.
// The stride is the distance in bytes between vertices. We use the offset to point to the normals
// instead of the positions.
glVertexArrayVertexBuffer(m_vao->back(), 0, m_vbo->back(), offsetof(Vertex, pos), sizeof(Vertex));
glVertexArrayVertexBuffer(m_vao->back(), 1, m_vbo->back(), offsetof(Vertex, normal), sizeof(Vertex));
glVertexArrayVertexBuffer(m_vao->back(), 2, m_vbo->back(), offsetof(Vertex, texCoord), sizeof(Vertex));
glEnableVertexArrayAttrib(m_vao->back(), 0);
glEnableVertexArrayAttrib(m_vao->back(), 1);
glEnableVertexArrayAttrib(m_vao->back(), 2);
m_numIndices.push_back(static_cast<GLsizei>(indices.size()));
}
AnimatedGeometry::AnimatedGeometry(std::filesystem::path filePath) {
vertex_shader = VertexShader("shaders/default.vert.glsl");
m_ibo = std::shared_ptr<std::vector<GLuint>>(
new std::vector<GLuint>(),
[](std::vector<GLuint>* p){
glDeleteBuffers(GLsizei(p->size()), p -> data());
delete p;
});
m_vbo = std::shared_ptr<std::vector<GLuint>>(
new std::vector<GLuint>(),
[](std::vector<GLuint>* p){
glDeleteBuffers(GLsizei(p->size()), p -> data());
delete p;
});
m_vao = std::shared_ptr<std::vector<GLuint>>(
new std::vector<GLuint>(),
[](std::vector<GLuint>* p){
glDeleteBuffers(GLsizei(p->size()), p -> data());
delete p;
});
if (!std::filesystem::exists(filePath)){
throw GeometryLoadingException(fmt::format("File {} does not exist", filePath.string().c_str()));
}
std::cout << filePath << std::endl;
std::vector<std::string> files = {};
for(auto& p: std::filesystem::directory_iterator(filePath)) {
files.push_back(p.path().string());
}
std::sort(files.begin(), files.end());
for (auto&p : files) {
std::cout << p << '\n';
load(p);
}
}
bool AnimatedGeometry::hasTextureCoords() const {
return false;
}
const VertexShader& AnimatedGeometry::getVertexShader() const {
return vertex_shader;
}
// Bind VAO and call glDrawElements.
void AnimatedGeometry::draw() const {
glBindVertexArray(m_vao->at(size_t(animation_index)));
glDrawElements(GL_TRIANGLES, m_numIndices[size_t(animation_index)], GL_UNSIGNED_INT, nullptr);
}
void AnimatedGeometry::updateFrame() {
animation_index = (animation_index + 1) % int(m_numIndices.size());
}
const void* AnimatedGeometry::getUniformData() const {
return nullptr;
}
GLsizeiptr AnimatedGeometry::getUniformDataSize() const {
return 0;
}
static glm::mat4 assimpMatrix(const aiMatrix4x4& m)
{
//float values[3][4] = {};
glm::mat4 matrix;
matrix[0][0] = m.a1;
matrix[0][1] = m.b1;
matrix[0][2] = m.c1;
matrix[0][3] = m.d1;
matrix[1][0] = m.a2;
matrix[1][1] = m.b2;
matrix[1][2] = m.c2;
matrix[1][3] = m.d2;
matrix[2][0] = m.a3;
matrix[2][1] = m.b3;
matrix[2][2] = m.c3;
matrix[2][3] = m.d3;
matrix[3][0] = m.a4;
matrix[3][1] = m.b4;
matrix[3][2] = m.c4;
matrix[3][3] = m.d4;
return matrix;
}
static glm::vec3 assimpVec(const aiVector3D& v)
{
return glm::vec3(v.x, v.y, v.z);
}<file_sep>/include/LightCamera.h
#pragma once
#include "prospective_camera.h"
#include <glm/glm.hpp>
#include <GL/glew.h>
#include <cstdio>
class LightCamera : public ProspectiveCamera
{
friend DrawableLight;
protected:
GLuint texShadow, framebuffer;
int TEX_WIDTH;
int TEX_HEIGHT;
public:
LightCamera(int, int);
glm::mat4 getProjectionMatrix() const;
GLuint getTexShadow() const;
GLuint getFramebuffer() const;
};
<file_sep>/src/gl/cube_texture.cpp
#include "gl/cube_texture.h"
#include "disable_all_warnings.h"
DISABLE_WARNINGS_PUSH()
#include <fmt/format.h>
#include <stb_image.h>
DISABLE_WARNINGS_POP()
CubeTexture::CubeTexture(std::filesystem::path filePath)
{
if (!std::filesystem::exists(filePath))
throw ImageLoadingException(fmt::format("File {} does not exist", filePath.string().c_str()));
// this gives path for folder
// Load images from disk to CPU memory.
std::string face[6] = { "right.png","left.png", "top.png","bottom.png","back.png", "front.png" };
// Create a texture on the GPU with 3 channels with 8 bits each.
m_texture = std::shared_ptr<GLuint>(new GLuint(), [](GLuint* p) {
glDeleteTextures(1, p);
delete p;
});
glCreateTextures(GL_TEXTURE_CUBE_MAP, 1, m_texture.get());
glBindTexture(GL_TEXTURE_CUBE_MAP, *m_texture);
//glTextureStorage2D(*m_texture, 1, GLRGB8, )
int width, height, channels;
for (int i = 0; i < 6; i++)
{
stbi_uc* pixels = stbi_load((filePath.string() + face[i]).c_str(), &width, &height, &channels, 3);
if (!pixels)
throw ImageLoadingException(fmt::format("Failed to load image file {}", (filePath.string() + face[i]).c_str()));
assert(width > 0 && height > 0);
glTexImage2D(
GL_TEXTURE_CUBE_MAP_POSITIVE_X + GLenum(i),
0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, pixels
);
}
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
}
void CubeTexture::bind(GLint textureSlot) const
{
glActiveTexture(GL_TEXTURE0 + GLenum(textureSlot));
glBindTexture(GL_TEXTURE_CUBE_MAP, *m_texture);
}<file_sep>/include/drawable_light.h
#pragma once
#include <glm/glm.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <GL/glew.h>
#include "drawable.h"
//#include "LightCamera.h"
class LightCamera;
class DrawableLight : public Drawable {
private:
glm::vec3 lightColor{};
std::vector<std::shared_ptr<LightCamera>> lightCamera;
public:
DrawableLight(glm::vec3 color, const glm::vec3& baseTrans);
const glm::vec3& getColor() const;
void draw(const Camera& camera, const Scene& scene, const DrawableLight &light) const;
void update(const glm::mat4& transform, Scene& scene) override;
void drawDepth(const Camera &projection, const Scene &scene) const;
GLuint getFrameBuffer() const;
GLuint getTexShadow() const;
glm::mat4 getCameraMVP() const;
int getWidth();
int getHeight();
};<file_sep>/src/materials/solid_color_material.cpp
#include "util3D/material.h"
#include "materials/solid_color_material.h"
SolidColorMaterial::SolidColorMaterial(glm::vec3 color) {
fragment_shader = FragmentShader("shaders/solid.frag.glsl");
xray_shader = FragmentShader("shaders/xtoon.frag.glsl");
xray_cull_shader = FragmentShader("shaders/xray.frag.glsl");
solid_color_material_uniform.color = color;
initUniformBuffer();
}
const FragmentShader& SolidColorMaterial::getFragmentShader() {
return fragment_shader;
}
const FragmentShader& SolidColorMaterial::getXrayCullShader() {
return xray_cull_shader;
}
const FragmentShader& SolidColorMaterial::getXrayShader() {
return xray_shader;
}
const void* SolidColorMaterial::getUniformData() const {
return static_cast<const void*>(&solid_color_material_uniform);
}
GLsizeiptr SolidColorMaterial::getUniformDataSize() const {
return sizeof(SolidColorMaterialUnifrom);
}<file_sep>/src/util3D/point_light.cpp
#include "util3D/point_light.h"
#include "util3D/scene.h"
PointLight::PointLight() : PointLight(glm::vec3(1.0, 1.0, 1.0)) {}
PointLight::PointLight(const glm::vec3& color) {
data.casts_shadow = false;
data.light_color = glm::vec4(color, 0.5);
Light::updateUniformData();
}
void PointLight::update(const glm::mat4& transform) {
Transformable::update(transform);
data.light_position = getWorldPosition();
glBufferSubData(GL_UNIFORM_BUFFER, 0, sizeof(LightUniformData), static_cast<const void*>(&data));
}
void PointLight::addedToScene(Scene& _scene, std::shared_ptr<Transformable>& self) {
Transformable::addedToScene(_scene, self);
_scene.lights.push_back(std::dynamic_pointer_cast<Light>(self));
}<file_sep>/include/camera.h
//
// Created by erik on 5/25/20.
//
#pragma once
//#include "disable_all_warnings.h"
#include<glm/glm.hpp>
#include "LightCamera.h"
class Camera : public LightCamera {
private:
double sensitivity = 0.005;
float movementMul = 0.1f;
public:
Camera(int, int);
void updateViewMatrix();
void mouseRotate(double, double);
glm::mat4 getProjectionMatrix() const;
void prerender();
int getWidth() const;
int getHeight() const ;
};<file_sep>/src/materials/blinn_phong_material.cpp
#include "materials/blinn_phong_material.h"
#include "util3D/geometry.h"
BlinnPhongMaterial::BlinnPhongMaterial(glm::vec3 ks, float shininess, glm::vec3 kd, std::shared_ptr<Texture> _tex, std::shared_ptr<Texture> _toonTex)
{
fragment_shader = FragmentShader("shaders/blinn_phong.frag.glsl");
xray_shader = FragmentShader("shaders/xtoon.frag.glsl");
xray_cull_shader = FragmentShader("shaders/xray.frag.glsl");
blinn_phong_material_uniform.ks = ks;
blinn_phong_material_uniform.shininess = shininess;
blinn_phong_material_uniform.kd = kd;
initUniformBuffer();
texture = _tex;
toonTexture = _toonTex;
}
const FragmentShader& BlinnPhongMaterial::getFragmentShader() {
return fragment_shader;
}
const FragmentShader& BlinnPhongMaterial::getXrayCullShader() {
return xray_cull_shader;
}
const FragmentShader& BlinnPhongMaterial::getXrayShader() {
return xray_shader;
}
const void* BlinnPhongMaterial::getUniformData() const {
return static_cast<const void*>(&blinn_phong_material_uniform);
}
GLsizeiptr BlinnPhongMaterial::getUniformDataSize() const {
return sizeof(BlinnPhongMaterialUnifromData);
}
void BlinnPhongMaterial::draw(const Scene& scene, const Geometry& geometry) const {
glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); // Enable color writes.
glDepthMask(GL_FALSE); // Disable depth writes.
glDepthFunc(GL_EQUAL); // Only draw a pixel if it's depth matches the value stored in the depth buffer.
glEnable(GL_BLEND); // Enable blending.
glBlendFunc(GL_SRC_ALPHA, GL_ONE); // Additive blending.
for(std::shared_ptr<Light> light : scene.getLights()) {
light -> bind();
geometry.draw();
}
glDepthFunc(GL_LEQUAL);
glDepthMask(GL_TRUE);
glDisable(GL_BLEND);
}
void BlinnPhongMaterial::bind() const {
Material::bind();
texture->bind(4);
glUniform1i(4, 4);
toonTexture->bind(5);
glUniform1i(5, 5);
}<file_sep>/src/util3D/material.cpp
#include "util3D/material.h"
#include "util3D/geometry.h"
Material::Material() {
ubo = std::shared_ptr<GLuint>(new GLuint(), [](GLuint *p){
glDeleteBuffers(1,p);
delete p;
});
glCreateBuffers(1, ubo.get());
}
void Material::initUniformBuffer() const {
glBindBuffer(GL_UNIFORM_BUFFER, *ubo);
glBufferData(GL_UNIFORM_BUFFER, getUniformDataSize(), getUniformData(), GL_STATIC_DRAW);
glBindBuffer(GL_UNIFORM_BUFFER, 0);
}
void Material::updateUniformData() const {
glBindBuffer(GL_UNIFORM_BUFFER, *ubo);
glBufferSubData(GL_UNIFORM_BUFFER,
0,
getUniformDataSize(),
getUniformData());
glBindBuffer(GL_UNIFORM_BUFFER, 0);
}
void Material::bind() const {
glBindBufferBase(GL_UNIFORM_BUFFER, 4, *ubo);
}
void Material::draw(const Scene& scene, const Geometry& geometry) const {
geometry.draw();
}<file_sep>/include/materials/skybox_material.h
#pragma once
#include "util3D/material.h"
#include "gl/shader_stage.h"
#include "gl/cube_texture.h"
class SkyboxMaterial : public Material {
private:
FragmentShader fragment_shader, xray_shader, xray_cull_shader;
std::shared_ptr<CubeTexture> texture, toonTexture;
public:
SkyboxMaterial(std::shared_ptr<CubeTexture> tex, std::shared_ptr<CubeTexture> toonTex);
const FragmentShader& getFragmentShader() override;
const FragmentShader& getXrayCullShader() override;
const FragmentShader& getXrayShader() override;
const void* getUniformData() const override;
GLsizeiptr getUniformDataSize() const override;
void draw(const Scene& scene, const Geometry& geometry) const override;
void bind() const override;
};<file_sep>/include/util3D/animated_geometry.h
#include "util3D/geometry.h"
class AnimatedGeometry :public Geometry{
private:
bool m_hasTextureCoords { false };
int animation_index = 0;
std::vector<GLsizei> m_numIndices = {};
std::shared_ptr<std::vector<GLuint>> m_ibo = nullptr;
std::shared_ptr<std::vector<GLuint>> m_vbo = nullptr;
std::shared_ptr<std::vector<GLuint>> m_vao = nullptr;
VertexShader vertex_shader;
void load(std::filesystem::path path);
public:
AnimatedGeometry() = default;
AnimatedGeometry(const AnimatedGeometry&) = default;
AnimatedGeometry(std::filesystem::path filePath);
bool hasTextureCoords() const;
const VertexShader& getVertexShader() const override;
// Bind VAO and call glDrawElements.
void draw() const;
void updateFrame();
virtual const void* getUniformData() const;
virtual GLsizeiptr getUniformDataSize() const;
virtual ~AnimatedGeometry() = default;
};
<file_sep>/include/gl/shader_stage.h
#pragma once
#include <string>
#include <sstream>
#include <filesystem>
#include <fstream>
#include <exception>
#include <fmt/format.h>
#include <GL/glew.h>
class Shader;
bool checkShaderErrors(GLuint shader);
template<GLenum SHADER_STAGE>
class ShaderStage {
std::shared_ptr<GLuint> m;
public:
ShaderStage() {
m = std::shared_ptr<GLenum>(new GLenum(), [](GLenum* p){
glDeleteShader(*p);
delete p;
});
*m = glCreateShader(SHADER_STAGE);
}
ShaderStage(const std::string& source, int i): ShaderStage() {
compile(source);
}
ShaderStage(std::filesystem::path shaderFile): ShaderStage() {
if (!std::filesystem::exists(shaderFile)) {
throw std::runtime_error(fmt::format("File {} does not exist", shaderFile.string().c_str()));
}
std::ifstream file(shaderFile, std::ios::binary);
std::stringstream buffer;
buffer << file.rdbuf();
std::string source = buffer.str();
compile(source);
}
void compile(const std::string& source) {
const char* shaderSourcePtr = source.c_str();
glShaderSource(*m, 1, &shaderSourcePtr, nullptr);
glCompileShader(*m);
if (!checkShaderErrors(*m)) {
throw std::runtime_error(fmt::format("Failed to compile shader {}", shaderSourcePtr));
}
}
GLenum getStage() {
return SHADER_STAGE;
}
friend Shader;
};
class VertexShader: public ShaderStage<GL_VERTEX_SHADER> {
using ShaderStage::ShaderStage;
};
class FragmentShader: public ShaderStage<GL_FRAGMENT_SHADER> {
using ShaderStage::ShaderStage;
};<file_sep>/src/gl/framebuffer.cpp
#include "gl/framebuffer.h"
FramebufferBindGuard::FramebufferBindGuard(GLuint m)
{
glBindFramebuffer(GL_FRAMEBUFFER, m);
}
FramebufferBindGuard::operator bool() const
{
return true;
}
FramebufferBindGuard::~FramebufferBindGuard()
{
glBindFramebuffer(GL_FRAMEBUFFER, 0);
}
Framebuffer::Framebuffer(const Texture& texture, GLenum attachment)
{
m_framebuffer = std::shared_ptr<GLuint>(new GLuint(),[](GLuint *p){
glDeleteFramebuffers(1, p);
delete p;
});
glCreateFramebuffers(1, m_framebuffer.get());
glNamedFramebufferTexture(*m_framebuffer, attachment, *(texture.m_texture), 0);
}
void Framebuffer::addAttachment(const Texture& texture, GLenum attachment)
{
glNamedFramebufferTexture(*m_framebuffer, attachment, *(texture.m_texture), 0);
}
void Framebuffer::bind() const
{
glBindFramebuffer(GL_FRAMEBUFFER, *m_framebuffer);
}
void Framebuffer::unbind() const
{
glBindFramebuffer(GL_FRAMEBUFFER, 0);
}
FramebufferBindGuard Framebuffer::bindGuard() const
{
return FramebufferBindGuard(*m_framebuffer);
}<file_sep>/src/util3D/camera.cpp
#include <memory>
#include <exception>
#include <stdexcept>
#include "util3D/camera.h"
#include "util3D/scene.h"
Camera::Camera() {
ubo = std::unique_ptr<GLuint, std::function<void(GLuint*)>>(new GLuint(), [](GLuint* p){
glDeleteBuffers(1, p);
delete p;
});
glCreateBuffers(1, ubo.get());
glBindBuffer(GL_UNIFORM_BUFFER, *ubo);
glBufferData(GL_UNIFORM_BUFFER, sizeof(CameraUniformData), NULL, GL_DYNAMIC_DRAW);
glBindBuffer(GL_UNIFORM_BUFFER, 0);
}
void Camera::render() {
prerender();
bindCamera();
const Scene& _scene = getScene();
for (const std::shared_ptr<Mesh> mesh : _scene.getMeshes()) {
renderMesh(_scene, *mesh);
}
postrender();
}
void Camera::update(const glm::mat4& transform) {
Transformable::update(transform);
data.mvp = getProjectionMatrix() * getInverseWorldTransform();
data.camera_position = getWorldPosition();
glBindBuffer(GL_UNIFORM_BUFFER, *ubo);
glBufferSubData(
GL_UNIFORM_BUFFER,
0,
sizeof(CameraUniformData),
static_cast<const void*>(&data));
glBindBuffer(GL_UNIFORM_BUFFER, 0);
}
void Camera::postrender(){}
void Camera::bindCamera() const {
glBindBufferBase(GL_UNIFORM_BUFFER, 0, *ubo);
}<file_sep>/include/util3D/directional_light.h
#include <glm/glm.hpp>
#include "gl/texture.h"
#include "gl/framebuffer.h"
#include "util3D/light.h"
#include "util3D/camera.h"
#include "util3D/transformable.h"
class DirectionalLight : public Light, public Camera {
private:
Texture texture;
Framebuffer framebuffer;
glm::mat4 projectionMatrix;
glm::ivec2 dimensions;
public:
DirectionalLight(const glm::mat4& _projectionMatrix, const glm::vec3& color, const glm::ivec2& _dimensions);
void update(const glm::mat4& transform) override;
const glm::mat4& getProjectionMatrix() const override;
void addedToScene(Scene& _scene, std::shared_ptr<Transformable>& self) override;
void renderMesh(const Scene& scene, const Mesh& mesh) const override;
void prerender() override;
void postrender() override;
void bind() override;
};<file_sep>/src/gl/shader.cpp
#include "gl/shader.h"
#include "disable_all_warnings.h"
#include <cassert>
DISABLE_WARNINGS_PUSH()
#include <fmt/format.h>
DISABLE_WARNINGS_POP()
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <glm/glm.hpp>
#include <glm/gtc/type_ptr.hpp>
#include "gl/shader_stage.h"
Shader::Shader()
{
program = std::shared_ptr<GLuint>(new GLuint(), [](GLuint *p) {
glDeleteProgram(*p);
delete p;
});
*program = glCreateProgram();
}
Shader::Shader(const VertexShader& vs, const FragmentShader& fs) : Shader() {
glAttachShader(*program, *(vs.m));
glAttachShader(*program, *(fs.m));
glLinkProgram(*program);
std::cerr << int(*program) << std::endl;
if (!checkProgramErrors(*program)) {
throw ShaderLoadingException("Shader program failed to link");
}
}
Shader::Shader(const VertexShader& vs) : Shader() {
glAttachShader(*program, *(vs.m));
glLinkProgram(*program);
std::cerr << int(*program) << std::endl;
if (!checkProgramErrors(*program)) {
throw ShaderLoadingException("Shader program failed to link");
}
}
Shader::Shader(std::shared_ptr<GLuint> _program)
: program(_program)
{
}
std::string parseSource();
void Shader::loadSource(const std::string& source, GLenum shaderStage) const {
GLuint shader = glCreateShader(shaderStage);
const char* shaderSourcePtr = source.c_str();
glShaderSource(shader, 1, &shaderSourcePtr, nullptr);
glCompileShader(shader);
if (!checkShaderErrors(shader)) {
throw ShaderLoadingException(fmt::format("Failed to compile shader {}", shaderSourcePtr));
}
glAttachShader(*program, shader);
glDeleteShader(shader);
}
void Shader::bind() const
{
glUseProgram(*program);
}
template<>
void Shader::loadUniform(GLint index, float data) const {
glUniform1f(index, data);
}
template<>
void Shader::loadUniform(GLint index, int data) const {
glUniform1i(index, data);
}
template<>
void Shader::loadUniform(GLint index, const glm::vec3& data) const {
glUniform3fv(index, 1, glm::value_ptr(data));
}
template<>
void Shader::loadUniform(GLint index, const glm::mat3& data) const {
glUniformMatrix3fv(index, 1, GL_FALSE, glm::value_ptr(data));
}
template<>
void Shader::loadUniform(GLint index, const glm::mat4& data) const {
glUniformMatrix4fv(index, 1, GL_FALSE, glm::value_ptr(data));
}
bool checkProgramErrors(GLuint program)
{
// Check if the program linked successfully
GLint linkSuccessful;
glGetProgramiv(program, GL_LINK_STATUS, &linkSuccessful);
// If it didn't, then read and print the link log
if (!linkSuccessful) {
GLint logLength;
glGetProgramiv(program, GL_INFO_LOG_LENGTH, &logLength);
std::string logBuffer;
logBuffer.resize(static_cast<size_t>(logLength));
glGetProgramInfoLog(program, logLength, nullptr, logBuffer.data());
std::cerr << logBuffer << std::endl;
return false;
} else {
return true;
}
}
std::string readFile(std::filesystem::path filePath)
{
std::ifstream file(filePath, std::ios::binary);
std::stringstream buffer;
buffer << file.rdbuf();
return buffer.str();
}
<file_sep>/include/util3D/transformable.h
#pragma once
#include <stdint.h>
#include <vector>
#include <memory>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtx/euler_angles.hpp>
class Scene;
class Transformable {
private:
glm::vec3 translation;
glm::vec3 rotation;
glm::quat quaternion;
glm::vec3 scale;
Scene* scene;
void updateRotation();
void updateQuaternion();
protected:
std::vector<std::shared_ptr<Transformable>> children;
glm::mat4 world_transform;
public:
Transformable();
Transformable(const Transformable& drawable);
void translate(const glm::vec3& translation);
void rotate(const glm::vec3& rotation);
void scaling(const glm::vec3& scale);
virtual void setTranslation(const glm::vec3& translation);
virtual void setRotation(const glm::vec3& rotation);
virtual void setQuaternion(const glm::quat& quaternion);
virtual void setScale(const glm::vec3& scale);
glm::vec3 getTranslation() const;
glm::vec3 getRotation() const;
glm::quat getQuaternion() const;
glm::vec3 getScale() const;
glm::vec3 getWorldPosition() const;
void add(std::shared_ptr<Transformable> child);
virtual void update(const glm::mat4& transform);
glm::mat4 getTransform() const;
glm::mat4 getInverseTransform() const;
const glm::mat4& getWorldTransform() const;
glm::mat4 getInverseWorldTransform() const;
const Scene& getScene() const;
virtual void addedToScene(Scene& _scene, std::shared_ptr<Transformable>& self);
virtual ~Transformable();
friend Scene;
};
<file_sep>/include/disable_all_warnings.h
#pragma once
// External libraries are usually not perfect (especially older ones) so they may generate
// many compile warnings when we use a high warning level on our own code. With these macros
// we disable compiler warnings between the DISABLE_WARNINGS_PUSH() and DISABLE_WARNINGS_POP
// functions.
#if defined(__clang__)
#define CLANG 1
#elif defined(__GNUC__)
#define GCC 1
#elif defined(_MSC_VER)
#define MSVC 1
#endif
#if defined(CLANG)
#define DISABLE_WARNINGS_PUSH() _Pragma("clang diagnostic push") _Pragma("clang diagnostic ignored \"-Wunused-function\"")
#define DISABLE_WARNINGS_POP() _Pragma("clang diagnostic pop")
#elif defined(GCC)
#define DISABLE_WARNINGS_PUSH()
#define DISABLE_WARNINGS_POP()
#elif defined(MSVC)
#define DISABLE_WARNINGS_PUSH() __pragma(warning(push, 0)) __pragma(warning())
#define DISABLE_WARNINGS_POP() __pragma(warning(pop))
#else
#define DISABLE_WARNINGS_PUSH()
#define DISABLE_WARNINGS_POP()
#endif<file_sep>/include/gl/framebuffer.h
#pragma once
#include <memory>
#include "disable_all_warnings.h"
DISABLE_WARNINGS_PUSH()
#include <GL/glew.h>
DISABLE_WARNINGS_POP()
#include "texture.h"
class Framebuffer;
class FramebufferBindGuard
{
private:
FramebufferBindGuard(const FramebufferBindGuard&) = delete;
FramebufferBindGuard(GLuint m);
public:
operator bool() const;
~FramebufferBindGuard();
friend Framebuffer;
};
class Framebuffer
{
private:
std::shared_ptr<GLuint> m_framebuffer = nullptr;
public:
Framebuffer() = default;
Framebuffer(const Texture& texture, GLenum attachment);
void addAttachment(const Texture&, GLenum);
void bind() const;
void unbind() const;
FramebufferBindGuard bindGuard() const;
};<file_sep>/src/prospective_camera.cpp
//
// Created by erik on 5/25/20.
//
#include <iostream>
#include <glm/glm.hpp>
#include <glm/gtx/euler_angles.hpp>
#include <GL/glew.h>
#include <glm/glm.hpp>
#include <glm/gtc/type_ptr.hpp>
#include "prospective_camera.h"
#include "util3D/mesh.h"
#include "util3D/material.h"
#include "materials/skybox_material.h"
#include "util3D/geometry.h"
ProspectiveCamera::ProspectiveCamera() : quad("resources/quad.obj")
{
prospectiveMatrix = glm::perspective(glm::radians(80.0f), 1.0f, 0.1f, 500.0f);
//generate depthmap for framebuffer
for (int i = 0; i < 2; i++)
{
depthTexture[i] = Texture(1024, 1024, GL_DEPTH_COMPONENT32F);
depthTexture[i].set(GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
depthTexture[i].set(GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
depthTexture[i].set(GL_TEXTURE_MIN_FILTER, GL_NEAREST);
depthTexture[i].set(GL_TEXTURE_MAG_FILTER, GL_NEAREST);
depthTexture[i].set(GL_TEXTURE_COMPARE_MODE, GL_COMPARE_REF_TO_TEXTURE);
depthTexture[i].set(GL_TEXTURE_COMPARE_FUNC, GL_LEQUAL);
framebuffer[i] = Framebuffer(depthTexture[i], GL_DEPTH_ATTACHMENT);
//generate color portion of framebuffer
colorTexture[i] = Texture(1024, 1024, GL_RGBA8);
colorTexture[i].set(GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
colorTexture[i].set(GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
colorTexture[i].set(GL_TEXTURE_MIN_FILTER, GL_NEAREST);
colorTexture[i].set(GL_TEXTURE_MAG_FILTER, GL_NEAREST);
framebuffer[i].addAttachment(colorTexture[i], GL_COLOR_ATTACHMENT0);
}
}
void ProspectiveCamera::mouseRotate(double degx, double degy)
{
rotate(glm::vec3(-sensitivity*degy , 0 ,-sensitivity*degx));
}
void ProspectiveCamera::prerender() {
//clear all buffers we're going to use
clearAllBuffers();
glViewport(0, 0, 1024, 1024);
framebuffer[targetBuffer].bind();
glEnable(GL_DEPTH_TEST);
glDepthMask(GL_TRUE);
glDepthFunc(GL_LEQUAL);
glColorMask(GL_FALSE,GL_FALSE, GL_FALSE, GL_FALSE);
glEnable(GL_CULL_FACE);
glCullFace(GL_BACK);
bindCamera();
const Scene& _scene = getScene();
for(const std::shared_ptr<Mesh> mesh : _scene.getMeshes()) {
mesh -> getDepthShader().bind();
mesh -> bind();
mesh -> getGeometry().bind();
mesh -> getGeometry().draw();
}
if (useXRay)
{
flipBuffers();
framebuffer[targetBuffer].bind();
for (const std::shared_ptr<Mesh> mesh : _scene.getMeshes()) {
mesh->getXrayCullShader().bind();
mesh->bind();
mesh->getGeometry().bind();
depthTexture[sourceBuffer].bind(1);
glUniform1i(3, 1);
mesh->getGeometry().draw();
}
}
glViewport(0, 0, 1024, 1024);
}
void ProspectiveCamera::renderMesh(const Scene& _scene, const Mesh& mesh) const
{
if (useXRay)
{
mesh.getXrayShader().bind();
}
else mesh.getShader().bind();
mesh.bind();
mesh.getGeometry().bind();
mesh.getMaterial().bind();
mesh.getMaterial().draw(_scene, mesh.getGeometry());
}
const glm::mat4& ProspectiveCamera::getProjectionMatrix() const
{
return prospectiveMatrix;
}
void ProspectiveCamera::postrender() {
//From this point on we will render some quads in screen space so we don't want any culling or depth tests to occur
glDisable(GL_CULL_FACE);
glDisable(GL_DEPTH_TEST);
glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
glDepthMask(GL_TRUE);
glDisable(GL_BLEND);
unsigned int i = 0;
for(; i < postFxShaders.size()-1; i++)
{
flipBuffers();
framebuffer[targetBuffer].bind();
colorTexture[sourceBuffer].bind(1);
depthTexture[sourceBuffer].bind(2);
postFxShaders[i]->bind();
quad.bind();
glUniform1i(0, 1);
glUniform1i(2, 2);
glUniform2fv(1, 1, glm::value_ptr(glm::vec2(1024, 1024)));
quad.draw();
}
//special case to draw directly to framebuffer
glBindFramebuffer(GL_FRAMEBUFFER, 0);
flipBuffers();
colorTexture[sourceBuffer].bind(1);
depthTexture[sourceBuffer].bind(2);
postFxShaders[i]->bind();
quad.bind();
glUniform1i(0, 1);
glUniform1i(2, 2);
glUniform2fv(1, 1, glm::value_ptr(glm::vec2(1024, 1024)));
quad.draw();
}
void ProspectiveCamera::addPostShader(std::shared_ptr<Shader> shader)
{
postFxShaders.push_back(shader);
}
void ProspectiveCamera::flipBuffers()
{
//flip the target and source
targetBuffer ^= 1UL << 0;
sourceBuffer ^= 1UL << 0;
}
void ProspectiveCamera::clearAllBuffers()
{
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glClearColor(0.f, 0.f, 0.f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
for (Framebuffer buf : framebuffer) {
buf.bind();
glClearColor(0.f, 0.f, 0.f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
}
}
void ProspectiveCamera::toggleXRay()
{
useXRay = !useXRay;
}<file_sep>/include/gl/shader.h
#pragma once
#include "disable_all_warnings.h"
DISABLE_WARNINGS_PUSH()
#include <GL/glew.h>
#include <glm/mat3x3.hpp>
#include <glm/mat4x4.hpp>
#include <glm/vec2.hpp>
#include <glm/vec3.hpp>
#include <glm/vec4.hpp>
#include <fmt/format.h>
DISABLE_WARNINGS_POP()
#include <exception>
#include <filesystem>
#include <vector>
#include <iostream>
#include <fstream>
bool checkShaderErrors(GLuint shader);
bool checkProgramErrors(GLuint program);
std::string readFile(std::filesystem::path filePath);
struct ShaderLoadingException : public std::runtime_error {
using std::runtime_error::runtime_error;
};
class VertexShader;
class FragmentShader;
class Shader {
private:
Shader(std::shared_ptr<GLuint> program);
public:
std::shared_ptr<GLuint> program;
Shader();
Shader(const VertexShader& vs, const FragmentShader& fs);
Shader(const VertexShader& vs);
void loadSource(const std::string& source, GLenum shaderType) const;
void load() const {}
template<class ...Args>
void load(std::filesystem::path shaderFile, Args... args) const {
if (!std::filesystem::exists(shaderFile)) {
throw ShaderLoadingException(fmt::format("File {} does not exist", shaderFile.string().c_str()));
}
GLuint shaderStage;
if (shaderFile.filename().string().find(".vert")!= std::string::npos) {
shaderStage = GL_VERTEX_SHADER;
} else if (shaderFile.filename().string().find(".geom")!= std::string::npos) {
shaderStage = GL_GEOMETRY_SHADER;
} else if (shaderFile.filename().string().find(".frag")!= std::string::npos) {
shaderStage = GL_FRAGMENT_SHADER;
} else if (shaderFile.filename().string().find(".comp")!= std::string::npos) {
shaderStage = GL_COMPUTE_SHADER;
} else {
throw ShaderLoadingException(fmt::format("Shader file should contain estension \".vert\" \".geom\" \".frag\" or \".comp\""));
}
const std::string shaderSource = readFile(shaderFile);
loadSource(shaderSource, shaderStage);
load(args...);
}
template<class ...Args>
Shader(Args... args) : Shader() {
load(args...);
glLinkProgram(*program);
if (!checkProgramErrors(*program)) {
throw ShaderLoadingException("Shader program failed to link");
}
}
void bind() const;
template<class T>
void loadUniform(GLint, T data) const;
};<file_sep>/include/util3D/material.h
#pragma once
#include <functional>
#include <GL/glew.h>
#include "util3D/scene.h"
#include "util3D/transformable.h"
#include "util3D/camera.h"
#include "gl/texture.h"
class Camera;
class Shader;
class Material {
private:
std::shared_ptr<GLuint> ubo;
public:
Material();
virtual const FragmentShader& getFragmentShader() = 0;
virtual const FragmentShader& getXrayCullShader() = 0;
virtual const FragmentShader& getXrayShader() = 0;
virtual const void* getUniformData() const = 0;
virtual GLsizeiptr getUniformDataSize() const = 0;
void initUniformBuffer() const;
void updateUniformData() const;
virtual void bind() const;
virtual void draw(const Scene& scene, const Geometry& geometry) const;
virtual ~Material() = default;
};<file_sep>/include/util3D/group.h
#pragma once
#include <glm/glm.hpp>
#include "util3D/transformable.h"
class Camera;
class Group : public Transformable {};<file_sep>/src/gl/texture.cpp
#include "gl/texture.h"
#include "disable_all_warnings.h"
DISABLE_WARNINGS_PUSH()
#include <fmt/format.h>
#include <stb_image.h>
DISABLE_WARNINGS_POP()
Texture::Texture(std::filesystem::path filePath)
{
if (!std::filesystem::exists(filePath))
throw ImageLoadingException(fmt::format("File {} does not exist", filePath.string().c_str()));
// Load image from disk to CPU memory.
int width, height, channels;
stbi_uc* pixels = stbi_load(filePath.string().c_str(), &width, &height, &channels, 3);
if (!pixels)
throw ImageLoadingException(fmt::format("Failed to load image file {}", filePath.string().c_str()));
assert(width > 0 && height > 0);
// Create a texture on the GPU with 3 channels with 8 bits each.
m_texture = std::shared_ptr<GLuint>(new GLuint(),[](GLuint *p){
glDeleteTextures(1, p);
delete p;
});
glCreateTextures(GL_TEXTURE_2D, 1, m_texture.get());
glTextureStorage2D(*m_texture, 1, GL_RGB8, width, height);
// Upload pixels into the GPU texture.
glTextureSubImage2D(*m_texture, 0, 0, 0, width, height, GL_RGB, GL_UNSIGNED_BYTE, pixels);
// Set behaviour for when texture coordinates are outside the [0, 1] range.
glTextureParameteri(*m_texture, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTextureParameteri(*m_texture, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
// Set interpolation for texture sampling (GL_NEAREST for no interpolation).
glTextureParameteri(*m_texture, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTextureParameteri(*m_texture, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
}
Texture::Texture(GLsizei width, GLsizei height, GLenum internalFormat)
{
// Create a texture on the GPU with 3 channels with 8 bits each.
m_texture = std::shared_ptr<GLuint>(new GLuint(),[](GLuint *p){
glDeleteTextures(1, p);
delete p;
});
glCreateTextures(GL_TEXTURE_2D, 1, m_texture.get());
glTextureStorage2D(*m_texture, 1, internalFormat, width, height);
// Set behaviour for when texture coordinates are outside the [0, 1] range.
glTextureParameteri(*m_texture, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTextureParameteri(*m_texture, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
// Set interpolation for texture sampling (GL_NEAREST for no interpolation).
glTextureParameteri(*m_texture, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTextureParameteri(*m_texture, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
}
void Texture::set(GLenum parameter, GLint setting)
{
glTextureParameteri(*m_texture, parameter, setting);
}
void Texture::bind(GLint textureSlot) const
{
glActiveTexture(GL_TEXTURE0 + GLenum(textureSlot));
glBindTexture(GL_TEXTURE_2D, *m_texture);
}
<file_sep>/include/util3D/point_light.h
#include "util3D/light.h"
#include "util3D/transformable.h"
class PointLight : public Light, public Transformable {
public:
PointLight();
PointLight(const glm::vec3& color);
void update(const glm::mat4& transform) override;
void addedToScene(Scene& _scene, std::shared_ptr<Transformable>& self) override;
};<file_sep>/src/util3D/scene.cpp
#include "util3D/scene.h"
#include "util3D/camera.h"
#include "util3D/light.h"
#include "util3D/directional_light.h"
#include "prospective_camera.h"
Scene::Scene()
{
scene = this;
lights = {};
meshes = {};
}
const std::vector<std::shared_ptr<Light>>& Scene::getLights() const {
return lights;
}
const std::vector<std::shared_ptr<Mesh>>& Scene::getMeshes() const {
return meshes;
}
void Scene::update() {
Transformable::update(getTransform());
for(const std::shared_ptr<DirectionalLight>& light : directional_lights) {
light->render();
}
}<file_sep>/include/group.h
#pragma once
#include "drawable.h"
#include <glm/glm.hpp>
class Group : public Drawable
{
public:
void draw(const Camera&, const Scene& scene, const DrawableLight &light) const;
void drawDepth(const Camera &projection, const Scene &scene) const;
};<file_sep>/src/util3D/transformable.cpp
#include <iostream>
#include <queue>
#include <glm/gtx/string_cast.hpp>
#include "util3D/transformable.h"
#include "util3D/scene.h"
Transformable::Transformable() : scene(nullptr), children()
{
this -> world_transform = glm::mat4(1.0f);
this -> translation = glm::vec3(0,0,0);
this -> rotation = glm::vec3(0,0,0);
this -> scale = glm::vec3(1,1,1);
}
Transformable::Transformable(const Transformable& transformable) : scene(nullptr), children()
{
this -> world_transform = transformable.world_transform;
this -> translation = transformable.translation;
this -> rotation = transformable.rotation;
this -> scale = transformable.scale;
}
void Transformable::updateRotation() {
rotation = glm::eulerAngles(quaternion);
}
void Transformable::updateQuaternion() {
quaternion = glm::quat(rotation);
}
void Transformable::rotate(const glm::vec3& _rotation)
{
rotation += _rotation;
updateQuaternion();
}
void Transformable::translate(const glm::vec3& _translation)
{
this->translation += _translation;
}
void Transformable::scaling(const glm::vec3& _scale)
{
this->scale *= _scale;
}
void Transformable::setTranslation(const glm::vec3& _translation)
{
this->translation = _translation;
}
void Transformable::setRotation(const glm::vec3& _rotation)
{
this->rotation = _rotation;
updateQuaternion();
}
void Transformable::setQuaternion(const glm::quat& _quaternion) {
quaternion = _quaternion;
updateRotation();
}
void Transformable::setScale(const glm::vec3& _scale)
{
this->scale = _scale;
}
glm::vec3 Transformable::getTranslation() const
{
return this->translation;
}
glm::vec3 Transformable::getRotation() const
{
return this->rotation;
}
glm::vec3 Transformable::getScale() const
{
return this->scale;
}
void Transformable::update(const glm::mat4& transform) {
this -> world_transform = transform*this->getTransform();
for (std::shared_ptr<Transformable> &child: this->children)
{
child->update(this -> world_transform);
}
}
glm::mat4 Transformable::getTransform() const
{
return
glm::translate(glm::mat4(1.0f), this->translation)*
glm::orientate4(this->rotation)*
glm::scale(glm::mat4(1.0f), this->scale);
}
glm::vec3 Transformable::getWorldPosition() const
{
glm::vec4 pos = this -> world_transform * glm::vec4(0.0f, 0.0f, 0.0f, 1.0f);
glm::vec3 res = glm::vec3(pos.x/pos.w, pos.y/pos.w, pos.z/pos.w);
return res;
}
glm::mat4 Transformable::getInverseTransform() const
{
return glm::inverse(getTransform());
}
const glm::mat4& Transformable::getWorldTransform() const {
return world_transform;
}
glm::mat4 Transformable::getInverseWorldTransform() const
{
return glm::inverse(world_transform);
}
void Transformable::add(std::shared_ptr<Transformable> child)
{
if (child -> scene)
{
throw std::logic_error("Transformable already has parent");
}
else
{
children.push_back(child);
if(scene)
{
child -> addedToScene(*scene, child);
}
}
}
void Transformable::addedToScene(Scene& _scene, std::shared_ptr<Transformable>& self)
{
scene = &_scene;
for (std::shared_ptr<Transformable> child : children)
{
child -> addedToScene(_scene, child);
}
}
const Scene& Transformable::getScene() const
{
return *scene;
}
Transformable::~Transformable() {}
<file_sep>/src/gl/shader_stage.cpp
#include "gl/shader.h"
#include "gl/shader_stage.h"
bool checkShaderErrors(GLuint shader)
{
// Check if the shader compiled successfully.
GLint compileSuccessful;
glGetShaderiv(shader, GL_COMPILE_STATUS, &compileSuccessful);
// If it didn't, then read and print the compile log.
if (!compileSuccessful) {
GLint logLength;
glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &logLength);
std::string logBuffer;
logBuffer.resize(static_cast<size_t>(logLength));
glGetShaderInfoLog(shader, logLength, nullptr, logBuffer.data());
std::cerr << logBuffer << std::endl;
return false;
} else {
return true;
}
}<file_sep>/include/materials/solid_color_material.h
#include <glm/glm.hpp>
#include "gl/shader_stage.h"
#include "util3D/material.h"
class FragmentShader;
typedef struct alignas(16) _SolidColorMaterialUnifrom{
glm::vec3 color;
} SolidColorMaterialUnifrom;
class SolidColorMaterial : public Material {
private:
FragmentShader fragment_shader, xray_shader, xray_cull_shader;
SolidColorMaterialUnifrom solid_color_material_uniform;
public:
SolidColorMaterial(glm::vec3 color);
const FragmentShader& getFragmentShader() override;
const FragmentShader& getXrayCullShader() override;
const FragmentShader& getXrayShader() override;
const void* getUniformData() const override;
GLsizeiptr getUniformDataSize() const override;
};
|
d4d8ffb0642e925b379bfeaeacb3f1653cee04d7
|
[
"C",
"CMake",
"C++"
] | 53
|
C++
|
Ryudas/CG-OpenGL-Demo
|
3f11460237bb425d015ae4c566e7fd38ace1b2c3
|
ded40d9a248fcd7808a120b918829c54624c925b
|
refs/heads/master
|
<file_sep>/*------------------------------------------------------------------*-
Port.H (v1.00)
------------------------------------------------------------------
'Port Header' (see Chap 10) for the project S_DELAY (see Chap 11)
COPYRIGHT
---------
This code is from the book:
PATTERNS FOR TIME-TRIGGERED EMBEDDED SYSTEMS by <NAME>
[Pearson Education, 2001; ISBN: 0-201-33138-1].
This code is copyright (c) 2001 by <NAME>.
See book for copyright details and other information.
-*------------------------------------------------------------------*/
// ------ LED_Flas.C -----------------------------------------------
#define TIMER_0_BASE TT_TIMER_1_BASE
#define TIMER_0_IRQ TT_TIMER_1_IRQ
#define TIMER_0_FREQ TT_TIMER_1_FREQ
#define LED_BASE (TT_LEDS_BASE)
#define LED0_pin (0x01 << 0)
#define LED1_pin (0x01 << 1)
#define LED2_pin (0x01 << 2)
#define LED3_pin (0x01 << 3)
#define KEY_BASE (TT_PB_1_BASE)
/*------------------------------------------------------------------*-
---- END OF FILE -------------------------------------------------
-*------------------------------------------------------------------*/
<file_sep>package eMarket.controller;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
import eMarket.domain.Product;
public class ProductValidator implements Validator {
public boolean supports(Class<?> clazz) {
return Product.class.equals(clazz);
}
@Override
public void validate(Object target, Errors errors) {
Product dto = (Product) target;
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name", "", "Field cannot be empty.");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "price", "", "Field cannot be empty.");
if ((dto.getPrice() != null) && (dto.getPrice() < 0)) {
errors.rejectValue("price", "", "Price cannot be negative.");
}
}
}
<file_sep>package eMarket.domain;
import javax.persistence.*;
//import javax.persistence.Column;
//import javax.persistence.Entity;
//import javax.persistence.GeneratedValue;
//import javax.persistence.GenerationType;
//import javax.persistence.Id;
//import javax.persistence.Transient;
@Entity(name="users")
public class UserInfo {
@Id
@GeneratedValue(strategy=GenerationType.TABLE)
@Column(name="id", nullable=false, length=11)
int id;
@Column(name="login", nullable=false, unique=true)
String login;
@Column(name="password", nullable=false)
String password;
//@Column(name="password2", nullable=false)
//why is there a password 2?
@Transient
String password2;
@Column(name="forenames", nullable=true)
String forenames;
@Column(name="lastnames", nullable=true)
String lastnames;
@Transient
String userType;
@Column(name="enabled", nullable=false, length=11)
private int enabled = 1;
//@Column(name="role", referencedColumnName="id" nullable=true, length=11)
@Transient
private Role role;
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = <PASSWORD>;
}
public String getPassword2() {
return password2;
}
public void setPassword2(String password2) {
this.password2 = password2;
}
public String getForenames() {
return forenames;
}
public void setForenames(String forenames) {
this.forenames = forenames;
}
public String getLastnames() {
return lastnames;
}
public void setLastnames(String lastnames) {
this.lastnames = lastnames;
}
public String getUserType() {
return userType;
}
public void setUserType(String userType) {
this.userType = userType;
}
public int isEnabled() {
return enabled;
}
public void setEnabled(int enabled) {
this.enabled = enabled;
}
public Role getRole() {
return role;
}
public void setRole(Role role) {
this.role = role;
}
@Override
public String toString() {
return "UserInfo [login=" + login + ", password=" + <PASSWORD> + ", password2=" + <PASSWORD> + ", forenames="
+ forenames + ", lastnames=" + lastnames + ", userType=" + userType + ", role=" + role + "]";
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getEnabled() {
return enabled;
}
}
<file_sep>## CO4105
### C++ Assignments
Assignment 2 & 3
<file_sep>#include "joystick_controller.h"
//function initialising the joystick
void Joystick_Init(void)
{
joystick_init();
}
//function which controls the joystick
void Joystick_Update(void)
{
/*setting up a variable which is assigned the function joystick_read
this function returns the status of the joystick, i.e. the position of the joystick*/
uint8_t joy = joystick_read();
//if the joystick is pressed in the centre
if (joy & JOYSTICK_CENTER)
{
/*this line is included to ensure that when the joystick is pressed in the centre
the turning on/off of the blue LED is visible
otherwise the next few lines of code are executed continuously and very quickly when
the joystick is pressed*/
while(joystick_read() & JOYSTICK_CENTER);
/*if the blue LED is OFF then the blue LED is turned ON
however, if the blue LED is ON then it is turned OFF*/
if(blue_state == 0)
{
blue_state = RGB_BLUE;
}
else
blue_state = 0;
}
//if the joystick is pushed upwards
if (joy & JOYSTICK_UP)
{
//and if the green LED duty cycle is greater than 0% then it is decremented by 10%
if (green_DC > 0)
{
green_DC--;
}
}
//if the joystick is pushed downwards
if (joy & JOYSTICK_DOWN)
{
//and if the green LED duty cycle is less than 100% then it is incremented by 10%
if (green_DC < 9)
{
green_DC++;
}
}
//if the joystick is pushed left
if (joy & JOYSTICK_LEFT)
{
//and if the red LED duty cycle is less than 100% then it is incremented by 10%
if (red_DC < 9)
{
red_DC++;
}
}
//if the joystick is pushed right
if (joy & JOYSTICK_RIGHT)
{
//and if the red LED duty cycle is greater than 0% then it is decremented by 10%
if (red_DC > 0)
{
red_DC--;
}
}
}
<file_sep>/*
* rgb_led.h
*
* Created on: 20 March 2018
* Author: nt161
*/
#ifndef TASKS_RGB_LED_HEADER_
#define TASKS_RGB_LED_HEADER_
#include "lpc_types.h"
#include "rgb.h"
#include "../adc/adc.h"
// ------ Public function prototypes -------------------------------
void rgb_led_init(void);
void rgb_update(void);
#endif /* TASKS_RGB_LED_HEADER_ */
<file_sep>#include "Staff.h"
Staff::Staff(const string& staffInfo)
{
istringstream staffStream(staffInfo);
staffStream >> staff_id;
staffStream >> load;
}
Staff::~Staff() {
}
string Staff::getStaffID() const{
return staff_id;
}
int Staff::getLoad() const {
return load;
}
void Staff::reduceLoad() {
load--;
}<file_sep>#include "LPC17xx.h"
#include "lpc_types.h"
#include "rgb.h"
#include "timer.h"
#include "lpc17xx_pinsel.h"
#include "lpc17xx_gpio.h"
#include "lpc17xx_ssp.h"
#include "led7seg.h"
int main (void)
{
// The work is being done in the timer interrupt service routine.
// All the main function does is initialise the RGB LED and
// the timer, and then go into an infinite loop.
//uint8_t state = 0;
//uint8_t ch = '0';
PINSEL_CFG_Type PinCfg;
SSP_CFG_Type SSP_ConfigStruct;
/*
* Initialize SPI pin connect
* P0.7 - SCK;
* P0.8 - MISO
* P0.9 - MOSI
* P2.2 - SSEL - used as GPIO
*/
PinCfg.Funcnum = 2;
PinCfg.OpenDrain = 0;
PinCfg.Pinmode = 0;
PinCfg.Portnum = 0;
PinCfg.Pinnum = 7;
PINSEL_ConfigPin(&PinCfg);
PinCfg.Pinnum = 8;
PINSEL_ConfigPin(&PinCfg);
PinCfg.Pinnum = 9;
PINSEL_ConfigPin(&PinCfg);
PinCfg.Funcnum = 0;
PinCfg.Portnum = 2;
PinCfg.Pinnum = 2;
PINSEL_ConfigPin(&PinCfg);
SSP_ConfigStructInit(&SSP_ConfigStruct);
// Initialize SSP peripheral with parameter given in structure above
SSP_Init(LPC_SSP1, &SSP_ConfigStruct);
// Enable SSP peripheral
SSP_Cmd(LPC_SSP1, ENABLE);
rgb_init();
timer0_init();
//rotary_init();
led7seg_init();
timer1_init();
//led7seg_setChar('A', FALSE);
while(1)
{
}
}
void check_failed(uint8_t *file, uint32_t line)
{
/* User can add his own implementation to report the file name and line number,
ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
/* Infinite loop */
while(1);
}
<file_sep>package eMarket.domain;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Transient;
@Entity(name="users")
public class UserInfo {
@Id
@GeneratedValue(strategy=GenerationType.TABLE)
int id;
@Column(unique=true, nullable=false)
String login;
@Column(unique=true, nullable=false)
String password;
@Transient
String password2;
String forenames;
String lastnames;
@Transient
String userType;
@Column(nullable=false)
private int enabled = 1;
@ManyToOne(fetch=FetchType.LAZY, cascade=CascadeType.ALL)
@JoinColumn(name="role", referencedColumnName="id")
private Role role;
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getPassword2() {
return password2;
}
public void setPassword2(String password2) {
this.password2 = password2;
}
public String getForenames() {
return forenames;
}
public void setForenames(String forenames) {
this.forenames = forenames;
}
public String getLastnames() {
return lastnames;
}
public void setLastnames(String lastnames) {
this.lastnames = lastnames;
}
public String getUserType() {
return userType;
}
public void setUserType(String userType) {
this.userType = userType;
}
public int isEnabled() {
return enabled;
}
public void setEnabled(int enabled) {
this.enabled = enabled;
}
public Role getRole() {
return role;
}
public void setRole(Role role) {
this.role = role;
}
@Override
public String toString() {
return "UserInfo [login=" + login + ", password=" + <PASSWORD> + ", <PASSWORD>=" + <PASSWORD> + ", forenames="
+ forenames + ", lastnames=" + lastnames + ", userType=" + userType + ", role=" + role + "]";
}
}
<file_sep>package CO3090.assignment2;
public enum FileItemType {
DIR,
FILE,
UNKNOWN
}<file_sep># Software-Work
Assignments Done Over The Course of Degree
<file_sep>/*------------------------------------------------------------------*-
Port.H (v1.00)
------------------------------------------------------------------
'Port Header' (see Chap 10) for the project S_DELAY (see Chap 11)
COPYRIGHT
---------
This code is from the book:
PATTERNS FOR TIME-TRIGGERED EMBEDDED SYSTEMS by <NAME>
[Pearson Education, 2001; ISBN: 0-201-33138-1].
This code is copyright (c) 2001 by <NAME>.
See book for copyright details and other information.
-*------------------------------------------------------------------*/
// ------ LED_Flas.C -----------------------------------------------
#ifndef _PORT_H
#define _PORT_H
// Connect LED from GND to this pin, via appropriate resistor
// [see Chapter 7 for details]
#define LED_BASE1 (ET_LEDS1_BASE)
#define LED_BASE2 (ET_LEDS2_BASE)
#define LED0_pin (0x01 << 0)
#define LED1_pin (0x01 << 1)
#define KEY0_BASE (ET_PB_1_BASE)
#define KEY1_BASE (ET_PB_2_BASE)
#define TEST0_PORT PIO_0_BASE
#define TEST0_pin (0x01 << 0)
#define MCP2551_int_n (ET_SPICAN_INT_BASE) // 1-bit Input
/*------------------------------------------------------------------*-
---- END OF FILE -------------------------------------------------
-*------------------------------------------------------------------*/
#endif
<file_sep>//Arduino Ohm Meter with Push Button
//The resistance of the resistor that we are measuring is referred to as the unknown resistor.
int led = 5;//setting the pin that will be used for the LED.
void setup(){
Serial.begin(9600); //Sets the data rate in bits per second.
pinMode(led, OUTPUT); //Sets the digital pin 5 as output.
}
void loop(){
float v_unknown = analogRead(A1);//when the push button is pressed the voltage across the unknown resistor is read and stored in the v_unknown variable. (The push button is merely a switch in my voltage divider circuit).
float v_value = (v_unknown/1023.0) * 5.0; //equation to convert the voltage (from a value between 0 to 1023) across the unknown resistor into a voltage between 0 and 5 volts. The corresponding value is saved to the v_value variable.
float current = (5-v_value)/10000; //equation to calculate the value of the current flowing through the circuit (in my circuit the resistor that will not be changed is the 10 kilo-ohm resistor hence the voltage has been divided by 10000), again the value is stored in the variable named current.
float resistance = (v_value/current);//equation to calculate unknown resistance, and this value will be stored in the variable named resistance.
//this part of the code will only be executed if the value of the voltage across the unknown resistor is greater than 0.05 volts.
if (v_value > 0.05) //This has been done to ensure that values are not displayed if a small current flows through the circuit.
{
Serial.println("Voltage across unknown resistor in Volts is: ");
Serial.println(v_value); //displays the voltage across the unknown resistor on the serial monitor
Serial.println("Resistance of unknown resistor in Ohms is: ");
Serial.println(resistance); //displays the resistance of unknown resistor on the serial monitor
for (int i=0; i<255; i++) //this for loop increments i from 1 to 255, in this loop this increases the brightness of the LED from 0 (minimum value) to 255 (maximum value) which is connected to pin 5 (which allows pulse width modulation).
{
analogWrite(led, i); //waits for 5 milliseconds when increasing the brightness, this enables the LED to gradually increase in brightness.
delay(5);
}
}
else //if the value of the voltage across the unknown resistor is less than 0.05 volts then the LED will not turn on (value is set to LOW).
{
digitalWrite(led, LOW);
}
delay(750);//waits for 0.75 seconds when displaying the voltage and resistance values on the serial monitor, this enables the user to read the values.
//if there was no delay then the values of the resistor and voltage would rapidly be displayed on the screen, leading to difficulty in reading them.
}
<file_sep>#pragma once
#include <string>
#include <sstream>
using namespace std;
class Staff{
public:
Staff(const string& staffInfo);
~Staff();
string getStaffID() const;
int getLoad() const;
void reduceLoad();
private:
string staff_id = "";
int load = -1;
};<file_sep>#ifndef RGB_UPDATE_HEADER
#define RGB_UPDATE_HEADER
#include "lpc_types.h"
#include "rgb.h"
extern uint8_t red_DC;
extern uint8_t green_DC;
extern uint8_t blue_state;
void RGB_Init(void);
void Update_Red(void);
void Update_Green(void);
void Update_Blue(void);
void On_Colour(uint8_t colour);
void Off_Colour(uint8_t colour);
#endif
<file_sep># Makefile
# the C++ compiler
CXX = g++
CC = $(CXX)
# options to pass to the compiler
CXXFLAGS = -Wall -ansi -O2 -g
adding : adding.o
$(CXX) $(CXXFLAGS) -o adding adding.o
adding.o : adding.cpp
$(CXX) $(CXXFLAGS) -c adding.cpp
.PHONY : clean
clean :
$(RM) adding adding.o *~
<file_sep>#! /bin/bash
#dirs= ls -R $1
#dirs=$@
#for dir in $dirs
#do
#echo "Directory: $dir"
#echo "Directories and files edited by $USERNAME in the last 48 hours"
#find $dirs -maxdepth 1 -mindepth 1 -type d -mtime -2 -printf 'Directory Owner: %u Directory Name: %f\n'
#find $dirs -maxdepth 1 -mindepth 1 -type f -mtime -2 -printf 'Directory Owner: %u File Name: %f\n'
#echo "Directories and files not owned by $USER in the last 48 hours"
#find $dirs -maxdepth 1 -mindepth 1 ! -uid "$(id -u)" -type d -mtime -2 -printf 'Directory Owner: %u Directory Name: %f\n'
#find $dirs -maxdepth 1 -mindepth 1 ! -user $USER -type d -mtime -2 -printf 'Directory Owner: %u Directory Name: %f\n'
#done
#!/bin/bash
dirs=$@
u=$USER
echo $u
for dir in $dirs ; do
if [ -n "$(find . -user "$username" -print -prune -o -prune)" ]; then
echo "The current directory is owned by $username."
echo "Directory: $dir"
find $dirs -maxdepth 1 -type d -mtime -2 -printf '%u %f\n'
fi
if [ -n "$(find . -user "$(id -u)" -print -prune -o -prune)" ]; then
echo "The current directory is owned by the current user."
echo "Directory: $dir"
find $dirs -maxdepth 1 -type d -mtime -2 -printf '%u %f\n'
fi
#if [$USER = '%u']
#then
#echo "Directory: $dir"
#find $dirs -maxdepth 1 -type d -mtime -2 -printf '%u %f\n'
#fi
done
<file_sep>/*
* seven_seg.c
*
* Created on: 20 March 2018
* Author: nt161
*/
#include "seven_seg.h"
// setting up a counter (which is used as a delay) to ensure the
// channel number is displayed for a second on the LED
int counter = 0;
// initialising the seven segment LED display
void seven_seg_init(void)
{
PINSEL_CFG_Type PinCfg;
SSP_CFG_Type SSP_ConfigStruct;
/*
* Initialize SPI pin connect
* P0.7 - SCK;
* P0.8 - MISO
* P0.9 - MOSI
* P2.2 - SSEL - used as GPIO
*/
PinCfg.Funcnum = 2;
PinCfg.OpenDrain = 0;
PinCfg.Pinmode = 0;
PinCfg.Portnum = 0;
PinCfg.Pinnum = 7;
PINSEL_ConfigPin(&PinCfg);
PinCfg.Pinnum = 8;
PINSEL_ConfigPin(&PinCfg);
PinCfg.Pinnum = 9;
PINSEL_ConfigPin(&PinCfg);
PinCfg.Funcnum = 0;
PinCfg.Portnum = 2;
PinCfg.Pinnum = 2;
PINSEL_ConfigPin(&PinCfg);
SSP_ConfigStructInit(&SSP_ConfigStruct);
// Initialize SSP peripheral with parameter given in structure above
SSP_Init(LPC_SSP1, &SSP_ConfigStruct);
// Enable SSP peripheral
SSP_Cmd(LPC_SSP1, ENABLE);
led7seg_init();
}
// if the counter is less than 10
// and if the rate of change of an ADC channel is less than -0.01 or greater than 0.01
// then the channel number is displayed on the seven segment LED
// and the counter is increased
// else the seven segment display is cleared and the counter is reset
void seven_seg_update(void)
{
if(counter < 10){
if(adc0_change_rate < -0.01 || adc0_change_rate > 0.01)
{
led7seg_setChar('0', FALSE);
}
else if(adc1_change_rate < -0.01 || adc1_change_rate > 0.01)
{
led7seg_setChar('1', FALSE);
}
else if(adc2_change_rate < -0.01|| adc2_change_rate > 0.01)
{
led7seg_setChar('2', FALSE);
}
counter++;
}
else
{
led7seg_setChar(' ', FALSE);
counter = 0;
}
}
<file_sep>SHELL:=/bin/bash
# bash will read this config file first
BASH_ENV=bash_env.sh
export BASH_ENV
all:
$(MAKE) clean
mkdir -p bin # no error if already exists
javac -d bin $$javac_cp $$java_files
$(MAKE) run_test
junit_runner:=org.junit.runner.JUnitCore
test:=Test_lab7
run_test:
cp test_bin/$(test).class bin # put the test class in the bin dir
java $$java_cp $(junit_runner) $(test) # run junit, and execute test
handin.zip:
zip -r handin.zip FEEDBACK_MACHINE
clean:
rm -rf bin/* handin.zip
# ignore ------------------------------------------------------------
test_bin: FORCE
javac -d test_bin $$javac_cp src/*.java test/*.java
rm test_bin/CC07.class
# as part of run_test we copy the test class into bin
FORCE:
<file_sep>/**
* (C) <NAME>, 2016
*/
package app.controller;
import javax.validation.Valid;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import app.domain.UserInfo;
import app.domain.UserType;
@Controller
@RequestMapping("/")
public class SignupController {
@InitBinder
protected void initBinder(WebDataBinder binder) {
binder.addValidators(new UserInfoValidator());
}
@RequestMapping(value = "/signup", method = RequestMethod.GET)
public String signup(@ModelAttribute("userInfo") UserInfo userInfo, Model model) {
model.addAttribute("userTypeValues",UserType.values());
return "Signup";
}
@RequestMapping(value="add", params = "add", method = RequestMethod.POST)
public String addNewUser(@Valid @ModelAttribute("userInfo") UserInfo userInfo, BindingResult result, Model model) {
if (result.hasErrors()) {
model.addAttribute("userTypeValues",UserType.values());
return "Signup";
} else {
return "redirect:login/";
}
}
@RequestMapping(value="add", params = "cancel", method = RequestMethod.POST)
public String cancelNewUser(@ModelAttribute("userInfo") UserInfo userInfo, Model model) {
return "redirect:login/";
}
}
<file_sep>/*------------------------------------------------------------------*-
main.h (2014-09-17)
------------------------------------------------------------------
Demonstration for time-trigger architecture on LPC1769.
This code should purely be used in training and teaching purposes for
for MSc Reliable Embedded Systems programme.
This code is copyright (c) University of Leicester 2014.
-*------------------------------------------------------------------*/
#ifndef _MAIN_H
#define _MAIN_H 1
#include "LPC17xx.h"
#include "lpc_types.h"
//#include <cr_section_macros.h>
//#include <NXP/crp.h>
// Required system operating frequency (in Hz)
// Will be checked in the scheduler initialisation file
#define Required_SystemCoreClock (100000000)
//------------------------------------------------------------------
// SHOULD NOT GENERALLY NEED TO EDIT THE SECTIONS BELOW
//------------------------------------------------------------------
#define RETURN_NORMAL 0
#define RETURN_ERROR 1
#endif
/*------------------------------------------------------------------*-
---- END OF FILE -------------------------------------------------
-*------------------------------------------------------------------*/
<file_sep>package CO3090.assignment2.server;
import java.awt.List;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Vector;
import CO3090.assignment2.FileItem;
import CO3090.assignment2.FileItemType;
public class FileUtility {
final static String fileSystemPath="./filesystems/";
public static Vector<FileItem> fileSearch(String fileName, Vector<FileItem> files){
Vector<FileItem> list_of_files = new Vector<FileItem>();
for(FileItem file : files){
if(file.getName().equals(fileName)){
list_of_files.add(file);
}
}
return list_of_files;
}
public static void main(String[] args){
Vector<String> fsIndex=readDistributedFilesystemList();
// for(String filesystem: fsIndex){
// for(FileItem f: readFS(fileSystemPath+filesystem)){
// System.out.println(fsIndex+" ->" +f);
// }
// }
/*FILE SEARCH*/
// StringBuilder json = new StringBuilder(); //list is the contents of the file system
// json.append("{\n\"list\": [{\n");
//
// for (String fileSystem : fsIndex){ //getting the file system names
//
// Vector<FileItem> files = readFS(fileSystemPath+fileSystem);
// Vector<FileItem> foundFiles = fileSearch("hello.txt",files);
// for(FileItem file : foundFiles){
// json.append("\"fs\" : " + "\"" + fileSystem + "\", \n");
// FileItem parentDir = file;
// String pathname = file.getName();
// while(parentDir.getParentDirectoryName() != null){
// String parentDirName = parentDir.getParentDirectoryName();
// parentDir = fileSearch(parentDirName, files).get(0);
// System.out.println("parent directory: "+parentDir);
// pathname = (parentDirName != null)?(parentDirName+ "/" + pathname):("");
// }
// pathname = "\"//" + pathname;
// json.append("\"path\" : " + pathname + "\"\n},\n");
// json.append("{\n");
// }
//
// }
// json.delete(json.length()-4, json.length());
// json.append("\n]\n}");
//
// System.out.println(json.toString());
/*MAX DEPTH SEARCH*/
// StringBuilder json = new StringBuilder();
// Vector<Integer> depth = new Vector<Integer>();
// json.append("{\n\"list\": [{\n");
// for (String fileSystem : fsIndex){ //getting the file system names
// json.append("\"fs\" : " + "\"" + fileSystem + "\", \n");
// Vector<FileItem> files = readFS(fileSystemPath+fileSystem);
// for(FileItem file : files){
// FileItem parentDir = file;
// int i = 1;
// while(parentDir.getParentDirectoryName() != null){
// parentDir = fileSearch(parentDir.getParentDirectoryName(), files).get(0);
// i = i+1;
// }
// depth.add(i);
// }
// int maxDepth = Collections.max(depth).intValue();
// json.append("\"depth\" : \"" + maxDepth + "\"\n},\n");
// json.append("{\n");
// }
//
// json.delete(json.length()-4, json.length());
// json.append("\n]\n}");
// //System.out.println(depth.toString());
// System.out.println(json.toString());
// }
/*TREE SEARCH*/
// HashMap<Integer, String> tree = new HashMap<Integer, String>();
// StringBuilder json = new StringBuilder();
//
// for (String fileSystem : fsIndex){ //getting the file system names
// StringBuilder sb = new StringBuilder();
// Vector<Integer> depth = new Vector<Integer>();
// json.append("\"fs\" : " + "\"" + fileSystem + "\", \n");
// Vector<FileItem> files = readFS(fileSystemPath+fileSystem);
// for (FileItem file: files){
// FileItem parentDir = file;
// int position = 0;
// int level = 1;
// if(parentDir.getParentDirectoryName() == null){
// System.out.println("file name = " + parentDir.getName());
// sb.append(parentDir.getName() + "{");
// position = sb.length()-1;
// System.out.println("last index = " + position);
// System.out.println("parentdir null = " + sb.toString());
// }
// else
// while(parentDir.getParentDirectoryName() != null){
// System.out.println("file is = " + parentDir.getName());
// if(!sb.toString().contains(parentDir.getName())){
// sb.append(parentDir.getName());
// position = sb.length()-1;
// System.out.println("parentdir !null = " + sb.toString());
// System.out.println("last index = " + position);
// }
//// else if(sb.toString().contains(parentDir.getName())){
//// }
// parentDir = fileSearch(parentDir.getParentDirectoryName(), files).get(0);
// //level++;
// for(int i = 1; i<depth.size(); i++){
// if(depth.get(i-1) < depth.get(i)){
//
// }
// else if(depth.get(i-1) > depth.get(i)){
//
// }
// else
// sb.append(",");
// i++;
// }
// level++;
//// if(sb.toString().contains(parentDir.getName()))
//// sb.append(parentDir.getName() + ".");
//// }
//
// //System.out.println(parentDir.toString());
// depth.add(level);
// }
// System.out.println(depth.toString());
// //System.out.println(json.toString());
// System.out.println(sb.toString());
// }
// }
}
/**
* @return return a list of files located in ./filesystems/.
*/
public static Vector<String> readDistributedFilesystemList(){
File[] files = new File(fileSystemPath).listFiles();
Vector<String> list=new Vector<String>();
for (File fsIndexFile : files) {
if (fsIndexFile.isFile()) {
list.add(fsIndexFile.getName());
}
}
return list;
}
/**
* @param txt file storing directory information
* @return return FileItem objects from the file provided.
*/
public static Vector<FileItem> readFS(String filename){
Vector<FileItem> map =new Vector<FileItem>();
try{
FileInputStream fstream = new FileInputStream(filename);
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null) {
if(!strLine.trim().startsWith("#") && !strLine.trim().equals("")){
String[] array=strLine.split(",");
String fitype=array[0];
String name=array[1];
String parent=array[2];
FileItemType type=FileItemType.UNKNOWN;
if(fitype!=null){
if(fitype.equals("FILE")){
type=FileItemType.FILE;
}else if(fitype.equals("DIR")){
type=FileItemType.DIR;
}else{
type=FileItemType.UNKNOWN;
}
}
if(parent.equals("?")){
parent=null;
}
FileItem f= new FileItem(name,type,parent);
map.add(f);
}
}
in.close();
}catch(Exception ex){
ex.printStackTrace();
}
return map;
}
}
<file_sep>package eMarket.controller;
import java.time.LocalDate;
import org.springframework.format.annotation.DateTimeFormat;
import eMarket.EMarketApp;
public class IndexFormDto {
@DateTimeFormat(pattern="dd/MM/yyyy")
private LocalDate date = EMarketApp.getSystemDate();
public LocalDate getDate() {
return date;
}
public void setDate(LocalDate date) {
this.date = date;
}
}
<file_sep>buildscript {
ext {
springBootVersion = '1.5.6.RELEASE'
}
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
classpath("org.springframework:springloaded:1.2.7.RELEASE")
}
}
apply plugin: 'groovy'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
repositories {
mavenCentral()
}
eclipse {
project {
buildCommand 'org.eclipse.jdt.core.javabuilder'
buildCommand 'org.eclipse.buildship.core.gradleprojectbuilder'
buildCommand 'org.springframework.ide.eclipse.core.springbuilder'
buildCommand 'org.eclipse.wst.common.project.facet.core.builder'
natures 'org.eclipse.jdt.core.javanature',
'org.eclipse.jdt.groovy.core.groovyNature',
'org.eclipse.buildship.core.gradleprojectnature',
'org.springframework.ide.eclipse.core.springnature',
'org.eclipse.wst.common.project.facet.core.nature'
}
}
task wrapper(type: Wrapper) {
gradleVersion = '4.1'
}
// tag::versions[]
ext {
jasperVersion = '9.0.0.M26'
lombokVersion = '1.16.18'
groovyVersion = '2.4.4'
}
// end::versions[]
dependencies {
// Spring Boot
compile("org.springframework.boot:spring-boot-starter-web:${springBootVersion}")
compile("org.springframework.boot:spring-boot-devtools")
// JSP
compile("org.apache.tomcat.embed:tomcat-embed-jasper:$jasperVersion")
compile("javax.servlet:jstl:1.2")
// Lombok
// compile("org.projectlombok:lombok:$lombokVersion")
// Bootstrap
compile("org.webjars:bootstrap:3.3.7")
}
///////////////////////////////////////////////////////////////////////////////
// PROJECT SPECIFIC
///////////////////////////////////////////////////////////////////////////////
// name of the jar to be generated
jar {
baseName = 'miniproject'
version = 'sprint2.17-18'
}
// name of the Eclipse project
eclipse.project.name = 'miniproject'
<file_sep>/*------------------------------------------------------------------*-
LED_flas.C (v1.00)
------------------------------------------------------------------
Simple 'Flash LED' test function.
COPYRIGHT
---------
This code is from the book:
PATTERNS FOR TIME-TRIGGERED EMBEDDED SYSTEMS by <NAME>
[Pearson Education, 2001; ISBN: 0-201-33138-1].
This code is copyright (c) 2001 by <NAME>.
See book for copyright details and other information.
-*------------------------------------------------------------------*/
//#include <altera_avalon_performance_counter.h>
#include <altera_avalon_pio_regs.h>
#include "../ET_TTC_Scheduler/Main.h"
#include "../ET_TTC_Scheduler/Port.h"
#include <stdio.h>
#include <string.h>
#include "sys/alt_alarm.h"
#include "system.h"
#include "nios2.h"
#include "altera_avalon_mutex.h"
#include "altera_avalon_mutex_regs.h"
#include "SharedMem_Mutex.h"
extern tByte Tick_message_data_G[4];
#define MESSAGE_WAITING 1
#define NO_MESSAGE 0
#define LOCK_SUCCESS 0
#define LOCK_FAIL 1
#define MESSAGE_BUFFER_BASE MSG_BUF_RAM_BASE
// Pointer to our mutex device
alt_mutex_dev* mutex; // = NULL;
// Message buffer structure
typedef struct {
tByte flag;
tByte buf[10];
} message_buffer_struct;
// Local variables
tWord id;
tWord cpu_id;
message_buffer_struct *message;
/*------------------------------------------------------------------*-
SharedMem_Init()
- See below.
-*------------------------------------------------------------------*/
void SharedMem_Init(void)
{
// Get the CPU ID
cpu_id = ALT_CPU_CPU_ID_VALUE;
// Initialise the message buffer location
message = (message_buffer_struct*)MESSAGE_BUFFER_BASE;
//creates a new pointer to a struct
//creates the pointer at the location message_buffer_base -- added these comments
// Open the real mutex to share a message buffer which is shared by TT_Core and ET_Core.
mutex = altera_avalon_mutex_open(MSG_BUF_MUTEX_NAME);
}
/*------------------------------------------------------------------*-
SharedMem_Update()
Flashes an LED (or pulses a buzzer, etc) on a specified port pin.
Must call at twice the required flash rate: thus, for 1 Hz
flash (on for 0.5 seconds, off for 0.5 seconds) must schedule
at 2 Hz.
-*------------------------------------------------------------------*/
void SharedMem_Update(void)
{
// Try and acquire the mutex (non-blocking).
if(altera_avalon_mutex_trylock(mutex, cpu_id) == LOCK_SUCCESS)
{
// Check if the message buffer is empty
if(message->flag == NO_MESSAGE)
{
message->buf[0] = cpu_id;
message->buf[1] = Tick_message_data_G[0];
message->buf[2] = Tick_message_data_G[1];
message->buf[3] = Tick_message_data_G[2];
message->buf[4] = Tick_message_data_G[3];
// Set the flag that a message has been put in the buffer.
message->flag = MESSAGE_WAITING;
}
// Release the mutex
altera_avalon_mutex_unlock(mutex);
}
else
{
// Change the LED from OFF to ON (or vice versa)
IOWR_ALTERA_AVALON_PIO_DATA(LED_BASE1,
IORD_ALTERA_AVALON_PIO_DATA(LED_BASE1) ^ LED1_pin);
}
}
/*------------------------------------------------------------------*-
---- END OF FILE -------------------------------------------------
-*------------------------------------------------------------------*/
<file_sep>/*------------------------------------------------------------------*-
port.c (2014-09-17)
------------------------------------------------------------------
Demonstration for time-trigger architecture on LPC1769.
This code should purely be used in training and teaching purposes for
for MSc Reliable Embedded Systems programme.
This code is copyright (c) University of Leicester 2014.
-*------------------------------------------------------------------*/
#ifndef _PORT_H
#define _PORT_H 1
// Project header
#include "../main/main.h"
// Heartbeat LED: see heartbeat.c
// Connected to "LED2" on LPC1769 board
// Port 0, Pin 22
#define HEARTBEAT_LED_PORT (0)
#define HEARTBEAT_LED_PIN (0b10000000000000000000000)
// Counter reset input
// Connected to "SW3" on LPC1769 Baseboard
// Port 0, Pin 4
#define SW_RST_CNT_PORT (0)
#define SW_RST_CNT_PIN (0b10000)
// 7-segment display is controlled with "SPI" link
// Uses SSP1 plus a pin for chip select
#define SSP_CHANNEL LPC_SSP1
#define LED_DISPLAY_PORT_CS (2)
#define LED_DISPLAY_PIN_CS (0b100)
#endif
/*------------------------------------------------------------------*-
---- END OF FILE -------------------------------------------------
-*------------------------------------------------------------------*/
<file_sep>/*
Author: nt161
Date: October 2018
A linear search algorithm implemented in parallel using openmp
*/
#include <stdio.h>
#include <stdlib.h>
#include <omp.h>
int main()
{
int i, thread_id;
int n = 99000000;
int key = n-1;
int *a = malloc(sizeof(int)*n);
double start;
for (i = 0; i < n; i++) {
a[i] = i;
}
start = omp_get_wtime();
printf("Max threads %d\n", omp_get_max_threads());
#pragma omp parallel private(i)
{
printf("thread %d\n", thread_id);
#pragma omp for
for(i=0; i<n; i++)
{
if(a[i] == key)
{
printf("Key found. Array position = %d. Time taken = %lf \n", i+1, omp_get_wtime() - start);
}
}
}
return 0;
}
<file_sep>/*------------------------------------------------------------------*-
2_50_XXg.C (v1.00)
------------------------------------------------------------------
*** THIS IS A SCHEDULER FOR A NIOS II PROCESSOR ***
*** Uses a full-featured interval timer peripheral ***
*** 50 MHz clock -> 50 ms (precise) tick interval ***
COPYRIGHT
---------
This code is from the book:
PATTERNS FOR TIME-TRIGGERED EMBEDDED SYSTEMS by <NAME>
[Pearson Education, 2001; ISBN: 0-201-33138-1].
This code is copyright (c) 2001 by <NAME>.
See book for copyright details and other information.
-*------------------------------------------------------------------*/
#include "Port.h"
#include "system.h"
#include "2_50_XXg.h"
#include "Sch51.h"
#include <sys/alt_irq.h>
#include <altera_avalon_timer_regs.h>
#include "../SPImcp2515/spi_mcp2515.h"
#include <altera_avalon_pio_regs.h>
#include "sys/alt_stdio.h"
// One byte of data (plus ID information) is sent to each Slave
extern tByte Tick_message_data_G[NUMBER_OF_SLAVES];
tByte Ack_message_data_G[NUMBER_OF_SLAVES];
// Slave IDs may be any non-zero tByte value (but all must be different)
tByte Current_Slave_IDs_G[NUMBER_OF_SLAVES] = {0};
// ------ Private constants ----------------------------------------
// Do not use ID 0x00 (used to start slaves)
static const tByte MAIN_SLAVE_IDs[NUMBER_OF_SLAVES] = {0x02}; //,0x03};
static const tByte BACKUP_SLAVE_IDs[NUMBER_OF_SLAVES] = {0x02}; //,0x03};
#define NO_NETWORK_ERROR (1)
#define NETWORK_ERROR (0)
tByte Slave_index_G = 0;
tByte First_ack_G = 1;
// ------ Private variables ----------------------------------------
static tWord Slave_reset_attempts_G[NUMBER_OF_SLAVES];
// ------ Public variable declarations -----------------------------
// The array of tasks (see Sch51.C)
extern sTask SCH_tasks_G[SCH_MAX_TASKS];
// Used to display the error code
// See Main.H for details of error codes
// See Port.H for details of the error port
extern tByte Error_code_G;
static void SCH_Update(void *);
/*------------------------------------------------------------------*-
SCH_Init_T2()
Scheduler initialisation function. Prepares scheduler
data structures and sets up timer interrupts at required rate.
You must call this function before using the scheduler.
-*------------------------------------------------------------------*/
void SCH_Init_T0(void)
{
tByte i;
tByte Slave_index;
// We allow any combination of ID numbers in slaves
for (Slave_index = 0; Slave_index < NUMBER_OF_SLAVES; Slave_index++)
{
Slave_reset_attempts_G[Slave_index] = 0;
Current_Slave_IDs_G[Slave_index] = MAIN_SLAVE_IDs[Slave_index];
Tick_message_data_G[Slave_index] = 'C';
}
// Get ready to send first tick message
First_ack_G = 1;
Slave_index_G = 0;
// ------ Set up the CAN link (begin) ------------------------
MCP2515_Init();
for (i = 0; i < SCH_MAX_TASKS; i++)
{
SCH_Delete_Task(i);
}
// Reset the global error variable
// - SCH_Delete_Task() will generate an error code,
// (because the task array is empty)
Error_code_G = 0;
// Now set up the interval timer
// The required overflow is 0.050 seconds (50 ms)
//IOWR_ALTERA_AVALON_TIMER_PERIODH(TIMER_0_BASE, (((50 * (TIMER_0_FREQ) / 1000) - 1) >> 16) & 0xFFFF);
//IOWR_ALTERA_AVALON_TIMER_PERIODL(TIMER_0_BASE, ( (50 * (TIMER_0_FREQ) / 1000) - 1) & 0xFFFF);
IOWR_ALTERA_AVALON_TIMER_PERIODH(TIMER_0_BASE, (alt_u16) (((50000 - 1) >> 16) & 0xFFFF)); //for 1 ms
IOWR_ALTERA_AVALON_TIMER_PERIODL(TIMER_0_BASE, (alt_u16) ((50000 - 1) & 0xFFFF));
IOWR_ALTERA_AVALON_TIMER_CONTROL(TIMER_0_BASE,
(0x1 << ALTERA_AVALON_TIMER_CONTROL_START_OFST) | // Start
(0x1 << ALTERA_AVALON_TIMER_CONTROL_CONT_OFST ) | // Continuous
(0x1 << ALTERA_AVALON_TIMER_CONTROL_ITO_OFST )); // Generate interrupts
alt_ic_isr_register(0, TIMER_0_IRQ, SCH_Update, 0, 0);
//alt_printf("S_init\r\n");
}
/*------------------------------------------------------------------*-
SCH_Start()
Starts the scheduler, by enabling interrupts.
NOTE: Usually called after all regular tasks are added,
to keep the tasks synchronised.
NOTE: ONLY THE SCHEDULER INTERRUPT SHOULD BE ENABLED!!!
-*------------------------------------------------------------------*/
void SCH_Start(void)
{
tByte Num_active_slaves;
tLong i;
tByte Slave_replied_correctly;
tByte Slave_index, Slave_ID;
for (i = 0; i <= 50000; i++);
// Currently disconnected from all slaves
Num_active_slaves = 0;
// After the initial (long) delay, all (operational) slaves will have timed out.
// All operational slaves will now be in the 'READY TO START' state
// Send them a 'slave id' message to get them started
Slave_index = 0;
do {
// Find the slave ID for this slave
Slave_ID = (tByte) Current_Slave_IDs_G[Slave_index];
Slave_replied_correctly = SCC_A_MASTER_Start_Slave(Slave_ID);
if (Slave_replied_correctly)
{
Num_active_slaves++;
Slave_index++;
}
else
{
// Slave did not reply correctly
// - try to switch to backup device (if available)
if (Current_Slave_IDs_G[Slave_index] != BACKUP_SLAVE_IDs[Slave_index])
{
// There is a backup available: switch to backup and try again
Current_Slave_IDs_G[Slave_index] = BACKUP_SLAVE_IDs[Slave_index];
}
else
{
// No backup available (or backup failed too) - have to continue
//Slave_index++;
}
}
} while (Slave_index < NUMBER_OF_SLAVES);
// DEAL WITH CASE OF MISSING SLAVE(S) HERE ...
if (Num_active_slaves < NUMBER_OF_SLAVES)
{
// User-defined error handling here...
// 1 or more slaves have not replied
// NOTE: In some circumstances you may wish to abort if slaves are missing
// - or reconfigure the network.
// Simplest solution is to display an error and carry on
// (this is what we do here)
Error_code_G = ERROR_SCH_ONE_OR_MORE_SLAVES_DID_NOT_START;
}
else
{
Error_code_G = 0;
}
alt_irq_cpu_enable_interrupts();
//alt_printf("S_start\r\n");
}
/*------------------------------------------------------------------*-
SCH_Update
This is the scheduler ISR. It is called at a rate
determined by the timer settings in SCH_Init().
This version is triggered by the interval timer interrupts:
the timer is automatically reloaded.
-*------------------------------------------------------------------*/
void SCH_Update(void * context)
{
tByte Index;
tByte Previous_slave_index;
// tByte Slave_replied_correctly;
IOWR_ALTERA_AVALON_TIMER_STATUS(TIMER_0_BASE,
IORD_ALTERA_AVALON_TIMER_STATUS(TIMER_0_BASE) &
~ALTERA_AVALON_TIMER_STATUS_TO_MSK); // Clear TO (timeout)
// Keep track of the current slave
Previous_slave_index = Slave_index_G; // First value of prev slave is 0...
if (++Slave_index_G >= NUMBER_OF_SLAVES)
{
Slave_index_G = 0;
}
/*
// Check that the appropriate slave responded to the previous message:
// (if it did, store the data sent by this slave)
if (SCC_A_MASTER_Process_Ack(Previous_slave_index) == RETURN_ERROR)
{
// Try to connect to the slave
Slave_replied_correctly = SCC_A_MASTER_Start_Slave(Current_Slave_IDs_G[Slave_index_G]);
if (Slave_replied_correctly == 0)
{
// No backup available (or backup failed too) - we shut down
// OTHER BEHAVIOUR MAY BE MORE APPROPRIATE IN YOUR APPLICATION
// SCC_A_MASTER_Shut_Down_the_Network();
}
}
*/
SCC_A_MASTER_Process_Ack(Previous_slave_index);
// Send 'tick' message to all connected slaves
// (sends one data byte to the current slave)
SCC_A_MASTER_Send_Tick_Message(Slave_index_G);
// NOTE: calculations are in *TICKS* (not milliseconds)
for (Index = 0; Index < SCH_MAX_TASKS; Index++)
{
// Check if there is a task at this location
if (SCH_tasks_G[Index].pTask)
{
if (SCH_tasks_G[Index].Delay == 0)
{
// The task is due to run
SCH_tasks_G[Index].RunMe = 1; // Set the run flag
if (SCH_tasks_G[Index].Period)
{
// Schedule periodic tasks to run again
SCH_tasks_G[Index].Delay = SCH_tasks_G[Index].Period;
}
}
else
{
// Not yet ready to run: just decrement the delay
SCH_tasks_G[Index].Delay -= 1;
}
}
}
//alt_printf("S_update\r\n");
}
/*------------------------------------------------------------------*-
---- END OF FILE -------------------------------------------------
-*------------------------------------------------------------------*/
/*------------------------------------------------------------------*-
SCC_A_MASTER_Send_Tick_Message()
This function sends a tick message, over the CAN network.
The receipt of this message will cause an interrupt to be generated
in the slave(s): this invoke the scheduler 'update' function
in the slave(s).
-*------------------------------------------------------------------*/
void SCC_A_MASTER_Send_Tick_Message(const tByte SLAVE_INDEX)
{
// Find the slave ID for this slave
// ALL SLAVES MUST HAVE A UNIQUE (non-zero) ID
tByte Slave_ID = (tByte) Current_Slave_IDs_G[SLAVE_INDEX];
// First byte of message must be slave ID
MCP2515_Write_Register(TXBnDm(TXBnDm0,TXBnDm0) , Slave_ID);
// Now the data
MCP2515_Write_Register(TXBnDm(TXBnDm0,TXBnDm1) , Tick_message_data_G[SLAVE_INDEX]);
/* Send RTS_TXB0_INSTRUCTION Instruction */
MCP2515_RTS_TXB_Instruction_CMD(RTS_INSTRUCTION_TXB0 );
}
/*------------------------------------------------------------------*-
SCC_A_MASTER_Start_Slave()
Try to connect to a slave device.
-*------------------------------------------------------------------*/
tByte SCC_A_MASTER_Start_Slave(const tByte SLAVE_ID)
{
tWord i;
tByte Slave_replied_correctly = 0;
tByte Ack_ID, Ack_00;
// Prepare a 'Slave ID' message
MCP2515_Write_Register(TXBnDm(TXBnDm0,TXBnDm0) , 0x00); // Not a valid slave ID
MCP2515_Write_Register(TXBnDm(TXBnDm0,TXBnDm1) , SLAVE_ID);
/* Send RTS_TXB0_INSTRUCTION Instruction */
MCP2515_RTS_TXB_Instruction_CMD(RTS_INSTRUCTION_TXB0 );
/*SPI_DataOut = (RTS_BUFFER0_INSTRUCTION << 8) | 0x01;
IOWR_ALTERA_AVALON_PIO_DATA(SPI_DataOut_BASE, SPI_DataOut);
IOWR_ALTERA_AVALON_PIO_DATA(SPI_DataOut_BASE, 0);
while(IORD_ALTERA_AVALON_PIO_DATA(SPI_Ack_BASE) == 0);
for (i = 0; i <= 2; i++);*/
//---
// Wait to give slave time to reply
for (i = 0; i <= 3000; i++);
// Check we had a reply
if ((MCP2515_Read_Register(CANINTF) & 0x02) != 0) //0x02 !=0
{
// An ack message was received - extract the data
Ack_00 = MCP2515_Read_Register(RXBnDm(RXBnDm1,RXBnDm0)); // Get data byte 0
Ack_ID = MCP2515_Read_Register(RXBnDm(RXBnDm1,RXBnDm1)); // Get data byte 1
// Clear *ALL* flags
MCP2515_Write_Register(CANINTF, 0x00);
if ((Ack_00 == 0x00) && (Ack_ID == SLAVE_ID))
{
Slave_replied_correctly = 1;
}
}
return Slave_replied_correctly;
}
/*------------------------------------------------------------------*-
SCC_A_MASTER_Process_Ack()
Make sure the slave (SLAVE_ID) has acknowledged the previous
message that was sent. If it has, extract the message data
from the USART hardware: if not, call the appropriate error
handler.
PARAMS: The index of the slave.
RETURNS: RETURN_NORMAL - Ack received (data in Ack_message_data_G)
RETURN_ERROR - No ack received (-> no data)
-*------------------------------------------------------------------*/
tByte SCC_A_MASTER_Process_Ack(const tByte SLAVE_INDEX)
{
tByte Ack_ID, Slave_ID;
// First time this is called there is no Ack message to check
// - we *assume* everything is OK
if (First_ack_G)
{
First_ack_G = 0;
return RETURN_NORMAL;
}
if ((MCP2515_Read_Register(CANINTF) & 0x02) != 0) //&0x02 originally
{
// An ack message was received
//
// Extract the data
// Get data byte 0 (Slave ID)
Ack_ID = MCP2515_Read_Register(RXBnDm(RXBnDm1,RXBnDm0));
Ack_message_data_G[SLAVE_INDEX] = MCP2515_Read_Register(RXBnDm(RXBnDm1,RXBnDm1));
// Clear *ALL* flags ...
MCP2515_Write_Register(CANINTF, 0x00);
// Find the slave ID for this slave
Slave_ID = (tByte) Current_Slave_IDs_G[SLAVE_INDEX];
if (Ack_ID == Slave_ID)
{
return RETURN_NORMAL;
}
}
// No message, or ID incorrect
return RETURN_ERROR;
}
<file_sep>package eMarket.department.repository;
import org.springframework.data.repository.CrudRepository;
import eMarket.department.Department;
public interface DepartmentRepository extends CrudRepository<Department, String> {
Department findByCode(String code);
}<file_sep>#!/bin/bash
if [[ $PWD = $TMP ]]
then
echo "in the TMP directory"
else
echo "not in the TMP directory"
fi
<file_sep><link rel='stylesheet' href='web/swiss.css'/>
# Exercise 03. Java Persistence API (JPA)
Table of contents:
* [Configuration](#configuration)
* [Examples](#examples-using-jpa)
* [Exercise](#star-star-exercise)
* [Additional resources on JPA](#additional-resources-on-jpa)
## Configuration
### Database access
The following Java class contains all the information that is required to connect to a MySQL server:
`src/main/java/jpa/DbConfig.java`
@Configuration
public class DbConfig {
@Bean
public DriverManagerDataSource dataSource() {
DriverManagerDataSource ds = new DriverManagerDataSource();
ds.setDriverClassName("com.mysql.jdbc.Driver");
// jdbc:mysql://host:port/db
ds.setUrl("jdbc:mysql://HOST:PORT/DB");
ds.setUsername("USERNAME");
ds.setPassword("<PASSWORD>");
return ds;
}
}
Replace the following parameters as follows depending on whether you are running your code from campus (e.g. from a lab machine) or off campus (e.g. from home or from eduroam):
##### From campus
Replace the following variables in the class `DbConfig.java` as follows:
* `HOST` with `mysql.mcscw3.le.ac.uk`
* `PORT` with `3306`
* `USERNAME` with your user name
* `PASSWORD` with your **<PASSWORD> password**, stored in `.my.cnf` file (open a terminal console and run the command `cat .my.cnf` to view it).
##### Off-campus
From a terminal console: run the command
ssh -fNg -L 3307:mysql.mcscw3.le.ac.uk:3306 ${<EMAIL>}@<EMAIL>
where `${USERNAME}` has to be replaced with your actual user name. This command creates a [SSH tunnel](https://en.wikipedia.org/wiki/Tunneling_protocol) from a port (`3307` in our command) on the local machine to the MySQL server port (`3306` in our command) on the MySQL host machine. The server `xanthus.mcscw3.le.ac.uk` is used as a gateway machine to reach the database server `mysql.mcscw3.le.ac.uk`. The command will ask for your Linux password. If the tunnel is created successfully, you should be able to use your terminal console as usual and **no success message is going to be shown**. This configuration is documented in more detail [here](https://campus.cs.le.ac.uk/labsupport/usinglinux/mysqlaccountdetails). If you are using Windows 10, you may want to [install Bash terminal](https://github.com/uol-inf/CO2006-17-18/blob/master/tooling.md#for-users-of-ms-windows-10).
Replace the following variables in the `DbConfig.java` as follows:
* `HOST` with `127.0.0.1`
* `PORT` with `3307`
* `USERNAME` and `PASSWORD` as above.
#### Hibernate configuration
In the `application.properties` file, write the following code:
`src/main/resources/application.properties`
# server port
server.port=8090
# Hibernate
spring.jpa.hibernate.ddl-auto=create
spring.jpa.hibernate.naming_strategy: org.hibernate.cfg.ImprovedNamingStrategy
The hibernate configuration is as follows:
* `spring.jpa.hibernate.ddl-auto` indicates whether the schema is generated automatically or not. Some of the options that are available are:
* `none`: the schema is not generated. This option allows you to reuse a previous database that is already populated with data.
* `create`: the schema is generated. When you run your application the second time, Spring will try to delete the schema before regenerating it from scratch. This option allows you to generate a schema from scratch form your Java code.
* `create-drop`: the schema is transient. That is, it will be created from scratch for your application instance and, once the execution is over, it is destroyed. This option is helpful to test your application once you have a proper test suite up and running. However, once the execution is over you will not be able to see what happened by inspecting the database with external tools such as [MySQLWorkbench](https://www.mysql.com/products/workbench/).
* `spring.jpa.hibernate.naming_strategy`: strategy used to create names for elements in the database schema.
## Examples using JPA
### a. Class
This example is adapted from [Exercise 02.a](../sprint4.ex02#star-a-tables).
From [Ex1_Department.java](src/main/java/jpa/a/Ex1_Department.java),
@Entity(name="Ex1_Department")
public class Ex1_Department {
@Id
@GeneratedValue(strategy=GenerationType.TABLE)
@Column(name="dept_code", nullable=false)
private String dept_code;
@Column(name="dept_name", nullable=false)
private String dept_name;
}
Hibernate generates:
CREATE TABLE `ex1_department` (
`dept_code` varchar(255) NOT NULL,
`dept_name` varchar(255) NOT NULL,
PRIMARY KEY (`dept_code`)
)
### b. One-to-one relation
This example is adapted from [Exercise 02.b](../sprint4.ex02#starstar-b-one-to-one-relation).
From [the classes in package b](src/main/java/jpa/b/),
@Entity(name="Ex2_Department")
public class Ex2_Department {
@Id
@GeneratedValue(strategy=GenerationType.TABLE)
private String dept_code;
@Column(name="dept_name", nullable=false)
private String dept_name;
@OneToOne(optional=false)
@JoinColumn(name="dept_hod")
private Ex2_Employee dept_hod;
}
@Entity(name="Ex2_Employee")
public class Ex2_Employee {
@Id
@GeneratedValue(strategy=GenerationType.TABLE)
@Column(name="employee_id", nullable=false)
private int employee_id;
@Column(name="employee_name", nullable=false)
private String employee_name;
@Column(name="job_title")
private String job_title;
}
Hibernate generates:
CREATE TABLE `ex2_department` (
`dept_code` varchar(255) NOT NULL,
`dept_name` varchar(255) NOT NULL,
`dept_hod` int(11) NOT NULL,
PRIMARY KEY (`dept_code`),
UNIQUE KEY `UK_71d5sfqnr6cn1o073vtc9kod8` (`dept_hod`),
CONSTRAINT `FKlenkowmjmf08eacg9o9cx25ht` FOREIGN KEY (`dept_hod`) REFERENCES `ex2_employee` (`employee_id`)
)
CREATE TABLE `ex2_employee` (
`employee_id` int(11) NOT NULL,
`employee_name` varchar(255) NOT NULL,
`employee_title` varchar(255) DEFAULT NULL,
PRIMARY KEY (`employee_id`)
)
### c. One-to-many relation
This example is adapted from [Exercise 02.c](../sprint4.ex02#starstar-c-one-to-many-relation).
From [the classes in package c](src/main/java/jpa/c/),
@Entity(name="Ex3_Department")
public class Ex3_Department {
@Id
@GeneratedValue(strategy=GenerationType.TABLE)
@Column(name="dept_code", nullable=false)
private String dept_code;
@Column(name="dept_name", nullable=false)
private String dept_name;
@OneToMany(fetch=FetchType.LAZY, cascade=CascadeType.ALL, orphanRemoval=true)
@JoinColumn(name="module_dept", referencedColumnName="dept_code")
private List<Ex3_Module> moduleList = new ArrayList<>();
}
@Entity(name="Ex3_Module")
public class Ex3_Module {
@Id
@GeneratedValue(strategy=GenerationType.TABLE)
@Column(name="module_code", nullable=false)
private String module_code;
@Column(name="module_title", nullable=false)
private String module_title;
@Column(name="module_credits", nullable=false)
private int module_credits;
}
Hibernate generates:
CREATE TABLE `ex3_department` (
`dept_code` varchar(255) NOT NULL,
`dept_name` varchar(255) NOT NULL,
PRIMARY KEY (`dept_code`)
)
CREATE TABLE `ex3_module` (
`module_code` varchar(255) NOT NULL,
`module_credits` int(11) NOT NULL,
`module_title` varchar(255) NOT NULL,
`module2dept` varchar(255) DEFAULT NULL,
PRIMARY KEY (`module_code`),
KEY `FK50qhb0a342bf82en76l8xcmeu` (`module_dept`),
CONSTRAINT `FK50qhb0a342bf82en76l8xcmeu` FOREIGN KEY (`module2dept`) REFERENCES `ex3_department` (`dept_code`)
)
### d. Many-to-many relation (no attributes)
This example is adapted from [Exercise 02.d](../sprint4.ex02#starstar-d-many-to-many-relation-no-attributes).
@Entity(name="Ex4_Department")
public class Ex4_Department {
@Id
@GeneratedValue(strategy=GenerationType.TABLE)
@Column(name="dept_code", nullable=false)
private String dept_code;
@Column(name="dept_name", nullable=false)
private String dept_name;
@ManyToMany
@JoinTable(name="Ex4_DepartmentEmployee",
joinColumns=@JoinColumn(name="department", referencedColumnName="dept_code"),
inverseJoinColumns=@JoinColumn(name="employee", referencedColumnName="employee_id"))
private List<Ex4_Employee> employeeList = new ArrayList<>();
}
@Entity(name="Ex4_Employee")
public class Ex4_Employee {
@Id
@GeneratedValue(strategy=GenerationType.TABLE)
@Column(name="employee_id", nullable=false)
private int employee_id;
@Column(name="employee_name", nullable=false)
private String employee_name;
@Column(name="job_title")
private String job_title;
@ManyToMany(mappedBy="employeeList")
private List<Ex4_Department> departmentList = new ArrayList<>();
}
From [the classes in package d](src/main/java/jpa/d/), Hibernate generates:
CREATE TABLE `ex4_department` (
`dept_code` varchar(255) NOT NULL,
`dept_name` varchar(255) NOT NULL,
PRIMARY KEY (`dept_code`)
)
CREATE TABLE `ex4_department_exployee` (
`department` varchar(255) NOT NULL,
`employee` int(11) NOT NULL,
KEY `FKc9v0dewrj88jbtfo6rvrv7u43` (`employee`),
KEY `FKchs2gmoi84i30k8hm4p79pfw6` (`department`),
CONSTRAINT `FKchs2gmoi84i30k8hm4p79pfw6` FOREIGN KEY (`department`) REFERENCES `ex4_department` (`dept_code`),
CONSTRAINT `FKc9v0dewrj88jbtfo6rvrv7u43` FOREIGN KEY (`employee`) REFERENCES `ex4_employee` (`employee_id`)
)
CREATE TABLE `ex4_employee` (
`employee_id` int(11) NOT NULL,
`employee_name` varchar(255) NOT NULL,
`employee_title` varchar(255) DEFAULT NULL,
PRIMARY KEY (`employee_id`)
)
### e. Many-to-many relation (with attributes)
This example is adapted from [Exercise 02.e](../sprint4.ex02#starstar-e-many-to-many-relation-with-attributes).
@Entity(name="Ex4b_Department")
public class Ex4_Department {
@Id
@GeneratedValue(strategy=GenerationType.TABLE)
@Column(name="dept_code", nullable=false)
private String dept_code;
@Column(name="dept_name", nullable=false)
private String dept_name;
}
@Entity(name="Ex4b_Employee")
public class Ex4_Employee {
@Id
@GeneratedValue(strategy=GenerationType.TABLE)
@Column(name="employee_id", nullable=false)
private int employee_id;
@Column(name="employee_name", nullable=false)
private String employee_name;
@Column(name="job_title")
private String job_title;
}
@Entity(name="Ex4b_DepartmentEmployee")
public class Ex4_DepartmentEmployee implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@ManyToOne
@JoinColumn(name="dept_code")
private Ex4_Department department;
@Id
@ManyToOne
@JoinColumn(name="employee_id")
private Ex4_Employee employee;
@Column(name="role", nullable=false)
private String role;
}
From [the classes in package e](src/main/java/jpa/e/), Hibernate generates:
CREATE TABLE `ex4b_department` (
`dept_code` varchar(255) NOT NULL,
`dept_name` varchar(255) NOT NULL,
PRIMARY KEY (`dept_code`)
)
CREATE TABLE `ex4b_department_employee` (
`role` varchar(255) NOT NULL,
`employee_employee_id` int(11) NOT NULL,
`department_dept_code` varchar(255) NOT NULL,
PRIMARY KEY (`employee_employee_id`,`department_dept_code`),
KEY `FK1pqdbwprosg9nj4gbk20w6qux` (`department_dept_code`),
CONSTRAINT `FK1pqdbwprosg9nj4gbk20w6qux` FOREIGN KEY (`department_dept_code`) REFERENCES `ex4b_department` (`dept_code`),
CONSTRAINT `FKkuauyf2r05xfdlvrxy06sljax` FOREIGN KEY (`employee_employee_id`) REFERENCES `ex4b_employee` (`employee_id`)
)
CREATE TABLE `ex4b_employee` (
`employee_id` int(11) NOT NULL,
`employee_name` varchar(255) NOT NULL,
`job_title` varchar(255) DEFAULT NULL,
PRIMARY KEY (`employee_id`)
)
## :star::star: Exercise
Given the following domain classes, already implemented in package `springData.domain`:
<img src="./web/cd.png" height=150" width="700"/>
The exercise consists in annotating the Java classes in the package `jpa.exercise` in order to generate the following schema in the database:
<img src="./web/eer.png" height=300" width="600"/>
whose SQL DDL script is as follows:
CREATE TABLE `modules` (
`modules_id` int(11) NOT NULL,
`modules_code` varchar(255) DEFAULT NULL,
`modules_description` varchar(255) DEFAULT NULL,
PRIMARY KEY (`modules_id`)
);
CREATE TABLE `students` (
`students_id` int(11) NOT NULL,
`students_full_name` varchar(255) DEFAULT NULL,
PRIMARY KEY (`students_id`)
);
CREATE TABLE `students_modules` (
`modules_students_id` int(11) NOT NULL,
`students_modules_id` int(11) NOT NULL,
KEY `FK3ah1sd78bn4ebo9iv580nhelq` (`students_modules_id`),
KEY `FKfgffxpiei0e99weuuefvhfcqo` (`modules_students_id`),
CONSTRAINT `FKfgffxpiei0e99weuuefvhfcqo` FOREIGN KEY (`modules_students_id`)
REFERENCES `students` (`students_id`),
CONSTRAINT `FK3ah1sd78bn4ebo9iv580nhelq` FOREIGN KEY (`students_modules_id`)
REFERENCES `modules` (`modules_id`)
);
Take into account the following:
* Names of tables, columns and foreign keys must match those that appear in the schema.
* All database operations performed on a student must be cascaded to linked modules.
## Additional resources on JPA
* [Tutorial JPA 1: mapping classes](https://www.javaworld.com/article/2077817/java-se/understanding-jpa-part-1-the-object-oriented-paradigm-of-data-persistence.html?page=1)
* [Tutorial JPA 2: mapping associations](https://www.javaworld.com/article/2077819/java-se/understanding-jpa-part-2-relationships-the-jpa-way.html?page=1)
* [Oracle tutorial on Java Persistence API](http://www.oracle.com/technetwork/articles/javaee/jpa-137156.html) (comprehensive)
***
© <NAME>, 2017-18
<file_sep># Makefile
# the C++ compiler
CXX = g++
CC = $(CXX)
# options to pass to the compiler
CXXFLAGS = -Wall -ansi -O2 -g
check : check.o
$(CXX) $(CXXFLAGS) -o check check.o
check.o : check.cpp
$(CXX) $(CXXFLAGS) -c check.cpp
.PHONY : clean
clean :
$(RM) check check.o *~
<file_sep># Makefile
#
<file_sep>const int flash_led = 10;
int state = HIGH;
void setup() {
pinMode(flash_led, OUTPUT);
digitalWrite(flash_led, HIGH);
cli();
TCCR1A = 0; // Clear timer control register
TCCR1B = 0; // Clear timer control register
TCNT1 = 0; // Timer counter set to zero
OCR1A = 15624; // Compare match register
TCCR1B |= (1 << WGM12); // Reset timer counter on interrupt
/*
* Prescaler settings for timer 1
* are controlled by CS10 to CS12:
* CS12 CS11 CS10
* 0 0 0 = timer stopped
* 0 0 1 = prescaler 1 (no prescaler)
* 0 1 0 = prescaler 8
* 0 1 1 = prescaler 64
* 1 0 0 = prescaler 256
* 1 0 1 = prescaler 1024
* (110 and 111 used for external clock source)
*
* Interrupt frequency will be CS/(PR * (CMR+1))
* where
* CS = Arduino Clock Speed (16 MHz usually)
* PR = Prescaler (see above)
* CMR = Compare Match Register
*
* See https://www.instructables.com/id/Arduino-Timer-Interrupts/
*/
TCCR1B |= (1 << CS12) | (1 << CS10);
TIMSK1 |= (1 << OCIE1A); // Enable timer compare interrupt
sei(); // Enable all interrupts
}
void loop()
{
// Nothing
}
ISR(TIMER1_COMPA_vect)
{
digitalWrite(flash_led, state);
state = (state == HIGH) ? LOW : HIGH;
}
<file_sep>/**
* (C) <NAME>, 2016
*/
package eMarket.controller;
import java.util.ArrayList;
import java.util.List;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import eMarket.domain.UserInfo;
import eMarket.domain.Role;
import eMarket.repository.RoleRepository;
import eMarket.repository.UserInfoRepository;
@Controller
@RequestMapping("/signup")
public class SignupController {
@Autowired UserInfoRepository userInfoRepo;
@Autowired RoleRepository roleRepo;
@InitBinder
protected void initBinder(WebDataBinder binder) {
binder.addValidators(new UserInfoValidator());
}
@RequestMapping(value = "/", method = RequestMethod.GET)
public String signup(@ModelAttribute("userInfo") UserInfo userInfo, Model model) {
// prepare view
// model.addAttribute("userTypeValues",UserType.values());
List<Role> list = ((List<Role>) roleRepo.findAll());
// create a list with the name of each role
// Without lambda expressions...
List<String> nameList = new ArrayList<>();
for (Role r: list) {
nameList.add(r.getRole());
}
model.addAttribute("userTypeValues", nameList);
//
// or equivalently with lambda expressions...
// model.addAttribute("userTypeValues",list.stream().map(r -> r.getRole()).collect(Collectors.toList()));
return "Signup";
}
@RequestMapping(value="add", params = "add", method = RequestMethod.POST)
public String addNewUser(@Valid @ModelAttribute("userInfo") UserInfo userInfo, BindingResult result, Model model) {
if (result.hasErrors()) {
// there are validation errors
// prepare view
// model.addAttribute("userTypeValues",UserType.values());
List<Role> list = ((List<Role>) roleRepo.findAll());
List<String> nameList = new ArrayList<>();
for (Role r: list) {
nameList.add(r.getRole());
}
model.addAttribute("userTypeValues", nameList);
// model.addAttribute("userTypeValues",list.stream().map(r -> r.getRole()).collect(Collectors.toList()));
return "Signup";
} else {
// no validation errors
// back-end logic
System.out.println("entered: " + userInfo.toString());
// get the user role name from the enum literal chosen
String userRole = userInfo.getUserType();
// we set the role from the information chosen about the user type (enumeration)
userInfo.setRole(roleRepo.findByRole(userRole));
// encrypt password
BCryptPasswordEncoder pe = new BCryptPasswordEncoder();
userInfo.setPassword(pe.encode(<PASSWORD>()));
// userInfo.setPassword(<PASSWORD>());
// save in repo
userInfoRepo.save(userInfo);
// prepare view
return "redirect:/login-form";
}
}
@RequestMapping(value="add", params = "cancel", method = RequestMethod.POST)
public String cancelNewUser(@ModelAttribute("userInfo") UserInfo userInfo, Model model) {
return "redirect:/login-form";
}
}
<file_sep>################################################################################
# Automatically-generated file. Do not edit!
################################################################################
# Add inputs and outputs from these tool invocations to the build variables
C_SRCS += \
../src/tasks/led_bank.c \
../src/tasks/rgb_led.c \
../src/tasks/serial_output.c \
../src/tasks/seven_seg.c
OBJS += \
./src/tasks/led_bank.o \
./src/tasks/rgb_led.o \
./src/tasks/serial_output.o \
./src/tasks/seven_seg.o
C_DEPS += \
./src/tasks/led_bank.d \
./src/tasks/rgb_led.d \
./src/tasks/serial_output.d \
./src/tasks/seven_seg.d
# Each subdirectory must supply rules for building sources it contributes
src/tasks/%.o: ../src/tasks/%.c
@echo 'Building file: $<'
@echo 'Invoking: MCU C Compiler'
arm-none-eabi-gcc -DDEBUG -D__USE_CMSIS=CMSISv1p30_LPC17xx -D__CODE_RED -D__NEWLIB__ -I"Z:\Assignment4V2\Lib_CMSISv1p30_LPC17xx\inc" -I"Z:\Assignment4V2\Lib_EaBaseBoard\inc" -I"Z:\Assignment4V2\Lib_MCU\inc" -O0 -g3 -Wall -c -fmessage-length=0 -fno-builtin -ffunction-sections -mcpu=cortex-m3 -mthumb -D__NEWLIB__ -MMD -MP -MF"$(@:%.o=%.d)" -MT"$(@:%.o=%.o)" -MT"$(@:%.o=%.d)" -o "$@" "$<"
@echo 'Finished building: $<'
@echo ' '
<file_sep>#include "BiArray.h"
#include <cmath>
#include <string>
using namespace std;
// default constructor
// setting initial values of size (of internal array) to zero, and capacity (of total array) to initial capacity
// allocating memory for the biArray of size equal to the capacity
// setting the head and tail pointers of the internal array to the middle
BiArray::BiArray() {
// IMPLEMENT ME
size = 0;
capacity = INITIALCAP;
biArray = new int[capacity];
int temp_head_index = floor((double)capacity/2);
int temp_tail_index = ceil((double)capacity/2);
head = biArray + temp_head_index;
tail = biArray + temp_tail_index;
}
// value constructor
// setting the capacity of external array to the initial capacity unless the low threshold multiplied by the size is
// greater than the initial capacity
// this size of the internal array is set to the size passed in the parameters
// allocating memory for the biArray of size equal to the capacity
// setting the head and tail pointers of internal array to the middle
// copying array contents into memory allocated for the new biArray
BiArray::BiArray(int arr[], int size) {
// IMPLEMENT ME
if((LO_THRESHOLD*size) > INITIALCAP)
{
capacity = LO_THRESHOLD*size;
}
else
{
capacity = INITIALCAP;
}
this->size = size;
biArray = new int[capacity];
int head_index = ((capacity - size)/2);
head = biArray + head_index - 1;
tail = biArray + head_index + size;
for(int i = 0; i<size; i++)
{
biArray[head_index+i] = arr[i];
}
}
// destructor
// setting the pointers of the head and tail to nullptr to ensure there are no dangling pointers
// deleting the memory allocated for the biArray
BiArray::~BiArray() {
// IMPLEMENT ME
head = nullptr;
tail = nullptr;
delete [] biArray;
}
// copy method for the copy constructor
// Initialises another biArray object using a biArray object that has been created
void BiArray::copy_(const BiArray& other){
this->size = other.size;
this->capacity = other.capacity;
this->biArray = new int[capacity];
for(int i = 0; i < size; i++)
{
biArray[i] = other.biArray[i];
}
this->head = other.head;
this->tail = other.tail;
}
// copy constructor
// we are doing a deep copy
// copy constructor is a constructor which creates an object by initializing
// it with an object of the same class, which has been created previously, using the copy method
BiArray::BiArray(const BiArray& other) {
// IMPLEMENT ME
copy_(other);
}
// move constructor
// we are swapping the contents essentially
// converting the resources owned by an rvalue object to be moved to an lvalue without copying
// then we are doing a bit of housekeeping and removing the reference to the other array
// again to ensure there are no dangling pointers
BiArray::BiArray(BiArray&& other) {
// IMPLEMENT ME
size = other.size;
capacity = other.capacity;
head = other.head;
tail = other.tail;
biArray = other.biArray;
other.size = 0;
other.capacity = 0;
other.head = nullptr;
other.tail = nullptr;
other.biArray = nullptr;
}
// copy assignment
// first we test for the same object
// we delete memory that was allocated if they aren't the same
// then we copy the new data
// finally return a reference to the current object
BiArray& BiArray::operator=(const BiArray& other) {
// IMPLEMENT ME
// below are just stub code
if(&other != this)
{
delete [] biArray;
copy_(other);
}
return *this;
}
// move assignment
// first we test for the same object
// we delete memory that was allocated if they aren't the same
// then we swap the data
// we do do a clean up
// finally return a reference to the current object
BiArray& BiArray::operator=(BiArray&& other) {
// IMPLEMENT ME
// below are just stub code
if(this != &other) //added
{
delete [] biArray;
size = other.size;
capacity = other.capacity;
head = other.head;
tail = other.tail;
biArray = other.biArray;
other.size = 0;
other.capacity = 0;
other.head = nullptr;
other.tail = nullptr;
other.biArray = nullptr;
}
return *this;
}
// v is set to the value of the i-th element (by reference).
// if i is out of bounds then it will return false
// else function returns true and sets v to the same value as the i-th element
bool BiArray::get(int i, int& v) const {
// IMPLEMENT ME
// below are just stub code
if(i < size && i >= 0)
{
v = *(head+1+i);
return true;
}
else
{
return false;
}
}
// i-th element is set to the value of v
// if i is out of bounds then it will return false
// else function returns true and sets i-th to the same value as v
bool BiArray::set(int i, int v) {
// IMPLEMENT ME
// below are just stub code
if (i < size && i >= 0)
{
*(head+1+i) = v;
return true;
}
else
return false;
}
// by overloading the operator this allows access to members of the biArray
// the compiler to can then return the corresponding element from the biArray
// by passing the index in the parameters
int BiArray::operator[](int i) const {
// IMPLEMENT ME
// below are just stub code
return *(head + i + 1);
}
// by overloading the operator this allows access to members of the biArray
// the compiler to can then return the reference to the corresponding element from the biArray
// by passing the index in the parameters
int& BiArray::operator[](int i) {
// IMPLEMENT ME
// below are just stub code
return *(head + i + 1);
}
void BiArray::push_back(int v) {
// IMPLEMENT ME
// if the tail position is less than the capacity then
// place the value in the tail position
// move the tail pointer one position to the right
// and increase the size of the internal array
if(tail < biArray + capacity)
{
*tail = v;
tail += 1;
size += 1;
}
else
{
// we only do the following if we need to resize the biArray
// pointer which also points to the biArray, so we can copy contents to a new memory that will be allocated
// without losing access to the original array
int* tempArray = biArray;
// checking if capacity is less than initial cap
// if so, then we set capacity to the initial cap
// otherwise we set it to the low threshold multiplied by the size of the internal array
if(capacity < INITIALCAP)
{
capacity = INITIALCAP;
}
else
{
capacity = LO_THRESHOLD*size;
}
// allocating memory for biArray using new capacity
biArray = new int[capacity];
// copying contents of tempArray into the middle of the new biArray
for(int i = 0; i < size; i++)
{
biArray[i + ((capacity-size)/2)] = *(head + i + 1);
}
// redefining head and tail pointers since these have moved
int head_index = ((capacity - size)/2) - 1;
head = biArray + head_index;
tail = head + size + 1;
// adding the value to the end of the array
// moving the tail pointer one position to the right
// and increasing the size of the internal array
*tail = v;
tail += 1;
size += 1;
// deleting the memory allocated for the temporary array
delete [] tempArray;
tempArray = nullptr;
}
}
bool BiArray::pop_back() {
// IMPLEMENT ME
// below are just stub code
// if size of the internal array is not equal to 0
// if so the tail pointer position is moved one position to the left
// size is also reduced by 1
// the function returns true
// else the function returns false
if(size != 0)
{
tail -= 1;
size -= 1;
// checking if capacity if greater than the high threshold multiplied by the size of the internal array
// if this is true, we have to resize the array
// so we do another check which looks at if the low threshold multiplied by the size is greater
// than the initial capacity
// if so then we set that as the capacity else we set the initial capacity as the capacity
if(capacity > (HI_THRESHOLD * size))
{
// pointer which also points to the biArray, so we can copy contents to a new memory that will be allocated
// without losing access to the original array
int* tempArray = biArray;
if((LO_THRESHOLD * size) > INITIALCAP)
{
capacity = LO_THRESHOLD * size;
}
else
{
capacity = INITIALCAP;
}
// allocating memory for biArray using new capacity
biArray = new int[capacity];
// copying contents of tempArray into the middle of the new biArray
for(int i = 0; i < size; i++)
{
biArray[i + ((capacity - size) / 2)] = *(head + i + 1);
}
// redefining head and tail pointers since these have moved
int head_index = ((capacity - size) / 2) - 1;
head = biArray + head_index;
tail = head + size + 1;
// deleting the memory allocated for the temporary array
delete [] tempArray;
tempArray = nullptr;
}
return true;
}
else
{
return false;
}
}
void BiArray::push_front(int v) {
// IMPLEMENT ME
// if the head position is greater than or equal to the beginning of the biArray
// then place the value in the head position
// move the head pointer one position to the left
// and increase the size of the internal array
if(head >= biArray)
{
*head = v;
head -= 1;
size += 1;
}
else
{
// we only do the following if we need to resize the biArray
// pointer which also points to the biArray, so we can copy contents to a new memory that will be allocated
// without losing access to the original array
int* tempArray = biArray;
// checking if capacity is less than initial cap
// if so, then we set capacity to the initial cap
// otherwise we set it to the low threshold multiplied by the size of the internal array
if(capacity < INITIALCAP)
{
capacity = INITIALCAP;
}
else
{
capacity = LO_THRESHOLD*size;
}
// allocating memory for biArray using new capacity
biArray = new int[capacity];
// copying contents of tempArray into the middle of the new biArray
for(int i = 0; i < size; i++)
{
biArray[i + ((capacity - size) / 2)] = *(head + i + 1);
}
// redefining head and tail pointers since these have moved
int head_index = ((capacity - size) / 2) - 1;
head = biArray + head_index;
tail = head + size + 1;
// then place the value in the head position
// move the head pointer one position to the left
// and increase the size of the internal array
*head = v;
head -= 1;
size += 1;
// deleting the memory allocated for the temporary array
delete [] tempArray;
tempArray = nullptr;
}
}
bool BiArray::pop_front() {
// IMPLEMENT ME
// below are just stub code
// if size of the internal array is not equal to 0
// if so the head pointer position is moved one position to the right
// size is also reduced by 1
// the function returns true
// else the function returns false
if(size != 0)
{
head += 1;
size -= 1;
// checking if capacity if greater than the high threshold multiplied by the size of the internal array
// if this is true, we have to resize the array
// so we do another check which looks at if the low threshold multiplied by the size is greater
// than the initial capacity
// if so then we set that as the capacity else we set the initial capacity as the capacity
if(capacity > (HI_THRESHOLD * size))
{
// pointer which also points to the biArray, so we can copy contents to a new memory that will be allocated
// without losing access to the original array
int* tempArray = biArray;
if((LO_THRESHOLD * size) > INITIALCAP)
{
capacity = LO_THRESHOLD * size;
}
else
{
capacity = INITIALCAP;
}
// allocating memory for biArray using new capacity
biArray = new int[capacity];
// copying contents of tempArray into the middle of the new biArray
for(int i = 0; i < size; i++)
{
biArray[i + ((capacity - size) / 2)] = *(head + i + 1);
}
// redefining head and tail pointers since these have moved
int head_index = ((capacity - size) / 2) - 1;
head = biArray + head_index;
tail = head + size + 1;
// deleting the memory allocated for the temporary array
delete [] tempArray;
tempArray = nullptr;
}
return true;
}
else
{
return false;
}
}
int BiArray::getSize() const {
// IMPLEMENT ME
// below are just stub code
return size;
}
int BiArray::getCapacity() const {
// IMPLEMENT ME
// below are just stub code
return capacity;
}
string BiArray::print() const {
// IMPLEMENT ME
// below are just stub code
std::string s = "[";
for(int* i = head+1; i < tail; i++)
{
if(i == (tail - 1))
{
s += std::to_string(*i);
}
else
{
s += std::to_string(*i) + " ";
}
}
s += "]";
return s;
}
string BiArray::printAll() const {
// IMPLEMENT ME
// below are just stub code
string s = "[";
for(int* i = biArray; i<=head; i++)
{
s += "X ";
}
for(int* j = head+1; j<tail; j++)
{
s += std::to_string(*j) + " ";
}
for(int* k = tail; k < biArray + capacity; k++)
{
s += (k == tail) ? ("X") : (" X");
}
s = s + "]";
return s;
}
// first checks if lhs size is equal to rhs size, then checks if size of both is 0,
// which would mean both lhs and rhs are equal
// otherwise it iterates through and checks the dereferenced heads of lhs and rhs, if these aren't the same then
// the function returns false
bool operator==(const BiArray& lhs, const BiArray& rhs) {
if(lhs.size == rhs.size)
{
if(lhs.size == 0 && rhs.size == 0) return true;
for(int i = 0;i<lhs.size;i++)
{
if(*(lhs.head + i + 1) != *(rhs.head + i + 1)) return false;
}
return true;
}
else
{
return false;
}
}
// first checks if lhs size is not equal to rhs size, if so it'll return true,
// otherwise checks if size is 0 for lhs and size is not 0 for lhs, in which case it would return false,
// which would mean both lhs and rhs are equal
// otherwise it iterates through and checks the dereferenced heads of lhs and rhs, if these aren't the same then
// the function returns true
bool operator!=(const BiArray& lhs, const BiArray& rhs) {
if(lhs.size != rhs.size) return true;
if(lhs.size == 0 && rhs.size != 0) return false; // double check this line
for(int i = 0;i<lhs.size;i++){
if(*(lhs.head + i + 1) != *(rhs.head + i + 1)) return true;
}
return false;
}
<file_sep>set -a # export all vars
# set -x # debug
# put_classes_in_bin="-d bin"
jars=`echo jars/*`
javac_cp="-cp ${jars// /:}"
java_cp="-cp ${jars// /:}:bin" # add bin directory for our classes
java_files=`ls src/*.java`
<file_sep>#include "ssp_config.h"
void com_Init(void)
{
/*
* Initialize SPI pin connect
* P0.7 - SCK;
* P0.8 - MISO
* P0.9 - MOSI
* P2.2 - SSEL - used as GPIO
*/
PinCfg.Funcnum = 2;
PinCfg.OpenDrain = 0;
PinCfg.Pinmode = 0;
PinCfg.Portnum = 0;
PinCfg.Pinnum = 7;
PINSEL_ConfigPin(&PinCfg);
PinCfg.Pinnum = 8;
PINSEL_ConfigPin(&PinCfg);
PinCfg.Pinnum = 9;
PINSEL_ConfigPin(&PinCfg);
PinCfg.Funcnum = 0;
PinCfg.Portnum = 2;
PinCfg.Pinnum = 2;
SSP_ConfigStructInit(&SSP_ConfigStruct);
// Initialize SSP peripheral with parameter given in structure above
SSP_Init(LPC_SSP1, &SSP_ConfigStruct);
// Enable SSP peripheral
SSP_Cmd(LPC_SSP1, ENABLE);
}
<file_sep>package CO3090.assignment2.client;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Vector;
import CO3090.assignment2.FileItem;
import CO3090.assignment2.SearchCriteria;
//Question 3.3
/*
* For each file server, QueryTree should return the directory
* structure as a string formatted according to the specified
* format.
*
* For example, given the directory structure in
* RemoteFilesystem1.txt and RemoteFilesystem2.txt.
* RFSServer should return:
*
{
"list": [{
"fs": "RemoteFilesystem1",
"path": "A{B,C{books.xls,D,E{readme.txt,hello.txt},F{G}}}"
},
{
"fs": "RemoteFilesystem2",
"path": "A{B{hello.txt,D{abc.txt,xyz.txt}},C{E{hello.txt,F{hello.txt}}}}"
}
]
}
*
*/
public class QueryTree implements SearchCriteria{
public static Vector<FileItem> fileSearch(String dir, Vector<FileItem> files){
Vector<FileItem> list_of_files = new Vector<FileItem>();
for(FileItem file : files){
if(file.getName().equals(dir)){
list_of_files.add(file);
}
}
return list_of_files;
}
@Override
public Object execute(HashMap<String, Vector<FileItem>> list) {
HashMap<Integer, Vector<FileItem>> tree = new HashMap<Integer, Vector<FileItem>>();
StringBuilder json = new StringBuilder();
StringBuilder sb = new StringBuilder();
json.append("{\n\"list\": [{\n");
for (String fileSystem : list.keySet()){ //getting the file system names
json.append("\"fs\" : " + "\"" + fileSystem + "\", \n");
Vector<FileItem> files = list.get(fileSystem);
for (FileItem file: files){
FileItem parentDir = file;
Integer i = new Integer(1);
while(parentDir.getParentDirectoryName() != null){
parentDir = fileSearch(file.getParentDirectoryName(), files).get(0);
i = i+1;
}
Vector<FileItem> temp_list = (tree.containsKey(i))?(tree.get(i)):(new Vector<FileItem>());
temp_list.add(file);
tree.put(i, temp_list);
}
for(int i : tree.keySet()){
if(i>1){
for(FileItem file: tree.get(i)){
String fname = file.getName();
int index;
if((index = sb.indexOf(fname+"{")) != -1){
sb.append(file.getParentDirectoryName() + "{" + fname + "}");
} else {
int last_index = sb.indexOf("{", index);
sb.replace(index,last_index, sb.substring(index, last_index) + "," + fname);
}
}
}
}
}
return json.append(sb).toString();
}
}
<file_sep>#!/usr/bin/python3
import serial
port = "/dev/ttyACM0"
with open("test.dat", "w") as outfile:
try:
with serial.Serial(port, 9600, timeout=1) as ser:
n = 0
while ser.is_open:
# Convert to UTF-8 from byte string, and strip return char(s)
line = ser.readline().decode('UTF-8').rstrip()
outfile.write("{}\n".format(line))
print(n, line)
n = n + 1
# value = int(line)
# if (value < 500):
# ser.write(b'R')
# else:
# ser.write(b'B')
except serial.serialutil.SerialException as e:
print("Serial communications error:")
print(e)
<file_sep>#define INT_IN_EP 0x81
#define BULK_OUT_EP 0x05
#define BULK_IN_EP 0x82
#define MAX_PACKET_SIZE 64
#define LE_WORD(x) ((x)&0xFF),((x)>>8)
// CDC definitions
#define CS_INTERFACE 0x24
#define CS_ENDPOINT 0x25
#define SET_LINE_CODING 0x20
#define GET_LINE_CODING 0x21
#define SET_CONTROL_LINE_STATE 0x22
void BulkOut(U8 bEP, U8 bEPStatus);
void BulkIn(U8 bEP, U8 bEPStatus);
BOOL HandleClassRequest(TSetupPacket *pSetup, int *piLen, U8 **ppbData);
void VCOM_init(void);
int VCOM_putchar(int c);
void VCOM_putstring (char datasend[]);
void VCOM_putstring2 (char datasend[]);
int VCOM_getchar(void);
int VCOM_GetString(char *data);
char* VCOM_RecieveString(void);
int VCOM_Available(void);
void USB_init (void);
void USB_IRQHandler(void);
void USBFrameHandler(U16 wFrame);
void enable_USB_interrupts(void);
void enable_USB_interrupts(void);
<file_sep>#! /bin/bash
for i in {0..23}
do
echo $i
ssh-keygen -G /tmp/mods-X.candidate -b 768
done
<file_sep>package CO3090.assignment2.client;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Vector;
import CO3090.assignment2.FileItem;
import CO3090.assignment2.SearchCriteria;
//Question 3.3
/*
* For each file server, QueryTree should return the directory
* structure as a string formatted according to the specified
* format.
*
* For example, given the directory structure in
* RemoteFilesystem1.txt and RemoteFilesystem2.txt.
* RFSServer should return:
*
{
"list": [{
"fs": "RemoteFilesystem1",
"path": "A{B,C{books.xls,D,E{readme.txt,hello.txt},F{G}}}"
},
{
"fs": "RemoteFilesystem2",
"path": "A{B{hello.txt,D{abc.txt,xyz.txt}},C{E{hello.txt,F{hello.txt}}}}"
}
]
}
*
*/
public class QueryTree implements SearchCriteria{
public static Vector<FileItem> fileSearch(String dir, Vector<FileItem> files){
Vector<FileItem> list_of_files = new Vector<FileItem>();
for(FileItem file : files){
if(file.getName().equals(dir)){
list_of_files.add(file);
}
}
return list_of_files;
}
@Override
public Object execute(HashMap<String, Vector<FileItem>> list) {
StringBuilder json = new StringBuilder();
json.append("{\n\"list\": [{\n");
for (String fileSystem : list.keySet()){ //getting the file system names
StringBuilder sb = new StringBuilder();
Vector<Integer> depth = new Vector<Integer>();
json.append("\"fs\" : " + "\"" + fileSystem + "\", \n");
Vector<FileItem> files = list.get(fileSystem);
for (FileItem file: files){
FileItem parentDir = file;
int position = 0;
int level = 1;
if(parentDir.getParentDirectoryName() == null){
// System.out.println("file name = " + parentDir.getName());
sb.append(parentDir.getName() + "{");
position = sb.length()-1;
// System.out.println("last index = " + position);
// System.out.println("parentdir null = " + sb.toString());
}
else
while(parentDir.getParentDirectoryName() != null){
//System.out.println("file is = " + parentDir.getName());
if(!sb.toString().contains(parentDir.getName())){
sb.append(parentDir.getName()+",");
position = sb.length()-1;
//System.out.println("parentdir !null = " + sb.toString());
//System.out.println("last index = " + position);
}
// else if(sb.toString().contains(parentDir.getName())){
// }
parentDir = fileSearch(parentDir.getParentDirectoryName(), files).get(0);
level++;
// for(int i = 1; i<depth.size(); i++){
// if(depth.get(i-1) < depth.get(i)){
//
// }
// else if(depth.get(i-1) > depth.get(i)){
//
// }
// else
// sb.append(",");
// i++;
// }
// level++;
// if(sb.toString().contains(parentDir.getName()))
// sb.append(parentDir.getName() + ".");
// }
//System.out.println(parentDir.toString());
depth.add(level);
}
//System.out.println(depth.toString());
//System.out.println(json.toString());
//System.out.println(sb.toString());
}
json.append("\"path\" : " + sb + "\"\n},\n");
json.append("{\n");
}
json.delete(json.length()-4, json.length());
json.append("\n]\n}");
return json.toString();
}
}
<file_sep>
#include <altera_avalon_pio_regs.h>
#include "system.h"
#include "../TTC_Scheduler_slave/2_50_XXg.h"
#include "spi_mcp2515.h"
#include "../TTC_Scheduler_slave/Main.h"
#include "../TTC_Scheduler_slave/PORT.h"
#include "alt_spi_master.h"
#include "altera_avalon_spi.h"
alt_u8 write_data[50],read_data[50];
/*-------------MCP2515_Init---------------------------
* This function performs reset, setup receive buffer mask and
* configure the filters for MCP2515.
* --------------------------------------------------------*/
void MCP2515_Init(void)
{
/* Snd reset instruction */
MCP2515_Reset();
//Set Configuration Mode
MCP2515_SetMode(_CANSPI_MODE_CONFIG);
//set bit timing, masks, and rollover mode
MCP2515_SetBitTiming(0x01,0xB5,0x01);
// We *don't* use Buffer 0 here.
// We therefore set it to receive CAN messages, as follows:
// - with Standard IDs.
// - matching the filter settings.
// [As all our messages have Extended IDs, this won't happen...]
MCP2515_Write_Register(RXB0CTRL, 0x20); //0x02);
// --- Now set up masks and filters (BEGIN) ---
// Buffer 0 mask
// (all 1s - so filter must match every bit)
// [Standard IDs]
MCP2515_Write_Register(RXM0SIDH, 0xFF);
MCP2515_Write_Register(RXM0SIDL, 0xE0);
// Buffer 0 filters
// (all 1s, and Standard messages only)
MCP2515_Write_Register(RXF0SIDH, 0xFF);
MCP2515_Write_Register(RXF0SIDL, 0xE0);
MCP2515_Write_Register(RXF1SIDH, 0xFF);
MCP2515_Write_Register(RXF1SIDL, 0xE0);
// We set up MCP2510 Buffer 1 to receive Tick messages, as follows:
// - with Extended IDs.
// - matching the filter settings (see below)
MCP2515_Write_Register(RXB1CTRL, 0x40); //0x04);
// Buffer 1 mask
// (all 1s - so filter must match every bit)
// [Extended IDs]
MCP2515_Write_Register(RXM1SIDH, 0xFF);
MCP2515_Write_Register(RXM1SIDL, 0xE3);
MCP2515_Write_Register(RXM1EID8, 0xFF);
MCP2515_Write_Register(RXM1EID0, 0xFF);
// Buffer 1 filters
// (only accept messages with Extended ID 0x00000000)
// We set *ALL* relevant filters (2 - 5) to match this message
MCP2515_Write_Register(RXF2SIDH, 0x00);
MCP2515_Write_Register(RXF2SIDL, 0x08); // EXIDE bit
MCP2515_Write_Register(RXF2EID8, 0x00);
MCP2515_Write_Register(RXF2EID0, 0x00);
MCP2515_Write_Register(RXF3SIDH, 0x00);
MCP2515_Write_Register(RXF3SIDL, 0x08); // EXIDE bit
MCP2515_Write_Register(RXF3EID8, 0x00);
MCP2515_Write_Register(RXF3EID0, 0x00);
MCP2515_Write_Register(RXF4SIDH, 0x00);
MCP2515_Write_Register(RXF4SIDL, 0x08); // EXIDE bit
MCP2515_Write_Register(RXF4EID8, 0x00);
MCP2515_Write_Register(RXF4EID0, 0x00);
MCP2515_Write_Register(RXF5SIDH, 0x00);
MCP2515_Write_Register(RXF5SIDL, 0x08); // EXIDE bit
MCP2515_Write_Register(RXF5EID8, 0x00);
MCP2515_Write_Register(RXF5EID0, 0x00);
// --- Now set up masks and filters (END) ---
// Interrupts are required if data are in Buffer 1.
// Clear *all* interrupt flags before enabling interrupt
MCP2515_Write_Register(CANINTF, 0x00);
// Enable MCP2510 interrupt generation
// (*Rx only here - no errors, etc *)
// Interrupts from Buffer 1 only
MCP2515_Write_Register(CANINTE, 0x02);
// Prepare 'Ack' message...
// EXTENDED IDs used here
// (ID 0x000000FF used for Ack messages - matches PTTES)
MCP2515_Write_Register(TXB0SIDH, 0x00);
MCP2515_Write_Register(TXB0SIDL, 0x08); // EXIDE bit
MCP2515_Write_Register(TXB0EID8, 0x00);
MCP2515_Write_Register(TXB0EID0, 0xFF);
// Set Normal Mode
MCP2515_Write_Register(CANCTRL, _CANSPI_MODE_NORMAL);
// Number of data bytes
// NOTE: First byte is the slave ID
MCP2515_Write_Register(TXB0DLC, 0x02);
// Initial values of the data bytes
// [Generally only need to change data values and send message]
MCP2515_Write_Register(TXBnDm(0,0), 0x01); // Slave ID
MCP2515_Write_Register(TXBnDm(0,1), 0x02); // Data byte 0, etc...
}
/*-------------MCP2515_SetBitTiming---------------------------
* This function setup the baud rate for the SPI-CAN module.
* Input = rCNF1, mask for configuration register 1
* Input = rCNF2, mask for configuration register 2
* Inout = rCNF3, mask for configuration register 3
* --------------------------------------------------------*/
unsigned char MCP2515_SetBitTiming(unsigned char rCNF1, unsigned char rCNF2, unsigned char rCNF3)
{
//https://www.kvaser.com/support/calculators/bit-timing-calculator/
// Configure to 250kbps (in case of 16 MHz CAN controller clock).
MCP2515_Write_Register(CNF1, rCNF1);
MCP2515_Write_Register(CNF2, rCNF2);
MCP2515_Write_Register(CNF3, rCNF3);
return 0;
}
/*-------------MCP2515_changeBits---------------------------
* This function changes particular bits in the
* specified register
* Input = reg_address
* Input = mask
* Inout = specify value
* --------------------------------------------------------*/
void MCP2515_changeBits(unsigned char reg_address,unsigned char change_bits, unsigned char change_val)
{
unsigned char reg_val, temp;
temp=change_bits & change_val;
reg_val=MCP2515_Read_Register(reg_address);
reg_val=reg_val & 0x1F;
temp=temp|reg_val;
MCP2515_Write_Register(reg_address,temp);
}
/*-------------MCP2515_SetMode---------------------------
* This function set the mode of the MCP2515. The following
modes are possible.
* _CANSPI_MODE_NORMAL 0x00
_CANSPI_MODE_SLEEP 0x20
_CANSPI_MODE_LOOP 0x40
_CANSPI_MODE_LISTEN 0x60
_CANSPI_MODE_CONFIG 0x80
* Input = mode
* Output =void
* --------------------------------------------------------*/
void MCP2515_SetMode(unsigned char mode)
{
MCP2515_changeBits(CANCTRL, (7 << REQOP0),(mode));
while(getMode != (mode>>REQOP0)){
MCP2515_changeBits(CANCTRL, (7 << REQOP0),(mode));
}
}
/*-------------MCP2515_Reset---------------------------
* This function reset SPI-CAN module.
* Input = void
* output = void
* --------------------------------------------------------*/
void MCP2515_Reset()
{
write_data[0]= RESET_INSTRUCTION;
/* Send Reset Instruction */
alt_avalon_spi_command((alt_u32)ALT_SPI_MASTER,
0,1, write_data,0,
read_data,0);
}
/*-------------MCP2515_Read_Register----------------------
* Send reset instruction to the MCP2515. Device should
* reinitialize yourself and go to the configuration mode
* Input = Read Register address
* Output = content of the register
* --------------------------------------------------------*/
tByte MCP2515_Read_Register(const tByte Register_address)
{
tByte Register_contents;
/* Read Instruction */
write_data[0]=READ_INSTRUCTION;
write_data[1]=Register_address;
alt_avalon_spi_command((alt_u32)ALT_SPI_MASTER,
0,2, write_data,1,
read_data,0);
Register_contents=read_data[0];
return Register_contents;
}
/*-------------MCP2515_Read_Rx_Buffer_Register-------------
* Input = instruction
* Output = content of the receive buffer register
* --------------------------------------------------------*/
tByte MCP2515_Read_Rx_Buffer_Register(const tByte instruction)
{
tByte Register_contents;
/* Read Receive Buffer Instruction */
write_data[0]=instruction;
alt_avalon_spi_command((alt_u32)ALT_SPI_MASTER,
0,1, write_data,1,
read_data,0);
Register_contents=read_data[0];
return Register_contents;
}
/*-------------MCP2515_Write_Register-----------------------
* Input = Write Register address
* Input = Write Register contents
* Output= void-------------------------------------------*/
void MCP2515_Write_Register(const tByte Register_address,
const tByte Register_contents)
{
/* Read Receive Buffer Instruction */
write_data[0]=WRITE_BYTE_INSTRUCTION;
write_data[1]=Register_address;
write_data[2]=Register_contents;
alt_avalon_spi_command((alt_u32)ALT_SPI_MASTER,
0,3, write_data,0,
read_data,0);
}
/*-------------MCP2515_RTS_TXB_Instruction_CMD-----------------------
* This function sends request for the transmission of data through
* SPI-CAN module.
* Input = tx_buffer_to_send, Transmit Buffer to send
* Output= void-------------------------------------------*/
void MCP2515_RTS_TXB_Instruction_CMD(const tByte tx_buffer_to_send)
{
/* RTS Transmit Buffer Instruction */
write_data[0]=tx_buffer_to_send;
alt_avalon_spi_command((alt_u32)ALT_SPI_MASTER,
0,1, write_data,0,
read_data,0);
}
/*--------------------------------------------------------*/
<file_sep>public class Lab1 {
String f () {
return "hello world";
}
int sum(int x, int y) {
return x+y;
}
boolean fizz(int x, int y) {
int answer = y/x;
System.out.print(answer);
if(answer == 0)
{
return true;
}
else return false;
}
int cop(int x, int y) {
return -1;
}
}
<file_sep>/*
* adc.c
*
* Created on: 17 March 2018
* Author: nt161
*/
#include "adc.h"
// initialising the external variables
float adc_0_value = 0, adc_1_value = 0, adc_2_value = 0;
float adc0_change_rate = 0, adc1_change_rate = 0, adc2_change_rate = 0;
float average_adc_0 = 0, average_adc_1 = 0, average_adc_2 = 0;
// declaring 3 ring buffers for each adc channel
RingBuffer buffer_adc_0;
RingBuffer buffer_adc_1;
RingBuffer buffer_adc_2;
// initialises the buffer
// setting the head of the buffer
void initialise_buffer(RingBuffer* buf)
{
int i;
buf->head = 0;
for (i=0; i<BUFFER_SIZE; i++) buf->data[i] = 0.0;
}
// a function that adds data to the buffer
// and sets the new head position
void add_to_buffer(RingBuffer* buf, float x)
{
buf->data[buf->head] = x;
buf->head = (buf->head + 1) % BUFFER_SIZE;
}
// a function that gets the most recent value that has been added to the buffer
uint32_t get_most_recent(RingBuffer* buf)
{
if (buf->head == 0) return buf->data[BUFFER_SIZE - 1];
return buf->data[buf->head - 1];
}
// Because this function doesn't change the struct, the parameter can be
// the struct itself, and we use the . notation to get at the head and data.
// this function gets the average of the values in the ring buffer
float get_average(RingBuffer buf)
{
int i;
float average = 0.0;
for (i=0; i<BUFFER_SIZE; i++) average += buf.data[i];
return (average / BUFFER_SIZE);
}
// initialising the adc channels and the ring buffers for each channel
void adc_initialise(void)
{
LPC_SC->PCONP |= 1 << 12;
LPC_PINCON->PINSEL1 = (LPC_PINCON->PINSEL1 & ~(0x3 << 14)) | (0x1 << 14);
LPC_PINCON->PINSEL1 = (LPC_PINCON->PINSEL1 & ~(0x3 << 16)) | (0x1 << 16);
LPC_PINCON->PINSEL1 = (LPC_PINCON->PINSEL1 & ~(0x3 << 18)) | (0x1 << 18);
initialise_buffer(&buffer_adc_0);
initialise_buffer(&buffer_adc_1);
initialise_buffer(&buffer_adc_2);
}
// returns the value that is read from the adc channel
uint32_t adc_read_general(uint8_t channel)
{
LPC_ADC->ADCR = (1 << channel) | (2 << 8) | (1 << 21) | (1 << 24);
// Wait for result - use ADC Global Data Register
while((LPC_ADC->ADGDR & (1 << 31)) == 0);
// Capture complete... Now clear ADCR
LPC_ADC->ADCR = 0;
return (LPC_ADC->ADGDR >> 4) & 0xfff;
}
// function updates values related to adc channel 0
void adc_0_update(void)
{
//reads the current value of adc channel 0
//and stores the value in a variable
adc_0_value = adc_read_general(0);
//stores the rate of change of channel 0 (in volts)
adc0_change_rate = ((adc_0_value - get_most_recent(&buffer_adc_0))/4095.0)*3.3;
//stores the average value of the adc channel readings stored in the buffer
average_adc_0 = get_average(buffer_adc_0);
//adds the new read value to the buffer
add_to_buffer(&buffer_adc_0, adc_0_value);
}
// function updates values related to adc channel 0
void adc_1_update(void)
{
// reads the current value of adc channel 1
// and stores the value in a variable
adc_1_value = adc_read_general(1);
// stores the rate of change of channel 1 (in volts)
adc1_change_rate = ((adc_1_value - get_most_recent(&buffer_adc_1))/4095.0)*3.3;
// stores the average value of the adc channel readings stored in the buffer
average_adc_1 = get_average(buffer_adc_1);
// adds the new read value to the buffer
add_to_buffer(&buffer_adc_1, adc_1_value);
}
// function updates values related to adc channel 2
void adc_2_update(void)
{
// reads the current value of adc channel 2
// and stores the value in a variable
adc_2_value = adc_read_general(2);
// stores the rate of change of channel 2 (in volts)
adc2_change_rate = ((adc_2_value - get_most_recent(&buffer_adc_2))/4095.0)*3.3;
// stores the average value of the adc channel readings stored in the buffer
average_adc_2 = get_average(buffer_adc_2);
// adds the new read value to the buffer
add_to_buffer(&buffer_adc_2, adc_2_value);
}
<file_sep>#ifndef DISP7SEG_HEADER
#define DISP7SEG_HEADER
#include "lpc_types.h"
#include "led7seg.h"
extern uint8_t update_frequency; //this value should be changing from 5 to 15
void SevenSeg_Init(void);
void SevenSeg_Update(void);
#endif
<file_sep>/*
* adc_task.h
*
* Created on: 15 Feb 2018
* Author: nt161
*/
#ifndef ADC_TASK_HEADER
#define ADC_TASK_HEADER
#include "lpc17xx_adc.h"
#include "lpc17xx_pinsel.h"
#include <LPC17xx.h>
extern uint32_t reading_pot;
void adc_init(void);
uint32_t adc_read(void);
void adc_update(void);
#endif /* ADC_TASK_HEADER */
<file_sep>package eMarket;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Calendar;
import java.util.TimeZone;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import eMarket.domain.Role;
import eMarket.domain.Store;
import eMarket.repository.ProductRepository;
import eMarket.repository.RoleRepository;
@SpringBootApplication
public class EMarketApp extends WebMvcConfigurerAdapter implements CommandLineRunner {
@Autowired ProductRepository productRepo;
@Autowired RoleRepository roleRepo;
private static Store store = new Store();
private static LocalDate systemDate;
public final static int ADMIN = 1;
public final static int USER = 2;
public final static int PREMIUM = 3;
public static Store getStore() {
return store;
}
public static void setStore(Store store) {
EMarketApp.store = store;
}
public static LocalDate getSystemDate() {
return systemDate;
}
public static void setSystemDate(LocalDate systemDate) {
EMarketApp.systemDate = systemDate;
}
public static void main(String[] args) {
SpringApplication.run(EMarketApp.class, args);
}
public void run(String... args) {
// initialize calendar
Calendar calendar = Calendar.getInstance();
calendar.setTimeZone(TimeZone.getTimeZone("GMT"));
systemDate = calendar.getTime().toInstant().atZone(ZoneId.of("GMT")).toLocalDate();
roleRepo.save(new Role(ADMIN,"ADMIN"));
roleRepo.save(new Role(USER,"USER"));
roleRepo.save(new Role(PREMIUM,"PREMIUM"));
//
// // PRODUCTS
// Product banana = new Product(0,"Banana","yellow",0.16);
// productRepo.save(banana);
//// EMarketApp.getStore().getProductList().add(banana);
// Product orange = new Product(1,"Orange","Valencian",0.20);
//// EMarketApp.getStore().getProductList().add(orange);
// productRepo.save(orange);
// Product apple = new Product(2,"Apple","Royal Gala",0.25);
//// EMarketApp.getStore().getProductList().add(apple);
// productRepo.save(apple);
//// EMarketApp.getStore().getProductList().add(new Product(3,"Grapes","Red",1.49));
// productRepo.save(new Product(3,"Grapes","Red",1.49));
// Product kiwi = new Product(4,"Kiwi","Green",0.35);
//// EMarketApp.getStore().getProductList().add(kiwi);
// productRepo.save(kiwi);
//// Product.lastId = 5;
//
// // DEALS
// // bananas
// SimpleDateFormat isoFormat = new SimpleDateFormat("dd/MM/yyyy");
// isoFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
// String startDate = "02/08/2017";
// try {
// LocalDate newDate = isoFormat.parse(startDate).toInstant().atZone(ZoneId.of("GMT")).toLocalDate();
//
// Deal deal = new Deal(0,newDate,0.10,banana);
// deal.close();
//// EMarketApp.getStore().getDealList().add(deal);
// dealRepo.save(deal);
// } catch (ParseException e) {
// e.printStackTrace();
// }
// // oranges
// LocalDate today = getSystemDate();
// Deal deal = new Deal(1,today,0.20,orange);
// deal.close();
//// EMarketApp.getStore().getDealList().add(deal);
// dealRepo.save(deal);
// // kiwis
// try {
// LocalDate date1 = isoFormat.parse("01/06/2018").toInstant().atZone(ZoneId.of("GMT")).toLocalDate();
//// last change deal = new Deal(2,date1,0.20,kiwi);
// deal = new Deal(2,date1,0.20,apple);
//// EMarketApp.getStore().getDealList().add(deal);
// dealRepo.save(deal);
//
// date1 = isoFormat.parse("01/01/1965").toInstant().atZone(ZoneId.of("GMT")).toLocalDate();
// deal = new Deal(3,date1,0.20,kiwi);
// date1 = isoFormat.parse("05/01/1965").toInstant().atZone(ZoneId.of("GMT")).toLocalDate();
// deal.setEndDate(date1);
//// EMarketApp.getStore().getDealList().add(deal);
// dealRepo.save(deal);
//
// date1 = isoFormat.parse("02/01/1970").toInstant().atZone(ZoneId.of("GMT")).toLocalDate();
// deal = new Deal(4,date1,0.20,kiwi);
// date1 = isoFormat.parse("04/01/1970").toInstant().atZone(ZoneId.of("GMT")).toLocalDate();
// deal.setEndDate(date1);
//// EMarketApp.getStore().getDealList().add(deal);
// dealRepo.save(deal);
//
// } catch (ParseException e) {
// e.printStackTrace();
// }
// Deal.lastId = 5;
}
}
<file_sep>/*------------------------------------------------------------------*-
LED_flas.C (v1.00)
------------------------------------------------------------------
Simple 'Flash LED' test function.
COPYRIGHT
---------
This code is from the book:
PATTERNS FOR TIME-TRIGGERED EMBEDDED SYSTEMS by <NAME>
[Pearson Education, 2001; ISBN: 0-201-33138-1].
This code is copyright (c) 2001 by <NAME>.
See book for copyright details and other information.
-*------------------------------------------------------------------*/
//#include <altera_avalon_performance_counter.h>
#include <altera_avalon_pio_regs.h>
#include "../ET_TTC_Scheduler/Main.h"
#include "../ET_TTC_Scheduler/Port.h"
#include "system.h"
#include "HEARTBEAT.h"
//extern tByte Tick_message_data_G;
/*------------------------------------------------------------------*-
LED_Flash_Init()
- See below.
-*------------------------------------------------------------------*/
void HEARTBEAT_Init(void)
{
// Tick_message_data_G = 1;
// Do nothing
}
/*------------------------------------------------------------------*-
LED_Flash_Update()
Flashes an LED (or pulses a buzzer, etc) on a specified port pin.
Must call at twice the required flash rate: thus, for 1 Hz
flash (on for 0.5 seconds, off for 0.5 seconds) must schedule
at 2 Hz.
-*------------------------------------------------------------------*/
void HEARTBEAT_Update(void)
{
// Change the LED from OFF to ON (or vice versa)
IOWR_ALTERA_AVALON_PIO_DATA(LED_BASE2,
IORD_ALTERA_AVALON_PIO_DATA(LED_BASE2) ^ LED0_pin);
}
/*------------------------------------------------------------------*-
---- END OF FILE -------------------------------------------------
-*------------------------------------------------------------------*/
<file_sep># CO2006-17-18
This repository is for each student to submit assessed coursework.
By using this repository, I acknowledge that:
* I have signed the [declaration of academic honesty](https://campus.cs.le.ac.uk/ForStudents/plagiarism/DoAIF.pdf) - if you signed this form last year, you don't need to do it again;
* the assessed components of this module correspond to individual assessment;
* that the solution provided for the mini project is the result of my sole individual work.
<file_sep>// pass.cpp
// see website for instructions
//
// Author: nt161
// Version: 1
#include <iostream> // use the standard IO library
#include <string> // use the standard string library
using namespace std;
int main () {
int cw_mark = 0;
int exam_mark = 0;
int cw_mark_cap = 0;
float final_mark = 0;
cout << "Please enter your coursework mark:" << endl;
cin >> cw_mark;
cout << "Please enter your exam mark:" << endl;
cin >> exam_mark;
if(exam_mark <= 25)
{
cw_mark = 50;
}
else
{
cw_mark_cap = 2*exam_mark;
if(cw_mark_cap > 100)
{
cw_mark_cap = 100;
}
}
if(cw_mark > cw_mark_cap)
{
cw_mark = cw_mark_cap;
}
final_mark = (0.6*exam_mark) + (0.4*cw_mark);
if(final_mark<50)
{
cout << "Your module mark is " << final_mark << "\n" << "Unfortunately, you have not passed" << endl;
}
else
{
cout << "Your module mark is " << final_mark << "\n" << "Congratulation, you have passed" << endl;
}
return 0;
}
<file_sep># Makefile
# the C++ compiler
CXX = g++
CC = $(CXX)
# options to pass to the compiler
CXXFLAGS = -Wall -ansi -O2 -g
fillArray : fillArray.o
$(CXX) $(CXXFLAGS) -o fillArray fillArray.o
fillArray.o : fillArray.cpp
$(CXX) $(CXXFLAGS) -c fillArray.cpp
.PHONY : clean
clean :
$(RM) fillArray fillArray.o *~
<file_sep>
#include "../tasks/ssp_config.h"
#include "../scheduler/ttc_scheduler_o.h"
#include "../tasks/disp7seg_update.h"
#include "../tasks/rotary_Update.h"
#include "../tasks/rgb_update.h"
#include "../tasks/joystick_controller.h"
int main (void)
{
com_Init();
RGB_Init();
Joystick_Init();
SevenSeg_Init();
RotaryEncoder_Init();
SCH_Init();
SCH_Add_Task(Joystick_Update, 0, 500);
SCH_Add_Task(Update_Blue, 5, 5);
SCH_Add_Task(Update_Red, 10, 5);
SCH_Add_Task(Update_Green, 15, 5);
SCH_Add_Task(RotaryEncoder_Update, 25, 100);
SCH_Add_Task(SevenSeg_Update, 50, 100);
SCH_Start();
while(1)
{
SCH_Dispatch_Tasks();
}
return 0;
}
void check_failed(uint8_t *file, uint32_t line)
{
/* User can add his own implementation to report the file name and line number,
ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
/* Infinite loop */
while(1);
}
<file_sep>#include "Student.h"
#include "Staff.h"
#include "Project.h"
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <fstream>
#include <map>
#include <memory>
using namespace std;
int score = 0;
map<string, int> supervisors;
map<int, shared_ptr<Project>> projects;
map<string, int> student_allocation;
void findOptimalChoice(shared_ptr<Student> stu) {
int current_choice = stu->getFirstChoice();
shared_ptr<Project> p = projects[stu->getFirstChoice()];
for (int i = 4; i > 0; i--) {
if (p->getMultiplicity() == 0 || supervisors[p->getStaffID()] == 0) {
switch (i) {
case 4:
current_choice = stu->getSecondChoice();
p = projects[current_choice];
break;
case 3:
current_choice = stu->getThirdChoice();
p = projects[current_choice];
break;
case 2:
current_choice = stu->getFourthChoice();
p = projects[current_choice];
break;
case 1:
student_allocation.insert(pair<string, int>(stu->getStudID(), 0));
}
}
else {
p->reduceMultiplicity();
supervisors[p->getStaffID()]--;
student_allocation.insert(pair<string, int>(stu->getStudID(), current_choice));
score += i;
break;
}
}
}
void writeFile(map<string, int> allocation, int tot_score) {
ofstream out("alloc.txt");
for (const auto& x : allocation) {
out << x.first << " " << x.second << "\n";
}
out << tot_score;
}
int main(int argc, const char* argv[]) {
if (argc != 4)
{
cout << "You need to supply 3 arguments to run this program." << endl;
return 0;
}
if ((strcmp(argv[1], "staff.txt") != 0) || (strcmp(argv[2], "projects.txt") != 0) || (strcmp(argv[3], "students.txt") != 0))
{
cout << "Please run the program like so: ./main staff.txt projects.txt students.txt" << endl;
return 0;
}
ifstream staff_file(argv[1]);
string staffContents = "";
while (!staff_file.eof())
{
getline(staff_file, staffContents);
if (staffContents.empty())
{
break;
}
Staff sta(staffContents);
supervisors.insert(pair<string, int>(sta.getStaffID(), sta.getLoad()));
}
staff_file.close();
ifstream project_file(argv[2]);
string projectContents = "";
while (!project_file.eof())
{
getline(project_file, projectContents);
if (projectContents.empty())
{
break;
}
shared_ptr<Project> pro = make_shared<Project>(projectContents);
projects.insert(pair<int, shared_ptr<Project>>(pro->getProjID(), pro));
}
project_file.close();
ifstream student_file(argv[3]);
string studentContents = "";
while (!student_file.eof())
{
getline(student_file, studentContents);
if (studentContents.empty())
{
break;
}
shared_ptr<Student> stu = make_shared<Student>(studentContents);
findOptimalChoice(stu);
}
student_file.close();
writeFile(student_allocation, score);
cout << "Program has completed \nPlease check the directory (where the program is stored) for the produced file alloc.txt" << endl;
}<file_sep>#pragma once
#include <string>
#include <sstream>
using namespace std;
class Student {
public:
Student(const string& studentInfo);
~Student();
string getStudID() const;
int getFirstChoice() const;
int getSecondChoice() const;
int getThirdChoice() const;
int getFourthChoice() const;
private:
string stud_id = "";
int first = -1;
int second = -1;
int third = -1;
int fourth = -1;
};<file_sep>package CO3090.assignment2.server;
import CO3090.assignment2.*;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.rmi.*;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.*;
import java.util.HashMap;
import java.util.Vector;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
//Question (2.3)
public class RFSServer extends UnicastRemoteObject implements RFSInterface
{
public RFSServer() throws RemoteException {
super();
}
public static void main(String[] args) {
if (System.getSecurityManager() == null) {
System.setSecurityManager(new RMISecurityManager());
}
String name = "rmi://localhost/FileSearch";
try {
RFSInterface engine = new RFSServer();
/*complete this method*/
//Registry registry = LocateRegistry.getRegistry(name);
//LocateRegistry.createRegistry(insert portnumber)
Naming.rebind(name, engine);
System.out.println("FileSearch Service bound");
} catch (Exception e) {
System.err.println("FolderSearch exception: " +
e.getMessage());
e.printStackTrace();
}
}
//Question (2.3)
@Override
public Object executeQuery(SearchCriteria searchCriteria) throws RemoteException {
HashMap<String, Vector<FileItem>> map = new HashMap<String, Vector<FileItem>>();
Vector<String> remote_filesystems = FileUtility.readDistributedFilesystemList();
for (String filesystem: remote_filesystems)
{
map.put(filesystem.substring(0, filesystem.lastIndexOf('.')), FileUtility.readFS(FileUtility.fileSystemPath + filesystem));
}
return searchCriteria.execute(map);
}
}
<file_sep>#include "pca9532_leds.h"
//function initialising I2C and the pca9532 LEDs
void pca9532_leds_init()
{
PINSEL_CFG_Type PinCfg;
//Initialize I2C2 pin connect
PinCfg.Funcnum = 2;
PinCfg.Pinnum = 10;
PinCfg.Portnum = 0;
PINSEL_ConfigPin(&PinCfg);
PinCfg.Pinnum = 11;
PINSEL_ConfigPin(&PinCfg);
//Initialize I2C peripheral
I2C_Init(LPC_I2C2, 100000);
//Enable I2C1 operation
I2C_Cmd(LPC_I2C2, ENABLE);
//initialise pca9532 LEDs
pca9532_init();
}
//function controlling the pca9532 LEDs
void pca9532_leds_update()
{
//a variable which stores the potentiometer reading as a floating point number
float float_reading;
//conversion of potentiometer reading to a floating point value between 0.0 and 1.0
float_reading = reading_pot / 4095.0;
//if the joystick is in mode 1
if (mode == 1)
{
//declaring variables that correspond to the LEDs that will be switched on or off
uint16_t on_leds;
uint16_t off_leds;
//variable that will store the potentiometer value as a number between 0 and 16
uint16_t pot_led;
/*converting the value of the floating point potentiometer reading
* into a value between 0 and 16 and assigning the value to a 16 bit integer*/
pot_led = (uint16_t) (float_reading * 16);
/*assigning a single LED to a variable using bit masking and bit shifting to extract the LED
* (from the 16) which corresponds to the voltage of the potentiometer*/
on_leds = 0x0001 << (15 - pot_led) ;
//assigning the rest of the LEDs to a variable
off_leds = ~on_leds;
//assigning which LEDs to turn off and which LED to turn on
pca9532_setLeds(on_leds, off_leds);
}
//if the joystick is in mode 2
if(mode == 2)
{
/*scaling the potentiometer reading to give a valid period with value between 0 - 255
* where 0 means 152 Hz and 255 means 0.59 Hz
* and assigning the value to a variable named period*/
uint8_t period = (uint8_t) (float_reading * 255);
//function which sets all the LEDs to blink
pca9532_setBlink0Leds(0xFFFF);
/*function which sets the LEDs to blink with a certain period
* which is equal to the value stored in the variable named "period"*/
pca9532_setBlink0Period(period);
}
//if the joystick is in mode 3
if (mode == 3)
{
/*scaling the potentiometer reading to give a valid duty cycle with values from 0 - 100 (a percentage)
where where 25 means 25% duty cycle
and assigning the value in a variable called duty*/
uint8_t duty = (uint8_t) (float_reading * 100);
//function which sets all the LEDs to blink
pca9532_setBlink0Leds(0xFFFF);
/*function which sets the LEDs to blink with a certain duty cycle
* which is equal to the value stored in the variable named "duty"*/
pca9532_setBlink0Duty(duty);
}
}
<file_sep>#include <iostream>
#include <vector>
using std::ostream;
using std::vector;
// templated class for a polynomial, with coefficients of type T
// The type T is assumed to have a zero element 0
// Furthermore T is assumed to have implemented:
// the + operator;
// the == operator;
// the << operator.
template<typename T>
class Polynomial {
public:
// Default constructor. Constructs the polynomial "0"
Polynomial() {
// IMPLEMENT ME
this->poly.push_back(0);
this->deg = 0;
}
// Value constructor. Constructs a polynomial based on the vector
// of coefficients, in descending order of exponents.
// For example, if coef contains {0,6,8,9,4}, then it constructs
// the polynomial 6x^3 + 8x^2 + 9x + 4
Polynomial(vector<T> other) {
// IMPLEMENT ME
bool check = true;
for (T o : other)
{
if (!(o == 0) && check || !check)
{
check = false;
deg++;
}
}
deg--;
for (int i = other.size() - 1; i >= 0; i--)
{
poly.push_back(other[i]);
}
}
// default destructor, shallow copy constructor and copy assignment
// should be ok
// Return the degree of the polynomial.
int degree() const {
// IMPLEMENT ME
// below are just stub code
return deg;
}
// Return the coefficient of the x^i term. If i is negative or
// larger than the degree, 0 is returned.
T getCoef(int i) const {
// IMPLEMENT ME
// below are just stub code
if (i < 0 || i > deg)
{
return 0;
}
else
{
return poly[i];
}
}
// Addition of two polynomials. This time it is a member function
Polynomial operator+(const Polynomial& other) const {
// IMPLEMENT ME
// below are just stub code
Polynomial sum;
if (this->poly.size() > other.poly.size())
{
sum.poly.resize(this->poly.size());
}
else
{
sum.poly.resize(other.poly.size());
}
for (int i = 0; i < sum.poly.size(); i++)
{
if (i >= other.poly.size())
{
sum.poly[i] = this->poly[i] + 0;
}
else if (i >= this->poly.size())
{
sum.poly[i] = 0 + other.poly[i];
}
else
{
sum.poly[i] = this->poly[i] + other.poly[i];
}
}
vector<T> temp;
for (int k = sum.poly.size() - 1; k >= 0; k--)
{
temp.push_back(sum.poly[k]);
}
bool check = true;
int new_deg = 0;
for (T p : temp) {
if ((!(p == 0) && check) || !check)
{
check = false;
new_deg++;
}
}
new_deg--;
sum.deg = new_deg;
return sum;
}
// Print the polynomial, in descending order of coefficients and
// with the usual "x^..." terms.
// It is not necessary to print it "pretty".
// For example, if the polynomial is 2x^4 + x^3 - 5x - 1, it is
// sufficient to print it as 2x^4 + 1x^3 + 0x^2 + -5x^1 + -1x^0
// Minor formatting differences will be accepted.
// If you print it pretty you get up to 5 bonus marks (out of 100
// for this task). See the testPrintPretty() test case.
// (This bonus part may not be as easy as it seems...)
friend ostream& operator<<(ostream& os, const Polynomial<T>& p) {
// IMPLEMENT ME
for (int i = p.degree(); i >= 0; i--)
{
if (i == 0)
{
os << p.getCoef(i) << "x^" << i;
}
else
{
os << p.getCoef(i) << "x^" << i << " + ";
}
}
return os;
}
private:
// TODO: add any private variables/functions needed
int deg = 0;
vector<T> poly;
};
<file_sep># Makefile
# the C++ compiler
CXX = g++
CC = $(CXX)
# options to pass to the compiler
CXXFLAGS = -Wall -ansi -O2 -g
pass : pass.o
$(CXX) $(CXXFLAGS) -o pass pass.o
pass.o : pass.cpp
$(CXX) $(CXXFLAGS) -c pass.cpp
.PHONY : clean
clean :
$(RM) pass pass.o *~
<file_sep>/*------------------------------------------------------------------*-
2_50_XXg.C (v1.00)
------------------------------------------------------------------
*** THIS IS A SCHEDULER FOR A NIOS II PROCESSOR ***
*** Uses a full-featured interval timer peripheral ***
*** 50 MHz clock -> 50 ms (precise) tick interval ***
COPYRIGHT
---------
This code is from the book:
PATTERNS FOR TIME-TRIGGERED EMBEDDED SYSTEMS by <NAME>
[Pearson Education, 2001; ISBN: 0-201-33138-1].
This code is copyright (c) 2001 by <NAME>.
See book for copyright details and other information.
-*------------------------------------------------------------------*/
#include <altera_avalon_pio_regs.h>
#include "2_50_XXg.h"
#include "Sch51.h"
#include <sys/alt_irq.h>
#include "../SPImcp2515_slave/spi_mcp2515.h"
#include "system.h"
#include "../TTC_Scheduler_slave/Main.h"
#include "../TTC_Scheduler_slave/PORT.h"
#include "sys/alt_stdio.h"
// ------ Public variable declarations -----------------------------
tByte Tick_message_data_G;
// Data sent from this slave to the master
// - data may be sent on, by the master, to another slave
extern tByte Ack_message_data_G;
/* A variable to hold the value of the button pio edge capture register. */
int context=0;
volatile int edge_capture;
// The array of tasks (see Sch51.C)
extern sTask SCH_tasks_G[SCH_MAX_TASKS];
// Used to display the error code
// See Main.H for details of error codes
// See Port.H for details of the error port
extern tByte Error_code_G;
static void SCH_Update(void *);
/*------------------------------------------------------------------*-
SCH_Init_T2()
Scheduler initialisation function. Prepares scheduler
data structures and sets up timer interrupts at required rate.
You must call this function before using the scheduler.
-*------------------------------------------------------------------*/
void SCH_Init_T0(void)
{
tByte i;
//--- CAN initialisation ---//
MCP2515_Init();
for (i = 0; i < SCH_MAX_TASKS; i++)
{
SCH_Delete_Task(i);
}
// Reset the global error variable
// - SCH_Delete_Task() will generate an error code,
// (because the task array is empty)
Error_code_G = 0;
IOWR_ALTERA_AVALON_PIO_IRQ_MASK(MCP2551_int_n, 1); //PIO_2_BASE for CAN Slave Interrupt
alt_ic_isr_register(0, PIO_2_IRQ, SCH_Update, (void*)&edge_capture, 0);
//alt_printf("S_init\r\n");
}
/*------------------------------------------------------------------*-
SCH_Start()
Starts the scheduler, by enabling interrupts.
NOTE: Usually called after all regular tasks are added,
to keep the tasks synchronised.
NOTE: ONLY THE SCHEDULER INTERRUPT SHOULD BE ENABLED!!!
-*------------------------------------------------------------------*/
void SCH_Start(void)
{
tByte Tick_00, Tick_ID;
tByte Start_slave;
tByte CAN_interrupt_flag;
// We can be at this point because:
// 1. The network has just been powered up
// 2. An error has occurred in the Master, and it is not generating ticks
// 3. The network has been damaged and no ticks are being received by this slave
//
Start_slave = 0;
SCH_Report_Status(); // Sch not yet running - do this manually
// Now wait (indefinitely) for appropriate signal from the master
do {
IOWR_ALTERA_AVALON_PIO_DATA(TEST_1_BASE,
IORD_ALTERA_AVALON_PIO_DATA(TEST_1_BASE) ^ TEST1_pin);
// Wait for CAN message to be received
do {
CAN_interrupt_flag = MCP2515_Read_Register(CANINTF);
} while ((CAN_interrupt_flag & 0x02) == 0);
// Get the first two data bytes
Tick_00 = MCP2515_Read_Register(RXBnDm(1,0)); // Get data byte 0, Buffer 1
Tick_ID = MCP2515_Read_Register(RXBnDm(1,1)); // Get data byte 1, Buffer 1
// We simply clear *ALL* flags here...
MCP2515_Write_Register(CANINTF, 0x00);
if ((Tick_00 == 0x00) && (Tick_ID == SLAVE_ID))
{
// Message is correct
Start_slave = 1;
// Prepare Ack message for transmission to Master
MCP2515_Write_Register(TXBnDm(0,0) , 0x00); // Set data byte 0 (always 0x00)
MCP2515_Write_Register(TXBnDm(0,1) , SLAVE_ID); // Slave ID
/* Send RTS_TXB0_INSTRUCTION Instruction */
MCP2515_RTS_TXB_Instruction_CMD(RTS_INSTRUCTION_TXB0 );
}
else
{
// Not yet received correct message - wait
Start_slave = 0;
}
} while (!Start_slave);
alt_irq_cpu_enable_interrupts(); //can move to down
}
/*------------------------------------------------------------------*-
SCH_Update
This is the scheduler ISR. It is called at a rate
determined by the timer settings in SCH_Init().
This version is triggered by the interval timer interrupts:
the timer is automatically reloaded.
-*------------------------------------------------------------------*/
void SCH_Update(void * context)
{
tByte Index;
//Disable Interrupt for IO Port
IOWR_ALTERA_AVALON_PIO_IRQ_MASK(MCP2551_int_n, 0);
/* Cast context to edge_capture's type. It is important that this be
* declared volatile to avoid unwanted compiler optimization.
*/
volatile int* edge_capture_ptr = (volatile int*) context;
/* Store the value in the Button's edge capture register in *context. */
*edge_capture_ptr = IORD_ALTERA_AVALON_PIO_EDGE_CAP(MCP2551_int_n);
IOWR_ALTERA_AVALON_PIO_EDGE_CAP(MCP2551_int_n,0);
//Enable Interrupt for IO Port
IOWR_ALTERA_AVALON_PIO_IRQ_MASK(MCP2551_int_n,1);
// Check tick data - send ack if necessary
// NOTE: 'START' message will only be sent after a 'time out'
if (SCC_A_SLAVE_Process_Tick_Message() == SLAVE_ID)
{
SCC_A_SLAVE_Send_Ack_Message_To_Master();
}
// NOTE: calculations are in *TICKS* (not milliseconds)
for (Index = 0; Index < SCH_MAX_TASKS; Index++)
{
// Check if there is a task at this location
if (SCH_tasks_G[Index].pTask)
{
if (SCH_tasks_G[Index].Delay == 0)
{
// The task is due to run
SCH_tasks_G[Index].RunMe = 1; // Set the run flag
if (SCH_tasks_G[Index].Period)
{
// Schedule periodic tasks to run again
SCH_tasks_G[Index].Delay = SCH_tasks_G[Index].Period;
}
}
else
{
// Not yet ready to run: just decrement the delay
SCH_tasks_G[Index].Delay -= 1;
}
}
}
//alt_printf("S_update\r\n");
}
/*------------------------------------------------------------------*-
SCC_A_SLAVE_Process_Tick_Message()
The ticks messages are crucial to the operation of this shared-clock
scheduler: the arrival of a tick message (at regular intervals)
invokes the 'Update' ISR, that drives the scheduler.
The tick messages themselves may contain data. These data are
extracted in this function.
-*------------------------------------------------------------------*/
tByte SCC_A_SLAVE_Process_Tick_Message(void)
{
tByte Tick_ID;
// Must have received a message (to generate the 'Tick')
// The first byte is the ID of the slave for which the data are
// intended
Tick_ID = MCP2515_Read_Register(RXBnDm(1,0)); // Get data byte 0 (Slave ID)
if (Tick_ID == SLAVE_ID)
{
// Only if there is a match do we need to copy these fields
Tick_message_data_G = MCP2515_Read_Register(RXBnDm(1,1));
}
// Clear *ALL* flags ...
MCP2515_Write_Register(CANINTF, 0x00);
return Tick_ID;
}
/*------------------------------------------------------------------*-
SCC_A_SLAVE_Send_Ack_Message_To_Master()
Slave must send and 'Acknowledge' message to the master, after
tick messages are received. NOTE: Only tick messages specifically
addressed to this slave should be acknowledged.
The acknowledge message serves two purposes:
[1] It confirms to the master that this slave is alive & well.
[2] It provides a means of sending data to the master and - hence
- to other slaves.
NOTE: Data transfer between slaves is NOT permitted!
-*------------------------------------------------------------------*/
void SCC_A_SLAVE_Send_Ack_Message_To_Master(void)
{
// Prepare Ack message for transmission to Master
// First byte of message must be slave ID
MCP2515_Write_Register(TXBnDm(0,0), SLAVE_ID);
//Ack_message_data_G ='C';
// Now the data
MCP2515_Write_Register(TXBnDm(0,1) , Ack_message_data_G);
/* Send RTS_TXB0_INSTRUCTION Instruction */
MCP2515_RTS_TXB_Instruction_CMD(RTS_INSTRUCTION_TXB0);
}
/*------------------------------------------------------------------*-
---- END OF FILE -------------------------------------------------
-*------------------------------------------------------------------*/
<file_sep>#pragma once
#include <string>
#include <sstream>
using namespace std;
class Project {
public:
Project(const string& projectInfo);
~Project();
int getProjID() const;
string getStaffID() const;
int getMultiplicity() const;
void reduceMultiplicity();
string getProjTitle() const;
private:
int project_id = -1;
string staff_id = "";
int multiplicity = -1;
string proj_title = "";
};
<file_sep>/**
* (C) <NAME>, 2017
*/
package eMarket.controller;
import javax.validation.Valid;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import eMarket.EMarketApp;
@Controller
@RequestMapping("/")
public class IndexController {
@InitBinder
protected void initBinder(WebDataBinder binder) {
binder.addValidators(new IndexValidator());
}
@RequestMapping("/")
public String index(@ModelAttribute("indexFormDto") IndexFormDto indexFormDto) {
indexFormDto.setDate(EMarketApp.getSystemDate());
return "index";
}
@RequestMapping(value = "/setDate", method = RequestMethod.POST)
public String setDate(@Valid @ModelAttribute("indexFormDto") IndexFormDto indexFormDto, BindingResult result, Model model) {
if (!result.hasErrors() ) {
System.out.println("changing date to " + indexFormDto.getDate().toString());
EMarketApp.setSystemDate(indexFormDto.getDate());
}
return "index";
}
}
<file_sep>/*
* rgb_led.c
*
* Created on: 20 March 2018
* Author: nt161
*/
#include "rgb_led.h"
// initialising the RGB led
// and setting it to display green initially when the task is scheduled
void rgb_led_init(void)
{
rgb_init();
rgb_setLeds(RGB_GREEN);
}
// this function checks whether the rate of change of a channel is greater than 0.01 volts
// and if it is then RGB led is set to turn red
// if however the rate of a channel is less than -0.01 volts then the RGB led is set to turn blue
// and in all other cases the RGB led is set to green
void rgb_update (void)
{
if(adc0_change_rate > 0.01 || adc1_change_rate > 0.01 || adc2_change_rate > 0.01)
{
rgb_setLeds(RGB_RED);
}
else if(adc0_change_rate < -0.01 || adc1_change_rate < -0.01 || adc2_change_rate < -0.01)
{
rgb_setLeds(RGB_BLUE);
}
else
{
rgb_setLeds(RGB_GREEN);
}
}
<file_sep>/**
* (C) <NAME>, 2016
*/
package app.controller;
import javax.validation.Valid;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import app.domain.UserInfoLogin;
@Controller
@RequestMapping("/")
public class LoginController {
@InitBinder
protected void initBinder(WebDataBinder binder) {
binder.addValidators(new UserInfoLoginValidator());
}
@RequestMapping("/")
public String index() {
return "Landing";
}
@RequestMapping("/main")
public String main() {
return "Main";
}
@RequestMapping(value = "/login", method = RequestMethod.GET)
public String login(@ModelAttribute("userInfoLogin") UserInfoLogin userInfoLogin) {
return "Login";
}
@RequestMapping(value = "/authenticate", params = "accept", method = RequestMethod.POST)
public String authenticate(@Valid @ModelAttribute("userInfoLogin") UserInfoLogin UserInfoLogin, BindingResult result, Model model) {
if (result.hasErrors()) {
return "Login";
} else {
return "Main";
}
}
@RequestMapping(value = "/authenticate", params = "cancel", method = RequestMethod.POST)
public String cancelAuthenticate(@ModelAttribute("userInfoLogin") UserInfoLogin userInfoLogin, Model model) {
return "Landing";
}
@RequestMapping("/logoff")
public String logoff() {
return "Landing";
}
}
<file_sep>#ifndef _SPI_MCP2515_H
#define _SPI_MCP2515_H
#include "../TTC_Scheduler_slave/Main.h"
#define SPI_NUM_DEVICES 1
//--------------------------------------------------------
// SPI Commands to MCP2510
//--------------------------------------------------------
#define RESET_INSTRUCTION 0xC0 // Instruction for immediate reset
#define READ_INSTRUCTION 0x03 // Read register
#define WRITE_BYTE_INSTRUCTION 0x02 // Write register
#define READRX_INSTRUCTION 0x90 // 10010mn0 - m,n is address of the RX buffer
#define LOADTX_INSTRUCTION 0x40 // 01000abc - a,b,c is address of the TX buffer
#define RTS_INSTRUCTION_TXB0 0x81 // 10000abc - a,b,c is address of the TX buffer
#define RTS_INSTRUCTION_TXB1 0x82 // 10000abc - a,b,c is address of the TX buffer
#define RTS_INSTRUCTION_TXB2 0x84 // 10000abc - a,b,c is address of the TX buffer
#define READSTAT_INSTRUCTION 0xA0 // Read device status instructio
#define RXSTAT_INSTRUCTION 0xB0 // Read receive buffer status instruction
#define BITMODIFY_INSTRUCTION 0x05 // For specific bit modifications
// Flags in the result of READ STATE instruction
// (Can be used as bit masks for each flag)
#define STATE_RX0_FULL (0x01 << 0) // 00000001
#define STATE_RX1_FULL (0x01 << 1) // 00000010
#define STATE_TX0_TXREQ (0x01 << 2) // 00000100
#define STATE_TX0_EMPTY (0x01 << 3) // 00001000
#define STATE_TX1_TXREQ (0x01 << 4) // 00010000
#define STATE_TX1_EMPTY (0x01 << 5) // 00100000
#define STATE_TX2_TXREQ (0x01 << 6) // 01000000
#define STATE_TX2_EMPTY (0x01 << 7) // 10000000
#define LOAD_TX_BUFFER_TXB0SIDH 0x40
#define LOAD_TX_BUFFER_TXB0D0 0x41
#define LOAD_TX_BUFFER_TXB1SIDH 0x42
#define LOAD_TX_BUFFER_TXB1D0 0x43
#define LOAD_TX_BUFFER_TXB2SIDH 0x44
#define LOAD_TX_BUFFER_TXB2D0 0x45
#define RTS_TXB0_INSTRUCTION 0x81
#define RTS_TXB1_INSTRUCTION 0x82
#define RTS_TXB2_INSTRUCTION 0x84
//--------------------------------------------------------
// MCP2510 Registers
//--------------------------------------------------------
/*Bit definitions for register CNF1
(MCP2515 Configuration 1 register)*/
#define CNF1 0x2A
#define SJW1 7 // RW-0, Synchronization jump width length bit 1
#define SJW0 6 // RW-0, Synchronization jump width length bit 0
#define BRP5 5 // RW-0, Baud rate prescaler bit 5
#define BRP4 4 // RW-0, Baud rate prescaler bit 4
#define BRP3 3 // RW-0, Baud rate prescaler bit 3
#define BRP2 2 // RW-0, Baud rate prescaler bit 2
#define BRP1 1 // RW-0, Baud rate prescaler bit 1
#define BRP0 0 // RW-0, Baud rate prescaler bit 0
/*Bit definitions for register CNF2
(MCP2515 Configuration 2 register)*/
#define CNF2 0x29
#define BTLMODE 7 // RW-0, PS bit time length bit
#define SAM 6 // RW-0, Sample point configuration bit
#define PHSEG12 5 // RW-0, PS1 length bit 2
#define PHSEG11 4 // RW-0, PS1 length bit 1
#define PHSEG10 3 // RW-0, PS1 length bit 0
#define PRSEG2 2 // RW-0, Propagation segment length bit 2
#define PRSEG1 1 // RW-0, Propagation segment length bit 1
#define PRSEG0 0 // RW-0, Propagation segment length bit 0
// Bit definitions for register CNF3
// (MCP2515 Configuration 3 register)
#define CNF3 0x28
#define SOF 7 // RW-0, Start of frame signal bit
#define WAKFIL 6 // RW-0, Wake-up filter bit
#define PHSEG22 2 // RW-0, PS2 bit 2
#define PHSEG21 1 // RW-0, PS2
#define PHSEG20 0 // RW-0, PS2
/* Bit definitions for register CANCTRL
(MCP2515 CAN control register)*/
#define CANCTRL 0x0F
#define REQOP2 7 // RW-1, Request operation mode bit 2
#define REQOP1 6 // RW-0, Request operation mode bit 1
#define REQOP0 5 // RW-0, Request operation mode bit 0
#define ABAT 4 // RW-0, Abort all pending transmissions bit
#define OSM 3 // RW-0, One shot mode
#define CLKEN 2 // RW-1, CLKOUT pin enable
#define CLKPRE1 1 // RW-1, CLKOUT pin prescaler 1
#define CLKPRE0 0 // RW-1, CLKOUT pin prescaler 0
/*Bit definitions for register CANSTAT
(MCP2515 CAN status register)*/
#define CANSTAT 0x0E
#define OPMOD2 7 // R-1, Operation mode bit 2
#define OPMOD1 6 // R-0, Operation mode bit 1
#define OPMOD0 5 // R-0, Operation mode bit 0
#define ICOD2 3 // R-0, Interrupt flag code bit 2
#define ICOD1 2 // R-0, Interrupt flag code bit 1
#define ICOD0 1 // R-0, Interrupt flag code bit 0
/* Bit definitions for registers TXBnCTRL
(MCP2515 Transmit buffer n control register)*/
#define TXBnCTRL(n) 0x30+(n*0x10)
#define TXB0CTRL TXBnCTRL(0)
#define TXB1CTRL TXBnCTRL(1)
#define TXB2CTRL TXBnCTRL(2)
#define ABTF 6 // R-0, Message aborted flag bit
#define MLOA 5 // R-0, Message lost arbitration bit
#define TXERR 4 // R-0, Transmit error detected bit
#define TXREQ 3 // RW-0, Message transmit request bit
#define TXP1 1 // RW-0, Transmit buffer priority bit 1
#define TXP0 0 // RW-0, Transmit buffer priority bit
/*Bit definitions for registers TXBnDLC
(MCP2515 Transmit buffer data length control)*/
#define TXBnDLC(n) 0x35+(n*0x10)
#define TXB0DLC TXBnDLC(0)
#define TXB1DLC TXBnDLC(1)
#define TXB2DLC TXBnDLC(2)
#define RTR 6 // RW-x, Remote transfer request
#define DLC3 3 // RW-x, Data length code bit 3
#define DLC2 2 // RW-x, Data length code bit 2
#define DLC1 1 // RW-x, Data length code bit 1
#define DLC0 0 // RW-x, Data length code bit 0
/*Bit definitions for register TXBnSIDH
(MCP2515 Transmit buffer n - standard identifier high)*/
#define TXBnSIDH(n) 0x31+(n*0x10)
#define TXB0SIDH TXBnSIDH(0)
#define TXB1SIDH TXBnSIDH(1)
#define TXB2SIDH TXBnSIDH(2)
#define SID10 7 // RW-x, Standard identifier, bit 10
#define SID9 6 // RW-x, Standard identifier, bit 9
#define SID8 5 // RW-x, Standard identifier, bit 8
#define SID7 4 // RW-x, Standard identifier, bit 7
#define SID6 3 // RW-x, Standard identifier, bit 6
#define SID5 2 // RW-x, Standard identifier, bit 5
#define SID4 1 // RW-x, Standard identifier, bit 4
#define SID3 0 // RW-x, Standard identifier, bit 3
/*Bit definitions for register TXBnSIDL
(MCP2515 Transmit buffer n - standard identifier low)*/
#define TXBnSIDL(n) 0x32+(n*0x10)
#define TXB0SIDL TXBnSIDL(0)
#define TXB1SIDL TXBnSIDL(1)
#define TXB2SIDL TXBnSIDL(2)
#define SID2 7 // RW-x, Standard identifier, bit 2
#define SID1 6 // RW-x, Standard identifier, bit 1
#define SID0 5 // RW-x, Standard identifier, bit 0
#define EXIDE 3 // RW-x, Extended identifier enable bit
#define EID17 1 // RW-x, Extended identifier, bit 17
#define EID16 0 // RW-x, Extended identifier, bit 16
/*Bit definitions for register TXBnEID8
(MCP2515 Transmit buffer n - extended identifier high)*/
#define TXBnEID8(n) 0x33+(n*0x10)
#define TXB0EID8 TXBnEID8(0)
#define TXB1EID8 TXBnEID8(1)
#define TXB2EID8 TXBnEID8(2)
#define EID15 7 // RW-x, Extended identifier, bit 15
#define EID14 6 // RW-x, Extended identifier, bit 14
#define EID13 5 // RW-x, Extended identifier, bit 13
#define EID12 4 // RW-x, Extended identifier, bit 12
#define EID11 3 // RW-x, Extended identifier, bit 11
#define EID10 2 // RW-x, Extended identifier, bit 10
#define EID9 1 // RW-x, Extended identifier, bit 9
#define EID8 0 // RW-x, Extended identifier, bit 8
/*Bit definitions for register TXBnEID0
(Transmit buffer n - extended identifier high)*/
#define TXBnEID0(n) 0x34+(n*0x10)
#define TXB0EID0 TXBnEID0(0)
#define TXB1EID0 TXBnEID0(1)
#define TXB2EID0 TXBnEID0(2)
#define EID7 7 // RW-x, Extended identifier, bit 7
#define EID6 6 // RW-x, Extended identifier, bit 6
#define EID5 5 // RW-x, Extended identifier, bit 5
#define EID4 4 // RW-x, Extended identifier, bit 4
#define EID3 3 // RW-x, Extended identifier, bit 3
#define EID2 2 // RW-x, Extended identifier, bit 2
#define EID1 1 // RW-x, Extended identifier, bit 1
#define EID0 0 // RW-x, Extended identifier, bit 0
/* Bit definitions for registers TXBnDm
(MCP2515 Transmit buffer N data byte M) */
#define TXBnDm(n,m) 0x36+(n*0x10)+m
#define TXBnDm7 7 // RW-x, Transmit buffer N, data byte M, bit 7
#define TXBnDm6 6 // RW-x, Transmit buffer N, data byte M, bit 6
#define TXBnDm5 5 // RW-x, Transmit buffer N, data byte M, bit 5
#define TXBnDm4 4 // RW-x, Transmit buffer N, data byte M, bit 4
#define TXBnDm3 3 // RW-x, Transmit buffer N, data byte M, bit 3
#define TXBnDm2 2 // RW-x, Transmit buffer N, data byte M, bit 2
#define TXBnDm1 1 // RW-x, Transmit buffer N, data byte M, bit 1
#define TXBnDm0 0 // RW-x, Transmit buffer N, data byte M, bit 0
/* Bit definitions for register TXRTSCTRL
(MCP2515 TXn buffer pin control and status)*/
#define TXRTSCTRL 0x0D
#define B2RTS 5 // R, TX2RTS pin state bit
#define B1RTS 4 // R, TX1RTS pin state bit
#define B0RTS 3 // R, TX0RTS pin function enable bit
#define B2RTSM 2 // RW-0, TX2RTS pin mode bit
#define B1RTSM 1 // RW-0, TX1RTS pin mode bit
#define B0RTSM 0 // RW-0, TX0RTS pin mode bit
// Bit definitions for registers RXBnCTRL
// (Receive buffer n control register)
#define RXBnCTRL(n) 0x60+(n*0x10)
#define RXB0CTRL RXBnCTRL(0)
#define RXB1CTRL RXBnCTRL(1)
#define RXM1 6 // RW-0, Receive buffer operating mode bit 1
#define RXM0 5 // RW-0, Receive buffer operating mode bit 0
#define RXRTR 3 // R-0, Receive remote transfer request bit
#define BUKT 2 // RW-0, Rollover enable bit (used only by RXB0CTRL)
#define FILHIT2 2 // R-0, Filter hit bit 2 (used only by RXB1CTRL)
#define FILHIT1 1 // R-0, Filter hit bit 1 (used only by RXB1CTRL)
#define FILHIT0 0 // R-0, Filter hit bit
// Bit definitions for registers RXBnSIDH
// (Receive buffer n standard identifier high)
#define RXBnSIDH(n) 0x61+(n*0x10)
#define RXB0SIDH RXBnSIDH(0)
#define RXB1SIDH RXBnSIDH(1)
#define SID10 7 // RW-x, Standard identifier, bit 10
#define SID9 6 // RW-x, Standard identifier, bit 9
#define SID8 5 // RW-x, Standard identifier, bit 8
#define SID7 4 // RW-x, Standard identifier, bit 7
#define SID6 3 // RW-x, Standard identifier, bit 6
#define SID5 2 // RW-x, Standard identifier, bit 5
#define SID4 1 // RW-x, Standard identifier, bit 4
#define SID3 0 // RW-x, Standard identifier, bit 3
// Bit definitions for register RXBnSIDL
// (Receive buffer n - standard identifier low)
#define RXBnSIDL(n) 0x62+(n*0x10)
#define RXB0SIDL RXBnSIDL(0)
#define RXB1SIDL RXBnSIDL(1)
#define SID2 7 // RW-x, Standard identifier, bit 2
#define SID1 6 // RW-x, Standard identifier, bit 1
#define SID0 5 // RW-x, Standard identifier, bit 0
#define SRR 4 // RW-x, Standard frame remote transmit request bit, bit 1
#define IDE 3 // RW-x, Extanded identifier flag bit, bit 0
#define EID17 1 // RW-x, Extended identifier, bit 17
#define EID16 0 // RW-x, Extended identifier, bit 16
// Bit definitions for register RXBnEID8
// (Revceive buffer n - extended identifier high)
#define RXBnEID8(n) 0x63+(n*0x10)
#define RXB0EID8 RXBnEID8(0)
#define RXB1EID8 RXBnEID8(1)
#define EID15 7 // RW-x, Extended identifier, bit 15
#define EID14 6 // RW-x, Extended identifier, bit 14
#define EID13 5 // RW-x, Extended identifier, bit 13
#define EID12 4 // RW-x, Extended identifier, bit 12
#define EID11 3 // RW-x, Extended identifier, bit 11
#define EID10 2 // RW-x, Extended identifier, bit 10
#define EID9 1 // RW-x, Extended identifier, bit 9
#define EID8 0 // RW-x, Extended identifier, bit 8
// Bit definitions for register RXBnEID0
// (Receive buffer n - extended identifier high)
#define RXBnEID0(n) 0x64+(n*0x10)
#define RXB0EID0 RXBnEID0(0)
#define RXB1EID0 RXBnEID0(1)
#define EID7 7 // RW-x, Extended identifier, bit 7
#define EID6 6 // RW-x, Extended identifier, bit 6
#define EID5 5 // RW-x, Extended identifier, bit 5
#define EID4 4 // RW-x, Extended identifier, bit 4
#define EID3 3 // RW-x, Extended identifier, bit 3
#define EID2 2 // RW-x, Extended identifier, bit 2
#define EID1 1 // RW-x, Extended identifier, bit 1
#define EID0 0 // RW-x, Extended identifier, bit 0
// Bit definitions for registers RXBnDLC
// (Receive buffer data length control)
#define RXBnDLC(n) 0x65+(n*0x10)
#define RXB0DLC RXBnDLC(0)
#define RXB1DLC RXBnDLC(1)
#define RTR 6 // RW-x, Remote transfer request
#define DLC3 3 // RW-x, Data length code bit 3
#define DLC2 2 // RW-x, Data length code bit 2
#define DLC1 1 // RW-x, Data length code bit 1
#define DLC0 0 // RW-x, Data length code bit 0
// Bit definitions for registers RXBnDm
// (Receive buffer N data byte M)
#define RXBnDm(n,m) 0x66 + (n*0x10) + m
#define RXBnDm7 7 // RW-x, Receive buffer N, data byte M, bit 7
#define RXBnDm6 6 // RW-x, Receive buffer N, data byte M, bit 6
#define RXBnDm5 5 // RW-x, Receive buffer N, data byte M, bit 5
#define RXBnDm4 4 // RW-x, Receive buffer N, data byte M, bit 4
#define RXBnDm3 3 // RW-x, Receive buffer N, data byte M, bit 3
#define RXBnDm2 2 // RW-x, Receive buffer N, data byte M, bit 2
#define RXBnDm1 1 // RW-x, Receive buffer N, data byte M, bit 1
#define RXBnDm0 0 // RW-x, Receive buffer N, data b
// Bit definitions for registers RXFnSIDH
// (Filter n standard identifier high)
#define RXFnSIDH(n) 0+(n*4)+((n>2)?4:0)
#define RXF0SIDH RXFnSIDH(0)
#define RXF1SIDH RXFnSIDH(1)
#define RXF2SIDH RXFnSIDH(2)
#define RXF3SIDH RXFnSIDH(3)
#define RXF4SIDH RXFnSIDH(4)
#define RXF5SIDH RXFnSIDH(5)
// Bit definitions for register RXFnSIDL
// (Filter n - standard identifier low)
#define RXFnSIDL(n) 1+(n*4)+((n>2)?4:0)
#define RXF0SIDL RXFnSIDL(0)
#define RXF1SIDL RXFnSIDL(1)
#define RXF2SIDL RXFnSIDL(2)
#define RXF3SIDL RXFnSIDL(3)
#define RXF4SIDL RXFnSIDL(4)
#define RXF5SIDL RXFnSIDL(5)
// Bits are same as in TXBnSIDL
// Bit definitions for register RXFnEID8
// (Filter n - extended identifier high)
#define RXFnEID8(n) 2+(n*4)+((n>2)?4:0)
#define RXF0EID8 RXFnEID8(0)
#define RXF1EID8 RXFnEID8(1)
#define RXF2EID8 RXFnEID8(2)
#define RXF3EID8 RXFnEID8(3)
#define RXF4EID8 RXFnEID8(4)
#define RXF5EID8 RXFnEID8(5)
// Bits EID15-EID8 are same as in TXBnEID8
// Bit definitions for register RXFnEID0
// (Filter buffer n - extended identifier low)
#define RXFnEID0(n) 3+(n*4)+((n>2)?4:0)
#define RXF0EID0 RXFnEID0(0)
#define RXF1EID0 RXFnEID0(1)
#define RXF2EID0 RXFnEID0(2)
#define RXF3EID0 RXFnEID0(3)
#define RXF4EID0 RXFnEID0(4)
#define RXF5EID0 RXFnEID0(5)
// Bits EID7-EID0 are same as in TXBnEID0
// Bit definitions for registers RXMnSIDH
// (Mask n standard identifier high)
#define RXMnSIDH(n) 0x20+(n*4)
#define RXM0SIDH RXMnSIDH(0)
#define RXM1SIDH RXMnSIDH(1)
// Bits are same as in TXBnSIDH
// Bit definitions for register RXMnSIDL
// (Mask n - standard identifier low)
#define RXMnSIDL(n) 0x21+(n*4)
#define RXM0SIDL RXMnSIDL(0)
#define RXM1SIDL RXMnSIDL(1)
// Bits are same as in TXBnSIDL
// Bit definitions for register RXMnEID8
// (Filter n - extended identifier high)
#define RXMnEID8(n) 0x22+(n*4)
#define RXM0EID8 RXMnEID8(0)
#define RXM1EID8 RXMnEID8(1)
// Bits EID15-EID8 are same as in TXBnEID8
// Bit definitions for register RXMnEID0
// (Filter buffer n - extended identifier high)
#define RXMnEID0(n) 0x23+(n*4)
#define RXM0EID0 RXMnEID0(0)
#define RXM1EID0 RXMnEID0(1)
// Bits EID7-EID0 are same as in TXBnEID0
// Indexes of RX and TX buffers
#define NO_FILTERS 6
#define NO_MASKS 2
#define NO_TX_BUFFERS 3
#define NO_RX_BUFFERS 2
#define TXB0 0 // Transmit buffer 0
#define TXB1 1 // Transmit buffer 1
#define TXB2 2 // Transmit buffer 2
#define RXB0 0 // Receive buffer 0
#define RXB1 1 //
/*Bit definitions for register CANINTE
(MCP2515 Interrupt enable register)*/
#define CANINTE 0x2B
#define MERRE 7 // RW-0, Message error interrupt enable bit
#define WAKIE 6 // RW-0, Wakeup interrupt enable bit
#define ERRIE 5 // RW-0, Error interrupt enable bit
#define TX2IE 4 // RW-0, Transmit buffer 2 empty interrupt enable bit
#define TX1IE 3 // RW-0, Transmit buffer 1 empty interrupt enable bit
#define TX0IE 2 // RW-0, Transmit buffer 0 empty interrupt enable bit
#define RX1IE 1 // RW-0, Receive buffer 1 full interrupt enable bit
#define RX0IE 0 // RW-0, Receive buffer 0 full interrupt enable bit
/*Bit definitions for register CANINTF
(MCP2515 Interrupt flag register)*/
#define CANINTF 0x2C
#define MERRF 7 // RW-0, Message error interrupt flag bit
#define WAKIF 6 // RW-0, Wakeup interrupt flag bit
#define ERRIF 5 // RW-0, Error interrupt flag bit
#define TX2IF 4 // RW-0, Transmit buffer 2 empty interrupt flag bit
#define TX1IF 3 // RW-0, Transmit buffer 1 empty interrupt flag bit
#define TX0IF 2 // RW-0, Transmit buffer 0 empty interrupt flag bit
#define RX1IF 1 // RW-0, Receive buffer 1 full interrupt flag bit
#define RX0IF 0 // RW-0, Receive buffer 0 full interrupt flag bit
/* Bit definitions for register EFLG
(Error flag register)*/
#define EFLG 0x2D
#define RX1OVR 7 // RW-0, Receive buffer 1 overflow flag bit
#define RX0OVR 6 // RW-0, Receive buffer 0 overflow flag bit
#define TXBO 5 // R-0, Bus-off error flag bit
#define TXEP 4 // R-0, Transmit error - passive flag bit
#define RXEP 3 // R-0, Receive error - passive flag bit
#define TXWAR 2 // R-0, Transmit error warning flag bit
#define RXWAR 1 // R-0, Receive error warning flag bit
#define EWARN 0 // R-0, Error warning flag bit
/* CANSPI_OP_MODE */
/* The CANSPI_OP_MODE constants define CANSPI
* operation mode. Function CANSPISetOperationMode
* expects one of these as it's argument: */
#define _CANSPI_MODE_BITS 0xE0 //Use this to access opmode bits
#define _CANSPI_MODE_NORMAL 0x00
#define _CANSPI_MODE_SLEEP 0x20
#define _CANSPI_MODE_LOOP 0x40
#define _CANSPI_MODE_LISTEN 0x60
#define _CANSPI_MODE_CONFIG 0x80
/*CANSPI_CONFIG_FLAGS
The CANSPI_CONFIG_FLAGS constants define flags
* related to the CANSPI module configuration.
* The functions CANSPIInitialize, CANSPISetBaudRate,
* CANSPISetMask and CANSPISetFilter expect one of these
* (or a bitwise combination) as their argument:*/
#define _CANSPI_CONFIG_DEFAULT 0xFF // 11111111
#define _CANSPI_CONFIG_PHSEG2_PRG_BIT 0x01
#define _CANSPI_CONFIG_PHSEG2_PRG_ON 0xFF // XXXXXXX1
#define _CANSPI_CONFIG_PHSEG2_PRG_OFF 0xFE // XXXXXXX0
#define _CANSPI_CONFIG_LINE_FILTER_BIT 0x02
#define _CANSPI_CONFIG_LINE_FILTER_ON 0xFF // XXXXXX1X
#define _CANSPI_CONFIG_LINE_FILTER_OFF 0xFD // XXXXXX0X
#define _CANSPI_CONFIG_SAMPLE_BIT 0x04
#define _CANSPI_CONFIG_SAMPLE_ONCE 0xFF // XXXXX1XX
#define _CANSPI_CONFIG_SAMPLE_THRICE 0xFB // XXXXX0XX
#define _CANSPI_CONFIG_MSG_TYPE_BIT 0x08
#define _CANSPI_CONFIG_STD_MSG 0xFF // XXXX1XXX
#define _CANSPI_CONFIG_XTD_MSG 0xF7 // XXXX0XXX
#define _CANSPI_CONFIG_DBL_BUFFER_BIT 0x10
#define _CANSPI_CONFIG_DBL_BUFFER_ON 0xFF // XXX1XXXX
#define _CANSPI_CONFIG_DBL_BUFFER_OFF 0xEF // XXX0XXXX
#define _CANSPI_CONFIG_MSG_BITS 0x60
#define _CANSPI_CONFIG_ALL_MSG 0xFF // X11XXXXX
#define _CANSPI_CONFIG_VALID_XTD_MSG 0xDF // X10XXXXX
#define _CANSPI_CONFIG_VALID_STD_MSG 0xBF // X01XXXXX
#define _CANSPI_CONFIG_ALL_VALID_MSG 0x9F // X00XXXXX
/* CANSPI_TX_MSG_FLAGS
CANSPI_TX_MSG_FLAGS are flags related to
* transmission of a CANSPI message:*/
#define _CANSPI_TX_PRIORITY_BITS 0x03
#define _CANSPI_TX_PRIORITY_0 0xFC // XXXXXX00
#define _CANSPI_TX_PRIORITY_1 0xFD // XXXXXX01
#define _CANSPI_TX_PRIORITY_2 0xFE // XXXXXX10
#define _CANSPI_TX_PRIORITY_3 0xFF // XXXXXX11
#define _CANSPI_TX_FRAME_BIT 0x08
#define _CANSPI_TX_STD_FRAME 0xFF // XXXXX1XX
#define _CANSPI_TX_XTD_FRAME 0xF7 // XXXXX0XX
#define _CANSPI_TX_RTR_BIT 0x40
#define _CANSPI_TX_NO_RTR_FRAME 0xFF // X1XXXXXX
#define _CANSPI_TX_RTR_FRAME 0xBF // X0XXXXXX
/* CANSPI_RX_MSG_FLAGS
CANSPI_RX_MSG_FLAGS are flags related to
* reception of CANSPI message. If a particular bit
* is set then corresponding meaning is TRUE otherwise
* it will be FALSE.*/
#define _CANSPI_RX_FILTER_BITS 0x07 // Use this to access filter bits
#define _CANSPI_RX_FILTER_1 0x00
#define _CANSPI_RX_FILTER_2 0x01
#define _CANSPI_RX_FILTER_3 0x02
#define _CANSPI_RX_FILTER_4 0x03
#define _CANSPI_RX_FILTER_5 0x04
#define _CANSPI_RX_FILTER_6 0x05
#define _CANSPI_RX_OVERFLOW 0x08 // Set if Overflowed else cleared
#define _CANSPI_RX_INVALID_MSG 0x10 // Set if invalid else cleared
#define _CANSPI_RX_XTD_FRAME 0x20 // Set if XTD message else cleared
#define _CANSPI_RX_RTR_FRAME 0x40 // Set if RTR message else cleared
#define _CANSPI_RX_DBL_BUFFERED 0x80 // Set if this message was hardware double-buffered
/*CANSPI_FILTER
The CANSPI_FILTER constants define filter codes.
* Functions CANSPISetFilter expects one of these as it's argument:
*/
#define _CANSPI_FILTER_B1_F1 0
#define _CANSPI_FILTER_B1_F2 1
#define _CANSPI_FILTER_B2_F1 2
#define _CANSPI_FILTER_B2_F2 3
#define _CANSPI_FILTER_B2_F3 4
#define _CANSPI_FILTER_B2_F4 5
void CANSPISetOperationMode(unsigned char mode,unsigned char WAIT);
void CANSPISetFilter(unsigned short CANSPI_FILTER, long value, unsigned short CANSPI_CONFIG_FLAGS);
unsigned short CANSPIRead(long *id, unsigned short *data, unsigned short *datalen, unsigned short *CANSPI_RX_MSG_FLAGS);
unsigned short CANSPIWrite(long id, unsigned short *data, unsigned short datalen, unsigned short CANSPI_TX_MSG_FLAGS);
unsigned char MCP2515_SetBitTiming(unsigned char rCNF1, unsigned char rCNF2, unsigned char rCNF3);
void MCP2515_changeBits(unsigned char reg_address,unsigned char change_bits, unsigned char change_val);
void MCP2515_Reset(void);
void MCP2515_Init(void);
tByte MCP2515_Read_Register(const tByte Register_address);
void MCP2515_Write_Register(const tByte Register_address, const tByte Register_contents);
void MCP2515_RTS_TXB_Instruction_CMD(const tByte tx_buffer);
void MCP2515_SetMode(unsigned char mode);
/* Macros */
#define getMode (MCP2515_Read_Register(CANSTAT) >> 5)
#endif
<file_sep>/**
* Voter
*
* Program which handles the clients
*
* @author nt161
* @version $Id: Voter.java 26-04-18 nt161 $
*
*/
package CO2017.exercise3.nt161;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
/**
* Class representing communication from client side
*/
public class Voter {
// data sent by client
private static char client_vote; // the client's vote
private static int client_vid; // the client's voter ID
private static int client_bnum; // the client's ballot number
// The values that are generated by the server.
private static char server_vote; // the server's vote
private static int server_vid; // the server's voter ID
private static int server_bnum; // the server's ballot number
// port and server address for the command line arguments
private static int port;
private static String serverAddress;
public static void main (String args[]) throws IOException{
// the first command line argument is the server address
serverAddress = args[0];
// the second command line argument is the port
port = Integer.valueOf(args[1]);
String line_fromServer ; // line received from the server
String[] cl_s_comm; // communication array between server and client
String server_message; // final message from the server
// creating a new socket which is listening to the server
try(Socket server = new Socket(serverAddress, port);){
// buffered reader that reads input from the server
BufferedReader in = new BufferedReader(new InputStreamReader(server.getInputStream()));
// writer that sends information to the server
Writer server_out = new OutputStreamWriter(server.getOutputStream());
// another buffered reader that reads data entered by client
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
// prints out that the connection to the server has been established
System.out.println("Connected to "+ server.getInetAddress());
// asks the client to enter voter ID
System.out.print("Enter voter ID: ");
// saves the value of the client's voter ID
client_vid = Integer.parseInt(stdin.readLine());
// sends the client id to the server
server_out.write(client_vid + "\r\n");
server_out.flush();
// if the client voter ID is not equal to 0
if (0 != client_vid){
// then the server response is read by the client
line_fromServer = in.readLine();
// this ensures that the message received is split into separate chunks
// using the colon as a delimiter
cl_s_comm = line_fromServer.split(":");
// the first value received from the server is the voter id
server_vid = Integer.valueOf(cl_s_comm[0]);
// the second value is the client ballot number
client_bnum = Integer.valueOf(cl_s_comm[1]);
// the last value is the message from the server
server_message = cl_s_comm[2];
// if the server message is equal to DUPLICATE
if (server_message.equals("DUPLICATE")){
// prints out the client voter ID and an error message
System.out.println(client_vid + " voter already voted : VOTE REJECTED.");
// closes the server
server.close();
}
// if the server message is equal to INVALID_VID i.e. invalid voter ID
else if (server_message.equals("INVALID_VID")){
// prints out the client voter ID and an error message
System.out.println(client_vid + " invalid voter : VOTE REJECTED.");
// closes the server
server.close();
}
else {
// otherwise prints out the client voter id and ballot number
System.out.println(client_vid + ":" + client_bnum);
}
// this ensures that as long as the line does not reach 0:END
// the client continues to listen to the socket and
// prints the information sent from the server
// this is for the ballot paper
while(!(line_fromServer = in.readLine()).equals("0:END")){
System.out.println(line_fromServer);
}
// client is asked to enter vote
System.out.println("Enter vote: ");
// client's vote is stored
client_vote = stdin.readLine().charAt(0);
// the client voter ID, ballot number and vote are sent to the server
server_out.write(client_vid + ":" + client_bnum + ":" + client_vote + "\r\n");
server_out.flush();
line_fromServer = in.readLine(); // again the server information is read by the client
cl_s_comm = line_fromServer.split(":"); // using the colon as a delimiter
server_vid = Integer.valueOf( cl_s_comm[0]); //
server_bnum = Integer.valueOf(cl_s_comm[1]); //
server_vote = cl_s_comm[2].charAt(0); //
String validation_message = cl_s_comm[3]; //
// if the server message says ABORT
// then an error message is displayed and the server is closed
if (validation_message.equals("ABORT")){
System.out.println("Invalid vote");
server.close();
}
// if however there is no discrepancy between client and server values then the vote is processed
if ( client_vid == server_vid && client_bnum == server_bnum && client_vote == server_vote && validation_message.equals("OK")){
System.out.println("Vote processed");
}
}
}
catch (SocketException se){
System.out.println("client disconnected");
}
catch (UnknownHostException ue){
System.out.println("invalid address");
}
catch (NullPointerException ne){
System.err.println(ne);
}
catch (NumberFormatException ne){
System.out.println("Invalid format");
System.out.println("Connection disconnected");
}
}
}
<file_sep>package app.controller;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
import app.domain.UserInfo;
public class UserInfoValidator implements Validator {
public boolean supports(Class<?> clazz) {
return UserInfo.class.equals(clazz);
}
@Override
public void validate(Object target, Errors errors) {
UserInfo dto = (UserInfo) target;
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "forenames", "", "Field cannot be empty.");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "lastnames", "", "Field cannot be empty.");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "login", "", "Field cannot be empty.");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password", "", "Field cannot be empty.");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password2", "", "Field cannot be empty.");
if (!dto.getPassword().equals(dto.getPassword2())) {
errors.rejectValue("password2", "", "Paswords do not match.");
}
}
}
<file_sep>#ifndef JOYSTICK_CONTROLLER_HEADER
#define JOYSTICK_CONTROLLER_HEADER
#include "lpc_types.h"
#include "joystick.h"
#include "rgb_update.h"
void Joystick_Init(void);
void Joystick_Update(void);
#endif
<file_sep>package eMarket;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Calendar;
import java.util.List;
import java.util.TimeZone;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import eMarket.department.Department;
import eMarket.department.Module;
import eMarket.department.repository.DepartmentRepository;
import eMarket.department.repository.ModuleRepository;
import eMarket.repository.DealRepository;
import eMarket.repository.ProductRepository;
import eMarket.repository.RoleRepository;
import eMarket.repository.UserInfoRepository;
@SpringBootApplication
public class EMarketApp extends WebMvcConfigurerAdapter implements CommandLineRunner {
@Autowired ProductRepository productRepo;
@Autowired DealRepository dealRepo;
@Autowired RoleRepository roleRepo;
@Autowired UserInfoRepository userRepo;
@Autowired ModuleRepository moduleRepo;
@Autowired DepartmentRepository deptRepo;
private static LocalDate systemDate;
public static LocalDate getSystemDate() {
return systemDate;
}
public static void setSystemDate(LocalDate systemDate) {
EMarketApp.systemDate = systemDate;
}
public static void main(String[] args) {
SpringApplication.run(EMarketApp.class, args);
}
public void run(String... args) {
// initialize calendar
Calendar calendar = Calendar.getInstance();
calendar.setTimeZone(TimeZone.getTimeZone("GMT"));
systemDate = calendar.getTime().toInstant().atZone(ZoneId.of("GMT")).toLocalDate();
moduleRepo.deleteAll();
deptRepo.deleteAll();
// BEGIN CHECKPOINT EXERCISE ON SPRING DATA
Department informaticsDepartment = new Department();
informaticsDepartment.setCode("INF");
informaticsDepartment.setName("Informatics");
deptRepo.save(informaticsDepartment);
Department engineeringDepartment = new Department();
engineeringDepartment.setCode("ENG");
engineeringDepartment.setName("Engineering");
deptRepo.save(engineeringDepartment);
Module CO2001 = new Module();
CO2001.setCode("CO2001");
CO2001.setTitle("User Interfaces and HCI");
CO2001.setCredits(10);
// moduleRepo.save(CO2001);
informaticsDepartment.getModuleList().add(CO2001);
Module CO2006 = new Module();
CO2006.setCode("CO2006");
CO2006.setTitle("Software Engineering and System Development");
CO2006.setCredits(20);
informaticsDepartment.getModuleList().add(CO2006);
//moduleRepo.save(CO2006);
Module CO2011 = new Module();
CO2011.setCode("CO2011");
CO2011.setTitle("Automata, Languages and Computation");
CO2011.setCredits(20);
//moduleRepo.save(CO2011);
informaticsDepartment.getModuleList().add(CO2011);
Module CO2012 = new Module();
CO2012.setCode("CO2012");
CO2012.setTitle("Software Project Management and Professionalism");
CO2012.setCredits(10);
//moduleRepo.save(CO2012);
informaticsDepartment.getModuleList().add(CO2012);
deptRepo.save(informaticsDepartment);
// List<Department> list = deptRepo.findByCode("INF");
// deptRepo.save(managedDepartment);
// Department engineeringDepartment = new Department();
// Department managedDepartment2 = deptRepo.save(engineeringDepartment);
// List<Department> list2 = deptRepo.findByCode("ENG");
// deptRepo.save(managedDepartment2);
//
// Module module = new Module();
// Department managedDepartment = deptRepo.save(informaticsDepartment);
// List<Department> list = deptRepo.findByCode("INF");
// deptRepo.save(managedDepartment);
//
// Department engineeringDepartment = new Department();
// Department managedDepartment2 = deptRepo.save(engineeringDepartment);
// List<Department> list2 = deptRepo.findByCode("ENG");
// deptRepo.save(managedDepartment2);
// END CHECKPOINT EXERCISE ON SPRING DATA
}
}
<file_sep>import matplotlib.pyplot as plt
from scipy import signal
from scipy.signal import find_peaks
import numpy as np
#converting the text file with heart data to an array for processing
def text_file_to_array(filename):
arr = []
inp = open(filename, "r")
#read line into array
for line in inp.readlines():
# loop over the elements, split by whitespace
for i in line.split():
# convert to integer and append to the list
arr.append(int(i))
return arr
#butterworth filter for removing noise on signal
#still need to explain why a butterworth filter has been used
def butterworth_filter(orig_sig):
b, a = signal.butter(6, 0.5, 'low')
output_signal = signal.filtfilt(b, a, orig_sig)
return output_signal
#function to plot original and filtered signals on a graph for comparison
def plot_orig_filtered(orig_sig, filtered):
plt.plot(orig_sig, label='original')
plt.plot(filtered, label='filtered')
plt.legend()
return plt.show()
#original r_peak finding function with bpm calculator
def bpm_from_peaks(freq, sig, threshold):
beat_count = 0
for i in range(1, len(sig) - 2):
if sig[i] > sig[i - 1] and sig[i] > sig[i + 1] and sig[i] > threshold:
beat_count = beat_count + 1
fs = freq
n = len(sig)
duration_in_seconds = n/fs
duration_in_minutes = duration_in_seconds/60
bpm = beat_count/duration_in_minutes
return round(bpm)
#function which finds the position of the r peaks
def r_peak_positions(freq, filtered, graph = None):
peaks, _ = find_peaks(filtered, distance=freq/2)
#for physionet we have to use the distance as the sampling frequency, however for our data dividing by 2 gives accurate results
position_of_peaks = []
for i in peaks[1:]:
position_of_peaks.append(int(i))
if graph is True:
plt.plot(filtered)
plt.plot(peaks, filtered[peaks], "x")
return plt.show()
else:
return position_of_peaks
def bpm_from_r_peak_positions(filtered, freq, r_peak_array):
fs = freq
n = len(filtered)
duration_in_seconds = n/fs
duration_in_minutes = duration_in_seconds/60
bpm = len(r_peak_array)/duration_in_minutes
return round(bpm)
<file_sep>#ifndef SSPCONFIG_HEADER
#define SSPCONFIG_HEADER
#include "lpc17xx_pinsel.h"
#include "lpc17xx_gpio.h"
#include "lpc17xx_ssp.h"
PINSEL_CFG_Type PinCfg;
SSP_CFG_Type SSP_ConfigStruct;
void com_Init(void);
#endif
<file_sep>/*------------------------------------------------------------------*-
Port.H (v1.00)
------------------------------------------------------------------
'Port Header' (see Chap 10) for the project S_DELAY (see Chap 11)
COPYRIGHT
---------
This code is from the book:
PATTERNS FOR TIME-TRIGGERED EMBEDDED SYSTEMS by <NAME>
[Pearson Education, 2001; ISBN: 0-201-33138-1].
This code is copyright (c) 2001 by <NAME>.
See book for copyright details and other information.
-*------------------------------------------------------------------*/
// ------ LED_Flas.C -----------------------------------------------
#ifndef _PORT_H
#define _PORT_H
// Connect LED from GND to this pin, via appropriate resistor
// [see Chapter 7 for details]
#define LED_BASE (PIO_0_BASE)
#define LED0_pin (0x01 << 0)
#define LED1_pin (0x01 << 1)
#define LED3_pin (0x01 << 3)
#define MCP2551_int_n (PIO_2_BASE)
#define KEY_0_BASE (PIO_4_BASE)
#define KEY0_MASK (0x01 << 0)
#define KEY0_pin (0)
#define KEY_1_BASE (PIO_5_BASE)
#define KEY1_MASK (0x01 << 0)
#define KEY1_pin (0)
#define TEST_1_BASE (PIO_1_BASE)
#define TEST1_pin (0x01 << 0)
#define TEST2_pin (0x01 << 1)
#define TEST3_pin (0x01 << 2)
/*------------------------------------------------------------------*-
---- END OF FILE -------------------------------------------------
-*------------------------------------------------------------------*/
#endif
<file_sep>#!/bin/bash
if [ $# -eq 1 ]
then
if [ -f $1 ]
then
if [ -r $1 ]
then
base=`basename $1`
sort -k 1 -d $1 --field-separator=";" > "alpha-${base}"
sort -k 2 -h $1 --field-separator=";" > "size-${base}"
sort -k 3 -M $1 --field-separator=";" > "date-${base}"
sort -k 4 -n $1 --field-separator=";" > "value-${base}"
else
echo "$1 is not readable."
fi
else
echo "$1 does not exist."
fi
else
echo "Usage: q8-sort.sh <file>"
fi
<file_sep>#include "lpc17xx_timer.h"
#include "led7seg.h"
#include "rgb.h"
void timer0_init(void)
{
//Power to timer 0 is enabled
LPC_SC->PCONP |= 1 << 1;
//the timer counter and prescale counter are reset
LPC_TIM0->TCR = 2;
//setting the prescale register to 1MHz frequency - the timer counter register increments
// every time the timer reaches the value of 25.
LPC_TIM0->PR = 25 - 1;
//setting match register:
//An action takes place when the timer counter reaches the match register
//value of 1000
LPC_TIM0->MR0 = 1000 - 1;
//setting match register:
//An action takes place when the timer counter reaches the match register
//value of 750
LPC_TIM0->MR1 = 750 - 1;
//setting actions for the timer:
//the first condition generating an interrupt on match register zero, TIMER0_IRQHandler is called
//then the timer counter is reset to zero
//last condition generating an interrupt on match register one, TIMER0_IRQHandler is called
LPC_TIM0->MCR |= (1<<0 | 1<<1 | 1<<3);
// Enable interrupts.
NVIC_EnableIRQ(TIMER0_IRQn);
//the timer counter and prescale counter start to count upwards
LPC_TIM0->TCR = 1;
}
void timer1_init(void)
{
//Power to timer 1 is enabled
LPC_SC->PCONP |= 1 << 2;
//the timer counter and prescale counter are reset
LPC_TIM1->TCR = 2;
//setting the prescale register to 1KHz frequency - the timer counter register increments
// every time the timer reaches the value of 25000.
LPC_TIM1->PR = 25000 - 1;
//setting match register:
//An action takes place when the timer counter reaches the match register
//value of 1000
LPC_TIM1->MR0 = 1000 - 1;
//setting actions for the timer:
//the first condition generating an interrupt on match register zero, TIMER1_IRQHandler is called
//then the timer counter is reset to zero
LPC_TIM1->MCR |= (1<<0 | 1<<1);
// Enable interrupts.
NVIC_EnableIRQ(TIMER1_IRQn);
//the timer counter and prescale counter start to count upwards
LPC_TIM1->TCR = 1;
}
void TIMER0_IRQHandler(void)
{
// Store the current state of the timer interrupt register
uint8_t ir = LPC_TIM0->IR;
if (ir & (1<<0)) // Interrupt generated from MR0 (bit 0 set)
{
LPC_TIM0->IR |= (1<<0); // Clear the interrupt register (write 1 to bit 0)
rgb_setLeds(0);//Turning the LED off
}
if (ir & (1<<1)) // Interrupt generated from MR1 (bit 1 set)
{
LPC_TIM0->IR |= (1<<1); // Clear the interrupt register (write 1 to bit 0)
rgb_setLeds(4);//setting the LED colour to green
}
}
void TIMER1_IRQHandler(void)
{
// Store the current state of the timer interrupt register
uint8_t ir = LPC_TIM1->IR;
static char digit = '0'; //setting up the variable for the seven-segment LED display
if (ir & (1<<0)) // Interrupt generated from MR0 (bit 0 set)
{
LPC_TIM1->IR |= (1<<0); // Clear the interrupt register (write 1 to bit 0)
led7seg_setChar(digit, FALSE);//setting the seven-segment LED to display numbers
if(digit == '9'){
digit = '0'; //when the number reaches 9 then number starts to count from 0 again
}
else digit++; //increments the value for the variable
}
}
<file_sep>#include "LPC17xx.h"
#include "string.h"
#include "stdlib.h"
#include "../include/type.h"
#include "../include/lpcusb_type.h"
#include "../include/usbstruct.h"
#include "../include/usbapi.h"
#include "../include/usbdebug.h"
#include "../include/serial_fifo.h"
#include "../include/USBVcom.h"
// data structure for GET_LINE_CODING / SET_LINE_CODING class requests
typedef struct {
U32 dwDTERate;
U8 bCharFormat;
U8 bParityType;
U8 bDataBits;
} TLineCoding;
TLineCoding LineCoding = {115200, 0, 0, 8};
U8 abBulkBuf[64];
U8 abClassReqData[8];
U8 txdata[VCOM_FIFO_SIZE];
U8 rxdata[VCOM_FIFO_SIZE];
fifo_t txfifo;
fifo_t rxfifo;
const U8 abDescriptors[] = {
// device descriptor
0x12,
DESC_DEVICE,
LE_WORD(0x0101), // bcdUSB
0x02, // bDeviceClass
0x00, // bDeviceSubClass
0x00, // bDeviceProtocol
MAX_PACKET_SIZE0, // bMaxPacketSize
LE_WORD(0xFFFF), // idVendor
LE_WORD(0x0005), // idProduct
LE_WORD(0x0100), // bcdDevice
0x01, // iManufacturer
0x02, // iProduct
0x03, // iSerialNumber
0x01, // bNumConfigurations
// configuration descriptor
0x09,
DESC_CONFIGURATION,
LE_WORD(67), // wTotalLength
0x02, // bNumInterfaces
0x01, // bConfigurationValue
0x00, // iConfiguration
0xC0, // bmAttributes
0x32, // bMaxPower
// control class interface
0x09,
DESC_INTERFACE,
0x00, // bInterfaceNumber
0x00, // bAlternateSetting
0x01, // bNumEndPoints
0x02, // bInterfaceClass
0x02, // bInterfaceSubClass
0x01, // bInterfaceProtocol, linux requires value of 1 for the cdc_acm module
0x00, // iInterface
// header functional descriptor
0x05,
CS_INTERFACE,
0x00,
LE_WORD(0x0110),
// call management functional descriptor
0x05,
CS_INTERFACE,
0x01,
0x01, // bmCapabilities = device handles call management
0x01, // bDataInterface
// ACM functional descriptor
0x04,
CS_INTERFACE,
0x02,
0x02, // bmCapabilities
// union functional descriptor
0x05,
CS_INTERFACE,
0x06,
0x00, // bMasterInterface
0x01, // bSlaveInterface0
// notification EP
0x07,
DESC_ENDPOINT,
INT_IN_EP, // bEndpointAddress
0x03, // bmAttributes = intr
LE_WORD(8), // wMaxPacketSize
0x0A, // bInterval
// data class interface descriptor
0x09,
DESC_INTERFACE,
0x01, // bInterfaceNumber
0x00, // bAlternateSetting
0x02, // bNumEndPoints
0x0A, // bInterfaceClass = data
0x00, // bInterfaceSubClass
0x00, // bInterfaceProtocol
0x00, // iInterface
// data EP OUT
0x07,
DESC_ENDPOINT,
BULK_OUT_EP, // bEndpointAddress
0x02, // bmAttributes = bulk
LE_WORD(MAX_PACKET_SIZE), // wMaxPacketSize
0x00, // bInterval
// data EP in
0x07,
DESC_ENDPOINT,
BULK_IN_EP, // bEndpointAddress
0x02, // bmAttributes = bulk
LE_WORD(MAX_PACKET_SIZE), // wMaxPacketSize
0x00, // bInterval
// string descriptors
0x04,
DESC_STRING,
LE_WORD(0x0409),
0x0E,
DESC_STRING,
'L', 0, 'P', 0, 'C', 0, 'U', 0, 'S', 0, 'B', 0,
0x14,
DESC_STRING,
'U', 0, 'S', 0, 'B', 0, 'S', 0, 'e', 0, 'r', 0, 'i', 0, 'a', 0, 'l', 0,
0x12,
DESC_STRING,
'D', 0, 'E', 0, 'A', 0, 'D', 0, 'C', 0, '0', 0, 'D', 0, 'E', 0,
// terminating zero
0
};
/**
Local function to handle incoming bulk data
@param [in] bEP
@param [in] bEPStatus
*/
void BulkOut(U8 bEP, U8 bEPStatus)
{
int i, iLen;
if (fifo_free(&rxfifo) < MAX_PACKET_SIZE) {
// may not fit into fifo
return;
}
// get data from USB into intermediate buffer
iLen = USBHwEPRead(bEP, abBulkBuf, sizeof(abBulkBuf));
for (i = 0; i < iLen; i++) {
// put into FIFO
if (!fifo_put(&rxfifo, abBulkBuf[i])) {
// overflow... :(
ASSERT(FALSE);
break;
}
}
}
/**
Local function to handle outgoing bulk data
@param [in] bEP
@param [in] bEPStatus
*/
void BulkIn(U8 bEP, U8 bEPStatus)
{
int i, iLen;
if (fifo_avail(&txfifo) == 0) {
// no more data, disable further NAK interrupts until next USB frame
USBHwNakIntEnable(0);
return;
}
// get bytes from transmit FIFO into intermediate buffer
for (i = 0; i < MAX_PACKET_SIZE; i++) {
if (!fifo_get(&txfifo, &abBulkBuf[i])) {
break;
}
}
iLen = i;
// send over USB
if (iLen > 0) {
USBHwEPWrite(bEP, abBulkBuf, iLen);
}
}
/**
Local function to handle the USB-CDC class requests
@param [in] pSetup
@param [out] piLen
@param [out] ppbData
*/
BOOL HandleClassRequest(TSetupPacket *pSetup, int *piLen, U8 **ppbData)
{
switch (pSetup->bRequest) {
// set line coding
case SET_LINE_CODING:
DBG("SET_LINE_CODING\n");
memcpy((U8 *)&LineCoding, *ppbData, 7);
*piLen = 7;
DBG("dwDTERate=%u, bCharFormat=%u, bParityType=%u, bDataBits=%u\n",
LineCoding.dwDTERate,
LineCoding.bCharFormat,
LineCoding.bParityType,
LineCoding.bDataBits);
break;
// get line coding
case GET_LINE_CODING:
DBG("GET_LINE_CODING\n");
*ppbData = (U8 *)&LineCoding;
*piLen = 7;
break;
// set control line state
case SET_CONTROL_LINE_STATE:
// bit0 = DTR, bit = RTS
DBG("SET_CONTROL_LINE_STATE %X\n", pSetup->wValue);
break;
default:
return FALSE;
}
return TRUE;
}
/**
Initialises the VCOM port.
Call this function before using VCOM_putchar or VCOM_getchar
*/
void VCOM_init(void)
{
fifo_init(&txfifo, txdata);
fifo_init(&rxfifo, rxdata);
NVIC_EnableIRQ(USB_IRQn);
}
/**
Writes one character to VCOM port
@param [in] c character to write
@returns character written, or EOF if character could not be written
*/
int VCOM_putchar(int c)
{
return fifo_put(&txfifo, c) ? c : EOF;
}
void VCOM_putstring (char datasend[])
{
uint32_t lenghtdata = 0;
uint32_t var = 0;
lenghtdata = strlen(datasend);
for (var = 0; var < lenghtdata; ++var) {
BOOL done = FALSE;
while (!done)
{
done = fifo_put(&txfifo, datasend[var]);
}
}
}
void VCOM_putstring2 (char datasend[])
{
uint32_t lenghtdata = 0;
uint32_t var = 0;
lenghtdata = strlen(datasend);
for (var = 0; var < lenghtdata; ++var) {
BOOL done = FALSE;
while (!done){
done = fifo_put(&txfifo, datasend[var]);
}
}
}
/**
Reads one character from VCOM port
@returns character read, or EOF if character could not be read
*/
int VCOM_getchar(void)
{
U8 c;
return fifo_get(&rxfifo, &c) ? c : EOF;
}
int VCOM_GetString(char *data)
{
uint32_t lenghtcheck;
uint32_t var = 0;
U8 c;
lenghtcheck = fifo_avail(&rxfifo);
char datarec[lenghtcheck + 1];
for (var = 0; var <= lenghtcheck; ++var)
{
datarec[var] = fifo_get(&rxfifo, &c) ? c : EOF;
}
datarec[lenghtcheck + 1] = 0;
data = (char *) malloc((lenghtcheck + 1) );
strncpy(data, datarec, (lenghtcheck+1));
if (strncpy(data, datarec, (lenghtcheck + 1)))
{
return 1;
}
return 0;
}
char* VCOM_RecieveString(void)
{
uint32_t lenghtcheck;
uint32_t var = 0;
U8 c;
lenghtcheck = fifo_avail(&rxfifo);
char datarec[lenghtcheck + 1];
for (var = 0; var <= lenghtcheck; ++var)
{
datarec[var] = fifo_get(&rxfifo, &c) ? c : EOF;
}
char *data = (char *) malloc((lenghtcheck + 1) );
strncpy(data, datarec, lenghtcheck);
data[lenghtcheck] = 0;
return data;
}
int VCOM_Available(void)
{
int aval = 0;
aval = fifo_avail(&rxfifo);
return aval;
}
/**
Interrupt handler
Simply calls the USB ISR
*/
//void USBIntHandler(void)
void USB_IRQHandler(void)
{
USBHwISR();
}
void USB_init (void)
{
// initialise stack
USBInit();
// register descriptors
USBRegisterDescriptors(abDescriptors);
// register class request handler
USBRegisterRequestHandler(REQTYPE_TYPE_CLASS, HandleClassRequest, abClassReqData);
// register endpoint handlers
USBHwRegisterEPIntHandler(INT_IN_EP, NULL);
USBHwRegisterEPIntHandler(BULK_IN_EP, BulkIn);
USBHwRegisterEPIntHandler(BULK_OUT_EP, BulkOut);
// register frame handler
USBHwRegisterFrameHandler(USBFrameHandler);
// enable bulk-in interrupts on NAKs
USBHwNakIntEnable(INACK_BI);
}
void USBFrameHandler(U16 wFrame)
{
if (fifo_avail(&txfifo) > 0) {
// data available, enable NAK interrupt on bulk in
USBHwNakIntEnable(INACK_BI);
}
}
void enable_USB_interrupts(void)
{
NVIC_EnableIRQ(USB_IRQn);
}
<file_sep>#ifndef ROTARY_HEADER
#define ROTARY_HEADER
#include "lpc_types.h"
#include "rotary.h"
#include "disp7seg_update.h"
void RotaryEncoder_Init(void);
void RotaryEncoder_Update(void);
#endif
<file_sep>// namedWelcome.cpp
// program to asks the user to input her name and print out
// Hello <name>!
// Welcome to CO7105
//
// Author: nt161
// Version: 1
#include <iostream> // use the standard IO library
#include <string> // use the standard string library
using namespace std;
int main () {
string name;
cout << "Enter name: " << endl;
cin >> name;
cout << "Hello " << name << "\n" << "Welcome to CO7105" << endl;
return 0;
}
<file_sep>/*
* led_bank.h
*
* Created on: 18 March 2018
* Author: nt161
*/
#ifndef TASKS_LED_BANK_HEADER_
#define TASKS_LED_BANK_HEADER_
#include "lpc17xx_pinsel.h"
#include "lpc17xx_i2c.h"
#include "pca9532.h"
#include "../adc/adc.h"
// ------ Public function prototypes -------------------------------
void led_bank_init(void);
void led_display_adc_general(uint32_t value);
void led_display_adc_0_average(void);
#endif /* TASKS_LED_BANK_HEADER_ */
<file_sep>package eMarket.repository;
import java.util.List;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import eMarket.domain.Deal;
public interface DealRepository extends CrudRepository<Deal, Integer> {
Deal findById(int id);
@Query(value = "SELECT deal_id,deal_start_date,deal_end_date,deal_discount, deal_product from product as p, deal as d where d.deal_product=p.product_id and d.deal_id=?1", nativeQuery=true)
List<Deal> findAllByCustomQuery(int id);
}<file_sep>package eMarket.department.repository;
import org.springframework.data.repository.CrudRepository;
import eMarket.department.Module;
public interface ModuleRepository extends CrudRepository<Module, String> {
Module findByCode(String code);
}<file_sep>################################################################################
# Automatically-generated file. Do not edit!
################################################################################
-include ../makefile.init
RM := rm -rf
# All of the sources participating in the build are defined here
-include sources.mk
-include src/tasks/subdir.mk
-include src/system/subdir.mk
-include src/scheduler/subdir.mk
-include src/main/subdir.mk
-include src/lpcusb/source/subdir.mk
-include src/adc/subdir.mk
-include subdir.mk
-include objects.mk
ifneq ($(MAKECMDGOALS),clean)
ifneq ($(strip $(C_DEPS)),)
-include $(C_DEPS)
endif
endif
-include ../makefile.defs
# Add inputs and outputs from these tool invocations to the build variables
# All Target
all: Assignment4Final.axf
# Tool invocations
Assignment4Final.axf: $(OBJS) $(USER_OBJS)
@echo 'Building target: $@'
@echo 'Invoking: MCU Linker'
arm-none-eabi-gcc -nostdlib -L"Z:\Assignment4V2\Lib_CMSISv1p30_LPC17xx\Debug" -L"Z:\Assignment4V2\Lib_EaBaseBoard\Debug" -L"Z:\Assignment4V2\Lib_MCU\Debug" -Xlinker --gc-sections -Xlinker -Map=Assignment4Final.map -mcpu=cortex-m3 -mthumb -T "Assignment4Final_Debug.ld" -o "Assignment4Final.axf" $(OBJS) $(USER_OBJS) $(LIBS)
@echo 'Finished building target: $@'
@echo ' '
$(MAKE) --no-print-directory post-build
# Other Targets
clean:
-$(RM) $(OBJS)$(C_DEPS)$(EXECUTABLES) Assignment4Final.axf
-@echo ' '
post-build:
-@echo 'Performing post-build steps'
-arm-none-eabi-size Assignment4Final.axf; # arm-none-eabi-objdump -h -S Assignment4Final.axf >Assignment4Final.lss
-@echo ' '
.PHONY: all clean dependents
.SECONDARY: post-build
-include ../makefile.targets
<file_sep>#ifndef TIMER_HEADER
#define TIMER_HEADER
void timer0_init(void);
void TIMER0_IRQHandler(void);
#endif
<file_sep>import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from scipy import signal
import peakutils
import pywt
import wfdb
#lowpass = 100
#highpass = 0.01
#fig, ax = plt.subplots(3, sharex=True)
#arr = plt.subplots(3, sharex=True)
#a, b = signal.butter(6, (highpass, lowpass), btype='bandpass', analog=True)
#filtered_signal = signal.lfilter(b, a, dataset)
#smoothed_signal = signal.cspline1d(filtered_signal, lamb=1000)
#arr[0].plot(dataset)
#arr[1].plot(filtered_signal)
#arr[2].plot(smoothed_signal)
#ax[0].plot(dataset)
#ax[1].plot(filtered_signal)
#ax[2].plot(smoothed_signal)
arr = []
inp = open ("test.txt","r")
#read line into array
for line in inp.readlines():
# loop over the elemets, split by whitespace
for i in line.split():
# convert to integer and append to the list
arr.append(int(i))
# fs = 100
# t = np.arange(1000)/fs
# signala = np.sin(2*np.pi*100*t)
# plt.plot(t, signala, label='a')
#
#fc = 100
#Wn = fc / (fc / 2)
# b, a = signal.butter(5, w, 'low')
# output = signal.filtfilt(b, a, signala)
# plt.plot(t, output, label='filtered')
# plt.legend()
# plt.show()
b, a = signal.butter(6, 0.5, 'low')
output_signal = signal.filtfilt(b, a, arr)
plt.plot(arr, label='original')
plt.plot(output_signal, label='filtered')
plt.legend()
plt.show()
<file_sep>// Variables
int PulseSensorPurplePin = 0; // Pulse Sensor PURPLE WIRE connected to ANALOG PIN 0
int Signal; // holds the incoming raw data. Signal value can range from 0-1024
// The SetUp Function:
void setup()
{
Serial.begin(115200); // Set's up Serial Communication at certain speed faster than the rate at which data is being sampled.
cli();//stop interrupts
//set timer1 interrupt at 100Hz
TCCR1A = 0;// set entire TCCR2A register to 0
TCCR1B = 0;// same for TCCR2B
TCNT1 = 0;//initialize counter value to 0
// set compare match register for 100Hz increments
OCR1A = 2499;// = (16*10^6) / (100*64) - 1 (must be <65536) -- where 100 is the frequency from what I recall
// turn on CTC mode
TCCR1B |= (1 << WGM12);
// Set CS01 and CS00 bits for 64 prescaler
TCCR1B |= (1 << CS11) | (1 << CS10);
// enable timer compare interrupt
TIMSK1 |= (1 << OCIE0A);
sei();
}
// The Main Loop Function
void loop()
{
//Do nothing!
}
ISR(TIMER1_COMPA_vect)
{
Signal = analogRead(PulseSensorPurplePin); // Read the PulseSensor's value.
// Assign this value to the "Signal" variable.
Serial.println(Signal); // Send the Signal value to Serial Plotter.
}
<file_sep>/* Please note: even though it says IMPLEMENT ME, in some cases
the implementation can be empty. In fact, you may wish to remove
some of the functions entirely
*/
#include "Football.h"
#include<cmath>
// -------------- Team --------------------
// constructor which sets the team name and the number of goals conceded to zero
Team::Team(const string& name) {
// IMPLEMENT ME
this->team_name = name;
goals_conceded = 0;
}
// increments the number of goals conceded by g
void Team::addGoalsConceded(int g) {
// IMPLEMENT ME
goals_conceded += g;
}
Team::~Team() {
// IMPLEMENT ME
}
// added a getter because goals_conceded is a private member
int Team::getGoalsConceded() const{
return goals_conceded;
}
// added a getter because team_name is a private member
string Team::getTeamName(){
return team_name;
}
// -------------- Player ------------------
//~ Player::Player() {
//~ // see comment in .h
//~ }
// the player constructor sets the name, team, assists to 0 and goals scored to 0
Player::Player(const string& name, Team* t) {
// IMPLEMENT ME
this->name = name;
this->t = t;
assists = 0;
goals_scored = 0;
}
// don't remove this even if you want to make the destructor pure virtual
Player::~Player() {
// IMPLEMENT ME
}
// increments the number of goals scored by g
void Player::addGoalsScored(int g) {
// IMPLEMENT ME
goals_scored += g;
}
// increments the number of assists by a
void Player::addAssists(int a) {
// IMPLEMENT ME
assists += a;
}
/* int Player::getScore() const {
* // IMPLEMENT ME
* }
*/
//~ string Player::print() const {
//~ // IMPLEMENT ME
//~ // below are just stub code
//~ string removeMe = "";
//~ return removeMe;
//~ }
// -------------- Attacker ------------------
Attacker::Attacker(const string& name, Team* t) : Player(name, t){
// IMPLEMENT ME
}
Attacker::~Attacker() {
// IMPLEMENT ME
}
// solves the score of the attacker according to the table given in doc
int Attacker::getScore() const {
// IMPLEMENT ME
// below are just stub code
return (4*goals_scored) + (3*assists);
}
string Attacker::print() const{
// IMPLEMENT ME
// below are just stub code
string s = "";
s += "Attacker: " + name + ", Team: " + t->getTeamName() + "\n";
s += " Goals scored: " + to_string(goals_scored) + "\n";
s += " Assists: " + to_string(assists) + "\n";
s += " Goals conceded: " + to_string(t->getGoalsConceded()) + "\n";
s += " Score: " + to_string(getScore());
return s;
}
// -------------- Midfielder ------------------
Midfielder::Midfielder(const string& name, Team* t) : Player(name, t) {
// IMPLEMENT ME
}
Midfielder::~Midfielder() {
// IMPLEMENT ME
}
// solves the score of the midfielder according to the table given in doc
int Midfielder::getScore() const {
// IMPLEMENT ME
// below are just stub code
if(t->getGoalsConceded() == 0)
{
return (5*goals_scored) + (3*assists) + 1;
}
else
{
return (5*goals_scored) + (3*assists);
}
}
string Midfielder::print() const {
// IMPLEMENT ME
// below are just stub code
string s = "";
s += "Midfielder: " + name + ", Team: " + t->getTeamName() + "\n";
s += " Goals scored: " + to_string(goals_scored) + "\n";
s += " Assists: " + to_string(assists) + "\n";
s += " Goals conceded: " + to_string(t->getGoalsConceded()) + "\n";
s += " Score: " + to_string(getScore());
return s;
}
// -------------- Defender ------------------
Defender::Defender(const string& name, Team* t) : Player(name, t){
// IMPLEMENT ME
}
Defender::~Defender() {
// IMPLEMENT ME
}
// solves the score of the defender according to the table given in doc
int Defender::getScore() const {
// IMPLEMENT ME
// below are just stub code
if(t->getGoalsConceded() == 0)
{
return (6*goals_scored) + (3*assists) + 4;
}
else
{
return (6*goals_scored) + (3*assists) - (floor(t->getGoalsConceded()/2));
}
}
string Defender::print() const {
// IMPLEMENT ME
// below are just stub code
string s = "";
s += "Defender: " + name + ", Team: " + t->getTeamName() + "\n";
s += " Goals scored: " + to_string(goals_scored) + "\n";
s += " Assists: " + to_string(assists) + "\n";
s += " Goals conceded: " + to_string(t->getGoalsConceded()) + "\n";
s += " Score: " + to_string(getScore());
return s;
}
// -------------- Goalkeeper ------------------
// constructor for goalkeeper sets shots saved to 0
Goalkeeper::Goalkeeper(const string& name, Team* t) : Player(name, t) {
// IMPLEMENT ME
shots_saved = 0;
}
Goalkeeper::~Goalkeeper() {
// IMPLEMENT ME
}
// increments the number of shots saved by ss
void Goalkeeper::addShotsSaved(int ss) {
// IMPLEMENT ME
shots_saved += ss;
}
// solves the score of the goalkeeper according to the table given in doc
int Goalkeeper::getScore() const {
// IMPLEMENT ME
// below are just stub code
if(t->getGoalsConceded() == 0)
{
return (6*goals_scored) + (3*assists) + (floor((shots_saved/3)) * 1) + 4;
}
else
{
return (6*goals_scored) + (3*assists) - (floor((t->getGoalsConceded()/2))) + (floor((shots_saved/3)));
}
}
string Goalkeeper::print() const {
// IMPLEMENT ME
// below are just stub code
string s = "";
s += "Goalkeeper: " + name + ", Team: " + t->getTeamName() + "\n";
s += " Goals scored: " + to_string(goals_scored) + "\n";
s += " Assists: " + to_string(assists) + "\n";
s += " Goals conceded: " + to_string(t->getGoalsConceded()) + "\n";
s += " Shots saved: " + to_string(shots_saved) + "\n";
s += " Score: " + to_string(getScore());
return s;
}
// -------------- FantasyTeam ------------------
// the constructor for sets the number of players to 0
FantasyTeam::FantasyTeam() {
// IMPLEMENT ME
this->num_players = 0;
}
FantasyTeam::~FantasyTeam() {
// IMPLEMENT ME
}
// as long as number of players is less than 11 and the player hasn't been added to the team
// then the player is added and function returns true
bool FantasyTeam::addPlayer(Player* p) {
// IMPLEMENT ME
// below are just stub code
if(num_players < 11)
{
for(auto &pl : players)
{
if(p == pl) return false;
}
players[num_players++] = p;
return true;
}
else
{
return false;
}
}
// adds all the scores of the players
// to give a total score for the team
int FantasyTeam::getScore() const {
// IMPLEMENT ME
// below are just stub code
int score_total = 0;
for(int i=0; i<num_players; i++)
{
score_total += players[i]->getScore();
}
return score_total;
}
<file_sep>from tkinter import *
from tkinter import filedialog
from tkinter import messagebox
import matplotlib.pyplot as plt
from scipy import signal
import numpy as np
import math
#pending tasks: print output on gui and tell the user when it has arrhythmia, exception handling,
# print the ecg trace on the screen
class Gui:
def __init__(self, master):
self.master = master
master.title("Heart Diagnostic Monitor")
master.geometry("355x80")
# ******* Main Menu ********
menu = Menu(root)
master.config(menu=menu)
fileMenu = Menu(menu)
menu.add_cascade(label="File", menu=fileMenu)
fileMenu.add_command(label="Exit", command=self.quit)
#********** Buttons *************
self.load_data_button = Button(master, text='Upload Data', relief="ridge", command=self.upload)
self.load_data_button.grid(row=1, column=0)
self.quit_button = Button(master, text='Quit', bg="black", fg="white", relief="ridge", height="1", width="10", command=self.quit)
self.quit_button.grid(row=1, column=4, padx=10)
#************ User Input ************
self.freq_label = Label(master, text="Sample Frequency")
self.freq_label.grid(row=2, column=0, sticky=E, padx=10)
self.freq_entry = Entry(master, width="18")
self.freq_entry.grid(row=2, column=1, padx=5)
# self.threshold_label = Label(master, text="Threshold")
# self.threshold_label.grid(row=3, column=0, padx=10)
# self.threshold_entry = Entry(master, width="18")
# self.threshold_entry.grid(row=3, column=1, padx=5)
#self.button_1 = Button(master, text="nishat smells", command=lambda: self.message("count: "+ str(self.count)))
#self.button_1.pack()
def text_file_to_array(self, filename):
arr = []
try:
inp = open(filename, "r")
# read line into array
for line in inp.readlines():
# loop over the elements, split by whitespace
for i in line.split():
# convert to integer and append to the list
arr.append(int(i))
return arr
except FileNotFoundError:
print("File not found")
exit()
def butterworth_filter(self, orig_sig):
b, a = signal.butter(6, 0.5, 'low')
output_signal = signal.filtfilt(b, a, orig_sig)
return output_signal
def plot_graph(filtered, bpm):
plt.plot(filtered, label='ECG Trace at' + bpm)
plt.legend()
return plt.show()
def threshold(self, sig):
#threshold_value = (max(sig)+min(sig)) / 2
diff = max(sig) - min(sig)
threshold_value = max(sig) - diff * 0.33
return threshold_value
def bpm_from_peak_finder(self, freq, sig, threshold):
beat_count = 0
for i in range(1, len(sig) - 2):
if sig[i] > sig[i - 1] and sig[i] > sig[i + 1] and sig[i] > threshold:
beat_count = beat_count + 1
fs = freq
n = len(sig)
duration_in_seconds = n/fs
duration_in_minutes = duration_in_seconds/60
bpm = beat_count/duration_in_minutes
return round(bpm)
def sample_positions_to_time(self, freq, sig, threshold):
positions = []
for i in range(1, len(sig) - 2):
if sig[i] > sig[i - 1] and sig[i] > sig[i + 1] and sig[i] > threshold:
i = i/freq
positions.append(i)
return positions
def average_differences(self, r_peak_times):
diffs = np.diff(r_peak_times)
avg_diffs = sum(diffs)/len(diffs)
return avg_diffs
def root_mean_square_differences(self, r_peak_times):
square = []
r_peak_diffs = np.diff(r_peak_times)
for i in range(len(r_peak_diffs) - 2):
r_peak_diffs[i] = r_peak_diffs[i] * r_peak_diffs[i]
square.append(r_peak_diffs[i])
sum_of_squares = sum(square)
mean = sum_of_squares/len(square)
rmssd = math.sqrt(mean)
return rmssd
def standard_dev_diffs(self, r_peak_times):
diffs = np.diff(r_peak_times)
mean_of_diffs = sum(diffs)/len(diffs)
diff_with_mean = []
square = []
for i in r_peak_times:
i = i - mean_of_diffs
diff_with_mean.append(i)
for j in diff_with_mean:
j = j * j
square.append(j)
sum_of_squares = sum(square)
mean = sum_of_squares/len(square)
sd = math.sqrt(mean)
return sd
def has_arrhythmia(self, SDRR):
if SDRR > 15:
print("Arrhythmia Detected!")
def hrv(self, RMSSD):
if RMSSD < 0.6:
print("Arrhythmia Detected!")
def arrhythmia_type(self, bpm):
if bpm < 50:
print("Bradycardia detected!")
elif bpm > 100:
print("Tachycardia detected!")
def upload(self):
filename = filedialog.askopenfilename()
print('Selected:', filename)
# file = open(root.filename).read()
data = self.text_file_to_array(filename)
filtered = self.butterworth_filter(data)
threshold = self.threshold(filtered)
bpm = self.bpm_from_peak_finder(int(self.freq_entry.get()), filtered, threshold)
print("HeartRate = ", bpm, " bpm")
self.arrhythmia_type(bpm)
time = self.sample_positions_to_time(int(self.freq_entry.get()), filtered, threshold)
SDRR = self.standard_dev_diffs(time)
RMSSD = self.root_mean_square_differences(time)
print("SDSD = ", SDRR, " seconds")
print("RMSSD = ", RMSSD, " seconds")
self.has_arrhythmia(SDRR)
if bpm > 50:
self.hrv(RMSSD)
print("Heart rhythm is healthy")
def quit(self):
exit()
root = Tk()
GUI = Gui(root)
root.mainloop()
<file_sep>/*------------------------------------------------------------------*-
LED_flas.C (v1.00)
------------------------------------------------------------------
Simple 'Flash LED' test function.
COPYRIGHT
---------
This code is from the book:
PATTERNS FOR TIME-TRIGGERED EMBEDDED SYSTEMS by <NAME>
[Pearson Education, 2001; ISBN: 0-201-33138-1].
This code is copyright (c) 2001 by <NAME>.
See book for copyright details and other information.
-*------------------------------------------------------------------*/
//#include <altera_avalon_performance_counter.h>
#include <altera_avalon_pio_regs.h>
#include "../TTC_Scheduler_slave/Main.h"
#include "../TTC_Scheduler_slave/PORT.h"
#include "system.h"
#include "PushButton.h"
// ------ Public variable definitions ------------------------------
unsigned int Sw_pressed_G = 0; // The current switch status
tByte Ack_message_data_G;
// ------ Private constants ----------------------------------------
// Allows NO or NC switch to be used (or other wiring variations)
#define SW_PRESSED (0)
// SW_THRES must be > 1 for correct debounce behaviour
#define SW_THRES (3)
// ------ Private variable definitions ------------------------------
static unsigned char pb0_input = 0;
/*------------------------------------------------------------------*-
PushButton_Init()
- See below.
-*------------------------------------------------------------------*/
void PushButton_Init(void)
{
// Do nothing
}
/*------------------------------------------------------------------*-
LED_Flash_Update()
-*------------------------------------------------------------------*/
void PushButton_Update(void)
{
// Change the LED from OFF to ON (or vice versa)
// IOWR_ALTERA_AVALON_PIO_DATA(LED_BASE,
// IORD_ALTERA_AVALON_PIO_DATA(LED_BASE) ^ LED_pin);
static unsigned int Duration;
// Read "reset count" switch input (pb0)
pb0_input = IORD_ALTERA_AVALON_PIO_DATA(KEY_0_BASE);
if (pb0_input == SW_PRESSED)
{
Duration += 1;
if (Duration > SW_THRES)
{
Duration = SW_THRES;
Sw_pressed_G = 1; // Switch is pressed...
Ack_message_data_G = 0xAA;
return;
}
// Switch pressed, but not yet for long enough
Sw_pressed_G = 0;
Ack_message_data_G = 'C';
return;
}
// Switch not pressed - reset the count
Duration = 0;
Sw_pressed_G = 0; // Switch not pressed...
Ack_message_data_G = 'C';
}
/*------------------------------------------------------------------*-
---- END OF FILE -------------------------------------------------
-*------------------------------------------------------------------*/
<file_sep>/*
* alt_spi_master.h
*
* Created on: 14 Feb 2016
* Author: <NAME>
*/
#ifndef ALT_SPI_MASTER_H_
#define ALT_SPI_MASTER_H_
#define ALT_SPI_MASTER (SPI_0_BASE)
#define alt_spi_rx_data_reg (ALT_SPI_MASTER+0)
#define alt_spi_tx_data_reg (ALT_SPI_MASTER+1)
#define alt_spi_status_reg (ALT_SPI_MASTER+2)
#define alt_spi_ctrl_reg (ALT_SPI_MASTER+3)
#define alt_spi_slave_sel_reg (ALT_SPI_MASTER+5)
#endif /* ALT_SPI_MASTER_H_ */
<file_sep><link rel='stylesheet' href='web/swiss.css'/>
# Sprint 4 - Exercise 06 (Spring Security)
Base code implementing a security layer with users of role `MANAGER`, who have access to the product catalogue only in our online shop `EMarket`.
## Goal
In this tutorial, we are going to discuss how to augment our web applications with the security control measures discussed in the lecture regarding:
* Secure communication using a public key infrastructure.
* Access control using [Spring Security](http://projects.spring.io/spring-security/):
* consideration of one type of users in the domain model;
* authentication using secure passwords with the algorithm BCrypt; and
* authorization.
## Tutorial
### Setting the infrastructure
Make sure you have the right dependencies in your script [build.gradle](./build.gradle): security dependency must be uncommented and that the file [DbConfig.java](src/main/java/eMarket/DbConfig.java) is configured using your MySQL credentials.
### Secure communication using a public key infrastructure
In this section, we are going to implement a partial public key infrastructure in which the only step that we are going to skip is the deployment of the digital certificate on to a CA server. The first step is to create the digital certificate and the second step is to configure the web application with it.
#### Generating the digital certificate
We are going to use [Java's keytool](https://docs.oracle.com/javase/6/docs/technotes/tools/windows/keytool.html), a key and certificate management utility. It allows users to administer their own public/private key pairs and associated certificates for use in self-authentication in a public key infrastructure. It also allows users to cache the public keys (in the form of certificates) of their communicating peers. keytool stores the keys and certificates in a [keystore](https://docs.oracle.com/javase/6/docs/technotes/tools/windows/keytool.html#KeyStore).
The first step is to generate a digital certificate (X.509 v3 self-signed) that contains a key pair (a public key and associated private key) by using the option `-genkeypair`. Run the following command from a terminal console:
keytool -genkeypair -alias tomcat -keyalg RSA -keystore ./keystore.jks
In the command above:
* The certificate and the private key are stored in a new keystore entry identified by `-alias`.
* `-keyalg` specifies the algorithm to be used to generate the key pair,
* `-keystore` indicates the keystore location. If the JKS storetype is used and a keystore file does not yet exist, then certain keytool commands may result in a new keystore file being created.
* Other parameters, such as a validity period for the certificate, can also be specified. Check [keytool's documentation](https://docs.oracle.com/javase/6/docs/technotes/tools/windows/keytool.html) for more details.
The command will prompt an interactive dialogue in which you have to provide the information requested:
* Use `<PASSWORD>` as password for both the keystore and for the certificate:
<img src="web/keytool.png" alt="digital certificate generation" width="675" height="300">
Copy the generated file `keystore.jks` to folder `src/main/resources`.
#### Setting up SSL/TLS for the web application
Configure the web container to use the port 8090 with SSL by adding the following lines to file `application.properties`:
server.port=8090
server.ssl.key-store=classpath:keystore.jks
server.ssl.key-store-password=<PASSWORD>
server.ssl.key-password=<PASSWORD>
Ask the servlet container to secure all http requests by appending the following lines to the configuration of the `http` object in method `configure()` of the class [eMarket.SecurityConfig](src/main/java/eMarket/SecurityConfig.java) by using `http.requiresChannel().anyRequest().requiresSecure();`.
The `HttpSecurity` class is discussed in more detail below.
By running `gradle bootRun`, you should be able to access to your application at `https://localhost:8090/` in a secure way. That is, all the information that you enter in a form is going to be encrypted. However, as discussed in the lecture the browser should still complain that the digital certificate has not been registered by a Certification Authority (CA).
### Access Control
In this section, we are going to implement the three aspects of access control introduced in the lecture.
#### User identification
The concepts of user and of role are going to be included in the domain model so that our system gains knowledge about real users. We are going to hook these classes into the Spring Security framework so that we can reuse the authentication mechanism that is built in the framework. The information about users will be kept in a MySQL database through JPA and Hibernate as we did in previous sessions.
In previous worksheets, we have considered the business logic of the web app in the controller class and in the domain model, which may suffice for simple web apps. A **service layer** allows us to decouple the business logic from the web layer (controllers, views, validation, error handling, ...) and from the repository layer (persistence in a database), allowing us to develop more interesting functionality involving transactions and concurrent processes (both out of the scope of CO2006). However, note that repositories depend on the implementation of the domain object model and that a service layer resides atop the data layer. A class annotated with `@Service` indicates that it is a service component in the business layer.
##### Configuration
Let's configure the database connection:
* Reuse the `DbConfig.java` file with the configuration of the connection to the database that was used in previous lab sessions.
##### Domain model
The domain model of the application, including users and roles, is represented using a class diagrams as follows:
<img src="web/domain.png" alt="user model" width="600" height="500">
A user object is used to store the user name and the password for authentication purposes. Each user object is associated with a specific role in this model.
##### Repository
The repositories for `User` and `Role` objects can be found in interfaces `eMarket.repository.UserRepository` and `eMarket.repository.RoleRepository`.
##### Service layer
The main purpose of the service layer to be developed is to extend the facilities provided by Spring Security with our own implementation of roles and users. In particular, we are going to implement a [UserDetailsService](https://docs.spring.io/spring-security/site/docs/current/reference/html5/#userdetailsservice-implementations) for user data and performs no other function other than to supply that data to other components within the framework. Spring Security provides a number of built-in implementations of this service, including one that uses an in-memory map (`InMemoryDaoImpl`) and another that uses JDBC (`JdbcDaoImpl`). However, we are going to develop a custom service implementation to illustrate how to extend a service provided by the Spring Framework that uses a MySQL database to store user information through Hibernate.
In the class [eMarket.services.CustomUserDetailsService](src/main/java/eMarket/services/CustomUserDetailsService.java):
* `loadUserByUsername()` retrieves information about the principal (the actor instance to be authenticated) from the database and instantiates a Spring Security `User` object. This method returns a `UserDetails` instance, which can be regarded as the [adapter](https://www.tutorialspoint.com/design_pattern/adapter_pattern.htm) between your own user database and what Spring Security needs to authenticate the user.
* More information about these notions can be found [here](https://docs.spring.io/spring-security/site/docs/current/reference/html5/#core-components).
#### Access control: authentication and authorization
Access control is configured in the class [eMarket.SecurityConfig](src/main/java/eMarket/SecurityConfig.java):
* `configureGlobal(AuthenticationManagerBuilder auth)` deals with the authentication of a user. In this method we are using the [Bcrypt algorithm](https://en.wikipedia.org/wiki/Bcrypt) to encode the password. More information about the authentication process in Spring Security can be found [here](http://docs.spring.io/spring-security/site/docs/current/reference/html/technical-overview.html#tech-intro-authentication).
* `configure(HttpSecurity http)` configures access control for each HTTP request that can be served by our controllers by adding access control rules to the [HttpSecurity object](https://docs.spring.io/spring-security/site/docs/current/reference/html5/#jc-httpsecurity).
* Access control rules are configured by using `HttpSecurity`'s fluent API under `.authorizeRequests()`. Each rule has a pattern that matches the requested services and a condition that inspects the role of the principal object requesting access to that service. In our simple web app of the example, there is only one service, which can be requested both by users and by admin users. The code `.exceptionHandling().accessDeniedPage("/user-error");` tells the servlet container how to deal with no authorizations. If you don't want to mention this redirection explicitly, the default url is `/error`.
* `.formLogin()` configures the login form. When a principal object performing a request is not authenticated, it is redirected to `/login`. Upon successful authentication, the principal object is redirected to `/success-login`. Otherwise, it is redirected to `/error-login`. These requests are going to be implemented in a separate access control controller below.
* `logout()` configures the process of logging out and redirects the principal object to `/user-logout`.
* `.requiresChannel().anyRequest().requiresSecure()` forces the use of a secure communication channel for each request.
When the web app is run, the method `run` in the class [eMarket.EMarketApp](src/main/java/eMarket/EMarketApp.java) adds a user to our database. Note that the code in that class is using the Bcrypt algorithm to store passwords securely in the database.
##### Controller
The HTTP requests used in the configuration of the `HttpSecurity` objects are handled by the [AuthenticationController](src/main/java/eMarket/controller/AuthenticationController.java).
##### Views
The views required to complete the implementation are in the folder [src/main/webapp/WEB-INF/views/security](src/main/webapp/WEB-INF/views/security/).
At this stage, you should be able to run `./gradlew clean bootRun` and to access the web application by using the information about users provided in the class `EMarketApp`.
## Exercises
### a. Define a secure connection
1. Create a new keystore with a new key using `keytool`.
2. Configure the web app to use that keystore in file [application.properties](src/main/resources/application.properties).
3. Configure the web app to enforce secure communication via HTTPS in file [SecurityConfig.java](src/main/java/eMarket/SecurityConfig.java).
### b. Authentication
In class [EMarketApp](src/main/java/eMarket/EMarketApp.java), create:
* a new role `CUSTOMER`;
* a new user with username `Alice`, with password `<PASSWORD>`, and with role `CUSTOMER`.
### c. Authorization
Implement the following access matrix in [SecurityConfig.java](src/main/java/eMarket/SecurityConfig.java):
| REQUEST | ROLE |
|--|--|
| /product | MANAGER |
| /product/ | MANAGER |
| /test | CUSTOMER |
| /test/ | CUSTOMER |
| /test2 | MANAGER,CUSTOMER |
| /test2/ | MANAGER,CUSTOMER |
### d. Analyzing the dependencies to the security layer
An effective way to learn what the dependencies are between the web layer and the security layer consists in removing the security layer:
1. Comment the dependencies regarding security in [build.gradle](./build.gradle).
2. Refresh the project configuration in the STS using `./gradlew cleanEclipse eclipse` and refresh project on the package explorer.
3. The IDE will highlight the dependencies as compilation errors: comment all of them.
4. Check that you can run your application with `./gradlew clean bootRun` and that the main requests are accessible.
## Additional resources
* [Spring Security reference documentation](https://docs.spring.io/spring-security/site/docs/current/reference/html5/)
## Credits
Some materials have been adapted from [Spring MVC: Security with MySQL and Hibernate](http://fruzenshtein.com/spring-mvc-security-mysql-hibernate/).
***
© <NAME>, 2016-18 <file_sep>/*
Author: nt161
Date: October 2018
Part 1
*/
#include <stdio.h>
#include <stdlib.h>
#include <omp.h>
/*
Ex1
*/
int main(int argc, char **argv) {
int i;
int N = 5;
double A[] = {3,2,4,1,2}, B[] = {1,4,3,2,6}, C[N], D[N];
const double c = 4;
const double x = 7;
double y;
#pragma omp parallel for
for (i = 0; i < N; i++)
{
y = sqrt(A[i]);
D[i] = y + A[i] / (x * x);
}
return 0;
}
/*
Ex2
*/
int main(int argc, char **argv) {
int i;
int N = 5;
double A[] = {3,2,4,1,2}, B[] = {1,4,3,2,6}, C[N], D[N];
const double c = 4;
const double x = 7;
double y;
#pragma omp parallel
{
#pragma omp for nowait
for (i = 0; i < N; i++)
{
D[i] = x * A[i] + x * B[i];
}
#pragma omp for
for (i = 0; i < N; i++)
{
C[i] = c * D[i];
}
} // end omp parallel
return 0;
}
/*
Ex3
This cannot be parallelised and the explanation is given in the report
*/
int main(int argc, char **argv) {
int i;
int N = 5;
double A[] = {3,2,4,1,2}, B[] = {1,4,3,2,6}, C[N], D[N];
const double c = 4;
const double x = 7;
double y;
#pragma omp parallel for
for (int i = 1; i < N; i++)
{
A[i] = B[i] – A[i – 1];
}
return 0;
}
/*
Ex4
*/
int main(int argc, char **argv) {
double A[2] = {}, B[4] = {4,3,2,6}, C[2] = {2,2};
void mxv_row(int m, int n, double *A, double *B, double *C)
{
int i, j;
#pragma omp parallel for private(i,j) shared(m,n,A,B,C)
for (i=0; i<m; i++)
{
A[i] = 0.0;
for (j=0; j<n; j++)
{
A[i] += B[i*n+j]*C[j];
}
}
}
mxv_row(2,2,A,B,C);
return 0;
}
<file_sep>#include "../main/main.h"
#include "../scheduler/ttc_scheduler_o.h"
#include "../adc/adc.h"
#include "../tasks/led_bank.h"
#include "../tasks/rgb_led.h"
#include "../tasks/seven_seg.h"
#include "../tasks/serial_output.h"
int main (void)
{
// initialising all the various hardware
adc_initialise();
serial_output_init();
rgb_led_init();
seven_seg_init();
led_bank_init();
SCH_Init();
SCH_Start();
SCH_Add_Task(rgb_update, 0, 100); // updates the RGB LED based on the rate of change of a channel
SCH_Add_Task(adc_0_update, 1, 100); // updates information regarding ADC channel 0
SCH_Add_Task(adc_1_update, 2, 100); // updates information regarding ADC channel 1
SCH_Add_Task(adc_2_update, 3, 100); // updates information regarding ADC channel 2
SCH_Add_Task(serial_output_update, 7, 100); //updates the serial terminal output
SCH_Add_Task(seven_seg_update, 5, 100); // updates the seven segment display
SCH_Add_Task(led_display_adc_0_average, 11, 100); // updates pca9532 LEDs according to ADC channel 0
while(1)
{
SCH_Dispatch_Tasks();
}
return 0;
}
void check_failed(uint8_t *file, uint32_t line)
{
/* User can add his own implementation to report the file name and line number,
ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
/* Infinite loop */
while(1);
}
<file_sep><link rel='stylesheet' href='web/swiss.css'/>
# Spring MVC: exercise 06 - Unit testing with JUnit and Hamcrest
The following exercises need to be solved in the files under the folder `src/test/java`, in the package `code`.
To run your JUnit cases, there are different options:
* From the STS IDE:
* right click on source code folder `src/test/java` or on a specific test java file
* `Run As` > `JUnit test`
* You will see the result in the JUnit view
* From Gradle (terminal)
* run `./gradlew test`
* this will generate a report under `build/reports/tests/index.html`, which can be accessed
* If you can't see the folder `build`, go to section [Troubleshooting](#troubleshooting) of this worksheet.
* From the STS IDE: right click on file `index.html` > `Open with...` > `Web browser`
* From your system: use a browser and access `file:///<absolute path>/build/reports/tests/index.html`
## :star: Exercise 1
Ensure via JUnit tests with Hamcrest matchers that `list` from `code.JUnitExercise.java`:
1. has a size of `3`
2. contains the elements `2, 4, 5` in any order
3. every item is greater than `1`
## :star: Exercise 2
Ensure via JUnit tests with Hamcrest matchers that the `ints` array from `code.JUnitExercise.java`:
1. has a size of `4`
2. contains `7, 5, 12, 16` in the given order
## :star: Exercise 3
Write JUnit tests that, using Hamcrest matchers, ensure that:
1. `""` is an empty string
2. a given string (e.g. `""`), check that it is either empty or null
## :star::star: Exercise 4
Given the class `code.Todo.java`, write tests that use Hamcrest matchers (for beans) that ensure that:
1. A `Todo` object has a property called `"task"`
2. If a `Todo` object is constructed with the task `"Learn Hamcrest"` that the task property has the correct value
3. Two objects created with the same values, have the same property values
## :star: Exercise 5
Given the class `code.Todo.java`, write tests that use Hamcrest matchers (for beans) that ensure that:
* the method `Todo::setYear(int)` throws an exception of type `Exception.class` when we use a year that has already passed (e.g. `2006`)
## Troubleshooting
### I can't see the `build` folder
You may not be able to see the `build` folder in `Package explorer` of the Java perspective of your STS if it is being filtered
To show it, in the `Package explorer` of the Java perspective, click on `1` and `2` as shown in the picture:
<img src="./web/show-filter-menu.png" width=350 height=300>
Deselect `Gradle build folder` if it is currently excluded from the view:
<img src="./web/filter-menu-gradle-build.png" width=300 height=400>
## Additional resources
* [Hamcrest (homepage)](http://hamcrest.org)
* [Hamcrest quick reference](http://www.marcphilipp.de/downloads/posts/2013-01-02-hamcrest-quick-reference/Hamcrest-1.3.pdf)
* [Hamcrest examples](http://www.leveluplunch.com/java/examples/#java-hamcrest)
* [Using Hamcrest for testing - Tutorial](http://www.vogella.com/tutorials/Hamcrest/article.html) (Vogella)
* [Three ways to test exceptions](http://www.mkyong.com/unittest/junit-4-tutorial-2-expected-exception-test/) (Mkyong.com)<file_sep>#include "joystick_controller.h"
/*initialising the external variable (mode) to 0.
* So none of the RGB LEDs will be on when the program is run until the joystick is moved
* in any of the three directions*/
uint8_t mode = 0;
//function initialising the joystick
void joystick_controller_init(void)
{
joystick_init();
}
//function which controls the RGB LEDs and changes the mode of the joystick depending on its direction
void joystick_controller_update(void)
{
/*setting up a variable which is assigned the function joystick_read
* this function returns the status of the joystick, i.e. the position of the joystick*/
uint8_t joystick_status = joystick_read();
/*if the joystick is moved to the left
* then the RED led is switched on
* and the mode of the joystick is set to 1*/
if (joystick_status & JOYSTICK_LEFT)
{
rgb_setLeds(RGB_RED);
mode = 1;
}
/*if the joystick is moved to the right
* then the BLUE led is switched on,
* all the LEDs are turned off i.e. clearing the LEDs
* and the mode of the joystick is set to 2*/
if (joystick_status & JOYSTICK_RIGHT)
{
rgb_setLeds(RGB_BLUE);
pca9532_setLeds(0x0000, 0xFFFF);
mode = 2;
}
/*if the joystick is moved upwards
* then the GREEN led is switched on
* all the LEDs are turned off i.e. clearing the LEDs
* and the mode of the joystick is set to 3*/
if (joystick_status & JOYSTICK_UP)
{
rgb_setLeds(RGB_GREEN);
pca9532_setLeds(0x0000, 0xFFFF);
mode = 3;
}
}
<file_sep>#include "rotary_update.h"
//initialising the state of the rotary encoder to stationary
uint8_t state = ROTARY_WAIT;
//function initialising the rotary encoder
void RotaryEncoder_Init(void)
{
rotary_init();
}
//function which controls the rotary encoder
void RotaryEncoder_Update(void)
{
/*setting up a variable which is assigned the function rotary_read
this function returns the status of the rotary encoder, i.e. if the rotary encoder*/
state = rotary_read();
//if the rotary encoder is not stationary
if (state != ROTARY_WAIT)
{
/*if the rotary encoder is being turned clockwise and the speed at which the
digit is changing is less than 1.5 seconds
then the variable update_frequency is incremented*/
if ((state == ROTARY_RIGHT) && (update_frequency < 15))
{
update_frequency++;
}
/*if the rotary encoder is being turned anti-clockwise and the speed at which the
digit is changing is greater than 0.5 seconds
then the variable update_frequency is decremented*/
if ((state == ROTARY_LEFT) && (update_frequency > 5))
{
update_frequency--;
}
}
}
<file_sep>// hello-world.cpp
// program to print out a "Welcome to C++" message
// Author: nt161
// Version: 1
#include <iostream>
int main () {
std::cout << "Welcome to C++" << std::endl;
return 0;
}
<file_sep>package jpa.c;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
@Entity(name="Ex3_Department")
public class Ex3_Department {
@Id
@GeneratedValue(strategy=GenerationType.TABLE)
@Column(name="dept_code", nullable=false)
private String dept_code;
@Column(name="dept_name", nullable=false)
private String dept_name;
@OneToMany(fetch=FetchType.LAZY, cascade=CascadeType.ALL, orphanRemoval=true)
@JoinColumn(name="module_dept", referencedColumnName="dept_code")
private List<Ex3_Module> moduleList = new ArrayList<>();
}<file_sep>/*
* seven_seg.h
*
* Created on: 20 March 2018
* Author: nt161
*/
#ifndef TASKS_SEVEN_SEG_HEADER_
#define TASKS_SEVEN_SEG_HEADER_
#include "lpc17xx_pinsel.h"
#include "lpc17xx_gpio.h"
#include "lpc17xx_ssp.h"
#include "led7seg.h"
#include "../adc/adc.h"
// ------ Public function prototypes -------------------------------
void seven_seg_init(void);
void seven_seg_update(void);
#endif /* TASKS_SEVEN_SEG_HEADER_ */
<file_sep>#/bin/sh
#write a shell script to start the RMI server
#Question (4.4)
java -cp ./bin/ -Djava.rmi.server.codebase=https://campus.cs.le.ac.uk/people/nt161/Coursework2-server.jar -Djava.rmi.server.useCodebaseOnly=false -Djava.security.policy=https://campus.cs.le.ac.uk/people/nt161/policy.permission CO3090.assignment2.server.RFSServer
<file_sep>/*
* system.h - SOPC Builder system and BSP software package information
*
* Machine generated for CPU 'TT_Core' in SOPC Builder design 'slave'
* SOPC Builder design path: C:/Users/a/Documents/EG3205_Work/Assignment_2_solution/slave/slave.sopcinfo
*
* Generated: Wed Dec 12 22:55:30 GMT 2018
*/
/*
* DO NOT MODIFY THIS FILE
*
* Changing this file will have subtle consequences
* which will almost certainly lead to a nonfunctioning
* system. If you do modify this file, be aware that your
* changes will be overwritten and lost when this file
* is generated again.
*
* DO NOT MODIFY THIS FILE
*/
/*
* License Agreement
*
* Copyright (c) 2008
* Altera Corporation, San Jose, California, USA.
* All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
* This agreement shall be governed in all respects by the laws of the State
* of California and by the laws of the United States of America.
*/
#ifndef __SYSTEM_H_
#define __SYSTEM_H_
/* Include definitions from linker script generator */
#include "linker.h"
/*
* CPU configuration
*
*/
#define ALT_CPU_ARCHITECTURE "altera_nios2_qsys"
#define ALT_CPU_BIG_ENDIAN 0
#define ALT_CPU_BREAK_ADDR 0x00008820
#define ALT_CPU_CPU_FREQ 50000000u
#define ALT_CPU_CPU_ID_SIZE 1
#define ALT_CPU_CPU_ID_VALUE 0x00000001
#define ALT_CPU_CPU_IMPLEMENTATION "tiny"
#define ALT_CPU_DATA_ADDR_WIDTH 0x10
#define ALT_CPU_DCACHE_LINE_SIZE 0
#define ALT_CPU_DCACHE_LINE_SIZE_LOG2 0
#define ALT_CPU_DCACHE_SIZE 0
#define ALT_CPU_EXCEPTION_ADDR 0x00000020
#define ALT_CPU_FLUSHDA_SUPPORTED
#define ALT_CPU_FREQ 50000000
#define ALT_CPU_HARDWARE_DIVIDE_PRESENT 0
#define ALT_CPU_HARDWARE_MULTIPLY_PRESENT 0
#define ALT_CPU_HARDWARE_MULX_PRESENT 0
#define ALT_CPU_HAS_DEBUG_CORE 1
#define ALT_CPU_HAS_DEBUG_STUB
#define ALT_CPU_HAS_JMPI_INSTRUCTION
#define ALT_CPU_ICACHE_LINE_SIZE 0
#define ALT_CPU_ICACHE_LINE_SIZE_LOG2 0
#define ALT_CPU_ICACHE_SIZE 0
#define ALT_CPU_INST_ADDR_WIDTH 0x10
#define ALT_CPU_NAME "TT_Core"
#define ALT_CPU_RESET_ADDR 0x00000000
/*
* CPU configuration (with legacy prefix - don't use these anymore)
*
*/
#define NIOS2_BIG_ENDIAN 0
#define NIOS2_BREAK_ADDR 0x00008820
#define NIOS2_CPU_FREQ 50000000u
#define NIOS2_CPU_ID_SIZE 1
#define NIOS2_CPU_ID_VALUE 0x00000001
#define NIOS2_CPU_IMPLEMENTATION "tiny"
#define NIOS2_DATA_ADDR_WIDTH 0x10
#define NIOS2_DCACHE_LINE_SIZE 0
#define NIOS2_DCACHE_LINE_SIZE_LOG2 0
#define NIOS2_DCACHE_SIZE 0
#define NIOS2_EXCEPTION_ADDR 0x00000020
#define NIOS2_FLUSHDA_SUPPORTED
#define NIOS2_HARDWARE_DIVIDE_PRESENT 0
#define NIOS2_HARDWARE_MULTIPLY_PRESENT 0
#define NIOS2_HARDWARE_MULX_PRESENT 0
#define NIOS2_HAS_DEBUG_CORE 1
#define NIOS2_HAS_DEBUG_STUB
#define NIOS2_HAS_JMPI_INSTRUCTION
#define NIOS2_ICACHE_LINE_SIZE 0
#define NIOS2_ICACHE_LINE_SIZE_LOG2 0
#define NIOS2_ICACHE_SIZE 0
#define NIOS2_INST_ADDR_WIDTH 0x10
#define NIOS2_RESET_ADDR 0x00000000
/*
* Define for each module class mastered by the CPU
*
*/
#define __ALTERA_AVALON_MUTEX
#define __ALTERA_AVALON_ONCHIP_MEMORY2
#define __ALTERA_AVALON_PIO
#define __ALTERA_AVALON_TIMER
#define __ALTERA_NIOS2_QSYS
/*
* System configuration
*
*/
#define ALT_DEVICE_FAMILY "Cyclone III"
#define ALT_ENHANCED_INTERRUPT_API_PRESENT
#define ALT_IRQ_BASE NULL
#define ALT_LOG_PORT "/dev/null"
#define ALT_LOG_PORT_BASE 0x0
#define ALT_LOG_PORT_DEV null
#define ALT_LOG_PORT_TYPE ""
#define ALT_NUM_EXTERNAL_INTERRUPT_CONTROLLERS 0
#define ALT_NUM_INTERNAL_INTERRUPT_CONTROLLERS 1
#define ALT_NUM_INTERRUPT_CONTROLLERS 1
#define ALT_STDERR "/dev/null"
#define ALT_STDERR_BASE 0x0
#define ALT_STDERR_DEV null
#define ALT_STDERR_TYPE ""
#define ALT_STDIN "/dev/null"
#define ALT_STDIN_BASE 0x0
#define ALT_STDIN_DEV null
#define ALT_STDIN_TYPE ""
#define ALT_STDOUT "/dev/null"
#define ALT_STDOUT_BASE 0x0
#define ALT_STDOUT_DEV null
#define ALT_STDOUT_TYPE ""
#define ALT_SYSTEM_NAME "slave"
/*
* TT_core_memory configuration
*
*/
#define ALT_MODULE_CLASS_TT_core_memory altera_avalon_onchip_memory2
#define TT_CORE_MEMORY_ALLOW_IN_SYSTEM_MEMORY_CONTENT_EDITOR 0
#define TT_CORE_MEMORY_ALLOW_MRAM_SIM_CONTENTS_ONLY_FILE 0
#define TT_CORE_MEMORY_BASE 0x0
#define TT_CORE_MEMORY_CONTENTS_INFO ""
#define TT_CORE_MEMORY_DUAL_PORT 0
#define TT_CORE_MEMORY_GUI_RAM_BLOCK_TYPE "AUTO"
#define TT_CORE_MEMORY_INIT_CONTENTS_FILE "slave_TT_core_memory"
#define TT_CORE_MEMORY_INIT_MEM_CONTENT 1
#define TT_CORE_MEMORY_INSTANCE_ID "NONE"
#define TT_CORE_MEMORY_IRQ -1
#define TT_CORE_MEMORY_IRQ_INTERRUPT_CONTROLLER_ID -1
#define TT_CORE_MEMORY_NAME "/dev/TT_core_memory"
#define TT_CORE_MEMORY_NON_DEFAULT_INIT_FILE_ENABLED 0
#define TT_CORE_MEMORY_RAM_BLOCK_TYPE "AUTO"
#define TT_CORE_MEMORY_READ_DURING_WRITE_MODE "DONT_CARE"
#define TT_CORE_MEMORY_SINGLE_CLOCK_OP 0
#define TT_CORE_MEMORY_SIZE_MULTIPLE 1
#define TT_CORE_MEMORY_SIZE_VALUE 16384
#define TT_CORE_MEMORY_SPAN 16384
#define TT_CORE_MEMORY_TYPE "altera_avalon_onchip_memory2"
#define TT_CORE_MEMORY_WRITABLE 1
/*
* hal configuration
*
*/
#define ALT_MAX_FD 32
#define ALT_SYS_CLK TT_TIMER_1
#define ALT_TIMESTAMP_CLK none
/*
* msg_buf_mutex configuration
*
*/
#define ALT_MODULE_CLASS_msg_buf_mutex altera_avalon_mutex
#define MSG_BUF_MUTEX_BASE 0x9480
#define MSG_BUF_MUTEX_IRQ -1
#define MSG_BUF_MUTEX_IRQ_INTERRUPT_CONTROLLER_ID -1
#define MSG_BUF_MUTEX_NAME "/dev/msg_buf_mutex"
#define MSG_BUF_MUTEX_OWNER_INIT 0
#define MSG_BUF_MUTEX_OWNER_WIDTH 16
#define MSG_BUF_MUTEX_SPAN 8
#define MSG_BUF_MUTEX_TYPE "altera_avalon_mutex"
#define MSG_BUF_MUTEX_VALUE_INIT 0
#define MSG_BUF_MUTEX_VALUE_WIDTH 16
/*
* msg_buf_ram configuration
*
*/
#define ALT_MODULE_CLASS_msg_buf_ram altera_avalon_onchip_memory2
#define MSG_BUF_RAM_ALLOW_IN_SYSTEM_MEMORY_CONTENT_EDITOR 0
#define MSG_BUF_RAM_ALLOW_MRAM_SIM_CONTENTS_ONLY_FILE 0
#define MSG_BUF_RAM_BASE 0x9000
#define MSG_BUF_RAM_CONTENTS_INFO ""
#define MSG_BUF_RAM_DUAL_PORT 0
#define MSG_BUF_RAM_GUI_RAM_BLOCK_TYPE "AUTO"
#define MSG_BUF_RAM_INIT_CONTENTS_FILE "slave_msg_buf_ram"
#define MSG_BUF_RAM_INIT_MEM_CONTENT 1
#define MSG_BUF_RAM_INSTANCE_ID "NONE"
#define MSG_BUF_RAM_IRQ -1
#define MSG_BUF_RAM_IRQ_INTERRUPT_CONTROLLER_ID -1
#define MSG_BUF_RAM_NAME "/dev/msg_buf_ram"
#define MSG_BUF_RAM_NON_DEFAULT_INIT_FILE_ENABLED 0
#define MSG_BUF_RAM_RAM_BLOCK_TYPE "AUTO"
#define MSG_BUF_RAM_READ_DURING_WRITE_MODE "DONT_CARE"
#define MSG_BUF_RAM_SINGLE_CLOCK_OP 0
#define MSG_BUF_RAM_SIZE_MULTIPLE 1
#define MSG_BUF_RAM_SIZE_VALUE 1024
#define MSG_BUF_RAM_SPAN 1024
#define MSG_BUF_RAM_TYPE "altera_avalon_onchip_memory2"
#define MSG_BUF_RAM_WRITABLE 1
/*
* tt_leds configuration
*
*/
#define ALT_MODULE_CLASS_tt_leds altera_avalon_pio
#define TT_LEDS_BASE 0x9430
#define TT_LEDS_BIT_CLEARING_EDGE_REGISTER 0
#define TT_LEDS_BIT_MODIFYING_OUTPUT_REGISTER 0
#define TT_LEDS_CAPTURE 0
#define TT_LEDS_DATA_WIDTH 4
#define TT_LEDS_DO_TEST_BENCH_WIRING 0
#define TT_LEDS_DRIVEN_SIM_VALUE 0
#define TT_LEDS_EDGE_TYPE "NONE"
#define TT_LEDS_FREQ 50000000
#define TT_LEDS_HAS_IN 0
#define TT_LEDS_HAS_OUT 1
#define TT_LEDS_HAS_TRI 0
#define TT_LEDS_IRQ -1
#define TT_LEDS_IRQ_INTERRUPT_CONTROLLER_ID -1
#define TT_LEDS_IRQ_TYPE "NONE"
#define TT_LEDS_NAME "/dev/tt_leds"
#define TT_LEDS_RESET_VALUE 0
#define TT_LEDS_SPAN 16
#define TT_LEDS_TYPE "altera_avalon_pio"
/*
* tt_pb_1 configuration
*
*/
#define ALT_MODULE_CLASS_tt_pb_1 altera_avalon_pio
#define TT_PB_1_BASE 0x9420
#define TT_PB_1_BIT_CLEARING_EDGE_REGISTER 0
#define TT_PB_1_BIT_MODIFYING_OUTPUT_REGISTER 0
#define TT_PB_1_CAPTURE 0
#define TT_PB_1_DATA_WIDTH 1
#define TT_PB_1_DO_TEST_BENCH_WIRING 1
#define TT_PB_1_DRIVEN_SIM_VALUE 0
#define TT_PB_1_EDGE_TYPE "NONE"
#define TT_PB_1_FREQ 50000000
#define TT_PB_1_HAS_IN 1
#define TT_PB_1_HAS_OUT 0
#define TT_PB_1_HAS_TRI 0
#define TT_PB_1_IRQ -1
#define TT_PB_1_IRQ_INTERRUPT_CONTROLLER_ID -1
#define TT_PB_1_IRQ_TYPE "NONE"
#define TT_PB_1_NAME "/dev/tt_pb_1"
#define TT_PB_1_RESET_VALUE 0
#define TT_PB_1_SPAN 16
#define TT_PB_1_TYPE "altera_avalon_pio"
/*
* tt_timer_1 configuration
*
*/
#define ALT_MODULE_CLASS_tt_timer_1 altera_avalon_timer
#define TT_TIMER_1_ALWAYS_RUN 0
#define TT_TIMER_1_BASE 0x9400
#define TT_TIMER_1_COUNTER_SIZE 32
#define TT_TIMER_1_FIXED_PERIOD 0
#define TT_TIMER_1_FREQ 50000000
#define TT_TIMER_1_IRQ 0
#define TT_TIMER_1_IRQ_INTERRUPT_CONTROLLER_ID 0
#define TT_TIMER_1_LOAD_VALUE 49999
#define TT_TIMER_1_MULT 0.0010
#define TT_TIMER_1_NAME "/dev/tt_timer_1"
#define TT_TIMER_1_PERIOD 1
#define TT_TIMER_1_PERIOD_UNITS "ms"
#define TT_TIMER_1_RESET_OUTPUT 0
#define TT_TIMER_1_SNAPSHOT 1
#define TT_TIMER_1_SPAN 32
#define TT_TIMER_1_TICKS_PER_SEC 1000.0
#define TT_TIMER_1_TIMEOUT_PULSE_OUTPUT 0
#define TT_TIMER_1_TYPE "altera_avalon_timer"
#endif /* __SYSTEM_H_ */
<file_sep>package eMarket.controller;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
import eMarket.EMarketApp;
import eMarket.domain.Deal;
public class DealValidator implements Validator {
public boolean supports(Class<?> clazz) {
return DealFormDto.class.equals(clazz);
}
@Override
public void validate(Object target, Errors errors) {
DealFormDto dto = (DealFormDto) target;
// TODO: add validation code here
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "startDate", "", "Field cannot be empty.");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "discount", "", "Field cannot be empty.");
if(dto.getProductId() == -1){
errors.rejectValue("productId", "", "Product invalid: have to choose a product.");
}
if ((dto.getDiscount() >= 1) || (dto.getDiscount() <= 0)) {
errors.rejectValue("discount", "", "Discount invalid: cannot be less than/equal to 0 or greater than 1.");
}
if((dto.getStartDate() == null)) {
errors.rejectValue("startDate", "", "Start date invalid: cannot be before empty.");
}
if((dto.getEndDate() != null) && (dto.getStartDate() != null) && (dto.getEndDate().isBefore(dto.getStartDate()))) {
errors.rejectValue("endDate", "", "End date invalid: cannot be before system date.");
}
if((dto.getStartDate()!= null)){
if((dto.getEndDate()== null)){
for(int i = 0; i<EMarketApp.getStore().getDealList().size(); i++){
if(dto.getProductId() == EMarketApp.getStore().getDealList().get(i).getId()){
if(EMarketApp.getStore().getDealList().get(i).getEndDate().isAfter(dto.getStartDate())){
errors.rejectValue("startDate", "", "Start date invalid: overlapping dates.");
}
}
}
}
}
if(dto.getEndDate()!=null){
for(int i = 0; i<EMarketApp.getStore().getDealList().size(); i++){
if(dto.getProductId() == EMarketApp.getStore().getDealList().get(i).getId()){
if (!(EMarketApp.getStore().getDealList().get(i).getEndDate().isBefore(dto.getStartDate()) || EMarketApp.getStore().getDealList().get(i).getStartDate().isAfter(dto.getEndDate()))) {
errors.rejectValue("endDate", "", "Date invalid: overlapping dates.");
}
}
}
}
}
}<file_sep>#include "Project.h"
Project::Project(const string& projectInfo)
{
istringstream projectStream(projectInfo);
projectStream >> project_id;
projectStream >> staff_id;
projectStream >> multiplicity;
getline(projectStream, proj_title);
}
Project::~Project() {
}
int Project::getProjID() const {
return project_id;
}
string Project::getStaffID() const {
return staff_id;
}
int Project::getMultiplicity() const {
return multiplicity;
}
void Project::reduceMultiplicity() {
multiplicity--;
}
string Project::getProjTitle() const {
return proj_title;
}
<file_sep><link rel='stylesheet' href='web/swiss.css'/>
# CO2006 17-18 - SPRINT 3 - MINIPROJECT
## Disclaimer on Plagiarism and Collusion
This is an **individual piece of coursework** that is assessed. Plagiarism, including collusion, is penalized. For further information check the [section Referencing and Academic Integrity in the BSc handbook](https://campus.cs.le.ac.uk/ForStudents/handbooks17/BScStudentHandbook2017-18.pdf).
By submitting your solution, you are stating that you are aware of the consequences, as summarized in the [Declaration of Academic Honesty](https://campus.cs.le.ac.uk/ForStudents/plagiarism/DoAIF.pdf) that you signed already, and that the solution provided for the worksheet is the result of your **sole individual work**.
## Description
An initial prototype of a login system has been implemented as a Spring MVC web application. After a meeting with the main stakeholders, this first prototype is assumed to be correct and is going to be modified in different branches of development by different teams for different products. In order to ensure that subsequent changes do not affect the original functionality of the system, an executable specification of the system has to be developed in the file [src/test/groovy/LoginSpec.groovy](https://github.com/uol-inf/CO2006-17-18/blob/master/sprint3/miniproject/src/test/groovy/app/LoginSpec.groovy).
Two important aspects need to be considered when designing and developing the feature specification:
1. **Navigation route coverage**: all possible navigation routes have to be tested, considering navigation using request mappings and redirections in the controllers, and validation code in the validator classes. That is, the code that has to be inspected is in request handler methods of controllers (`LoginController` and `SignupController`) and in classes providing support for validation (`UserInfoLoginValidator` and `UserInfoValidator`).
2. **Feature methods** (test cases):
* Test cases must be developed using the [Spock framework](http://spockframework.org/) and they should be well documented using behaviour-driven development stories, using the structure `given/when/then` (or equivalent).
* There must be a test case for each route in the JUnit report generated by the command `./gradlew clean test` (or equivalent command in Windows) at `build/reports/tests/test/index.html` (test cases listed under `app>LoginSpec`). If you use a block `where:`, apply [method unrolling](http://spockframework.org/spock/docs/1.1/all_in_one.html#_method_unrolling) using the annotation `@Unroll` and placeholders in the name of the test case.
* All test cases must pass but the oracle in the test case must be meaningful. That is, a test case that is always correct independently of the system will be deemed to be incorrect.
Copy the source code of the login system to your GitHub repository and develop the specification in the file [src/test/groovy/app/LoginSpec.groovy](https://github.com/uol-inf/CO2006-17-18/blob/master/sprint3/miniproject/src/test/groovy/app/LoginSpec.groovy).
## Exercises
### Rubric
In order to give an idea of the level of effort required for each exercise, exercises are tagged with a level of difficulty as follows:
* :star: : The effort lays in implementing the description of the given test case. The challenge consists in using appropriate matchers (from `Hamcrest` or from `Spring MVC Test`) to define assertions as described.
* :star::star: : As above but the structure of the test case is not given. You need to determine what blocks to use and document the appropriately. The challenge consists in developing feature methods using Spock and in defining correct assertions, which are not given explicitly.
* :star::star::star:: As above but the test cases are not given, you need to find with the help of [Jacoco](http://www.eclemma.org/jacoco/). The challenge consists in knowing **when to stop testing**, considering the [aspects described above](#description), and **in determining the correctness of the test cases**.
### :star: A. Writing feature methods [50 marks]
Implement the following feature methods in the class `LoginSpec` using `Spock` and appropriate matchers for the assertions. All test cases under this section carry equal marks.
Only **valid** test cases that **pass** are considered correct. That is:
* tests with assertions that are always correct or incorrect do not contribute towards the mark; and
* failures do not contribute towards the mark.
0.
**Given** the context of the controller is setup<br/>
**When** I perform an HTTP GET '/'<br/>
**Then** the status of the HTTP reponse should be `Ok` (`200`)<br/>
**And** I should see the view `Landing`<br/>
1.
**Given** the context of the controller is setup<br/>
**When** I perform an HTTP GET '/main'<br/>
**Then** the status of the HTTP reponse should be `Ok` (`200`)<br/>
**And** I should see the view `Main`<br/>
2.
**Given** the context of the controller is setup<br/>
**When** I perform an HTTP GET '/login'<br/>
**Then** the status of the HTTP reponse should be `Ok` (`200`)<br/>
**And** I should see the view `Login`<br/>
3.
**Given** the context of the controller is setup<br/>
**When** I perform an HTTP POST `/authenticate` with<br/>
* `accept = ''`
* `login = 'a'`
* `password = ''`
**Then** the status of the HTTP reponse should be `Ok` (`200`)<br/>
**And** I should see the view `Login`<br/>
4.
**Given** the context of the controller is setup<br/>
**When** I perform an HTTP POST `/authenticate` with<br/>
* `accept = ''`
* `login = ''`
* `password = 'a'`
**Then** the status of the HTTP reponse should be `Ok` (`200`)<br/>
**And** I should see the view `Login`<br/>
5.
**Given** the context of the controller is setup<br/>
**When** I perform an HTTP POST `/add` with<br/>
* `add=''`
* `forenames = 'Joe'`
* `lastnames = 'Smith'`
* `login = 'js100'`
* `password = '<PASSWORD>'`
* `password2 = '<PASSWORD>'`
**Then** I should see the view `redirect:login/`<br/>
6.
**Given** the context of the controller is setup<br/>
**When** I perform an HTTP POST `/add` with<br/>
* `add=''`
* `forenames = ''`
* `lastnames = 'Smith'`
* `login = 'js100'`
* `password = '<PASSWORD>'`
* `password2 = '<PASSWORD>'`
**Then** I should see the view `Signup`<br/>
7.
**Given** the context of the controller is setup<br/>
**When** I perform an HTTP POST `/add` with<br/>
* `add=''`
* `forenames = 'Joe'`
* `lastnames = ''`
* `login = 'js100'`
* `password = '<PASSWORD>'`
* `password2 = '<PASSWORD>'`
**Then** I should see the view `Signup`<br/>
### :star::star: B. Building a specification from semi-informal requirements [20 marks]
Implement the following scenarios as feature methods in the class `LoginSpec` using `Spock` and appropriate matchers for the assertions. All test cases under this section carry equal marks.
Only **valid** test cases that **pass** are considered correct. That is:
* tests with assertions that are always correct or incorrect do not contribute towards the mark; and
* failures do not contribute towards the mark.
8. The HTTP GET request `/signup` should redirect the user to the view `Signup`
9. The HTTP POST request `/authenticate` with the values listed below for the attributes of the command object `userInfoLogin` should redirect the user to view `Login`:
* `accept = ''`
* `login = 'user'`
* `password = 'a'`
10. The HTTP POST request `/add` with the values listed below for the attributes of the command object `userInfo` should redirect the user to view `Signup`:
* `add=''`
* `forenames = 'Joe'`
* `lastnames = 'Smith'`
* `login = ''`
* `password = '<PASSWORD>'`
* `password2 = '<PASSWORD>'`
11. The HTTP POST request `/add` with the values listed below for the attributes of the command object `userInfo` should redirect the user to view `Signup`:
* `add=''`
* `forenames = 'Joe'`
* `lastnames = 'Smith'`
* `login = 'js100'`
* `password = ''`
* `password2 = '<PASSWORD>'`
### :star::star::star: C. Build a feature specification that is complete and correct [30 marks]
Complete the feature specification with feature methods in order to guarantee that you have tested the web app in full. That is, find as many feature methods as possible in order to achieve 100% coverage of the source code, ensuring that all possible navigation routes have been covered. We are going to use [Jacoco](http://www.eclemma.org/jacoco/) for computing code coverage with respect to a JUnit test suite.
Note that, in addition, test cases must be correct.
Two main aspects are going to be considered when marking this section:
1. **Navigation route coverage**: a percentage of the covered navigational routes will be considered as an upper bound of your mark. That is if tests cases only cover 90% of all the possible navigation routes, the maximum mark is 90%.
2. **Test cases**:
* The mark for each test is computed with respect to the percentage of navigation routes covered. For a given coverage percentage, e.g. 90% of navigation routes, if there are several tests for the same navigation route, the mark for each test case will be small. For example, if you have 20 tests, the mark for each test will be of 4.5 marks out of 100 (`= 90/20`), and 1.35 out of 30.<br/>
If, instead, only the minimum amount of tests for exercising the system navigational routes is provided, the test will carry a greater mark. For example, if this bound was 2 tests, each test case developed would be worth 45 marks (`= 90/2`) out of 100, and 13.5 out of 30.
* Only **valid** test cases that **pass** are considered correct. That is:
* tests with assertions that are always correct or incorrect do not contribute towards the mark; and
* failures do not contribute towards the mark.
* *Hint*: there are less than 20 test cases.
There is no limit in the number of test cases to be developed but there is a point where adding more test cases is pointless (and it is your job, as a tester, to find what this upper bound may be). However, please do not try with more than 20 test cases.
## Submission procedure
### Checkpoint: Wed 15/11/2017, 23:59 (midnight)
* Commit and push your mini project (the whole project) to your GitHub repository, under the folder `sprint3/miniproject` so that you can find your file `gradle.build` in `sprint3/miniproject/gradle.build`
* A smoke test (that is, a simple test with a trivial assertion, e.g. `1==1`) should be available so that when `./gradlew test` (or equivalent command for `MS Windows`) is executed, the Spock test report should be generated automatically without problems. This should have been generated at `build/spock-reports/index.html`. In addition, a JUnit report should appear at `build/reports/tests/test/index.html`.
### Release: Wed 22/11/2017, 23:59 (midnight)
* The steps for the checkpoint, as explained above, should have been implemented.
* Make a release on GitHub
1. Open the repo in Github
2. Click Releases
3. Click `Create a new release`
4. Enter the `Tag Version` as `sprint3` (leave `@ Target Master`)
5. Enter the `Release Title` as `Sprint 3 submission`
6. Click `Publish Release`
## Submission
This assignment is worth **20%** of the overall module mark and the mark is provided out of **100**:
* 10% for the checkpoint submission
* 90% for the release submission
### CHECKPOINT SUBMISSION (10%)
We are going to consider that the software infrastructure for the assignment is set up:
1. The code is available in your repository the right location: 2.5 marks
2. The `./gradlew test` command can be executed without problems after adding a smoke test (with a dummy assertion): 5 marks
3. The Spock report is generated for the smoke test: 2.5 marks
Note that it is not possible to solve `2` without solving `1`, and `3` without solving `2`.
### RELEASE SUBMISSION (90%)
The project submitted must compile and it must be executable as explained in the worksheet (e.g. there are compilation errors) with the command `./gradlew clean test`. Otherwise, the submission will receive a mark of `0` (`zero`).
<file_sep>/*------------------------------------------------------------------*-
Modifications in the master code by nt161:
-- in the spi_mcp2515.c file the MCP2515_Init(void) was altered and the number of data bytes was changed to 0x03 ----> MCP2515_Write_Register(TXB0DLC, 0x03);
as the master will only send 3 bytes at most in every tick message, byte one being the slave ID and the other two bytes are codes for operating the LEDs on
the slaves.
-- included the pushbutton.h file in the 2_50_XXg.c file in order to send messages to the slave if the push button was pressed
this if statement was implemented in the SCC_A_MASTER_Send_Tick_Message(const tByte SLAVE_INDEX) function in the same file.
-- only two codes are sent to the slave if the push button on the master are pressed, one is 0x06 which turns on LED 5 on the
TT core and 0x03 which turns on LED 0 on the ET core
-- however, if the pushbutton is not pressed a message of 0x43, (as this value is used in the pushbutton.c file, well the ASCII character 'C' is used)
is sent to the slave
Main.c (v1.00)
------------------------------------------------------------------
Demonstration program for:
Generic 16-bit auto-reload scheduler (using a full-featured
interval timer).
Assumes 50 MHz clock signal (-> 50 ms tick interval).
*** All timing is in TICKS (not milliseconds) ***
COPYRIGHT
---------
This code is from the book:
PATTERNS FOR TIME-TRIGGERED EMBEDDED SYSTEMS by <NAME>
[Pearson Education, 2001; ISBN: 0-201-33138-1].
This code is copyright (c) 2001 by <NAME>.
See book for copyright details and other information.
-*------------------------------------------------------------------*/
#include "Main.h"
#include "2_50_XXg.h"
#include "../SPImcp2515/SPI_MCP2515.h"
#include "../Tasks/PushButton.h"
#include "../Tasks/LED_ONOFF.h"
#include "../Tasks/HEARTBEAT.h"
#include "altera_avalon_spi.h"
#include "../SPImcp2515/alt_spi_master.h"
#include "../TTC_Scheduler/PORT.h"
#include <altera_avalon_pio_regs.h>
#include "sys/alt_stdio.h"
/* ............................................................... */
/* ............................................................... */
void alt_main(void)
{
// Set up the scheduler
SCH_Init_T0();
// Prepare for the 'Flash_LED' task
PushButton_Init();
LED_ONOFF_Init();
HEARTBEAT_Init();
// Add the 'Flash LED' task (on for ~1000 ms, off for ~1000 ms)
// - timings are in ticks (50 ms tick interval)
// (Max interval / delay is 65535 ticks)
SCH_Add_Task(PushButton_Update, 2, 5);
SCH_Add_Task(LED_ONOFF_Update, 5, 20);
SCH_Add_Task(HEARTBEAT_Update, 0, 100);
// Start the scheduler
SCH_Start();
while(1)
{
SCH_Dispatch_Tasks();
}
}
/*------------------------------------------------------------------*-
---- END OF FILE -------------------------------------------------
-*------------------------------------------------------------------*/
<file_sep>from math import sin
from numpy.core.multiarray import arange, zeros
from numpy.core.umath import pi
from numpy.matlib import rand, randn
N = 10001
Nf = 3
t = arange(N, dtype=float)
#pick random periods between 10 and 2010 and convert them to frequencies
Ts = rand(Nf)*2000+10
fs = 1./Ts
#pick random amplitudes
amp = rand(Nf)*200+10
#pick random phases
phi = rand(Nf)*2*pi
#calculate signal
h = zeros(N)
for j in range(len(fs)):
print("amp[{}] = {}".format(j,amp[j]))
print("fs[{}] = {}".format(j,fs[j]))
print("phi[{}] = {}".format(j,phi[j]))
h += amp[j]*sin(2*pi*t*fs[j]+phi[j])
#make a noisy signal by adding white noise
#hn = h + randn(N)*3*h + randn(N)*700
<file_sep>/**
* (C) <NAME>, 2017
*/
package eMarket.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class OrderController {
@RequestMapping("/system/user")
public String user() {
return "indexUser";
}
@RequestMapping("/system/premium")
public String premium() {
return "indexPremium";
}
@RequestMapping("/order")
public String order() {
return "form/order";
}
@RequestMapping("/order/wishlist")
public String wishlist() {
return "form/wishlist";
}
}
<file_sep>#include "../scheduler/ttc_scheduler_o.h"
#include "../tasks/joystick_controller.h"
#include "../tasks/adc_task.h"
#include "../tasks/pca9532_leds.h"
#include "rgb.h"
int main (void)
{
rgb_init(); //red, green and blue LEDs initialisation
joystick_controller_init(); //joystick initialisation
adc_init(); //analogue to digital converter initialisation
pca9532_leds_init(); //pca9532 LEDs initialisation
SCH_Init(); //scheduler initialisation
SCH_Add_Task(joystick_controller_update, 0, 75); //updates every 75ms, starting from 0
SCH_Add_Task(adc_update, 2, 20); //updates every 20ms, starting from 2
SCH_Add_Task(pca9532_leds_update, 4, 20); //updates every 20ms, starting from 4
SCH_Start(); //begins scheduler
while(1)
{
SCH_Dispatch_Tasks();//begins tasks
}
return 0;
}
void check_failed(uint8_t *file, uint32_t line)
{
/* User can add his own implementation to report the file name and line number,
ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
/* Infinite loop */
while(1);
}
<file_sep>################################################################################
# Automatically-generated file. Do not edit!
################################################################################
# Add inputs and outputs from these tool invocations to the build variables
C_SRCS += \
../src/tasks/disp7seg_update.c \
../src/tasks/joystick_controller.c \
../src/tasks/rgb_update.c \
../src/tasks/rotary_Update.c \
../src/tasks/ssp_config.c
OBJS += \
./src/tasks/disp7seg_update.o \
./src/tasks/joystick_controller.o \
./src/tasks/rgb_update.o \
./src/tasks/rotary_Update.o \
./src/tasks/ssp_config.o
C_DEPS += \
./src/tasks/disp7seg_update.d \
./src/tasks/joystick_controller.d \
./src/tasks/rgb_update.d \
./src/tasks/rotary_Update.d \
./src/tasks/ssp_config.d
# Each subdirectory must supply rules for building sources it contributes
src/tasks/%.o: ../src/tasks/%.c
@echo 'Building file: $<'
@echo 'Invoking: MCU C Compiler'
arm-none-eabi-gcc -DDEBUG -D__USE_CMSIS=CMSISv1p30_LPC17xx -D__CODE_RED -D__NEWLIB__ -I"C:\Users\NTarannum\Documents\LPCXpresso_8.2.2_650\workspace\EG2204_Assignment2_Final\Lib_CMSISv1p30_LPC17xx\inc" -I"C:\Users\NTarannum\Documents\LPCXpresso_8.2.2_650\workspace\EG2204_Assignment2_Final\Lib_EaBaseBoard\inc" -I"C:\Users\NTarannum\Documents\LPCXpresso_8.2.2_650\workspace\EG2204_Assignment2_Final\Lib_MCU\inc" -O0 -g3 -Wall -c -fmessage-length=0 -fno-builtin -ffunction-sections -mcpu=cortex-m3 -mthumb -D__NEWLIB__ -MMD -MP -MF"$(@:%.o=%.d)" -MT"$(@:%.o=%.o)" -MT"$(@:%.o=%.d)" -o "$@" "$<"
@echo 'Finished building: $<'
@echo ' '
<file_sep>// CONFIGURE PORT
<file_sep>#include "adc_task.h"
//initialising the external variable to 0
uint32_t reading_pot = 0;
//function which initialises the analogue to digital converter
void adc_init (void)
{
PINSEL_CFG_Type PinCfg;
// Configuring pin 23 on port 0 - the trimming pot is connected to this.
// The trimming pot is connected to GPIO_11, and GPIO_11 is P0.23 and also AD0.0
// (Channel 0 of the ADC).
PinCfg.Funcnum = 1;
PinCfg.OpenDrain = 0;
PinCfg.Pinmode = 0;
PinCfg.Pinnum = 23;
PinCfg.Portnum = 0;
PINSEL_ConfigPin(&PinCfg);
// Configure ADC: 0.2 MHz
ADC_Init(LPC_ADC, 200000);
// Disable interrupt
ADC_IntConfig(LPC_ADC,ADC_CHANNEL_0,DISABLE);
// Enable ADC
ADC_ChannelCmd(LPC_ADC,ADC_CHANNEL_0,ENABLE);
}
//function which reads the value of potentiometer
uint32_t adc_read(void)
{
ADC_StartCmd(LPC_ADC,ADC_START_NOW);
// The line below sits in an infinite while loop until data collection
// is complete.
while (!(ADC_ChannelGetStatus(LPC_ADC,ADC_CHANNEL_0,ADC_DATA_DONE)));
return ADC_ChannelGetData(LPC_ADC,ADC_CHANNEL_0);
}
/*function which reads value of the potentiometer and saves it in a variable.
* setting up an external variable which is assigned the function adc_read*/
void adc_update()
{
reading_pot = adc_read();
}
<file_sep>/**
* (C) <NAME>, 2016
*/
package eMarket.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import eMarket.EMarketApp;
import eMarket.domain.UserInfo;
import eMarket.domain.UserInfoLogin;
import eMarket.repository.UserInfoRepository;
@Controller
public class LoginController {
@Autowired UserInfoRepository userInfoRepo;
@InitBinder
protected void initBinder(WebDataBinder binder) {
binder.addValidators(new UserInfoLoginValidator());
}
@RequestMapping(value = "/", method = RequestMethod.GET)
public String landing() {
return "Landing";
}
@RequestMapping(value = "/login-form", method = RequestMethod.GET)
public String login(@ModelAttribute("userInfoLogin") UserInfoLogin userInfoLogin) {
return "login-form";
}
@RequestMapping(value = "/success-login", method = RequestMethod.GET)
public String authenticate() {
System.out.println("enters /success-login");
User authUser = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
authUser.getAuthorities().stream().forEach(c -> System.out.println (c));
System.out.println("logging in as " + authUser.getUsername());
UserInfo user = userInfoRepo.findByLogin(authUser.getUsername());
String view;
switch (user.getRole().getId()) {
case EMarketApp.ADMIN:
view = "redirect:/system/";
break;
case EMarketApp.PREMIUM:
view = "redirect:/system/premium";
break;
default: // case EMarketApp.USER:
view = "redirect:/system/user";
break;
}
return view;
}
@RequestMapping("/access-denied")
public String accessDenied() {
return "redirect:/login-form";
}
}
<file_sep>// adding.cpp
// program to asks the user to input two numbers
// and prints the sum of them
//
// Author: nt161
// Version: 1
#include <iostream> // use the standard IO library
#include <string> // use the standard string library
using namespace std;
int main () {
int x,y;
cin >> x;
cin >> y;
int answer = x+ y;
cout << x << " plus " << y << " is "<< answer << endl;
return 0;
}
<file_sep>/*------------------------------------------------------------------*-
ttc_scheduler_o.c (2013-07-07)
-*------------------------------------------------------------------*/
/*------------------------------------------------------------------*-
This code is copyright (c) 2001-2013 <NAME> ("the author").
This code is intended SOLELY for use in training courses (during
which participants examine and complete the code presented here).
The projects is not complete and the code is not suitable for use
in production or prototype systems.
Subject to the above conditions, redistribution and use of this
software - in source or binary form, with or without modification
- is permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.
3. The name of the author may not be used to endorse or promote
products derived from this software without specific prior
written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS
OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-*------------------------------------------------------------------*/
// Project header
#include "../main/main.h"
// Port header
#include "../port/port.h"
#include "ttc_scheduler_o.h"
// ------ Public variable definitions ------------------------------
// Used to report errors, if required, using Heartbeat LED
// See heartbeat.c (if used) for basic error-reporting mechanism
// See ttc_scheduler.h for details of error codes
// See port.h for details of the error port
uint32_t Error_code_G;
// ------ Private variable definitions -----------------------------
// The array of tasks
// Check array size in scheduler header file
sTask SCH_tasks_G[SCH_MAX_TASKS];
// The current tick count
static uint32_t Tick_count_G = 0;
// Flag indicating whether any task is running
static uint32_t Task_running_G = 0;
// ------ Private function prototypes ------------------------------
static void SCH_Go_To_Sleep(void);
/*------------------------------------------------------------------*-
SCH_Init()
Scheduler initialisation function. Prepares scheduler
data structures and sets up timer interrupts every 1 ms.
You must call this function before using the scheduler.
Note: We assume that the processor clock is 100 MHz:
see System_Init() for details of this configuration.
-*------------------------------------------------------------------*/
void SCH_Init(void)
{
uint32_t i;
for (i = 0; i < SCH_MAX_TASKS; i++)
{
SCH_Delete_Task(i);
}
// Reset the global error variable
// - SCH_Delete_Task() will generate an error code,
// (because the task array is empty)
Error_code_G = 0;
// Using CMSIS
//
// Must check board oscillator frequency, etc
// - see "system_lpc17xx.c" (in linked CMSIS project)
//
// *If* these values have been set correctly for your hardware
// SystemCoreClock gives the system operating frequency (in Hz)
if (SystemCoreClock != Required_SystemCoreClock)
{
// Error codes are listed in scheduler header file
Error_code_G = ERROR_SCH_INCORRECT_CORE_FREQUENCY;
}
// Now to set up SysTick timer for 1 ms "ticks"
if (SysTick_Config(SystemCoreClock / 1000))
{
// Fatal error
// Cannot - for some reason - set required tick rate
// (not much we can do if the oscillator is not running correctly)
//
// In most cases, this will force a WDT reset, followed by
// "fail silent" behaviour.
//
// If the WDT is not enabled, the system will simply
// "pause" in the reset state.
while(1);
}
// NOTE: TT design.
// There should only be one interrupt enabled
// - not setting interrupt priorities
}
/*------------------------------------------------------------------*-
SCH_Start()
Starts the scheduler, by enabling SysTick interrupt.
NOTE: Usually called after all regular tasks are added,
to keep the tasks synchronised.
NOTE: ONLY THE SCHEDULER INTERRUPT SHOULD BE ENABLED!!!
-*------------------------------------------------------------------*/
void SCH_Start(void)
{
// Enable SysTick timer
SysTick->CTRL |= 0x01;
// Enable SysTick exception request
SysTick->CTRL |= 0x02;
}
/*------------------------------------------------------------------*-
SysTick_Handler()
[Function name determined by CMIS standard.]
This is the scheduler ISR. It is called at a rate
determined by the timer settings in the SCH_Init() function.
-*------------------------------------------------------------------*/
void SysTick_Handler(void)
{
// Increment tick count (only)
Tick_count_G++;
// As this is a TTC scheduler, we don't usually expect
// to have a task running when the timer ISR is called
if (Task_running_G == 1)
{
// Simple error reporting via heartbeat / error LED.
// (This value is *not* reset.)
Error_code_G = ERROR_SCH_SYSTEM_OVERLOAD;
}
}
/*------------------------------------------------------------------*-
SCH_Dispatch_Tasks()
This is the 'dispatcher' function. When a task (function)
is due to run, SCH_Dispatch_Tasks() will run it.
This function must be called (repeatedly) from the main loop.
-*------------------------------------------------------------------*/
void SCH_Dispatch_Tasks(void)
{
uint32_t Index;
uint32_t Update_required = 0;
// Need to check for a timer interrupt since this
// function was last executed (in case idle mode is not being used)
// Disable timer interrupt
// NOTE: *all* interrupts disabled (but this is a TT design)
__disable_irq();
if (Tick_count_G > 0)
{
Tick_count_G--;
Update_required = 1;
}
// Re-enable timer interrupts
__enable_irq();
while (Update_required)
{
// Go through the task array
for (Index = 0; Index < SCH_MAX_TASKS; Index++)
{
// Check if there is a task at this location
if (SCH_tasks_G[Index].pTask)
{
if (--SCH_tasks_G[Index].Delay == 0)
{
// The task is due to run
// Set "Task_running" flag
__disable_irq();
Task_running_G = 1;
__enable_irq();
(*SCH_tasks_G[Index].pTask)(); // Run the task
// Clear "Task_running" flag
__disable_irq();
Task_running_G = 0;
__enable_irq();
if (SCH_tasks_G[Index].Period != 0)
{
// Schedule period tasks to run again
SCH_tasks_G[Index].Delay = SCH_tasks_G[Index].Period;
}
else
{
// Delete one-shot tasks
SCH_tasks_G[Index].pTask = 0;
}
}
}
}
// Disable timer interrupt
__disable_irq();
if (Tick_count_G > 0)
{
Tick_count_G--;
Update_required = 1;
}
else
{
Update_required = 0;
}
// Re-enable timer interrupts
__enable_irq();
}
// The scheduler may enter idle mode at this point (if used)
SCH_Go_To_Sleep();
}
/*------------------------------------------------------------------*-
SCH_Add_Task()
Causes a task (function) to be executed at regular intervals
or after a user-defined delay
Fn_P - The name of the function which is to be scheduled.
NOTE: All scheduled functions must be 'void, void' -
that is, they must take no parameters, and have
a void return type.
DELAY - The interval (TICKS) before the task is first executed
PERIOD - If 'PERIOD' is 0, the function is only called once,
at the time determined by 'DELAY'. If PERIOD is non-zero,
then the function is called repeatedly at an interval
determined by the value of PERIOD (see below for examples
which should help clarify this).
RETURN VALUE:
Returns the position in the task array at which the task has been
added. If the return value is SCH_MAX_TASKS then the task could
not be added to the array (there was insufficient space). If the
return value is < SCH_MAX_TASKS, then the task was added
successfully.
Note: this return value may be required, if a task is
to be subsequently deleted - see SCH_Delete_Task().
EXAMPLES:
Task_ID = SCH_Add_Task(Do_X,1000,0);
Causes the function Do_X() to be executed once after 1000 sch ticks.
Task_ID = SCH_Add_Task(Do_X,0,1000);
Causes the function Do_X() to be executed regularly, every 1000 sch ticks.
Task_ID = SCH_Add_Task(Do_X,300,1000);
Causes the function Do_X() to be executed regularly, every 1000 ticks.
Task will be first executed at T = 300 ticks, then 1300, 2300, etc.
-*------------------------------------------------------------------*/
uint32_t SCH_Add_Task(void (* pFunction)(),
const uint32_t DELAY,
const uint32_t PERIOD)
{
uint32_t Index = 0;
// First find a gap in the array (if there is one)
while ((SCH_tasks_G[Index].pTask != 0) && (Index < SCH_MAX_TASKS))
{
Index++;
}
// Have we reached the end of the list?
if (Index == SCH_MAX_TASKS)
{
// Task list is full
//
// Set the global error variable
Error_code_G = ERROR_SCH_TOO_MANY_TASKS;
// Also return an error code
return SCH_MAX_TASKS;
}
// If we're here, there is a space in the task array
SCH_tasks_G[Index].pTask = pFunction;
SCH_tasks_G[Index].Delay = DELAY + 1;
SCH_tasks_G[Index].Period = PERIOD;
return Index; // return position of task (to allow later deletion)
}
/*------------------------------------------------------------------*-
SCH_Delete_Task()
Removes a task from the scheduler. Note that this does
*not* delete the associated function from memory:
it simply means that it is no longer called by the scheduler.
TASK_INDEX - The task index. Provided by SCH_Add_Task().
RETURN VALUE: RETURN_ERROR or RETURN_NORMAL
-*------------------------------------------------------------------*/
uint32_t SCH_Delete_Task(const uint32_t TASK_INDEX)
{
uint32_t Return_code;
if (SCH_tasks_G[TASK_INDEX].pTask == 0)
{
// No task at this location...
//
// Set the global error variable
Error_code_G = ERROR_SCH_CANNOT_DELETE_TASK;
// ...also return an error code
Return_code = RETURN_ERROR;
}
else
{
Return_code = RETURN_NORMAL;
}
SCH_tasks_G[TASK_INDEX].pTask = 0x0000;
SCH_tasks_G[TASK_INDEX].Delay = 0;
SCH_tasks_G[TASK_INDEX].Period = 0;
SCH_tasks_G[TASK_INDEX].RunMe = 0;
return Return_code; // return status
}
/*------------------------------------------------------------------*-
SCH_Go_To_Sleep()
This scheduler enters 'sleep mode' between clock ticks
to save power. The next clock tick will return the processor
to the normal operating state.
Note: a slight performance improvement is possible if this
function is implemented as a macro, or if the code here is simply
pasted into the 'dispatch' function (but at the cost of code
readability).
*** Various power-saving options can be added
*** (e.g. shut down unused peripherals)
-*------------------------------------------------------------------*/
void SCH_Go_To_Sleep()
{
// Enter sleep mode = "Wait For Interrupt"
__WFI();
}
/*------------------------------------------------------------------*-
---- END OF FILE -------------------------------------------------
-*------------------------------------------------------------------*/
<file_sep>package jpa.e;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
@Entity(name="Ex4b_DepartmentEmployee")
public class Ex4_DepartmentEmployee implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@ManyToOne
@JoinColumn(name="dept_code")
private Ex4_Department department;
@Id
@ManyToOne
@JoinColumn(name="employee_id")
private Ex4_Employee employee;
@Column(name="role", nullable=false)
private String role;
}<file_sep>/*
* pca9532_leds.h
*
* Created on: 17 Feb 2018
* Author: nt161
*/
#ifndef PCA9532_LEDS_HEADER
#define PCA9532_LEDS_HEADER
#include "lpc17xx_pinsel.h"
#include "lpc17xx_i2c.h"
#include "pca9532.h"
#include "adc_task.h"
#include "joystick_controller.h"
void pca9532_leds_init(void);
void pca9532_leds_update(void);
#endif /* PCA9532_LEDS_HEADER */
<file_sep>import matplotlib.pyplot as plt
from scipy import signal
from scipy.signal import find_peaks
import numpy as np
import math
import sys
def text_file_to_array(filename):
arr = []
try:
inp = open(filename, "r")
#read line into array
for line in inp.readlines():
# loop over the elements, split by whitespace
for i in line.split():
# convert to integer and append to the list
arr.append(int(i))
return arr
except FileNotFoundError:
print("File does not exist")
sys.exit()
def butterworth_filter(sig):
b, a = signal.butter(6, 0.5, 'low')
output_signal = signal.filtfilt(b, a, sig)
return output_signal
# def write_to_file(sig, freq):
# my_list = []
# for i in range(len(sig)):
# i = i/freq
# #print(i)
# my_list.append(i)
# with open('your_file.txt', 'w') as f:
# for item in my_list:
# print >> your_file.txt, item
def threshold(sig):
#threshold_value = (max(sig)+min(sig)) / 2
diff = max(sig) - min(sig)
threshold_value = max(sig) - diff * 0.33
return threshold_value
def cross_peaks(sig, threshold):
r_peaks = []
for i in range(1, len(sig) - 2):
if sig[i] > sig[i - 1] and sig[i] > sig[i + 1] and sig[i] > threshold:
r_peaks.append(sig[i])
else:
r_peaks.append(None)
r_peaks.extend([None, None, None])
return r_peaks
def r_peaks(sig, threshold):
r_peaks = []
for i in range(1, len(sig) - 2):
if sig[i] > sig[i - 1] and sig[i] > sig[i + 1] and sig[i] > threshold:
r_peaks.append(sig[i])
return r_peaks
def normalise(sig):
norm_sig = []
diff = max(sig) - min(sig)
for i in sig:
i = (i - min(sig)) / diff
norm_sig.append(i)
return norm_sig
def norm_thresh(sig):
return max(sig) - 0.33
def bpm_from_peak_finder(freq, sig, threshold):
beat_count = 0
for i in range(0, len(sig) - 1):
if sig[i] > sig[i - 1] and sig[i] > sig[i + 1] and sig[i] > threshold:
beat_count = beat_count + 1
fs = freq
n = len(sig)
duration_in_seconds = n/fs
duration_in_minutes = duration_in_seconds/60
bpm = beat_count/duration_in_minutes
return round(bpm)
def sample_positions_to_time(freq, sig, threshold):
positions = []
for i in range(1, len(sig) - 2):
if sig[i] > sig[i - 1] and sig[i] > sig[i + 1] and sig[i] > threshold:
i = i/freq
positions.append(i)
return positions
def plot_peaks(sig, r_peaks):
plt.plot(sig, label='filtered signal')
plt.plot(r_peaks, "x", label='peaks')
# times = []
# for i in range(len(sig)):
# i = i/freq
# #print(i)
# times.append(i)
#plt.xticks(np.arange(min(times), max(times)))
return plt.show()
def average_differences(r_peak_times):
diffs = np.diff(r_peak_times)
avg_diffs = sum(diffs)/len(diffs)
return avg_diffs
def root_mean_square_differences(r_peak_times):
square = []
r_peak_diffs = np.diff(r_peak_times)
for i in range(len(r_peak_diffs) - 2):
r_peak_diffs[i] = r_peak_diffs[i] * r_peak_diffs[i]
square.append(r_peak_diffs[i])
sum_of_squares = sum(square)
mean = sum_of_squares/len(square)
rmssd = math.sqrt(mean)
return rmssd
def standard_dev_diffs(r_peak_times):
diffs = np.diff(r_peak_times)
mean_of_diffs = sum(diffs)/len(diffs)
diff_with_mean = []
square = []
for i in r_peak_times:
i = i - mean_of_diffs
diff_with_mean.append(i)
for j in diff_with_mean:
j = j * j
square.append(j)
sum_of_squares = sum(square)
mean = sum_of_squares/len(square)
sd = math.sqrt(mean)
return sd
def standard_dev(list):
mean_of_diffs = sum(list)/len(list)
diff_with_mean = []
square = []
for i in list:
i = i - mean_of_diffs
diff_with_mean.append(i)
for j in diff_with_mean:
j = j * j
square.append(j)
sum_of_squares = sum(square)
mean = sum_of_squares/len(square)
sd = math.sqrt(mean)
return sd
def arrhythmia_type(bpm):
if bpm < 50:
print("Bradycardia detected!")
elif bpm > 100:
print("Tachycardia detected!")
else:
return print("Heart rate normal")
def disp_normalised(file):
sig = text_file_to_array(file)
filtered = butterworth_filter(sig)
norm_sig = normalise(filtered)
thresh = norm_thresh(norm_sig)
peaks = cross_peaks(norm_sig, thresh)
return plot_peaks(norm_sig, peaks)
def disp(file):
sig = text_file_to_array(file)
filtered = butterworth_filter(sig)
#norm_sig = normalise(filtered)
thresh = threshold(filtered)
peaks = cross_peaks(filtered, thresh)
return plot_peaks(filtered, peaks)
def find_closest_points(height, norm_sig, n):
num_of_points = 25
points_1 = []
points_2 = []
keys = norm_sig.keys()
#for loop below will iterate back from the location of the peak at n by 25 samples.
for i in range(n, n-num_of_points):
p1 = norm_sig.get(keys[i])
p2 = norm_sig.get(keys[i-1])
if p1 > height and p2 < height:
points_1.append([i/100, p1]) #returns index and height value
points_1.append([(i+1)/100, p2])
#for loop below will iterate forward from the location of the peak at n by 25 samples.
for i in range(n, n+num_of_points):
p1 = norm_sig.get(keys[i])
p2 = norm_sig.get(keys[i+1])
if p1 > height and p2 < height:
points_1.append([i/100, p1])
points_1.append([(i+1)/100, p2])
return [points_1, points_2]
def interpolate(x1, y1, x2, y2):
m = (y2 - y1)/(x2 - x1)
c = y1 - m*x1
return lambda y: (y-c)/m
def peak_width(norm_sig, peaks):
peak_widths = []
n = 0
for peak_time in peaks:
for sig_time in norm_sig:
if peak_time == sig_time:
peak_half_height = 0.5*norm_sig.get(peak_time, 0)
closest_points = find_closest_points(peak_half_height, norm_sig, n)
f1 = interpolate(closest_points[0][1], closest_points[0][2], closest_points[0][3], closest_points[0][4])
f2 = interpolate(closest_points[1][1], closest_points[1][2], closest_points[1][3], closest_points[1][4])
f1_intersect = f1(peak_half_height)
f2_intersect = f2(peak_half_height)
peak_widths.append(abs(f1_intersect-f2_intersect))
n += 1
n = 0
return peak_widths
def heart_monitor(file, freq):
sig = text_file_to_array(file)
filtered = butterworth_filter(sig)
# write_to_file(filtered, freq)
min_thresh = threshold(filtered)
#print("half-height", width_at_half_height(peaks))
heart_rate = bpm_from_peak_finder(freq, filtered, min_thresh)
print("bpm", heart_rate)
if arrhythmia_type(heart_rate) < 50:
print("Bradycardia detected")
elif arrhythmia_type(heart_rate) > 100:
print("Tachycardia detected")
else:
print("Heart Rate normal")
disp(file)
r_peaks_time = sample_positions_to_time(freq, filtered, min_thresh)
print("sdsd = ", standard_dev_diffs(r_peaks_time))
if standard_dev_diffs(r_peaks_time) > 15:
print("Arrhythmia detected")
print("rmssd = ", root_mean_square_differences(r_peaks_time))
if root_mean_square_differences(r_peaks_time) < 0.6:
print("Arrhythmia detected")
normalised = normalise(filtered)
norm_dict = dict(zip(r_peaks_time, normalised))
peak_widths = peak_width(norm_dict, r_peaks_time)
print("standard deviation of width of r peaks = ", standard_dev(peak_widths))
return 0
#heart_monitor("test_new.txt", 100)
# heart_monitor("samples_hemal.txt", 128)
# print()
# print("sinus rhythm")
#
#heart_monitor("norm_17052.txt", 128)
#
#heart_monitor("normal_sinus16272_ecg1_128_bpm=60.txt", 128)
#
#heart_monitor("normal_sinus16273_ecg1_128_bpm=96.txt", 128)
# #
# print()
# print("arrhythmia")
# heart_monitor("arr_203.txt", 360) #
# heart_monitor("arr_207.txt", 360) #
# heart_monitor("arr_232.txt", 360) #bradycardia
#
# print()
# print("atrial")
# #heart_monitor("atrial_04015_ecg1.txt", 250)
# heart_monitor("atrial_04908.txt", 250) #tachycardia<file_sep>package jpa.e;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity(name="Ex4b_Department")
public class Ex4_Department {
@Id
@GeneratedValue(strategy=GenerationType.TABLE)
@Column(name="dept_code", nullable=false)
private String dept_code;
@Column(name="dept_name", nullable=false)
private String dept_name;
}<file_sep>#!/bin/bash
import serial
import time
ser = serial.Serial('COM3', 9600, timeout=0)
while 1:
try:
print(ser.readline())
time.sleep(1)
except ser.SerialTimeoutException:
print('Data could not be read')
time.sleep(1)
<file_sep><link rel='stylesheet' href='web/swiss.css'/>
# CO2006 MINI-PROJECT 16-17: eMarket (skeleton)
You can reuse this code for your mini project.
<file_sep>SHELL:=/bin/bash
# bash will read this config file first
BASH_ENV=bash_env.sh
export BASH_ENV
all:
$(MAKE) clean
mkdir -p bin # no error if already exists
javac -d bin $$javac_cp $$java_files
run:
java $$java_cp CC05
clean:
rm -rf bin/*
FORCE:
<file_sep>import matplotlib.pyplot as plt
from scipy import signal
from scipy.signal import find_peaks
import numpy as np
import math
import sys
def text_file_to_array(filename):
arr = []
try:
inp = open(filename, "r")
#read line into array
for line in inp.readlines():
# loop over the elements, split by whitespace
for i in line.split():
# convert to integer and append to the list
arr.append(int(i))
return arr
except FileNotFoundError:
print("File does not exist")
sys.exit()
def butterworth_filter(orig_sig):
b, a = signal.butter(6, 0.5, 'low')
output_signal = signal.filtfilt(b, a, orig_sig)
return output_signal
def plot_orig_filtered(orig_sig, filtered):
plt.plot(orig_sig, label='original')
plt.plot(filtered, label='filtered')
plt.legend()
return plt.show()
def peak_finder(sig, threshold):
#for physionet data do not use the filtered data
#peak_positions = []
r_peaks = []
#beat_count = 0
for i in range(1, len(sig) - 2):
if sig[i] > sig[i - 1] and sig[i] > sig[i + 1] and sig[i] > threshold:
#beat_count = beat_count + 1
#peak_positions.append(i)
r_peaks.append(sig[i])
# fs = freq
# n = len(sig)
# duration_in_seconds = n/fs
# duration_in_minutes = duration_in_seconds/60
# bpm = beat_count/duration_in_minutes
# print("r_peaks = ", r_peaks)
# print("peak_sample_positions = ", peak_positions)
# print("bpm_from_makeshift = ", round(bpm))
return r_peaks
def bpm_from_peak_finder(freq, sig, threshold):
beat_count = 0
for i in range(1, len(sig) - 2):
if sig[i] > sig[i - 1] and sig[i] > sig[i + 1] and sig[i] > threshold:
beat_count = beat_count + 1
fs = freq
n = len(sig)
duration_in_seconds = n/fs
duration_in_minutes = duration_in_seconds/60
bpm = beat_count/duration_in_minutes
return round(bpm)
def sample_positions_to_time(freq, sig, threshold):
positions = []
for i in range(1, len(sig) - 2):
if sig[i] > sig[i - 1] and sig[i] > sig[i + 1] and sig[i] > threshold:
i = i/freq
positions.append(i)
return positions
def r_peak_positions(freq, filtered, graph = None):
peaks, _ = find_peaks(filtered, distance=freq/2)
#for physionet we have to use the distance as the sampling frequency, however for our data dividing by 2 gives accurate results
position_of_peaks = []
# we also have to change peaks[1:] to just peaks for physionet
for i in peaks:
position_of_peaks.append(int(i))
if graph is True:
plt.plot(filtered)
plt.plot(peaks, filtered[peaks], "x")
return plt.show()
else:
return position_of_peaks
# def bpm_from_r_peak_positions(filtered, freq, r_peak_array):
# fs = freq
# n = len(filtered)
# duration_in_seconds = n/fs
# duration_in_minutes = duration_in_seconds/60
# bpm = len(r_peak_array)/duration_in_minutes
# return print("bpm from peak positions", round(bpm))
# def r_peak_values(filtered, freq):
# #again have to change distance to freq for physionet
# peaks, _ = find_peaks(filtered, distance=freq/2)
# r_peaks_array = []
# #same goes for physionet here we don't type peaks[1:]
# for i in filtered[peaks]:
# r_peaks_array.append(int(i))
# return r_peaks_array
def final_r_peaks(r_peaks_array):
final_peaks = []
avg = sum(r_peaks_array)/len(r_peaks_array)
error = 0.05 * avg
upper_end = avg + error
lower_end = avg - error
for i in range(len(r_peaks_array)):
if upper_end > r_peaks_array[i] > lower_end:
final_peaks.append(r_peaks_array[i])
return final_peaks
# def root_mean_square_differences(r_peaks_times):
# square = []
# r_peak_diffs = np.diff(r_peaks_times)
# #print(r_peak_diffs)
# for i in r_peak_diffs:
# # if i == (len(r_peak_diffs) - 2):
# # break
# i = i*i
# square.append(i)
# #print(square)
# sum_of_squares = sum(square)
# #print(sum_of_squares)
# mean = sum_of_squares/len(square)
# #print(mean)
# rmssd = math.sqrt(mean)
# return rmssd
def average_differences(r_peak_times):
diffs = np.diff(r_peak_times)
avg_diffs = sum(diffs)/len(diffs)
return avg_diffs
def root_mean_square_differences(r_peak_times):
square = []
r_peak_diffs = np.diff(r_peak_times)
for i in range(len(r_peak_diffs) - 2):
r_peak_diffs[i] = r_peak_diffs[i] * r_peak_diffs[i]
square.append(r_peak_diffs[i])
sum_of_squares = sum(square)
mean = sum_of_squares/len(square)
rmssd = math.sqrt(mean)
return rmssd
# https://stackoverflow.com/questions/24624039/how-to-get-hrv-heart-rate-variability-from-hr-heart-rate
# this is the same as sdnn
def standard_dev_diffs(r_peak_times):
diffs = np.diff(r_peak_times)
mean_of_diffs = sum(diffs)/len(diffs)
diff_with_mean = []
square = []
for i in r_peak_times:
i = i - mean_of_diffs
diff_with_mean.append(i)
for j in diff_with_mean:
j = j * j
square.append(j)
sum_of_squares = sum(square)
mean = sum_of_squares/len(square)
sd = math.sqrt(mean)
return sd
# dataset = text_file_to_array("test_new.txt")
#
# filtered_sig = butterworth_filter(dataset)
# #must filter before we use the function given below else peaks aren't detected using the peakutils function
#
# r_peaks_on_graph = r_peak_positions(100, filtered_sig, True)
#
#
# r_peak_positions_array = r_peak_positions(100, filtered_sig)
# print("new_r_peak_positions = ", r_peak_positions_array)
#
# r_peak_values_array = r_peak_values(filtered_sig, 100)
# print("orig_r_peaks = ", r_peak_values_array)
#
# r_peaks = final_r_peaks(r_peak_values_array)
# print("new_r_peaks = ", r_peaks)
#
#
# # differences = np.diff(r_peak_values_array)
# # print(differences)
#
# #print("bpm = ", (bpm_from_r_peak_positions(filtered_sig, 100, r_peak_positions_array)))
#peak_finder(100, filtered_sig, 530)
# print("average = ", average(r_peaks))
# print("standard deviation = ", standard_dev(r_peaks))
# print("rmssd = ", root_mean_square_differences(r_peaks))
atrial = text_file_to_array("atrial_04043_ecg1.txt")
time_atrial = sample_positions_to_time(250, atrial, 170)
print("bpm atrial = ", bpm_from_peak_finder(250, atrial, 170))
print("average differences atrial = ", average_differences(time_atrial))
print("sdsd atrial = ", standard_dev_diffs(time_atrial))
print("rmssd atrial = ", root_mean_square_differences(time_atrial))
atrial_2 = text_file_to_array("atrial_04015_ecg1.txt")
#filt_atrial_2 = butterworth_filter(atrial_2)
# plot_orig_filtered(atrial_2, butterworth_filter(atrial_2))
# plt.plot(atrial_2)
# plt.plot(atrial)
# plt.show()
time_atrial_2 = sample_positions_to_time(250, atrial_2, 100)
# peaks_atrial = r_peak_positions(250, filt_atrial_2, graph=True)
print("\nbpm atrial 2 = ", bpm_from_peak_finder(250, atrial_2, 100))
print("average differences atrial 2 = ", average_differences(time_atrial_2))
print("sdsd atrial 2 = ", standard_dev_diffs(time_atrial_2))
print("rmssd atrial 2 = ", root_mean_square_differences(time_atrial_2))
atrial_3 = text_file_to_array("atrial_05261_ecg1.txt")
# plt.plot(atrial_3)
# plt.show()
time_atrial_3 = sample_positions_to_time(250, atrial_3, 200)
print("\nbpm atrial 3 = ", bpm_from_peak_finder(250, atrial_3, 200))
print("average differences atrial 3 = ", average_differences(time_atrial_3))
print("sdsd atrial 3 = ", standard_dev_diffs(time_atrial_3))
print("rmssd atrial 3 = ", root_mean_square_differences(time_atrial_3))
mydata = text_file_to_array("test_new.txt")
filteredsig = butterworth_filter(mydata)
plt.plot(filteredsig)
plt.show()
time_mine = sample_positions_to_time(100, filteredsig, 530)
print("\nbpm mine = ", bpm_from_peak_finder(100, filteredsig, 530))
print("average differences mine = ", average_differences(time_mine))
print("sdsd mine = ", standard_dev_diffs(time_mine))
print("rmssd mine = ", root_mean_square_differences(time_mine))
sinus = text_file_to_array("normal_sinus16272_ecg1_128.txt")
#filteredsinus = butterworth_filter(sinus)
#plot_orig_filtered(sinus, filteredsinus)
time_sinus = sample_positions_to_time(128, sinus, 100)
print("\nbpm normal = ", bpm_from_peak_finder(128, sinus, 100))
print("average differences normal = ", average_differences(time_sinus))
print("sdsd normal = ", standard_dev_diffs(time_sinus))
print("rmssd normal = ", root_mean_square_differences(time_sinus))
sinus_2 = text_file_to_array("normal_sinus16272_ecg1_128.txt")
#filteredsinus = butterworth_filter(sinus)
#plot_orig_filtered(sinus, filteredsinus)
time_sinus_2 = sample_positions_to_time(128, sinus_2, 100)
print("\nbpm normal 2 = ", bpm_from_peak_finder(128, sinus_2, 100))
print("average differences normal 2 = ", average_differences(time_sinus_2))
print("sdsd normal 2 = ", standard_dev_diffs(time_sinus_2))
print("rmssd normal 2 = ", root_mean_square_differences(time_sinus_2))
#print("bpm = ", (bpm_from_peaks(128, filtered_sig, )))
#for physionet data use the initial bpm function not the new one, else the value is wrong
#and don't use the filtered signal for this
hemal_sig = text_file_to_array("ecg_hemal_1000.txt")
filtered_hemal = butterworth_filter(hemal_sig)
#plt.plot(hemal_sig)
#plt.show()
time_hemal = sample_positions_to_time(1000, filtered_hemal, 2660)
print("\nbpm Hemal_1 = ", bpm_from_peak_finder(1000, hemal_sig, 2660))
print("average differences Hemal_1 = ", average_differences(time_hemal))
print("sdsd Hemal_1 = ", standard_dev_diffs(time_hemal))
print("rmssd Hemal_1 = ", root_mean_square_differences(time_hemal))
hemal_sig_2 = text_file_to_array("ecg_hemal_v2_1000.txt")
filtered_hemal_2 = butterworth_filter(hemal_sig_2)
# plt.plot(filtered_hemal)
# plt.show()
time_hemal_2 = sample_positions_to_time(1000, filtered_hemal, 2620)
print("\nbpm Hemal_2 = ", bpm_from_peak_finder(1000, hemal_sig, 2620))
print("average differences Hemal_2 = ", average_differences(time_hemal_2))
print("sdsd Hemal_2 = ", standard_dev_diffs(time_hemal_2))
print("rmssd Hemal_2 = ", root_mean_square_differences(time_hemal_2))
arrhythmia_1 = text_file_to_array("arrhythmia_100_MLII_360.txt")
# plt.plot(arrhythmia_1)
# plt.show()
time_arr_1 = sample_positions_to_time(360, arrhythmia_1, 1050)
print("\nbpm arrhythmia_1 = ", bpm_from_peak_finder(360, arrhythmia_1, 1050))
print("average differences arrhythmia_1 = ", average_differences(time_arr_1))
print("sdsd arrhythmia_1 = ", standard_dev_diffs(time_arr_1))
print("rmssd arrhythmia_1 = ", root_mean_square_differences(time_arr_1))
arrhythmia_2 = text_file_to_array("arrhythmia_101_MLII_360.txt")
# plt.plot(arrhythmia_2)
# plt.show()
time_arr_2 = sample_positions_to_time(360, arrhythmia_2, 1150)
print("\nbpm arrhythmia_2 = ", bpm_from_peak_finder(360, arrhythmia_2, 1150))
print("average differences arrhythmia_2 = ", average_differences(time_arr_2))
print("sdsd arrhythmia_2 = ", standard_dev_diffs(time_arr_2))
print("rmssd arrhythmia_2 = ", root_mean_square_differences(time_arr_2))
arrhythmia_3 = text_file_to_array("arrhythmia_116_MLII_360.txt")
# plt.plot(arrhythmia_3)
# plt.show()
time_arr_3 = sample_positions_to_time(360, arrhythmia_3, 1100)
print("\nbpm arrhythmia_3 = ", bpm_from_peak_finder(360, arrhythmia_3, 1100))
print("average differences arrhythmia_3 = ", average_differences(time_arr_3))
print("sdsd arrhythmia_3 = ", standard_dev_diffs(time_arr_3))
print("rmssd arrhythmia_3 = ", root_mean_square_differences(time_arr_3))<file_sep>/*
* serial_output.h
*
* Created on: 19 March 2018
* Author: nt161
*/
#ifndef TASKS_SERIAL_OUTPUT_HEADER_
#define TASKS_SERIAL_OUTPUT_HEADER_
#include "lpc_types.h"
#include "../lpcusb/include/usbapi.h"
#include "../lpcusb/include/USBVcom.h"
#include "../adc/adc.h"
// ------ Public function prototypes -------------------------------
void serial_output_init(void);
void serial_output_update(void);
#endif /* TASKS_SERIAL_OUTPUT_HEADER_ */
<file_sep>/*
Author: nt161
Date: October 2018
A linear search algorithm
*/
#include <stdio.h>
#include <stdlib.h>
#include <omp.h>
int main()
{
int i;
int n = 99000000;
int key = n-1;
int *a = malloc(sizeof(int)*n);
double start;
//creates an array of length 99000000 with values up to 98999999
for (i = 0; i < n; i++)
{
a[i] = i;
}
//starts timing the run time of the program
start = omp_get_wtime();
//loop iterates through the array until it finds the key
for(i=0; i<n; i++)
{
//if the element in the array is the same as the key the time taken for execution
if(a[i] == key)
{
printf("Key found. Array position = %d. Time taken = %lf \n", i+1, omp_get_wtime() - start);
}
}
return 0;
}
<file_sep>Two Issues:
- The '.exe' file is there so that CM will be able to submit your work
once you have compiled it. (Remember, you may need to navigate away
from the exercise and back again, for the 'Submit' button to become
active.)
- Have a look a the Makefile - what do you think the '.PHONY' target
is about?
<file_sep><link rel='stylesheet' href='web/swiss.css'/>
# Spring MVC: exercise 05 - form validation and redirections
Import the project `sprint2/SpringMvc_ex05` from your local GitHub repository into your STS workspace using `Import>Existing Gradle Project`.
In this exercise, we are going to develop a web application with a form that submits information about students. We are going to focus on:
* adding form validation using Spring annotations; and
* using redirections in order to allow our controller to trigger http requests (to **delegate** work to other controllers)
## Skeleton of the web application
By the end of these exercises, the presentation layer should implement the following navigational model as a state machine, where screenshots represent `views` (states) and links represent transitions (http requests available from a particular view):
<img src="web/sm.pdf" alt="navigational model" width="750" height="400">
The architecture of the codebase available in the repository is as follows:
/src
|-- main
|-- java
|-- labMvc
|-- LabMvcApplication.java:
|-- WebConfig.java
|-- control
|-- IndexController.java
|-- domain
|-- Student.java
|-- resources
|-- application.properties
|-- webapp
|-- WEB-INF
|-- views: where the JSP files can be found
|-- index.jsp
|-- forms
|-- error.jsp
|-- final.jsp
|-- form.jsp
|-- result.jsp
The differences with the codebase of `exercise 04` are as follows:
* class [src/main/java/labMvc/control/StudentValidator.java](./src/main/java/labMvc/control/StudentValidator.java) implements the conditions that need to be checked on objects `Student` in the method `validate(Object target, Errors errors)`. Objects `Student` are used as **command objects** (a JavaBean which will be populated with the data from your forms, aka **data transfer object**) when the form in the JSP view [src/main/webapp/WEB-INF/views/form/form.jsp](./src/main/webapp/WEB-INF/views/form/form.jsp) is sent in a POST request;
* class [src/main/java/labMvc/control/IndexController.java](./src/main/java/labMvc/control/IndexController.java) links the validator for the command object `Student` by using the binding below and by annotating a model attribute with the annotation `@Valid` in a request handler method:
@InitBinder
protected void initBinder(WebDataBinder binder) {
binder.addValidators(new StudentValidator());
}
## :star: a. Validation
In this exercise, we are going to implement a basic form validation mechanism that will allow us to check the information that users provide through web forms using Spring annotations.
* In the method `addStudent()` of the controller class [src/main/java/labMvc/control/IndexController.java](./src/main/java/labMvc/control/IndexController.java), add a Spring annotation to enable validation of the information received from the web form in the view [src/main/webapp/WEB-INF/views/form/form.jsp](./src/main/webapp/WEB-INF/views/form/form.jsp).
* In the method `validate()` of the validator class [src/main/java/labMvc/control/StudentValidator.java](./src/main/java/labMvc/control/StudentValidator.java), add code to check the following conditions:
* `name too short`: the student name has less than 5 characters
* `low age`: the student age is less than 18
## :star::star: b. Redirection
In this exercise, you are going to implement how to perform an automatic URL redirection to `/finalPage` when the request `/redirect` reaches the controller. Add this code in the method `redirect()` of the class [src/main/java/labMvc/control/IndexController.java](./src/main/java/labMvc/control/IndexController.java).
<!--
// REDIRECTION
@RequestMapping(value = "/redirect", method = RequestMethod.GET)
public String redirect() {
return "redirect:/finalPage";
}
@RequestMapping(value = "/finalPage", method = RequestMethod.GET)
public String finalPage() {
return "/form/final";
}
The only part that is unusual in the code above is the use of the statement `redirect:`, which triggers an HTTP request `/finalPage`.
-->
Hint: revise :movie_camera: [the section chaining](https://app.pluralsight.com/player?course=springmvc-intro&author=bryan-hansen&name=springmvc-m5-views&clip=5&mode=live) of the tutorial [Introduction to Spring MVC](https://app.pluralsight.com/library/courses/springmvc-intro/table-of-contents) on Pluralsight.
## Additional Resources
The code used in this tutorial has been adapted from the following sources:
* [Handling forms](http://www.tutorialspoint.com/spring/spring_mvc_form_handling_example.htm)
* [Handling exceptions](http://www.tutorialspoint.com/spring/spring_exception_handling_example.htm)
* [Page redirection](http://www.tutorialspoint.com/spring/spring_page_redirection_example.htm)
***
© <NAME>, 2015-17<file_sep>/*------------------------------------------------------------------*-
ttc_scheduler_o.h (2013-07-07)
------------------------------------------------------------------
See ttc_scheduler_o.c for details.
-*------------------------------------------------------------------*/
/*------------------------------------------------------------------*-
This code is intended SOLELY for use in training courses (during
which participants examine and complete the code presented here).
The projects is not complete and the code is not suitable for use
in production or prototype systems.
Subject to the above conditions, redistribution and use of this
software - in source or binary form, with or without modification
- is permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.
3. The name of the author may not be used to endorse or promote
products derived from this software without specific prior
written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR �AS IS� AND ANY EXPRESS
OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-*------------------------------------------------------------------*/
#ifndef _TTC_SCHEDULER_H
#define _TTC_SCHEDULER_H 1
#include "../main/main.h"
// ------ Public data type declarations ----------------------------
// User-define type to store required data for each task
typedef struct
{
// Pointer to the task (must be a 'void (void)' function)
void (*pTask) (void);
// Delay (ticks) until the task will (next) be run
// - see SCH_Add_Task() for further details
uint32_t Delay;
// Interval (ticks) between subsequent runs.
// - see SCH_Add_Task() for further details
uint32_t Period;
// Incremented (by scheduler) when task is due to execute
uint32_t RunMe;
} sTask;
// ------ Public function prototypes -------------------------------
void SCH_Init(void);
void SCH_Start(void);
void SCH_Dispatch_Tasks(void);
uint32_t SCH_Add_Task(void (*) (void), const uint32_t, const uint32_t);
uint32_t SCH_Delete_Task(const uint32_t);
// ------ Public constants -----------------------------------------
// The maximum number of tasks required at any one time
// during the execution of the program
//
// MUST BE ADJUSTED FOR EACH NEW PROJECT
#define SCH_MAX_TASKS (10)
//------------------------------------------------------------------
// Error codes for scheduler
//------------------------------------------------------------------
#define ERROR_SCH_TOO_MANY_TASKS (1)
#define ERROR_SCH_CANNOT_DELETE_TASK (2)
#define ERROR_SCH_INCORRECT_CORE_FREQUENCY (3)
#define ERROR_SCH_SYSTEM_OVERLOAD (4)
#endif
/*------------------------------------------------------------------*-
---- END OF FILE -------------------------------------------------
-*------------------------------------------------------------------*/
<file_sep>// fillArray.cpp
// see website for instructions
//
// Author:
// Version:
#include <iostream> // use the standard IO library
#include <string> // use the standard string library
using namespace std;
int main () {
}
<file_sep>package CO2017.exercise2.nt161;
/**
* QueueHandler
*
* Handles a file of incoming Transaction data.
*
* @author 169018358
* @version $ID: QueueHandler.java version 8 $
* @last_modified 15/03/18
*/
import java.io.IOException;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashSet;
import java.util.Scanner;
import java.util.concurrent.*;
import java.lang.String;
/**
* Class to read in a file of Transaction data, create suitable Transaction instances,
* and add them to the TransactionManager.
*/
public class QueueHandler extends java.lang.Object implements java.lang.Runnable {
private final TransactionManager transactionmanager; // transaction manager instance that the processes will share
private final ThreadPoolExecutor thread_executer; // used by SimController class to manage the process threads
private final String filename; // filename from which the process data can be read
// constructor just sets the three attributes
public QueueHandler(ThreadPoolExecutor e,
TransactionManager tm,
java.lang.String f){
thread_executer = e;
transactionmanager = tm;
filename = f;
}
// behaviour of the QueueHandler when executed
@Override
public void run(){
// extract the filename from the command line
// and convert it to a filepath object
String fname = filename;
Path fpath = Paths.get(fname);
// open the file using a Scanner and read it line by line
try (Scanner file = new Scanner(fpath)) {
while (file.hasNextLine()) {
// read the next line of the file into another Scanner
Scanner line = new Scanner(file.nextLine());
// split the line on ":"
line.useDelimiter(":");
// read ID (char) and runtime (int)
char transactionid = line.next().charAt(0);
int runtime = line.nextInt();
// remaining elements on the line are resources
// put them all into a HashSet
HashSet<Resource> resources = new HashSet<Resource> ();
while(line.hasNext()) {
resources.add(new Resource(line.next().charAt(0)));
}
// creating a transaction object and adding it to the arrival queue
// of the TransactionManager using the enQueue method
// after waiting until the arrival queue is not full anymore
Transaction transaction = new Transaction (transactionmanager, transactionid, runtime, resources);
while(transactionmanager.isArrivalQueueFull()){}
transactionmanager.enQueue(transaction);
line.close();
// printing out the ID, runtime and resources associated with a transaction
System.out.printf("ID: %c, runtime: %s, resources: %s%n",
transactionid, runtime, resources);
}
// close the file
file.close();
}
// catch exception if file is not found
catch (NoSuchFileException e) {
System.err.println("File not found: "+fname);
System.exit(1);
}
// catch input/output exception
catch (IOException e) {
System.err.println(e);
System.exit(1);
}
// catch interrupted exception
catch (InterruptedException e) {
e.printStackTrace();
}
}
} // QueueHandler
<file_sep>package uk.ac.le.cs.CO3090.cw1;
import java.util.*;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.Semaphore;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
/**
* @author nt161
*
*/
public class WebCrawler implements Runnable, CounterInterface {
public final static int MAX_PAGES_NUM=50;
public final static int TIME_OUT=10000;
public final static int MAX_QUEUE_SIZE=20000;
public final static int MAX_THREAD_NUM=10;
public final static int MAX_CHAR_COUNT=1000000;
public final static String ALPHABET="abcdefghijklmnopqrstuvwxyz";
static BlockingQueue<String> urlQueue = new ArrayBlockingQueue<String>(MAX_QUEUE_SIZE); //blocking queue
static ArrayList<String> visited = new ArrayList<String>();
static List<String> syncVisited=Collections.synchronizedList(visited); //making the list for visited web pages synchronised to ensure it is thread safe
//ensures that only one thread can access that list
static ConcurrentHashMap<Character, Integer> results = new ConcurrentHashMap<>();
private HashMap<Character, Integer> letterfreq = new HashMap<>(); //map that contains the results of the frequencies for each URL that is visited object
static ThreadPoolExecutor executorPool = (ThreadPoolExecutor) Executors.newFixedThreadPool(MAX_THREAD_NUM); //creating a threadpool to
static Boolean timedOut = false; //this is used
private static final Semaphore semaphore = new Semaphore(MAX_THREAD_NUM); //used to ensure mutual exclusion
private static WebCrawler webCrawler;
int current_character_count=0; //stores the current character count
static AtomicInteger total_character_count = new AtomicInteger(0); //stores the total character count
@Override
public void run() {
String website;
try {
website = urlQueue.poll(TIME_OUT,TimeUnit.MILLISECONDS); //using a blocking queue so it is a thread safe type
//we assign URL of a website to the string object
if(website != null) {
//we only run the count method if polling the queue hasn't returned null
count(website);
}
else {
timedOut = true; //else if it is null then timedOut is set to true
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public synchronized void count(String URL) throws InterruptedException{
if(!syncVisited.contains(URL) && syncVisited.size() < MAX_PAGES_NUM) { //checks if the visited list doesn't contains the URL and the size of the list is less than the maximum number of pages
syncVisited.add(URL); //if so it will add the URL to the list
String page_content=Utility.getTextFromAddress(URL);
letterfreq = Utility.calculate(Utility.getPlainText(page_content)); //calculating the letter frequency and storing the result to the map
for (int i=0; i<ALPHABET.length(); i++) {
char c = ALPHABET.charAt(i);
//System.out.println(c);
results.put(c, results.get(c) + letterfreq.get(c)); //adding the current page statistics to the map which contains the statistics from all the pages visited
}
for (int i : letterfreq.values()) { //
if(total_character_count.get() + i < MAX_CHAR_COUNT)
current_character_count += i;
}
total_character_count.getAndAdd(current_character_count); //
ArrayList<String> list = Utility.extractHyperlinks(URL, page_content); //extracts the hyperlinks from the website
for(String link: list){
urlQueue.offer(link, TIME_OUT, TimeUnit.MILLISECONDS); //adds the links to the queue and so will stop adding links if the queue is full
}
}
}
@Override
public void printStatistics() {
System.out.println("Total number of characters:" + total_character_count.get()); //prints out the total number of characters
System.out.println("Pages visited:"+ syncVisited.size()); //prints out the number of pages visited
for (Map.Entry<Character, Integer> entry : results.entrySet()) { //iterates through the map and prints out the percentage of each letter found overall
String key = entry.getKey().toString();
Integer value = entry.getValue();
float percentage = ((float)value/(float)total_character_count.get())*100;
System.out.println(key + " = " + percentage + "%");
}
}
public static void main(String[] args){
// TODO complete this method
for (int i=0; i<ALPHABET.length(); i++) { //Initialises the map with each letter being assigned a value of zero
char c = ALPHABET.charAt(i);
results.put(c, 0);
}
String baseURL = "https://www.bbc.co.uk"; //base URL where the crawling starts
urlQueue.add(baseURL); //adding the URL to the queue
while(syncVisited.size()<MAX_PAGES_NUM && total_character_count.get()<MAX_CHAR_COUNT && !timedOut) { //this will continue executing as long as the list size
webCrawler = new WebCrawler(); //creating an instance of the WebCrawler
Thread thread = new Thread(webCrawler); //creates a new thread which is passed the WebCrawler instance
try {
semaphore.acquire(); //acquiring the semaphore
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Runnable thread_runner = () -> { //this creates a new runnable object and when the thread is run, it will release the semaphore
try {
thread.run();
} finally {
semaphore.release(); //releasing the semaphore
}
};
executorPool.execute(thread_runner); //The threadpool is executed and this will be used to manage the threads
}
executorPool.shutdown(); //When the maximum pages has been reached, then the threadpool will be shutdown, so no new threads can run.
try {
executorPool.awaitTermination(60000, TimeUnit.MILLISECONDS); //this will wait for a minute until all the threads that were pending to be executed
} catch (InterruptedException e) { //to execute if it is still
// TODO Auto-generated catch block
e.printStackTrace();
}
webCrawler.printStatistics(); //prints out the total frequencies as a percentage
}
} <file_sep>package eMarket.repository;
import org.springframework.data.repository.CrudRepository;
import eMarket.domain.Role;
public interface RoleRepository extends CrudRepository<Role, Integer> {
public Role findById(int id);
public Role findByRole(String role);
}
<file_sep>import java.util.*;
public class CC08_soln {
int size(MyNode n) {
if(isLeaf(n)) return 1;
return 1+size(n.left)+size(n.right);
}
int height(MyNode n) {
if(isLeaf(n)) return 1;
return 1+Math.max(height(n.left),height(n.right));
}
List nodes_less_than(MyNode t, int k) {
List this_node;
if(((Integer)t.obj) < k)
this_node=cons(t.obj,nil());
else
this_node=nil();
if(isLeaf(t)) return this_node;
List left_nodes = nodes_less_than(t.left,k);
List right_nodes = nodes_less_than(t.right,k);
return append(left_nodes,append(this_node,right_nodes));
}
List nodes_greater_than(MyNode t, int k) {
List this_node;
if(((Integer)t.obj) > k)
this_node=cons(t.obj,nil());
else
this_node=nil();
if(isLeaf(t)) return this_node;
List left_nodes = nodes_greater_than(t.left,k);
List right_nodes = nodes_greater_than(t.right,k);
return append(left_nodes,append(this_node,right_nodes));
}
// we assume each integer in the tree is unique (i.e. there are no
// nodes decorated with the same integer)
boolean is_binary_search_tree(MyNode n) {
// this is very inefficient! search the web for a more efficient
// version using extra parameters min and max
if(isLeaf(n)) return true;
int k = (Integer)(n.obj);
List l = nodes_less_than(n.right,k);
if(!l.isEmpty()) return false;
l = nodes_greater_than(n.left,k);
if(!l.isEmpty()) return false;
return(is_binary_search_tree(n.left) && is_binary_search_tree(n.right));
}
// testing code
void main() {
MyNode t12 = node(leaf(1),"+",leaf(2));
System.out.println("size passes test: "+(size(t12)==3));
System.out.println("height passes test: "+(height(t12)==2));
// the following is similar to the example from wikipedia
MyNode binary_search_tree =
node(
node(
leaf(1),
3,
node(
leaf(4),
6,
leaf(7))),
8,
leaf(10));
System.out.println(
"is_binary_search_tree passes test: "
+is_binary_search_tree(binary_search_tree));
}
public static void main(String[] args) {
new CC08_soln().main();
}
//////////////////////////////////////////////////////////////////////
// basic tree functions
MyNode node(MyNode l, Object o, MyNode r) {
return new MyNode(l,o,r);
}
MyNode leaf(Object o) {
return new MyNode(null,o,null);
}
boolean isLeaf(MyNode n) {
return (n.left == null) && (n.right == null);
}
boolean isNode(MyNode n) {
return !(isLeaf(n));
}
// most of the following methods could/should be static
// clone is protected, so we could subclass but... YOU ARE NOT
// ALLOWED TO USE THIS FUNCTION!!! IT IS ONLY FOR IMPLEMENTING cons
// ETC.
List copy(List l0) {
List to_return = new LinkedList();
for(int i=0; i<l0.size(); i++) {
to_return.add(i,l0.get(i));
}
return to_return;
}
// the empty list
List nil() {
return new LinkedList();
}
// add at front of list
List cons(Object o, List l0) {
List l = copy(l0);
l.add(0,o);
return l;
}
// head of the list
Object hd(List l) { return l.get(0); }
// tail of the list
List tl(List l0) {
List l = copy(l0);
l.remove(0);
return l;
}
// add at end of list
List append1(List l0, Object o) {
List l = copy(l0);
l.add(l.size(),o);
return l;
}
// join two lists together
List append(List l01, List l02) {
List to_return = copy(l01);
List l2 = copy(l02);
while(true) {
if(l2.isEmpty()) return to_return;
to_return=append1(to_return,hd(l2));
l2=tl(l2);
}
}
// for debugging
String asString(List l) {
String to_return ="[";
while(true) {
if(l.isEmpty()) return (to_return+"]");
if(tl(l).isEmpty()) return (to_return+hd(l)+"]");
to_return+=hd(l)+",";
l=tl(l);
}
}
String list_to_string(List l) {
String to_return ="[";
while(true) {
if(l.isEmpty()) return (to_return+"]");
if(tl(l).isEmpty()) return (to_return+hd(l)+"]");
to_return+=hd(l)+",";
l=tl(l);
}
}
}
<file_sep>[mysql]
host = localhost
database = project_data
user = root
password = <PASSWORD><file_sep>/*
* adc.h
*
* Created on: 17 March 2018
* Author: nt161
*/
#ifndef ADC_HEADER_
#define ADC_HEADER_
#include "lpc17xx_adc.h"
#include "lpc17xx_pinsel.h"
#include <LPC17xx.h>
// ------ Public function prototypes -------------------------------
// constant for the size of the buffer
#define BUFFER_SIZE 10
// A struct to hold the buffer - the data and the "head" (next location to be written).
// sets the size of the buffer as well
typedef struct {
uint32_t data[BUFFER_SIZE];
uint32_t head;
} RingBuffer;
extern RingBuffer buffer_adc_0, buffer_adc_1, buffer_adc_2;
extern float adc_0_value, adc_1_value, adc_2_value;
extern float average_adc_0, average_adc_1, average_adc_2;
extern float adc0_change_rate, adc1_change_rate, adc2_change_rate;
void initialise_buffer(RingBuffer* buf);
void add_to_buffer(RingBuffer* buf, float x);
uint32_t get_most_recent(RingBuffer* buf);
float get_average(RingBuffer buf);
void adc_initialise(void);
uint32_t adc_read_general(uint8_t channel);
void adc_0_update(void);
void adc_1_update(void);
void adc_2_update(void);
#endif /* ADC_HEADER_ */
<file_sep>/*
* system.h - SOPC Builder system and BSP software package information
*
* Machine generated for CPU 'ET_Core' in SOPC Builder design 'slave'
* SOPC Builder design path: C:/Users/a/Documents/EG3205_Work/Assignment_2_solution/slave/slave.sopcinfo
*
* Generated: Wed Dec 12 22:53:01 GMT 2018
*/
/*
* DO NOT MODIFY THIS FILE
*
* Changing this file will have subtle consequences
* which will almost certainly lead to a nonfunctioning
* system. If you do modify this file, be aware that your
* changes will be overwritten and lost when this file
* is generated again.
*
* DO NOT MODIFY THIS FILE
*/
/*
* License Agreement
*
* Copyright (c) 2008
* Altera Corporation, San Jose, California, USA.
* All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
* This agreement shall be governed in all respects by the laws of the State
* of California and by the laws of the United States of America.
*/
#ifndef __SYSTEM_H_
#define __SYSTEM_H_
/* Include definitions from linker script generator */
#include "linker.h"
/*
* CPU configuration
*
*/
#define ALT_CPU_ARCHITECTURE "altera_nios2_qsys"
#define ALT_CPU_BIG_ENDIAN 0
#define ALT_CPU_BREAK_ADDR 0x00008820
#define ALT_CPU_CPU_FREQ 50000000u
#define ALT_CPU_CPU_ID_SIZE 1
#define ALT_CPU_CPU_ID_VALUE 0x00000000
#define ALT_CPU_CPU_IMPLEMENTATION "tiny"
#define ALT_CPU_DATA_ADDR_WIDTH 0x10
#define ALT_CPU_DCACHE_LINE_SIZE 0
#define ALT_CPU_DCACHE_LINE_SIZE_LOG2 0
#define ALT_CPU_DCACHE_SIZE 0
#define ALT_CPU_EXCEPTION_ADDR 0x00000020
#define ALT_CPU_FLUSHDA_SUPPORTED
#define ALT_CPU_FREQ 50000000
#define ALT_CPU_HARDWARE_DIVIDE_PRESENT 0
#define ALT_CPU_HARDWARE_MULTIPLY_PRESENT 0
#define ALT_CPU_HARDWARE_MULX_PRESENT 0
#define ALT_CPU_HAS_DEBUG_CORE 1
#define ALT_CPU_HAS_DEBUG_STUB
#define ALT_CPU_HAS_JMPI_INSTRUCTION
#define ALT_CPU_ICACHE_LINE_SIZE 0
#define ALT_CPU_ICACHE_LINE_SIZE_LOG2 0
#define ALT_CPU_ICACHE_SIZE 0
#define ALT_CPU_INST_ADDR_WIDTH 0x10
#define ALT_CPU_NAME "ET_Core"
#define ALT_CPU_RESET_ADDR 0x00000000
/*
* CPU configuration (with legacy prefix - don't use these anymore)
*
*/
#define NIOS2_BIG_ENDIAN 0
#define NIOS2_BREAK_ADDR 0x00008820
#define NIOS2_CPU_FREQ 50000000u
#define NIOS2_CPU_ID_SIZE 1
#define NIOS2_CPU_ID_VALUE 0x00000000
#define NIOS2_CPU_IMPLEMENTATION "tiny"
#define NIOS2_DATA_ADDR_WIDTH 0x10
#define NIOS2_DCACHE_LINE_SIZE 0
#define NIOS2_DCACHE_LINE_SIZE_LOG2 0
#define NIOS2_DCACHE_SIZE 0
#define NIOS2_EXCEPTION_ADDR 0x00000020
#define NIOS2_FLUSHDA_SUPPORTED
#define NIOS2_HARDWARE_DIVIDE_PRESENT 0
#define NIOS2_HARDWARE_MULTIPLY_PRESENT 0
#define NIOS2_HARDWARE_MULX_PRESENT 0
#define NIOS2_HAS_DEBUG_CORE 1
#define NIOS2_HAS_DEBUG_STUB
#define NIOS2_HAS_JMPI_INSTRUCTION
#define NIOS2_ICACHE_LINE_SIZE 0
#define NIOS2_ICACHE_LINE_SIZE_LOG2 0
#define NIOS2_ICACHE_SIZE 0
#define NIOS2_INST_ADDR_WIDTH 0x10
#define NIOS2_RESET_ADDR 0x00000000
/*
* Define for each module class mastered by the CPU
*
*/
#define __ALTERA_AVALON_JTAG_UART
#define __ALTERA_AVALON_MUTEX
#define __ALTERA_AVALON_ONCHIP_MEMORY2
#define __ALTERA_AVALON_PIO
#define __ALTERA_AVALON_SPI
#define __ALTERA_NIOS2_QSYS
/*
* ET_Core_Memory configuration
*
*/
#define ALT_MODULE_CLASS_ET_Core_Memory altera_avalon_onchip_memory2
#define ET_CORE_MEMORY_ALLOW_IN_SYSTEM_MEMORY_CONTENT_EDITOR 0
#define ET_CORE_MEMORY_ALLOW_MRAM_SIM_CONTENTS_ONLY_FILE 0
#define ET_CORE_MEMORY_BASE 0x0
#define ET_CORE_MEMORY_CONTENTS_INFO ""
#define ET_CORE_MEMORY_DUAL_PORT 0
#define ET_CORE_MEMORY_GUI_RAM_BLOCK_TYPE "AUTO"
#define ET_CORE_MEMORY_INIT_CONTENTS_FILE "slave_ET_Core_Memory"
#define ET_CORE_MEMORY_INIT_MEM_CONTENT 1
#define ET_CORE_MEMORY_INSTANCE_ID "NONE"
#define ET_CORE_MEMORY_IRQ -1
#define ET_CORE_MEMORY_IRQ_INTERRUPT_CONTROLLER_ID -1
#define ET_CORE_MEMORY_NAME "/dev/ET_Core_Memory"
#define ET_CORE_MEMORY_NON_DEFAULT_INIT_FILE_ENABLED 0
#define ET_CORE_MEMORY_RAM_BLOCK_TYPE "AUTO"
#define ET_CORE_MEMORY_READ_DURING_WRITE_MODE "DONT_CARE"
#define ET_CORE_MEMORY_SINGLE_CLOCK_OP 0
#define ET_CORE_MEMORY_SIZE_MULTIPLE 1
#define ET_CORE_MEMORY_SIZE_VALUE 16348
#define ET_CORE_MEMORY_SPAN 16348
#define ET_CORE_MEMORY_TYPE "altera_avalon_onchip_memory2"
#define ET_CORE_MEMORY_WRITABLE 1
/*
* System configuration
*
*/
#define ALT_DEVICE_FAMILY "Cyclone III"
#define ALT_ENHANCED_INTERRUPT_API_PRESENT
#define ALT_IRQ_BASE NULL
#define ALT_LOG_PORT "/dev/null"
#define ALT_LOG_PORT_BASE 0x0
#define ALT_LOG_PORT_DEV null
#define ALT_LOG_PORT_TYPE ""
#define ALT_NUM_EXTERNAL_INTERRUPT_CONTROLLERS 0
#define ALT_NUM_INTERNAL_INTERRUPT_CONTROLLERS 1
#define ALT_NUM_INTERRUPT_CONTROLLERS 1
#define ALT_STDERR "/dev/jtag_uart_0"
#define ALT_STDERR_BASE 0x9488
#define ALT_STDERR_DEV jtag_uart_0
#define ALT_STDERR_IS_JTAG_UART
#define ALT_STDERR_PRESENT
#define ALT_STDERR_TYPE "altera_avalon_jtag_uart"
#define ALT_STDIN "/dev/jtag_uart_0"
#define ALT_STDIN_BASE 0x9488
#define ALT_STDIN_DEV jtag_uart_0
#define ALT_STDIN_IS_JTAG_UART
#define ALT_STDIN_PRESENT
#define ALT_STDIN_TYPE "altera_avalon_jtag_uart"
#define ALT_STDOUT "/dev/jtag_uart_0"
#define ALT_STDOUT_BASE 0x9488
#define ALT_STDOUT_DEV jtag_uart_0
#define ALT_STDOUT_IS_JTAG_UART
#define ALT_STDOUT_PRESENT
#define ALT_STDOUT_TYPE "altera_avalon_jtag_uart"
#define ALT_SYSTEM_NAME "slave"
/*
* et_leds1 configuration
*
*/
#define ALT_MODULE_CLASS_et_leds1 altera_avalon_pio
#define ET_LEDS1_BASE 0x9470
#define ET_LEDS1_BIT_CLEARING_EDGE_REGISTER 0
#define ET_LEDS1_BIT_MODIFYING_OUTPUT_REGISTER 0
#define ET_LEDS1_CAPTURE 0
#define ET_LEDS1_DATA_WIDTH 2
#define ET_LEDS1_DO_TEST_BENCH_WIRING 0
#define ET_LEDS1_DRIVEN_SIM_VALUE 0
#define ET_LEDS1_EDGE_TYPE "NONE"
#define ET_LEDS1_FREQ 50000000
#define ET_LEDS1_HAS_IN 0
#define ET_LEDS1_HAS_OUT 1
#define ET_LEDS1_HAS_TRI 0
#define ET_LEDS1_IRQ -1
#define ET_LEDS1_IRQ_INTERRUPT_CONTROLLER_ID -1
#define ET_LEDS1_IRQ_TYPE "NONE"
#define ET_LEDS1_NAME "/dev/et_leds1"
#define ET_LEDS1_RESET_VALUE 0
#define ET_LEDS1_SPAN 16
#define ET_LEDS1_TYPE "altera_avalon_pio"
/*
* et_leds2 configuration
*
*/
#define ALT_MODULE_CLASS_et_leds2 altera_avalon_pio
#define ET_LEDS2_BASE 0xa000
#define ET_LEDS2_BIT_CLEARING_EDGE_REGISTER 0
#define ET_LEDS2_BIT_MODIFYING_OUTPUT_REGISTER 0
#define ET_LEDS2_CAPTURE 0
#define ET_LEDS2_DATA_WIDTH 2
#define ET_LEDS2_DO_TEST_BENCH_WIRING 0
#define ET_LEDS2_DRIVEN_SIM_VALUE 0
#define ET_LEDS2_EDGE_TYPE "NONE"
#define ET_LEDS2_FREQ 50000000
#define ET_LEDS2_HAS_IN 0
#define ET_LEDS2_HAS_OUT 1
#define ET_LEDS2_HAS_TRI 0
#define ET_LEDS2_IRQ -1
#define ET_LEDS2_IRQ_INTERRUPT_CONTROLLER_ID -1
#define ET_LEDS2_IRQ_TYPE "NONE"
#define ET_LEDS2_NAME "/dev/et_leds2"
#define ET_LEDS2_RESET_VALUE 0
#define ET_LEDS2_SPAN 16
#define ET_LEDS2_TYPE "altera_avalon_pio"
/*
* et_pb_1 configuration
*
*/
#define ALT_MODULE_CLASS_et_pb_1 altera_avalon_pio
#define ET_PB_1_BASE 0x9450
#define ET_PB_1_BIT_CLEARING_EDGE_REGISTER 0
#define ET_PB_1_BIT_MODIFYING_OUTPUT_REGISTER 0
#define ET_PB_1_CAPTURE 0
#define ET_PB_1_DATA_WIDTH 1
#define ET_PB_1_DO_TEST_BENCH_WIRING 1
#define ET_PB_1_DRIVEN_SIM_VALUE 0
#define ET_PB_1_EDGE_TYPE "NONE"
#define ET_PB_1_FREQ 50000000
#define ET_PB_1_HAS_IN 1
#define ET_PB_1_HAS_OUT 0
#define ET_PB_1_HAS_TRI 0
#define ET_PB_1_IRQ -1
#define ET_PB_1_IRQ_INTERRUPT_CONTROLLER_ID -1
#define ET_PB_1_IRQ_TYPE "NONE"
#define ET_PB_1_NAME "/dev/et_pb_1"
#define ET_PB_1_RESET_VALUE 0
#define ET_PB_1_SPAN 16
#define ET_PB_1_TYPE "altera_avalon_pio"
/*
* et_pb_2 configuration
*
*/
#define ALT_MODULE_CLASS_et_pb_2 altera_avalon_pio
#define ET_PB_2_BASE 0x9440
#define ET_PB_2_BIT_CLEARING_EDGE_REGISTER 0
#define ET_PB_2_BIT_MODIFYING_OUTPUT_REGISTER 0
#define ET_PB_2_CAPTURE 0
#define ET_PB_2_DATA_WIDTH 1
#define ET_PB_2_DO_TEST_BENCH_WIRING 1
#define ET_PB_2_DRIVEN_SIM_VALUE 0
#define ET_PB_2_EDGE_TYPE "NONE"
#define ET_PB_2_FREQ 50000000
#define ET_PB_2_HAS_IN 1
#define ET_PB_2_HAS_OUT 0
#define ET_PB_2_HAS_TRI 0
#define ET_PB_2_IRQ -1
#define ET_PB_2_IRQ_INTERRUPT_CONTROLLER_ID -1
#define ET_PB_2_IRQ_TYPE "NONE"
#define ET_PB_2_NAME "/dev/et_pb_2"
#define ET_PB_2_RESET_VALUE 0
#define ET_PB_2_SPAN 16
#define ET_PB_2_TYPE "altera_avalon_pio"
/*
* et_spi_0 configuration
*
*/
#define ALT_MODULE_CLASS_et_spi_0 altera_avalon_spi
#define ET_SPI_0_BASE 0x9420
#define ET_SPI_0_CLOCKMULT 1
#define ET_SPI_0_CLOCKPHASE 0
#define ET_SPI_0_CLOCKPOLARITY 0
#define ET_SPI_0_CLOCKUNITS "Hz"
#define ET_SPI_0_DATABITS 8
#define ET_SPI_0_DATAWIDTH 16
#define ET_SPI_0_DELAYMULT "1.0E-9"
#define ET_SPI_0_DELAYUNITS "ns"
#define ET_SPI_0_EXTRADELAY 0
#define ET_SPI_0_INSERT_SYNC 0
#define ET_SPI_0_IRQ 1
#define ET_SPI_0_IRQ_INTERRUPT_CONTROLLER_ID 0
#define ET_SPI_0_ISMASTER 1
#define ET_SPI_0_LSBFIRST 0
#define ET_SPI_0_NAME "/dev/et_spi_0"
#define ET_SPI_0_NUMSLAVES 1
#define ET_SPI_0_PREFIX "spi_"
#define ET_SPI_0_SPAN 32
#define ET_SPI_0_SYNC_REG_DEPTH 2
#define ET_SPI_0_TARGETCLOCK 128000u
#define ET_SPI_0_TARGETSSDELAY "0.0"
#define ET_SPI_0_TYPE "altera_avalon_spi"
/*
* et_spican_int configuration
*
*/
#define ALT_MODULE_CLASS_et_spican_int altera_avalon_pio
#define ET_SPICAN_INT_BASE 0x9460
#define ET_SPICAN_INT_BIT_CLEARING_EDGE_REGISTER 0
#define ET_SPICAN_INT_BIT_MODIFYING_OUTPUT_REGISTER 0
#define ET_SPICAN_INT_CAPTURE 1
#define ET_SPICAN_INT_DATA_WIDTH 1
#define ET_SPICAN_INT_DO_TEST_BENCH_WIRING 1
#define ET_SPICAN_INT_DRIVEN_SIM_VALUE 0
#define ET_SPICAN_INT_EDGE_TYPE "FALLING"
#define ET_SPICAN_INT_FREQ 50000000
#define ET_SPICAN_INT_HAS_IN 1
#define ET_SPICAN_INT_HAS_OUT 0
#define ET_SPICAN_INT_HAS_TRI 0
#define ET_SPICAN_INT_IRQ 0
#define ET_SPICAN_INT_IRQ_INTERRUPT_CONTROLLER_ID 0
#define ET_SPICAN_INT_IRQ_TYPE "EDGE"
#define ET_SPICAN_INT_NAME "/dev/et_spican_int"
#define ET_SPICAN_INT_RESET_VALUE 0
#define ET_SPICAN_INT_SPAN 16
#define ET_SPICAN_INT_TYPE "altera_avalon_pio"
/*
* hal configuration
*
*/
#define ALT_MAX_FD 32
#define ALT_SYS_CLK none
#define ALT_TIMESTAMP_CLK none
/*
* jtag_uart_0 configuration
*
*/
#define ALT_MODULE_CLASS_jtag_uart_0 altera_avalon_jtag_uart
#define JTAG_UART_0_BASE 0x9488
#define JTAG_UART_0_IRQ 3
#define JTAG_UART_0_IRQ_INTERRUPT_CONTROLLER_ID 0
#define JTAG_UART_0_NAME "/dev/jtag_uart_0"
#define JTAG_UART_0_READ_DEPTH 64
#define JTAG_UART_0_READ_THRESHOLD 8
#define JTAG_UART_0_SPAN 8
#define JTAG_UART_0_TYPE "altera_avalon_jtag_uart"
#define JTAG_UART_0_WRITE_DEPTH 64
#define JTAG_UART_0_WRITE_THRESHOLD 8
/*
* msg_buf_mutex configuration
*
*/
#define ALT_MODULE_CLASS_msg_buf_mutex altera_avalon_mutex
#define MSG_BUF_MUTEX_BASE 0x9480
#define MSG_BUF_MUTEX_IRQ -1
#define MSG_BUF_MUTEX_IRQ_INTERRUPT_CONTROLLER_ID -1
#define MSG_BUF_MUTEX_NAME "/dev/msg_buf_mutex"
#define MSG_BUF_MUTEX_OWNER_INIT 0
#define MSG_BUF_MUTEX_OWNER_WIDTH 16
#define MSG_BUF_MUTEX_SPAN 8
#define MSG_BUF_MUTEX_TYPE "altera_avalon_mutex"
#define MSG_BUF_MUTEX_VALUE_INIT 0
#define MSG_BUF_MUTEX_VALUE_WIDTH 16
/*
* msg_buf_ram configuration
*
*/
#define ALT_MODULE_CLASS_msg_buf_ram altera_avalon_onchip_memory2
#define MSG_BUF_RAM_ALLOW_IN_SYSTEM_MEMORY_CONTENT_EDITOR 0
#define MSG_BUF_RAM_ALLOW_MRAM_SIM_CONTENTS_ONLY_FILE 0
#define MSG_BUF_RAM_BASE 0x9000
#define MSG_BUF_RAM_CONTENTS_INFO ""
#define MSG_BUF_RAM_DUAL_PORT 0
#define MSG_BUF_RAM_GUI_RAM_BLOCK_TYPE "AUTO"
#define MSG_BUF_RAM_INIT_CONTENTS_FILE "slave_msg_buf_ram"
#define MSG_BUF_RAM_INIT_MEM_CONTENT 1
#define MSG_BUF_RAM_INSTANCE_ID "NONE"
#define MSG_BUF_RAM_IRQ -1
#define MSG_BUF_RAM_IRQ_INTERRUPT_CONTROLLER_ID -1
#define MSG_BUF_RAM_NAME "/dev/msg_buf_ram"
#define MSG_BUF_RAM_NON_DEFAULT_INIT_FILE_ENABLED 0
#define MSG_BUF_RAM_RAM_BLOCK_TYPE "AUTO"
#define MSG_BUF_RAM_READ_DURING_WRITE_MODE "DONT_CARE"
#define MSG_BUF_RAM_SINGLE_CLOCK_OP 0
#define MSG_BUF_RAM_SIZE_MULTIPLE 1
#define MSG_BUF_RAM_SIZE_VALUE 1024
#define MSG_BUF_RAM_SPAN 1024
#define MSG_BUF_RAM_TYPE "altera_avalon_onchip_memory2"
#define MSG_BUF_RAM_WRITABLE 1
/*
* pio_0 configuration
*
*/
#define ALT_MODULE_CLASS_pio_0 altera_avalon_pio
#define PIO_0_BASE 0x94a0
#define PIO_0_BIT_CLEARING_EDGE_REGISTER 0
#define PIO_0_BIT_MODIFYING_OUTPUT_REGISTER 0
#define PIO_0_CAPTURE 0
#define PIO_0_DATA_WIDTH 1
#define PIO_0_DO_TEST_BENCH_WIRING 0
#define PIO_0_DRIVEN_SIM_VALUE 0
#define PIO_0_EDGE_TYPE "NONE"
#define PIO_0_FREQ 50000000
#define PIO_0_HAS_IN 0
#define PIO_0_HAS_OUT 1
#define PIO_0_HAS_TRI 0
#define PIO_0_IRQ -1
#define PIO_0_IRQ_INTERRUPT_CONTROLLER_ID -1
#define PIO_0_IRQ_TYPE "NONE"
#define PIO_0_NAME "/dev/pio_0"
#define PIO_0_RESET_VALUE 0
#define PIO_0_SPAN 16
#define PIO_0_TYPE "altera_avalon_pio"
#endif /* __SYSTEM_H_ */
<file_sep>/*
* system.h - SOPC Builder system and BSP software package information
*
* Machine generated for CPU 'nios2_qsys_0' in SOPC Builder design 'master'
* SOPC Builder design path: C:/Users/a/Documents/EG3205_Work/Assignment_2_solution/master/master.sopcinfo
*
* Generated: Fri Dec 14 12:46:56 GMT 2018
*/
/*
* DO NOT MODIFY THIS FILE
*
* Changing this file will have subtle consequences
* which will almost certainly lead to a nonfunctioning
* system. If you do modify this file, be aware that your
* changes will be overwritten and lost when this file
* is generated again.
*
* DO NOT MODIFY THIS FILE
*/
/*
* License Agreement
*
* Copyright (c) 2008
* Altera Corporation, San Jose, California, USA.
* All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
* This agreement shall be governed in all respects by the laws of the State
* of California and by the laws of the United States of America.
*/
#ifndef __SYSTEM_H_
#define __SYSTEM_H_
/* Include definitions from linker script generator */
#include "linker.h"
/*
* CPU configuration
*
*/
#define ALT_CPU_ARCHITECTURE "altera_nios2_qsys"
#define ALT_CPU_BIG_ENDIAN 0
#define ALT_CPU_BREAK_ADDR 0x00004820
#define ALT_CPU_CPU_FREQ 50000000u
#define ALT_CPU_CPU_ID_SIZE 1
#define ALT_CPU_CPU_ID_VALUE 0x00000000
#define ALT_CPU_CPU_IMPLEMENTATION "tiny"
#define ALT_CPU_DATA_ADDR_WIDTH 0xf
#define ALT_CPU_DCACHE_LINE_SIZE 0
#define ALT_CPU_DCACHE_LINE_SIZE_LOG2 0
#define ALT_CPU_DCACHE_SIZE 0
#define ALT_CPU_EXCEPTION_ADDR 0x00000020
#define ALT_CPU_FLUSHDA_SUPPORTED
#define ALT_CPU_FREQ 50000000
#define ALT_CPU_HARDWARE_DIVIDE_PRESENT 0
#define ALT_CPU_HARDWARE_MULTIPLY_PRESENT 0
#define ALT_CPU_HARDWARE_MULX_PRESENT 0
#define ALT_CPU_HAS_DEBUG_CORE 1
#define ALT_CPU_HAS_DEBUG_STUB
#define ALT_CPU_HAS_JMPI_INSTRUCTION
#define ALT_CPU_ICACHE_LINE_SIZE 0
#define ALT_CPU_ICACHE_LINE_SIZE_LOG2 0
#define ALT_CPU_ICACHE_SIZE 0
#define ALT_CPU_INST_ADDR_WIDTH 0xf
#define ALT_CPU_NAME "nios2_qsys_0"
#define ALT_CPU_RESET_ADDR 0x00000000
/*
* CPU configuration (with legacy prefix - don't use these anymore)
*
*/
#define NIOS2_BIG_ENDIAN 0
#define NIOS2_BREAK_ADDR 0x00004820
#define NIOS2_CPU_FREQ 50000000u
#define NIOS2_CPU_ID_SIZE 1
#define NIOS2_CPU_ID_VALUE 0x00000000
#define NIOS2_CPU_IMPLEMENTATION "tiny"
#define NIOS2_DATA_ADDR_WIDTH 0xf
#define NIOS2_DCACHE_LINE_SIZE 0
#define NIOS2_DCACHE_LINE_SIZE_LOG2 0
#define NIOS2_DCACHE_SIZE 0
#define NIOS2_EXCEPTION_ADDR 0x00000020
#define NIOS2_FLUSHDA_SUPPORTED
#define NIOS2_HARDWARE_DIVIDE_PRESENT 0
#define NIOS2_HARDWARE_MULTIPLY_PRESENT 0
#define NIOS2_HARDWARE_MULX_PRESENT 0
#define NIOS2_HAS_DEBUG_CORE 1
#define NIOS2_HAS_DEBUG_STUB
#define NIOS2_HAS_JMPI_INSTRUCTION
#define NIOS2_ICACHE_LINE_SIZE 0
#define NIOS2_ICACHE_LINE_SIZE_LOG2 0
#define NIOS2_ICACHE_SIZE 0
#define NIOS2_INST_ADDR_WIDTH 0xf
#define NIOS2_RESET_ADDR 0x00000000
/*
* Define for each module class mastered by the CPU
*
*/
#define __ALTERA_AVALON_JTAG_UART
#define __ALTERA_AVALON_ONCHIP_MEMORY2
#define __ALTERA_AVALON_PIO
#define __ALTERA_AVALON_SPI
#define __ALTERA_AVALON_TIMER
#define __ALTERA_NIOS2_QSYS
/*
* System configuration
*
*/
#define ALT_DEVICE_FAMILY "Cyclone III"
#define ALT_ENHANCED_INTERRUPT_API_PRESENT
#define ALT_IRQ_BASE NULL
#define ALT_LOG_PORT "/dev/null"
#define ALT_LOG_PORT_BASE 0x0
#define ALT_LOG_PORT_DEV null
#define ALT_LOG_PORT_TYPE ""
#define ALT_NUM_EXTERNAL_INTERRUPT_CONTROLLERS 0
#define ALT_NUM_INTERNAL_INTERRUPT_CONTROLLERS 1
#define ALT_NUM_INTERRUPT_CONTROLLERS 1
#define ALT_STDERR "/dev/jtag_uart_0"
#define ALT_STDERR_BASE 0x50a0
#define ALT_STDERR_DEV jtag_uart_0
#define ALT_STDERR_IS_JTAG_UART
#define ALT_STDERR_PRESENT
#define ALT_STDERR_TYPE "altera_avalon_jtag_uart"
#define ALT_STDIN "/dev/jtag_uart_0"
#define ALT_STDIN_BASE 0x50a0
#define ALT_STDIN_DEV jtag_uart_0
#define ALT_STDIN_IS_JTAG_UART
#define ALT_STDIN_PRESENT
#define ALT_STDIN_TYPE "altera_avalon_jtag_uart"
#define ALT_STDOUT "/dev/jtag_uart_0"
#define ALT_STDOUT_BASE 0x50a0
#define ALT_STDOUT_DEV jtag_uart_0
#define ALT_STDOUT_IS_JTAG_UART
#define ALT_STDOUT_PRESENT
#define ALT_STDOUT_TYPE "altera_avalon_jtag_uart"
#define ALT_SYSTEM_NAME "master"
/*
* hal configuration
*
*/
#define ALT_MAX_FD 32
#define ALT_SYS_CLK TIMER_0
#define ALT_TIMESTAMP_CLK none
/*
* jtag_uart_0 configuration
*
*/
#define ALT_MODULE_CLASS_jtag_uart_0 altera_avalon_jtag_uart
#define JTAG_UART_0_BASE 0x50a0
#define JTAG_UART_0_IRQ 3
#define JTAG_UART_0_IRQ_INTERRUPT_CONTROLLER_ID 0
#define JTAG_UART_0_NAME "/dev/jtag_uart_0"
#define JTAG_UART_0_READ_DEPTH 64
#define JTAG_UART_0_READ_THRESHOLD 8
#define JTAG_UART_0_SPAN 8
#define JTAG_UART_0_TYPE "altera_avalon_jtag_uart"
#define JTAG_UART_0_WRITE_DEPTH 64
#define JTAG_UART_0_WRITE_THRESHOLD 8
/*
* onchip_memory2_0 configuration
*
*/
#define ALT_MODULE_CLASS_onchip_memory2_0 altera_avalon_onchip_memory2
#define ONCHIP_MEMORY2_0_ALLOW_IN_SYSTEM_MEMORY_CONTENT_EDITOR 0
#define ONCHIP_MEMORY2_0_ALLOW_MRAM_SIM_CONTENTS_ONLY_FILE 0
#define ONCHIP_MEMORY2_0_BASE 0x0
#define ONCHIP_MEMORY2_0_CONTENTS_INFO ""
#define ONCHIP_MEMORY2_0_DUAL_PORT 0
#define ONCHIP_MEMORY2_0_GUI_RAM_BLOCK_TYPE "AUTO"
#define ONCHIP_MEMORY2_0_INIT_CONTENTS_FILE "master_onchip_memory2_0"
#define ONCHIP_MEMORY2_0_INIT_MEM_CONTENT 1
#define ONCHIP_MEMORY2_0_INSTANCE_ID "NONE"
#define ONCHIP_MEMORY2_0_IRQ -1
#define ONCHIP_MEMORY2_0_IRQ_INTERRUPT_CONTROLLER_ID -1
#define ONCHIP_MEMORY2_0_NAME "/dev/onchip_memory2_0"
#define ONCHIP_MEMORY2_0_NON_DEFAULT_INIT_FILE_ENABLED 0
#define ONCHIP_MEMORY2_0_RAM_BLOCK_TYPE "AUTO"
#define ONCHIP_MEMORY2_0_READ_DURING_WRITE_MODE "DONT_CARE"
#define ONCHIP_MEMORY2_0_SINGLE_CLOCK_OP 0
#define ONCHIP_MEMORY2_0_SIZE_MULTIPLE 1
#define ONCHIP_MEMORY2_0_SIZE_VALUE 16348
#define ONCHIP_MEMORY2_0_SPAN 16348
#define ONCHIP_MEMORY2_0_TYPE "altera_avalon_onchip_memory2"
#define ONCHIP_MEMORY2_0_WRITABLE 1
/*
* pio_0 configuration
*
*/
#define ALT_MODULE_CLASS_pio_0 altera_avalon_pio
#define PIO_0_BASE 0x5090
#define PIO_0_BIT_CLEARING_EDGE_REGISTER 0
#define PIO_0_BIT_MODIFYING_OUTPUT_REGISTER 0
#define PIO_0_CAPTURE 0
#define PIO_0_DATA_WIDTH 8
#define PIO_0_DO_TEST_BENCH_WIRING 0
#define PIO_0_DRIVEN_SIM_VALUE 0
#define PIO_0_EDGE_TYPE "NONE"
#define PIO_0_FREQ 50000000
#define PIO_0_HAS_IN 0
#define PIO_0_HAS_OUT 1
#define PIO_0_HAS_TRI 0
#define PIO_0_IRQ -1
#define PIO_0_IRQ_INTERRUPT_CONTROLLER_ID -1
#define PIO_0_IRQ_TYPE "NONE"
#define PIO_0_NAME "/dev/pio_0"
#define PIO_0_RESET_VALUE 0
#define PIO_0_SPAN 16
#define PIO_0_TYPE "altera_avalon_pio"
/*
* pio_1 configuration
*
*/
#define ALT_MODULE_CLASS_pio_1 altera_avalon_pio
#define PIO_1_BASE 0x5060
#define PIO_1_BIT_CLEARING_EDGE_REGISTER 0
#define PIO_1_BIT_MODIFYING_OUTPUT_REGISTER 0
#define PIO_1_CAPTURE 0
#define PIO_1_DATA_WIDTH 3
#define PIO_1_DO_TEST_BENCH_WIRING 0
#define PIO_1_DRIVEN_SIM_VALUE 0
#define PIO_1_EDGE_TYPE "NONE"
#define PIO_1_FREQ 50000000
#define PIO_1_HAS_IN 0
#define PIO_1_HAS_OUT 1
#define PIO_1_HAS_TRI 0
#define PIO_1_IRQ -1
#define PIO_1_IRQ_INTERRUPT_CONTROLLER_ID -1
#define PIO_1_IRQ_TYPE "NONE"
#define PIO_1_NAME "/dev/pio_1"
#define PIO_1_RESET_VALUE 0
#define PIO_1_SPAN 16
#define PIO_1_TYPE "altera_avalon_pio"
/*
* pio_2 configuration
*
*/
#define ALT_MODULE_CLASS_pio_2 altera_avalon_pio
#define PIO_2_BASE 0x5070
#define PIO_2_BIT_CLEARING_EDGE_REGISTER 0
#define PIO_2_BIT_MODIFYING_OUTPUT_REGISTER 0
#define PIO_2_CAPTURE 1
#define PIO_2_DATA_WIDTH 1
#define PIO_2_DO_TEST_BENCH_WIRING 1
#define PIO_2_DRIVEN_SIM_VALUE 0
#define PIO_2_EDGE_TYPE "FALLING"
#define PIO_2_FREQ 50000000
#define PIO_2_HAS_IN 1
#define PIO_2_HAS_OUT 0
#define PIO_2_HAS_TRI 0
#define PIO_2_IRQ 2
#define PIO_2_IRQ_INTERRUPT_CONTROLLER_ID 0
#define PIO_2_IRQ_TYPE "EDGE"
#define PIO_2_NAME "/dev/pio_2"
#define PIO_2_RESET_VALUE 0
#define PIO_2_SPAN 16
#define PIO_2_TYPE "altera_avalon_pio"
/*
* pio_4 configuration
*
*/
#define ALT_MODULE_CLASS_pio_4 altera_avalon_pio
#define PIO_4_BASE 0x5050
#define PIO_4_BIT_CLEARING_EDGE_REGISTER 0
#define PIO_4_BIT_MODIFYING_OUTPUT_REGISTER 0
#define PIO_4_CAPTURE 0
#define PIO_4_DATA_WIDTH 1
#define PIO_4_DO_TEST_BENCH_WIRING 1
#define PIO_4_DRIVEN_SIM_VALUE 0
#define PIO_4_EDGE_TYPE "NONE"
#define PIO_4_FREQ 50000000
#define PIO_4_HAS_IN 1
#define PIO_4_HAS_OUT 0
#define PIO_4_HAS_TRI 0
#define PIO_4_IRQ -1
#define PIO_4_IRQ_INTERRUPT_CONTROLLER_ID -1
#define PIO_4_IRQ_TYPE "NONE"
#define PIO_4_NAME "/dev/pio_4"
#define PIO_4_RESET_VALUE 0
#define PIO_4_SPAN 16
#define PIO_4_TYPE "altera_avalon_pio"
/*
* pio_5 configuration
*
*/
#define ALT_MODULE_CLASS_pio_5 altera_avalon_pio
#define PIO_5_BASE 0x5040
#define PIO_5_BIT_CLEARING_EDGE_REGISTER 0
#define PIO_5_BIT_MODIFYING_OUTPUT_REGISTER 0
#define PIO_5_CAPTURE 0
#define PIO_5_DATA_WIDTH 1
#define PIO_5_DO_TEST_BENCH_WIRING 1
#define PIO_5_DRIVEN_SIM_VALUE 0
#define PIO_5_EDGE_TYPE "NONE"
#define PIO_5_FREQ 50000000
#define PIO_5_HAS_IN 1
#define PIO_5_HAS_OUT 0
#define PIO_5_HAS_TRI 0
#define PIO_5_IRQ -1
#define PIO_5_IRQ_INTERRUPT_CONTROLLER_ID -1
#define PIO_5_IRQ_TYPE "NONE"
#define PIO_5_NAME "/dev/pio_5"
#define PIO_5_RESET_VALUE 0
#define PIO_5_SPAN 16
#define PIO_5_TYPE "altera_avalon_pio"
/*
* spi_0 configuration
*
*/
#define ALT_MODULE_CLASS_spi_0 altera_avalon_spi
#define SPI_0_BASE 0x5020
#define SPI_0_CLOCKMULT 1
#define SPI_0_CLOCKPHASE 0
#define SPI_0_CLOCKPOLARITY 0
#define SPI_0_CLOCKUNITS "Hz"
#define SPI_0_DATABITS 8
#define SPI_0_DATAWIDTH 16
#define SPI_0_DELAYMULT "1.0E-9"
#define SPI_0_DELAYUNITS "ns"
#define SPI_0_EXTRADELAY 0
#define SPI_0_INSERT_SYNC 0
#define SPI_0_IRQ 1
#define SPI_0_IRQ_INTERRUPT_CONTROLLER_ID 0
#define SPI_0_ISMASTER 1
#define SPI_0_LSBFIRST 0
#define SPI_0_NAME "/dev/spi_0"
#define SPI_0_NUMSLAVES 1
#define SPI_0_PREFIX "spi_"
#define SPI_0_SPAN 32
#define SPI_0_SYNC_REG_DEPTH 2
#define SPI_0_TARGETCLOCK 128000u
#define SPI_0_TARGETSSDELAY "0.0"
#define SPI_0_TYPE "altera_avalon_spi"
/*
* timer_0 configuration
*
*/
#define ALT_MODULE_CLASS_timer_0 altera_avalon_timer
#define TIMER_0_ALWAYS_RUN 0
#define TIMER_0_BASE 0x5000
#define TIMER_0_COUNTER_SIZE 32
#define TIMER_0_FIXED_PERIOD 1
#define TIMER_0_FREQ 50000000
#define TIMER_0_IRQ 0
#define TIMER_0_IRQ_INTERRUPT_CONTROLLER_ID 0
#define TIMER_0_LOAD_VALUE 249999
#define TIMER_0_MULT 0.0010
#define TIMER_0_NAME "/dev/timer_0"
#define TIMER_0_PERIOD 5
#define TIMER_0_PERIOD_UNITS "ms"
#define TIMER_0_RESET_OUTPUT 0
#define TIMER_0_SNAPSHOT 1
#define TIMER_0_SPAN 32
#define TIMER_0_TICKS_PER_SEC 200.0
#define TIMER_0_TIMEOUT_PULSE_OUTPUT 0
#define TIMER_0_TYPE "altera_avalon_timer"
#endif /* __SYSTEM_H_ */
<file_sep># Makefile
# the C++ compiler
CXX = g++
CC = $(CXX)
# options to pass to the compiler
CXXFLAGS = -Wall -ansi -O2 -g
convert : convert.o
$(CXX) $(CXXFLAGS) -o convert convert.o
convert.o : convert.cpp
$(CXX) $(CXXFLAGS) -c convert.cpp
.PHONY : clean
clean :
$(RM) convert convert.o *~
<file_sep>/*
Version of isort using typed interfaces
*/
import java.util.*;
// generic typed insertion sort ----------------------------------------
public class CC05 {
// compare two elements ----------------------------------------
static interface Comp<E> {
public boolean c_lt(E e1, E e2); // c_ stands for "comp"
}
// "list-like" operations ----------------------------------------
// string/list operations; E is element type; L is list type; g_
// stands for "generic"
static interface Ops<E,L> {
L g_nil();
L g_cons(E x, L l);
L g_append(L l1, L l2);
L g_append1(L l, E e);
boolean g_is_empty(L l);
E g_hd(L l);
L g_tl(L l);
}
// insertion sort ----------------------------------------
static class Sorter<E,L> {
Comp<E> comp;
Ops<E,L> ops;
public Sorter(Comp<E> c, Ops<E,L> o) {
this.comp = c;
this.ops = o;
}
L insert(E o, L l) {
L to_return = ops.g_nil();
while(true) {
if(ops.g_is_empty(l)) return ops.g_append1(to_return,o);
E o2 = ops.g_hd(l);
if(comp.c_lt(o2,o))
to_return = ops.g_append1(to_return,o2);
else
return ops.g_append(ops.g_append1(to_return,o),l);
l = ops.g_tl(l);
}
}
L isort(L l) {
L to_return = ops.g_nil();
while(true) {
if(ops.g_is_empty(l)) return to_return;
E o = ops.g_hd(l);
to_return = insert(o,to_return);
l = ops.g_tl(l);
}
}
} // Sorter
// example executions ----------------------------------------
// the same isort code works for int lists and strings!
public void main() {
// // sort list of integers ----------------------------------------
// {
// Sorter<Integer,List<Integer>> x =
// new Sorter(
// new I_comp(),
// new I_list_ops()
// );
// List<Integer> l = java.util.Arrays.asList(new Integer[] {4,1,2,0});
// // System.out.println(x.isort(l));
// }
//
// // sort a string ----------------------------------------
// {
// Sorter<Character,String> x =
// new Sorter(
// new C_comp(),
// new String_ops()
// );
// // System.out.println(x.isort("defabcg"));
// }
// sort a list of people by first name
List<Person> ps = java.util.Arrays.asList(new Person[] {
new Person("Bert","Dent"),
new Person("Alf","Figgis"),
new Person("Charlie","Carruthers"),
new Person("Ellie","Bloggs"),
new Person("Davina","Ewans")
});
{
Sorter<Person,List<Person>> x =
new Sorter(
new Comp_by_first_name(),
new P_list_ops()
);
System.out.println(x.isort(ps));
}
// sort a list of people by last name
// FIXME add some code here
{ Sorter<Person,List<Person>> y =
new Sorter(
new Comp_by_last_name(),
new P_list_ops()
);
System.out.println(y.isort(ps));
}
}
// static main ----------------------------------------
public static void main(String[] args) {
new CC05().main();
}
// example ops (person list) ----------------------------------------
static class Person {
String first, last;
Person(String f, String l) { first=f; last=l; }
public String toString() { return "-"+first+" "+last+"-"; }
}
// returns true if s1 < s2
static boolean lexcompare(String s1, String s2) {
return s1.compareTo(s2) < 0;
}
// compare by first name
static class Comp_by_first_name implements Comp<Person> {
public boolean c_lt(Person e1, Person e2) {
//return true; // FIXME replace this; use lexcompare from just above
return lexcompare(e1.first,e2.first);
}
}
// compare by last name
static class Comp_by_last_name implements Comp<Person> {
public boolean c_lt(Person e1, Person e2) {
//return true; // FIXME replace this; use lexcompare from just above
return lexcompare(e1.last,e2.last);
}
}
static class P_list_ops implements Ops<Person,List<Person>> {
public boolean g_is_empty(List<Person> l) { return l.isEmpty(); }
public Person g_hd(List<Person> l) { return (Person)(hd(l)); }
public List<Person> g_tl(List<Person> l) { return (List<Person>)tl(l); }
public List<Person> g_append(List<Person> l1,List<Person> l2) {
return (List<Person>)append(l1,l2);
}
public List<Person> g_append1(List<Person> l1, Person e) {
return (List<Person>)append1(l1,e);
}
public List<Person> g_nil() { return (List<Person>)nil(); }
public List<Person> g_cons(Person x, List<Person> l) {
return (List<Person>)cons(x,l);
}
//////////////////////////////////////////////////////////////////////
// cons, nil etc are implemented below this line;
// you can probably ignore what is below
// most of the following methods could/should be static
// clone is protected, so we could subclass but...
// YOU ARE NOT ALLOWED TO USE THIS COPY FUNCTION!!! IT IS ONLY FOR
// IMPLEMENTING cons ETC.
List copy(List l0) {
List to_return = new LinkedList();
for(int i=0; i<l0.size(); i++) {
to_return.add(i,l0.get(i));
}
return to_return;
}
// the empty list
List nil() {
return new LinkedList();
}
// add at front of list
List cons(Object o, List l0) {
List l = copy(l0);
l.add(0,o);
return l;
}
// head of the list
Object hd(List l) { return l.get(0); }
// tail of the list
List tl(List l0) {
List l = copy(l0);
l.remove(0);
return l;
}
// add at end of list
List append1(List l0, Object o) {
List l = copy(l0);
l.add(l.size(),o);
return l;
}
// join two lists together
List append(List l01, List l02) {
List to_return = copy(l01);
List l2 = copy(l02);
while(true) {
if(l2.isEmpty()) return to_return;
to_return=append1(to_return,hd(l2));
l2=tl(l2);
}
}
String list_to_string(List l) {
String to_return ="[";
while(true) {
if(l.isEmpty()) return (to_return+"]");
if(tl(l).isEmpty()) return (to_return+hd(l)+"]");
to_return+=hd(l)+",";
l=tl(l);
}
}
}
// example ops (string) ----------------------------------------
static class String_ops implements Ops<Character,String> {
public boolean g_is_empty(String l) { return l.equals(""); }
public Character g_hd(String l) { return l.charAt(0); }
public String g_tl(String l) { return l.substring(1); }
public String g_append(String l1,String l2) { return l1+l2; }
public String g_append1(String l1, Character e) { return l1+e; }
public boolean g_lt(Character o1,Character o2) { return o1 < o2; }
public String g_nil() { return ""; }
public String g_cons(Character x, String l) { return x.toString()+l; }
}
// char compare
static class C_comp implements Comp<Character> {
public boolean c_lt(Character e1, Character e2) {
return e1 < e2;
}
}
// example ops (int list) ----------------------------------------
// int compare
static class I_comp implements Comp<Integer> {
public boolean c_lt(Integer e1, Integer e2) {
return e1 < e2;
}
}
static class I_list_ops implements Ops<Integer,List<Integer>> {
public boolean g_is_empty(List<Integer> l) { return l.isEmpty(); }
public Integer g_hd(List<Integer> l) { return (Integer)(hd(l)); }
public List<Integer> g_tl(List<Integer> l) { return (List<Integer>)tl(l); }
public List<Integer> g_append(List<Integer> l1,List<Integer> l2) {
return (List<Integer>)append(l1,l2);
}
public List<Integer> g_append1(List<Integer> l1, Integer e) {
return (List<Integer>)append1(l1,e);
}
public List<Integer> g_nil() { return (List<Integer>)nil(); }
public List<Integer> g_cons(Integer x, List<Integer> l) {
return (List<Integer>)cons(x,l);
}
//////////////////////////////////////////////////////////////////////
// cons, nil etc are implemented below this line;
// you can probably ignore what is below
// most of the following methods could/should be static
// clone is protected, so we could subclass but...
// YOU ARE NOT ALLOWED TO USE THIS COPY FUNCTION!!! IT IS ONLY FOR
// IMPLEMENTING cons ETC.
List copy(List l0) {
List to_return = new LinkedList();
for(int i=0; i<l0.size(); i++) {
to_return.add(i,l0.get(i));
}
return to_return;
}
// the empty list
List nil() {
return new LinkedList();
}
// add at front of list
List cons(Object o, List l0) {
List l = copy(l0);
l.add(0,o);
return l;
}
// head of the list
Object hd(List l) { return l.get(0); }
// tail of the list
List tl(List l0) {
List l = copy(l0);
l.remove(0);
return l;
}
// add at end of list
List append1(List l0, Object o) {
List l = copy(l0);
l.add(l.size(),o);
return l;
}
// join two lists together
List append(List l01, List l02) {
List to_return = copy(l01);
List l2 = copy(l02);
while(true) {
if(l2.isEmpty()) return to_return;
to_return=append1(to_return,hd(l2));
l2=tl(l2);
}
}
String list_to_string(List l) {
String to_return ="[";
while(true) {
if(l.isEmpty()) return (to_return+"]");
if(tl(l).isEmpty()) return (to_return+hd(l)+"]");
to_return+=hd(l)+",";
l=tl(l);
}
}
}
}
<file_sep>package eMarket;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
@EnableWebSecurity
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
DataSource dataSource;
@Bean
public PasswordEncoder passwordEncoder(){
PasswordEncoder encoder = new BCryptPasswordEncoder();
return encoder;
}
@Autowired
private UserDetailsService userDetailsService;
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
}
//anything need to be done in configureGlobal?
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
//do we have the next three lines or the original coding that's commented above
.requiresChannel()
.anyRequest()
.requiresSecure()
// TODO: AUTHENTICATION AND AUTHORIZATION
.and()
.formLogin()
// to show the page where we enter login credentials
.loginPage("/login-form")
// to process authentication: /login handler method implemented by Spring Security
.loginProcessingUrl("/login")
// where to go after successful login
.defaultSuccessUrl("/success-login",true) // the second parameter is for enforcing this url always
// to show an error page if the authentication failed
.failureUrl("/login-form")
// everyone can access these requests
.permitAll()
.and()
.logout()
//what do we do here? confused !?!?!?
// to logout
.invalidateHttpSession(true)
// with CSRF we need to map the POST request /logout
// if CSRF is disabled the GET request /logout is mapped by default
// to an internal Spring Security handler method
.logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
.logoutSuccessUrl("/login-form")
.permitAll()
// AUTHORIZATION
.and()
.authorizeRequests()
// .antMatchers("/product/**").hasRole("MANAGER")
// .antMatchers("/test/**").hasRole("CUSTOMER")
// .antMatchers("/test2/**").hasAnyRole("MANAGER","CUSTOMER")
.antMatchers("/system").hasRole("ADMIN")
.antMatchers("/system/").hasRole("ADMIN")
.antMatchers("/system/user").hasAnyRole("USER","PREMIUM")
.antMatchers("/system/user/**").hasAnyRole("USER","PREMIUM")
.antMatchers("/system/premium").hasRole("PREMIUM")
.antMatchers("/system/premium/**").hasRole("PREMIUM")
.antMatchers("/setDate/**").hasRole("ADMIN")
.antMatchers("/deal/").hasRole("ADMIN")
.antMatchers("/deal/add/**").hasRole("ADMIN")
.antMatchers("/deal/delete/**").hasRole("ADMIN")
.antMatchers("/product/").hasRole("ADMIN")
.antMatchers("/product/productDetail/**").hasRole("ADMIN")
.antMatchers("/product/add/**").hasRole("ADMIN")
.antMatchers("/product/delete/**").hasRole("ADMIN")
.antMatchers("/signup/").permitAll()
.antMatchers("/signup/add/**").permitAll()
.antMatchers("/order").hasAnyRole("USER","PREMIUM")
.antMatchers("/order/").hasAnyRole("USER","PREMIUM")
.antMatchers("/order/wishlist/**").hasRole("PREMIUM")
.anyRequest().authenticated() // all requests ABOVE this statement require authentication
.and()
// to redirect the user when trying to access a resource to which access is not granted
.exceptionHandling().accessDeniedPage("/access-denied");
}
}
<file_sep>// convert.cpp
// program to asks the user to input a temperature in Celsius
// and converts it to Fahrenheit
//
// Author: nt161
// Version: 1
#include <iostream> // use the standard IO library
#include <string> // use the standard string library
using namespace std;
int main () {
double input;
double answer;
cout << "Enter a number: " << endl;
cin >> input;
answer = (input*9/5) + 32;
cout << input << " Celsius is equal to " << answer << " Fahrenheit";
}
<file_sep>#include "disp7seg_update.h"
//initialising the display digit to 0
static uint8_t digit = '0';
//initialising the external variable which retains the frequency at which the digit changes
uint8_t update_frequency = 10;
//function initialising the seven segment display
void SevenSeg_Init(void)
{
led7seg_init();
//clearing the seven segment display
led7seg_setChar(' ', FALSE);
}
//function which controls the seven segment display
void SevenSeg_Update (void)
{
/*setting up a delay to ensure that the digit changes at the correct frequency, corresponding
to the external variable update_frequency*/
static int delay = 0 ;
//if the display digit is greater than 9 then the number on display starts to count from 0 again
if(digit > '9')
{
digit = '0';
}
/*if the delay is greater than or equal to the frequency, then the digit is incremented
and the delay is reset to 0*/
else if (delay >= update_frequency)
{
digit++;
delay = 0;
}
//if neither of the above conditions are satisfied then the delay is incremented
else
delay++;
//setting the digit to be displayed on the seven segment display
led7seg_setChar(digit, FALSE);
}
<file_sep>import serial, io
#import numpy
#import matplotlib.pyplot as plt
#from drawnow import *
from datetime import datetime
arduinoData = serial.Serial('COM3',9600)
outfile = 'data.txt'
sio=io.TextIOWrapper(io.BufferedRWPair(arduinoData,arduinoData,1),encoding='ascii',newline='\r')
with open(outfile,'w') as f:
while True: # while loop that loops forever
while (arduinoData.inWaiting()==0): #Wait here until there is data
pass #do nothing
arduinoString = sio.readline()
f.write(datetime.now(),isoformat() + '\t' + arduinoString + '\n')
f.flush()
<file_sep>typedef enum {NORMAL, SHOCK, CPR} State;
const int redPin = 13;//the number of the RED LED pin
const int grnPin = 12;//number of the GREEN LED pin
const int cprPin = 2;//pushbutton pin which starts SHOCK state and gives cpr
const int heartPin = 3;//pushbutton pin which starts CPR state
// include the library code:
#include <LiquidCrystal.h>
//initialize the library with the numbers of the interface pins
LiquidCrystal lcd(11, 10, 7, 6, 5, 4);
int cprState = 0; //variable for reading pushbutton status
int heartState = 0; //variable for reading pushbutton status
long heartRate;
int speakerPin = 9; //variable setting up the buzzer
long interval = 30000; //interval at which to give CPR
void setup(){
Serial.begin(9600);
//initialize the LED pins as an output:
pinMode(redPin, OUTPUT);
pinMode(grnPin, OUTPUT);
//initialize the pushbutton pins as an input:
pinMode(cprPin, INPUT);
pinMode(heartPin, INPUT);
//set up the LCD's number of columns and rows:
lcd.begin(16, 2);
//initialise the random number generator:
randomSeed(analogRead(A0));
//initialise the buzzer as an output:
pinMode(speakerPin, OUTPUT);
}
void loop(){
static State current_state = NORMAL;//Initiates current state as NORMAL
switch(current_state)
{
case NORMAL:
heartState = digitalRead(heartPin);
Serial.print("In NORMAL, heartState = ");
Serial.println(heartState);
if (heartState == HIGH)//checks if the heart is beating
{
digitalWrite(redPin, LOW);
digitalWrite(grnPin, HIGH);
lcd.setCursor(0,0);
lcd.print("Heartrate Normal");
// set the cursor to column 0, line 1
// (note: line 1 is the second row, since counting begins with 0):
lcd.setCursor(0, 1);
long randomNumheartRate = random(-5, 6);
heartRate = 80 + (randomNumheartRate + 2);//generates a random heart rate between 77 to 87
lcd.print(heartRate);//heart rate is printed on the lcd
lcd.print("bpm");
delay(1000);
break;
}
else //if heart has stopped, then goes into SHOCK mode
{
Serial.println("In NORMAL, going to SHOCK");
current_state = SHOCK;
}
break;
case SHOCK:
{
Serial.print("In SHOCK, heartState = ");
Serial.println(heartState);
digitalWrite(grnPin, LOW);
digitalWrite(redPin, HIGH);
lcd.setCursor(0,0);
lcd.print("Heart Stopped!!!");
lcd.setCursor(0,1);
lcd.print("Stand Clear!");
delay(2500);
lcd.clear();
for (int i=9; i>-1; i--)//counts down from 9 to 0 until 10 seconds pass
{
tone(9, 450, 100);
delay(1000);
lcd.setCursor(0,0);
lcd.print("Get ready...");
lcd.setCursor(0,1);
lcd.print(i);//number of seconds left is printed on the lcd
lcd.print(" seconds left");
}
tone(9, 625, 1000);//give an electric shock to the patient
lcd.clear();
lcd.setCursor(0,0);
lcd.print("Electric shock!!");
delay(1000);
heartState = digitalRead(heartPin);
if(heartState == LOW)//if this button is pressed then the system goes into CPR mode
{
Serial.println("In SHOCK, going into CPR");
current_state = CPR;
}
else //if button is not pressed then the heartbeat is normal and system goes to NORMAL mode
{
Serial.println("In SHOCK, going into NORMAL");
current_state = NORMAL;
}
}
break;
case CPR:
{
digitalWrite(grnPin, LOW);
digitalWrite(redPin, LOW);
lcd.clear();
lcd.print("Start CPR...");
long startTime = millis();//storing the time code reaches this line
while((millis() - startTime) <= interval)//deducting the start time from the current time (represented by the millis() function) and if it is less than 30 seconds the code in the while loop is executed
{
static int lastPressed = millis();
int timeDifference;
if (digitalRead(cprPin) == 0)
{
timeDifference = millis() - lastPressed;
lastPressed = millis();
if ((timeDifference > 500) && (timeDifference < 1000))
{
// If it is more than a second (but less than 2 seconds) since the last time the button was pressed, light the green LED
digitalWrite(grnPin, HIGH);
lcd.clear();
lcd.setCursor(0,0);
lcd.print(timeDifference); //prints onto lcd the rate at which the button is being pressed
lcd.print(" ms/press");
lcd.setCursor(0,1);
lcd.print("correct rate");
tone(9, 625, 200);
delay(200);
digitalWrite(grnPin, LOW);
}
else
{
// Less than a second since the switch was last pressed or more than 2 seconds, light the red LED
digitalWrite(redPin, HIGH);
if(timeDifference < 500){ //if it has been less than a second since the button has been pressed the following code is executed
lcd.clear();
lcd.setCursor(0,0);
lcd.print(timeDifference);//prints onto lcd the rate at which the button is being pressed
lcd.print(" ms/press");
lcd.setCursor(0,1);
lcd.print("Too fast!");
tone(9, 250, 200);//plays a tone for 200 milliseconds telling user that cpr is being done too fast as printed on the lcd in the previous line of code
delay(200);
digitalWrite(redPin, LOW);
}
if(timeDifference > 1000){ //if it has been more than 2 seconds since the button has been pressed the following code is executed
lcd.clear();
lcd.setCursor(0,0);
lcd.print(timeDifference);//prints onto lcd the rate at which the button is being pressed
lcd.print(" ms/press");
lcd.setCursor(0,1);
lcd.print("Too slow!");
tone(9, 250, 200);//plays a tone for 200 milliseconds telling user that cpr is being done too slow as printed on the lcd in the previous line of code
delay(200);
digitalWrite(redPin, LOW);
}
}
// Wait until the switch is released
while (digitalRead(cprPin) == 0) /* do nothing */ ;
// Small delay to debounce
delay(100);
}
}
lcd.clear();
lcd.print("Continue CPR?");
delay(3000);//gives the user some time to press the button to initiate SHOCK mode
heartState = digitalRead(heartPin);
if(heartState == LOW)
{
Serial.println("In CPR, going into SHOCK");
current_state = SHOCK;
}
else //if button is not pressed then the system goes into NORMAL mode and the heart is beating again
{
Serial.println("In CPR, going into NORMAL");
current_state = NORMAL;
}
}
break;
}
}
<file_sep>import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from biosppy.signals import ecg
import math
dataset = pd.read_csv("test_new_1500_points.csv") #Read data from CSV datafile
plt.title("Heart Rate Signal") #The title of our plot
plt.plot(dataset) #Draw the plot object
plt.show() #Display the plot
# process it and plot
signal = np.loadtxt('test_new.txt')
out = ecg.ecg(signal=signal, sampling_rate=100, show=True)<file_sep>//package eMarket;
//
//import javax.sql.DataSource;
//
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.context.annotation.Bean;
//import org.springframework.context.annotation.Configuration;
//import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
//import org.springframework.security.config.annotation.web.builders.HttpSecurity;
//import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
//import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
//import org.springframework.security.core.userdetails.UserDetailsService;
//import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
//import org.springframework.security.crypto.password.PasswordEncoder;
//
//@EnableWebSecurity
//@Configuration
//public class SecurityConfig extends WebSecurityConfigurerAdapter {
// @Autowired
// DataSource dataSource;
//
// @Bean
// public PasswordEncoder passwordEncoder(){
// PasswordEncoder encoder = new BCryptPasswordEncoder();
// return encoder;
// }
//
// @Autowired
// private UserDetailsService userDetailsService;
//
// @Autowired
// public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
// auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
// }
//
// protected void configure(HttpSecurity http) throws Exception {
// http
// .csrf().disable()
// // TODO: AUTHENTICATION AND AUTHORIZATION
// ;
// }
//
//}
// <file_sep># Makefile
# the C++ compiler
CXX = g++
CXXVERSION = $(shell g++ --version | grep ^g++ | sed 's/^.* //g')
# options to pass to the compiler
CXXFLAGS = -O0 -g3
ifeq "$(CXXVERSION)" "4.6.3"
CXXFLAGS += -std=c++0x
else
CXXFLAGS += -std=c++11
endif
All: all
all: main
main: Main.cpp Project.o Staff.o Student.o
$(CXX) $(CXXFLAGS) Main.cpp Project.o Staff.o Student.o -o main
Project.o: Project.cpp Project.h
$(CXX) $(CXXFLAGS) -c Project.cpp -o Project.o
Staff.o: Staff.cpp Staff.h
$(CXX) $(CXXFLAGS) -c Staff.cpp -o Staff.o
Student.o: Student.cpp Student.h
$(CXX) $(CXXFLAGS) -c Student.cpp -o Student.o
deepclean:
rm -f *~ *.o main *.exe *.stackdump main
clean:
-rm -f *~ *.o *.stackdump
<file_sep>/*
* serial_output.c
*
* Created on: 19 March 2018
* Author: nt161
*/
#include "serial_output.h"
// a character array which is used to display
// "strings" when using the sprintf function
// this is done because c does not have a string data type
char adc_string[100];
//initialises the serial output
void serial_output_init(){
USB_init();
VCOM_init();
USBHwConnect(TRUE);
}
void serial_output_update(){
// a variable which stores which "char" has been pressed on the keyboard
char readIn = VCOM_getchar();
// if the character '0' is pressed then the current value of the adc channel 0 is displayed
// as well as the average value
if (readIn == '0')
{
sprintf(adc_string, "ADC channel 0 Current Value: %f\n\r", adc_0_value);
VCOM_putstring2(adc_string);
sprintf(adc_string, "ADC channel 0 Average Value: %f\n\r", average_adc_0);
VCOM_putstring2(adc_string);
}
// if the character '1' is pressed then the current value of the adc channel 1 is displayed
// as well as the average value
if (readIn == '1')
{
sprintf(adc_string, "ADC channel 1 Current Value: %f\n\r", adc_1_value);
VCOM_putstring2(adc_string);
sprintf(adc_string, "ADC channel 1 Average Value: %f\n\r", average_adc_1);
VCOM_putstring2(adc_string);
}
// if the character '2' is pressed then the current value of adc channel 2 is displayed
// as well as the average value
if (readIn == '2')
{
sprintf(adc_string, "ADC channel 2 Current Value: %f\n\r", adc_2_value);
VCOM_putstring2(adc_string);
sprintf(adc_string, "ADC channel 2 Average Value %f\n\r", average_adc_2);
VCOM_putstring2(adc_string);
}
// if the rate of change of a channel is greater than 0.01 or less than -0.01
// then the value of the rate of change is displayed on the serial terminal
if((adc0_change_rate > 0.01) || (adc0_change_rate < -0.01))
{
sprintf(adc_string, "ADC channel 0 Rate Of Change: %f\n\r", adc0_change_rate);
VCOM_putstring2(adc_string);
}
else if ((adc1_change_rate > 0.01) || (adc1_change_rate < -0.01))
{
sprintf(adc_string, "ADC channel 1 Rate Of Change: %f\n\r", adc1_change_rate);
VCOM_putstring2(adc_string);
}
else if((adc2_change_rate > 0.01) || (adc2_change_rate < -0.01))
{
sprintf(adc_string, "ADC channel 2 Rate Of Change: %f\n\r", adc2_change_rate);
VCOM_putstring2(adc_string);
}
}
<file_sep>from tkinter import *
root = Tk()
label_1 = Label(root, text="Name")
label_2 = Label(root, text="Password")
entry_1 = Entry(root) #input from user
entry_2 = Entry(root)
#think of an excel sheet
label_1.grid(row=0, sticky=E) #by default column is equal to 0 #E means EAST so place to right, i.e right align
label_2.grid(row=1, sticky=E)
entry_1.grid(row=0, column=1)
entry_2.grid(row=1, column=1)
c = Checkbutton(root, text="Keep Me Logged In")
c.grid(columnspan=2)
root.mainloop()<file_sep>#! /bin/bash
echo "$USER files changed under 48 hours ago in $1"
find $1 -maxdepth 1 -mtime -2 -type d
find $1 -maxdepth 1 -mtime -2 -type f
echo "directories not owned by $USER"
find $1 -maxdepth 1 ! -user $USER -type d
echo "executable files not owned by $USER"
find $1 -executable ! -user $USER -type f<file_sep>package eMarket.department;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
@Entity(name="Department")
public class Department {
@Id
@Column(name="dept_code", nullable=false)
private String code;
@Column(name="dept_name", nullable=false)
private String name;
@OneToMany(fetch=FetchType.LAZY, cascade=CascadeType.ALL, orphanRemoval=true)
@JoinColumn(name="module_dept", referencedColumnName="dept_code")
private List<Module> moduleList = new ArrayList<>();
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Module> getModuleList() {
return moduleList;
}
public void setModuleList(List<Module> moduleList) {
this.moduleList = moduleList;
}
}<file_sep>
arr = []
inp = open ("test.txt","r")
#read line into array
for line in inp.readlines():
# loop over the elemets, split by whitespace
for i in line.split():
# convert to integer and append to the list
arr.append(int(i))
print(arr)
<file_sep>/*------------------------------------------------------------------*-
2_50_XXg.C (v1.00)
------------------------------------------------------------------
*** THIS IS A SCHEDULER FOR A NIOS II PROCESSOR ***
*** Uses a full-featured interval timer peripheral ***
*** 50 MHz clock -> 50 ms (precise) tick interval ***
COPYRIGHT
---------
This code is from the book:
PATTERNS FOR TIME-TRIGGERED EMBEDDED SYSTEMS by <NAME>
[Pearson Education, 2001; ISBN: 0-201-33138-1].
This code is copyright (c) 2001 by <NAME>.
See book for copyright details and other information.
-*------------------------------------------------------------------*/
#include "2_50_XXg.h"
#include "Sch51.h"
#include <sys/alt_irq.h>
#include <altera_avalon_timer_regs.h>
#include "PORT.h"
#include "./port.h"
#include "system.h"
#include "altera_avalon_pio_regs.h"
// ------ Public variable declarations -----------------------------
// The array of tasks (see Sch51.C)
extern sTask SCH_tasks_G[SCH_MAX_TASKS];
// Used to display the error code
// See Main.H for details of error codes
// See Port.H for details of the error port
extern tByte Error_code_G;
static void SCH_Update(void *);
/*------------------------------------------------------------------*-
SCH_Init_T2()
Scheduler initialisation function. Prepares scheduler
data structures and sets up timer interrupts at required rate.
You must call this function before using the scheduler.
-*------------------------------------------------------------------*/
void SCH_Init_T0(void)
{
tByte i;
for (i = 0; i < SCH_MAX_TASKS; i++)
{
SCH_Delete_Task(i);
}
// Reset the global error variable
// - SCH_Delete_Task() will generate an error code,
// (because the task array is empty)
Error_code_G = 0;
// Now set up the interval timer
// The required overflow is 0.050 seconds (50 ms)
// IOWR_ALTERA_AVALON_TIMER_PERIODH(TIMER_0_BASE, (((50 * (TIMER_0_FREQ) / 1000) - 1) >> 16) & 0xFFFF);
//IOWR_ALTERA_AVALON_TIMER_PERIODL(TIMER_0_BASE, ( (50 * (TIMER_0_FREQ) / 1000) - 1) & 0xFFFF);
IOWR_ALTERA_AVALON_TIMER_PERIODH(TIMER_0_BASE, (alt_u16) (((50000 - 1) >> 16) & 0xFFFF)); //for 1 ms
IOWR_ALTERA_AVALON_TIMER_PERIODL(TIMER_0_BASE, (alt_u16) ((50000 - 1) & 0xFFFF));
IOWR_ALTERA_AVALON_TIMER_CONTROL(TIMER_0_BASE,
(0x1 << ALTERA_AVALON_TIMER_CONTROL_START_OFST) | // Start
(0x1 << ALTERA_AVALON_TIMER_CONTROL_CONT_OFST ) | // Continuous
(0x1 << ALTERA_AVALON_TIMER_CONTROL_ITO_OFST )); // Generate interrupts
alt_ic_isr_register(0, TIMER_0_IRQ, SCH_Update, 0, 0);
}
/*------------------------------------------------------------------*-
SCH_Start()
Starts the scheduler, by enabling interrupts.
NOTE: Usually called after all regular tasks are added,
to keep the tasks synchronised.
NOTE: ONLY THE SCHEDULER INTERRUPT SHOULD BE ENABLED!!!
-*------------------------------------------------------------------*/
void SCH_Start(void)
{
alt_irq_cpu_enable_interrupts();
}
/*------------------------------------------------------------------*-
SCH_Update
This is the scheduler ISR. It is called at a rate
determined by the timer settings in SCH_Init().
This version is triggered by the interval timer interrupts:
the timer is automatically reloaded.
-*------------------------------------------------------------------*/
void SCH_Update(void * context)
{
tByte Index;
IOWR_ALTERA_AVALON_TIMER_STATUS(TIMER_0_BASE,
IORD_ALTERA_AVALON_TIMER_STATUS(TIMER_0_BASE) &
~ALTERA_AVALON_TIMER_STATUS_TO_MSK); // Clear TO (timeout)
// NOTE: calculations are in *TICKS* (not milliseconds)
for (Index = 0; Index < SCH_MAX_TASKS; Index++)
{
// Check if there is a task at this location
if (SCH_tasks_G[Index].pTask)
{
if (SCH_tasks_G[Index].Delay == 0)
{
// The task is due to run
SCH_tasks_G[Index].RunMe = 1; // Set the run flag
if (SCH_tasks_G[Index].Period)
{
// Schedule periodic tasks to run again
SCH_tasks_G[Index].Delay = SCH_tasks_G[Index].Period;
}
}
else
{
// Not yet ready to run: just decrement the delay
SCH_tasks_G[Index].Delay -= 1;
}
}
}
}
/*------------------------------------------------------------------*-
---- END OF FILE -------------------------------------------------
-*------------------------------------------------------------------*/
<file_sep>import matplotlib.pyplot as plt
from scipy import signal
from scipy.fftpack import fft
import numpy as np
import heartpy as hp
#I've already done this part!
# filename = 'filtered_signal_order6_wn_0.5.txt'
# with open(filename, mode="w") as outfile:
# for s in output_signal:
# outfile.write("%s\n" % s)
#this code is not needed anymore because we can use floats and we don't need to make an integer array
#this makes the bmp have an incorrect value
# fil_sig = []
# inp = open ("filtered_signal_order6_wn_0.5.txt","r")
# #read line into array
# for line in inp.readlines():
# # loop over the elements, split by a full stop
# for i in line.split("."):
# # convert to integer and append to the list
# fil_sig.append(int(i))
#taking every other element and putting it into a filtered signal array, this is an integer array so the bmp can be found
#again not needed
# print(fil_sig)
# fil_sig = fil_sig[0::2]
# print(fil_sig)
# new_int_arr = np.array(fil_sig)
# np.asarray(new_int_arr, dtype=int)
# print(new_int_arr)
def text_file_to_array(filename):
arr = []
inp = open(filename, "r")
#read line into array
for line in inp.readlines():
# loop over the elements, split by whitespace
for i in line.split():
# convert to integer and append to the list
arr.append(int(i))
return arr
dataset = text_file_to_array("test_new.txt")
def butterworth_filter(orig_sig):
b, a = signal.butter(6, 0.5, 'low')
output_signal = signal.filtfilt(b, a, orig_sig)
return output_signal
def plot_orig_filtered(orig_sig, filtered):
plt.plot(orig_sig, label='original')
plt.plot(filtered, label='filtered')
plt.legend()
return plt.show()
def bpm_from_peaks(freq, sig, threshold):
beat_count = 0
for i in range(1, len(sig) - 2):
if sig[i] > sig[i - 1] and sig[i] > sig[i + 1] and sig[i] > threshold:
beat_count = beat_count + 1
fs = freq
n = len(sig)
duration_in_seconds = n/fs
duration_in_minutes = duration_in_seconds/60
bmp = beat_count/duration_in_minutes
return round(bmp)
# filtered_sig = butterworth_filter(dataset)
# plt.plot(dataset)
# plt.show()
# plot_orig_filtered(dataset, filtered_sig)
# print("bpm =", bpm_from_peaks(100, filtered_sig, 530))
#hemal_sig = text_file_to_array("ecg_hemal.txt")
#plt.plot(hemal_sig)
#plt.show()
#print("bpm =", bpm_from_peaks(1000, hemal_sig, 2660))
testdata = text_file_to_array("physionet1.txt")
print(testdata)
print("bpm =", bpm_from_peaks(720, testdata, 2110))
# org_fft = np.fft.fft(np.array(filtered_sig).flatten())
# freq = np.fft.fftfreq(filtered_sig.size, 1/100.)
# f1 = plt.figure()
# A1 = f1.add_subplot(211)
# A1.plot(freq, np.abs(org_fft))
# plt.show()
# N = 1639
# T = 100
# x = np.linspace(0, N*T, N)
# y = np.array(filtered_sig)
# padded = np.pad(y, 1650, 'constant')
# yf = fft(y)
#
# #however if I do yf = fft(fft(y)) the fourier transform looks correct but I don't understand exactly why that is the case
#
# #yf = np.fft.rfft(y, 1650)
#
# xf = np.linspace(0.0, 1.0/(2.0*T), N)
#
# plt.plot(xf, abs(yf))
# plt.grid()
# plt.show()
data = hp.get_data('test_new_filtered.csv') #data.csv is sampled at 100Hz
working_data, measures = hp.process(data, 100.0, report_time=True)
hp.plotter(working_data, measures)
print('bmp = ', measures['bpm'])
print('standard deviation = ', measures['sdsd'])
print('rms of sd = ', measures['rmssd'])
# physionet data is not working
# physionet = hp.get_data('physionet1.csv') #data.csv is sampled at 720Hz
# working_data, measures = hp.process(physionet, 720.0, report_time=True)
# hp.plotter(working_data, measures)
# print('bmp = ', measures['bpm'])
# print('standard deviation = ', measures['sdsd'])
# print('rms of sd = ', measures['rmssd'])
#hemal's data gives wrong values
# hemal_ecg = hp.get_data('hemal_ecg.csv') #data.csv is sampled at 1000Hz
# working_data, measures = hp.process(hemal_ecg, 1000.0, report_time=True)
# hp.plotter(working_data, measures)
# print('bmp = ', measures['bpm'])
# print('standard deviation = ', measures['sdsd'])
# print('rms of sd = ', measures['rmssd'])
<file_sep># Makefile
# the C++ compiler
CXX = g++
CC = $(CXX)
# options to pass to the compiler
CXXFLAGS = -Wall -ansi -O2 -g
namedWelcome : namedWelcome.o
$(CXX) $(CXXFLAGS) -o namedWelcome namedWelcome.o
namedWelcome.o : namedWelcome.cpp
$(CXX) $(CXXFLAGS) -c namedWelcome.cpp
.PHONY : clean
clean :
$(RM) namedWelcome namedWelcome.o *~
<file_sep>package eMarket;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import eMarket.domain.Deal;
import eMarket.domain.Product;
import eMarket.domain.Store;
@SpringBootApplication
public class EMarketApp extends WebMvcConfigurerAdapter implements CommandLineRunner {
private static Store store = new Store();
public static Store getStore() {
return store;
}
private static LocalDate systemDate;
public static LocalDate getSystemDate() {
return systemDate;
}
public static void setSystemDate(LocalDate systemDate) {
EMarketApp.systemDate = systemDate;
}
public static void main(String[] args) {
SpringApplication.run(EMarketApp.class, args);
}
public void run(String... args) {
// initialize calendar
Calendar calendar = Calendar.getInstance();
calendar.setTimeZone(TimeZone.getTimeZone("GMT"));
systemDate = calendar.getTime().toInstant().atZone(ZoneId.of("GMT")).toLocalDate();
// PRODUCTS
Product banana = new Product(0,"Banana","yellow",0.16);
EMarketApp.getStore().getProductList().add(banana);
Product orange = new Product(1,"Orange","Valencian",0.20);
EMarketApp.getStore().getProductList().add(orange);
EMarketApp.getStore().getProductList().add(new Product(2,"Apple","Royal Gala",0.25));
Product.lastId = 3;
// DEALS
// bananas
SimpleDateFormat isoFormat = new SimpleDateFormat("dd/MM/yyyy");
isoFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
String startDate = "02/08/2017";
try {
LocalDate newDate = isoFormat.parse(startDate).toInstant().atZone(ZoneId.of("GMT")).toLocalDate();
Deal deal = new Deal(0,newDate,0.10,banana);
deal.close();
EMarketApp.getStore().getDealList().add(deal);
} catch (ParseException e) {
e.printStackTrace();
}
// oranges
LocalDate today = getSystemDate();
Deal deal = new Deal(1,today,0.20,orange);
deal.close();
EMarketApp.getStore().getDealList().add(deal);
Deal.lastId = 2;
}
}
<file_sep>#include "Student.h"
Student::Student(const string& studentInfo)
{
istringstream studentStream(studentInfo);
studentStream >> stud_id;
studentStream >> first;
studentStream >> second;
studentStream >> third;
studentStream >> fourth;
}
Student::~Student() {
}
string Student::getStudID() const {
return stud_id;
}
int Student::getFirstChoice() const {
return first;
}
int Student::getSecondChoice() const {
return second;
}
int Student::getThirdChoice() const {
return third;
}
int Student::getFourthChoice() const {
return fourth;
}
<file_sep>/*
* led_bank.c
*
* Created on: 18 March 2018
* Author: nt161
*/
#include "led_bank.h"
// initialising the pca9532 LEDs
void led_bank_init (void)
{
PINSEL_CFG_Type PinCfg;
/* Initialize I2C2 pin connect */
PinCfg.Funcnum = 2;
PinCfg.Pinnum = 10;
PinCfg.Portnum = 0;
PINSEL_ConfigPin(&PinCfg);
PinCfg.Pinnum = 11;
PINSEL_ConfigPin(&PinCfg);
// Initialize I2C peripheral
I2C_Init(LPC_I2C2, 100000);
/* Enable I2C1 operation */
I2C_Cmd(LPC_I2C2, ENABLE);
pca9532_init();
}
// displays the channel value as a scaled value on the 16 pca9532 LEDs
// using bit shifting and masking
void led_display_adc_general(uint32_t value)
{
uint16_t display_value = 0xFFFF >> (uint32_t) ((float) value / (float) 0x0FFF * 16);
pca9532_setLeds(~display_value, display_value);
}
// this function is called from the main and is used to display the value of ADC channel 0
// on the pca9532 LEDs
void led_display_adc_0_average (void)
{
led_display_adc_general(average_adc_0);
}
<file_sep>package eMarket.controller;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
import eMarket.EMarketApp;
import eMarket.domain.Deal;
import eMarket.repository.DealRepository;
public class DealValidator implements Validator {
DealRepository dealRepo;
public DealValidator(DealRepository dealRepository) {
this.dealRepo = dealRepository;
}
public boolean supports(Class<?> clazz) {
return DealFormDto.class.equals(clazz);
}
@Override
public void validate(Object target, Errors errors) {
DealFormDto dto = (DealFormDto) target;
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "startDate", "", "Field cannot be empty.");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "discount", "", "Field cannot be empty.");
if (dto.getProductId() < 0) {
errors.rejectValue("productId", "", "No product selected.");
}
if (dto.getDiscount() == 0.0) {
errors.rejectValue("discount", "", "Discount has to be different from 0.0.");
}
if (dto.getStartDate() == null) {
errors.rejectValue("startDate", "", "Field cannot be empty.");
}
if ((dto.getStartDate() != null)) {
if ((dto.getEndDate() == null)) {
// OPEN - OPEN
Stream<Deal> deals =
EMarketApp.getStore().getDealList().stream().filter(d -> (((Deal) d).getProduct().getId() == dto.getProductId()));
List<Object> elements = Arrays.asList(deals.filter(d -> d.getEndDate() == null).toArray());
if (elements.size() > 0) {
errors.rejectValue("startDate", "", "Dates overlap with another deal.");
}
// OPEN - CLOSED
deals =
EMarketApp.getStore().getDealList().stream().filter(d -> (((Deal) d).getProduct().getId() == dto.getProductId()));
elements = Arrays.asList(deals.filter(d -> d.getEndDate() != null).filter(d ->
dto.getStartDate().compareTo(d.getEndDate()) <= 0
).toArray());
if (elements.size() > 0) {
errors.rejectValue("startDate", "", "Dates overlap with another deal.");
}
} else {
if (dto.getEndDate().isBefore(dto.getStartDate())) {
errors.rejectValue("endDate", "", "End date is anterior to start date.");
}
// CLOSED - OPEN
// deals with an end date
Stream<Deal> deals =
EMarketApp.getStore().getDealList().stream().filter(d -> (((Deal) d).getProduct().getId() == dto.getProductId()));
List<Object> elements = Arrays.asList(deals.filter(d -> d.getEndDate() == null).filter(d ->
dto.getEndDate().compareTo(d.getStartDate()) >= 0
).toArray());
if (elements.size() > 0) {
errors.rejectValue("endDate", "", "Dates overlap with another deal." + ((Deal) elements.get(0)).getStartDateAsString() + " - endDate: " + ((Deal) elements.get(0)).getEndDateAsString());
}
// CLOSED - CLOSED
deals =
EMarketApp.getStore().getDealList().stream().filter(d -> (((Deal) d).getProduct().getId() == dto.getProductId()));
elements = Arrays.asList(deals.filter(d -> d.getEndDate() != null).filter(d ->
(dto.getStartDate().compareTo(d.getStartDate()) >= 0
&&
dto.getStartDate().compareTo(d.getEndDate()) <= 0)
||
(dto.getStartDate().compareTo(d.getStartDate()) <= 0
&&
dto.getEndDate().compareTo(d.getEndDate()) >= 0)
).toArray());
if (elements.size() > 0) {
errors.rejectValue("startDate", "", "Dates overlap with another deal - startDate: " + ((Deal) elements.get(0)).getStartDateAsString() + " - endDate: " + ((Deal) elements.get(0)).getEndDateAsString());
errors.rejectValue("endDate", "", "Dates overlap with another deal." + ((Deal) elements.get(0)).getStartDateAsString() + " - endDate: " + ((Deal) elements.get(0)).getEndDateAsString());
}
deals =
EMarketApp.getStore().getDealList().stream().filter(d -> (((Deal) d).getProduct().getId() == dto.getProductId()));
elements = Arrays.asList(deals.filter(d -> d.getEndDate() != null).filter(d ->
dto.getEndDate().compareTo(d.getEndDate()) <= 0
&&
dto.getEndDate().compareTo(d.getStartDate()) >= 0
).toArray());
if (elements.size() > 0) {
errors.rejectValue("startDate", "", "Dates overlap with another deal." + ((Deal) elements.get(0)).getStartDateAsString() + " - endDate: " + ((Deal) elements.get(0)).getEndDateAsString());
errors.rejectValue("endDate", "", "Dates overlap with another deal." + ((Deal) elements.get(0)).getStartDateAsString() + " - endDate: " + ((Deal) elements.get(0)).getEndDateAsString());
}
}
}
}
}
<file_sep>################################################################################
# Automatically-generated file. Do not edit!
################################################################################
-include ../makefile.init
RM := rm -rf
# All of the sources participating in the build are defined here
-include sources.mk
-include src/tasks/subdir.mk
-include src/system/subdir.mk
-include src/scheduler/subdir.mk
-include src/main/subdir.mk
-include subdir.mk
-include objects.mk
ifneq ($(MAKECMDGOALS),clean)
ifneq ($(strip $(C_DEPS)),)
-include $(C_DEPS)
endif
endif
-include ../makefile.defs
# Add inputs and outputs from these tool invocations to the build variables
# All Target
all: scheduler_assignment2.axf
# Tool invocations
scheduler_assignment2.axf: $(OBJS) $(USER_OBJS)
@echo 'Building target: $@'
@echo 'Invoking: MCU Linker'
arm-none-eabi-gcc -nostdlib -L"C:\Users\NTarannum\Documents\LPCXpresso_8.2.2_650\workspace\EG2204_Assignment2_Final\Lib_CMSISv1p30_LPC17xx\Debug" -L"C:\Users\NTarannum\Documents\LPCXpresso_8.2.2_650\workspace\EG2204_Assignment2_Final\Lib_EaBaseBoard\Debug" -L"C:\Users\NTarannum\Documents\LPCXpresso_8.2.2_650\workspace\EG2204_Assignment2_Final\Lib_MCU\Debug" -Xlinker --gc-sections -Xlinker -Map=scheduler_assignment2.map -mcpu=cortex-m3 -mthumb -T "scheduler_assignment2_Debug.ld" -o "scheduler_assignment2.axf" $(OBJS) $(USER_OBJS) $(LIBS)
@echo 'Finished building target: $@'
@echo ' '
$(MAKE) --no-print-directory post-build
# Other Targets
clean:
-$(RM) $(EXECUTABLES)$(OBJS)$(C_DEPS) scheduler_assignment2.axf
-@echo ' '
post-build:
-@echo 'Performing post-build steps'
-arm-none-eabi-size scheduler_assignment2.axf; # arm-none-eabi-objdump -h -S scheduler_assignment2.axf >scheduler_assignment2.lss
-@echo ' '
.PHONY: all clean dependents
.SECONDARY: post-build
-include ../makefile.targets
<file_sep>/*------------------------------------------------------------------*-
Main.H (v1.00)
------------------------------------------------------------------
'Project Header' (see Chap 9) for project S_Delay (see Chap 11)
COPYRIGHT
---------
This code is from the book:
PATTERNS FOR TIME-TRIGGERED EMBEDDED SYSTEMS by <NAME>
[Pearson Education, 2001; ISBN: 0-201-33138-1].
This code is copyright (c) 2001 by <NAME>.
See book for copyright details and other information.
-*------------------------------------------------------------------*/
#ifndef _MAIN_H
#define _MAIN_H
#include <system.h>
//------------------------------------------------------------------
// SHOULD NOT NEED TO EDIT THE SECTIONS BELOW
//------------------------------------------------------------------
typedef unsigned char tByte;
typedef unsigned int tWord;
typedef unsigned long tLong;
// Misc #defines
#ifndef TRUE
#define FALSE 0
#define TRUE (!FALSE)
#endif
#define RETURN_NORMAL 0
#define RETURN_ERROR 1
//------------------------------------------------------------------
// Error codes
// - see Chapter 14.
//------------------------------------------------------------------
#define ERROR_SCH_TOO_MANY_TASKS (1)
#define ERROR_SCH_CANNOT_DELETE_TASK (2)
#define ERROR_SCH_WAITING_FOR_SLAVE_TO_ACK (3)
#define ERROR_SCH_WAITING_FOR_START_COMMAND_FROM_MASTER (3)
#define ERROR_SCH_ONE_OR_MORE_SLAVES_DID_NOT_START (4)
#define ERROR_SCH_LOST_SLAVE (5)
#define ERROR_SCH_CAN_BUS_ERROR (6)
#define ERROR_I2C_WRITE_BYTE (10)
#define ERROR_I2C_READ_BYTE (11)
#define ERROR_I2C_WRITE_BYTE_AT24C64 (12)
#define ERROR_I2C_READ_BYTE_AT24C64 (13)
#define ERROR_I2C_DS1621 (14)
#define ERROR_USART_TI (21)
#define ERROR_USART_WRITE_CHAR (22)
#define ERROR_SPI_EXCHANGE_BYTES_TIMEOUT (31)
#define ERROR_SPI_X25_TIMEOUT (32)
#define ERROR_SPI_MAX1110_TIMEOUT (33)
#define ERROR_ADC_MAX150_TIMEOUT (44)
#endif
/*------------------------------------------------------------------*-
---- END OF FILE -------------------------------------------------
-*------------------------------------------------------------------*/
<file_sep>
#include <altera_avalon_pio_regs.h>
#include "system.h"
#include "../TTC_Scheduler/2_50_XXg.h"
#include "spi_mcp2515.h"
#include "../TTC_Scheduler/Main.h"
#include "../TTC_Scheduler/Port.h"
#include "alt_spi_master.h"
#include "altera_avalon_spi.h"
alt_u8 write_data[50],read_data[50];
void MCP2515_Init(void)
{
/* Snd reset instruction */
MCP2515_Reset();
/* Set Configuration Mode */
MCP2515_SetMode(_CANSPI_MODE_CONFIG);
/* set bit timing, masks, and rollover mode */
MCP2515_SetBitTiming(0x01,0xB5,0x01);
// We *don't* use Buffer 0 here.
// We therefore set it to receive CAN messages, as follows:
// - with Standard IDs.
// - matching the filter settings.
// [As all our messages have Extended IDs, this won't happen...]
MCP2515_Write_Register(RXB0CTRL, 0x20); //0x02====== NO need to use it! It might be 0x20
// --- Now set up masks and filters (BEGIN) ---
// Buffer 0 mask
// (all 1s - so filter must match every bit)
// [Standard IDs]
MCP2515_Write_Register(RXM0SIDH, 0xFF);
MCP2515_Write_Register(RXM0SIDL, 0xE0);
// Buffer 0 filters
// (all 1s, and Standard messages only)
MCP2515_Write_Register(RXF0SIDH, 0xFF);
MCP2515_Write_Register(RXF0SIDL, 0xE0);
MCP2515_Write_Register(RXF1SIDH, 0xFF);
MCP2515_Write_Register(RXF1SIDL, 0xE0);
// We set up MCP2510 Buffer 1 to receive Ack messages, as follows:
// - with Extended IDs.
// - matching the filter settings (see below)
MCP2515_Write_Register(RXB1CTRL, 0x40); //0x04====== NO need to use it! It might be 0x40
// Buffer 1 mask
// (all 1s - so filter must match every bit)
// [Extended IDs]
MCP2515_Write_Register(RXM1SIDH, 0xFF);
MCP2515_Write_Register(RXM1SIDL, 0xE3);
MCP2515_Write_Register(RXM1EID8, 0xFF);
MCP2515_Write_Register(RXM1EID0, 0xFF);
// Buffer 1 filters
// (only accept Ack messages - with Extended ID 0x000000FF)
// We set *ALL* relevant filters (2 - 5) to match this message
MCP2515_Write_Register(RXF2SIDH, 0x00);
MCP2515_Write_Register(RXF2SIDL, 0x08); // EXIDE bit
MCP2515_Write_Register(RXF2EID8, 0x00);
MCP2515_Write_Register(RXF2EID0, 0xFF);
MCP2515_Write_Register(RXF3SIDH, 0x00);
MCP2515_Write_Register(RXF3SIDL, 0x08); // EXIDE bit
MCP2515_Write_Register(RXF3EID8, 0x00);
MCP2515_Write_Register(RXF3EID0, 0xFF);
MCP2515_Write_Register(RXF4SIDH, 0x00);
MCP2515_Write_Register(RXF4SIDL, 0x08); // EXIDE bit
MCP2515_Write_Register(RXF4EID8, 0x00);
MCP2515_Write_Register(RXF4EID0, 0xFF);
MCP2515_Write_Register(RXF5SIDH, 0x00);
MCP2515_Write_Register(RXF5SIDL, 0x08); // EXIDE bit
MCP2515_Write_Register(RXF5EID8, 0x00);
MCP2515_Write_Register(RXF5EID0, 0xFF);
// --- Now set up masks and filters (END) ---
MCP2515_Write_Register(CANCTRL, _CANSPI_MODE_NORMAL);
// NO interrupts required
MCP2515_Write_Register(CANINTE, 0x00);
// Prepare 'Tick' message...
// EXTENDED IDs used here
// (ID 0x00000000 used for Tick messages - matches PTTES)
MCP2515_Write_Register(TXB0SIDH, 0x00);
MCP2515_Write_Register(TXB0SIDL, 0x08); // EXIDE bit
MCP2515_Write_Register(TXB0EID8, 0x00);
MCP2515_Write_Register(TXB0EID0, 0x00);
// Number of data bytes
MCP2515_Write_Register(TXB0DLC, 0x02);
/* Set Normal Mode */
MCP2515_SetMode(_CANSPI_MODE_NORMAL);
}
/*-------------MCP2515_SetBitTiming---------------------------
* This function setup the baud rate for the SPI-CAN module.
* Input = rCNF1, mask for configuration register 1
* Input = rCNF2, mask for configuration register 2
* Inout = rCNF3, mask for configuration register 3
* --------------------------------------------------------*/
unsigned char MCP2515_SetBitTiming(unsigned char rCNF1, unsigned char rCNF2, unsigned char rCNF3)
{
//https://www.kvaser.com/support/calculators/bit-timing-calculator/
// Configure to 250kbps (in case of 16 MHz CAN controller clock).
MCP2515_Write_Register(CNF1, rCNF1);
MCP2515_Write_Register(CNF2, rCNF2);
MCP2515_Write_Register(CNF3, rCNF3);
return 0;
}
/*-------------MCP2515_changeBits---------------------------
* This function changes particular bits in the
* specified register
* Input = reg_address
* Input = mask
* Inout = specify value
* --------------------------------------------------------*/
void MCP2515_changeBits(unsigned char reg_address,unsigned char change_bits, unsigned char change_val)
{
unsigned char reg_val, temp;
temp=change_bits & change_val;
reg_val=MCP2515_Read_Register(reg_address);
reg_val=reg_val & 0x1F;
temp=temp|reg_val;
MCP2515_Write_Register(reg_address,temp);
}
/*-------------MCP2515_Reset---------------------------
* This function reset SPI-CAN module.
* Input = void
* output = void
* --------------------------------------------------------*/
void MCP2515_Reset()
{
write_data[0]= RESET_INSTRUCTION;
/* Send Reset Instruction */
alt_avalon_spi_command((alt_u32)ALT_SPI_MASTER,
0,1, write_data,0,
read_data,0);
}
/*-------------MCP2515_SetMode---------------------------
* This function set the mode of the MCP2515. The following
modes are possible.
* _CANSPI_MODE_NORMAL 0x00
_CANSPI_MODE_SLEEP 0x20
_CANSPI_MODE_LOOP 0x40
_CANSPI_MODE_LISTEN 0x60
_CANSPI_MODE_CONFIG 0x80
* Input = mode
* Output =void
* --------------------------------------------------------*/
void MCP2515_SetMode(unsigned char mode)
{
MCP2515_changeBits(CANCTRL, (7 << REQOP0),(mode));
while(getMode != (mode>>REQOP0));
}
/*-------------MCP2515_Read_Register----------------------
* Send reset instruction to the MCP2515. Device should
* reinitialize yourself and go to the configuration mode
* Input = Read Register address
* Output = content of the register
* --------------------------------------------------------*/
tByte MCP2515_Read_Register(const tByte Register_address)
{
tByte Register_contents;
/* Read Instruction */
write_data[0]=READ_INSTRUCTION;
write_data[1]=Register_address;
alt_avalon_spi_command((alt_u32)ALT_SPI_MASTER,
0,2, write_data,1,
read_data,0);
Register_contents=read_data[0];
return Register_contents;
}
/*-------------MCP2515_Read_Rx_Buffer_Register-------------
* Input = instruction
* Output = content of the receive buffer register
* --------------------------------------------------------*/
tByte MCP2515_Read_Rx_Buffer_Register(const tByte instruction)
{
tByte Register_contents;
/* Read Receive Buffer Instruction */
write_data[0]=instruction;
alt_avalon_spi_command((alt_u32)ALT_SPI_MASTER,
0,1, write_data,1,
read_data,0);
Register_contents=read_data[0];
return Register_contents;
}
/*-------------MCP2515_Write_Register-----------------------
* Input = Write Register address
* Input = Write Register contents
* Output= void-------------------------------------------*/
void MCP2515_Write_Register(const tByte Register_address,
const tByte Register_contents)
{
/* Read Receive Buffer Instruction */
write_data[0]=WRITE_BYTE_INSTRUCTION;
write_data[1]=Register_address;
write_data[2]=Register_contents;
alt_avalon_spi_command((alt_u32)ALT_SPI_MASTER,
0,3, write_data,0,
read_data,0);
}
/*-------------MCP2515_RTS_TXB_Instruction_CMD-----------------------
* This function sends request for the transmission of data through
* SPI-CAN module.
* Input = tx_buffer_to_send, Transmit Buffer to send
* Output= void-------------------------------------------*/
void MCP2515_RTS_TXB_Instruction_CMD(const unsigned char tx_buffer)
{
/* RTS Transmit Buffer Instruction */
write_data[0]=tx_buffer;
alt_avalon_spi_command((alt_u32)ALT_SPI_MASTER,
0,1, write_data,0,
read_data,0);
}
/*--------------------------------------------------------*/
<file_sep>/*
* joystick_controller.h
*
* Created on: 16 Feb 2018
* Author: nt161
*/
#ifndef JOYSTICK_CONTROLLER_HEADER
#define JOYSTICK_CONTROLLER_HEADER
#include "lpc_types.h"
#include "rgb.h"
#include "joystick.h"
#include "pca9532.h"
extern uint8_t mode;
void joystick_controller_init(void);
void joystick_controller_update(void);
#endif /* JOYSTICK_CONTROLLER_HEADER_ */
<file_sep>package eMarket.repository;
import org.springframework.data.repository.CrudRepository;
import eMarket.domain.Role;
public interface RoleRepository extends CrudRepository<Role, Integer> {
public Role findById(Integer id);
}
<file_sep>// check.cpp
// program to asks the user to input a number between 0 and 100
// In the case the number is too low it outputs "Your number is below 0"
// In the case the number is too high it outputs "Your number is above 100"
// Otherwise it outputs "<number> is in range"
//
// Author: nt161
// Version: 1
#include <iostream> // use the standard IO library
#include <string> // use the standard string library
using namespace std;
int main () {
int input;
cout << "Enter a number: " << endl;
cin >> input;
if (input < 0)
{
cout << "Your number is below 0" << endl;
}
else if (input > 100)
{
cout << "Your number is above 100" << endl;
}
else
cout << input << " is in range" << endl;
return 0;
}
<file_sep>#include "rgb_update.h"
//variable which corresponds to the state of the LED i.e. the current colour
static uint8_t state = 0x00;
//initialising the external variable of the red duty cycle
uint8_t red_DC = 5;
//initialising the external variable of the green duty cycle
uint8_t green_DC = 5;
//initialising the variable which corresponds to the state of the blue LED
uint8_t blue_state = 0;
//initialising the RGB LED and turning it off
void RGB_Init(void)
{
rgb_init();
rgb_setLeds(state);
}
//function which turns on the LED corresponding to the colour inserted in the parameters
void On_Colour (uint8_t colour)
{
state |= colour;
rgb_setLeds(state);
}
//function which turns off the LED corresponding to the colour inserted in the parameters
void Off_Colour (uint8_t colour)
{
state &= ~colour;
rgb_setLeds(state);
}
//function which controls the RED LED according to its duty cycle
void Update_Red(void)
{
/*setting up a counter to ensure that the red LED turns on/off according to its duty cycle
this works like a delay*/
static uint8_t red_counter = 0;
/*if the counter is equal to 0 and the duty cycle is not equal to 0%
the the RED LED is turned on*/
if((red_counter == 0) && (red_DC != 0))
{
On_Colour(RGB_RED);
}
/*if the counter is equal to the duty cycle and the duty cycle is not equal to 100%
the the RED LED is turned off*/
if((red_counter == red_DC) && (red_DC != 10))
{
Off_Colour(RGB_RED);
}
//the counter is incremented
red_counter++;
//if the counter is equal to 10 then the counter is reset to 0
if(red_counter == 10)
{
red_counter = 0;
}
}
//function which controls the GREEN LED according to its duty cycle
void Update_Green(void)
{
/*setting up a counter to ensure that the green LED turns on/off according to its duty cycle
this works like a delay*/
static uint8_t green_counter = 0;
/*if the counter is equal to 0 and the duty cycle is not equal to 0%
the the GREEN LED is turned on*/
if((green_counter == 0) && (green_DC != 0))
{
On_Colour(RGB_GREEN);
}
/*if the counter is equal to the duty cycle and the duty cycle is not equal to 100%
the the GREEN LED is turned off*/
if((green_counter == green_DC) && (green_DC != 10))
{
Off_Colour(RGB_GREEN);
}
//the counter is incremented
green_counter++;
//if the counter is equal to 10 then the counter is reset to 0
if(green_counter == 10)
{
green_counter = 0;
}
}
//function which controls the BLUE LED
void Update_Blue(void)
{
/*if the state of the blue LED is 0 then the LED is switched off
else it is switch on*/
if(blue_state == 0){
Off_Colour(RGB_BLUE);
}
else
On_Colour(RGB_BLUE);
}
<file_sep>################################################################################
# Automatically-generated file. Do not edit!
################################################################################
# Add inputs and outputs from these tool invocations to the build variables
C_SRCS += \
../src/lpcusb/source/USBVcom.c \
../src/lpcusb/source/lpc17xx_libcfg_default.c \
../src/lpcusb/source/serial_fifo.c \
../src/lpcusb/source/usbcontrol.c \
../src/lpcusb/source/usbhw_lpc.c \
../src/lpcusb/source/usbinit.c \
../src/lpcusb/source/usbstdreq.c
OBJS += \
./src/lpcusb/source/USBVcom.o \
./src/lpcusb/source/lpc17xx_libcfg_default.o \
./src/lpcusb/source/serial_fifo.o \
./src/lpcusb/source/usbcontrol.o \
./src/lpcusb/source/usbhw_lpc.o \
./src/lpcusb/source/usbinit.o \
./src/lpcusb/source/usbstdreq.o
C_DEPS += \
./src/lpcusb/source/USBVcom.d \
./src/lpcusb/source/lpc17xx_libcfg_default.d \
./src/lpcusb/source/serial_fifo.d \
./src/lpcusb/source/usbcontrol.d \
./src/lpcusb/source/usbhw_lpc.d \
./src/lpcusb/source/usbinit.d \
./src/lpcusb/source/usbstdreq.d
# Each subdirectory must supply rules for building sources it contributes
src/lpcusb/source/%.o: ../src/lpcusb/source/%.c
@echo 'Building file: $<'
@echo 'Invoking: MCU C Compiler'
arm-none-eabi-gcc -DDEBUG -D__USE_CMSIS=CMSISv1p30_LPC17xx -D__CODE_RED -D__NEWLIB__ -I"Z:\Assignment4V2\Lib_CMSISv1p30_LPC17xx\inc" -I"Z:\Assignment4V2\Lib_EaBaseBoard\inc" -I"Z:\Assignment4V2\Lib_MCU\inc" -O0 -g3 -Wall -c -fmessage-length=0 -fno-builtin -ffunction-sections -mcpu=cortex-m3 -mthumb -D__NEWLIB__ -MMD -MP -MF"$(@:%.o=%.d)" -MT"$(@:%.o=%.o)" -MT"$(@:%.o=%.d)" -o "$@" "$<"
@echo 'Finished building: $<'
@echo ' '
|
3905516703ceff7a9e3e3d933a8a1b6b779bf324
|
[
"Markdown",
"Makefile",
"INI",
"Gradle",
"Java",
"Python",
"Text",
"C",
"C++",
"Shell"
] | 166
|
C
|
ntarannum/Software-Work
|
c06364693eb6ab6ca400bee9819fbe329d93d9a0
|
b3673191cf59ab779bc5ac001b8f36a6780c433f
|
refs/heads/master
|
<repo_name>JorisSchelfaut/udemy-angular-8-course-project<file_sep>/src/app/recipes/recipes.component.ts
import { Component, OnInit } from '@angular/core';
import { Recipe } from '../recipes/recipe.model';
@Component({
selector: 'app-recipes',
templateUrl: './recipes.component.html',
styleUrls: ['./recipes.component.css']
})
export class RecipesComponent implements OnInit {
recipes: Recipe[] = [
new Recipe("Some recipe","This is a dummy recipe...","https://www.inspiredtaste.net/wp-content/uploads/2018/09/Easy-Oven-Baked-Salmon-Recipe-2-1200.jpg")
];
constructor() { }
ngOnInit() {
}
}
/* generated using ng g c recipes --spec false */
|
93c57855e73f5fe066f3f6a36669bf059e064c68
|
[
"TypeScript"
] | 1
|
TypeScript
|
JorisSchelfaut/udemy-angular-8-course-project
|
df2db60d3865cb2badd522e597385fdd4e87cb45
|
53b6f7606a6aeb48fb43e26d7e66917963cb48aa
|
refs/heads/master
|
<file_sep>// Dependencies
var express = require("express");
var mongoose = require("mongoose");
mongoose.Promise = Promise;
mongoose.connect("mongodb://heroku_5dx6346c:<EMAIL>:37100/heroku_5dx6346c");
var db = mongoose.connection;
// Show any mongoose errors
db.on("error", function(error) {
console.log("Mongoose Error: ", error);
});
// Once logged in to the db through mongoose, log a success message
db.once("open", function() {
console.log("Mongoose connection successful.");
});
//initialize express app
var app = express();
//body-parser boilerplate
var bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({ extended: false }));
//handlebars boilerplate
var exphbs = require("express-handlebars");
app.engine("handlebars", exphbs({ defaultLayout: "main" }));
app.set("view engine", "handlebars");
// Set up an Express Router
var router = express.Router();
// Require routes file pass router object
require("./config/routes")(router);
//requiring models
var Note = require("./models/Note.js");
var Article = require("./models/Article.js");
// Have every request go through router middleware
app.use(router);
//declare port
var port = process.env.PORT || 3000;
// Serve static content for the app from the "public" directory in the application directory.
app.use(express.static(process.cwd() + "/public"));
app.listen(port, function() {
console.log("App running on port 3000!");
});<file_sep>var scrape = require("../scripts/scrape");
var Article = require("../models/Article");
var articlesController = require("../controllers/articles");
var notesController = require("../controllers/notes");
module.exports = function(router) {
router.get("/", function(req, res) {
Article.find({saved: false}, function(error, found) {
if (error) {
console.log(error);
} else if (found.length === 0) {
res.render("empty")
} else {
var hbsObject = {
articles: found
};
res.render("index", hbsObject);
}
});
});
router.get("/api/fetch", function(req, res) {
// scrapes articles and saves unique ones to database
articlesController.fetch(function(err, docs) {
//lets user know if there were new articles or not
if (!docs || docs.insertedCount === 0) {
res.json({message: "No new articles today. Check back tomorrow!"});
}
else {
res.json({message: "Added " + docs.insertedCount + " new articles!"});
}
});
});
//retrieves the saved articles
router.get("/saved", function(req, res) {
articlesController.get({saved: true}, function(data) {
var hbsObject = {
articles: data
};
res.render("saved", hbsObject);
});
});
//for saving or unsaving articles
router.patch("/api/articles", function(req, res) {
articlesController.update(req.body, function(err, data) {
//this gets sent back to app.js and the article is either saved or unsaved
res.json(data);
});
});
// router.get("/api/notes/:article_id?", function(req, res) {
// var query = {};
// if (req.params.article_id) {
// query._id = req.params.article_id;
// }
// notesController.get(query, function(err, data) {
// res.json(data);
// });
// });
// router.delete("/api/notes/:id", function(req, res) {
// var query = {};
// query._id = req.params.id;
// notesController.delete(query, function(err, data) {
// res.json(data);
// });
// });
// router.post("/api/notes", function(req, res) {
// notesController.save(req.body, function(data) {
// res.json(data);
// });
// });
};
<file_sep>var request = require("request");
var cheerio = require("cheerio");
//handles scraping the articles from NYT
var scrape = function(cb) {
var articlesArr = [];
request("https://www.nytimes.com/", function(error, response, html) {
var $ = cheerio.load(html);
$("h2.story-heading").each(function(i, element) {
var result = {};
// Add the text and href of every link, and save them as properties of the result object
result.title = $(this).children("a").text();
result.link = $(this).children("a").attr("href");
if (result.title !== "" && result.link !== "") {
articlesArr.push(result);
}
});
cb(articlesArr);
});
};
module.exports = scrape;
<file_sep># news-notes
App that uses web scraping to collect news articles that users can comment on. The app uses mongodb to store the article info and comments.
|
1b9ecec84c474947613e716af02632cf20836d01
|
[
"JavaScript",
"Markdown"
] | 4
|
JavaScript
|
msibilsk/news-notes
|
e6478f9eade1b15fdaf30e91412b6b6cc13d2e4d
|
e3ebf5fbaacf22f55429c35f89cda5884d8f01be
|
refs/heads/master
|
<repo_name>ropensci-archive/natserv<file_sep>/tests/testthat/helper-natserv.R
library("vcr")
vcr::vcr_configure(dir = "../fixtures")
vcr::check_cassette_names()
|
4679ede982884c01e34e47e1ce4a87e553baf14d
|
[
"R"
] | 1
|
R
|
ropensci-archive/natserv
|
ef8d717cd81504e827f91a599dbbd1a7949f782f
|
ca25f820e42f57d15b856e60c40f616f441a81b8
|
refs/heads/master
|
<file_sep>require 'c_tokenizer_ext'
class StringEater::CTokenizer
def self.tokens
@tokens ||= []
end
def self.add_field name, opts={}
self.tokens << StringEater::Token::new_field(name, opts)
define_method(name) {@extracted_tokens[name]}
end
def self.look_for tokens
self.tokens << StringEater::Token::new_separator(tokens)
end
# This is very slow, only do it when necessary
def self.dup_tokens
Marshal.load(Marshal.dump(tokens))
end
def initialize
refresh_tokens
end
def tokens
@tokens
end
def extract_all_fields
@token_filter = lambda do |t|
t.opts[:extract] = true if t.name
end
refresh_tokens
end
def extract_no_fields
@token_filter = lambda do |t|
t.opts[:extract] = false if t.name
end
refresh_tokens
end
def extract_fields *fields
@token_filter = lambda do |t|
t.opts[:extract] = fields.include?(t.name)
end
refresh_tokens
end
# This is very slow, only do it once before processing
def refresh_tokens
@tokens = self.class.dup_tokens
if @token_filter
@tokens.each{|t| @token_filter.call(t)}
end
tokens_to_find = tokens.each_with_index.map do |t, i|
[i, t.string] if t.string
end.compact
@tokens_to_find_indexes = tokens_to_find.map{|t| t[0]}
@tokens_to_find_strings = tokens_to_find.map{|t| t[1]}
tokens_to_extract = tokens.each_with_index.map do |t, i|
[i, t.name] if t.extract?
end.compact
@tokens_to_extract_indexes = tokens_to_extract.map{|t| t[0]}
@tokens_to_extract_names = tokens.map{|t| t.name}
@have_tokens_to_extract = (@tokens_to_extract_indexes.size > 0)
end
def describe_line
tokens.inject("") do |desc, t|
desc << (t.string || t.name.to_s || "xxxxxx")
end
end
def do_extra_parsing
end
def tokenize! string, &block
@string = string
@extracted_tokens ||= {}
@extracted_tokens.clear
return unless @have_tokens_to_extract
@extracted_tokens = ctokenize!(@string,
@tokens_to_find_indexes,
@tokens_to_find_strings,
@tokens_to_extract_indexes,
@tokens_to_extract_names)
# extra parsing hook
do_extra_parsing
if block_given?
yield @extracted_tokens
end
# return self for chaining
self
end
private
def set_token_startpoint ix, startpoint
@tokens[ix].breakpoints[0] = startpoint
end
def get_token_startpoint ix
@tokens[ix].breakpoints[0]
end
def set_token_endpoint ix, endpoint
@tokens[ix].breakpoints[1] = endpoint
end
def extract_token? ix
@tokens[ix].extract?
end
end
<file_sep>class StringEater::Token
attr_accessor :name, :string, :opts, :breakpoints, :children
def initialize
@opts = {}
@breakpoints = [nil,nil]
end
def extract?
@opts[:extract]
end
def self.new_field(name, opts)
t = new
t.name = name
t.opts = {:extract => true}.merge(opts)
t
end
def self.new_separator(string)
t = new
t.string = string
t
end
end
<file_sep>require 'mkmf'
create_makefile('c_tokenizer_ext')
<file_sep># String Eater
A fast ruby string tokenizer. It eats strings and dumps tokens.
## License
String Eater is released under the
[MIT license](http://en.wikipedia.org/wiki/MIT_License).
See the LICENSE file.
## Requirements
String Eater probably only works in Ruby 1.9.2+ with MRI. It's been
tested with Ruby 1.9.3p194.
String Eater uses a C extension, so it will only work on Ruby
implemenatations that provide support for C extensions.
## Installation
If your system is set up to allow it, you can just do
gem install string-eater
Or, if you prefer a more hands-on approach or want to hack at the source:
git clone git://github.com/dantswain/string-eater.git
cd string-eater
rake install
If you are working on a system where you need to `sudo gem install`
you can do
rake gem
sudo gem install string-eater
As always, you can `rake -T` to find out what other rake tasks we have
provided.
## Basic Usage
Suppose we want to tokenize a string that contains address information
for a person and is consistently formatted like
Last Name, First Name | Street address, City, State, Zip
Suppose we only want to extract the last name, city, and state.
To do this using String Eater, create a subclass of
`StringEater::Tokenizer` like this
require 'string-eater'
class PersonTokenizer < StringEater::Tokenizer
add_field :last_name
look_for ", "
add_field :first_name, :extract => false
look_for " | "
add_field :street_address, :extract => false
look_for ", "
add_field :city
look_for ", "
add_field :state
look_for ", "
end
Note the use of `:extract => false` to specify fields that are important
to the structure of the line but that we don't necessarily need to
extract.
Then, we can tokenize the string like this:
tokenizer = PersonTokenizer.new
string = "Flinstone, Fred | 301 Cobblestone Way, Bedrock, NA, 00000"
tokenizer.tokenize! string
puts tokenizer.last_name # => "Flinstone"
puts tokenizer.city # => "Bedrock"
puts tokenizer.state # => "NA"
We can also do something like this:
tokenizer.tokenize!(string) do |tokens|
puts "The #{tokens[:last_name]}s live in #{tokens[:city]}"
end
For another example, see `examples/nginx.rb`, which defines an
[nginx](http://nginx.org) log line tokenizer.
## Implementation
There are actually three tokenizer algorithms provided here. The
three algorithms should be interchangeable.
1. `StringEater::CTokenizer` - A C extension implementation. The
fastest of the three. This is the default implementation for
`StringEater::Tokenizer`.
2. `StringEater::RubyTokenizer` - A pure-Ruby implementation. This is
a slightly different implementation of the algorithm - an
implementation that is faster on Ruby than a translation of the C
algorithm. Probably not as fast (or not much faster) than using
Ruby regular expressions.
3. `StringEater::RubyTokenizerEachChar` - A pure-Ruby implementation.
This is essentially the same as the C implementation, but written
in pure Ruby. It uses `String#each_char` and is therefore VERY
SLOW! It provides a good way to hack the algorithm, though.
The main algorithm works by finding the start and end points of tokens
in a string. The search is done incrementally (i.e., loop through the
string and look for each sequence of characters). The algorithm is
"lazy" in the sense that only the required tokens are copied for
output ("extracted").
## Performance
Soon I'll add some code here to run your own benchmarks.
I've run my own benchmarks comparing String Eater to some code that does the
same task (both tokenizing nginx log lines) using Ruby regular expressions. So
far, String Eater is about 200% faster; able to process over 100,000 lines per
second on my laptop vs less than 50,000 lines per second for the regular
expression version. I'm working to further optimize the String Eater code.
## Contributing
The usual github process applies here:
1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Added some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request
You can also contribute to the author's ego by letting him know that
you find String Eater useful ;)
<file_sep># this tokenizer is very slow, but it illustrates the
# basic idea of the C tokenizer
class StringEater::RubyTokenizerEachChar
def self.tokens
@tokens ||= []
end
def self.combined_tokens
@combined_tokens ||= []
end
def self.add_field name, opts={}
self.tokens << StringEater::Token::new_field(name, opts)
define_method(name) {@extracted_tokens[name]}
end
def self.look_for tokens
self.tokens << StringEater::Token::new_separator(tokens)
end
def self.combine_fields opts={}
from_token_index = self.tokens.index{|t| t.name == opts[:from]}
to_token_index = self.tokens.index{|t| t.name == opts[:to]}
self.combined_tokens << [opts[:as], from_token_index, to_token_index]
define_method(opts[:as]) {@extracted_tokens[opts[:as]]}
end
def tokens
@tokens ||= self.class.tokens
end
def combined_tokens
@combined_tokens ||= self.class.combined_tokens
end
def refresh_tokens
@combined_tokens = nil
@tokens = nil
tokens
end
def describe_line
tokens.inject("") do |desc, t|
desc << (t.string || t.name.to_s || "xxxxxx")
end
end
def find_breakpoints string
tokenize!(string) unless @string == string
tokens.inject([]) do |bp, t|
bp << t.breakpoints
bp
end.flatten.uniq
end
def tokenize! string, &block
@string = string
@extracted_tokens ||= {}
@extracted_tokens.clear
@tokens_to_find ||= tokens.each_with_index.map do |t, i|
[i, t.string] if t.string
end.compact
@tokens_to_extract_indeces ||= tokens.each_with_index.map do |t, i|
i if t.extract?
end.compact
tokens.first.breakpoints[0] = 0
find_index = 0
curr_token = @tokens_to_find[find_index]
curr_token_index = curr_token[0]
curr_token_length = curr_token[1].length
looking_for_index = 0
looking_for = curr_token[1][looking_for_index]
counter = 0
string.each_char do |c|
if c == looking_for
if looking_for_index == 0
# entering new token
if curr_token_index > 0
t = tokens[curr_token_index - 1]
t.breakpoints[1] = counter
if t.extract?
@extracted_tokens[t.name] = string[t.breakpoints[0]...t.breakpoints[1]]
end
end
tokens[curr_token_index].breakpoints[0] = counter
end
if looking_for_index >= (curr_token_length - 1)
# leaving token
tokens[curr_token_index].breakpoints[1] = counter
if curr_token_index >= tokens.size-1
# we're done!
break
else
tokens[curr_token_index + 1].breakpoints[0] = counter + 1
end
# next token
find_index += 1
if find_index >= @tokens_to_find.length
# we're done!
break
end
curr_token = @tokens_to_find[find_index]
curr_token_index = curr_token[0]
curr_token_length = curr_token[1].length
looking_for_index = 0
else
looking_for_index += 1
end
end
looking_for = curr_token[1][looking_for_index]
counter += 1
end
last_token = tokens.last
last_token.breakpoints[1] = string.length
if last_token.extract?
@extracted_tokens[last_token.name] = string[last_token.breakpoints[0]..last_token.breakpoints[1]]
end
combined_tokens.each do |combiner|
name = combiner[0]
from = @tokens[combiner[1]].breakpoints[0]
to = @tokens[combiner[2]].breakpoints[1]
@extracted_tokens[name] = string[from...to]
end
if block_given?
yield @extracted_tokens
end
# return self for chaining
self
end
end
<file_sep>require 'spec_helper'
require 'string-eater'
$: << File.expand_path(File.join(File.dirname(__FILE__), '..', 'examples'))
require 'nginx'
describe NginxLogTokenizer do
before(:each) do
@tokenizer = NginxLogTokenizer.new
@str = '172.16.31.10 - - [01/Aug/2012:09:14:25 -0500] "GET /this_is_a_url HTTP/1.1" 304 152 "http://referrer.com" "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)" "-" "there could be" other "stuff here"'
@str2 = '172.16.31.10 - - [01/Aug/2012:09:14:25 -0500] "GET /this_is_a_url HTTP/1.1" 304 152 "http://referrer.com" "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)" "-"'
end
{
:ip => "172.16.31.10",
:request => "GET /this_is_a_url HTTP/1.1",
:status_code => 304,
:referrer_url => "http://referrer.com",
:user_agent => "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)",
:remainder => "\"there could be\" other \"stuff here\"",
}.each_pair do |token,val|
it "should find the right value for #{token}" do
@tokenizer.tokenize!(@str).send(token).should == val
end
end
it "should handle there not being a remainder correctly" do
@tokenizer.tokenize!(@str2).remainder.should be_nil
end
end
<file_sep>module StringEater
autoload :Token, 'token'
autoload :RubyTokenizer, 'ruby-tokenizer'
autoload :RubyTokenizerEachCHar, 'ruby-tokenizer-each-char'
autoload :CTokenizer, 'c-tokenizer'
autoload :VERSION, 'version'
class Tokenizer < CTokenizer; end
end
<file_sep># this tokenizer is fairly fast, but not necessarily faster than regexps
class StringEater::RubyTokenizer
def self.tokens
@tokens ||= []
end
def self.combined_tokens
@combined_tokens ||= []
end
def self.add_field name, opts={}
self.tokens << StringEater::Token::new_field(name, opts)
define_method(name) {@extracted_tokens[name]}
end
def self.look_for tokens
self.tokens << StringEater::Token::new_separator(tokens)
end
def self.combine_fields opts={}
from_token_index = self.tokens.index{|t| t.name == opts[:from]}
to_token_index = self.tokens.index{|t| t.name == opts[:to]}
self.combined_tokens << [opts[:as], from_token_index, to_token_index]
define_method(opts[:as]) {@extracted_tokens[opts[:as]]}
end
def tokens
@tokens ||= self.class.tokens
end
def combined_tokens
@combined_tokens ||= self.class.combined_tokens
end
def refresh_tokens
@combined_tokens = nil
@tokens = nil
tokens
end
def describe_line
tokens.inject("") do |desc, t|
desc << (t.string || t.name.to_s || "xxxxxx")
end
end
def find_breakpoints(string)
@literal_tokens ||= tokens.select{|t| t.string}
@breakpoints ||= Array.new(2*@literal_tokens.size + 2)
@breakpoints[0] = 0
@breakpoints[-1] = string.length
start_point = 0
@literal_tokens.each_with_index do |t, i|
@breakpoints[2*i+1], start_point = find_end_of(t, string, start_point)
@breakpoints[2*i+2] = start_point
end
@breakpoints
end
def tokenize! string, &block
@extracted_tokens ||= {}
@extracted_tokens.clear
@tokens_to_extract ||= tokens.select{|t| t.extract?}
find_breakpoints(string)
last_important_bp = [@breakpoints.length, tokens.size].min
(0...last_important_bp).each do |i|
tokens[i].breakpoints = [@breakpoints[i], @breakpoints[i+1]]
end
@tokens_to_extract.each do |t|
@extracted_tokens[t.name] = string[t.breakpoints[0]...t.breakpoints[1]]
end
combined_tokens.each do |combiner|
name = combiner[0]
from = @tokens[combiner[1]].breakpoints[0]
to = @tokens[combiner[2]].breakpoints[1]
@extracted_tokens[name] = string[from...to]
end
if block_given?
yield @extracted_tokens
end
# return self for chaining
self
end
protected
def find_end_of token, string, start_at
start = string.index(token.string, start_at+1) || string.length
[start, [start + token.string.length, string.length].min]
end
end
<file_sep>require File.expand_path('../lib/version', __FILE__)
require 'rake'
Gem::Specification.new do |gem|
gem.name = "string-eater"
gem.authors = ["<NAME>"]
gem.email = ["<EMAIL>"]
gem.description = "Fast string tokenizer. Nom strings."
gem.summary = "Fast string tokenizer. Nom strings."
gem.homepage = "http://github.com/simplifi/string-eater"
gem.files = FileList['lib/*.rb', 'lib/**/*.rb/', 'ext/**/*.rb',
'ext/**/*.c', 'spec/**/*.rb', 'examples/*.rb',
'[A-Z]*'].to_a
gem.test_files = FileList['spec/**/*.rb'].to_a
gem.require_paths = ["lib", "ext/string-eater"]
gem.extensions = ['ext/string-eater/extconf.rb']
gem.version = StringEater::VERSION::STRING
end
<file_sep>require 'spec_helper'
require 'string-eater'
TestedClass = StringEater::CTokenizer
describe StringEater do
it "should have a version" do
StringEater::VERSION::STRING.split(".").size.should >= 3
end
end
# normal use
class Example1 < TestedClass
add_field :first_word
look_for " "
add_field :second_word, :extract => false
look_for "|"
add_field :third_word
end
describe Example1 do
before(:each) do
@tokenizer = Example1.new
@str1 = "foo bar|baz"
@first_word1 = "foo"
@second_word1 = "bar"
@third_word1 = "baz"
@bp1 = [0, 3,4,7,8,11]
end
describe "find_breakpoints" do
it "should return an array of the breakpoints" do
@tokenizer.find_breakpoints(@str1).should == @bp1 if @tokenizer.respond_to?(:find_breakpoints)
end
end
describe "#extract_all_fields" do
it "should extract all of the fields" do
@tokenizer.extract_all_fields
@tokenizer.tokenize!(@str1)
@tokenizer.first_word.should == @first_word1
@tokenizer.second_word.should == @second_word1
@tokenizer.third_word.should == @third_word1
end
end
describe "#extract_no_fields" do
it "should not extract any of the fields" do
@tokenizer.extract_no_fields
@tokenizer.tokenize!(@str1)
@tokenizer.first_word.should be_nil
@tokenizer.second_word.should be_nil
@tokenizer.third_word.should be_nil
end
end
describe "#extract_fields" do
it "should allow us to set which fields get extracted" do
@tokenizer.extract_fields :second_word
@tokenizer.tokenize!(@str1)
@tokenizer.first_word.should be_nil
@tokenizer.second_word.should == @second_word1
@tokenizer.third_word.should be_nil
end
end
describe "tokenize!" do
it "should return itself" do
@tokenizer.tokenize!(@str1).should == @tokenizer
end
it "should set the first word" do
@tokenizer.tokenize!(@str1).first_word.should == "foo"
end
it "should set the third word" do
@tokenizer.tokenize!(@str1).third_word.should == "baz"
end
it "should not set the second word" do
@tokenizer.tokenize!(@str1).second_word.should be_nil
end
it "should yield a hash of tokens if a block is given" do
@tokenizer.tokenize!(@str1) do |tokens|
tokens[:first_word].should == "foo"
end
end
it "should return everything to the end of the line for the last token" do
s = "c defg asdf | foo , baa"
@tokenizer.tokenize!("a b|#{s}").third_word.should == s
end
it "should work if the last delimeter is missing and the second-to-last field is not used" do
s = "a b"
# @tokenizer.extract_all_fields
@tokenizer.tokenize!(s).third_word.should be_nil
end
end
end
# an example where we ignore after a certain point in the string
class Example2 < TestedClass
add_field :first_word, :extract => false
look_for " "
add_field :second_word
look_for " "
add_field :third_word, :extract => false
look_for "-"
end
describe Example2 do
before(:each) do
@tokenizer = Example2.new
@str1 = "foo bar baz-"
@second_word1 = "bar"
end
describe "tokenize!" do
it "should find the token when there is extra stuff at the end of the string" do
@tokenizer.tokenize!(@str1).second_word.should == @second_word1
end
end
end
# an example where the split is more than one char
class Example3 < TestedClass
look_for "foo="
add_field :foo_val
look_for "&"
end
describe Example3 do
before(:each) do
@tokenizer = Example3.new
end
describe "tokenize!" do
it "should find the token if there is only one occurrence of the characters in the separator" do
@tokenizer.tokenize!("abcd?foo=val&blah").foo_val.should == "val"
end
it "should still work if part of the separator token occurs" do
@tokenizer.tokenize!("abcd?foo_blah=baz&foo=bar&buh").foo_val.should == "bar"
end
end
end
# CTokenizer doesn't do combine_fields because
# writing out breakpoints is a significant slow-down
if TestedClass.respond_to?(:combine_fields)
# an example where we combine fields
class Example3 < TestedClass
add_field :first_word, :extract => false
look_for " \""
add_field :part1, :extract => false
look_for " "
add_field :part2
look_for " "
add_field :part3, :extract => false
look_for "\""
combine_fields :from => :part1, :to => :part3, :as => :parts
end
describe Example3 do
before(:each) do
@tokenizer = Example3.new
@str1 = "foo \"bar baz bang\""
@part2 = "baz"
@parts = "bar baz bang"
end
it "should extract like normal" do
@tokenizer.tokenize!(@str1).part2.should == @part2
end
it "should ignore like normal" do
@tokenizer.tokenize!(@str1).part1.should be_nil
end
it "should extract the combined field" do
@tokenizer.tokenize!(@str1).parts.should == @parts
end
end
end
<file_sep>$LOAD_PATH.concat %w[./lib ./ext/string-eater]
|
840f772f3ba8f943ab9320005c82d6ff6adce2c0
|
[
"Markdown",
"Ruby"
] | 11
|
Ruby
|
gbitgit/string-eater
|
7f3b9b99a2f7081eaeaa4beea4c5f11b2af99a60
|
800c1e9db87cca89fafda01b364bc4c216250210
|
refs/heads/master
|
<repo_name>2021alexl/StockX-to-Excel<file_sep>/main.py
from __future__ import print_function
import requests
import json
import openpyxl
import re
import os
import string
import math
def load_from_json(file):
try:
with open(file, 'r') as myfile:
return json.load(myfile)
except IOError:
with open(file, 'w') as myfile:
json.dump({}, myfile)
return {}
config = load_from_json('config.json')
workbook_name = config['workbookName']
email = config['email']
password = config['<PASSWORD>']
attributes = config['attributes']
market_attributes = config['marketAttributes']
width = config['width']
def center(text, spacer=' ', length=width, clear=False, display=True):
if clear:
os.system('cls' if os.name == 'nt' else 'clear')
count = int(math.ceil((length - len(text)) / 2))
if count > 0:
if display:
print(spacer * count + text + spacer * count)
else:
return (spacer * count + text + spacer * count)
else:
if display:
print(text)
else:
return text
class Stockx():
API_BASE = 'https://stockx.com/api'
def __init__(self):
self.customer_id = None
self.headers = None
def __api_query(self, request_type, command, data=None):
endpoint = self.API_BASE + command
response = None
if request_type == 'GET':
response = requests.get(endpoint, params=data, headers=self.headers)
elif request_type == 'POST':
response = requests.post(endpoint, json=data, headers=self.headers)
elif request_type == 'DELETE':
response = requests.delete(endpoint, json=data, headers=self.headers)
return response.json()
def __get(self, command, data=None):
return self.__api_query('GET', command, data)
def __post(self, command, data=None):
return self.__api_query('POST', command, data)
def __delete(self, command, data=None):
return self.__api_query('DELETE', command, data)
def authenticate(self, email, password):
endpoint = self.API_BASE + '/login'
payload = {
'email': email,
'password': password
}
response = requests.post(endpoint, json=payload)
customer = response.json().get('Customer', None)
if customer is None:
raise ValueError('Authentication failed, check username/password')
self.customer_id = response.json()['Customer']['id']
self.headers = {
'JWT-Authorization': response.headers['jwt-authorization']
}
return True
def selling(self):
command = '/customers/{0}/selling'.format(self.customer_id)
response = self.__get(command)
return response['PortfolioItems']
stockx = Stockx()
def json_to_title(json):
return re.sub(r'(\w)([A-Z])', r'\1 \2', json).title().replace('Shoe Size', 'Size')
def setup_workbook(attributes, market_attributes, workbook_name):
wb = openpyxl.Workbook()
ws = wb.active
headers = [json_to_title(item) for item in attributes + market_attributes]
for i in range(0, len(headers)):
cell = ws[list(string.ascii_uppercase)[i + list(string.ascii_uppercase).index('B')] + str(2)]
cell.value = headers[i]
cell.alignment = openpyxl.styles.Alignment(horizontal='center', vertical='center')
wb.save(workbook_name)
def write_workbook(email, password, attributes, market_attributes, workbook_name):
wb = openpyxl.load_workbook(workbook_name)
ws = wb.active
if stockx.authenticate(email, password):
i = 0
for item in stockx.selling():
if item['text'] == 'Asking':
product = item['product']
for k in range(0, len(attributes)):
cell = ws[list(string.ascii_uppercase)[k + list(string.ascii_uppercase).index('B')] + str(3 + i)]
cell.value = product[attributes[k]]
cell.alignment = openpyxl.styles.Alignment(horizontal='center', vertical='center')
if market_attributes != []:
market = product['market']
for k in range(len(attributes), len(attributes) + len(market_attributes)):
cell = ws[list(string.ascii_uppercase)[k + list(string.ascii_uppercase).index('B')] + str(3 + i)]
cell.value = market[market_attributes[k - len(attributes)]]
cell.alignment = openpyxl.styles.Alignment(horizontal='center', vertical='center')
i += 1
wb.save(workbook_name)
center(' ', clear=True)
center('StockX to Excel by @DefNotAvg')
center('-', '-')
print('{}\r'.format(center('Setting up the Excel Workbook...', display=False)), end='')
setup_workbook(attributes, market_attributes, workbook_name)
center('Successfully set up the Excel Workbook!!')
print('{}\r'.format(center('Writing StockX data to {}...'.format(workbook_name), display=False)), end='')
write_workbook(email, password, attributes, market_attributes, workbook_name)
center('Successfully exported StockX data to {}!!'.format(workbook_name))<file_sep>/README.md
# StockX to Excel
A simple program to export your StockX selling list to Excel.
## Getting Started
Edit config.json to your liking then run main.py.
## config.json
* workbookName - Name of the Excel workbook you'd like results written to
* email - Your StockX email
* password - <PASSWORD>
* attributes - A list of attributes to record
* marketAttributes - A list of market attributes to record
* width - Number of characters to center the program output around
## Prerequisites
* Working on Python 2.7.16 or Python 3.6.8
* [requests](http://docs.python-requests.org/en/master/)
* [openpyxl](https://openpyxl.readthedocs.io/en/stable/)
## To-Do
- [ ] Update README with examples
|
59526b15735470333a1ae6191f1cecd181fd553c
|
[
"Markdown",
"Python"
] | 2
|
Python
|
2021alexl/StockX-to-Excel
|
a46784f80a36de527eb893cd74cfa16e081fe81a
|
0f967fecc5c7576f5af0903b16d908ce22ff47ff
|
refs/heads/master
|
<repo_name>taochanglian/springcloud<file_sep>/springcloud-client/src/main/java/com/mycompany/microservice/client/ClientApplication.java
package com.mycompany.microservice.client;
import com.sun.deploy.util.SessionState;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* Created by tao on 17/1/19.
*/
@SpringBootApplication
public class ClientApplication {
public static void main(String[] args) {
SpringApplication.run(ClientApplication.class,args);
}
}
<file_sep>/pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>springcloud</groupId>
<artifactId>springcloud</artifactId>
<packaging>pom</packaging>
<version>1.0-SNAPSHOT</version>
<modules>
<module>eureka-server</module>
<module>config-server</module>
<module>springcloud-api</module>
<module>springcloud-client</module>
</modules>
<!-- Inherit defaults from Spring Boot -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.3.RELEASE</version>
</parent>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Camden.SR4</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!--Start eureka & eurekaServer -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka-server</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!--END eureka & eurekaServer -->
<!-- Start spring cloud config server & client -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-server</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-client</artifactId>
</dependency>
<!-- End spring cloud config server & client -->
<!--Start spring cloud Hystrix -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-hystrix</artifactId>
</dependency>
<!--End spring cloud Hystrix -->
<!--Start spring cloud zuul -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-zuul</artifactId>
</dependency>
<!--ENd spring cloud zuul -->
</dependencies>
</project><file_sep>/springcloud-api/src/main/java/com/mycompany/microservice/api/controller/PersonController.java
package com.mycompany.microservice.api.controller;
import com.mycompany.microservice.api.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* Created by tao on 17/1/19.
*/
@Controller
@RequestMapping("/persons")
public class PersonController {
@Autowired
private IUserService userService;
@RequestMapping("/hello")
public String hello(){
userService.hello();
return "Hello";
}
}
|
6f0c5b9e12fea5f0649df03b8beddf06cfa18e7e
|
[
"Java",
"Maven POM"
] | 3
|
Java
|
taochanglian/springcloud
|
0f13de32cddc83619b5a69c5ddd58292c66a5113
|
ad65b79041832882c055f87bc670256c930f8952
|
refs/heads/master
|
<repo_name>MrWZZ/WZZ_ZONE<file_sep>/pages/knowledge/knowledge.js
//首页导航数组(通用模块有这个的副本,需要一起修改)
var homeLinks = [
{ title:"主页", url:"/WZZ_ZONE/index.html" },
{ title:"知识总结", url:"/WZZ_ZONE/pages/knowledge/knowledge.html" },
{ title:"方法库", url:"#" },
{ title:"收藏", url:"/WZZ_ZONE/pages/collection/collection.html" },
{ title:"作品", url:"#" },
{ title:"踩过的坑", url:"/WZZ_ZONE/pages/mistake/mistake.html" }
];
//首页导航生成(通用模块有这个的副本,需要一起修改)
function CreateHomeLinks()
{
var homeNavPanel = document.querySelector(".home_nav");
for(var i in homeLinks)
{
var a = document.createElement("a");
a.setAttribute("href",homeLinks[i].url);
a.text = homeLinks[i].title;
homeNavPanel.appendChild(a);
}
}
//知识数组
var knowledgeList = [
//前端
{type : "前端",
slots:[
{title:"HTML",url:"web_developer/html_summary/html_summary.html"},
{title:"CSS",url:"web_developer/css_summary/css_summary.html"},
{title:"JavaScript",url:"web_developer/javascript_summary/javascript_summary.html"},
{title:"JQuery",url:"web_developer/jquery_summary/jquery_summary.html"}
]},
//软件
{type : "软件",
slots:[
{title:"Unity3D",url:"#"},
{title:"Atom",url:"software/atom/atom.html"},
{title:"Git",url:"software/git/git.html"}
]},
//语言
{type : "语言",
slots:[
{title:"C++",url:"#"},
{title:"C#",url:"#"},
{title:"UML",url:"language/uml/uml.html"},
{title:"数据结构与算法",url:"language/structures_and_algorithms/structures_and_algorithms.html"}
]}
];
//生成知识的各个模块
function CreateModel()
{
var center = document.querySelector(".center");
for(var i in knowledgeList)
{
var knowledge_type = document.createElement("div");
knowledge_type.setAttribute("class","knowledge_type");
var h2 = document.createElement("h2");
h2.innerHTML = knowledgeList[i].type;
knowledge_type.appendChild(h2);
var knowledge_content = document.createElement("div");
knowledge_content.setAttribute("class","knowledge_content");
for(var j in knowledgeList[i].slots)
{
var a = document.createElement("a");
a.text = knowledgeList[i].slots[j].title;
a.setAttribute("href",knowledgeList[i].slots[j].url);
knowledge_content.appendChild(a);
}
knowledge_type.appendChild(knowledge_content);
center.appendChild(knowledge_type);
}
}
CreateModel();
CreateHomeLinks();
<file_sep>/pages/knowledge/web_developer/css_summary/pages.js
//页面数组
var pages = [
{ title:"概述", url:"pages/1.html" },
{ title:"属性简明介绍", url:"pages/2.html" },
{ title:"设置文本样式", url:"pages/3.html" },
{ title:"过渡、动画、变换", url:"pages/4.html" }
];
<file_sep>/pages/knowledge/web_developer/css_summary/pages/1.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<link rel="stylesheet" href="/WZZ_ZONE/pages/summary.css">
</head>
<body>
<pre class="w_doc">
<h1 class="h1">样式的层叠和继承</h1>
浏览器时根据层叠和继承规则确定显示一个元素时各种样式属性采用的值。
每一个元素都有一套浏览器呈现页面时要用到的CSS属性。对于这种属性,浏览器都需要查看其所有的样式来源。
<b>浏览器样式</b>
浏览器样式是元素尚未设置样式时浏览器应用在它身上的默认样式。
这种样式因浏览器而略有差异,不过大体一致。
<b>用户样式</b>
大多浏览器都允许用户定义自己的样式。
以谷歌的Chrome为例,它会在用户的个人信息目录中生成一个Default/User StyleSheets/Custom.css的文件。
<b>样式如何层叠</b>
浏览器要显示元素时求索一个CSS属性值的次序。
1. 元素内嵌样式。(style属性)
2. 文档内嵌样式。(style元素)
3. 外部样式。 (link元素)
4. 用户样式。
5. 浏览器样式。
<b>用重要样式调整层叠次序</b>
把样式属性值标记为重要(important),可以改变正常的层叠次序。
不管这个样式定义在哪个地方,浏览器都会优先考虑。
<xmp>color:black !important;</xmp>
能凌驾于作者定义的重要属性值之上的只有用户样式表中定义的重要属性值。
而对于普通属性,作者定义的样式优先用户定义的样式。
<strong>根据具体程度和定义次序解决同级样式冲突</strong>
如果有两条定义于同一层次的样式都能应用于一个元素,而且他们都包含着浏览器要查看的CSS属性值,
浏览器会评估两条样式的具体程度,然后选中较为特殊的那条。
样式的具体程度通过统计三类特征得出:
1. 样式的选择器中id值的数目。
2. 选择器中其他属性和伪类的数目。
3. 选择器中元素名和伪元素的数目。
第一个的值:0-1-1。
第二个的值:0-1-2。
第三个的值:1-0-0。
先比较第一列的值:第三个最高,该id的元素应用其样式。
比较第二列的,第一个和第二个相同,比较下一列,第二个的大,应用其样式。
如果同一个样式属性出现在具体程度相当的几条样式中,那么浏览器会根据其位置的先后选择所有的值。
规则是使用最后面的属性。
<b>继承</b>
如果浏览器在直接相关的样式中找不到某个属性的值,就会求助于继承机制,使用父元素的这个样式的属性值。
但并非所有的CSS属性值都可以继承,这方面有个经验可以参考:
与元素外观(文字颜色、字体等)相关的的样式会被继承;与元素在页面上布局相关的样式不会被继承。
在样式中使用inherit这个特别设立的值可以强行实施继承,明示浏览器在该属性上使用父元素样式中的代码。
<h1 class="h1">CSS中的长度</h1>
CSS规定了两种类型的长度单位:绝对长度、相对长度。
<b>绝对长度</b>
+ in:英寸。
+ cm:厘米。
+ mm:毫米。
+ pt:磅(1磅=1/72英寸)
+ pc:pica(1pica=12pt)
<b>相对长度</b>
+ em:元素字号的几倍。
+ rem:根元素字号的几倍。
+ px:像素(假定显示设备分辨率为96dpi)
+ %:一个度量单位表示为其他属性值的百分比。
注意:并非所有属性都能用这个单位;百分比挂钩的其他属性各不相同。
+ vw:1vw等于文档显示区域宽度的1%。
+ vh:1vh等于文档显示区域高度的1%。
+ vmin、vmax:分别表示vw和vh中较小和较大的那个值。
<b>用算式作值</b>
<xmp>width:calc(50% - 20px);</xmp>
</pre>
</body>
</html>
<file_sep>/pages/knowledge/web_developer/html_summary/pages/4_document_segmentation.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="/WZZ_ZONE/pages/summary.css">
<title></title>
</head>
<body>
<pre class="w_doc">
<h1 class="h1">h1~h6元素</h1>
+ 意义:标题
+ 示例:<xmp><h1 id="h1">h1~h6元素</h1></xmp>
<h1 class=".h1" >hgroup元素</h1>
+ 意义:标题组
+ 示例:
<xmp class="block">
<hgroup>
<h1> ... </h1>
</hgroup>
</xmp>
<h1 class="h1">section元素</h1>
+ 意义:表示文档中的一节
+ 示例:<xmp><section> ... </section></xmp>
<h1 class="h1">header元素</h1>
+ 意义:表示一节的首部
+ 示例:<xmp><header> ... </header></xmp>
<h1 class="h1">footer元素</h1>
+ 意义:表示一节的尾部
+ 示例:<xmp><footer> ... </footer></xmp>
<h1 class="h1">nav元素</h1>
+ 意义:表示文档中的一个区域,包含着到其他页面的连接
+ 示例:
<xmp class="block">
<nav>
<ul>
<li><a href="#"> ... </a></li>
</ul>
</nav>
</xmp>
<h1 class="h1">article元素</h1>
+ 意义:代表HTML文档中一段独立成篇的内容
+ 示例:<xmp><article class=""> ... </article></xmp>
<h1 class="h1">aside元素</h1>
+ 意义:表示跟周边内容稍沾边一点的内容,类似于书籍或杂志中的侧栏
+ 示例:<xmp><aside class=""> ... </aside></xmp>
<h1 class="h1">address元素</h1>
+ 意义:用来表示文档或article元素的联系信息
+ 示例:<xmp><address class=""> ... </address></xmp>
<h1 class="h1">details元素</h1>
+ 意义:在文档中生成一个区域,用户可以展开它以了解关于某主题的更多详情
+ 示例:
<xmp class="block">
<details open>
<summary> 这里是概要内容 </summary>
<p>这里是具体内容,合上后将会隐藏</p>
<p>这里是具体内容,合上后将会隐藏</p>
</details>
</xmp>
演示:
<div class="demo">
<details open>
<summary> 这里是概要内容 </summary>
<p>这里是具体内容,合上后将会隐藏</p>
<p>这里是具体内容,合上后将会隐藏</p>
</details>
</div>
open属性:要让页面一显示details元素就呈展开状态,就需要使用它的open属性。
summary元素的作用是为该详情区域生成一个说明标签或标题。
</pre>
</body>
</html>
<file_sep>/pages/knowledge/software/git/pages/1.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<pre class="w_doc">
<h1 class="h1">常用命令</h1>
<b>丢弃本地所有修改(新增、删除、更改)</b>
<code>git checkout .</code>
<b>合并分支</b>
如:将dev分支合并到master上
1.查询分支
<code>git branch</code>
2.转到master上
<code>git checkout master</code>
3.进行合并
<code>git merge dev -m "进行合并"</code>
</pre>
</body>
</html>
<file_sep>/pages/knowledge/software/atom/pages.js
//页面数组
var pages = [
{ title:"概要", url:"pages/1.html" },
];
<file_sep>/pages/knowledge/web_developer/javascript_summary/pages.js
//页面数组
var pages = [
{ title:"属性预览",url:"pages/1.html"},
{ title:"基础入门", url:"pages/2.html" },
{ title:"对象", url:"pages/3.html" },
{ title:"正则表达式", url:"pages/4.html" },
];
<file_sep>/pages/knowledge/web_developer/html_summary/pages/1_creating_html.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="/WZZ_ZONE/pages/summary.css">
<title></title>
</head>
<body>
<pre class="w_doc">
<h1 class="h1">全局属性</h1>
全局属性,用来配置所有元素共有的行为。
<b>+ accesskey属性</b>
使用该属性可以设定一个或几个用来选择页面上的元素的快捷键。
代码:
<xmp class="block">
Name:<input type="text" name="name" accesskey="n">
</xmp>
演示:
<div class="demo">
Name:<input type="text" name="name" accesskey="n">
</div>
现在按下<kbd>Alt+N</kbd>可将焦点转移到input元素上。
<b>+ class属性</b>
该属性用来将元素归类。
<b>+ contenteditable属性</b>
该属性是HTML5中新增加的属性,其用途是让用户能够修改页面上的内容。
代码:
<xmp class="block">
<p contenteditable="true">这里的内容可以直接在网页上修改。</p>
</xmp>
演示:
<div class="demo">
<p contenteditable="true">这里的内容可以直接在网页上修改。</p>
</div>
<b>+ dir属性</b>
该属性用来规定元素中文字的方向。
其有效值有两个:ltr(用于从左到右)和rtl(用于从右到左)。
代码:
<xmp class="block">
<p dir="ltr">ltr(用于从左到右)</p>
<p dir="rtl">rtl(用于从右到左)</p>
</xmp>
演示:
<div class="demo">
<p dir="ltr">ltr(用于从左到右)</p>
<p dir="rtl">rtl(用于从右到左)</p>
</div>
这里rtl的显示出现了一点偏差,后面的讲到的bdi元素会解决这个问题。
<b>+ draggable属性</b>
该属性用来表示元素是否可以被拖放。
有三个允许的值:
1. true:此元素能被拖动。
2. false:此元素不能被拖动。
3. auto:浏览器可以自主决定某个元素是否能被拖动。(默认)
代码:
<xmp class="block">
<div id="src" draggable="true" style="width:50px;height:50px;background:red"></div>
<div id="target" style="width:100px;height:50px;border:1px solid black;"></div>
<script type="text/javascript">
var src = document.getElementById("src");
var target = document.getElementById("target");
//ondragenter,ondragover的默认行为是拒绝接受任何被拖动的项目,阻止默认行为让他可以接受。
target.ondragenter = function(e){e.preventDefault();};
target.ondragover = function(e){e.preventDefault();};
target.ondrop = function(e)
{
//如果要克隆出一个新的元素的话就取消注释下面代码
// var newElem = src.cloneNode(false);
target.appendChild(src);
//阻止默认行为是为了防止浏览器做出出乎意料的事。
e.preventDefault();
};
</script>
</xmp>
演示:
<div class="demo">
<div id="src" draggable="true" style="width:50px;height:50px;background:red"></div>
<div id="target" style="width:100px;height:50px;border:1px solid black;"></div>
<script class="execute_fun" type="text/javascript">
var src = document.getElementById("src");
var target = document.getElementById("target");
target.ondragenter = function(e){e.preventDefault();};
target.ondragover = function(e){e.preventDefault();};
target.ondrop = function(e)
{
target.appendChild(src);
e.preventDefault();
};
</script>
</div>
<b>+ hidden属性</b>
hidden是个布尔属性,表示相关元素当前毋须关注,浏览器对它的处理是<xmp>display:none;</xmp>
<b>+ id属性</b>
id属性用来分配一个唯一的标识符。
<b>+ lang属性</b>
用于说明元素内容使用的语言。
<b>+ spellcheck属性</b>
用来表明浏览器是否应该对元素的内容进行拼写检查,这个属性只有用在用户可以编辑的元素上时才有意义。
<b>+ style属性</b>
用来直接在元素身上定义CSS样式。
<b>+ tabindex属性</b>
HTML页面上的键盘焦点可以通过按<kbd>Tab</kbd>键在各元素之间进行切换,tabindex可以改变默认的转移顺序。
代码:
<xmp class="block">
Name:<input type="text" name="name" tabindex="1">
City:<input type="text" name="city" tabindex="3">
<input type="submit" tabindex="2">
</xmp>
演示:
<div class="demo">
Name:<input type="text" name="name" tabindex="1">
City:<input type="text" name="city" tabindex="3">
<input type="submit" tabindex="2">
</div>
按下<kbd>Tab</kbd>键后tabindex值为1的会被第一个选中,然后往下类推。负数不会被选中。
<b>+ title属性</b>
该属性提供了元素的额外信息,浏览器通常用这些东西显示工具提示。
代码:
<xmp class="block">
<span title="这里是提示的内容">鼠标移到这里会显示title中的内容。</span>
</xmp>
演示:
<div class="demo">
<span title="这里是提示的内容">鼠标移到这里会显示title中的内容。</span>
</div>
<hr>
<h1 id="DOCTYPE" class="h1">DOCTYPE元素</h1>
DOCTYPE元素独一无二,而且自成一类。每一个HTML文档都必须以DOCTYPE元素开头。
浏览器据此得知自己将要处理的是HTML内容。
<h1 id="html" class="n1">html元素</h1>
html元素更恰当的名称是根元素,它代表文档中HTML部分的开始。
<h1 id="head" class="h1">head元素</h1>
head元素包含着文档的元素据。在HTML中,元素据向浏览器提供了有关文档内容和标记的信息。
此外还可以包含脚本和对外部资源的引用。
<h1 class="h1" id="body">body元素</h1>
html文档的元素据和文档信息包装在head元素中,文档的内容则包装在 body元素中。
<h1 class="h1" id="title">title元素</h1>
+ 允许具有的父元素:head
+ 局部属性:无
+ 示例:<xmp><title> ... </title></xmp>
title元素的作用是设置文档的标题或名称。浏览器通常将该元素的内容显示在其窗口的顶部或标签页的标签上。
每一个HTML文档都应该有且只有一个title元素。
<h1 class="h1" id="base">base元素</h1>
+ 允许具有的父元素:head
+ 局部属性:href、target
+ 示例:<xmp><base href="#" target="_blank"></xmp>
base元素可以用来设置一个基准URL,让HTML文档中的相对链接在此基础上进行解析。
此外,该元素还能设定链接在用户点击时的打开方式,以及提交表单时浏览器如何反应。
<h1 class="h1" id="meta">meta元素</h1>
+ 允许具有的父元素:head
+ 局部属性:name、content、charset、http-equiv
+ 示例:<xmp><meta charset="utf-8"></xmp>
meta元素可以用来定义文档的各种元数据,一个HTML文档中可以包含多个meta元素。
注意每个meta元素只能用于一种用途。
用法1:<xmp><meta name="author" content="WZZ"></xmp>
name属性用来表示元数据的类型,而content属性用来提供值。
用法2:<xmp><meta charset="utf-8"></xmp>
声明HTML文档内容所用的字符编码。
用法3:<xmp><meta http-equiv="refresh" content="5"></xmp>
<b>改写HTTP标头字段的值。</b>
+ refresh:
以秒为单位指定一个时间间隔,在此时间过去之后将从服务器重新载入当前页面。
也可以另行指定一个URL让浏览器载入。
如:<xmp><meta http-equiv="refresh" content="5;http://www.baidu.com"></xmp>
+ default-style:
指定页面优先使用的样式表。
对应的content属性值应与同一个文档中某个style元素或link元素的title属性值相同。
+ content-type:
这是另一种声明HTML页面所用字符编码的方法。
<h1 class="h1" id="style">style元素</h1>
+ 允许具有的父元素:任何可以包含元数据的元素
+ 局部属性:type、media、scoped
+ 示例:<xmp><style media="screen"> {...} </style></xmp>
style元素可以用来定义HTML文档内嵌的CSS样式。
1. 指定样式类型
type属性可以用来将所定义的样式类型告诉浏览器。
但是浏览器支持的样式机制只有CSS一种,所以这个属性的值总是text/css。
2. 指定样式作用范围
如果style元素中有scoped属性存在,那么其中定义的样式只作用于该元素的父元素及所有兄弟元素。
3. 指定样式使用的媒体
media属性可以用来表明文档在什么情况下应使用该元素中定义的样式。
用法:<xmp><style media="screen AND (max-width:500px)" type="text/css"> {...} </style></xmp>
+ all:将样式用于所有设备(默认)
+ screen:将样式用于计算机显示屏幕
+ print:将样式用于打印预览和打印页面时
+ tv:将样式用于电视机
AND用来组合设备和特性条件,除了AND,还可以使用NOT和表示OR的逗号<xmp>,</xmp>。
width等特性通常会跟限定词min和max配和使用。
+ width height:指定浏览器窗口的宽度和高度。单位:px。
+ device-width device-height:指定整个设备(而不仅仅是浏览器窗口)的宽度和高度。单位:px。
+ resolution:指定设备的像素密度。单位:dpi、dpcm。
+ orientation:指定设备的较长边朝向。值:portrait、landscape。
<h1 class="h1" id="link">link元素</h1>
+ 允许具有的父元素:head、noscript
+ 局部属性:href、rel、hreflang、media、type、sizes
+ 示例:<xmp><link rel="stylesheet" href="/css/master.css"></xmp>
link元素可以用来在HTML文档和外部资源之间建立联系。
<b>局部属性说明</b>
+ href:指定link元素指向的资源的URL。
+ hreflang:说明所关联资源使用的语言。
+ media:说明所关联的内容用于哪种设备。
+ rel:说明文档与所关联资源的关系类型。
+ sizes:指定图标的大小。
+ type:指定所关联资源的MIME类型。
<h1 class="h1" id="script">script元素</h1>
+ 允许具有的父元素:可以包含元数据或短语元素的任何元素
+ 局部属性:type、src、defer、async、charset
+ 示例:<xmp><script src="..." charset="utf-8"></script></xmp>
script元素可以用来在页面中加入脚本,方式有在文档中定义脚本和引用外部文件中的脚本两种。
<b>局部属性说明</b>
+ type:表示所引用或定义的脚本的类型。
+ src:指定外部脚本文件的URL。
+ defer:告诉浏览器要等页面载入和解析完毕之后才能执行脚本。
+ async:异步执行脚本。
+ charset:说明外部脚本文件所用字符编码,只用与src属性一同使用。
<h1 class="h1" id="noscript">noscript元素</h1>
+ 允许具有的父元素:可以包含元数据或短语元素的任何元素
+ 局部属性:无
+ 示例:<xmp><noscript> ... </noscript></xmp>
noscript元素可以用来向禁用了JavaScript或浏览器不支持的JavaScript的用户显示一些内容。
还有一种用法是在浏览器不支持JavaScript时将其引至另一个URL。
<xmp class="block">
<noscript>
<meta http-equiv="refresh" content="0;http://">
</noscript>
</xmp>
</pre>
</body>
</html>
<file_sep>/pages/mistake/pages.js
//页面数组
var pages = [
{ title:"JavaScript", url:"pages/java_script.html" },
{ title:"Atom", url:"pages/atom.html" },
{ title:"CSS", url:"pages/css.html" },
];
|
6c7f7fab0831ccd3f97800122876bdc9584924f7
|
[
"JavaScript",
"HTML"
] | 9
|
JavaScript
|
MrWZZ/WZZ_ZONE
|
72dad1333a70c143f87d630fd074004c1ca9da6f
|
788d6ccc036dd66b60397d7d17dcc330dd237a68
|
refs/heads/master
|
<repo_name>antoniojunior52/estrutura-repeticao-array-junior<file_sep>/Ativ3/Program.cs
using System;
namespace Ativ3
{
internal class NewBaseType
{
static void Main(string[] args)
{
int salario;
Console.WriteLine("Informe seu salário:");
salario = Convert.ToInt16(Console.ReadLine());
if (salario <= 1100)
{
double v = 0.075 * salario;
double g = salario - v;
Console.WriteLine($"Seu salario descontado do INSS é {g} reais");
}
else if (salario >= 1100.01 & salario <= 2003.48)
{
double h = 0.09 * salario;
double i = salario - h;
Console.WriteLine($"Seu salario descontado do INSS é {i} reais");
}
else if (salario >= 2003.49 & salario <= 3305.22)
{
double j = 0.12 * salario;
double m = salario - j;
Console.WriteLine($"Seu salario descontado do INSS é {m} reais");
}
else if (salario >= 3305.23 & salario <= 6433.57)
{
double d = 0.14 * salario;
double a = salario - d;
Console.WriteLine($"Seu salario descontadoo do INSS é {a} reais");
}
}
}
}
|
28d5ea2466a219f1abd53f3e59c60c9d5ea9d034
|
[
"C#"
] | 1
|
C#
|
antoniojunior52/estrutura-repeticao-array-junior
|
181bbb86e4ef17fe5e7cc5aa4b104ccfc71c266b
|
d658dfc98f1f11947b066635f34762dcda307088
|
refs/heads/master
|
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using raspberry_api.Models;
namespace raspberry_api.Controllers
{
[Route("api/[controller]")]
public class TemperaturesController : Controller
{
private readonly TemperaturesContext _context;
public TemperaturesController(TemperaturesContext context)
{
_context = context;
}
// GET api/values
[HttpGet]
public IEnumerable<Reading> Get()
{
return _context.Readings.ToList();
}
[HttpPost]
public IActionResult Post([FromBody]Reading value)
{
_context.Readings.Add(value);
_context.SaveChanges();
return StatusCode(201, value);
}
}
}<file_sep>using System;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
namespace raspberry_api.Models
{
public class TemperaturesContext : DbContext
{
public TemperaturesContext(DbContextOptions options) : base(options)
{}
protected override void OnModelCreating(ModelBuilder builder)
{
builder.Entity<Reading>().HasKey(x => x.Id);
builder.Entity<Reading>()
.Property(b => b.TimeStamp)
.HasDefaultValue(DateTime.Now);
base.OnModelCreating(builder);
}
public DbSet<Reading> Readings { get; set; }
}
public class Reading
{
public int Id { get; set; }
public float Temperature { get; set; }
public float Humidity { get; set; }
public DateTime TimeStamp { get; set; }
}
}<file_sep>using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using raspberry_api.Models;
namespace raspberryapi.Migrations
{
[DbContext(typeof(TemperaturesContext))]
partial class TemperaturesContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
modelBuilder
.HasAnnotation("ProductVersion", "1.1.2")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("raspberry_api.Models.Reading", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<float>("Humidity");
b.Property<float>("Temperature");
b.Property<DateTime>("TimeStamp")
.ValueGeneratedOnAdd()
.HasDefaultValue(new DateTime(2017, 7, 24, 10, 53, 16, 922, DateTimeKind.Local));
b.HasKey("Id");
b.ToTable("Readings");
});
}
}
}
|
0d3844d8106abae6dbcb07cc2da7a8d3e0c83ded
|
[
"C#"
] | 3
|
C#
|
stefana99/raspberry-api
|
b17a732c5ca6e761b0380aeb79ea0842b5d18ad6
|
8b4245036ca90ea1cff7d216c87659612a729d36
|
refs/heads/master
|
<file_sep>### 1066.Campus-Bikes-II
此题是著名的带权二分图的最优匹配问题,可由KM算法解决。在这里我们尝试用比较容易理解的搜索的方法来解决。
我们将“自行车被选取的状态”作为节点,状态之间的跳转理解为节点之间的相邻关系,状态之间的权重差就是相邻边的权重,就可以用Dijkstra算法了。举个例子,状态0110表示前两个工人(0号和1号)已经被配对1号和2号自行车的最优价值(即最小的配对距离之和)。注意,这个状态中我们不再区分前两个工人分别配对了哪辆自行车,我们不关心,我们只关心前两个工人的总和状态。状态0110可以转移到另外两种状态:如果2号工人选择0号自行车,即转移到了1110,权重的变化就是dist[2][2];如果2号工人选择3号自行车,即转移到了0111,权重的变化就是dist[3][2]。
我们的起点是全为0的state,终点是一个包含m个1(工人数目)的state,求其最短路径。至此,我们已经完全把这道题转化为了Dijkstra的模板了。BFS+PQ利用贪心法的思想就可以很容易解决:利用优先队列来进行BFS搜索,所有状态在队列里按照cost从小到大排序。如果某个状态第一次被PQ弹出,那么它对应的cost就是实现该状态的最优解。
[Leetcode Link](https://leetcode.com/problems/campus-bikes-ii)
<file_sep>class Solution {
int dist[10][10];
public:
int assignBikes(vector<vector<int>>& workers, vector<vector<int>>& bikes)
{
int m = workers.size();
int n = bikes.size();
for (int i=0; i<m; i++)
for (int j=0; j<n; j++)
{
int x1 = workers[i][0];
int y1 = workers[i][1];
int x2 = bikes[j][0];
int y2 = bikes[j][1];
dist[i][j] = abs(x1-x2)+abs(y1-y2);
}
vector<int>dp(1<<m, INT_MAX/2);
vector<int>dp2;
dp[0] = 0;
for (int j=0; j<n; j++)
{
dp2 = dp;
for (int state = 0; state < (1<<m); state++)
{
for (int i=0; i<m; i++)
{
if ((state >> i) &1)
dp[state] = min(dp[state], dp2[state- (1<<i)] + dist[i][j]);
}
}
}
return dp[(1<<m)-1];
}
};
|
9c5a2d26a36f820f8fc8f8516829f5d2eb7c0118
|
[
"Markdown",
"C++"
] | 2
|
Markdown
|
Yixiao99/LeetCode
|
51b87cf5b84196e7bd99295710a27fbbed53d9a7
|
270b7ed43b237dc813961cba1894196d84db44cd
|
refs/heads/main
|
<file_sep>use clap::{App, AppSettings, Arg};
use regex::Regex;
use rusqlite::{named_params, Connection, Result, NO_PARAMS};
use std::error;
// Regex pattern for query string
const PATTERN: &str = r"^(?P<book>\w+)( (?P<start_chapter>\d+)(:(?P<start_verse>\d+)(-((?P<end_chapter>\d+):)?(?P<end_verse>\d+))?)?)?$";
// Struct for capturing query parameters
struct Range<'t> {
book: &'t str,
start_chapter: i32,
end_chapter: i32,
start_verse: i32,
end_verse: i32,
}
fn main() -> Result<(), Box<dyn error::Error>> {
// Generate and capture usage
let matches = App::new("dra-cli")
.setting(AppSettings::ArgRequiredElseHelp)
.setting(AppSettings::TrailingVarArg)
.version("0.1.0")
.about("Command-line interface for Douay-Rheims American Bible")
.arg(
Arg::new("books")
.short('b')
.long("books")
.takes_value(false)
.about("Lists the available books"),
)
.arg(
Arg::new("QUERY")
.required(true)
.conflicts_with("books")
.takes_value(true)
.multiple(true)
.about("Query string:\n\t<book code> <chapter>:<verse>\n\t<book code> <chapter>:<start_verse>-<end_verse>\n\t<book code> <chapter>:<start_verse>-<end_chapter>:<end_verse>"),
)
.get_matches();
// If -b then list books
if matches.is_present("books") {
return list_books();
}
// If query present then try to print verses
if matches.is_present("QUERY") {
let query_list: Vec<&str> = matches
.values_of("QUERY")
.ok_or("No query string")?
.collect();
let query = &query_list.join(" ");
// Capture query parameters or return error if invalid
let range = parse_query(query)?;
// Print verses based on range
return print_verses(&range);
}
Ok(())
}
// Lists the books in books table
fn list_books() -> Result<(), Box<dyn error::Error>> {
let conn = Connection::open("dra.db")?;
println!("The following books are available:");
let mut stmt = conn.prepare("SELECT code, long FROM books")?;
let mut rows = stmt.query(NO_PARAMS)?;
while let Some(row) = rows.next()? {
println!(
"\t{}\t{}",
row.get::<usize, Box<str>>(0)?,
row.get::<usize, Box<str>>(1)?
);
}
Ok(())
}
// Parses query using regex
// Returns captured parameters if query valid, error otherwise
fn parse_query(query: &str) -> Result<Range, Box<dyn error::Error>> {
let pattern = Regex::new(PATTERN)?;
let capture = pattern.captures(query).ok_or("Invalid query string")?;
let book = capture
.name("book")
.ok_or("Query string does not contain book")?
.as_str();
let start_chapter = capture
.name("start_chapter")
.ok_or("Query string does not contain chapter")?
.as_str()
.trim()
.parse()?;
let end_chapter = match capture.name("end_chapter") {
Some(ch2) => ch2.as_str().trim().parse()?,
None => start_chapter,
};
let start_verse_present: bool;
let start_verse = match capture.name("start_verse") {
Some(v1) => {
start_verse_present = true;
v1.as_str().trim().parse()?
},
None => {
start_verse_present = false;
1
},
};
let end_verse = match capture.name("end_verse") {
Some(v2) => v2.as_str().trim().parse()?,
None if start_verse_present => start_verse,
_ => 200
};
Ok(Range {
book,
start_chapter,
end_chapter,
start_verse,
end_verse,
})
}
// Prints verses based on range
fn print_verses(range: &Range) -> Result<(), Box<dyn error::Error>> {
if range.end_chapter < range.start_chapter {
Err("Query range invalid: end_chapter precedes start_chapter")?
} else if range.end_chapter == range.start_chapter && range.end_verse < range.start_verse {
Err("Query range invalid: end_verse precedes start_verse")?
}
let conn = Connection::open("dra.db")?;
let mut stmt = conn.prepare("SELECT chapter, startVerse, verseText FROM engDRA_vpl WHERE rowid BETWEEN (SELECT MIN(rowid) FROM engDRA_vpl WHERE book = :book AND chapter >= :start_chapter AND startVerse >= :start_verse) AND (SELECT MAX(rowid) FROM engDRA_vpl WHERE book = :book AND chapter <= :end_chapter AND startVerse <= :end_verse)")?;
let mut rows = stmt.query_named(named_params!{":book":range.book, ":start_chapter":range.start_chapter, ":end_chapter":range.end_chapter, ":start_verse":range.start_verse, ":end_verse":range.end_verse})?;
while let Some(row) = rows.next()? {
println!(
"{:7} {}",
format!(
"{}:{}",
row.get::<usize, i32>(0)?,
row.get::<usize, i32>(1)?
),
row.get::<usize, Box<str>>(2)?
);
}
Ok(())
}
<file_sep>[package]
name = "dra-cli"
version = "0.1.0"
authors = ["sullivandj"]
edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
clap = "3.0.0-beta.2"
regex = "1.4.3"
[dependencies.rusqlite]
version = "0.24.2"
features = ["bundled"]<file_sep># dra-cli
Command line app to read DRA Bible
Steps to run:
cargo build --release
./target/release/dra-cli.exe [FLAGS] <QUERY>
USAGE:
dra-cli.exe [FLAGS] <QUERY>...
ARGS:
 <QUERY>... Query string:
  <book code> <chapter>:<verse>
  <book code> <chapter>:<start_verse>-<end_verse>
  <book code> <chapter>:<start_verse>-<end_chapter>:<end_verse>
FLAGS:
 -b, --books Lists the available books
 -h, --help Prints help information
 -V, --version Prints version information
|
3a95d98d1538bd0ac7724c072f0b9d87d64f7ec8
|
[
"TOML",
"Rust",
"Markdown"
] | 3
|
Rust
|
ds411/dra-cli
|
27ab6fbf628b11bf5aaaa315b75f614aa7338950
|
97f02b206e21c5ad33c30ffd14c6cef48d2bfddc
|
refs/heads/main
|
<repo_name>rolandvarga/rename-tool<file_sep>/main.go
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"os"
"strings"
)
var (
dir = "/Volumes/stuff/tv/Batman_The_Animated_Series_1992"
)
type final struct {
Files []outputFile `json:"files"`
}
type outputFile struct {
Episode string `json:"episode"`
Title string `json:"title"`
Season int `json:"season"`
}
func main() {
sample, err := os.Open("sample.json")
if err != nil {
fmt.Println(err)
os.Exit(1)
}
defer sample.Close()
content, err := ioutil.ReadAll(sample)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
finalF := &final{}
err = json.Unmarshal(content, finalF)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
for _, f := range finalF.Files {
fmt.Println(f.Title)
}
files, err := ioutil.ReadDir(dir)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
count := 0
match := 0
for _, f := range files {
count++
for _, final := range finalF.Files {
if strings.Contains(f.Name(), final.Title) {
match++
fmt.Println("***")
oldName := fmt.Sprintf("%s/%s", dir, f.Name())
newName := fmt.Sprintf("%s/%s - %s.mkv", dir, final.Episode, final.Title)
fmt.Println(oldName)
fmt.Println(newName)
err := os.Rename(oldName, newName)
if err != nil {
fmt.Println(err)
continue
}
}
}
}
fmt.Printf("Total count: %d\nTotal match: %d\n", count, match)
}
|
29884c422890b04949479d1c050ab10ad71bf91f
|
[
"Go"
] | 1
|
Go
|
rolandvarga/rename-tool
|
0819bb4f5b484c3a6192a9d68374abafc6491b46
|
657cd2d4f7d2c37b2837f14d7266e8741a8af57e
|
refs/heads/master
|
<file_sep>const aes256 = require('aesencryption256');
console.log(aes256("testthescript"));<file_sep># Aes256EncryptionPackage
A aes256 package where only pass the value to encrypt in AES256 form and it will convert same as online tool available as PFL. https://www.devglan.com/online-tools/aes-encryption-decryption
# Using NPM
$ npm aesencryption256
# Run the node file for example test.js
|
a162edc5a59b549410c982d1be49b29097a5e155
|
[
"JavaScript",
"Markdown"
] | 2
|
JavaScript
|
shubhamJ0/Aes256EncryptionPackage
|
92220f1f05ad9328736dc1e166867b15cec83a21
|
9c31fb44d85f967e9a18a93805f0b302899d7d15
|
refs/heads/master
|
<repo_name>shizunaito/ReactorKitSample<file_sep>/ReactorKitSample/Error/GitHubClientError.swift
//
// GitHubClientError.swift
// ReactorKitSample
//
// Created by 伊藤静那(<NAME>) on 2018/02/25.
// Copyright © 2018年 ShizunaIto. All rights reserved.
//
enum GitHubClientError : Error {
case connectionError(Error)
case responseParseError(Error)
case apiError(GitHubAPIError)
}
<file_sep>/ReactorKitSampleTests/MockGitHubService.swift
//
// MockGitHubService.swift
// ReactorKitSampleTests
//
// Created by 伊藤静那(<NAME>) on 2018/02/25.
// Copyright © 2018年 ShizunaIto. All rights reserved.
//
@testable import ReactorKitSample
import RxSwift
import RxTest
class MockGitHubService: GitHubServiceType {
func serach(query: String?, page: Int) -> Observable<(repos: [String], nextPage: Int?)> {
let emptyResult: ([String], Int?) = ([], nil)
guard let query = query else {
return Observable.just(emptyResult)
}
let result: ([String], Int?) = ([query], page + 1)
return Observable.just(result)
}
}
<file_sep>/ReactorKitSample/Response/Reqository.swift
//
// Reqository.swift
// ReactorKitSample
//
// Created by 伊藤静那(<NAME>) on 2018/02/25.
// Copyright © 2018年 ShizunaIto. All rights reserved.
//
struct Repository : Decodable {
let id: Int
let name: String
let fullName: String
let owner: User
enum CodingKeys : String, CodingKey {
case id
case name
case fullName = "full_name"
case owner
}
}
<file_sep>/ReactorKitSample/GitHubClient.swift
//
// GitHubClient.swift
// ReactorKitSample
//
// Created by 伊藤静那(<NAME>) on 2018/02/25.
// Copyright © 2018年 ShizunaIto. All rights reserved.
//
import Foundation
import RxSwift
class GitHubClient {
static func send<Request : GitHubRequest>(request: Request) -> Single<Request.Response> {
return Single.create(subscribe: { observer -> Disposable in
let session = URLSession(configuration: URLSessionConfiguration.default)
let urlRequest = request.buildURLRequest()
let task = session.dataTask(with: urlRequest) {
(data, response, error) in
switch (data, response, error) {
case (_, _, let error?):
observer(.error(GitHubClientError.connectionError(error)))
case (let data?, let response?, _):
do {
let response = try request.response(from: data, urlResponse: response)
observer(.success(response))
} catch let error as GitHubAPIError {
observer(.error(GitHubClientError.apiError(error)))
} catch {
observer(.error(GitHubClientError.responseParseError(error)))
}
default:
fatalError("Invalid response combination \(data), \(response), \(error).")
}
}
task.resume()
return Disposables.create {
session.invalidateAndCancel()
}
})
}
// static func send<Request : GitHubRequest>(request: Request,
// completion: @escaping (Result<Request.Response, GitHubClientError>) -> Void) {
// let session = URLSession(configuration: URLSessionConfiguration.default)
// let urlRequest = request.buildURLRequest()
// let task = session.dataTask(with: urlRequest) {
// data, response, error in
//
// switch (data, response, error) {
// case (_, _, let error?):
// completion(Result(error: .connectionError(error)))
// case (let data?, let response?, _):
// do {
// let response = try request.response(from: data, urlResponse: response)
// completion(Result(value: response))
// } catch let error as GitHubAPIError {
// completion(Result(error: .apiError(error)))
// } catch {
// completion(Result(error: .responseParseError(error)))
// }
// default:
// fatalError("Invalid response combination \(data), \(response), \(error).")
// }
// }
// task.resume()
// }
}
<file_sep>/ReactorKitSample/Response/SearchResponse.swift
//
// SearchResponse.swift
// ReactorKitSample
//
// Created by 伊藤静那(I<NAME>) on 2018/02/25.
// Copyright © 2018年 ShizunaIto. All rights reserved.
//
struct SearchResponse<Item : Decodable> : Decodable {
let totalCount: Int
let items: [Item]
enum codingKeys : String, CodingKey {
case totalCount = "total_count"
case items
}
}
<file_sep>/ReactorKitSample/Error/GitHubAPIError.swift
//
// GitHubAPIError.swift
// ReactorKitSample
//
// Created by 伊藤静那(<NAME>) on 2018/02/25.
// Copyright © 2018年 ShizunaIto. All rights reserved.
//
struct GitHubAPIError : Decodable, Error {
struct FieldError : Decodable {
let resource: String
let field: String
let code: String
}
let message: String
let fieldErrors: [FieldError]
}
<file_sep>/ReactorKitSample/Response/User.swift
//
// User.swift
// ReactorKitSample
//
// Created by 伊藤静那(I<NAME>) on 2018/02/25.
// Copyright © 2018年 ShizunaIto. All rights reserved.
//
struct User : Decodable {
let id: Int
let login: String
}
<file_sep>/ReactorKitSample/GitHubService.swift
//
// GitHubService.swift
// ReactorKitSample
//
// Created by 伊藤静那(<NAME>) on 2018/02/23.
// Copyright © 2018年 ShizunaIto. All rights reserved.
//
import RxSwift
import RxCocoa
protocol GitHubServiceType {
func serach(query: String?, page: Int) -> Observable<(repos: [String], nextPage: Int?)>
}
final class GitHubService: GitHubServiceType {
var disposeBag = DisposeBag()
private func url(for query: String?, page: Int) -> URL? {
guard let query = query, !query.isEmpty else { return nil }
return URL(string: "https://api.github.com/search/repositories?q=\(query)&page=\(page)")
}
func serach(query: String?, page: Int) -> Observable<(repos: [String], nextPage: Int?)> {
let request = GitHubAPI.SearchRepositories(keyword: "aaa")
GitHubClient.send(request: request)
.subscribe { observer in
switch observer {
case let .success(response):
for item in response.items {
print(item.fullName)
}
case let .error(error):
print(error)
}
}
.disposed(by: disposeBag)
let emptyResult: ([String], Int?) = ([], nil)
guard let url = self.url(for: query, page: page) else { return Observable.just(emptyResult) }
return URLSession.shared.rx.json(url: url)
.map { json -> ([String], Int?) in
guard let dict = json as? [String : Any] else { return emptyResult }
guard let items = dict["items"] as? [[String : Any]] else { return emptyResult }
let repos = items.flatMap { $0["full_name"] as? String}
let nextPage = repos.isEmpty ? nil : page + 1
return(repos, nextPage)
}
.do(onError: { error in
if case let .some(.httpRequestFailed(response, _)) = error as? RxCocoaURLError, response.statusCode == 403 {
print("warning")
}
})
.catchErrorJustReturn(emptyResult)
}
}
<file_sep>/ReactorKitSample/GitHubSeachViewReactor.swift
//
// GitHubSeachViewReactor.swift
// ReactorKitSample
//
// Created by 伊藤静那(<NAME>) on 2018/02/21.
// Copyright © 2018年 ShizunaIto. All rights reserved.
//
import ReactorKit
import RxCocoa
import RxSwift
class GitHubSeachViewReactor: Reactor {
enum Action {
case updateQuery(String?)
case loadNextPage
}
enum Mutation {
case setQuery(String?)
case setRepos([String], nextPage: Int?)
case appendRepos([String], nextPage: Int?)
case setLoadingNextPage(Bool)
}
struct State {
var quary: String?
var repos: [String] = []
var nextPage: Int?
var isLoadingNextPage = false
}
let initialState = State()
private let gitHubService: GitHubServiceType
init(gitHubService: GitHubServiceType) {
self.gitHubService = gitHubService
}
func mutate(action: Action) -> Observable<Mutation> {
switch action {
case .updateQuery(let query):
return Observable.concat([
Observable.just(Mutation.setQuery(query)),
self.gitHubService.serach(query: query, page: 1)
.takeUntil(self.action.filter(isUpdateQueryAction))
.map { Mutation.setRepos($0, nextPage: $1) }
])
case .loadNextPage:
guard !self.currentState.isLoadingNextPage else { return Observable.empty() }
guard let page = self.currentState.nextPage else { return Observable.empty() }
return Observable.concat([
Observable.just(Mutation.setLoadingNextPage(true)),
self.gitHubService.serach(query: self.currentState.quary, page: page)
.takeUntil(self.action.filter(isUpdateQueryAction))
.map { Mutation.appendRepos($0, nextPage: $1) },
Observable.just(Mutation.setLoadingNextPage(false))
])
}
}
func reduce(state: State, mutation: Mutation) -> State {
switch mutation {
case let .setQuery(query):
var newState = state
newState.quary = query
return newState
case let .setRepos(repos, nextPage):
var newState = state
newState.repos = repos
newState.nextPage = nextPage
return newState
case let .appendRepos(repos, nextPage):
var newState = state
newState.repos.append(contentsOf: repos)
newState.nextPage = nextPage
return newState
case let .setLoadingNextPage(isLoadingNextPage):
var newState = state
newState.isLoadingNextPage = isLoadingNextPage
return newState
}
}
private func isUpdateQueryAction(_ action: Action) -> Bool {
if case .updateQuery = action {
return true
} else {
return false
}
}
}
<file_sep>/ReactorKitSampleTests/GitHubSearchViewControllerTests.swift
//
// GitHubSearchViewControllerTests.swift
// ReactorKitSampleTests
//
// Created by 伊藤静那(<NAME>) on 2018/02/25.
// Copyright © 2018年 ShizunaIto. All rights reserved.
//
import XCTest
@testable import ReactorKitSample
class GitHubSearchViewControllerTests: XCTestCase {
var viewController = GitHubSearchViewController()
override func setUp() {
super.setUp()
let storyboard = UIStoryboard(name: "Main", bundle: nil)
viewController = storyboard.instantiateViewController(withIdentifier: "GitHubSearchViewController") as! GitHubSearchViewController
viewController.loadViewIfNeeded()
}
override func tearDown() {
super.tearDown()
}
func testState_repos() {
let reactor = GitHubSeachViewReactor(gitHubService: MockGitHubService())
reactor.stub.isEnabled = true
viewController.reactor = reactor
reactor.stub.state.value = GitHubSeachViewReactor.State(quary: "", repos: ["aaa", "bbb"], nextPage: 0, isLoadingNextPage: false)
XCTAssertEqual(viewController.tableView.visibleCells.first?.textLabel?.text, "aaa")
}
}
<file_sep>/ReactorKitSampleTests/GitHubSeachViewReactorTest.swift
//
// GitHubSeachViewReactorTest.swift
// GitHubSeachViewReactorTest
//
// Created by 伊藤静那(<NAME>) on 2018/02/25.
// Copyright © 2018年 ShizunaIto. All rights reserved.
//
import XCTest
@testable import ReactorKitSample
class GitHubSeachViewReactorTest: XCTestCase {
func testUpdateQuery() {
let reactor = GitHubSeachViewReactor(gitHubService: MockGitHubService())
reactor.action.onNext(.updateQuery("aaa"))
XCTAssertEqual(reactor.currentState.quary, "aaa")
}
func testLoadNextPage() {
let reactor = GitHubSeachViewReactor(gitHubService: MockGitHubService())
reactor.action.onNext(.loadNextPage)
XCTAssertEqual(reactor.currentState.isLoadingNextPage, false)
}
}
|
ee2bda3904e59455c4b8079ac3a13006e5b1b8ba
|
[
"Swift"
] | 11
|
Swift
|
shizunaito/ReactorKitSample
|
c6f7ce47122985cf990328d9c311ed3e9507539f
|
5dfd65586330533c0d6adea478bc50e3c82f760a
|
refs/heads/master
|
<file_sep>package com.camilo.anotacoes.service.exception;
public class CategoriaJaCadastradaException extends RuntimeException {
private static final long serialVersionUID = 1L;
public CategoriaJaCadastradaException(String message) {
super(message);
}
}<file_sep>var Notesware = Notesware || {};
Notesware.AdicionaGrupo = (function() {
function AdicionaGrupo() {
this.botaoAdicionarGrupo = $('.js-adiciona-grupo');
this.painelAdicionaGrupo = $('.panel-default');
}
AdicionaGrupo.prototype.enable = function() {
this.botaoAdicionarGrupo.on('click', onBotaoAdicionarGrupoClick.bind(this));
}
function onBotaoAdicionarGrupoClick() {
this.painelAdicionaGrupo.toggleClass('hidden');
}
return AdicionaGrupo;
})();
$(function() {
var adicionaGrupo = new Notesware.AdicionaGrupo();
adicionaGrupo.enable();
});<file_sep>package com.camilo.anotacoes.service.exception;
public class GrupoJaCadastradoException extends RuntimeException {
private static final long serialVersionUID = 1L;
public GrupoJaCadastradoException(String message) {
super(message);
}
}<file_sep>package com.camilo.anotacoes.service;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.camilo.anotacoes.model.Categoria;
import com.camilo.anotacoes.repository.Categorias;
import com.camilo.anotacoes.service.exception.CategoriaJaCadastradaException;
@Service
public class CadastroCategoriaService {
@Autowired
private Categorias categorias;
@Transactional
public Categoria salvar(Categoria categoria) {
Optional<Categoria> categoriaOptional = categorias.findByNomeIgnoreCase(categoria.getNome());
if (categoriaOptional.isPresent()) {
throw new CategoriaJaCadastradaException("Esta categoria já está cadastrada!");
}
return categorias.saveAndFlush(categoria);
}
}
<file_sep>var Notesware = Notesware || {};
Notesware.GrupoCadastroRapido = (function() {
function GrupoCadastroRapido() {
this.modal = $('#modalCadastroRapidoGrupo');
this.botaoSalvar = this.modal.find('.js-modal-cadastro-grupo-salvar-btn');
this.form = this.modal.find('form');
this.url = this.form.attr('action');
this.inputNomeGrupo = $('#nomeGrupo');
this.containerMensagemErro = $('.js-mensagem-cadastro-rapido-grupo');
}
GrupoCadastroRapido.prototype.iniciar = function() {
this.form.on('submit', function(event) { event.preventDefault() });
this.modal.on('shown.bs.modal', onModalShow.bind(this));
this.modal.on('hide.bs.modal', onModalClose.bind(this))
this.botaoSalvar.on('click', onBotaoSalvarClick.bind(this));
}
function onModalShow() {
this.inputNomeGrupo.focus();
}
function onModalClose() {
this.inputNomeGrupo.val('');
this.containerMensagemErro.addClass('hidden');
this.form.find('.form-group').removeClass('has-error');
}
function onBotaoSalvarClick() {
var nomeGrupo = this.inputNomeGrupo.val().trim();
$.ajax({
url : this.url,
method : 'POST',
contentType : 'application/json',
data : JSON.stringify({
nome : nomeGrupo
}),
error : onErroSalvandoGrupo.bind(this),
success : onGrupoSalvo.bind(this)
});
}
function onErroSalvandoGrupo(obj) {
var mensagemErro = obj.responseText;
this.containerMensagemErro.removeClass('hidden');
this.containerMensagemErro.html('<span>' + mensagemErro + '</span>');
this.form.find('.form-group').addClass('has-error');
}
function onGrupoSalvo(grupo) {
var comboGrupo = $('#grupo');
comboGrupo.append('<option value=' + grupo.codigo + '>' + grupo.nome
+ '</option>');
comboGrupo.val(grupo.codigo);
this.modal.modal('hide');
}
return GrupoCadastroRapido;
})();
$(function() {
var grupoCadastroRapido = new Notesware.GrupoCadastroRapido();
grupoCadastroRapido.iniciar();
});
<file_sep>CREATE TABLE categoria (
codigo BIGINT(20) PRIMARY KEY AUTO_INCREMENT,
nome VARCHAR(50) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE grupo (
codigo BIGINT(20) PRIMARY KEY AUTO_INCREMENT,
nome VARCHAR(50) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE lembrete (
codigo BIGINT(20) PRIMARY KEY AUTO_INCREMENT,
titulo VARCHAR(80) NOT NULL,
descricao TEXT NOT NULL,
codigo_categoria BIGINT(20) NOT NULL,
codigo_grupo BIGINT(20),
ordem INTEGER,
data_cadastro DATE,
FOREIGN KEY (codigo_categoria) REFERENCES categoria(codigo),
FOREIGN KEY (codigo_grupo) REFERENCES grupo(codigo)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO categoria VALUES (0, 'Spring');
INSERT INTO categoria VALUES (0, 'Angular');
INSERT INTO grupo VALUES (0, 'Configuração projeto Eclipse-Spring');
INSERT INTO grupo VALUES (0, 'Configuração projeto Angular');
<file_sep>var Notesware = Notesware || {};
Notesware.MaskMoney = (function() {
function MaskMoney() {
this.ordem = $('.js-ordem');
}
MaskMoney.prototype.enable = function() {
this.ordem.maskMoney({ precision: 0, thousands: '.', allowZero: true, allowNegative: true });
}
return MaskMoney;
})();
$(function() {
var maskMoney = new Notesware.MaskMoney();
maskMoney.enable();
});<file_sep>package com.camilo.anotacoes.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.camilo.anotacoes.model.Categoria;
import com.camilo.anotacoes.service.CadastroCategoriaService;
import com.camilo.anotacoes.service.exception.CategoriaJaCadastradaException;
@Controller
@RequestMapping("/categorias")
public class CategoriasController {
@Autowired
private CadastroCategoriaService cadastroCategoriaService;
@GetMapping(value = "/novo")
public ModelAndView novo(Categoria categoria) {
return new ModelAndView("categoria/CadastroCategoria");
}
@PostMapping(value = "/novo")
public ModelAndView cadastrar(@Validated Categoria categoria, BindingResult result, Model model, RedirectAttributes attr) {
if (result.hasErrors()) {
return novo(categoria);
}
try {
cadastroCategoriaService.salvar(categoria);
} catch (CategoriaJaCadastradaException e) {
result.rejectValue("nome", e.getMessage(), e.getMessage());
return novo(categoria);
}
attr.addFlashAttribute("mensagem", "Categoria salva com sucesso!");
return new ModelAndView("redirect:/categorias/novo");
}
@PostMapping(consumes = { MediaType.APPLICATION_JSON_VALUE })
public @ResponseBody ResponseEntity<?> salvar(@RequestBody @Validated Categoria categoria, BindingResult result) {
if (result.hasErrors()) {
return ResponseEntity.badRequest().body(result.getFieldError("nome").getDefaultMessage());
}
categoria = cadastroCategoriaService.salvar(categoria);
return ResponseEntity.ok(categoria);
}
}
|
54f9ccf11716c38df65528ff60cd63c198053184
|
[
"JavaScript",
"Java",
"SQL"
] | 8
|
Java
|
craitz/Notesware
|
2ea4b18fe082de33b7d2053a8c5c8d2ebb7d0a76
|
9d0d66051aacba091b8f7eaac3d43039f79f3077
|
refs/heads/master
|
<file_sep>from pathlib import Path
from ..base.report import BaseSummaryHomeStage, BaseReport
from ..base.fastqc import FastQCStage
from . import RNASeqStageMixin, here
from .star import STARStage
from .cufflinks import CufflinksStage
from .cuffdiff import CuffdiffStage
class RNASeqFastQCStage(RNASeqStageMixin, FastQCStage):
template_entrances = ['rna_seq/fastqc.html']
class RNASeqSummaryHomeStage(RNASeqStageMixin, BaseSummaryHomeStage):
template_entrances = ['rna_seq/index.html']
class RNASeqReport(BaseReport):
stage_classes = [
RNASeqSummaryHomeStage,
RNASeqFastQCStage,
STARStage,
CufflinksStage,
CuffdiffStage,
]
static_roots = [
here / 'static',
*BaseReport.static_roots,
]
<file_sep>from pathlib import Path
from bc_report.info import AnalysisInfo
from bc_report import create_logger
from ..base.report import BaseStage
from . import RNASeqStageMixin
logger = create_logger(__name__)
class CuffdiffStage(RNASeqStageMixin, BaseStage):
template_entrances = ['rna_seq/cuffdiff.html']
result_folder_name = 'cuffdiff'
def parse(self, analysis_info: AnalysisInfo):
data_info = super().parse(analysis_info)
data_info['raw_output'] = self.collect_raw_output(analysis_info)
return data_info
def collect_raw_output(self, analysis_info: AnalysisInfo):
"""Render the link to the raw output files"""
raw_output_filenames = [
# isoform
'isoform_exp.diff',
'isoforms.count_tracking',
'isoforms.fpkm_tracking',
'isoforms.read_group_tracking',
# gene
'gene_exp.diff',
'genes.count_tracking',
'genes.fpkm_tracking',
'genes.read_group_tracking',
# cds
'cds_exp.diff',
'cds.count_tracking',
'cds.fpkm_tracking',
'cds.read_group_tracking',
# tss
'tss_group_exp.diff',
'tss_groups.count_tracking',
'tss_groups.fpkm_tracking',
'tss_groups.read_group_tracking',
# diff
'cds.diff',
'promoters.diff',
'splicing.diff',
# info
'run.info',
'read_groups.info',
'bias_params.info',
'var_model.info',
'run_cuffdiff.log',
]
actual_output_dir = self._locate_result_folder().name
raw_output_links = {
filename: '../result/{output_dir}/{filename}'.format(
output_dir=actual_output_dir,
filename=filename
)
for filename in raw_output_filenames
}
return raw_output_links
<file_sep>{% extends 'rna_seq/base.html' %}
{% block title %}Cufflinks{% endblock title %}
{% block nav %}
{% set active = "cufflinks" %}
{% include "rna_seq/_includes/nav.html" %}
{% endblock nav %}
{% block content %}
<h2>Cufflinks</h2>
<h2>Original output files</h2>
{% for condition, samples in analysis_info.conditions.items() %}
<h3>Condition: {{ condition }}</h3>
<table class="table table-striped">
<thead>
<tr>
<th>Sample</th>
<th>Inferred expression FPKM values (TSV)</th>
<th>Transcripts (GTF)</th>
<th>Log files</th>
</tr>
</thead>
<tbody>
{% for sample in samples %}
{% set file_links = data_info.raw_output[sample] %}
<tr>
<td>{{ sample }}</td>
<!-- Expression FPKM -->
<td>
{% for f in ['genes.fpkm_tracking', 'isoforms.fpkm_tracking'] %}
<a href="{{ file_links[f] }}">
<i class="fa fa-file-o" aria-hidden="true"></i>
<code>{{ f }}</code>
</a>{% if not loop.last %}<br>{% endif %}
{% endfor %}
</td>
<!-- Transcript.gtf -->
<td>
{% for f in ['transcripts.gtf', 'skipped.gtf'] %}
<a href="{{ file_links[f] }}">
<i class="fa fa-file-o" aria-hidden="true"></i>
<code>{{ f }}</code>
</a>{% if not loop.last %}<br>{% endif %}
{% endfor %}
</td>
<!-- Log files -->
<td>
{% for f in ['run_cufflinks.log'] %}
<a href="{{ file_links[f] }}">
<i class="fa fa-file-o" aria-hidden="true"></i>
<code>{{ f }}</code>
</a>{% if not loop.last %}<br>{% endif %}
{% endfor %}
</td>
</tr>
{% endfor %}
</tbody>
</table>
{% endfor %}
{% endblock content %}
<file_sep>from pathlib import Path
from bc_report.report import Report, Stage, SummaryStage
here = Path(__file__).parent
class BaseStage(Stage):
template_find_paths = [
here / 'templates',
]
class BaseSummaryHomeStage(SummaryStage):
template_entrances = ['base/index.html']
template_find_paths = [
here / 'templates',
]
class BaseReport(Report):
stage_classes = [BaseSummaryHomeStage]
static_roots = [
here / 'static',
]
<file_sep>import sys
import re
from os import path
from pathlib import Path
from setuptools import setup, find_packages
from codecs import open
here = path.abspath(path.dirname(__file__))
def utf8_open(*path_parts):
return open(path.join(*path_parts), encoding='utf-8')
def find_version(*path_parts):
with utf8_open(*path_parts) as f:
version_match = re.search(
r"^__version__ = ['\"]([^'\"]*)['\"]",
f.read(), re.M
)
if version_match:
return version_match.group(1)
raise RuntimeError("Unable to find version string.")
with utf8_open("README.md") as readme_f:
with utf8_open("CHANGELOG.md") as changes_f:
long_description = readme_f.read() + '\n' + changes_f.read()
# Recursively find all files under bc_pipelines/*/{static,templates}
package_data = {}
pipelines = list(Path('bc_pipelines').iterdir())
for pipeline in pipelines:
files = []
for folder in ['static', 'templates']:
files.extend(
p.relative_to(pipeline).as_posix()
for p in pipeline.glob('%s/**/*' % folder)
if p.name not in ['.DS_Store'] and not p.is_dir()
)
package_data[pipeline.as_posix().replace('/', '.')] = files
# Define package dependencies
pkg_deps = [
'PyYAML >= 3.11',
'Jinja2 >= 2.8',
'click >= 6.0',
]
if sys.platform.startswith("win32"):
color_dep = ['colorlog[windows]']
else:
color_dep = ['colorlog']
all_dep = []
for deps in [color_dep]:
all_dep.extend(deps)
setup(
name='bc_report',
version=find_version('bc_report', '__init__.py'),
license='MIT',
description='BioCloud report generator',
long_description=long_description,
author='<NAME>',
author_email='<EMAIL>',
url='https://github.com/ccwang002/bc_report',
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.5',
'Topic :: Scientific/Engineering :: Bio-Informatics',
],
keywords='ngs',
install_requires=pkg_deps,
extras_require={
':python_version=="3.3"': ['pathlib'],
'color': color_dep,
'all': all_dep,
},
packages=[
*find_packages(
include=['bc_report'],
exclude=[
'contrib', 'docs', 'examples',
'*.tests', '*.tests.*', 'tests.*', 'tests',
]
),
'bc_pipelines.base',
'bc_pipelines.rna_seq',
],
package_data=package_data,
zip_safe=False,
entry_points={
'console_scripts': [
'bc_report = bc_report.cli:generate_report_cli',
],
},
)
<file_sep>import importlib
import logging
from pathlib import Path
import shutil
import sys
import click
from . import create_logger
logger = create_logger(__name__)
CAVEAT_MESSAGE = '''\
New output result is under {!s}.
The folder can be downloaded and viewed locally.
Quick remainder for serving current folder through http:
$ python3 -m http.server
# Serving HTTP on 0.0.0.0 port 8000 ...
'''
def create_log_format(log_time, color):
color_log_fmt = (
'%(log_color)s%(levelname)-7s%(reset)s %(cyan)s%(name)-8s%(reset)s '
'%(log_color)s[%(funcName)s]%(reset)s %(message)s'
)
log_fmt = '[%(levelname)-7s][%(name)-8s][%(funcName)-8s] %(message)s'
if log_time:
color_log_fmt = '%(asctime)s ' + color_log_fmt
log_fmt = '[%(asctime)s]' + log_fmt
if color:
try:
import colorlog
log_formatter = colorlog.ColoredFormatter(
color_log_fmt,
'%Y-%m-%d %H:%M:%S',
log_colors=colorlog.default_log_colors
)
return log_formatter
except ImportError:
logger.warning(
"Color logs require colorlog, "
"try pip install colorlog or colorlog[windows] on Windows"
)
log_formatter = logging.Formatter(
log_fmt,
'%Y-%m-%d %H:%M:%S'
)
return log_formatter
ReadableAbsoluteFolderPath = click.Path(
exists=True,
dir_okay=True, file_okay=False,
readable=True,
resolve_path=True
)
@click.command(context_settings={
'help_option_names': ['-h', '--help']
})
@click.option(
'-v', '--verbose', count=True,
help='Increase verbosity (noiser when more -v)',
)
@click.option(
'--log-time/--no-log-time', default=False,
help='Add time stamp in log',
)
@click.option(
'--color/--no-color', default=True,
help='Produce colorful logs',
)
@click.option(
'-f', '--force/--no-force', default=False,
help='Overwrite the output folder if it exists',
)
@click.option(
'-p', '--pipeline',
metavar='bc_pipelines.mypipeline.report.Report',
help='Full path to the pipeline class',
required=True,
)
@click.argument('job_dir', type=ReadableAbsoluteFolderPath)
@click.argument('out_dir', type=click.Path(), default='./output')
def generate_report_cli(
pipeline, job_dir, out_dir,
verbose, log_time, color, force,
):
# Setup console logging
console = logging.StreamHandler()
all_loggers = logging.getLogger()
all_loggers.addHandler(console)
# Decide the logging level
if verbose == 1:
loglevel = logging.INFO
elif verbose >= 2:
loglevel = logging.DEBUG
else:
loglevel = logging.WARNING
all_loggers.setLevel(loglevel)
# Set log format
console.setFormatter(create_log_format(log_time, color))
logger.debug(
'Using pipeline: {} to parse job folder {} and generate report at {}.'
.format(pipeline, job_dir, out_dir)
)
# Get and import the pipeline class
logger.debug(
'Importing pipeline report class {pipeline:s} ...'
.format(pipeline=pipeline)
)
pipe_module_name, pipe_class_name = pipeline.rsplit('.', 1)
pipe_module = importlib.import_module(pipe_module_name)
pipeline_report_cls = getattr(pipe_module, pipe_class_name)
# Processing the job and output folders
job_dir_p, out_dir_p = Path(job_dir), Path(out_dir)
if out_dir_p.exists():
if not force:
sys.exit(
"Cannot overwrite output folder (force overwriting by passing "
"--force option). Current operation has been aborted."
)
logger.warning(
"Report output folder {:s} has already existed! ..."
.format(out_dir_p.as_posix())
)
# remove the output folder completely
shutil.rmtree(out_dir_p.as_posix())
# Create the output folder
out_dir_p.mkdir(parents=True)
# Initiate the report class
report = pipeline_report_cls(job_dir_p)
# Generate the report
report.generate(out_dir_p)
logger.info("Job successfully end. Print message")
print(CAVEAT_MESSAGE.format(out_dir))
<file_sep>## Installation
conda create -n bcreport python=3.5 ipython click jinja2 pandas seaborn
pip install colorlog
pip install --editable .[color]
<file_sep>from pathlib import Path
from bc_report.report import Stage
from ..base.report import BaseSummaryHomeStage
here = Path(__file__).parent
class RNASeqStageMixin(Stage):
template_find_paths = [
here / 'templates',
*BaseSummaryHomeStage.template_find_paths,
]
<file_sep>{% extends 'base/base.html' %}
{% set active="overview" %}
{% block nav %}
{% include "rna_seq/_includes/nav.html" %}
{% endblock nav %}
<file_sep>const autoprefixer = require('autoprefixer');
const csso = require('postcss-csso');
const gulp = require('gulp');
const postcss = require('gulp-postcss');
const sass = require('gulp-sass');
// Server
gulp.task('default', ['styles'], () => {
gulp.watch('bc_pipelines/base/static_src/css/**/*.scss', ['styles']);
});
// Styles
gulp.task('styles', () => {
return gulp.src('bc_pipelines/base/static_src/css/site.scss')
.pipe(sass().on('error', sass.logError))
.pipe(postcss([
autoprefixer,
csso
]))
.pipe(gulp.dest('bc_pipelines/base/static/css'));
});
<file_sep>import logging
__version__ = '0.3.0'
def create_logger(name):
logger = logging.getLogger(name)
logger.addHandler(logging.NullHandler())
return logger
<file_sep>from pathlib import Path
from bc_report.info import AnalysisInfo
from bc_report import create_logger
from ..base.report import BaseStage
from . import RNASeqStageMixin
logger = create_logger(__name__)
class CufflinksStage(RNASeqStageMixin, BaseStage):
template_entrances = ['rna_seq/cufflinks.html']
result_folder_name = 'cufflinks'
def parse(self, analysis_info: AnalysisInfo):
data_info = super().parse(analysis_info)
data_info['raw_output'] = self.collect_raw_output(analysis_info)
return data_info
def collect_raw_output(self, analysis_info: AnalysisInfo):
"""Render the link to the raw output files"""
raw_output_filenames = [
'genes.fpkm_tracking',
'isoforms.fpkm_tracking',
'run_cufflinks.log',
'skipped.gtf',
'transcripts.gtf',
]
actual_output_dir = self._locate_result_folder().name
raw_output_links = {}
for sample in analysis_info.samples:
raw_output_links[sample] = {
filename: '../result/{output_dir}/{sample}/{filename}'.format(
output_dir=actual_output_dir,
sample=sample,
filename=filename
)
for filename in raw_output_filenames
}
return raw_output_links
<file_sep>from pathlib import Path
from typing import List
import re
import jinja2
from . import create_logger
from .info import AnalysisInfo
from .utils import (
merged_copytree,
discover_file_by_patterns,
copy,
strify_path, humanfmt, tojson
)
logger = create_logger(__name__)
class Stage:
template_entrances = ['stage.html']
template_find_paths = ['templates']
embed_result_joint = []
embed_result_per_condition = []
embed_result_per_sample = []
result_folder_name = ''
def __init__(self, report: 'Report'):
self.report = report
self._setup_jinja2()
def parse(self, analysis_info: AnalysisInfo):
data_info = {}
return data_info
def get_context_data(self, data_info):
return dict(
data_info=data_info,
analysis_info=self.report.analysis_info,
)
def render(self, data_info, report_root):
for tpl_name in self.template_entrances:
tpl = self._env.get_template(tpl_name)
html = tpl.render(self.get_context_data(data_info))
# remove folder structure in template name
tpl_report_path = report_root / tpl_name.rsplit('/', 1)[1]
logger.debug('writing template to %s' % tpl_report_path.as_posix())
with tpl_report_path.open('w') as f:
f.write(html)
def copy_static(self, report_root):
result_dir = self._locate_result_folder()
self.copy_static_per_sample(result_dir, report_root)
self.copy_static_per_condition(result_dir, report_root)
self.copy_static_joint(result_dir, report_root)
@property
def name(self):
return self.__class__.__name__
def _setup_jinja2(self):
_template_paths = [
strify_path(p) for p in self.template_find_paths
]
logger.debug(
"Jinja2 reads templates from {}".format(_template_paths)
)
self._report_loader = jinja2.FileSystemLoader(_template_paths)
self._env = jinja2.Environment(
loader=self._report_loader,
extensions=['jinja2.ext.with_'],
)
self._env.globals['static'] = self._template_static_path
self._env.globals['humanfmt'] = humanfmt
self._env.filters['tojson'] = tojson
def _template_static_path(self, *path_parts):
return Path('static', *path_parts).as_posix()
def _locate_result_folder(self):
if not self.result_folder_name:
raise ValueError("Stage {:s} does not have result_folder_name set")
folder_pattern = r"^(\d+_|){}$".format(self.result_folder_name)
logger.debug(
"Result folder name regex pattern: {}".format(folder_pattern))
valid_name = re.compile(folder_pattern).match
stage_result_path = [
p for p in self.report.analysis_info.result_root.iterdir()
if valid_name(p.name)
]
if not stage_result_path:
raise ValueError(
"No matched folder name found for pattern {}"
.format(folder_pattern)
)
if len(stage_result_path) > 1:
raise ValueError(
"Duplicated stage result folders found: {} of pattern {}"
.format(stage_result_path, self.result_folder_name)
)
return stage_result_path[0]
def copy_static_joint(self, result_dir, report_root):
for desc in self.embed_result_joint:
src_root = result_dir / desc['src']
dest_root = report_root / 'static' / desc['dest']
if not dest_root.exists():
dest_root.mkdir(parents=True)
file_list = discover_file_by_patterns(src_root, desc['patterns'])
for fp in file_list:
copy(fp, dest_root)
@staticmethod
def copy_static_grouped(
result_root, report_root,
src_rel_pth, dest_rel_pth, file_patterns, groups
):
all_src_root = result_root / src_rel_pth
all_dest_root = report_root / dest_rel_pth
for grp in groups:
grp_src_root = all_src_root / grp
grp_dest_root = all_dest_root / dest_rel_pth / grp
grp_dest_root.mkdir(parents=True)
file_list = discover_file_by_patterns(grp_src_root, file_patterns)
for fp in file_list:
copy(fp, grp_dest_root)
@staticmethod
def batch_copy_static_grouped(
result_dir, report_root, desc_sources, groups=None
):
for desc in desc_sources:
Stage.copy_static_grouped(
result_dir, report_root,
desc['src'], desc['dest'], groups
)
def copy_static_per_condition(self, result_dir, report_root):
self.batch_copy_static_grouped(
result_dir, report_root,
desc_sources=self.embed_result_per_condition,
groups=self.report.analysis_info.conditions.keys()
)
def copy_static_per_sample(self, result_dir, report_root):
self.batch_copy_static_grouped(
result_dir, report_root,
desc_sources=self.embed_result_per_sample,
groups=self.report.analysis_info.samples.keys()
)
class SummaryStage(Stage):
def get_context_data(self, data_info):
context = super().get_context_data(data_info)
context['joint_data_info'] = context['data_info']
del context['data_info']
return context
def _locate_result_folder(self):
return self.report.analysis_info.result_root
class Report:
stage_classes = []
"""(List of class name) Store the sequence of stages in use."""
static_roots = []
def __init__(self, analysis_dir):
"""Initiate a new report based on given job result."""
logger.debug(
"New report {} object has been initiated"
.format(type(self).__name__)
)
self.analysis_info = AnalysisInfo(analysis_dir)
self.report_root = None
self._stages = self.initiate_stages()
self.data_info = {
stage.name: None
for stage in self.tool_stages
}
def initiate_stages(self) -> List[Stage]:
return [
stage_cls(self)
for stage_cls in self.stage_classes
]
def parse(self, analysis_info: AnalysisInfo):
for stage in self.tool_stages:
logger.info('Parsing stage %s' % stage.name)
self.data_info[stage.name] = stage.parse(analysis_info)
def generate(self, report_dir: Path):
self.report_root = report_dir
logger.info('Parsing result')
self.parse(self.analysis_info)
logger.info('Rendering report')
self.render_report()
logger.info('Copying static files')
self.copy_static()
def render_report(self):
"""Render and output the report"""
for stage in self.tool_stages:
stage.render(self.data_info[stage.name], self.report_root)
for stage in self.summary_stages:
stage.render(self.data_info, self.report_root)
def copy_static(self):
merged_copytree(self.static_roots, self.report_root / 'static')
for stage in self.all_stages:
stage.copy_static(self.report_root)
@property
def all_stages(self) -> List[Stage]:
return self._stages
@property
def tool_stages(self) -> List[Stage]:
return (
stage for stage in self._stages
if not isinstance(stage, SummaryStage)
)
@property
def summary_stages(self) -> List[Stage]:
return (
stage for stage in self._stages
if isinstance(stage, SummaryStage)
)
<file_sep>from collections import OrderedDict
import decimal
import io
from pathlib import Path
import zipfile
import numpy as np
import pandas as pd
from bc_report.info import AnalysisInfo
from bc_report import create_logger
from .report import BaseStage
D = decimal.Decimal
logger = create_logger(__name__)
class OverSeq:
def __init__(self, seq, count, percentage, possible_source):
self.seq = seq
self.count = D(count)
self.percentage = D(percentage).quantize(D("0.01"))
self.possible_source = possible_source
def parse_fastqc_data(data_f):
qc_info = OrderedDict()
qc_data = {}
qc_desc = None
next(data_f) # FastQC version info
for line in data_f:
new_sec = line.startswith('>>')
sec_end = line.startswith('>>END_MODULE')
if new_sec and not sec_end:
qc_desc, qc_status = line.rstrip()[2:].rsplit('\t', 1)
qc_info[qc_desc] = qc_status
qc_data[qc_desc] = []
elif not new_sec and not sec_end:
qc_data[qc_desc].append(line.rstrip('\n').split('\t'))
return qc_info, qc_data
class FastQCStage(BaseStage):
template_entrances = ['base/fastqc.html']
result_folder_name = 'fastqc'
MODULES = OrderedDict([
('Basic Statistics', None),
('Per base sequence quality', 'per_base_quality.png'),
('Per tile sequence quality', None),
('Per sequence quality scores', 'per_sequence_quality.png'),
('Per sequence GC content', 'per_sequence_gc_content.png'),
('Per base N content', 'per_base_n_content.png'),
('Sequence Length Distribution', 'sequence_length_distribution.png'),
('Sequence Duplication Levels', 'duplication_levels.png'),
('Overrepresented sequences', None),
('Adapter Content', None),
('Kmer Content', None),
])
STATUS_TO_ICON_CLASS = {
'pass': 'fa-check',
'fail': 'fa-times',
'warn': 'fa-exclamation',
}
def accepted_data_sources(self, data_sources) -> OrderedDict:
filtered_sources = OrderedDict()
for source_name, source in data_sources.items():
if source.file_type in ['FASTA', 'FASTQ']:
filtered_sources[Path(source_name)] = source
return filtered_sources
def parse_per_base_quality(self, data_info, source_p, qc_data):
perbase_q = qc_data['Per base sequence quality']
df = (
pd.DataFrame(perbase_q[1:], columns=perbase_q[0])
.assign(**{
# '#Base': lambda x: x['#Base'].astype(np.int),
'Mean': lambda x: x['Mean'].astype(np.float),
})
)
data_info['per_base_quality'].append({
'name': source_p.stem,
'data': list(df['Mean'].values),
'pointStart': 1,
})
def parse(self, analysis_info: AnalysisInfo):
data_info = super().parse(analysis_info)
data_info['qc_info'] = OrderedDict()
data_info['qc_data'] = {}
result_root = analysis_info.result_root / self._locate_result_folder()
accepted_sources = self.accepted_data_sources(
analysis_info.data_sources
)
for source_p, source in accepted_sources.items():
fastqc_zip_pth = Path(
result_root,
source_p.stem, '{}_fastqc.zip'.format(source_p.stem)
)
logger.debug('Parsing FastQC zip file %s' % fastqc_zip_pth.as_posix())
with zipfile.ZipFile(fastqc_zip_pth.as_posix(), 'r') as zipf:
fastqc_data_pth = '{}/fastqc_data.txt'.format(fastqc_zip_pth.stem)
with io.TextIOWrapper(zipf.open(fastqc_data_pth), encoding='utf8') as f:
qc_info, qc_data = parse_fastqc_data(f)
data_info['qc_info'][source_p.name] = qc_info
data_info['qc_data'][source_p.name] = qc_data
# Parse FastQC per base quality
data_info['per_base_quality'] = []
for source_p, source in accepted_sources.items():
self.parse_per_base_quality(
data_info, source_p, data_info['qc_data'][source.name]
)
# Parse FastQC base statistics
data_info['base_stat'] = OrderedDict()
for source_p, source in accepted_sources.items():
base_stat = dict(data_info['qc_data'][source.name]['Basic Statistics'])
base_stat['Total Sequences'] = int(base_stat['Total Sequences'])
data_info['base_stat'][source.name] = base_stat
# data source to result mapping
data_info['raw_output'] = {}
for source_p, source in accepted_sources.items():
html_link, zip_link = [
'../result/{fastqc_dir}/{src_name}/{src_name}_fastqc.{ext}'
.format(
fastqc_dir=result_root.name,
src_name=source_p.stem,
ext=ext,
)
for ext in ['html', 'zip']
]
data_info['raw_output'][source_p.name] = {
'html': html_link,
'zip': zip_link,
'stem': source_p.stem,
}
return data_info
def get_context_data(self, data_info):
context = super().get_context_data(data_info)
context.update({
'MODULES': self.MODULES,
'STATUS_TO_ICON_CLASS': self.STATUS_TO_ICON_CLASS,
})
return context
<file_sep>from collections import OrderedDict, namedtuple
from pathlib import Path
from typing import Dict
import yaml
from . import create_logger
logger = create_logger(__name__)
DataSource = namedtuple('DataSource', ['name', 'path', 'file_type', 'strand'])
class AnalysisInfo:
def __init__(self, job_dir):
self.result_root = Path(job_dir).resolve()
yaml_pth = self.result_root / 'analysis_info.yaml'
logger.debug(
'Reading analysis info from {:s}'.format(yaml_pth.as_posix())
)
with yaml_pth.open() as f:
self._raw = yaml.load(f)
self.data_sources = self.parse_data_sources()
self.conditions = self.parse_conditions()
self.parameters = self.parse_parameters()
samples = OrderedDict()
for condition_samples in self.conditions.values():
samples.update(condition_samples)
self.samples = samples
def parse_data_sources(self) -> Dict[str, DataSource]:
data_sources = OrderedDict()
for data_source in self._raw['data_sources']:
name, info = next(iter(data_source.items()))
# Ensure it doesnt contain any path
name = Path(name).name
data_sources[name] = (
DataSource(name, info['path'], info['type'], info['strand'])
)
return data_sources
def parse_conditions(self) -> Dict[str, Dict]:
conditions = OrderedDict()
for condition in self._raw['conditions']:
condition_name, samples = next(iter(condition.items()))
condition_samples = OrderedDict()
for sample in samples:
condition_samples.update(sample)
conditions[condition_name] = condition_samples
return conditions
def parse_parameters(self):
parameters = {}
for param_name, param_val in self._raw['parameters'].items():
parameters[param_name] = param_val
return parameters
<file_sep>import ast
from datetime import datetime
from pathlib import Path
from seaborn.palettes import husl_palette
from bc_report.info import AnalysisInfo
from bc_report import create_logger
from ..base.report import BaseStage
from . import RNASeqStageMixin
logger = create_logger(__name__)
def parse_star_log(log_str: str):
"""Parse STAR's Log.final.out format"""
align_stat = dict(
tuple(l.strip().split(' |\t', 1))
for l in log_str.splitlines()
if ' |\t' in l
)
# Convert to proper data types
for metric_key, metric_val in align_stat.items():
if metric_val.endswith('%'):
# Convert to percentage
align_stat[metric_key] = float(metric_val[:-1]) / 100
elif metric_key in [
'Started job on',
'Started mapping on',
'Finished on',
]:
# Convert to datetime
align_stat[metric_key] = datetime.strptime(
metric_val, '%b %d %H:%M:%S'
)
else:
# Convert to int or float from str
#
# >>> import ast
# >>> type(ast.literal_eval('10.0'))
# float
# >>> type(ast.literal_eval('10'))
# int
#
# Ref: http://stackoverflow.com/a/9510585
align_stat[metric_key] = ast.literal_eval(metric_val)
# Compute number of unmapped reads
num_input_reads = align_stat['Number of input reads']
for percent_metric in [
'% of reads unmapped: too many mismatches',
'% of reads unmapped: too short',
'% of reads unmapped: other',
]:
num_metric = 'Number %s' % percent_metric[len('% '):]
align_stat[num_metric] = int(
align_stat[percent_metric] * num_input_reads
)
return align_stat
class STARStage(RNASeqStageMixin, BaseStage):
template_entrances = ['rna_seq/star.html']
result_folder_name = 'STAR'
NUM_READ_METRICS = [
'Number of input reads',
'Uniquely mapped reads number',
'Number of reads mapped to multiple loci',
'Number of reads mapped to too many loci',
'Number of reads unmapped: too many mismatches',
'Number of reads unmapped: too short',
'Number of reads unmapped: other',
'Number of chimeric reads',
]
PERCENT_METRICS = [
'Uniquely mapped reads %',
'% of reads mapped to multiple loci',
'% of reads mapped to too many loci',
'% of reads unmapped: too many mismatches',
'% of reads unmapped: too short',
'% of reads unmapped: other',
'% of chimeric reads',
]
def parse(self, analysis_info: AnalysisInfo):
data_info = super().parse(analysis_info)
logger.info('Parsing STAR alignment statistics from log file')
align_stat = {}
result_dir = self._locate_result_folder()
for sample in analysis_info.samples:
with result_dir.joinpath(sample, 'Log.final.out').open() as f:
align_stat[sample] = parse_star_log(f.read())
data_info['align_stat'] = align_stat
logger.info('Generating raw output file links')
data_info['raw_output'] = self.collect_raw_output(analysis_info)
return data_info
def get_context_data(self, data_info):
context = super().get_context_data(data_info)
context['NUM_READ_METRICS'] = self.NUM_READ_METRICS
context['PERCENT_METRICS'] = self.PERCENT_METRICS
METRICS_DISPLAY = [
'unique',
'mulit-map (multiple loci)',
'multi-map (too many loci)',
'unmapped (too many mismatches)',
'unmapped (too short)',
'unmapped (other)',
'chimeric',
]
# Prepare data for plotting
analysis_info = self.report.analysis_info
plot_num_read_data = []
for metric, metric_display in zip(
reversed(self.NUM_READ_METRICS[1:]),
reversed(METRICS_DISPLAY),
):
plot_num_read_data.append({
'name': metric_display,
'data': [
data_info['align_stat'][sample][metric]
for sample in analysis_info.samples
],
})
# Compute the color for condition plot bands
condition_bands = []
condition_counter = 0
for (condition, samples), color in zip(
analysis_info.conditions.items(),
husl_palette(len(analysis_info.conditions), l=0.8, s=0.6),
):
condition_bands.append({
'from': condition_counter - 0.5,
'to': condition_counter + len(samples) - 0.5,
'color': 'rgba({:d}, {:d}, {:d}, 0.4)'.format(
*[int(c * 255) for c in color]
),
'label': {
'text': condition,
'align': 'right',
'x': -5,
}
})
condition_counter += len(samples)
context['plot'] = {
'condition_bands': condition_bands,
'data': {
'num_read': plot_num_read_data,
}
}
return context
def collect_raw_output(self, analysis_info: AnalysisInfo):
"""Render the link to the raw output files"""
raw_output_filenames = [
'Aligned.sortedByCoord.out.bam',
'Aligned.sortedByCoord.out.bam.bai',
'Log.final.out',
'Log.out',
'Log.progress.out',
'SJ.out.tab', # high confidence collapsed splice junction
]
actual_output_dir = self._locate_result_folder().name
raw_output_links = {}
for sample in analysis_info.samples:
raw_output_links[sample] = {
filename: '../result/{output_dir}/{sample}/{filename}'.format(
output_dir=actual_output_dir,
sample=sample,
filename=filename
)
for filename in raw_output_filenames
}
return raw_output_links
|
c7f0c2e738816c857d1869338096fefbf53b4691
|
[
"Markdown",
"Python",
"JavaScript",
"HTML"
] | 16
|
Python
|
ccwang002/bc_report
|
b422cb201d15fcf4f7b8d164fb018111ad128e99
|
eda92b7e136a910152b9db76c9c7457160c3bbd8
|
refs/heads/master
|
<file_sep>'use strict';
const validator = require('./validator');
validator.func = function() {
return 'dddd';
};
<file_sep>'use strict';
class Util {
static getDataType(target) {
// basic type, String Number Boolean Symbol undefined null
// reference type, Object
let type = Object.prototype.toString.call(target);
type = type.replace(/^\[object /, '');
type = type.replace(/\]$/, '');
return type;
}
/**
* get http request data
* @param {Object} ctx koa request context
* @param {String} from where get request data
*/
static getRequestData(ctx, from) {
if (!ctx) throw TypeError('parameter ctx is invalid');
if (ctx.method !== 'GET') {
from = from || 'body';
return ctx.request[from];
} else {
from = from || 'query';
return ctx[from];
}
}
}
module.exports = Util;
<file_sep>'use strict';
const Ajv = require('ajv');
const Util = require('./util');
class AjvWrapper {
constructor() {
this.schemas = {};
this.ajv = new Ajv();
}
/**
* Register new schema to ajv instance.
* @param {String} name schema name
* @param {Object} schema schema entity
* @param {Object} options other related parameters
*/
registerSchema(name, schema, options) {
if (typeof name !== 'string') throw TypeError('parameter name must be String type');
if (Util.getDataType(schema) !== 'Object') throw TypeError('parameter schema must be Object type');
if (this.schemas[name]) throw Error(`schema '${name}' has already been registered`);
if (!options || Util.getDataType(options) !== 'Object') options = {};
let schemaObj = { validate: this.ajv.compile(schema) };
this.schemas[name] = Object.assign(schemaObj, options);
}
}
module.exports = new AjvWrapper();
<file_sep># koa-data-validator
request data validator
|
8b98fd842ef5dcabb07caa4f537cd5a09c97d632
|
[
"JavaScript",
"Markdown"
] | 4
|
JavaScript
|
jude-liu/koa-data-validator
|
1ab7a29992f2f5f73e740552be2bcb32faf36f96
|
861ce47f6d100ec3eeb3ecb91e018201e2e8172d
|
refs/heads/main
|
<file_sep><?php
echo "Ini konfig"
?><file_sep><?php
//file login
?><file_sep><?php
// skrip index
$data="Ini adalah kalimat";
?>
|
282ed3aed35570cd6781194f3541d3659c251648
|
[
"PHP"
] | 3
|
PHP
|
rizaru22/login
|
c35ce0c610702f25034412df8659323a611a57fc
|
54f403be2825ed13ad8704d762c842680695a79a
|
refs/heads/master
|
<repo_name>finn722/temprespository<file_sep>/src/com/eduask/bean/User.java
package com.eduask.bean;
import java.util.Date;
public class User {
private Long uid;
private String account;
private String pwd;
private String username;
private String gender;
private String phone;
private String headImg;
private Date lastLoginTime;
private String lastLoginIp;
private AccountEnable accountEnable = new AccountEnable();
private Role role = new Role();//岗位
private Department department = new Department();
public Long getUid() {
return uid;
}
public void setUid(Long uid) {
this.uid = uid;
}
public String getAccount() {
return account;
}
public void setAccount(String account) {
this.account = account;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getHeadImg() {
return headImg;
}
public void setHeadImg(String headImg) {
this.headImg = headImg;
}
public Date getLastLoginTime() {
return lastLoginTime;
}
public void setLastLoginTime(Date lastLoginTime) {
this.lastLoginTime = lastLoginTime;
}
public String getLastLoginIp() {
return lastLoginIp;
}
public void setLastLoginIp(String lastLoginIp) {
this.lastLoginIp = lastLoginIp;
}
public AccountEnable getAccountEnable() {
return accountEnable;
}
public void setAccountEnable(AccountEnable accountEnable) {
this.accountEnable = accountEnable;
}
public Role getRole() {
return role;
}
public void setRole(Role role) {
this.role = role;
}
public Department getDepartment() {
return department;
}
public void setDepartment(Department department) {
this.department = department;
}
}
<file_sep>/src/data.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///oa?useUnicode=true&characterEncoding=utf-8
jdbc.user=root
jdbc.pwd=<PASSWORD><file_sep>/src/com/eduask/dao/BaseDao.java
package com.eduask.dao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import com.eduask.util.ConnectionHelper;
public class BaseDao {
protected Connection conn;
protected Statement stat;
protected PreparedStatement ps;
protected ResultSet rs;
protected Connection getConnection(){
String driverClass = ConnectionHelper.newInstance().getString("jdbc.driver");
String url = ConnectionHelper.newInstance().getString("jdbc.url");
String user = ConnectionHelper.newInstance().getString("jdbc.user");
String pwd = ConnectionHelper.newInstance().getString("jdbc.pwd");
try {
Class.forName(driverClass);
conn = DriverManager.getConnection(url, user, pwd);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return conn;
}
protected void closeResource(){
if(rs!=null){
try {
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(ps!=null){
try {
ps.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(stat!=null){
try {
stat.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(conn!=null){
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
<file_sep>/src/com/eduask/service/IUserService.java
package com.eduask.service;
import java.util.List;
import java.util.Set;
import com.eduask.bean.Department;
import com.eduask.bean.User;
import com.eduask.form.LoginForm;
import com.eduask.util.PageUtil;
public interface IUserService {
public User loginUser(LoginForm loginForm);
public Integer checkAccount(String account);
public List<User> findAll(User user, PageUtil pageUtil);
public boolean save(User user);
public boolean enableUser(String id);
public boolean disableUser(String id);
public boolean delete(String id);
public User findById(String id);
public boolean update(User user);
public void initpwd(String uid);
public Long getTotalCount(User user);
public boolean deleteByIds(Set<Long> sessionSet);
public boolean initpwdByIds(Set<Long> sessionSet);
public List<Department> findDepartmentList();
public void updateRoleIdIsNull(List<Long> uids);
}
<file_sep>/src/com/eduask/util/ReturnResult.java
package com.eduask.util;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class ReturnResult<T> {
private Integer statusId;
private Object msg;
private List<T> list = new ArrayList<T>();
public String toJson() throws IllegalArgumentException, IllegalAccessException{
StringBuffer json = new StringBuffer();
if(this!=null){
json.append("{'statusId':"+statusId+",'msg':'"+msg+"','list':[");
//循环Collection
Field[] fields = null;
if(list.size()>0){
Class cla = list.get(0).getClass();
fields = cla.getDeclaredFields();
}
for(int k = 0;k<list.size();k++){
json.append("{");
for(int i=0;i<fields.length;i++){
fields[i].setAccessible(true);//获取权限
String typeStr = fields[i].getType().toString();
if(typeStr.indexOf("String")!=-1){
json.append("'"+fields[i].getName()+"':'"+fields[i].get(list.get(k))+"'");
}else if(typeStr.indexOf("Date")!=-1){
json.append("'"+fields[i].getName()+"':'"+new SimpleDateFormat("yyyy-MM-dd").format((Date)(fields[i].get(list.get(k))))+"'");
}else{
json.append("'"+fields[i].getName()+"':"+fields[i].get(list.get(k)));
}
if(i!=fields.length-1){
json.append(",");
}
}
if(k==list.size()-1){
json.append("}");
}else{
json.append("},");
}
}
json.append("]}");
}
return json.toString();
}
public Integer getStatusId() {
return statusId;
}
public void setStatusId(Integer statusId) {
this.statusId = statusId;
}
public Object getMsg() {
return msg;
}
public void setMsg(Object msg) {
this.msg = msg;
}
public List<T> getList() {
return list;
}
public void setList(List<T> list) {
this.list = list;
}
}
<file_sep>/src/com/eduask/dao/IBaseDao.java
package com.eduask.dao;
import java.util.List;
import com.eduask.bean.User;
import com.eduask.util.PageUtil;
public interface IBaseDao<T> {
}
<file_sep>/src/com/eduask/servlet/UserServlet.java
package com.eduask.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.catalina.connector.Request;
import com.eduask.bean.Department;
import com.eduask.bean.Role;
import com.eduask.bean.User;
import com.eduask.form.LoginForm;
import com.eduask.service.IUserService;
import com.eduask.service.impl.UserServiceImpl;
import com.eduask.util.PageUtil;
import com.eduask.util.ReturnResult;
@WebServlet("/user/UserServlet")
public class UserServlet extends BaseServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
this.doGet(request, response);
}
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
String method = request.getParameter("method");
Class cla = this.getClass();
try {
Method method1 = cla.getDeclaredMethod(method, HttpServletRequest.class,HttpServletResponse.class);
method1.invoke(this, request, response);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void loginUser(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String account = request.getParameter("account");
String pwd = request.getParameter("pwd");
String rempwd = request.getParameter("rempwd");
LoginForm loginForm = new LoginForm();
loginForm.setAccount(account);
loginForm.setPwd(pwd);
System.out.println(111);
if(Boolean.parseBoolean(rempwd)){
Cookie cookie1 = new Cookie("account", account);
Cookie cookie2 = new Cookie("pwd",pwd);
cookie1.setMaxAge(Integer.MAX_VALUE);
cookie2.setMaxAge(Integer.MAX_VALUE);
cookie1.setPath("/");
cookie2.setPath("/");
response.addCookie(cookie1);
response.addCookie(cookie2);
}
User user = userService.loginUser(loginForm);
System.out.println(user);
if(user==null&&!Boolean.parseBoolean(rempwd)){
//登陆失败
request.setAttribute("loginForm", loginForm);
request.getRequestDispatcher("../login.jsp").forward(request, response);
}else{
request.getSession().setAttribute("loginUser",user);
response.sendRedirect("../role/RoleServlet?method=list");
}
}
public void checkAccount(HttpServletRequest request, HttpServletResponse response) throws IOException {
// TODO Auto-generated method stub
String account = request.getParameter("account");
String status = null;
Integer disabled = userService.checkAccount(account);
response.setContentType("text/html;charset=utf-8");
//如果账户正常,那么返回1,如果账户被禁用,那么返回-1,如果账户不存在,返回0
PrintWriter pw = response.getWriter();
ReturnResult result = new ReturnResult();
if(disabled==1){//正常
result.setStatusId(disabled);
result.setMsg("当前用户允许登录");
}else if(disabled==-1){
result.setStatusId(disabled);
result.setMsg("当前用户帐号异常,请联系管理员");
}else{
result.setStatusId(0);
result.setMsg("账户不存在,是否<a href=\"register.jsp?account="+account+"\">立即注册</a>");
}
try {
pw.write(result.toJson());
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
pw.flush();
pw.close();
}
public void list(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
String clear = request.getParameter("clear");
if("true".equals(clear)){
request.getSession().removeAttribute("account");
request.getSession().removeAttribute("username");
request.getSession().removeAttribute("department");
request.getSession().removeAttribute("gender");
request.getSession().removeAttribute("disabled");
}
String pageIndex = request.getParameter("pageIndex");
//获取查询表单中的参数
String account = request.getParameter("account");
System.out.println(account);
String username = request.getParameter("username");
String department = request.getParameter("department");
String sex = request.getParameter("sex");
String disabled = request.getParameter("disabled");
System.out.println(disabled);
if(account!=null){
request.getSession().setAttribute("account", account);
}
if(username!=null){
request.getSession().setAttribute("username", username);
}
if(department!=null){
request.getSession().setAttribute("department", department);
}
if(sex!=null){
request.getSession().setAttribute("gender", sex);
}
if(disabled!=null){
request.getSession().setAttribute("disabled", disabled);
}
User user = new User();
if(request.getSession().getAttribute("account")!=null){
user.setAccount(request.getSession().getAttribute("account").toString());
}
if(request.getSession().getAttribute("username")!=null){
user.setUsername(request.getSession().getAttribute("username").toString());
}
if(request.getSession().getAttribute("department")!=null&&!"".equals(request.getSession().getAttribute("department"))){
user.getDepartment().setId(Long.valueOf(request.getSession().getAttribute("department").toString()));
}
if(request.getSession().getAttribute("gender")!=null&&!"".equals(request.getSession().getAttribute("gender"))){
user.setGender(request.getSession().getAttribute("gender").toString());
}
if(request.getSession().getAttribute("disabled")!=null){
user.getAccountEnable().setEnableId(Long.valueOf(request.getSession().getAttribute("disabled").toString()));
}
PageUtil pageUtil = new PageUtil();
pageUtil.setPageIndex(Long.valueOf(pageIndex));
Long totalCount = userService.getTotalCount(user);
pageUtil.setTotalCount(totalCount);
List<User> userlist = userService.findAll(user, pageUtil);
List<Department> departments = userService.findDepartmentList();
request.setAttribute("departments", departments);
request.setAttribute("userlist", userlist);
request.setAttribute("pageUtil", pageUtil);
request.getRequestDispatcher("../WEB-INF/user/list.jsp").forward(request, response);
}
public void saveUI(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
//查询角色列表
List<Role> rolelist = roleService.findAll();
request.setAttribute("rolelist", rolelist);
request.getRequestDispatcher("../WEB-INF/user/saveUI.jsp").forward(request, response);
}
private void editUI(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
//查询要修改的用户
String id = request.getParameter("id");
User user = userService.findById(id);
request.setAttribute("editUser", user);
//查询角色列表
List<Role> rolelist = roleService.findAll();
request.setAttribute("rolelist", rolelist);
request.getRequestDispatcher("../WEB-INF/user/saveUI.jsp").forward(request, response);
}
public void save(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException{
String account = request.getParameter("account");
String username = request.getParameter("username");
String gender = request.getParameter("gender");
String phone = request.getParameter("phone");
//String headImg
String roleid = request.getParameter("roleid");
User user = new User();
user.setAccount(account);
user.setUsername(username);
user.setGender(gender);
user.setPhone(phone);
if(roleid==null||"".equals(roleid)){
user.getRole().setRoleid(null);
}else{
user.getRole().setRoleid(Long.valueOf(roleid));
}
boolean flag = userService.save(user);
if(flag){
response.sendRedirect("UserServlet?method=list&pageIndex=1");
}else{
request.getRequestDispatcher("UserServlet?method=saveUI").forward(request, response);
}
}
private void edit(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException{
String uid = request.getParameter("uid");
String account = request.getParameter("account");
String username = request.getParameter("username");
String gender = request.getParameter("gender");
String phone = request.getParameter("phone");
//String headImg
String roleid = request.getParameter("roleid");
User user = new User();
user.setUid(Long.valueOf(uid));
user.setAccount(account);
user.setUsername(username);
user.setGender(gender);
user.setPhone(phone);
if(roleid==null||"".equals(roleid)){
user.getRole().setRoleid(null);
}else{
user.getRole().setRoleid(Long.valueOf(roleid));
}
boolean flag = userService.update(user);
if(flag){
response.sendRedirect("UserServlet?method=list&pageIndex=1");
}else{
request.getRequestDispatcher("UserServlet?method=editUI&id="+uid).forward(request, response);
}
}
private void enableUser(HttpServletRequest request, HttpServletResponse response) throws IOException{
String id = request.getParameter("id");
boolean flag = userService.enableUser(id);
response.sendRedirect("UserServlet?method=list&pageIndex=1");
}
private void disableUser(HttpServletRequest request, HttpServletResponse response) throws IOException{
String id = request.getParameter("id");
boolean flag = userService.disableUser(id);
response.sendRedirect("UserServlet?method=list&pageIndex=1");
}
private void delete(HttpServletRequest request, HttpServletResponse response) throws IOException{
String id = request.getParameter("id");
boolean flag = userService.delete(id);
response.sendRedirect("UserServlet?method=list&pageIndex=1");
}
private void initpwd(HttpServletRequest request, HttpServletResponse response) throws IOException{
String uid = request.getParameter("id");
userService.initpwd(uid);
response.sendRedirect("UserServlet?method=list&pageIndex=1");
}
private void deleteUids(HttpServletRequest request, HttpServletResponse response) throws IOException{
//获取复选框多个选中选项
String[] uids2 = request.getParameterValues("uid");
Long[] uids1 = new Long[uids2.length];
for(int i=0;i<uids1.length;i++){
uids1[i] = Long.valueOf(uids2[i]);
}
//获取session中保存的要操作的uid数组,和当前页选中的数组合并为一个新数组
Set<Long> sessionSet = (Set<Long>) request.getSession().getAttribute("uidSet1");
if(sessionSet!=null){
sessionSet.addAll(Arrays.asList(uids1));
}else{
sessionSet = new HashSet<Long>(Arrays.asList(uids1));
}
boolean flag = userService.deleteByIds(sessionSet);
request.getSession().removeAttribute("uidSet1");
response.sendRedirect("UserServlet?method=list&pageIndex=1");
}
private void initpwdUids(HttpServletRequest request, HttpServletResponse response) throws IOException{
//获取复选框多个选中选项
String[] uids2 = request.getParameterValues("uid");
Long[] uids1 = new Long[uids2.length];
for(int i=0;i<uids1.length;i++){
uids1[i] = Long.valueOf(uids2[i]);
}
//获取session中保存的要操作的uid数组,和当前页选中的数组合并为一个新数组
Set<Long> sessionSet = (Set<Long>) request.getSession().getAttribute("uidSet");
if(sessionSet!=null){
sessionSet.addAll(Arrays.asList(uids1));
}else{
sessionSet = new HashSet<Long>(Arrays.asList(uids1));
}
boolean flag = userService.initpwdByIds(sessionSet);
request.getSession().removeAttribute("uidSet");
response.sendRedirect("UserServlet?method=list&pageIndex=1");
}
private void saveCheckedUid(HttpServletRequest request, HttpServletResponse response) throws IOException, IllegalArgumentException, IllegalAccessException{
String uids = request.getParameter("uids");
String[] uidArr = uids.split("-");
Long[] uids1 = new Long[uidArr.length];
for(int i=0;i<uids1.length;i++){
uids1[i] = Long.valueOf(uidArr[i]);
}
List<Long> uidParaList = Arrays.asList(uids1);
if(request.getSession().getAttribute("uidSet")!=null){
Set<Long> sessionSet = (Set<Long>) request.getSession().getAttribute("uidSet");
sessionSet.addAll(uidParaList);
request.getSession().setAttribute("uidSet", sessionSet);
}else{
request.getSession().setAttribute("uidSet", new HashSet<Long>(uidParaList));
}
PrintWriter pw = response.getWriter();
ReturnResult returnRes = new ReturnResult();
returnRes.setStatusId(1);
pw.write(returnRes.toJson());
pw.flush();
pw.close();
}
}
<file_sep>/src/com/eduask/dao/impl/RoleDaoImpl.java
package com.eduask.dao.impl;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import com.eduask.bean.PurView;
import com.eduask.bean.Role;
import com.eduask.dao.BaseDao;
import com.eduask.dao.IRoleDao;
import com.eduask.util.PageUtil;
import com.mysql.fabric.xmlrpc.base.Array;
public class RoleDaoImpl extends BaseDao implements IRoleDao {
@Override
public List<Role> findAll() {
// TODO Auto-generated method stub
List<Role> rolelist = new ArrayList<Role>();
getConnection();
String sql = "select roleid,rolename from role";
try {
ps = conn.prepareStatement(sql);
rs = ps.executeQuery();
while(rs.next()){
Role role = new Role();
role.setRoleid(rs.getLong(1));
role.setRolename(rs.getString(2));
rolelist.add(role);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
closeResource();
}
return rolelist;
}
@Override
public Role findById(Long id) {
// TODO Auto-generated method stub
return null;
}
@Override
public boolean save(Role role) {
// TODO Auto-generated method stub
boolean flag = false;
getConnection();
String sql = "insert into role(rolename,uid) values(?,?)";
try {
ps = conn.prepareStatement(sql);
ps.setString(1, role.getRolename());
ps.setLong(2, role.getCreateUser().getUid());
int num = ps.executeUpdate();
if(num>0){
flag = true;
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
closeResource();
}
return flag;
}
@Override
public boolean edit(Role t) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean delete(Long id) {
// TODO Auto-generated method stub
return false;
}
@Override
public List<Role> findByIds(Long[] ids) {
// TODO Auto-generated method stub
return null;
}
@Override
public void deleteFormRole_Purview(Long roleid) {
// TODO Auto-generated method stub
getConnection();
String sql = "delete from role_purview where roleid=?";
try {
ps = conn.prepareStatement(sql);
ps.setLong(1, roleid);
ps.executeUpdate();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
closeResource();
}
}
@Override
public void deleteFormRole(Long roleid) {
// TODO Auto-generated method stub
getConnection();
String sql = "delete from role where roleid=?";
try {
ps = conn.prepareStatement(sql);
ps.setLong(1, roleid);
ps.executeUpdate();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
closeResource();
}
}
@Override
public List<Long> findUserByRoleId(Long roleid) {
// TODO Auto-generated method stub
List<Long> uids = new ArrayList<Long>();
getConnection();
String sql = "select uid from user where roleid=?";
try {
ps = conn.prepareStatement(sql);
ps.setLong(1, roleid);
rs = ps.executeQuery();
while(rs.next()){
long uid = rs.getLong(1);
uids.add(uid);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
closeResource();
}
return uids;
}
@Override
public List<PurView> findTopPurviewList() {
// TODO Auto-generated method stub
List<PurView> purviewlist = new ArrayList<PurView>();
getConnection();
String sql = "select purid,purname from purview where parentpurid is null";
try {
ps = conn.prepareStatement(sql);
rs = ps.executeQuery();
while(rs.next()){
PurView purView = new PurView();
purView.setPurId(rs.getInt(1));
purView.setPurname(rs.getString(2));
purviewlist.add(purView);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
closeResource();
}
return purviewlist;
}
@Override
public List<PurView> findChildrenPurviewList(Integer parentpurid) {
// TODO Auto-generated method stub
List<PurView> purviewlist = new ArrayList<PurView>();
getConnection();
String sql = "select purid,purname from purview where parentpurid =?";
try {
ps = conn.prepareStatement(sql);
ps.setInt(1, parentpurid);
rs = ps.executeQuery();
while(rs.next()){
PurView purView = new PurView();
purView.setPurId(rs.getInt(1));
purView.setPurname(rs.getString(2));
purviewlist.add(purView);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
closeResource();
}
return purviewlist;
}
@Override
public Role getById(Long roleid) {
//要连着权限一起查询
Role role = null;
getConnection();
String sql1 = "select roleid,rolename from role where roleid=?";
String sql2 = "select p.purid,purname from role_purview rp,purview p where rp.purid=p.purid and rp.roleid=? and p.parentpurid is null";//查询该角色对应的一级权限
try {
ps = conn.prepareStatement(sql1);
ps.setLong(1, roleid);
rs = ps.executeQuery();
if(rs.next()){
role = new Role();
role.setRoleid(rs.getLong(1));
role.setRolename(rs.getString(2));
}
ps = conn.prepareStatement(sql2);
ps.setLong(1, roleid);
rs = ps.executeQuery();
List<PurView> toppurview = new ArrayList<PurView>();
while(rs.next()){
PurView purview = new PurView();
purview.setPurId(rs.getInt(1));
purview.setPurname(rs.getString(2));
toppurview.add(purview);
}
role.setPurviewList(toppurview);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
closeResource();
}
return role;
}
@Override
public Role findRoleByName(String rolename) {
// TODO Auto-generated method stub
Role role = null;
getConnection();
String sql = "select roleid,rolename from role where rolename=?";
try {
ps = conn.prepareStatement(sql);
ps.setString(1, rolename);
rs = ps.executeQuery();
if(rs.next()){
role = new Role();
role.setRoleid(rs.getLong(1));
role.setRolename(rs.getString(2));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
closeResource();
}
return role;
}
@Override
public boolean saveRoleAndPurviewForeign(Long roleid, String[] purids) {
// TODO Auto-generated method stub
boolean flag = false;
getConnection();
String sql = "insert into role_purview(roleid,purid) values(?,?)";
try {
ps = conn.prepareStatement(sql);
for(int i=0;i<purids.length;i++){
ps.setLong(1, roleid);
ps.setLong(2, Long.valueOf(purids[i]));
ps.addBatch();
}
int[] nums = ps.executeBatch();
flag = true;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
closeResource();
}
return flag;
}
@Override
public List<PurView> findChildrenPurviewList1(Long roleid,Integer purId) {
// TODO Auto-generated method stub
List<PurView> purviewlist = new ArrayList<PurView>();
getConnection();
String sql = "select purid,purname from purview where purid in (select purid from role_purview where roleid=?) and parentpurid=?";
try {
ps = conn.prepareStatement(sql);
ps.setLong(1, roleid);
ps.setInt(2, purId);
rs = ps.executeQuery();
while(rs.next()){
PurView purView = new PurView();
purView.setPurId(rs.getInt(1));
purView.setPurname(rs.getString(2));
purviewlist.add(purView);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
closeResource();
}
return purviewlist;
}
@Override
public void deleteRoleAndPurviewForeign(String roleid) {
// TODO Auto-generated method stub
getConnection();
String sql = "delete from role_purview where roleid=?";
try {
ps = conn.prepareStatement(sql);
ps.setLong(1, Long.valueOf(roleid));
int num = ps.executeUpdate();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
closeResource();
}
}
}
<file_sep>/src/com/eduask/util/PageUtil.java
package com.eduask.util;
public class PageUtil {
private Long totalCount;
private Long pageIndex;
private Long pageNum = 3L;
private Long totalPage;
public Long getTotalCount() {
return totalCount;
}
public void setTotalCount(Long totalCount) {
this.totalCount = totalCount;
}
public Long getPageIndex() {
return pageIndex;
}
public void setPageIndex(Long pageIndex) {
this.pageIndex = pageIndex;
}
public Long getTotalPage() {
if(totalCount%pageNum==0){
totalPage = totalCount/pageNum;
}else{
System.out.println(totalCount);
System.out.println(pageNum);
totalPage = totalCount/pageNum+1;
}
return totalPage;
}
public Long getPageNum() {
return pageNum;
}
}
<file_sep>/src/com/eduask/service/IRoleService.java
package com.eduask.service;
import java.util.List;
import com.eduask.bean.PurView;
import com.eduask.bean.Role;
import com.eduask.util.PageUtil;
public interface IRoleService {
List<Role> findAll();
void deleteFormRole_Purview(Long valueOf);
void deleteFormRole(Long valueOf);
List<Long> findUserByRoleId(String roleid);
List<PurView> findPurview();
Role getById(Long roleid);
Role findRoleByName(String rolename);
boolean save(Long uid, String rolename, String[] purids);
void deleteRoleAndPurviewForeign(String roleid);
void save(String roleid, String[] purids);
}
<file_sep>/src/com/eduask/dao/impl/UserDaoImpl.java
package com.eduask.dao.impl;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import com.eduask.bean.Department;
import com.eduask.bean.User;
import com.eduask.dao.BaseDao;
import com.eduask.dao.IUserDao;
import com.eduask.form.LoginForm;
import com.eduask.util.MD5Utils;
import com.eduask.util.PageUtil;
public class UserDaoImpl extends BaseDao implements IUserDao<User> {
@Override
public User loginUser(LoginForm loginForm) {
User user = null;
getConnection();
String sql = "select user.uid,username,headImg,lastLoginTime,lastLoginIp,user.roleid,rolename from user,role "
+ "where user.roleid = role.roleid and account=? and pwd=? and enableid=1";
try {
ps = conn.prepareStatement(sql);
ps.setString(1, loginForm.getAccount());
ps.setString(2, MD5Utils.md5(loginForm.getPwd()));
rs = ps.executeQuery();
if(rs.next()){
user = new User();
user.setUid(rs.getLong(1));
user.setUsername(rs.getString(2));
user.setHeadImg(rs.getString(3));
user.setLastLoginTime(rs.getTimestamp(4));
user.setLastLoginIp(rs.getString(5));
user.getRole().setRoleid(rs.getLong(6));
user.getRole().setRolename(rs.getString(7));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
closeResource();
}
return user;
}
@Override
public Integer checkAccount(String account) {
// TODO Auto-generated method stub
Integer disabled = 0;
getConnection();
String sql = "select enableid from user where account=?";
try {
ps = conn.prepareStatement(sql);
ps.setString(1, account);
rs = ps.executeQuery();
if(rs.next()){
disabled = rs.getInt(1);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
closeResource();
}
return disabled;
}
@Override
public List<User> findAll(User user1,PageUtil pageUtil) {
List<User> userlist = new ArrayList<User>();
getConnection();
String sql = "select * from (select tab.uid,account,username,gender,phone,rolename,enableid,enablename,departid from (select user.uid,account,username,gender,phone,roleid,user.enableid,enablename,user.departid from user,accountenable,department where user.enableid=accountenable.enableid and department.id = user.departid) tab left outer join role on tab.roleid=role.roleid) tab1 where 1=1 ";
if(user1.getAccount()!=null&&!"".equals(user1.getAccount())){
sql += "and tab1.account like ? ";
}
if(user1.getUsername()!=null&&!"".equals(user1.getUsername())){
sql += "and tab1.username like ? ";
}
if(user1.getDepartment().getId()!=null){
sql += "and tab1.departid=? ";
}
if(user1.getGender()!=null){
sql += "and tab1.gender=? ";
}
if(user1.getAccountEnable().getEnableId()!=null&&user1.getAccountEnable().getEnableId()!=0){
sql += "and tab1.enableid=? ";
}
System.out.println("listsql="+sql);
sql += " limit "+(pageUtil.getPageIndex()-1)*pageUtil.getPageNum()+","+pageUtil.getPageNum();
try {
ps = conn.prepareStatement(sql);
int index = 1;
if(user1.getAccount()!=null&&!"".equals(user1.getAccount())){
ps.setString(index, "%"+user1.getAccount()+"%");
index++;
}
if(user1.getUsername()!=null&&!"".equals(user1.getUsername())){
ps.setString(index, "%"+user1.getUsername()+"%");
index++;
}
if(user1.getDepartment().getId()!=null){
ps.setLong(index, user1.getDepartment().getId());
index++;
}
if(user1.getGender()!=null){
ps.setString(index, user1.getGender());
index++;
}
if(user1.getAccountEnable().getEnableId()!=null&&user1.getAccountEnable().getEnableId()!=0){
ps.setLong(index, user1.getAccountEnable().getEnableId());
index++;
}
rs = ps.executeQuery();
for(;rs.next();){
User user = new User();
user.setUid(rs.getLong(1));
user.setAccount(rs.getString(2));
user.setUsername(rs.getString(3));
user.setGender(rs.getString(4));
user.setPhone(rs.getString(5));
user.getRole().setRolename(rs.getString(6));
user.getAccountEnable().setEnableId(rs.getLong(7));
user.getAccountEnable().setEnableName(rs.getString(8));
userlist.add(user);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
closeResource();
}
return userlist;
}
@Override
public User findById(Long id) {
// TODO Auto-generated method stub
User user = null;
getConnection();
String sql = "select uid,account,username,gender,phone,headimg,roleid from user where uid=?";
try {
ps = conn.prepareStatement(sql);
ps.setLong(1, id);
rs = ps.executeQuery();
if(rs.next()){
user = new User();
user.setUid(rs.getLong(1));
user.setAccount(rs.getString(2));
user.setUsername(rs.getString(3));
user.setGender(rs.getString(4));
user.setPhone(rs.getString(5));
user.setHeadImg(rs.getString(6));
user.getRole().setRoleid(rs.getLong(7));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
closeResource();
}
return user;
}
@Override
public boolean save(User user) {
// TODO Auto-generated method stub
boolean flag = false;
getConnection();
String sql = "insert into user(account,pwd,gender,username,phone,headimg,enableid,roleid) values(?,'"+MD5Utils.md5("1234")+"',?,?,?,null,1,?)";
try {
ps = conn.prepareStatement(sql);
int index = 1;
ps.setString(index, user.getAccount());
index++;
ps.setString(index, user.getGender());
index++;
ps.setString(index, user.getUsername());
index++;
ps.setString(index, user.getPhone());
index++;
if(user.getRole().getRoleid()!=null){
ps.setLong(index, user.getRole().getRoleid());
}else{
//填充空值
ps.setObject(index, null);
}
int num = ps.executeUpdate();
if(num>0){
flag = true;
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
closeResource();
}
return flag;
}
@Override
public boolean edit(User user) {
// TODO Auto-generated method stub
boolean flag = false;
getConnection();
String sql = "update user set account=?,gender=?,username=?,phone=?,headimg=?,roleid=? where uid=?";
try {
ps = conn.prepareStatement(sql);
int index = 1;
ps.setString(index, user.getAccount());
index++;
ps.setString(index, user.getGender());
index++;
ps.setString(index, user.getUsername());
index++;
ps.setString(index, user.getPhone());
index++;
ps.setString(index, null);//图片
index++;
if(user.getRole().getRoleid()!=null){
ps.setLong(index, user.getRole().getRoleid());
}else{
//填充空值
ps.setObject(index, null);
}
index++;
ps.setLong(index, user.getUid());
int num = ps.executeUpdate();
if(num>0){
flag = true;
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
closeResource();
}
return flag;
}
@Override
public boolean delete(Long id) {
// TODO Auto-generated method stub
boolean flag = false;
getConnection();
String sql = "delete from user where uid=?";
try {
ps = conn.prepareStatement(sql);
ps.setLong(1, id);
int num = ps.executeUpdate();
if(num>0){
flag = true;
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
closeResource();
}
return flag;
}
@Override
public List<User> findByIds(Long[] ids) {
// TODO Auto-generated method stub
return null;
}
@Override
public boolean enableUser(Long id) {
// TODO Auto-generated method stub
boolean flag = false;
getConnection();
String sql = "update user set enableid=1 where uid=?";
try {
ps = conn.prepareStatement(sql);
ps.setLong(1, id);
int num = ps.executeUpdate();
if(num>0){
flag = true;
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
closeResource();
}
return flag;
}
@Override
public boolean disableUser(Long id) {
// TODO Auto-generated method stub
boolean flag = false;
getConnection();
String sql = "update user set enableid=-1 where uid=?";
try {
ps = conn.prepareStatement(sql);
ps.setLong(1, id);
int num = ps.executeUpdate();
if(num>0){
flag = true;
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
closeResource();
}
return flag;
}
@Override
public void initpwd(Long uid) {
// TODO Auto-generated method stub
getConnection();
String sql = "update user set pwd='<PASSWORD>' where uid=?";
try {
ps = conn.prepareStatement(sql);
ps.setLong(1, uid);
int num = ps.executeUpdate();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
closeResource();
}
}
@Override
public Long getTotalCount(User user1) {
// TODO Auto-generated method stub
Long totalCount = 0L;
getConnection();
String sql = "select count(*) from (select tab.uid,account,username,gender,phone,enableid,enablename,tab.id ,tab.roleid from (select user.uid,account,username,gender,phone,roleid,user.enableid,enablename,department.id from user,accountenable,department where user.enableid=accountenable.enableid and department.id = user.departid) tab left outer join role on tab.roleid=role.roleid) tab1 where 1=1 ";
if(user1.getAccount()!=null&&!"".equals(user1.getAccount())){
sql += "and tab1.account like ? ";
}
if(user1.getUsername()!=null&&!"".equals(user1.getUsername())){
sql += "and tab1.username like ? ";
}
if(user1.getDepartment().getId()!=null){
sql += "and tab1.id=? ";
}
if(user1.getGender()!=null){
sql += "and tab1.gender=? ";
}
if(user1.getAccountEnable().getEnableId()!=null&&user1.getAccountEnable().getEnableId()!=0){
sql += "and tab1.enableid=? ";
}
try {
ps = conn.prepareStatement(sql);
int index = 1;
if(user1.getAccount()!=null&&!"".equals(user1.getAccount())){
ps.setString(index, "%"+user1.getAccount()+"%");
index++;
}
if(user1.getUsername()!=null&&!"".equals(user1.getUsername())){
ps.setString(index, "%"+user1.getUsername()+"%");
index++;
}
if(user1.getDepartment().getId()!=null){
ps.setLong(index, user1.getDepartment().getId());
index++;
}
if(user1.getGender()!=null){
ps.setString(index, user1.getGender());
index++;
}
if(user1.getAccountEnable().getEnableId()!=null&&user1.getAccountEnable().getEnableId()!=0){
ps.setLong(index, user1.getAccountEnable().getEnableId());
index++;
}
rs = ps.executeQuery();
if(rs.next()){
totalCount = rs.getLong(1);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
closeResource();
}
return totalCount;
}
@Override
public boolean deleteByIds(Set<Long> sessionSet) {
// TODO Auto-generated method stub
boolean flag = false;
getConnection();
try {
conn.setAutoCommit(false);
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String sql = "delete from user where uid in (";
for(int i=0;i<sessionSet.size();i++){
if(i==sessionSet.size()-1){
sql += "?";
}else{
sql += "?,";
}
}
sql += ")";
try {
ps = conn.prepareStatement(sql);
int i = 0;
for(Long uid:sessionSet){
ps.setLong((i+1), uid);
i++;
}
int nums = ps.executeUpdate();
if(nums>0){
flag = true;
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
closeResource();
}
return flag;
}
@Override
public boolean initpwdByIds(Set<Long> sessionSet) {
boolean flag = false;
getConnection();
try {
conn.setAutoCommit(false);
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String sql = "update user set pwd='<PASSWORD>' where uid in (";
int i = 0;
for(Long uid:sessionSet){
if(i==sessionSet.size()-1){
sql += "?";
}else{
sql += "?,";
}
i++;
}
sql += ")";
System.out.println("sql=="+sql);
try {
ps = conn.prepareStatement(sql);
int j = 0;
for(Long uid:sessionSet){
ps.setLong((j+1), uid);
j++;
}
int nums = ps.executeUpdate();
//手动提交数据修改
conn.commit();
if(nums>0){
flag = true;
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
closeResource();
}
return flag;
}
@Override
public List<Department> findDepartmentList() {
// TODO Auto-generated method stub
List<Department> departmentlist = new ArrayList<Department>();
getConnection();
String sql = "select id,name from department";
try {
ps = conn.prepareStatement(sql);
rs = ps.executeQuery();
while(rs.next()){
Department department = new Department();
department.setId(rs.getLong(1));
department.setName(rs.getString(2));
departmentlist.add(department);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
closeResource();
}
return departmentlist;
}
@Override
public void updateRoleIdIsNull(List<Long> uids) {
// TODO Auto-generated method stub
getConnection();
String sql = "update user set roleid=null where uid=?";
try {
ps = conn.prepareStatement(sql);
for(int i=1;i<uids.size();i++){
ps.setLong(1, uids.get(i));
ps.addBatch();
}
ps.executeBatch();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
closeResource();
}
}
}
|
c2f8b080a85bb696ce9211fef7b4b5387c25a2fa
|
[
"Java",
"INI"
] | 11
|
Java
|
finn722/temprespository
|
7e68fe000c39f3cde003cf78997a9e3753c1bf9b
|
708ece65ca461340bae073f888dc7aed7f3a0036
|
refs/heads/master
|
<repo_name>vittorio101/openAtlas<file_sep>/databasemanager.cpp
//////////////////////////////////////////////////////////////////////////////
// //
// This file is part of openATLAS. //
// //
// openATLAS 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 //
// any later version. //
// //
// openATLAS 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 openATLAS. If not, see <http://www.gnu.org/licenses/>. //
// //
// Database Design by <NAME> 2013 - 2014 //
// <EMAIL> //
// Frontend developed by <NAME> 2013 - 2014 //
// <EMAIL> //
// //
//////////////////////////////////////////////////////////////////////////////
#include "databasemanager.h"
#include <QSettings>
#include <QMessageBox>
#include <QFile>
QString conn_file = "connection_to_openAtlas_connections_file";
QString conn_Postgres_DB = "connection_to_Postgres_Database";
QString conn_SQLite_DB = "connection_to_SQLite_Database";
DatabaseManager::DatabaseManager(QObject *parent) :
QObject(parent)
{
}
void DatabaseManager::startConnectionDatabase()
{
// read name of current connection from settings file
QSettings settings;
settings.beginGroup("DatabaseSettings");
QString connString = settings.value("DatafileConnections").toString();
settings.endGroup();
//check whether file connString exists
QFile file(connString);
if(!file.exists())
{
QMessageBox::critical(0, QObject::tr("Input Error"),
tr("The connection database file does not exist, please change the path or create a new one in the 'Settings'-menu!"));
}
else
{
connectionsDB = QSqlDatabase::addDatabase("QSQLITE", conn_file);
connectionsDB.setDatabaseName(connString);
connectionsDB = QSqlDatabase::database(conn_file);
QString Name = connectionsDB.databaseName();
QString Test = connectionsDB.connectionName();
}
}
bool DatabaseManager::startDB(QString password)
{
// read name of current connection and place of data file from settings file
QSettings settings;
settings.beginGroup("DatabaseSettings");
QString currentConnection = settings.value("currentDatabaseConnection").toString();
settings.endGroup();
QString connectionQueryString = "SELECT * FROM tbl_connections WHERE connection_name = '" + currentConnection + "';";
QSqlQuery connectionQuery(connectionQueryString, connectionsDB);
while(connectionQuery.next())
{
connection_name = connectionQuery.value(1).toString();
database_name = connectionQuery.value(2).toString();
database_driver = connectionQuery.value(3).toString();
database_server = connectionQuery.value(4).toString();
database_host = connectionQuery.value(5).toString();
database_port = connectionQuery.value(6).toInt();
database_username = connectionQuery.value(7).toString();
database_username_token = connectionQuery.value(8).toString();
}
if(database_driver == "QPSQL")
{
workingDB.close();
DB_Status = false;
workingDB = QSqlDatabase::addDatabase("QPSQL", conn_Postgres_DB);
workingDB.setDatabaseName(database_name);
workingDB.setHostName(database_host);
workingDB.setPort(database_port);
workingDB.setUserName(database_username);
workingDB.setPassword(<PASSWORD>);
if (!workingDB.open())
{
QMessageBox::critical(0, QObject::tr("Database Error"),
workingDB.lastError().text());
}
else
{
DB_Status = true;
return DB_Status;
}
}
else
{
DB_Status = false;
QFile file(database_name);
if(!file.exists())
{
QMessageBox::critical(0, QObject::tr("Input Error"),
tr("The database file does not exist, please change the path or create a new one in the 'Settings'-menu!"));
DB_Status = false;
}
else
{
workingDB = QSqlDatabase::addDatabase("QSQLITE", conn_SQLite_DB);
workingDB.setDatabaseName(database_name);
DB_Status = true;
}
return DB_Status;
}
}
<file_sep>/typewizard.h
#ifndef TYPEWIZARD_H
#define TYPEWIZARD_H
#include <QDialog>
#include <QtSql>
#include <QSortFilterProxyModel>
namespace Ui {
class TypeWizard;
}
class TypeWizard : public QDialog
{
Q_OBJECT
public:
explicit TypeWizard(const int &Level, QWidget *parent = 0);
~TypeWizard();
private:
int DataLevel;
Ui::TypeWizard *ui;
private slots:
void on_lineEdit_Filter_textEdited();
};
#endif // TYPEWIZARD_H
<file_sep>/mainwindow.h
//////////////////////////////////////////////////////////////////////////////
// //
// This file is part of openATLAS. //
// //
// openATLAS 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 //
// any later version. //
// //
// openATLAS 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 openATLAS. If not, see <http://www.gnu.org/licenses/>. //
// //
// Database Design by <NAME> 2013 - 2014 //
// <EMAIL> //
// Frontend developed by <NAME> 2013 - 2014 //
// <EMAIL> //
// //
//////////////////////////////////////////////////////////////////////////////
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QComboBox>
#include <QLabel>
#include <QtSql>
#include <ui_mainwindow.h>
#include <QSortFilterProxyModel>
#include <QNetworkReply>
#include <QStandardItemModel>
#include <marble/GeoPainter.h>
#include <marble/GeoDataDocument.h>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
QStandardItemModel* iStandardModel;
private:
Ui::MainWindow *ui;
void setupConnectionsModel();
void updateCurrentConnection();
void checkConnectionBasics();
void updateStatusBar(QString Text, int intIcon); //int Icon: 0 = try to connect, 1 = no connection, 2 = connected
void TimeMeasurementStatusBar(QString timeString);
void view_Basic();
void view_Items_clicked();
QStringList extractUidFromModel(QAbstractItemModel *model, const QModelIndex &parent);
QStringList extractStringsFromModel(QAbstractItemModel *model, const QModelIndex &parent, int column);
void loadLocalPicture(QString);
void loadOnlinePicture(QString);
void showMainpicture(QPixmap *pm);
void analyseMainImagePath(QString);
void HERE__START__THE__PRIVATE__SLOTS();
void update_sites_overview();
void update_sites_overview(QString marked);
void show_sites_in_database();
void show_features_in_site();
void show_su_in_feature();
void show_finds_in_su();
void clear_all_tabs();
void fill_listviewThumbnails(QString clickedUid);
void loadPlaceholder();
private slots:
// void on_listView_Content_clicked(const QModelIndex &index);
void update_tableViewItems(QString strIndex);
void on_lineEdit_Filter_textEdited();
void on_tableViewItems_clicked(const QModelIndex &index);
void on_tableViewItems_doubleClicked(const QModelIndex &index);
void on_createConnection_clicked();
void check_answer_changeConnectionDlg(const QString &newComboboxText);
void slot_netwManagerFinished(QNetworkReply *reply);
void on_pushButton_Edit_Overview_clicked();
void on_pushButton_TypeWizard_clicked();
void on_toolButton_Datalevel_home_clicked();
void on_toolButton_Datalevel_up_clicked();
void on_tableViewLocation_clicked();
void on_tableViewCultural_clicked();
void on_tableViewChronological_clicked();
void on_tableViewBibliography_clicked();
void on_tableViewEvidence_clicked();
void on_actionAbout_Qt_clicked();
void on_actionAbout_openAtlas_clicked();
void on_actionApplication_Preferences_clicked();
void on_actionTreeEditor_clicked();
protected:
QComboBox *ComboBoxConnections = new QComboBox;
QLabel *StatusbarLoadingTime = new QLabel;
QSqlQueryModel *listViewCategoriesModel = new QSqlQueryModel;
QSqlQueryModel *tableViewItemsModel = new QSqlQueryModel;
QSqlQueryModel *tableViewLocationModel = new QSqlQueryModel;
QSqlQueryModel *tableViewCulturalModel = new QSqlQueryModel;
QSqlQueryModel *tableViewChronologicalModel = new QSqlQueryModel;
QSqlQueryModel *tableViewBibliographyModel = new QSqlQueryModel;
QSqlQueryModel *tableViewEvidenceModel = new QSqlQueryModel;
QSortFilterProxyModel *proxymodelSites = new QSortFilterProxyModel;
QSortFilterProxyModel *proxymodelLocation = new QSortFilterProxyModel;
QSortFilterProxyModel *proxymodelCultural = new QSortFilterProxyModel;
QSortFilterProxyModel *proxymodelChronological = new QSortFilterProxyModel;
QSortFilterProxyModel *proxymodelBibliography = new QSortFilterProxyModel;
QSortFilterProxyModel *proxymodelEvidence = new QSortFilterProxyModel;
QSqlQueryModel *emptyViewItemsModel = new QSqlQueryModel;
Marble::GeoDataDocument *document = new Marble::GeoDataDocument;
virtual void wheelEvent(QWheelEvent* wheel);
void resizeEvent(QResizeEvent *resize);
QGraphicsScene *gs = new QGraphicsScene;
QPixmap *pm = new QPixmap;
QStandardItemModel *itemModel = new QStandardItemModel;
};
#endif // MAINWINDOW_H
<file_sep>/firststart.cpp
//////////////////////////////////////////////////////////////////////////////
// //
// This file is part of openATLAS. //
// //
// openATLAS 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 //
// any later version. //
// //
// openATLAS 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 openATLAS. If not, see <http://www.gnu.org/licenses/>. //
// //
// Database Design by <NAME> 2013 - 2014 //
// <EMAIL> //
// Frontend developed by <NAME> 2013 - 2014 //
// <EMAIL> //
// //
//////////////////////////////////////////////////////////////////////////////
#include "firststart.h"
#include "ui_firststart.h"
#include "createconnection.h"
#include <QFileDialog>
#include <QtSql>
#include <QMessageBox>
#include <QSettings>
#include <QString>
QString connectionsDir;
QString connectionFileName;
//////////////////////////////////////////////////////////////////////////////
// //
// Constructor and Deconstructor //
// for firstStart //
// //
//////////////////////////////////////////////////////////////////////////////
// Constructor
//////////////////////////////////////////////////////////////////////////////
firstStart::firstStart(QWidget *parent) :
QDialog(parent),
ui(new Ui::firstStart)
{
ui->setupUi(this);
firstScreen();
}
// Deconstructor
//////////////////////////////////////////////////////////////////////////////
firstStart::~firstStart()
{
delete ui;
}
//////////////////////////////////////////////////////////////////////////////
// //
// Private slots for firstStart //
// //
//////////////////////////////////////////////////////////////////////////////
void firstStart::on_toolButtonOpenFileDialog_clicked()
{
connectionsDir = QFileDialog::getExistingDirectory(this, tr("Open Directory"),
"",
QFileDialog::ShowDirsOnly
| QFileDialog::DontResolveSymlinks);
if(!connectionsDir.isEmpty())
{
QDir DirDatabaseFile = connectionsDir;
connectionFileName = DirDatabaseFile.absoluteFilePath("openatlas.cdf");
ui->lineEditPathConnections->setText((connectionFileName));
}
}
void firstStart::on_pushButton_01_Next_clicked()
{
secondScreen();
}
void firstStart::on_pushButton_02_Next_clicked()
{
thirdScreen();
QString create_DB_02;
QString create_DB_01 = "Create database '" + connectionFileName + "'...";
ui->plainTextEdit->setPlainText(create_DB_01);
QSqlDatabase database = QSqlDatabase::addDatabase("QSQLITE");
database.setDatabaseName(connectionFileName);
database.open();
if(!database.open())
{
QMessageBox::critical(0, tr("Cannot open database!"),
tr("Cannot create the connection data file!\n\nTip: Check, if you have write permission in this directory and if there is enough disk space!"),
QMessageBox::Cancel);
firstScreen();
}
else
{
create_DB_02 = create_DB_01 + "\nDone!\nCreate table 'tbl_connections'...";
ui->plainTextEdit->setPlainText(create_DB_02);
QSqlQuery query;
QString QueryString = "CREATE TABLE tbl_connections (oid INTEGER PRIMARY KEY, connection_name TEXT, database_name TEXT, database_driver TEXT, database_server TEXT, database_host TEXT, database_port INTEGER, database_username TEXT, database_username_token TEXT, database_password TEXT, UNIQUE (connection_name));";
query.exec(QueryString);
database.close();
QSettings settings;
settings.beginGroup("DatabaseSettings");
settings.setValue("DatafileConnections", connectionFileName);
QString create_DB_03 = create_DB_02 + "\nDone!\n\nClick the 'Next'-button to create a new database connection...";
ui->plainTextEdit->setPlainText(create_DB_03);
}
}
void firstStart::on_pushButton_02_Back_clicked()
{
firstScreen();
}
void firstStart::on_pushButton_03_Next_clicked()
{
CreateConnection *conndlg = new CreateConnection;
conndlg->exec();
ui->pushButton_01_Next->setVisible(false);
ui->pushButton_02_Next->setVisible(false);
ui->pushButton_02_Back->setVisible(false);
ui->pushButton_03_Next->setVisible(false);
QIcon icon1;
icon1.addFile(QString(":/buttons/Button_Ok"), QSize(), QIcon::Normal, QIcon::Off);
icon1.addFile((":/buttons/Button_Ok"), QSize(), QIcon::Normal, QIcon::Off);
ui->pushButton_01_Cancel->setIcon(icon1);
ui->pushButton_01_Cancel->setText("Finish");
ui->plainTextEdit->setPlainText(tr("Congratulations!\n\nOpenATLAS is now ready for use. Close this window by clicking the 'Finish'-button to start openAtlas.\n\nHave fun!!"));
}
//////////////////////////////////////////////////////////////////////////////
// //
// Private functions for CreateConnection //
// //
//////////////////////////////////////////////////////////////////////////////
//This functions are paiting the screen in different modes
//////////////////////////////////////////////////////////////////////////////
void firstStart::firstScreen()
{
//function NOT ready!!!
ui->groupBox->setTitle(tr("Step 1"));
ui->labelPathQuestion->setVisible(false);
ui->lineEditPathConnections->setVisible(true);
ui->toolButtonOpenFileDialog->setVisible(true);
ui->lineEditPathConnections->setText(connectionFileName);
ui->plainTextEdit->setVisible(true);
ui->plainTextEdit->setGeometry(QRect(10, 70, 461, 111));
ui->plainTextEdit->clear();
ui->plainTextEdit->setPlainText(tr("This seems to be the first start of openAtlas! Please set a folder, where the database connections will be saved..."));
ui->pushButton_01_Next->setVisible(true);
ui->pushButton_02_Next->setVisible(false);
ui->pushButton_02_Back->setVisible(false);
ui->pushButton_03_Next->setVisible(false);
}
void firstStart::secondScreen()
{
ui->groupBox->setTitle(tr("Step 2"));
ui->plainTextEdit->setVisible(false);
ui->labelPathQuestion->setVisible(true);
QString pathQuestion = "Do you want to create the connection data file 'openatlas.cdf' in\n\n" + connectionsDir + "?\n\nIf you want to change the folder, please click the 'Back'-Button, otherwise the 'Next'-Button.";
ui->labelPathQuestion->setText(pathQuestion);
ui->lineEditPathConnections->setVisible(false);
ui->toolButtonOpenFileDialog->setVisible(false);
ui->pushButton_01_Next->setVisible(false);
ui->pushButton_02_Next->setVisible(true);
ui->pushButton_02_Back->setVisible(true);
ui->pushButton_03_Next->setVisible(false);
}
void firstStart::thirdScreen()
{
ui->groupBox->setTitle(tr("Step 3"));
ui->plainTextEdit->setVisible(true);
ui->plainTextEdit->clear();
ui->plainTextEdit->setGeometry(QRect(10, 30, 461, 151));
ui->labelPathQuestion->setVisible(false);
ui->pushButton_01_Next->setVisible(false);
ui->pushButton_02_Next->setVisible(false);
ui->pushButton_02_Back->setVisible(false);
ui->pushButton_03_Next->setVisible(true);
}
<file_sep>/createconnection.h
//////////////////////////////////////////////////////////////////////////////
// //
// This file is part of openATLAS. //
// //
// openATLAS 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 //
// any later version. //
// //
// openATLAS 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 openATLAS. If not, see <http://www.gnu.org/licenses/>. //
// //
// Database Design by <NAME> 2013 - 2014 //
// <EMAIL> //
// Frontend developed by <NAME> 2013 - 2014 //
// <EMAIL> //
// //
//////////////////////////////////////////////////////////////////////////////
#ifndef CREATECONNECTION_H
#define CREATECONNECTION_H
#include <QDialog>
namespace Ui {
class CreateConnection;
}
class CreateConnection : public QDialog
{
Q_OBJECT
public:
explicit CreateConnection(QWidget *parent = 0);
~CreateConnection();
private slots:
void on_comboBoxDatabaseLocation_currentIndexChanged(const QString &location);
void on_toolButtonOpenFile_clicked();
void on_pushButtonTestConnection_clicked();
void on_pushButtonOk_clicked();
void on_lineEditDatabaseFile_textChanged();
void on_lineEditHostname_textChanged();
void on_lineEditPort_textChanged();
void on_lineEditUserName_textChanged();
void on_lineEditUserToken_textChanged();
void on_lineEditPassword_textChanged();
private:
Ui::CreateConnection *ui;
void setUiToLocal();
void setUiToNetwork();
bool checkContentOfLineSQLite();
bool checkContentOfLinePostgreSQL();
void inputErrorMsgBox(QString);
void saveSettings();
};
#endif // CREATECONNECTION_H
<file_sep>/firststart.h
//////////////////////////////////////////////////////////////////////////////
// //
// This file is part of openATLAS. //
// //
// openATLAS 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 //
// any later version. //
// //
// openATLAS 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 openATLAS. If not, see <http://www.gnu.org/licenses/>. //
// //
// Database Design by <NAME> 2013 - 2014 //
// <EMAIL> //
// Frontend developed by <NAME> 2013 - 2014 //
// <EMAIL> //
// //
//////////////////////////////////////////////////////////////////////////////
#ifndef FIRSTSTART_H
#define FIRSTSTART_H
#include <QDialog>
namespace Ui {
class firstStart;
}
class firstStart : public QDialog
{
Q_OBJECT
public:
explicit firstStart(QWidget *parent = 0);
~firstStart();
private:
Ui::firstStart *ui;
private slots:
void firstScreen();
void secondScreen();
void thirdScreen();
void on_toolButtonOpenFileDialog_clicked();
void on_pushButton_01_Next_clicked();
void on_pushButton_02_Back_clicked();
void on_pushButton_02_Next_clicked();
void on_pushButton_03_Next_clicked();
};
#endif // FIRSTSTART_H
<file_sep>/tree_editor.cpp
#include "tree_editor.h"
#include "ui_tree_editor.h"
#include "databasemanager.h"
#include <QStandardItemModel>
#include <QtSql>
#include <QDebug>
Tree_Editor::Tree_Editor(QWidget *parent) :
QDialog(parent),
ui(new Ui::Tree_Editor)
{
ui->setupUi(this);
// fill combobox with types
QSqlQueryModel *categoryModel = new QSqlQueryModel();
categoryModel->setQuery("SELECT child_name, child_id FROM openatlas.types_parent_child WHERE parent_id = 15", myDBM->workingDB);
ui->comboBox_SelectCategory->setModel(categoryModel);
// Modell erstellen
QStandardItemModel *commModel = new QStandardItemModel; // Modell erstellen
QStandardItem *parentItem = commModel->invisibleRootItem(); // Root Item erstellen
// QString rootNodesQueryString = "SELECT * FROM openatlas.types_parent_child WHERE parent_id = 15";
// QSqlQuery rootNodesQuery(rootNodesQueryString,myDBM->workingDB);
// while(rootNodesQuery.next())
// {
// QString rootNode = rootNodesQuery.value(3).toString();
// QStandardItem *item = new QStandardItem(QString(rootNode)); // Child vom Root
// parentItem->appendRow(item);
// qDebug() << item;
// }
//hier die Items (aber Daten sinds immer noch nicht!!!)
QStandardItem *item1 = new QStandardItem(QString("item1")); // Child vom Root
QStandardItem *item1_1Col1 = new QStandardItem(QString("item1_1Col1")); // Spalte 1 vom ChildChild
QStandardItem *item1_1Col2 = new QStandardItem(QString("item1_1Col2")); // Spalte 2 vom ChildChild
QStandardItem *item1_1Col3 = new QStandardItem(QString("item1_1Col3")); // Spalte 3 vom ChildChild
parentItem->appendRow(item1); // dem Root das Child anhängen
// Spalten vorbereiten
QList<QStandardItem*> itemList;
itemList.append(item1_1Col1);
itemList.append(item1_1Col2);
itemList.append(item1_1Col3);
item1->appendRow(itemList); // Child an Child hängen
commModel->setColumnCount(3); // 3 Spalten anzeigen
ui->treeView->setModel(commModel);
}
Tree_Editor::~Tree_Editor()
{
delete ui;
}
void Tree_Editor::on_comboBox_SelectCategory_currentIndexChanged(QString index)
{
}
<file_sep>/mainwindow.cpp
//////////////////////////////////////////////////////////////////////////////
// //
// This file is part of openATLAS. //
// //
// openATLAS 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 //
// any later version. //
// //
// openATLAS 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 openATLAS. If not, see <http://www.gnu.org/licenses/>. //
// //
// Database Design by <NAME> 2013 - 2014 //
// <EMAIL> //
// Frontend developed by <NAME> 2013 - 2014 //
// <EMAIL> //
// //
//////////////////////////////////////////////////////////////////////////////
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "version.h"
#include "databasemanager.h"
#include "login.h"
#include "createconnection.h"
#include "typewizard.h"
#include "preferences.h"
#include "tree_editor.h"
#include <marble/MarbleWidget.h>
#include <marble/GeoPainter.h>
#include <marble/GeoDataDocument.h>
#include <marble/GeoDataPlacemark.h>
#include <marble/GeoDataTreeModel.h>
#include <marble/MarbleModel.h>
#include <QScrollArea>
#include <QSettings>
#include <QDebug>
#include <QMessageBox>
#include <QStatusBar>
#include <QTimer>
#include <QtNetwork/QNetworkReply>
#include <QtNetwork/QNetworkAccessManager>
#include <QtNetwork/QNetworkRequest>
#include <QUrl>
//#include <QList>
//#include <QPair>
#include <QTableWidgetItem>
//#include <QVector>
#include <QHttp>
#include <QListWidgetItem>
#include <iostream>
using namespace Marble;
// database connection data
QString conn_to_openatlas_connections_file = "Connection_to_ConnectionsDataFile";
QString conn_to_openaltas_database = "Connection_to_openAtlas_Database";
QString currentConnection;
QString connString;
QString connection_name;
QString database_name;
QString database_driver;
QString database_server;
QString database_host;
QString database_port;
QString database_username;
QString database_username_token;
QString database_password;
QString trimmedText;
QString listViewCategoriesQuery;
QString x_lon_easting;
QString y_lat_northing;
QString ProjCS;
int categoryIndex;
int itemIndex;
int locationIndex;
int itemKey;
int nameUid;
bool DatabaseStatus;
QSqlDatabase connectionDB;
//class-wide variables for different purposes
QString strIndex;
QString strItem;
QString currentSite;
QString currentFeature;
QString currentStratigraphicalUnit;
QString currentFind;
QString groupBoxTitle;
// combobox strings
QString currentComboboxText;
QString newComboboxText;
// statusbar and statusbar strings
QStatusBar *statusbar;
QLabel *StatusbarIcon;
QLabel *StatusbarText;
// UI elements
QString filter;
QString strItem_part1;
QString strItem_part2;
QString strdataLevel;
QString imagePath;
//History for browser
int dataLevel;
QString last_clickedSite;
QString last_clickedSiteUid;
QModelIndex siteIndex;
QString last_clickedFeature;
QString last_clickedFeatureUid;
QModelIndex featureIndex;
QString last_clickedSU;
QString last_clickedSUUid;
QModelIndex suIndex;
QString last_clickedFind;
QString last_clickedFindUid;
QModelIndex findIndex;
QString clickedItem;
QStringList stringUids;
QString clickedUid;
QString clickedLocationUid;
QVariant varClickedItem;
QVariant varClickedLocation;
QString strNamePath;
bool ImageView;
QString mainImage;
QString imagePrefix;
QString imagePostfix;
QString imageName;
bool tabSitesDimensions;
/******************************************************************************
******************************************************************************
******************************************************************************
* *
* Constructor and Deconstructor *
* for mainWindow *
* *
******************************************************************************
******************************************************************************
*****************************************************************************/
/******************************************************************************
* MainWindow(QWidget*): Constructor, creates the MainWindow class
* Creates the main window, passing the parent to QMainWindow, and initializing
* the ui.
*****************************************************************************/
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
QString firstStart = "NO";
dataLevel = 0;
if(!myDBM->workingDB.isOpen())
{
myDBM->startConnectionDatabase();
}
//read application settings from standard settings location (OS dependend)
QSettings settings;
settings.beginGroup("MainWindow");
settings.setValue("FirstStart", firstStart);
restoreGeometry(settings.value("mainWindowGeometry").toByteArray());
restoreState(settings.value("mainWindowState").toByteArray());
int TabIndex = settings.value("TabIndex").toInt();
int TabDetailsIndex = settings.value("TabDetailsIndex").toInt();
int TabWidgetSpatialIndex = settings.value("TabSpatialIndex").toInt();
settings.endGroup();
settings.beginGroup("DatabaseSettings");
currentConnection = settings.value("currentDatabaseConnection").toString();
settings.endGroup();
settings.beginGroup("Preferences");
ImageView = settings.value("ImageViewActivated").toBool();
imagePrefix = settings.value("ImageFolderPath").toString();
imagePostfix = settings.value("ImageFileExtension").toString();
tabSitesDimensions = settings.value("TabSitesDimension").toBool();
settings.endGroup();
//create MainWindow
ui->setupUi(this);
// hide experimental tabs
ui->tabWidget_ItemDetails->removeTab(6);
ui->tabWidget_ItemDetails->removeTab(4);
this->setWindowTitle(openAtlasVersion);
ui->tabWidget->setCurrentIndex(TabIndex);
ui->tabWidget_ItemDetails->setCurrentIndex(TabDetailsIndex);
ui->tabWidget_Spatial->setCurrentIndex(TabWidgetSpatialIndex);
//Add QCombobox for Database Connections to toolbar 'Database'
ComboBoxConnections->setFixedHeight(24);
ComboBoxConnections->setFixedWidth(200);
ui->toolBarDatabase->addWidget(ComboBoxConnections);
setupConnectionsModel();
ComboBoxConnections->setCurrentIndex(ComboBoxConnections->findData(currentConnection, Qt::DisplayRole));
//create statusbar
StatusbarIcon = new QLabel(this);
StatusbarText = new QLabel(this);
StatusbarLoadingTime = new QLabel(this);
StatusbarLoadingTime->setText("Time Measurement");
StatusbarLoadingTime->setIndent(10);
ui->statusBar->addWidget(StatusbarLoadingTime);
ui->statusBar->addPermanentWidget(StatusbarText);
ui->statusBar->addPermanentWidget(StatusbarIcon);
// set some GUI settings
ui->lineEdit_Filter->installEventFilter(this);
ui->radioButton_OpenStreetMap->setChecked(true);
ui->pushButton_TypeWizard->setDisabled(true);
// set MarbleWidget properties
ui->MarbleWidget->setShowOverviewMap(false);
GeoDataPlacemark *place = new GeoDataPlacemark("Institute of Prehistoric and Historical Archaeology, University of Vienna");
place->setCoordinate( 16.3488, 48.2335, 0.0, GeoDataCoordinates::Degree );
GeoDataDocument *document = new GeoDataDocument;
document->append(place);
// Add the document to MarbleWidget's tree model
ui->MarbleWidget->model()->treeModel()->addDocument(document);
// set view to location University of Vienna, Department for Pre- and Early History
ui->MarbleWidget->centerOn(16.3488,48.2335);
//ui->MarbleWidget->zoomView(3500);
ui->MarbleWidget->zoomView(5000);
// set background color of thumbnails viewer to black
ui->listView_Thumbnails->setStyleSheet("* { background-color: rgb(0, 0, 0); }");
// load empty picture to graphicsview
loadLocalPicture("placeholder_empty.png");
view_Basic();
checkConnectionBasics();
// waiting for signal from combobox 'ComboBoxConnections'
connect(ComboBoxConnections, SIGNAL(currentIndexChanged(const QString)),
this, SLOT(check_answer_changeConnectionDlg(const QString)));
}
/******************************************************************************
* ~MainWindow(): Destructor
* Save application settings and deletes the ui.
*****************************************************************************/
MainWindow::~MainWindow()
{
//save application settings to standard location (OS dependend!)
QSettings settings;
settings.beginGroup("MainWindow");
settings.setValue("mainWindowState", saveState());
settings.setValue("mainWindowGeometry", saveGeometry());
settings.setValue("TabIndex", ui->tabWidget->currentIndex());
settings.setValue("TabDetailsIndex", ui->tabWidget_ItemDetails->currentIndex());
settings.setValue("TabSpatialIndex", ui->tabWidget_Spatial->currentIndex());
settings.endGroup();
delete ui;
}
/******************************************************************************
******************************************************************************
******************************************************************************
* *
* Private functions for MainWindow *
* *
******************************************************************************
******************************************************************************
*****************************************************************************/
/******************************************************************************
* updateCurrentConnection(): Private function
* Set ComboBox text to current connection name
* Last edit: 09.05.2014
*****************************************************************************/
void MainWindow::updateCurrentConnection()
{
QString newCurrentConnection = ComboBoxConnections->currentText();
QSettings settings;
settings.beginGroup("DatabaseSettings");
settings.setValue("currentDatabaseConnection", newCurrentConnection);
settings.endGroup();
}
/******************************************************************************
* view_Basic(): Private function
* Set visibility and content of all elements
* to the start view
* Last edit: 09.05.2014
*****************************************************************************/
void MainWindow::view_Basic()
{
ui->textEdit_DataLevel->setText("sites");
ui->lineEdit_Filter->setText("");
filter = ui->lineEdit_Filter->text();
on_lineEdit_Filter_textEdited();
ui->tabWidget->setDisabled(true);
ui->toolButton_Delete_Item->setDisabled(true);
ui->groupBox_Details->setTitle("Details for item");
// groupbox 'Spatial Info'
ui->textEdit_SpatialInfo_LocatedIn->clear();
ui->lineEdit_SpatialInfo_Easting->clear();
ui->lineEdit_SpatialInfo_Northing->clear();
ui->lineEdit_SpatialInfo_EPSG->clear();
ui->lineEdit_SpatialInfo_CS->clear();
ui->textEdit_Name->clear();
ui->textEdit_Description->clear();
ui->textEdit_Type->clear();
// MarbleWidget
ui->textEdit_Overview->clear();
ui->MarbleWidget->centerOn(16.3488,48.2335);
//ui->MarbleWidget->zoomView(3500);
ui->MarbleWidget->zoomView(5000);
}
/******************************************************************************
* view_items_clicked(): Private function
* Set visibility and content of all elements
* to the state 'items clicked'
* Last edit: 09.05.2014
*****************************************************************************/
void MainWindow::view_Items_clicked()
{
// clear all content
ui->textEdit_Name->clear();
ui->textEdit_Description->clear();
ui->textEdit_Type->clear();
// generell view settings
ui->tabWidget->setEnabled(true);
ui->toolButton_Delete_Item->setEnabled(true);
// set items in groupbox 'Overview' ReadOnly
ui->textEdit_Name->setReadOnly(true);
ui->textEdit_Type->setReadOnly(true);
ui->textEdit_Description->setReadOnly(true);
// set 'Item Details' buttons
ui->pushButton_Save_Overview->setDisabled(true);
ui->pushButton_Cancel_Overview->setDisabled(true);
ui->pushButton_TypeWizard->setDisabled(true);
// set 'Item Spatial Info' buttons
ui->pushButton_Save_SpatialInfo->setDisabled(true);
ui->pushButton_Cancel_SpatialInfo->setDisabled(true);
// set items in groupbox 'Spatial Info' ReadOnly
ui->textEdit_SpatialInfo_LocatedIn->setReadOnly(true);
ui->lineEdit_SpatialInfo_Easting->setReadOnly(true);
ui->lineEdit_SpatialInfo_Northing->setReadOnly(true);
ui->lineEdit_SpatialInfo_EPSG->setReadOnly(true);
ui->lineEdit_SpatialInfo_CS->setReadOnly(true);
// set buttons in Tab 'Cultural/Temporal' disabled
ui->pushButton_Cancel_Cultural->setDisabled(true);
ui->pushButton_Save_Cultural->setDisabled(true);
//QWidget *removedTab = ui->tabWidget->widget(3);
// QWidget *removedTab = ui->tab_Dimensions;
// qDebug()<< removedTab;
// ui->tabWidget_ItemDetails->removeTab(3);
// qDebug() << "Tab removed!";
// //ui->tabWidget->insertTab(3, removedTab, "TestWidget");
// ui->tabWidget->addTab(removedTab,"TestWidget");
}
/******************************************************************************
* setupConnectionsModel(): Private function
* Open the database connection file 'openatlas.cdf'
* and show the available connection names in 'ComboboxConnections'
* Last edit: 09.05.2014
*****************************************************************************/
void MainWindow::setupConnectionsModel()
{
QSqlQueryModel *model = new QSqlQueryModel();
model->setQuery("SELECT connection_name FROM tbl_connections", myDBM->connectionsDB);
ComboBoxConnections->setModel(model);
}
/******************************************************************************
* checkConnectionBasics(): Private function
* check basis connection settings
* Last edit: 09.05.2014
*****************************************************************************/
void MainWindow::checkConnectionBasics()
{
QString passwordNew;
QSettings settings;
settings.beginGroup("DatabaseSettings");
currentConnection = settings.value("currentDatabaseConnection").toString();
settings.endGroup();
QSqlDatabase connectionDB = QSqlDatabase::database(myDBM->conn_file);
QString connectionQueryString = "SELECT * FROM tbl_connections WHERE connection_name = '" + currentConnection + "';";
QSqlQuery connectionQuery(connectionQueryString, connectionDB);
while(connectionQuery.next())
{
connection_name = connectionQuery.value(1).toString();
database_name = connectionQuery.value(2).toString();
database_driver = connectionQuery.value(3).toString();
database_password = connectionQuery.value(9).toString();
}
if(database_password == "YES")
{
QString statusText = "Try to connect to " + database_name + " using connection '" + ComboBoxConnections->currentText() + "'...";
updateStatusBar(statusText, 0);
Login login;
if (login.exec() == QDialog::Accepted)
{
const QString password = login.linePassword();
passwordNew = password;
login.close();
}
else
{
QMessageBox::critical(this, tr("Connection Error"), tr("Cannot connect to database!"));
QString statusText = "Cannot connect to database " + database_name + "!";
updateStatusBar(statusText, 1);
return;
}
DatabaseStatus = myDBM->startDB(passwordNew);
}
else
{
DatabaseStatus = myDBM->startDB("");
}
//check, if the connection to the database works
if(DatabaseStatus == true)
{
QString statusText = "Connected to database " + database_name;
updateStatusBar(statusText, 2);
}
else
{
QString statusText = "Cannot connect to database " + database_name + "!";
updateStatusBar(statusText, 1);
myDBM->workingDB.close();
}
update_sites_overview();
}
/******************************************************************************
* update_sites_overview(): Private function
* load all sites on database and show in 'tableViewItems'
* Last edit: 09.05.2014
*****************************************************************************/
void MainWindow::update_sites_overview()
{
dataLevel = 0;
qDebug() << "'update_sites_overview', datalevel: " << dataLevel;
ui->textEdit_DataLevel->setText("sites");
ui->lineEdit_Filter->clear();
filter = "";
on_lineEdit_Filter_textEdited();
//update config settings
QSettings settings;
settings.beginGroup("DatabaseSettings");
currentConnection = settings.value("currentDatabaseConnection").toString();
settings.endGroup();
if(myDBM->workingDB.driverName() =="QPSQL")
{
QString query = "SELECT sites.uid, sites.entity_name_uri FROM openatlas.sites ORDER BY sites.entity_name_uri ASC;";
QTime myTimer;
myTimer.start();
int intNumber;
QString strNumber;
tableViewItemsModel->setQuery(query, myDBM->workingDB);
proxymodelSites->setSourceModel(tableViewItemsModel);
ui->tableViewItems->setModel(proxymodelSites);
ui->tableViewItems->resizeColumnToContents(1);
ui->tableViewItems->resizeRowsToContents();
ui->tableViewItems->hideColumn(0);
ui->tableViewItems->model()->setHeaderData(1, Qt::Horizontal, QObject::tr(""));
//ui->tableViewItems->activated(clickedUid);
int Milliseconds = myTimer.elapsed();
float Seconds = (float) Milliseconds/1000;
QString strSeconds;
strSeconds.append(QString("%1").arg(Seconds));
intNumber = tableViewItemsModel->query().size();
strNumber.append(QString("%1").arg(intNumber));
QString time = strNumber +" items loaded in " + strSeconds + " sec.";
TimeMeasurementStatusBar(time);
}
else
{
listViewCategoriesModel->setQuery("SELECT name FROM sqlite_master WHERE type='table'", myDBM->workingDB);
qDebug() << myDBM->workingDB.lastError();
}
clear_all_tabs();
}
/******************************************************************************
* update_sites_overview(QString marked): Private function
* load all sites on database and show in 'tableViewItems'
* Last edit: 09.05.2014
*****************************************************************************/
void MainWindow::update_sites_overview(QString marked)
{
dataLevel = 0;
qDebug() << "'update_sites_overview', datalevel: " << dataLevel;
ui->textEdit_DataLevel->setText("sites");
ui->lineEdit_Filter->clear();
filter = "";
on_lineEdit_Filter_textEdited();
//update config settings
QSettings settings;
settings.beginGroup("DatabaseSettings");
currentConnection = settings.value("currentDatabaseConnection").toString();
settings.endGroup();
if(myDBM->workingDB.driverName() =="QPSQL")
{
QString query = "SELECT sites.uid, sites.entity_name_uri FROM openatlas.sites ORDER BY sites.entity_name_uri ASC;";
tableViewItemsModel->setQuery(query, myDBM->workingDB);
proxymodelSites->setSourceModel(tableViewItemsModel);
int intActivatedItem= marked.toInt();
QModelIndex activatedItem(siteIndex);
ui->tableViewItems->setModel(proxymodelSites);
ui->tableViewItems->resizeColumnToContents(1);
ui->tableViewItems->resizeRowsToContents();
ui->tableViewItems->hideColumn(0);
//ui->tableViewItems->setCurrentIndex(siteIndex);
}
else
{
// listViewCategoriesModel->setQuery("SELECT name FROM sqlite_master WHERE type='table'", myDBM->workingDB);
// qDebug() << myDBM->workingDB.lastError();
}
}
/******************************************************************************
* updateStatusBar(QString Text, int intIcon): Private function
* write state of database connection to the right status ar
* Last edit: 09.05.2014
*****************************************************************************/
void MainWindow::updateStatusBar(QString Text, int intIcon)
{
switch(intIcon)
{
case 0:
StatusbarIcon->setPixmap(QPixmap(QString::fromUtf8(":/small/working")));
break;
case 1:
StatusbarIcon->setPixmap(QPixmap(QString::fromUtf8(":/small/disconnected")));
break;
case 2:
StatusbarIcon->setPixmap(QPixmap(QString::fromUtf8(":/small/connected")));
break;
}
StatusbarText->setText(Text);
}
/******************************************************************************
* TimeMeasurementStatusBar(QString timeString): Private function
* write loading time to the left status bar
* Last edit: 09.05.2014
*****************************************************************************/
void MainWindow::TimeMeasurementStatusBar(QString timeString)
{
StatusbarLoadingTime->setText(timeString);
}
/******************************************************************************
* on_lineEdit_Filter_textEdited(): Private function
* search filter for 'tableItemsView'
* Last edit: 09.05.2014
*****************************************************************************/
void MainWindow::on_lineEdit_Filter_textEdited()
{
filter = ui->lineEdit_Filter->text();
proxymodelSites->setFilterRegExp(QRegExp(filter, Qt::CaseInsensitive, QRegExp::Wildcard));
proxymodelSites->setFilterKeyColumn(1);
}
/******************************************************************************
* extractStringsFromModel(QAbstractItemModel *model,
* const QModelIndex &parent, int column): Private function
* Extract strings from datamodel
* Last edit: 09.05.2014
*****************************************************************************/
QStringList MainWindow::extractStringsFromModel(QAbstractItemModel *model, const QModelIndex &parent, int column)
{
QStringList retval;
int rowCount = model->rowCount(parent);
for(int i = 0; i < rowCount; ++i)
{
QModelIndex idx = model->index(i, column, parent);
if(idx.isValid())
{
retval << idx.data(Qt::DisplayRole).toString();
retval << extractStringsFromModel(model, idx, column);
}
}
return(retval);
}
void MainWindow::analyseMainImagePath(QString mainImage)
{
QString mainImagepath = mainImage.left(3);
if(mainImagepath == "htt" || mainImagepath == "ftp")
{
loadOnlinePicture(mainImage);
}
else
{
loadLocalPicture(mainImage);
}
}
void MainWindow::loadOnlinePicture(QString mainImage)
{
QNetworkAccessManager *m_netwManager = new QNetworkAccessManager(this);
connect(m_netwManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(slot_netwManagerFinished(QNetworkReply*)));
QUrl url(mainImage);
QNetworkRequest request(url);
m_netwManager->get(request);
}
void MainWindow::loadLocalPicture(QString mainImage)
{
QPixmap *pm = new QPixmap(mainImage);
showMainpicture(pm);
}
void MainWindow::loadPlaceholder()
{
QPixmap *pm_empty = new QPixmap("/home/viktor/0000_openAtlas_Project/openAtlas-dev/placeholder_empty.png");
showMainpicture(pm_empty);
}
void MainWindow::showMainpicture(QPixmap *pm)
{
QPixmap scaledImage;
//scaledImage = pm->scaled(ui->graphicsView->width()-10, ui->graphicsView->height()-10, Qt::KeepAspectRatio);
gs->addPixmap(scaledImage);
//ui->graphicsView->setScene(gs);
}
void MainWindow::show_sites_in_database()
{
// clear filter
ui->lineEdit_Filter->clear();
filter.clear();
on_lineEdit_Filter_textEdited();
QTime myTimer;
myTimer.start();
int intNumber;
QString strNumber;
if(myDBM->workingDB.driverName()== "QPSQL")
{
QString sitesQuery = "SELECT sites.uid, sites.entity_name_uri FROM openatlas.sites ORDER BY sites.entity_name_uri ASC;";
tableViewItemsModel->setQuery(sitesQuery, myDBM->workingDB);
if (myDBM->workingDB.lastError().isValid())
qDebug() << myDBM->workingDB.lastError();
}
else
{
tableViewItemsModel->setQuery("SELECT name FROM sqlite_master WHERE type='table'", myDBM->workingDB);
}
proxymodelSites->setSourceModel(tableViewItemsModel);
ui->tableViewItems->setModel(proxymodelSites);
strdataLevel = "sites";
ui->textEdit_DataLevel->setText(strdataLevel);
int Milliseconds = myTimer.elapsed();
float Seconds = (float) Milliseconds/1000;
QString strSeconds;
strSeconds.append(QString("%1").arg(Seconds));
intNumber = tableViewItemsModel->query().size();
strNumber.append(QString("%1").arg(intNumber));
QString time = strNumber +" items loaded in " + strSeconds + " sec.";
TimeMeasurementStatusBar(time);
}
void MainWindow::show_features_in_site()
{
// clear filter
ui->lineEdit_Filter->clear();
filter.clear();
on_lineEdit_Filter_textEdited();
QTime myTimer;
myTimer.start();
int intNumber;
QString strNumber;
if(myDBM->workingDB.driverName()== "QPSQL")
{
QString featuresQuery = "SELECT features.uid, features.entity_name_uri FROM openatlas.features WHERE features.parent = " + clickedUid + " ORDER BY features.entity_name_uri ASC;";
tableViewItemsModel->setQuery(featuresQuery, myDBM->workingDB);
if (myDBM->workingDB.lastError().isValid())
qDebug() << myDBM->workingDB.lastError();
}
else
{
tableViewItemsModel->setQuery("SELECT name FROM sqlite_master WHERE type='table'", myDBM->workingDB);
}
proxymodelSites->setSourceModel(tableViewItemsModel);
ui->tableViewItems->setModel(proxymodelSites);
int Milliseconds = myTimer.elapsed();
float Seconds = (float) Milliseconds/1000;
QString strSeconds;
strSeconds.append(QString("%1").arg(Seconds));
intNumber = tableViewItemsModel->query().size();
strNumber.append(QString("%1").arg(intNumber));
QString time = strNumber +" items loaded in " + strSeconds + " sec.";
TimeMeasurementStatusBar(time);
}
void MainWindow::show_su_in_feature()
{
// clear filter
ui->lineEdit_Filter->clear();
filter.clear();
on_lineEdit_Filter_textEdited();
QTime myTimer;
myTimer.start();
int intNumber;
QString strNumber;
if(myDBM->workingDB.driverName()== "QPSQL")
{
QString suQuery = "SELECT stratigraphical_units.uid, stratigraphical_units.entity_name_uri FROM openatlas.stratigraphical_units WHERE stratigraphical_units.parent = " + clickedUid + " ORDER BY stratigraphical_units.entity_name_uri ASC;";
qDebug() << "Querystring: " << suQuery;
tableViewItemsModel->setQuery(suQuery, myDBM->workingDB);
if (myDBM->workingDB.lastError().isValid())
qDebug() << myDBM->workingDB.lastError();
}
else
{
tableViewItemsModel->setQuery("SELECT name FROM sqlite_master WHERE type='table'", myDBM->workingDB);
}
proxymodelSites->setSourceModel(tableViewItemsModel);
ui->tableViewItems->setModel(proxymodelSites);
int Milliseconds = myTimer.elapsed();
float Seconds = (float) Milliseconds/1000;
QString strSeconds;
strSeconds.append(QString("%1").arg(Seconds));
intNumber = tableViewItemsModel->query().size();
strNumber.append(QString("%1").arg(intNumber));
QString time = strNumber +" items loaded in " + strSeconds + " sec.";
TimeMeasurementStatusBar(time);
}
void MainWindow::show_finds_in_su()
{
// clear filter
ui->lineEdit_Filter->clear();
filter.clear();
on_lineEdit_Filter_textEdited();
QTime myTimer;
myTimer.start();
int intNumber;
QString strNumber;
if(myDBM->workingDB.driverName()== "QPSQL")
{
QString suQuery = "SELECT finds.uid, finds.entity_name_uri FROM openatlas.finds WHERE finds.parent = " + clickedUid + "ORDER BY finds.entity_name_uri ASC;";
tableViewItemsModel->setQuery(suQuery, myDBM->workingDB);
if (myDBM->workingDB.lastError().isValid())
qDebug() << myDBM->workingDB.lastError();
}
else
{
tableViewItemsModel->setQuery("SELECT name FROM sqlite_master WHERE type='table'", myDBM->workingDB);
}
proxymodelSites->setSourceModel(tableViewItemsModel);
ui->tableViewItems->setModel(proxymodelSites);
int Milliseconds = myTimer.elapsed();
float Seconds = (float) Milliseconds/1000;
QString strSeconds;
strSeconds.append(QString("%1").arg(Seconds));
intNumber = tableViewItemsModel->query().size();
strNumber.append(QString("%1").arg(intNumber));
QString time = strNumber +" items loaded in " + strSeconds + " sec.";
TimeMeasurementStatusBar(time);
}
/******************************************************************************
* clear_all_tabs()
* Clear all fields in the right upper and lower Tab
* Last edit: 30.06.2014
*****************************************************************************/
void MainWindow::clear_all_tabs()
{
QSqlQueryModel *emptyModel = new QSqlQueryModel;
emptyModel->setQuery("");
//clear filter textfield
ui->lineEdit_Filter->clear();
filter = "";
//clear all fields in 'Details of Item'
ui->textEdit_Name->clear();
ui->textEdit_Description->clear();
ui->textEdit_Type->clear();
ui->groupBox_Details->setTitle("Details");
//clear all fields in tab 'Overview'
ui->textEdit_Overview->clear();
ui->label_Imageview->clear();
//clear all fields in 'Spatial Info'
ui->textEdit_SpatialInfo_LocatedIn->clear();
ui->lineEdit_SpatialInfo_Easting->clear();
ui->lineEdit_SpatialInfo_Northing->clear();
ui->lineEdit_SpatialInfo_EPSG->clear();
ui->lineEdit_SpatialInfo_CS->clear();
// clear all fields in tab 'Classification'
ui->tableViewChronological->setModel(emptyModel);
ui->textEdit_Chronological->clear();
ui->tableViewCultural->setModel(emptyModel);
ui->textEdit_Cultural->clear();
// clear all fields in tab 'Bibliography/Evidence'
ui->tableViewBibliography->setModel(emptyModel);
ui->textEdit_Bibliography->clear();
ui->tableViewEvidence->setModel(emptyModel);
ui->textEdit_Evidence->clear();
//set MARBLE view to location University of Vienna, Department for Pre- and Early History
ui->MarbleWidget->centerOn(16.3488,48.2335);
ui->MarbleWidget->zoomView(3500);
//set Tabs disabled
ui->tabWidget->setDisabled(true);
}
void MainWindow::fill_listviewThumbnails(QString clickedUid)
{
QString strimageQuery = "SELECT links_images.entity_uri FROM openatlas.links_images WHERE links_images.links_entity_uid_from = " + clickedUid + ";";
QSqlQuery imageQuery(strimageQuery, myDBM->workingDB);
int i = 0;
while(imageQuery.next())
{
i++;
qDebug() << "imageQuery number " << i << " called, clicked item: " << clickedItem;
QString partPath = imageQuery.value(0).toString();
imagePath = imagePrefix + partPath + imagePostfix;
loadOnlinePicture(imagePath);
}
}
/******************************************************************************
******************************************************************************
******************************************************************************
* *
* Private slots for MainWindow *
* *
******************************************************************************
******************************************************************************
*****************************************************************************/
void MainWindow::HERE__START__THE__PRIVATE__SLOTS()
{
// senseless empty function, just to see the start of the section 'private
// slots' in qtcreator overview
}
/******************************************************************************
* resizeEvent(): Private Slot
* updates the content of graphicsView every time the MainWindow is resized
* Last edit: 04.05.2014
*****************************************************************************/
void MainWindow::resizeEvent(QResizeEvent *resize)
{
//ui->graphicsView->fitInView(gs->itemsBoundingRect() ,Qt::KeepAspectRatio);
// expermiental picture view in tab 'Testtab'
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
int w = ui->label_Imageview->width();
int h = ui->label_Imageview->height();
ui->label_Imageview->setPixmap(pm->scaled(w, h, Qt::KeepAspectRatio));
//ui->label_Imageview->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored);
//ui->label_Imageview->setScaledContents(true);
}
/******************************************************************************
* wheelEvent(): Private Slot
* zoom mainPicture in and out by scrolling the mouse wheel
* Last edit: 04.05.2014
*****************************************************************************/
void MainWindow::wheelEvent(QWheelEvent* wheel)
{
//ui->graphicsView->setTransformationAnchor(QGraphicsView::AnchorUnderMouse);
// ui->graphicsView->setTransformationAnchor(QGraphicsView::AnchorViewCenter);
// int Height = ui->graphicsView->height();
// int Width = ui->graphicsView->width();
// ui->graphicsView->setFixedHeight(Height);
// ui->graphicsView->setFixedWidth(Width);
// // Scale the view / do the zoom
// double scaleFactor = 1.15;
// if(wheel->delta() > 0) {
// // Zoom in
// ui->graphicsView->scale(scaleFactor, scaleFactor);
// } else
// {
// // Zooming out
// ui->graphicsView->scale(1.0 / scaleFactor, 1.0 / scaleFactor);
// }
}
/******************************************************************************
* on_pushButton_Edit_Overview_clicked(): Private Slot
* Set line edits and text edits in group box'item Details' editable and
* the variable bool_overviewEditable to 'true'.
* Last edit: 04.05.2014
*****************************************************************************/
void MainWindow::on_pushButton_Edit_Overview_clicked()
{
ui->textEdit_Name->setReadOnly(false);
ui->textEdit_Description->setReadOnly(false);
ui->pushButton_Cancel_Overview->setEnabled(true);
ui->pushButton_Save_Overview->setEnabled(true);
ui->pushButton_TypeWizard->setEnabled(true);
}
/******************************************************************************
* on_pushButton_Edit_TypeWizard_clicked(): Private Slot
* call dialog 'Type Wizard'
* Last edit: 04.05.2014
*****************************************************************************/
void MainWindow::on_pushButton_TypeWizard_clicked()
{
TypeWizard *dialog = new TypeWizard(dataLevel);
qDebug() << "Calling TypeWizard, datalevel: " << dataLevel;
switch(dataLevel)
{
case 0:
dialog->setWindowTitle("Type Wizard - Sites");
break;
case 1:
dialog->setWindowTitle("Type Wizard - Features");
break;
case 2:
dialog->setWindowTitle("Type Wizard - Stratigraphical Units");
break;
case 3:
dialog->setWindowTitle("Type Wizard - Finds");
break;
}
dialog->exec();
}
/******************************************************************************
* on_toolButton_Datalevel_home_clicked(): Private Slot
* set Item browser to level 'sites' and clear history
* Last edit: 04.05.2014
*****************************************************************************/
void MainWindow::on_toolButton_Datalevel_home_clicked()
{
update_sites_overview();
last_clickedSite = "";
last_clickedSiteUid = "";
last_clickedFeature = "";
last_clickedFeatureUid = "";
last_clickedSU = "";
last_clickedSUUid = "";
last_clickedFind = "";
last_clickedFindUid = "";
ui->toolButton_Datalevel_home->setEnabled(false);
ui->toolButton_Datalevel_up->setEnabled(false);
clear_all_tabs();
}
/******************************************************************************
* on_toolButton_Datalevel_down_clicked(): Private Slot
*
* Last edit: 04.05.2014
*****************************************************************************/
void MainWindow::on_toolButton_Datalevel_up_clicked()
{
// do something
switch(dataLevel)
{
case 1:
clickedUid = last_clickedSiteUid;
strdataLevel = "Site '" + last_clickedSite + " -> Features";
// groupBoxTitle = "Details for site '" + currentSite +"' -> Feature '" + currentFeature + "'";
// ui->groupBox_Details->setTitle(groupBoxTitle);
ui->textEdit_DataLevel->setText(strdataLevel);
//update_sites_overview();
show_sites_in_database();
ui->toolButton_Datalevel_up->setEnabled(false);
ui->toolButton_Datalevel_home->setEnabled(false);
break;
case 2:
clickedUid = last_clickedSiteUid;
strdataLevel = "Site '" + last_clickedSite + " -> Features";
// groupBoxTitle = "Details for site '" + currentSite +"' -> Feature '" + currentFeature + "'";
// ui->groupBox_Details->setTitle(groupBoxTitle);
ui->textEdit_DataLevel->setText(strdataLevel);
show_features_in_site();
break;
case 3:
clickedUid = last_clickedFeatureUid;
strdataLevel = "Site '" + last_clickedSite + " -> Feature '" + last_clickedFeature + "' -> Stratigraphical Units";
// groupBoxTitle = "Details for site '" + currentSite +"' -> Feature '" + currentFeature + "'";
// ui->groupBox_Details->setTitle(groupBoxTitle);
ui->textEdit_DataLevel->setText(strdataLevel);
show_su_in_feature();
break;
}
dataLevel--;
clear_all_tabs();
}
/******************************************************************************
* check_answer_changeConnectionDlg(): Private Slot
* Check, if the content of 'ComboBoxConnection has really changed
* Last edit: 09.05.2014
*****************************************************************************/
void MainWindow::check_answer_changeConnectionDlg(const QString &newComboboxText)
{
QSettings settings;
settings.beginGroup("DatabaseSettings");
QString currentComboboxText = settings.value("currentDatabaseConnection").toString();
settings.endGroup();
if(newComboboxText == currentComboboxText)
{
return;
}
else
{
//reset time measurement and clear lineEditFilter
TimeMeasurementStatusBar("Time Measurement");
ui->lineEdit_Filter->clear();
filter = "";
currentConnection = ComboBoxConnections->currentText();
QSettings settings;
settings.beginGroup("DatabaseSettings");
settings.setValue("currentDatabaseConnection", currentConnection);
settings.endGroup();
checkConnectionBasics();
}
}
/******************************************************************************
* update_tableViewItems(QString categoryQueryResult): Private Slot
* update item list after listView_Content changed
* Last edit: 29.06.2014
*****************************************************************************/
void MainWindow::update_tableViewItems(QString categoryQueryResult)
{
// set timer to meassure loading time
QTime myTimer;
myTimer.start();
int intNumber;
QString strNumber;
if(myDBM->workingDB.driverName()== "QPSQL")
{
QString QueryItems = "SELECT " + categoryQueryResult + "." + "entity_name_uri, " + categoryQueryResult + ".uid FROM openatlas." + categoryQueryResult + " ORDER BY " + categoryQueryResult + ".entity_name_uri ASC";
tableViewItemsModel->setQuery(QueryItems, myDBM->workingDB);
}
else
{
tableViewItemsModel->setQuery("SELECT name FROM sqlite_master WHERE type='table'", myDBM->workingDB);
}
proxymodelSites->setSourceModel(tableViewItemsModel);
ui->tableViewItems->setModel(proxymodelSites);
ui->tableViewItems->resizeColumnToContents(0);
ui->tableViewItems->hideColumn(1);
ui->tableViewItems->resizeRowsToContents();
// measure the loading time
int Milliseconds = myTimer.elapsed();
float Seconds = (float) Milliseconds/1000;
QString strSeconds;
strSeconds.append(QString("%1").arg(Seconds));
intNumber = tableViewItemsModel->query().size();
strNumber.append(QString("%1").arg(intNumber));
// write measurement time to status bar
QString time = strNumber +" items loaded in " + strSeconds + " sec.";
TimeMeasurementStatusBar(time);
}
/******************************************************************************
* on_createConnection_clicked(): Private Slot
* Call dialog 'createConnection'
* Last edit: 09.05.2014
*****************************************************************************/
void MainWindow::on_createConnection_clicked()
{
CreateConnection *dlg = new CreateConnection;
dlg->exec();
setupConnectionsModel();
updateCurrentConnection();
}
void MainWindow::slot_netwManagerFinished(QNetworkReply *reply)
{
if (reply->error() != QNetworkReply::NoError) {
qDebug() << "Error in" << reply->url() << ":" << reply->errorString();
return;
}
QByteArray jpegData = reply->readAll();
//QPixmap *pm = new QPixmap;
pm->loadFromData(jpegData);
showMainpicture(pm);
// expermiental picture view
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
int w = ui->label_Imageview->width();
int h = ui->label_Imageview->height();
ui->label_Imageview->setPixmap(pm->scaled(w, h, Qt::KeepAspectRatio));
//ui->label_Imageview->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored);
// same code in resize-event...
}
/******************************************************************************
* on_tableViewItems_clicked(): Private slot
* read data from database
* Last edit: 09.05.2014
*****************************************************************************/
void MainWindow::on_tableViewItems_clicked(const QModelIndex &index)
{
clear_all_tabs();
QString queryString;
qDebug() << "'on_tableViewItems_clicked' called...";
view_Items_clicked();
varClickedItem = index.data();
clickedItem = varClickedItem.toString();
itemIndex = ui->tableViewItems->selectionModel()->currentIndex().row();
QString itemIndexString;
itemIndexString.append(QString("%1").arg(itemIndex));
QStringList stringUids = extractStringsFromModel(ui->tableViewItems->model(), QModelIndex(), 0);
QString clickedUid = stringUids.at(itemIndex);
switch(dataLevel)
{
case 0:
// write values for history
last_clickedSite = clickedItem;
last_clickedSiteUid = clickedUid;
// call query for site details
queryString = "SELECT * FROM openatlas.sites WHERE openatlas.sites.uid = '" + clickedUid + "';";
strItem_part1 = "Details for site '" + last_clickedSite + "'";
ui->groupBox_Details->setTitle(strItem_part1);
break;
case 1:
// write values for history
last_clickedFeature = clickedItem;
last_clickedFeatureUid = clickedUid;
// call query for features details
strItem_part1 = "Details for feature '" + last_clickedFeature + "'";
ui->groupBox_Details->setTitle(strItem_part1);
queryString = "SELECT * FROM openatlas.features WHERE openatlas.features.uid = '" + clickedUid + "';";
break;
case 2:
// write values for history
last_clickedSU = clickedItem;
last_clickedSUUid = clickedUid;
// call query for stratigraphical_unit details
strItem_part1 = "Details for stratigraphical unit '" + last_clickedSU + "'";
//groupBoxTitle = strItem_part1;
ui->groupBox_Details->setTitle(strItem_part1);
queryString = "SELECT * FROM openatlas.stratigraphical_units WHERE openatlas.stratigraphical_units.uid = '" + clickedUid + "';";
case 3:
// write values for history
last_clickedFind = clickedItem;
// last_clickedFindUid = clickedUid;
// call query for find details
strItem_part1 = "Details for find '" + last_clickedFind + "'";
ui->groupBox_Details->setTitle(strItem_part1);
queryString = "SELECT * FROM openatlas.finds WHERE openatlas.finds.uid = '" + clickedUid + "';";
break;
}
QString epsgCode;
QString absPeriod;
QString chronPeriod;
QString geogPosition;
QString location;
QString culturalClassification;
QString culturalClassificationString;
QString chronologicalClassification;
QString chronologicalClassificationString;
QString overviewSeperator = "==================<br />";
QSqlQuery workingQuery(queryString, myDBM->workingDB);
// get indices of columns
QSqlRecord rec = workingQuery.record();
nameUid = rec.indexOf("uid");
int nameUri = rec.indexOf("entity_name_uri");
int nameDescription = rec.indexOf("entity_description");
int namePath = rec.indexOf("name_path");
int nameStartTimeAbs = rec.indexOf("start_time_abs");
int nameEndTimeAbs = rec.indexOf("end_time_abs");
int nameStartTimeText = rec.indexOf("start_time_text");
int nameEndTimeText = rec.indexOf("end_time_text");
int nameEPSG = rec.indexOf("srid_epsg");
int nameX = rec.indexOf("x_lon_easting");
int nameY = rec.indexOf("y_lat_northing");
int nameEasting = rec.indexOf("x_wgs84");
int nameNorthing = rec.indexOf("y_wgs84");
int nameDimWidth = rec.indexOf("dim_width");
int nameDimLength = rec.indexOf("dim_length");
int nameDimHeight = rec.indexOf("dim_height");
int nameDimThickness = rec.indexOf("dim_thickness");
int nameDimWeight = rec.indexOf("dim_weight");
int nameDimWeightUnits = rec.indexOf("dim_units_weight");
int nameDimDiameter = rec.indexOf("dim_diameter");
int nameDimUnits = rec.indexOf("dim_units");
int nameDimDegrees = rec.indexOf("dim_degrees");
while(workingQuery.next())
{
// fill out tab view 'Dimensions'
// read values from database
QString length = workingQuery.value(nameDimLength).toString();
QString width = workingQuery.value(nameDimWidth).toString();
QString height = workingQuery.value(nameDimHeight).toString();
QString thickness = workingQuery.value(nameDimThickness).toString();
QString weight = workingQuery.value((nameDimWeight)).toString();
QString WeightUnits = workingQuery.value(nameDimWeightUnits).toString();
QString diameter = workingQuery.value(nameDimDiameter).toString();
QString degrees = workingQuery.value(nameDimDegrees).toString();
QString units = workingQuery.value(nameDimUnits).toString();
// write values to view
ui->lineEdit_Length->setText(length);
ui->lineEdit_Width->setText(width);
ui->lineEdit_Height->setText(height);
ui->lineEdit_Thickness->setText(thickness);
ui->lineEdit_Weight->setText(weight);
ui->lineEdit_Diameter->setText(diameter);
ui->lineEdit_Degrees->setText(degrees);
// write units to view and labels
ui->comboBox_Length_Unit->setItemText(0, units);
ui->comboBox_Weight_Unit->setItemText(0, WeightUnits);
ui->label_Unit_Diameter->setText(units);
ui->label_Unit_Height->setText(units);
ui->label_Unit_Thickness->setText(units);
ui->label_Unit_Width->setText(units);
// read WGS84 coordinates an call map view
qreal dbl_x_lon_easting = workingQuery.value(nameEasting).toDouble();
qreal dbl_y_lat_northing = workingQuery.value(nameNorthing).toDouble();
ui->MarbleWidget->centerOn(dbl_x_lon_easting, dbl_y_lat_northing);
ui->MarbleWidget->setShowOverviewMap(false);
// fill out details for item
ui->textEdit_Name->setText(workingQuery.value(nameUri).toString());
ui->textEdit_Description->setText(workingQuery.value(nameDescription).toString());
QString strTypeTmp = workingQuery.value(namePath).toString();
QString strTypeLong = strTypeTmp.section('>',2);
int strTypeSize = strTypeLong.size();
int strTypeSizeRight = strTypeSize - 1; // to delete the space at the beginning of 'namePathTmp2'
QString strType = strTypeLong.right(strTypeSizeRight);
ui->textEdit_Type->setText(strType);
// TODO: read path of main Window to QString image (@Stefan: implement in database view!)
// TODO: create chronological periods string
// create absolut period string for item
QString startTime = workingQuery.value(nameStartTimeAbs).toString();
QString endTime = workingQuery.value(nameEndTimeAbs).toString();
QString startTimeText = workingQuery.value(nameStartTimeText).toString();
QString endTimeText = workingQuery.value(nameEndTimeText).toString();
// fill out groupbox 'Temporal/Cultural'
QString strStartTimeText;
QString strEndTimeText;
if(startTimeText == "")
{
strStartTimeText = "";
}
else
{
strStartTimeText = startTimeText + " ";
}
if(endTimeText == "")
{
strEndTimeText = "";
}
else
{
strEndTimeText = endTimeText + " ";
}
QString strStartTime = strStartTimeText + startTime + " ";
QString strEndTime = endTimeText + " " + endTime;
ui->lineEdit_StartTime_Prefix->setText(startTimeText);
ui->lineEdit_EndTime_Prefix->setText(endTimeText);
ui->lineEdit_Cultural_StartTimeAbsolut->setText(startTime);
ui->lineEdit_Cultural_EndTimeAbsolut->setText(endTime);
if((startTime == "" && endTime == "") || (startTime == "0" && endTime == "0"))
{
absPeriod = "";
}
else
{
absPeriod = "<b>Absolut Period:</b><br />" + strStartTime + "to " + strEndTime + "<br />" + overviewSeperator;
}
// get epsg -code and coordinates from database
epsgCode = "EPSG:" + workingQuery.value(nameEPSG).toString();
QString strEPSGCode = workingQuery.value(nameEPSG).toString();
QString EPSGQueryString = "SELECT spatial_ref_sys.srText FROM public.spatial_ref_sys WHERE spatial_ref_sys.srid = " + strEPSGCode + ";";
QSqlQuery EPSGQuery(EPSGQueryString, myDBM->workingDB);
while(EPSGQuery.next())
{
QString ProjCSTmp = EPSGQuery.value(0).toString();
QString delimiterPattern("\"");
QStringList ProjCSList = ProjCSTmp.split(delimiterPattern);
ProjCS = ProjCSList[1];
}
x_lon_easting = workingQuery.value(nameX).toString();
y_lat_northing = workingQuery.value(nameY).toString();
if(workingQuery.value(25).toString() == "" || workingQuery.value(25).toString() == "0")
{
geogPosition = "";
}
else
{
geogPosition = "<b>Geographic Position:</b><br />Easting " + x_lon_easting + ", Northing " + y_lat_northing + " (" + epsgCode + " - " + ProjCS + ")" + "<br />" + overviewSeperator;
// fill out tab Spatial Info
ui->lineEdit_SpatialInfo_Easting->setText(x_lon_easting);
ui->lineEdit_SpatialInfo_Northing->setText(y_lat_northing);
ui->lineEdit_SpatialInfo_EPSG->setText(epsgCode);
ui->lineEdit_SpatialInfo_CS->setText(ProjCS);
}
}
// create location query string
QString strlocationQuery = "SELECT name_path, name, type_name, links_annotation FROM openatlas.links_places WHERE openatlas.links_places.links_entity_uid_from = " + clickedUid + ";";
QSqlQuery locationQuery(strlocationQuery, myDBM->workingDB);
QSqlRecord reclocationQuery = locationQuery.record();
// get indices of columns
int locationName = reclocationQuery.indexOf("name");
int locationType = reclocationQuery.indexOf("type_name");
while(locationQuery.next())
{
// build string for overview window
QString nameFieldname = locationQuery.value(locationName).toString();
QString strLocationType = locationQuery.value(locationType).toString();
location = "<b>Location:</b><br />" + nameFieldname + " (" + strLocationType + ")<br />" + overviewSeperator;
}
tableViewLocationModel->setQuery(strlocationQuery, myDBM->workingDB);
proxymodelLocation->setSourceModel(tableViewLocationModel);
ui->tableViewLocation->setModel(proxymodelLocation);
ui->tableViewLocation->resizeRowsToContents();
ui->tableViewLocation->resizeColumnsToContents();
ui->tableViewLocation->horizontalHeader()->setResizeMode(QHeaderView::Stretch);
ui->tableViewLocation->hideColumn(0);
ui->tableViewLocation->setSelectionBehavior(QAbstractItemView::SelectRows);
// set column titles
ui->tableViewLocation->model()->setHeaderData(1, Qt::Horizontal, QObject::tr("Name"));
ui->tableViewLocation->model()->setHeaderData(2, Qt::Horizontal, QObject::tr("Type"));
ui->tableViewLocation->model()->setHeaderData(3, Qt::Horizontal, QObject::tr("Parcel Number"));
// create cultural query string
QString strCulturalQuery = "SELECT links_cultural.name_path, links_cultural.name, links_cultural.links_uid FROM openatlas.links_cultural WHERE links_entity_uid_from = " + clickedUid + "ORDER BY links_cultural.name ASC;";
QList<QString> culturalClassificationList;
QSqlQuery culturalQuery(strCulturalQuery, myDBM->workingDB);
QSqlRecord recculturalQuery = culturalQuery.record();
int culturalName = recculturalQuery.indexOf("name");
while(culturalQuery.next())
{
QString name = culturalQuery.value(culturalName).toString();
culturalClassificationList.append(name);
}
QString culturalClassificationtmp = "";
foreach(culturalClassification, culturalClassificationList)
{
culturalClassificationtmp = culturalClassificationtmp + culturalClassification + "<br />";
}
if(culturalClassificationList.isEmpty())
{
culturalClassificationString = "";
}
else
{
culturalClassificationString = "<b>Cultural Classification:</b><br />" + culturalClassificationtmp + overviewSeperator;
}
// fill out tabView 'Classification' -> group box 'cultural classification'
tableViewCulturalModel->setQuery(strCulturalQuery, myDBM->workingDB);
proxymodelCultural->setSourceModel(tableViewCulturalModel);
ui->tableViewCultural->setModel(proxymodelCultural);
ui->tableViewCultural->resizeColumnsToContents();
ui->tableViewCultural->resizeRowsToContents();
ui->tableViewCultural->horizontalHeader()->setResizeMode(QHeaderView::Stretch);
ui->tableViewCultural->hideColumn(0);
ui->tableViewCultural->hideColumn(2);
// create chronological query string
QString strChronologicalQuery = "SELECT links_chronological.name_path, links_chronological.name, links_chronological.links_uid FROM openatlas.links_chronological WHERE links_entity_uid_from = " + clickedUid + ";";
QList<QString> chronologicalClassificationList;
QSqlQuery chronologicalQuery(strChronologicalQuery, myDBM->workingDB);
QSqlRecord recchronologicalQuery = chronologicalQuery.record();
int chronologicalName = recchronologicalQuery.indexOf("name");
while(chronologicalQuery.next())
{
QString name = chronologicalQuery.value(chronologicalName).toString();
chronologicalClassificationList.append(name);
}
QString chronologicalClassificationtmp = "";
foreach(chronologicalClassification, chronologicalClassificationList)
{
chronologicalClassificationtmp = chronologicalClassificationtmp + chronologicalClassification + "<br />";
}
if(chronologicalClassificationList.isEmpty())
{
chronologicalClassificationString = "";
}
else
{
chronologicalClassificationString = "<b>Chronological Classification:</b><br />" + chronologicalClassificationtmp + overviewSeperator;
}
// fill out tabView 'Classification' -> group box 'chronological classification'
tableViewChronologicalModel->setQuery(strChronologicalQuery, myDBM->workingDB);
proxymodelChronological->setSourceModel(tableViewChronologicalModel);
ui->tableViewChronological->setModel(proxymodelChronological);
ui->tableViewChronological->resizeColumnsToContents();
ui->tableViewChronological->resizeRowsToContents();
ui->tableViewChronological->horizontalHeader()->setResizeMode(QHeaderView::Stretch);
ui->tableViewChronological->hideColumn(0);
ui->tableViewChronological->hideColumn(2);
// fill out tabView 'Bibliography'
QString strBibliographyQuery = "SELECT links_bibliography.entity_name_uri, links_bibliography.entity_description FROM openatlas.links_bibliography WHERE links_entity_uid_from = " + clickedUid + ";";
tableViewBibliographyModel->setQuery(strBibliographyQuery, myDBM->workingDB);
proxymodelBibliography->setSourceModel(tableViewBibliographyModel);
ui->tableViewBibliography->setModel(proxymodelBibliography);
ui->tableViewBibliography->horizontalHeader()->setResizeMode(QHeaderView::Stretch);
ui->tableViewBibliography->hideColumn(1);
// fill out evidences
QString strEvidenceQuery = "SELECT links_evidence.name_path, links_evidence.name FROM openatlas.links_evidence WHERE links_entity_uid_from = " + clickedUid + ";";
tableViewEvidenceModel->setQuery(strEvidenceQuery, myDBM->workingDB);
proxymodelEvidence->setSourceModel(tableViewEvidenceModel);
ui->tableViewEvidence->setModel(proxymodelEvidence);
ui->tableViewEvidence->horizontalHeader()->setResizeMode(QHeaderView::Stretch);
ui->tableViewEvidence->hideColumn(0);
// merge strings and write to 'textEdit_Overview'
QString overviewText = chronologicalClassificationString + culturalClassificationString + chronPeriod + absPeriod + location + geogPosition;
ui->textEdit_Overview->setText(overviewText);
// read path of mainImage from database
QString strimageQuery = "SELECT links_images.entity_id FROM openatlas.links_images WHERE links_images.links_entity_uid_from = " + clickedUid + ";";
QSqlQuery imageQuery(strimageQuery, myDBM->workingDB);
QString partPath = imageQuery.value(0).toString();
QString imagePath = "";
while(imageQuery.next())
{
partPath = imageQuery.value(0).toString();
//imagePath = "http://nasorium.synology.me/Funde_bmp/" + partPath + ".png";
imagePath = imagePrefix + partPath + imagePostfix;
imageName = partPath + imagePostfix;
//ui->groupBox_Image_Overview->setTitle(imageName);
ui->listView_Thumbnails->setModel(itemModel);
ui->listView_Thumbnails->setSelectionMode(QAbstractItemView::SingleSelection);
QStandardItem *item = new QStandardItem;
if(ImageView==true)
{
analyseMainImagePath(imagePath);
}
}
}
/******************************************************************************
* on_tableViewItems_doubleClicked(const QModelIndex &index): Private Slot
* change tableViewItems to next lower level
* Last edit: 09.05.2014
*****************************************************************************/
void MainWindow::
on_tableViewItems_doubleClicked(const QModelIndex &index)
{
ui->toolButton_Datalevel_up->setEnabled(true);
ui->toolButton_Datalevel_home->setEnabled(true);
//set datalevel
if(dataLevel < 3)
{
dataLevel++;
qDebug() << "Datalevel: " << dataLevel;
qDebug() << "Last clicked Site: " << last_clickedSite << " Uid: " << last_clickedSiteUid;
qDebug() << "Last clicked Feature: " << last_clickedFeature << " Uid: " << last_clickedFeatureUid;
qDebug() << "Last clicked Stratigraphical Unit: " << last_clickedSU << " Uid: " << last_clickedSUUid;
// clear filter
ui->lineEdit_Filter->clear();
filter.clear();
on_lineEdit_Filter_textEdited();
QVariant varClickedItem = index.data();
clickedItem = varClickedItem.toString();
itemIndex = ui->tableViewItems->selectionModel()->currentIndex().row();
QString itemIndexString;
itemIndexString.append(QString("%1").arg(itemIndex));
//get uid
stringUids = extractStringsFromModel(ui->tableViewItems->model(), QModelIndex(), 0);
clickedUid = stringUids.at(itemIndex);
switch(dataLevel)
{
case 1:
// show features in site and set string for datalevel text
last_clickedSite = clickedItem;
strdataLevel = "Site '" + last_clickedSite + "' -> Features";
//groupBoxTitle = "Details for site '" + last_clickedSite +"'";
ui->textEdit_DataLevel->setText(strdataLevel);
// ui->groupBox_Details->setTitle(groupBoxTitle);
show_features_in_site();
break;
case 2:
// show stratigraphical units in feature and set string for datalevel text
last_clickedFeature = clickedItem;
strdataLevel = "Site '" + last_clickedSite + " -> Feature '" + last_clickedFeature + "' -> Stratigraphical Units";
//groupBoxTitle = "Details for site '" + last_clickedSite +"' -> Feature '" + last_clickedFeature + "'";
// ui->groupBox_Details->setTitle(groupBoxTitle);
ui->textEdit_DataLevel->setText(strdataLevel);
show_su_in_feature();
break;
case 3:
// show finds in stratigraphical unit and set string for datalevel text
last_clickedSU = clickedItem;
strdataLevel = "Site '" + last_clickedSite + " -> Feature '" + last_clickedFeature + "' -> Stratigraphical Unit '" + last_clickedSU + "' -> Finds";
//groupBoxTitle = "Details for site '" + last_clickedSite +"' -> Feature '" + last_clickedFeature + "'";
ui->textEdit_DataLevel->setText(strdataLevel);
show_finds_in_su();
}
}
}
/******************************************************************************
* on_tableViewLocation_clicked(): Private Slot
* show location path after clicking in table location name
* Last edit: 30.06.2014
*****************************************************************************/
void MainWindow::on_tableViewLocation_clicked()
{
int index = ui->tableViewLocation->selectionModel()->currentIndex().row();
QStringList stringList = extractStringsFromModel(ui->tableViewLocation->model(), QModelIndex(), 0);
QString string = stringList.at(index);
QString StringLong = string.section('>', 1, -2);
int intStringLong = StringLong.size();
int intStringSizeRight = intStringLong - 1; // to delete the space at the beginning
QString strLocation = StringLong.right(intStringSizeRight);
ui->textEdit_SpatialInfo_LocatedIn->setText(strLocation);
}
/******************************************************************************
* on_tableViewCultural_clicked(): Private Slot
* show cultural path after clicking in table Cultural Classification
* Last edit: 30.06.2014
*****************************************************************************/
void MainWindow::on_tableViewCultural_clicked()
{
int index = ui->tableViewCultural->selectionModel()->currentIndex().row();
QStringList stringList = extractStringsFromModel(ui->tableViewCultural->model(), QModelIndex(), 0);
QString string = stringList.at(index);
ui->textEdit_Cultural->setText(string);
}
/******************************************************************************
* on_tableViewChronological_clicked(): Private Slot
* show chronological path after clicking in table Chronological Classification
* Last edit: 30.06.2014
*****************************************************************************/
void MainWindow::on_tableViewChronological_clicked()
{
int index = ui->tableViewChronological->selectionModel()->currentIndex().row();
QStringList stringList = extractStringsFromModel(ui->tableViewChronological->model(), QModelIndex(), 0);
QString string = stringList.at(index);
ui->textEdit_Chronological->setText(string);
}
/******************************************************************************
* on_tableViewBibliography_clicked(): Private Slot
* show long citation after clicking in table Bibliography
* Last edit: 30.06.2014
*****************************************************************************/
void MainWindow::on_tableViewBibliography_clicked()
{
int index = ui->tableViewBibliography->selectionModel()->currentIndex().row();
QStringList stringList = extractStringsFromModel(ui->tableViewBibliography->model(), QModelIndex(), 1);
QString string = stringList.at(index);
ui->textEdit_Bibliography->setText(string);
}
/******************************************************************************
* on_tableViewEvidence_clicked(): Private Slot
* show evidence path after clicking in table Evidence
* Last edit: 30.06.2014
*****************************************************************************/
void MainWindow::on_tableViewEvidence_clicked()
{
int index = ui->tableViewEvidence->selectionModel()->currentIndex().row();
QStringList stringList = extractStringsFromModel(ui->tableViewEvidence->model(), QModelIndex(), 0);
QString string = stringList.at(index);
ui->textEdit_Evidence->setText(string);
}
/******************************************************************************
* on_actionAbout_Qt_clicked(): Private Slot
* show message box 'About Qt'
* Last edit: 01.07.2014
*****************************************************************************/
void MainWindow::on_actionAbout_Qt_clicked()
{
QMessageBox::aboutQt(this, "About Qt");
}
/******************************************************************************
* on_actionAbout_openAtlas_clicked(): Private Slot
* show message box 'About openAtlas'
* Last edit: 01.07.2014
*****************************************************************************/
void MainWindow::on_actionAbout_openAtlas_clicked()
{
QString aboutopenAtlasString = "openATLAS is a database application for the work with "
"archaeological, historical and spatial data.<br><br>"
"The developement is currently (2014) at an early stage and carried "
"out by a small team from the University of Vienna,"
"Institute of Prehistoric and Historical Archaeology.<br><br>"
"openATLAS is free software: you can redistribute "
"it and/or modify it under the terms of the GNU General Public Licenses "
"as published by the Free Software Foundation, either version 3 "
"of the License, or any later version.<br><br>"
"openATLAS 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 "
"<a href=\"http://www.gnu.org/licenses/gpl.html\">GNU General Public License</a>"
" for more details.<br><br>"
"Database Design by <NAME> 2013 - 2014<br>"
"<a href=\"mailto:<EMAIL>\"><EMAIL></a><br><br>"
"Frontend Development by <NAME> 2013 - 2014\n"
"<a href=\"mailto:<EMAIL>\"><EMAIL></a><br><br>"
"For more information and technical support see "
"<a href=\"http://www.openatlas.eu\">http://www.openatlas.eu</a>.";
QString title = "<h4>About " + openAtlasVersion + "</h4>";
QMessageBox::about( this, "About openAtlas", title + aboutopenAtlasString);
}
/******************************************************************************
* on_actionApplication_Preferences_clicked(): Private Slot
* call Application Preferences <dialog
* Last edit: 05.07.2014
*****************************************************************************/
void MainWindow::on_actionApplication_Preferences_clicked()
{
Preferences *dlg = new Preferences;
dlg->exec();
}
/******************************************************************************
* on_actionTreeEditor_clicked(): Private Slot
* show message box 'About openAtlas'
* Last edit: 05.07.2014
*****************************************************************************/
void MainWindow::on_actionTreeEditor_clicked()
{
Tree_Editor *dlg = new Tree_Editor;
dlg->exec();
}
<file_sep>/main.cpp
//////////////////////////////////////////////////////////////////////////////
// //
// This file is part of openATLAS. //
// //
// openATLAS 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 //
// any later version. //
// //
// openATLAS 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 openATLAS. If not, see <http://www.gnu.org/licenses/>. //
// //
// Database Design by <NAME> 2013 - 2014 //
// <EMAIL> //
// Frontend developed by <NAME> 2013 - 2014 //
// <EMAIL> //
// //
//////////////////////////////////////////////////////////////////////////////
#include "mainwindow.h"
#include "firststart.h"
#include "databasemanager.h"
#include <QApplication>
#include <QSettings>
//create an global instance of the Databasemanager
DatabaseManager *myDBM = new DatabaseManager;
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
//set application name to save the settings to an OS - dependend location
app.setOrganizationName("openAtlas 1.0 alpha");
// check if this is the first start of openAtlas
QSettings settings;
settings.beginGroup("MainWindow");
QString fStart = settings.value("FirstStart").toString();
settings.endGroup();
if(fStart == "")
{
firstStart *startwin = new firstStart;
startwin->exec();
}
//start the application
MainWindow w;
w.show();
return app.exec();
}
<file_sep>/README.md
openAtlas
=========
openATLAS-README-file
version 01, 2013-14-07
OpenATLAS is a database application for the work with archeological,
historical and spatial data. The developement is currently at an
early stage and carried out by a small team from the University of Vienna.
It uses classes and properties from the CIDOC Conceptual Reference Model
of the International Council of Museums to map its data. This international
standard for digital humanities garanties a high compatibility and
sustainability for the information collected in OpenATLAS.
OpenATLAS is powered by Postgresql and PostGIS (or Sqlite and Spatialite
in the file based-offline version) and therefore connectible to every
common GIS program like Qgis or ArcGIS. The project is written in c++,
using the Qt-framework in version 5.1 (status 2013-07-14).
<file_sep>/createconnection.cpp
//////////////////////////////////////////////////////////////////////////////
// //
// This file is part of openATLAS. //
// //
// openATLAS 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 //
// any later version. //
// //
// openATLAS 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 openATLAS. If not, see <http://www.gnu.org/licenses/>. //
// //
// Database Design by <NAME> 2013 - 2014 //
// <EMAIL> //
// Frontend developed by <NAME> 2013 - 2014 //
// <EMAIL> //
// //
//////////////////////////////////////////////////////////////////////////////
#include <QFileDialog>
#include <QMessageBox>
#include <QIntValidator>
#include <QFile>
#include <QDataStream>
#include <QSettings>
#include <QtSql>
#include "createconnection.h"
#include "ui_createconnection.h"
#include "mainwindow.h"
bool ConnectionTestStatus = false;
bool checkOfContentsStatus = false;
QString noNeed = "not required for SQLite";
QString SQLiteTestConnection = "testconnection_to_SQLite";
QString PostgresTestConnection = "testconnection_to_PostgreSQL";
//////////////////////////////////////////////////////////////////////////////
// //
// Constructor and Deconstructor //
// for CreateConnection //
// //
//////////////////////////////////////////////////////////////////////////////
// Constructor
//////////////////////////////////////////////////////////////////////////////
CreateConnection::CreateConnection(QWidget *parent) :
QDialog(parent),
ui(new Ui::CreateConnection)
{
ui->setupUi(this);
//allow just integers in field 'Port'
QIntValidator *validator = new QIntValidator(this);
ui->lineEditPort->setValidator(validator);
}
// Deconstructor
//////////////////////////////////////////////////////////////////////////////
CreateConnection::~CreateConnection()
{
delete ui;
}
//////////////////////////////////////////////////////////////////////////////
// //
// Private slots for CreateConnection //
// //
//////////////////////////////////////////////////////////////////////////////
void CreateConnection::on_comboBoxDatabaseLocation_currentIndexChanged(const QString &location)
{
ConnectionTestStatus = false;
if(location == "Local")
{
setUiToLocal();
}
else
{
setUiToNetwork();
}
}
void CreateConnection::on_toolButtonOpenFile_clicked()
{
QString fileName = QFileDialog::getOpenFileName(this,
tr("Open openAtlas Datafile"),
tr("/home/viktor"),
tr("openAtlas Datafiles (*.oad)"));
if (!fileName.isEmpty())
{
ui->lineEditDatabaseFile->setText(fileName);
}
//check, if the choosen file is a valid SQLite-file
QFile filetest(fileName);
filetest.open(QIODevice::ReadOnly);
QDataStream in(&filetest);
qint32 magicNumber;
in >> magicNumber;
if(magicNumber != 1397836905)
{
inputErrorMsgBox(tr("The choosen file is NOT a valid SQLite 3.x-file!"));
ui->lineEditDatabaseFile->setText("");
ui->lineEditDatabaseFile->setFocus();
}
}
void CreateConnection::on_pushButtonTestConnection_clicked()
{
//check content of lineEdits
if (ui->lineEditDatabaseDriver->text()=="QSQLITE")
{
checkOfContentsStatus = checkContentOfLineSQLite();
//if all necessary lines are filled, test the connection
if(checkOfContentsStatus == true)
{
ConnectionTestStatus = false; //value will be true after successfull connection test
QSqlDatabase SQLite = QSqlDatabase::addDatabase("QSQLITE", SQLiteTestConnection);
SQLite.setDatabaseName(ui->lineEditDatabaseFile->text());
SQLite.open();
if (!SQLite.isOpen())
{
QMessageBox::critical(0, QObject::tr("Database Error"),
SQLite.lastError().text());
}
else
{
QString info = "Successfully connected!\nDatabase file:\t" + SQLite.databaseName() + "" + "\nConnection name:\t" + SQLite.connectionName();
QMessageBox::information(0, QObject::tr("Connection Info"),
info);
ConnectionTestStatus = true;
}
SQLite.close();
}
}
else
{
//check content of lineEdits
checkOfContentsStatus = checkContentOfLinePostgreSQL();
if(checkOfContentsStatus == true)
{
ConnectionTestStatus = false;
QSqlDatabase PostgreSQL = QSqlDatabase::addDatabase("QPSQL", PostgresTestConnection);
PostgreSQL.setDatabaseName(ui->lineEditDatabaseFile->text());
PostgreSQL.setHostName(ui->lineEditHostname->text());
QString strPort;
int intPort;
strPort = ui->lineEditPort->text();
intPort = strPort.toInt();
PostgreSQL.setPort(intPort);
PostgreSQL.setUserName(ui->lineEditUserName->text());
PostgreSQL.setPassword(ui->lineEditPassword->text());
PostgreSQL.open();
if(!PostgreSQL.open())
{
QMessageBox::critical(0, QObject::tr("Connection Error"),
PostgreSQL.lastError().text());
}
else
{
QString info = "Successfully connected!\nDatabase name:\t" + PostgreSQL.databaseName() + "" + "\nConnection name:\t" + PostgreSQL.connectionName();
QMessageBox::information(0, QObject::tr("Connection Info"),
info);
ConnectionTestStatus = true;
}
PostgreSQL.close();
}
}
}
void CreateConnection::on_lineEditDatabaseFile_textChanged()
{
ConnectionTestStatus = false;
}
void CreateConnection::on_lineEditHostname_textChanged()
{
ConnectionTestStatus = false;
}
void CreateConnection::on_lineEditPort_textChanged()
{
ConnectionTestStatus = false;
}
void CreateConnection::on_lineEditUserName_textChanged()
{
ConnectionTestStatus = false;
}
void CreateConnection::on_lineEditUserToken_textChanged()
{
ConnectionTestStatus = false;
}
void CreateConnection::on_lineEditPassword_textChanged()
{
ConnectionTestStatus = false;
}
void CreateConnection::on_pushButtonOk_clicked()
{
if(ui->lineEditConnectionName->text()=="")
{
inputErrorMsgBox(tr("Please insert a Connection Name!"));
ui->lineEditConnectionName->setFocus();
}
else
{
if(ConnectionTestStatus != true)
{
inputErrorMsgBox(tr("There was no successfull connection test carried out!"));
}
else
{
QSettings settings;
settings.beginGroup("DatabaseSettings");
QString connString = settings.value("DatafileConnections").toString();
settings.endGroup();
QSqlDatabase connectionDB = QSqlDatabase::addDatabase("QSQLITE");
connectionDB.setDatabaseName(connString);
connectionDB.open();
if(!connectionDB.open())
{
QMessageBox::critical(0, QObject::tr("Connection Error"),
connectionDB.lastError().text());
}
else
{
QString ConnectionName = ui->lineEditConnectionName->text();
QString nameQueryString = "SELECT connection_name FROM tbl_connections WHERE connection_name='" + ConnectionName + "';";
QSqlQuery nameQuery(nameQueryString);
QVariant queryResult = nameQuery.first();
if(queryResult == ConnectionName)
{
inputErrorMsgBox(tr("Connection already exists, please choose another connection name!"));
ui->lineEditConnectionName->setFocus();
}
else
{
saveSettings();
}
}
}
}
}
//////////////////////////////////////////////////////////////////////////////
// //
// Private functions for CreateConnection //
// //
//////////////////////////////////////////////////////////////////////////////
// Changes the User Interface of Dialog 'Create new Connection'
// for the value of the combobox 'Database Location' = 'Network'
//////////////////////////////////////////////////////////////////////////////
void CreateConnection::setUiToNetwork()
{
//set all necessary Elements 'Enabled' or 'Disabled'
//and fill the fields with standard values
ui->lineEditDatabaseDriver->setText("QPSQL");
ui->lineEditDatabaseServer->setText("PostgreSQL/PostGIS");
ui->toolButtonOpenFile->hide();
ui->labelDatabaseFile->setText("Database Name:");
ui->lineEditDatabaseFile->setFixedWidth(200);
ui->lineEditDatabaseFile->setText("openatla_main_db");
ui->labelHostname->setEnabled(true);
ui->lineEditHostname->setEnabled(true);
ui->lineEditHostname->setText("www.openatlas.eu");
ui->labelPort->setEnabled(true);
ui->lineEditPort->setEnabled(true);
ui->lineEditPort->setText("5432");
ui->labelUserName->setEnabled(true);
ui->lineEditUserName->setEnabled(true);
ui->lineEditUserName->setText("openatla_jansaviktor");
ui->labelPassword->setEnabled(true);
ui->lineEditPassword->setEnabled(true);
ui->lineEditPassword->clear();
ui->lineEditPassword->setEchoMode(QLineEdit::Password);
}
// Changes the User Interface of Dialog 'Create new Connection'
// for the value of the combobox 'Database Location' = 'Network'
//////////////////////////////////////////////////////////////////////////////
void CreateConnection::setUiToLocal()
{
//set all Elements 'Disabled' or 'Enabled'
//and fill the fields with standard values
ui->lineEditDatabaseDriver->setText("QSQLITE");
ui->lineEditDatabaseServer->setText("SQLite/SpatialLite");
ui->toolButtonOpenFile->show();
ui->labelDatabaseFile->setText("Database File:");
ui->lineEditDatabaseFile->setFixedWidth(160);
ui->lineEditDatabaseFile->clear();
ui->labelHostname->setDisabled(true);
ui->lineEditHostname->setDisabled(true);
ui->lineEditHostname->setText(noNeed);
ui->labelPort->setDisabled(true);
ui->lineEditPort->setDisabled(true);
ui->lineEditPort->setText(noNeed);
ui->labelUserName->setDisabled(true);
ui->lineEditUserName->setDisabled(true);
ui->lineEditUserName->setText(noNeed);
ui->labelPassword->setDisabled(true);
ui->lineEditPassword->setDisabled(true);
ui->lineEditPassword->setText(noNeed);
ui->lineEditPassword->setEchoMode(QLineEdit::Normal);
}
// Check the Content of all necessary lines for a SQLite-database connection
//////////////////////////////////////////////////////////////////////////////
bool CreateConnection::checkContentOfLineSQLite()
{
if (ui->lineEditDatabaseFile->text()=="")
{
inputErrorMsgBox(tr("There is no datafile specified"));
return false;
}
else if (ui->lineEditUserToken->text()=="")
{
inputErrorMsgBox(tr("There is no user token specified"));
return false;
}
return true;
}
// Check the Content of all necessary lines for a PostgreSQL-database connection
//////////////////////////////////////////////////////////////////////////////
bool CreateConnection::checkContentOfLinePostgreSQL()
{
if (ui->lineEditDatabaseFile->text()=="")
{
inputErrorMsgBox(tr("There is no database specified"));
return false;
}
else if (ui->lineEditHostname->text()=="")
{
inputErrorMsgBox(tr("There is no hostname or IP-adress specified"));
return false;
}
else if (ui->lineEditPort->text()=="")
{
inputErrorMsgBox(tr("There is no port specified"));
return false;
}
else if (ui->lineEditUserName->text()=="")
{
inputErrorMsgBox(tr("There is no username specified"));
return false;
}
else if (ui->lineEditUserToken->text()=="")
{
inputErrorMsgBox(tr("There is no user token specified"));
return false;
}
return true;
}
// Show a messagebox with error messages depending on the input error
//////////////////////////////////////////////////////////////////////////////
void CreateConnection::inputErrorMsgBox(QString Message)
{
QMessageBox::critical(0, QObject::tr("Input Error"),
Message);
}
// Save the settings to the database
//////////////////////////////////////////////////////////////////////////////
void CreateConnection::saveSettings()
{
QString ConnectionName = ui->lineEditConnectionName->text();
QString DatabaseDriver = ui->lineEditDatabaseDriver->text();
QString DatabaseServer = ui->lineEditDatabaseServer->text();
QString DatabaseName = ui->lineEditDatabaseFile->text();
QString DatabaseHost = ui->lineEditHostname->text();
QString DatabasePort = ui->lineEditPort->text();
QString DatabaseUsername = ui->lineEditUserName->text();
QString DatabaseUsernameToken = ui->lineEditUserToken->text();
QString DatabasePassword;
if (ui->lineEditPassword->text() != "" && ui->lineEditPassword->text() != noNeed)
{
DatabasePassword = "YES";
}
else
{
DatabasePassword = "NO";
}
QSqlQuery myquery;
QString queryString = "INSERT INTO tbl_connections ('connection_name', 'database_driver', 'database_server', 'database_name', 'database_host', 'database_port', 'database_username', 'database_username_token', 'database_password') VALUES ('" + ConnectionName + "', '" + DatabaseDriver + "', '" + DatabaseServer + "', '" + DatabaseName + "', '" + DatabaseHost + "', '" + DatabasePort + "', '" + DatabaseUsername + "', '" + DatabaseUsernameToken + "', '" + DatabasePassword + "');";
myquery.exec(queryString);
QSettings settings;
settings.beginGroup("DatabaseSettings");
settings.setValue("currentDatabaseConnection", ConnectionName);
settings.endGroup();
QMessageBox::information(0, QObject::tr("Connection successfully saved"),
tr("Connection successfully saved!\nIf you want to use the new connection, choose it in the toolbar!"));
CreateConnection::close();
}
<file_sep>/typewizard.cpp
#include "typewizard.h"
#include "ui_typewizard.h"
#include "databasemanager.h"
#include <QDebug>
// UI elements
QString filterTypeWizard;
// data elements
int DataLevel;
QSqlQueryModel *tableViewTypesModel = new QSqlQueryModel;
QSortFilterProxyModel *proxymodel = new QSortFilterProxyModel;
TypeWizard::TypeWizard(const int &Level, QWidget *parent) :
QDialog(parent),
DataLevel(Level),
ui(new Ui::TypeWizard)
{
ui->setupUi(this);
ui->toolButton_Delete_Type->setDisabled(true);
;
QString QueryTypes;
switch(DataLevel)
{
case 0:
// define type querystring for sites
QueryTypes = "SELECT child_id, child_name FROM openatlas.types_parent_child WHERE parent_id = 3 ORDER BY child_name ASC;";
break;
case 1:
// define type querystring for features
QueryTypes = "SELECT child_id, child_name FROM openatlas.types_parent_child WHERE parent_id = 1 ORDER BY child_name ASC;";
break;
case 2:
// define type querystring for stratigraphical_units
QueryTypes = "SELECT child_id, child_name FROM openatlas.types_parent_child WHERE parent_id = 4 ORDER BY child_name ASC;";
break;
case 3:
// define type querystring for finds
QueryTypes = "SELECT child_id, child_name FROM openatlas.types_parent_child WHERE parent_id = 2 ORDER BY child_name ASC;";
break;
}
//QString
tableViewTypesModel->setQuery(QueryTypes, myDBM->workingDB);
proxymodel->setSourceModel(tableViewTypesModel);
ui->tableViewTypes->setModel(proxymodel);
ui->tableViewTypes->resizeColumnToContents(0);
ui->tableViewTypes->hideColumn(0);
ui->tableViewTypes->resizeRowsToContents();
ui->tableViewTypes->horizontalHeader()->setResizeMode(QHeaderView::Stretch);
qDebug() << "class TypeWizard called, Datalevel: " << DataLevel;
}
TypeWizard::~TypeWizard()
{
delete ui;
}
void TypeWizard::on_lineEdit_Filter_textEdited()
{
filterTypeWizard = ui->lineEdit_Filter->text();
proxymodel->setFilterRegExp(QRegExp(filterTypeWizard, Qt::CaseInsensitive, QRegExp::Wildcard));
proxymodel->setFilterKeyColumn(0);
}
<file_sep>/databasemanager.h
//////////////////////////////////////////////////////////////////////////////
// //
// This file is part of openATLAS. //
// //
// openATLAS 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 //
// any later version. //
// //
// openATLAS 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 openATLAS. If not, see <http://www.gnu.org/licenses/>. //
// //
// Database Design by <NAME> 2013 - 2014 //
// <EMAIL> //
// Frontend developed by <NAME> 2013 - 2014 //
// <EMAIL> //
// //
//////////////////////////////////////////////////////////////////////////////
#ifndef DATABASEMANAGER_H
#define DATABASEMANAGER_H
#include <QObject>
#include <QtSql>
class DatabaseManager : public QObject
{
Q_OBJECT
public:
explicit DatabaseManager(QObject *parent = 0);
void startConnectionDatabase();
bool startDB(QString password);
QSqlDatabase connectionsDB;
QSqlDatabase workingDB;
QString connection_name;
QString database_name;
QString database_driver;
QString database_server;
QString database_host;
int database_port;
QString database_username;
QString database_username_token;
QString database_password;
QString conn_file;
bool DB_Status;
private:
//QString conn_file;
signals:
public slots:
};
extern DatabaseManager *myDBM;
#endif // DATABASEMANAGER_H
<file_sep>/SQL_Statements/SQL_Statements.sql
-- insert Statement new entity (Site/Feature/SU/Find)
INSERT INTO openatlas.tbl_entities (user_id, classes_uid, entity_name_uri, entity_type, entity_description) VALUES ('youruserid', 12, 'your entitys name', 367, 'your entitys description'); -- replace values by variables from frontend. NOTE! Type: select UID by recursive query in GUI
--Type/Place etc. wizard:
-- select
SELECT child_id, child_name FROM openatlas.'your_entityclass'+parent_child WHERE parent_id = 'Topparent derived from GUI';
--Save child_id to variable - use variable for above value for entity_type
--Update Statements Tabs spatial:
UPDATE openatlas.tbl_entities SET (x_lon_easting, y_lat_northing, srid_epsg) = ('your x value', 'your y value' , 'your EPSG code') WHERE uid = 'records_uid'
--Update Statements Tabs chron/cult
UPDATE openatlas.tbl_entities SET (start_time_abs, end_time_abs, start_time_text, end_time_text) = ('your starttime integer', 'your endtime integer' , 'start text', 'end text') WHERE uid = 'records_uid'
--Update Statements Tabs dimensions
UPDATE openatlas.tbl_entities SET (dim_width, dim_length, dim_height, dim_thickness, dim_diameter, dim_units, dim_weight, dim_units_weight, dim_degrees) = (dim_width, dim_length, dim_height, dim_thickness, dim_diameter, dim_units, dim_weight, dim_units_weight, dim_degrees) WHERE uid = 'records_uid'
-- select dimension units:
SELECT name, id FROM openatlas.types_all_tree WHERE name_path LIKE '%> Distance >%'; --save id to unit field in tbl_entities
SELECT name, id FROM openatlas.types_all_tree WHERE name_path LIKE '%> Weight >%'; --save id to unit field tbl_entities
--update user_edit
UPDATE openatlas.tbl_entities SET (user_edit) = ('user_id') WHERE uid = 'records_uid';
--Insert statement child of site/feature/su
INSERT INTO openatlas.tbl_entities (user_id, classes_uid, entity_name_uri, entity_type, x_lon_easting, y_lat_northing, srid_epsg, start_time_abs, start_time_text, end_time_abs, end_time_text)
VALUES ('your user id', 'classes_uid - =12 except for finds where it is 15', 'name of the new entity', 'type = integer selected by wizard', 'parents x', 'parents y', 'parents epsg', 'parents start time', 'parents start text', 'parents end time', 'parents end text');
INSERT INTO openatlas.tbl_links (links_entity_uid_from, links_entity_uid_to, links_cidoc_number_direction, links_creator)
VALUES ('uid of parent', 'uid of new_child', 11, 'your user id');
----insert statement bibliographical reference
INSERT INTO openatlas.tbl_entities (user_id, classes_uid, entity_name_uri, entity_type, entity_description) VALUES ('youruserid', 11, 'Author Year', 'text-type', 'Full Citation');
---text type
SELECT name, id FROM openatlas.types_all_tree WHERE name_path LIKE '%> Text' OR name_path LIKE '%> Text >%'; --save id to type field in tbl_entities
--insert statement link to bibliographical reference
INSERT INTO openatlas.tbl_links (links_entity_uid_from, links_entity_uid_to, links_cidoc_number_direction, links_creator)
VALUES ('parent uid=uid of site/feature/su/find)', 'uid of bib ref', 4, 'youruserid');
--insert statement spatial
INSERT INTO openatlas.tbl_links (links_entity_uid_from, links_entity_uid_to, links_cidoc_number_direction, links_creator, links_annotation)
VALUES ('uid of parent', 'uid of new_child', 15, 'your user id', 'Parcel number');
UPDATE openatlas.tbl_links SET (links_entity_uid_to, links_annotation) = ('your new child uid by wizard', 'your new Parcel number') WHERE links_uid = 'your links uid';
--insert types general/evidence/cultural/chronological/
INSERT INTO openatlas.tbl_links (links_entity_uid_from, links_entity_uid_to, links_cidoc_number_direction, links_creator)
VALUES ('uid of parent', 'uid of new_child', 'links_cidoc_number_direction: chronological=13; cultural=9, all_typelinks=1(including evidence)', 'your user id');
UPDATE openatlas.tbl_links SET (links_entity_uid_to) = ('your new child uid by wizard') WHERE links_uid = 'your links uid';
--insert material
--insert statement spatial
INSERT INTO openatlas.tbl_links (links_entity_uid_from, links_entity_uid_to, links_cidoc_number_direction, links_creator, links_annotation)
VALUES ('uid of parent', 'uid material', 1, 'your user id', 'percentage of material');
UPDATE openatlas.tbl_links SET (links_entity_uid_to, links_annotation) = ('your material uid by wizard', 'new percentage') WHERE links_uid = 'your links uid';
--Delete statements
---tbl_entities
DELETE FROM openatlas.tbl_entities WHERE uid = 'my_current_uid';
--tbl_links
DELETE FROM openatlas.tbl_links WHERE links_uid = 'my_current_uid';
--Delete statement to delete arch unit + all subunits of resp. unit
WITH RECURSIVE path(id, path, parent, name, parent_id, name_path) AS (
SELECT openatlas.arch_parent_child.child_id, ''::text || openatlas.arch_parent_child.child_id::text AS path, NULL::text AS text, openatlas.arch_parent_child.child_name, openatlas.arch_parent_child.parent_id, ''::text || openatlas.arch_parent_child.child_name::text AS name_path
FROM openatlas.arch_parent_child
WHERE openatlas.arch_parent_child.parent_id = "Uid of arch unit goes here (without quotes)" -- replace value with parent of top-category you want to have displayed
UNION ALL
SELECT openatlas.arch_parent_child.child_id, (parentpath.path ||
CASE parentpath.path
WHEN ' > '::text THEN ''::text
ELSE ' > '::text
END) || openatlas.arch_parent_child.child_id::text, parentpath.path, openatlas.arch_parent_child.child_name, openatlas.arch_parent_child.parent_id,
(parentpath.name_path ||
CASE parentpath.name_path
WHEN ' > '::text THEN ''::text
ELSE ' > '::text
END) || openatlas.arch_parent_child.child_name::text
FROM openatlas.arch_parent_child, path parentpath
WHERE openatlas.arch_parent_child.parent_id::text = parentpath.id::text
)
DELETE FROM openatlas.tbl_entities WHERE UID IN (SELECT path.id FROM path);
DELETE FROM openatlas.tbl_entities WHERE UID = "uid of your arch unit goes here";
<file_sep>/tree_editor.h
#ifndef TREE_EDITOR_H
#define TREE_EDITOR_H
#include <QDialog>
#include <QStandardItemModel>
#include <QtSql>
namespace Ui {
class Tree_Editor;
}
class Tree_Editor : public QDialog
{
Q_OBJECT
public:
explicit Tree_Editor(QWidget *parent = 0);
~Tree_Editor();
private slots:
void on_comboBox_SelectCategory_currentIndexChanged(QString index);
private:
Ui::Tree_Editor *ui;
};
#endif // TREE_EDITOR_H
<file_sep>/preferences.cpp
#include "preferences.h"
#include "ui_preferences.h"
#include <QSettings>
#include <QFileDialog>
#include <QMessageBox>
bool ImageViewActivated;
QString fileExtension;
QString ImagePath;
int TabIndex;
int TabDataLevelIndex;
bool TabSitesOverview;
bool TabSitesSpatial;
bool TabSitesClassification;
bool TabSitesDimensions;
bool TabSitesImages;
bool TabSitesBibliography;
bool TabFeaturesOverview;
bool TabFeaturesSpatial;
bool TabFeaturesClassification;
bool TabFeaturesDimensions;
bool TabFeaturesImages;
bool TabFeaturesBibliography;
bool TabSUsOverview;
bool TabSUsSpatial;
bool TabSUsClassification;
bool TabSUsDimensions;
bool TabSUsImages;
bool TabSUsBibliography;
bool TabFindsOverview;
bool TabFindsSpatial;
bool TabFindsClassification;
bool TabFindsDimensions;
bool TabFindsImages;
bool TabFindsBibliography;
Preferences::Preferences(QWidget *parent) :
QDialog(parent),
ui(new Ui::Preferences)
{
ui->setupUi(this);
QSettings settings;
// read settings
settings.beginGroup("Preferences");
TabIndex = settings.value("TabIndex").toInt();
TabDataLevelIndex = settings.value("TabDataLevelIndex").toInt();
ImageViewActivated = settings.value("ImageViewActivated").toBool();
ImagePath = settings.value("ImageFolderPath").toString();
fileExtension = settings.value("ImageFileExtension").toString();
TabSitesOverview = settings.value("TabSitesOverview").toBool();
TabSitesSpatial = settings.value("TabSitesSpatial").toBool();
TabSitesClassification = settings.value("TabSitesClassification").toBool();
TabSitesDimensions = settings.value("TabSitesDimensions").toBool();
TabSitesImages = settings.value("TabSitesImages").toBool();
TabSitesBibliography = settings.value("TabSitesBibliography").toBool();
TabFeaturesOverview = settings.value("TabFeaturesOverview").toBool();
TabFeaturesSpatial = settings.value("TabFeaturesSpatial").toBool();
TabFeaturesClassification = settings.value("TabFeaturesClassification").toBool();
TabFeaturesDimensions = settings.value("TabFeaturesDimensions").toBool();
TabFeaturesImages = settings.value("TabFeaturesImages").toBool();
TabFeaturesBibliography = settings.value("TabFeaturesBibliography").toBool();
TabSUsOverview = settings.value("TabSUsOverview").toBool();
TabSUsSpatial = settings.value("TabSUsSpatial").toBool();
TabSUsClassification = settings.value("TabSUsClassification").toBool();
TabSUsDimensions = settings.value("TabSUsDimensions").toBool();
TabSUsImages = settings.value("TabSUsImages").toBool();
TabSUsBibliography = settings.value("TabSUsBibliography").toBool();
TabFindsOverview = settings.value("TabFindsOverview").toBool();
TabFindsSpatial = settings.value("TabFindsSpatial").toBool();
TabFindsClassification = settings.value("TabFindsClassification").toBool();
TabFindsDimensions = settings.value("TabFindsDimensions").toBool();
TabFindsImages = settings.value("TabFindsImages").toBool();
TabFindsBibliography = settings.value("TabFindsBibliography").toBool();
settings.endGroup();
ui->tabWidget->setCurrentIndex(TabIndex);
ui->tabWidget_DataLevel->setCurrentIndex(TabDataLevelIndex);
if(ImageViewActivated == true)
{
ui->checkBox_ImageView->setChecked(true);
ui->groupBox_imagePath->setEnabled(true);
ui->groupBox_imageExtension ->setEnabled(true);
}
else
{
ui->checkBox_ImageView->setChecked(false);
ui->groupBox_imagePath->setEnabled(false);
ui->groupBox_imageExtension ->setEnabled(false);
}
ui->label_currentImagefolderPath->setText(ImagePath);
ui->lineEdit_ImagefolderPath->setText(ImagePath);
// remove tab 'DataLevel until the function is implemented
ui->tabWidget->removeTab(1);
ui->checkBox_Sites_Overview->setChecked(TabSitesOverview);
ui->checkBox_Sites_Spatial->setChecked(TabSitesSpatial);
ui->checkBox_Sites_Classification->setChecked(TabSitesClassification);
ui->checkBox_Sites_Dimensions->setChecked(TabSitesDimensions);
ui->checkBox_Sites_Images->setChecked(TabSitesImages);
ui->checkBox_Sites_Bibliography_Evidence->setChecked(TabSitesBibliography);
ui->checkBox_Features_Overview->setChecked(TabFeaturesOverview);
ui->checkBox_Features_Spatial->setChecked(TabFeaturesSpatial);
ui->checkBox_Features_Classification->setChecked(TabFeaturesClassification);
ui->checkBox_Features_Dimensions->setChecked(TabFeaturesDimensions);
ui->checkBox_Features_Images->setChecked(TabFeaturesImages);
ui->checkBox_Features_Bibliography_Evidence->setChecked(TabFeaturesBibliography);
ui->checkBox_SUs_Overview->setChecked(TabSUsOverview);
ui->checkBox_SUs_Spatial->setChecked(TabSUsSpatial);
ui->checkBox_SUs_Classification->setChecked(TabSUsClassification);
ui->checkBox_SUs_Dimensions->setChecked(TabSUsDimensions);
ui->checkBox_SUs_Images->setChecked(TabSUsImages);
ui->checkBox_SUs_Bibliography_Evidence->setChecked(TabSUsBibliography);
ui->checkBox_Finds_Overview->setChecked(TabFindsOverview);
ui->checkBox_Finds_Spatial->setChecked(TabFindsSpatial);
ui->checkBox_Finds_Classification->setChecked(TabFindsClassification);
ui->checkBox_Finds_Dimensions->setChecked(TabFindsDimensions);
ui->checkBox_Finds_Images->setChecked(TabFindsImages);
ui->checkBox_Finds_Bibliography_Evidence->setChecked(TabFindsBibliography);
if(fileExtension == ".png") ui->radioButton_png->setChecked(true);
if(fileExtension == ".jpg") ui->radioButton_jpg->setChecked(true);
if(fileExtension == ".bmp") ui->radioButton_bmp->setChecked(true);
if(fileExtension == ".tiff") ui->radioButton_tiff->setChecked(true);
}
Preferences::~Preferences()
{
delete ui;
}
void Preferences::on_pushButton_Save_clicked()
{
//save openAtlas Preferences to standard location (OS dependend!)
QSettings settings;
settings.beginGroup("Preferences");
settings.setValue("TabIndex", ui->tabWidget->currentIndex());
settings.setValue("TabDataLevelIndex", ui->tabWidget_DataLevel->currentIndex());
// write settings for Images
settings.setValue("ImageViewActivated", ui->checkBox_ImageView->isChecked());
settings.setValue("ImageFolderPath", ui->lineEdit_ImagefolderPath->text());
settings.setValue("ImageFileExtension", fileExtension);
// write settings for enabled tabs
settings.setValue("TabSitesOverview", ui->checkBox_Sites_Overview->isChecked());
settings.setValue("TabSitesSpatial", ui->checkBox_Sites_Spatial->isChecked());
settings.setValue("TabSitesClassification", ui->checkBox_Sites_Classification->isChecked());
settings.setValue("TabSitesDimension", ui->checkBox_Sites_Dimensions->isChecked());
settings.setValue("TabSitesImages", ui->checkBox_Sites_Images->isChecked());
settings.setValue("TabSitesBibliography", ui->checkBox_Sites_Bibliography_Evidence->isChecked());
settings.setValue("TabFeaturesOverview", ui->checkBox_Features_Overview->isChecked());
settings.setValue("TabFeaturesSpatial", ui->checkBox_Features_Spatial->isChecked());
settings.setValue("TabFeaturesClassification", ui->checkBox_Features_Classification->isChecked());
settings.setValue("TabFeaturesDimension", ui->checkBox_Features_Dimensions->isChecked());
settings.setValue("TabFeaturesImages", ui->checkBox_Features_Images->isChecked());
settings.setValue("TabFeaturesBibliography", ui->checkBox_Features_Bibliography_Evidence->isChecked());
settings.setValue("TabSUsOverview", ui->checkBox_SUs_Overview->isChecked());
settings.setValue("TabSUsSpatial", ui->checkBox_SUs_Spatial->isChecked());
settings.setValue("TabSUsClassification", ui->checkBox_SUs_Classification->isChecked());
settings.setValue("TabSUsDimension", ui->checkBox_SUs_Dimensions->isChecked());
settings.setValue("TabSUsImages", ui->checkBox_SUs_Images->isChecked());
settings.setValue("TabSUsBibliography", ui->checkBox_SUs_Bibliography_Evidence->isChecked());
settings.setValue("TabFindsOverview", ui->checkBox_Finds_Overview->isChecked());
settings.setValue("TabFindsSpatial", ui->checkBox_Finds_Spatial->isChecked());
settings.setValue("TabFindsClassification", ui->checkBox_Finds_Classification->isChecked());
settings.setValue("TabFindsDimension", ui->checkBox_Finds_Dimensions->isChecked());
settings.setValue("TabFindsImages", ui->checkBox_Finds_Images->isChecked());
settings.setValue("TabFindsBibliography", ui->checkBox_Finds_Bibliography_Evidence->isChecked());
settings.endGroup();
QMessageBox::information(0, QObject::tr("Preferences Info"),
tr("Please restart openAtlas to use the new settings!"));
close();
}
void Preferences::on_pushButton_ImagefolderPath_clicked()
{
QString path = QFileDialog::getExistingDirectory(this,
tr("Imagefolder Path"));
if(path.isNull() == false)
{
ui->lineEdit_ImagefolderPath->setText(path);
}
}
void Preferences::on_radioButton_png_clicked()
{
if(ui->radioButton_png->isChecked())
{
fileExtension = ".png";
}
}
void Preferences::on_radioButton_jpg_clicked()
{
if(ui->radioButton_jpg->isChecked())
{
fileExtension = ".jpg";
}
}
void Preferences::on_radioButton_bmp_clicked()
{
if(ui->radioButton_bmp->isChecked())
{
fileExtension = ".bmp";
}
}
void Preferences::on_radioButton_tiff_clicked()
{
if(ui->radioButton_tiff->isChecked())
{
fileExtension = ".tiff";
}
}
void Preferences::on_checkBox_ImageView_clicked(bool checked)
{
if(checked == false)
{
ui->groupBox_imagePath->setEnabled(false);
ui->groupBox_imageExtension->setEnabled(false);
}
else
{
ui->groupBox_imagePath->setEnabled(true);
ui->groupBox_imageExtension->setEnabled(true);
}
}
<file_sep>/login.cpp
//////////////////////////////////////////////////////////////////////////////
// //
// This file is part of openATLAS. //
// //
// openATLAS 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 //
// any later version. //
// //
// openATLAS 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 openATLAS. If not, see <http://www.gnu.org/licenses/>. //
// //
// Database Design by <NAME> 2013 - 2014 //
// <EMAIL> //
// Frontend developed by <NAME> 2013 - 2014 //
// <EMAIL> //
// //
//////////////////////////////////////////////////////////////////////////////
#include "login.h"
#include "ui_login.h"
#include "mainwindow.h"
#include "databasemanager.h"
#include <QSettings>
//extern DatabaseManager *myDBM;
Login::Login(QWidget *parent):
QDialog(parent),
ui(new Ui::Login)
{
ui->setupUi(this);
QSettings settings;
settings.beginGroup("DatabaseSettings");
QString ConnectionName = settings.value("currentDatabaseConnection").toString();
settings.endGroup();
QSqlDatabase connectionDB = QSqlDatabase::database(myDBM->conn_file);
QString connectionQueryString = "SELECT * FROM tbl_connections WHERE connection_name = '" + ConnectionName + "';";
QSqlQuery connectionQuery(connectionQueryString, connectionDB);
while(connectionQuery.next())
{
QString database_name = connectionQuery.value(2).toString();
QString database_host = connectionQuery.value(5).toString();
QString database_username = connectionQuery.value(7).toString();
ui->label_ConnectionName->setText(ConnectionName);
ui->label_DatabaseName->setText(database_name);
ui->label_DatabaseHost->setText(database_host);
ui->label_Username->setText(database_username);
}
}
Login::~Login()
{
delete ui;
}
<file_sep>/preferences.h
#ifndef PREFERENCES_H
#define PREFERENCES_H
#include <QDialog>
namespace Ui {
class Preferences;
}
class Preferences : public QDialog
{
Q_OBJECT
public:
explicit Preferences(QWidget *parent = 0);
~Preferences();
private slots:
void on_pushButton_Save_clicked();
void on_pushButton_ImagefolderPath_clicked();
void on_radioButton_png_clicked();
void on_radioButton_jpg_clicked();
void on_radioButton_bmp_clicked();
void on_radioButton_tiff_clicked();
void on_checkBox_ImageView_clicked(bool checked);
private:
Ui::Preferences *ui;
};
#endif // PREFERENCES_H
|
4e0131d536c575e9e770f1e62af368da17a6823d
|
[
"Markdown",
"SQL",
"C++"
] | 18
|
C++
|
vittorio101/openAtlas
|
fc972c28f06fdb0a31025f46def0bacd22c4236a
|
f77a9baa557b344dd0b1d1e5d627926bceb57bca
|
refs/heads/master
|
<file_sep><h2>You can find me on:</h2>
<p>Codepen profile link: <a href="http://codepen.io/DevUIUX/" target="_blank">codepen.io/DevUIUX</a>.</p>
<p>Github profile link: <a href="https://github.com/Devuiux" target="_blank">github.com/Devuiux</a>.</p><file_sep>Portfolio
link: http://devuiux.github.io
<file_sep>Ractive.DEBUG = false;
window.onhashchange = OnHashChange;
window.onload = OnHashChange;
$(document).ready(function() {
const box1 = $('.box-1'),
box2 = $('.box-2'),
box3 = $('.box-3'),
box4 = $('.box-4');
box1.addClass('hover').delay(300).queue(function(next) {
$(this).removeClass('hover');
next();
box2.addClass('hover').delay(300).queue(function(next) {
$(this).removeClass('hover');
next();
box3.addClass('hover').delay(300).queue(function(next) {
$(this).removeClass('hover');
next();
box4.addClass('hover').delay(300).queue(function(next) {
$(this).removeClass('hover');
next();
box3.addClass('hover').delay(300).queue(function(next) {
$(this).removeClass('hover');
next();
box2.addClass('hover').delay(300).queue(function(next) {
$(this).removeClass('hover');
next();
box1.addClass('hover').delay(300).queue(function(next) {
$(this).removeClass('hover');
next();
});
});
});
});
});
});
});
});
var ractive = new Ractive({
el: '.cd-modal-content',
template: '#template'
});
//trigger the animation - open modal window
$('[data-type="modal-trigger"]').on('click', function() {
SetHashLocation($(this).attr('name'));
OpenModal($(this));
});
$(document).keyup(function(event) {
if (event.which == '27') closeModal();
});
$(window).on('resize', function() {
//on window resize - update cover layer dimention and position
if ($('.cd-section.modal-is-visible').length > 0) window.requestAnimationFrame(updateLayer);
});
function CustomSearch(boxName) {
$.get('pages/' + boxName + '.html').done(function(datain) {
ractive.set('dataout', datain);
if (boxName == 'contact' && $('.floating-labels').length > 0) {
floatLabels();
CheckRequired();
$('input[type="submit"]').click(function(e) {
CheckBefore();
if (BeforeSubmit() != true) e.preventDefault();
});
}
});
}
function SetHashLocation(boxName) {
window.location.hash = '#' + boxName;
}
function OnHashChange() {
var boxName = window.location.hash.substring(1);
(boxName != '') ? CustomSearch(boxName): closeModal();
$('[data-type="modal-trigger"]').each(function() {
if (boxName != '' && $(this).attr('name') == boxName && !$(this).hasClass('to-circle')) OpenModal($(this));
});
}
function WhichTransitionEvent() {
var t, el = document.createElement("fakeelement");
const transitions = {
"transition": "transitionend",
"OTransition": "oTransitionEnd",
"MozTransition": "transitionend",
"WebkitTransition": "webkitTransitionEnd"
};
for (t in transitions) {
if (el.style[t] !== undefined) return transitions[t];
}
}
const transitionEvent = WhichTransitionEvent();
function OpenModal(actionBtn) {
var scaleValue = retrieveScale(actionBtn.next('.cd-modal-bg'));
actionBtn.addClass('to-circle');
actionBtn.next('.cd-modal-bg').addClass('is-visible').one(transitionEvent, function() {
animateLayer(actionBtn.next('.cd-modal-bg'), scaleValue[0], scaleValue[1], true);
});
//if browser doesn't support transitions...
if (actionBtn.parents('.no-csstransitions').length > 0) animateLayer(actionBtn.next('.cd-modal-bg'), scaleValue[0], scaleValue[1], true);
}
function retrieveScale(btn) {
var btnH = btn.height() / 2,
btnW = btn.width() / 2,
top = btn.offset().top + btnH - $(window).scrollTop(),
left = btn.offset().left + btnW,
scale = scaleValue(top, left, btnH, btnW);
btn.css('position', 'fixed').velocity({
top: top - btnH,
left: left - btnW,
translateX: 0,
}, 0);
return [scale[0], scale[1]];
}
function scaleValue(topValue, leftValue, hValue, wValue) {
var maxDistH = (topValue > $(window).height() / 2) ? topValue : ($(window).height() - topValue),
maxDistW = (leftValue > $(window).width() / 2) ? leftValue : ($(window).width() - leftValue);
return [Math.ceil(maxDistH / hValue), Math.ceil(maxDistW / wValue)];
}
function animateLayer(layer, scaleValY, scaleValX, bool) {
layer.velocity({
scaleY: scaleValY,
scaleX: scaleValX
}, 400, function() {
$('body').toggleClass('overflow-hidden', bool);
(bool) ? layer.parents('.cd-section').addClass('modal-is-visible').end().off(transitionEvent): layer.removeClass('is-visible').removeAttr('style').siblings('[data-type="modal-trigger"]').removeClass('to-circle');
});
}
function updateLayer() {
var layer = $('.cd-section.modal-is-visible').find('.cd-modal-bg'),
layerH = layer.height() / 2,
layerW = layer.width() / 2,
layerTop = layer.siblings('.box').offset().top + layerH - $(window).scrollTop(),
layerLeft = layer.siblings('.box').offset().left + layerW,
scale = scaleValue(layerTop, layerLeft, layerH, layerW);
layer.velocity({
top: layerTop - layer.height() / 2,
left: layerLeft - layer.width() / 2,
scaleY: scale[0],
scaleX: scale[1]
}, 0);
}
function closeModal() {
var section = $('.cd-section.modal-is-visible');
section.removeClass('modal-is-visible').one(transitionEvent, function() {
animateLayer(section.find('.cd-modal-bg'), 1, 1, false);
});
//if browser doesn't support transitions...
if (section.parents('.no-csstransitions').length > 0) animateLayer(section.find('.cd-modal-bg'), 1, 1, false);
}
// form
function floatLabels() {
$('.floating-labels .cd-label').next().each(function() {
$(this).on('change keyup', function() {
($(this).val() != '') ? $(this).prev('.cd-label').addClass('float'): $(this).prev('.cd-label').removeClass('float');
});
});
}
function CheckRequired() {
$('.required').each(function() {
$(this).on('keyup keypress blur change', function() {
const name_regex = /^[a-zA-Z]+$/,
email_regex = /^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/;
var regex;
if ($(this).attr("id") == "cd-name") regex = name_regex;
if ($(this).attr("id") == "cd-email") regex = email_regex;
(!$(this).val().match(regex) || $(this).val().length == 0 || $(this).val() == '') ? $(this).addClass('error'): $(this).removeClass('error');
});
});
}
function BeforeSubmit() {
if ($('.cd-form').find('input, textarea').hasClass('error')) {
var errorWhere = $('.error').attr('id');
var errorMessage = $('.error-message');
if ($(".error").length > 1) errorMessage.html('<p>Please fill out the required fields.</p>')
else if (errorWhere == 'cd-name') errorMessage.html('<p>Please enter your NAME (only letters).</p>')
else if (errorWhere == 'cd-email') errorMessage.html('<p>Please enter a valid EMAIL address.</p>')
else if (errorWhere == 'cd-textarea') errorMessage.html('<p>Write me a message.</p>');
errorMessage.fadeIn(400);
return false;
} else {
return true;
}
}
function CheckBefore() {
$('.required').each(function() {
if ($(this).val() == 0) $(this).addClass('error');
});
}
// end form
|
3fed1b1765a59c3ad9685295f82f91bfd3309e66
|
[
"JavaScript",
"Text",
"HTML"
] | 3
|
HTML
|
Devuiux/devuiux.github.io
|
24a95db9ed136365852f42715d18cf2012292053
|
9332192ea7eb422fac1da51e4a76606f21c1b986
|
refs/heads/master
|
<repo_name>ViniciusTLR/Codigos_em_c<file_sep>/valor sugerido#.cpp
#include <iostream>
#include <locale>
using namespace std;
//Calcula o valor do produto e mais 20% para sugerir para a pessoa que quer comprar
int main(){
setlocale(LC_ALL, "ptb");
//VARIAVEIS
double produto, valor, sug;
//Inicio
cout << "Quanto custa o produto? ";
cin >> produto;
valor=produto*20/100;
sug=valor+produto;
cout << "\n\nvalor sugerido é de " << sug;
}
<file_sep>/medias dos entrevistados#.cpp
#include <iostream>
using namespace std;
//programa paraa calcula quantos foram os entrevistados e a media do peso e da idade deles
int main(){
//VARIAVEIS
int idade, entrevistados=0, totalid;
float peso, media_idade, media_peso, totalp;
//INICIO
cout << "Digite 0 para calcular as medias dos entrevistados\n\n";
cout << "Informe seu peso: ";
cin >> peso;
totalp=peso;
cout << "\nInforme sua idade: ";
cin >> idade;
totalid=idade;
while(peso!=0){
cout << "\nInforme seu peso: ";
cin >> peso;
totalp+=peso;
if(peso!=0){
cout << "\nInforme sua idade: ";
cin >> idade;
totalid+=idade;
}
entrevistados++;
}
cout << "\nNumeros de entrevistados: " <<entrevistados;
cout << "\n\nMedia do peso dos entrevistados: ";
media_peso = totalp/entrevistados;
cout << media_peso;
cout << "\n\nMedia da idade dos entrevistados: ";
media_idade = totalid/entrevistados;
cout << media_idade;
return 0;
}
<file_sep>/jokey club 2 (com comando while)#.cpp
#include<iostream>
using namespace std;
//Programa para definir em que categora a pessoa esta (usando o comando while)
int main(){
//VARIAVEIS
int idade=0;
//INICIO
while(idade != -1){
cout << "Informe sua idade: ";
cin >> idade;
if(idade >=7 && idade<=12){
cout << "Voce esta na categoria infantil\n\n";
}else if(idade>=13 && idade<=17){
cout << "Voce esta na categoria juvenil\n\n";
}else if(idade>=18 && idade <=49){
cout << "Voce esta na categoria adulto\n\n";
}else if(idade >=50){
cout << "Voce esta na categoria senior\n\n";
}else if(idade!= -1){
cout << "Voce esta fora da faixa etaria permitida\n\n";
}
}
return 0;
}
<file_sep>/media aritmetica(com função).cpp
#include<stdio.h>
//uma função que recebe quatro notas e retorne a media aritmética dessas notas
//função com retorno para calcular a media
float medianotas(float nota1, float nota2, float nota3, float nota4, float media){
media = (nota1 + nota2 + nota3 + nota4)/4;
return media;
}
float nota1, nota2, nota3, nota4, media,total;
int main(){
printf("Digite a primeira nota: ");
scanf("%f",¬a1);
printf("Digite a segunda nota: ");
scanf("%f",¬a2);
printf("Digite a terceira nota: ");
scanf("%f",¬a3);
printf("Digite a quarta nota: ");
scanf("%f",¬a4);
total=medianotas(nota1, nota2, nota3, nota4, media);
printf("A media das notas e: %f",total);
return 0;
}
<file_sep>/Numero fatorial#.cpp
#include<iostream>
using namespace std;
//Programa calcula o fatorial
int main(){
//VARIAVEIS
int num, contador, fatorial=1;
//INICIO
cout << "escolha um numero fatorial: ";
cin >> num;
for(contador=1; contador <= num; contador++){
fatorial*=contador;
}
cout << "\no fatorial desse numero e: " << fatorial;
return 0;
}
<file_sep>/matriz 3x4.cpp
#include<stdio.h>
//constroi uma matriz 3x4
int main(){
//VARIAVEIS
int matriz[3][4], i, j;
//INICIO
printf("Digite 12 valores para uma matriz[3][4]\n\n");
for(i=0;i<3;i++){
for(j=0;j<4;j++){
scanf("%d",&matriz[i][j]);
}
}
printf("\n");
printf("%d",matriz[0][0]);
printf(" | %d",matriz[0][1]);
printf(" | %d",matriz[0][2]);
printf(" | %d",matriz[0][3]);
printf("\n");
printf("%d",matriz[1][0]);
printf(" | %d",matriz[1][1]);
printf(" | %d",matriz[1][2]);
printf(" | %d",matriz[1][3]);
printf("\n");
printf("%d",matriz[2][0]);
printf(" | %d",matriz[2][1]);
printf(" | %d",matriz[2][2]);
printf(" | %d",matriz[2][3]);
return 0;
}
<file_sep>/notas menor que 5.cpp
#include<stdio.h>
//Leia uma matriz 10 x 3 com as notas de 10 alunos em 3 provas. Em seguida,
//escreva o número de alunos que não passou na prova 1, prova 2 e prova 3. Considere 5 como média e 10 nota máxima.
int main(){
//VARIAVEIS
float matriz[10][3], media, i, j;
int c=0;
//INICIO
printf("Digite as notas da primeira prova: \n");
for(i=0;i<5;i++){
for(j=0;j<2;j++){
scanf("%f", &matriz[2][5]);
if(matriz[2][5]<5){
c++;
}
}
}
printf("Reprovaram %d ", c); printf("alunos na prova 1\n\n");
printf("Digite as notas da segunda prova: \n");
c=0;
for(i=0;i<5;i++){
for(j=0;j<2;j++){
scanf("%f", &matriz[2][5]);
if(matriz[2][5]<5){
c++;
}
}
}
printf("Reprovaram %d ", c); printf("alunos na prova 2\n\n");
printf("Digite as notas da terceira prova: \n");
c=0;
for(i=0;i<5;i++){
for(j=0;j<2;j++){
scanf("%f", &matriz[2][5]);
if(matriz[2][5]<5){
c++;
}
}
}
printf("Reprovaram %d ", c); printf("alunos na prova 3\n");
return 0;
}
<file_sep>/Lista de Aprovados e reprovados.c
#include<stdio.h>
//LISTAS DE APROVADOS E REPROVADOS
int main(){
int lista,i,j=0;
float medias[5];
printf("Digite as medias: \n");
for(i=0;i<5;i++){
scanf("%f",&medias[i]);
}
printf("Digite [1] para lista de aprovados ou digite [2] para lista de reprovados\n");
scanf("%d",&lista);
switch(lista){
case 1:
for(i=0;i<5;i++){
medias[i];
if(medias[i]>5){
j++;
}
}
printf("Foram aprovados %d",j); printf(" alunos");
break;
case 2:
for(i=0;i<5;i++){
medias[i];
if(medias[i]<=5){
j++;
}
}
printf("Foram reprovados %d",j); printf(" alunos");
break;
}
return 0;
}
<file_sep>/Armazenar 45 nomes usando vetores#.cpp
#include<iostream>
using namespace std;
//Programa guarda 45 nomes dentro do vetor nomes
int main(){
//VARIAVEIS
string nomes[45];
int i;
//INICIO
for(i=0; i <= 44; i++){
cout << "digite o " << i+1 << " nome: ";
cin >> nomes[i];
}
return 0;
}
<file_sep>/peso da comida no restaurante#.cpp
#include<iostream>
using namespace std;
//Programa diz o prešo do prato de acordo com o prešo do quilo e do peso do seu prato
int main(){
//VARIAVEIS
float preco;
float peso;
double valor;
//INICIO
cout << "qual o preco do quilo da comida? \n\n";
cin >> preco; cout << "\n\n";
cout << "qual o peso do prato? \n\n";
cin >> peso;
valor = preco*peso/1000;
cout << "seu prato custa " << valor << " reais";
return 0;
}
<file_sep>/Descontos por niveis.c
#include<stdio.h>
#include<ctype.h>
//descontos diferentes para niveis de cliente
int main(){
int nivel;
float valor,desconto,total;
printf("Qual o valor do produto?\n");
scanf("%f",&valor);
printf("\nDigite o nivel do cliente para calcular o desconto. \n");
printf("Digite [1] para o nivel A, digite [2] para o nivel B ou digite [3] para o nivel C.\n");
scanf("%d",&nivel);
//nivel = toupper(nivel); serve para o A(maiusculo) e a(minusculo) serem iguais. FUNCIONA SÓ COM A BLIBLIOTECA #include<ctype.h>
switch(nivel){
case 1:
desconto=valor*20/100;
printf("***Cliente nivel A***");
printf("\nDesconto de %.2f",desconto); printf(" reais");
total=valor-desconto;
printf("\nO total a pagar e de %.2f",total); printf(" reais");
break;
case 2:
desconto=valor*15/100;
printf("***Cliente nivel B***");
printf("\nDesconto de %.2f",desconto); printf(" reais");
total=valor-desconto;
printf("\nO total a pagar e de %.2f",total); printf(" reais");
break;
case 3:
desconto=valor*10/100;
printf("\n***Cliente nivel C***");
printf("\nDesconto de %.2f",desconto); printf(" reais");
total=valor-desconto;
printf("\nO total a pagar e de %.2f",total); printf(" reais");
break;
default:
printf("####ERRO####");
}
return 0;
}
<file_sep>/diferença dos numeros(com função).cpp
#include<stdio.h>
//uma função que recebe dois valores (x,y) e retorne a diferença entre eles.
int diferenca(int x, int y){
int resul;
if(x>y){
resul = x - y;
return resul;
}else{
resul = x + y;
return resul;
}
}
int main(void){
int x,y,retorno;
printf("Digite o primeiro numero: ");
scanf("%d", &x);
printf("Digite o segundo numero: ");
scanf("%d", &y);
retorno=diferenca(x,y);
printf("A diferenca entre os numeros e: %d",retorno);
return 0;
}
<file_sep>/PROJETO_2.c
#include<stdio.h>
#include <locale.h>
#include <stdlib.h>
//PROJETO - FAZER UM JOGO EM QUE O ASTRONAUTA E SUA TRIPULAÇÃO SAIA EM BUSCA DO DNA PERFEITO PARA A CURA DO CORONAVÍRUS.
//VARIAVEIS
int i, j, x, opcoes, vidaperdida, visualizar;
int func_cobra, func_buraco, func_jacare, explodir;
char nome[1], nomes_tripulantes[2][20];
int C, CSS, HTML, JAVA, JAVASCRIPT,PYTHON, TYPESCRIPT;
int vida=100;
int resultado;
int cobra=0, jacare=0, buraco=0;
char dnacorreto[] = "ABCDJUEDIJXLOPDWUHTYLLOPJNBG", dnaemprocesso[29];
char c[] = "ABCD", css[] = "JUED" , html[] = "IJXL" , java[] = "OPDW", javascript[] = "UHTY", python[] = "LLOP" , typescript[] = "JNBG" ;
//INICIO DO CODIGO
//FUNÇÃO PARA DECOLAGEM
void decolar(int permitir){
printf("Aperte: 1 para Permitir decolagem: ");
scanf("%d",&permitir);
while(permitir!=1){
if(permitir==1){
printf("3,2,1 VAII!!\n");
}else{
printf("##APERTE O BOTÃO DE DECOLAGEM##\n");
scanf("%d",&permitir);
if(permitir==1){
printf("3,2,1 VAII!!\n");
}
}
}
}
//FUNCAO EXPLODIR FOGUETE
void explodir_foguete(int explodir){
printf("###KBOOOM###\n");
printf("Você explodiu o foguete, lista dos que vieram a óbito:\n %s",nome);
for(i=1;i<3;i++){
printf("\n %s",nomes_tripulantes[i]);
}
printf("\n");
}
//FUNÇÃO DE PONTOS
void pontos( int visualizar){
printf("\nSeu progresso no jogo:\n\n");
printf("Você perdeu "); vidaperdida=100-vida; printf("%d",vidaperdida); printf(" pontos de vida\n\n");
printf("Você foi picado por cobras %d",cobra); printf(" vez(es)\n\n");
printf("Você foi mordido por jacarés %d",jacare); printf(" vez(es)\n\n");
printf("Você caiu em buracos %d",cobra); printf(" vez(es)");
}
//FUNÇÃO COBRA
void funcao_cobra(int func_cobra){
cobra++;
printf("voce foi picado pela cobra... e perdeu 5 pontos de vida \n");
vida = vida-5;
printf("Sua vida e de:\n");
printf("%d",vida); printf("\n");
}
//FUNÇÃO JACARE
void funcao_jacare(int func_jacare){
jacare++;
printf("voce foi mordido pelo jacaré... e perdeu 7 pontos\n");
vida = vida-7;
printf("Sua vida e de:\n");
printf("%d",vida); printf("\n");
}
//FUNÇÃO BURACO
void funcao_buraco(int func_buraco){
buraco++;
printf("voce caiu no buraco... e perdeu 6 pontos\n");
vida = vida-6;
printf("Sua vida e de:\n");
printf("%d",vida); printf("\n");
}
int main (){
setlocale(LC_ALL, "Portuguese");
printf("***Administração Nacional de Aeronáutica e Espaco do Brasil***\n");
printf("Olá, astronauta, bem vindo a central da ANAE, antes do foguete ANTARES BRASILEIRO decolar nos diga o nome dos 3 tripulantes:\n\n ");
printf("Primeiro vamos começar com o líder, que é você, qual o seu nome?\n");
scanf("%s",&nome);
printf("Agora digite o nomes dos outros 2 tripulantes:\n");
for(i=1;i<3;i++){
printf("Digite o nome do %d", i); printf(" tripulante: ");
scanf("%s",&nomes_tripulantes[i]);
}
printf("Tudo pronto, vamos começar!\n\n %s",nome); printf(", precisamos que você escolha uma dessas opções para começar a missão,");
printf("Aperte:\n1 para Permitir decolagem\n2 para explodir foguete\n3 para Não permitir decolagem.\n");
scanf("%d",&opcoes);
switch(opcoes){
case 1:
printf("3,2,1 VAII!!\n");
break;
case 2:
explodir_foguete(explodir);
break;
case 3:
printf("SAIAM DO FOGUETE!!!");
break;
default:
printf("Você apertou uma opção que não existe");
}
//PLANETA C
printf("Você chegou ao planeta C, digite a senha do planeta C para ter permissão para pousar:\n");
scanf("%d",&C);
while (C !=4321){
printf("Digite a senha novamente:");
scanf("%d",&C);
}
if (C=4321){
printf("***Permissão concedida***"" \n");
}
printf("Voce avistou um lago e la esta o DNA, so que no caminho voce encontrou uma cobra e ira desafia-la\n");
printf("Resolva a seguinte questao:\n");
do{
printf("Qual e o resultado de 2+2?\n");
scanf("%d",&resultado);
if(resultado!=4){
funcao_cobra(func_cobra);
}else{
printf("voce acertou um soco na cobra!\n");
}
if(vida<1){
printf("==============================================================================================");
printf("\nQue pena, voce chegou a 0 pontos de vida. Aperte qualquer tecla para explodir o foguete!");
scanf("%d ",&opcoes);
explodir_foguete(explodir);
printf("==============================================================================================\n");
pontos(visualizar);
exit(0);
}
}while(resultado !=4);
printf("Sua vida e de:\n");
printf("%d",vida);
printf("\nProxima pergunta\n");
do{
printf("Qual e o resultado de 4+4?\n");
scanf("%d",&resultado);
if(resultado!=8){
funcao_cobra(func_cobra);
}else{
printf("\nvoce acertou um chute na cobra!\n");
}
if(vida<1){
printf("==============================================================================================");
printf("\nQue pena, voce chegou a 0 pontos de vida. Aperte qualquer tecla para explodir o foguete!");
scanf("%d ",&opcoes);
explodir_foguete(explodir);
printf("==============================================================================================\n");
pontos(visualizar);
exit(0);
}
}while(resultado !=8);
printf("Sua vida e de:\n");
printf("%d",vida);
printf("\nUltima pergunta:\n");
do{
printf("Qual e o resultado de 8+8?\n");
scanf("%d",&resultado);
if(resultado!=16){
funcao_cobra(func_cobra);
}else{
printf("\nvoce segurou na cabeça da cobra e a jogou muito longe!\n\n");
}
if(vida<1){
printf("==============================================================================================");
printf("\nQue pena, voce chegou a 0 pontos de vida. Aperte qualquer tecla para explodir o foguete!");
scanf("%d ",&opcoes);
explodir_foguete(explodir);
printf("==============================================================================================\n");
pontos(visualizar);
exit(0);
}
}while(resultado !=16);
printf("Sua vida e de:\n");
printf("%d",vida);
printf("\n\nParabens voce conseguiu passar da cobra \n");
printf("Você chegou ao lago... mergulhou e pegou o DNA.\n");
for(i=0;i<j+4;i++){
dnaemprocesso[i]=c[i];
}
printf("Você voltou para sua nave, agora vamos para o planeta CSS\n");
decolar(opcoes);
//PLANETA CSS
printf("Você chegou ao planeta CSS, digite a senha do planeta CSS para ter permissão para pousar:\n");
scanf("%d",&CSS);
while (CSS != 6542){
printf("Digite a senha novamente:");
scanf("%d",&CSS);
}
if (CSS=6542){
printf("***Permissão concedida***"" \n");
}
printf("Voce avistou um lago e la esta o DNA, so que no caminho voce encontrou uma jacare e ira desafia-lo\n");
printf("Resolva a seguinte questao:\n");
do{
printf("Qual e o resultado de 10-8?\n");
scanf("%d",&resultado);
if(resultado!=2){
funcao_jacare(func_jacare);
}else{
printf("\nvoce esquivou da mordida do jacare!\n");
}
if(vida<1){
printf("==============================================================================================");
printf("\nQue pena, voce chegou a 0 pontos de vida. Aperte qualquer tecla para explodir o foguete!");
scanf("%d ",&opcoes);
explodir_foguete(explodir);
printf("==============================================================================================\n");
pontos(visualizar);
exit(0);
}
}while(resultado !=2);
printf("Sua vida e de:\n");
printf("%d",vida);
printf("\nProxima pergunta\n");
do{
printf("Qual e o resultado de 32-24?\n");
scanf("%d",&resultado);
if(resultado!=8){
funcao_jacare(func_jacare);
}else{
printf("\nvoce subiu em uma arvore!\n");
}
if(vida<1){
printf("==============================================================================================");
printf("\nQue pena, voce chegou a 0 pontos de vida. Aperte qualquer tecla para explodir o foguete!");
scanf("%d ",&opcoes);
explodir_foguete(explodir);
printf("==============================================================================================\n");
pontos(visualizar);
exit(0);
}
}while(resultado !=8);
printf("Sua vida e de:\n");
printf("%d",vida);
printf("\nUltima pergunta:\n");
do{
printf("Qual e o resultado de 56-40?\n");
scanf("%d",&resultado);
if(resultado!=16){
funcao_jacare(func_jacare);
}else{
printf("\nvoce jogou uma pedra na cabeça do jacare e o jacare desmaiou!\n");
}
if(vida<1){
printf("==============================================================================================");
printf("\nQue pena, voce chegou a 0 pontos de vida. Aperte qualquer tecla para explodir o foguete!");
scanf("%d ",&opcoes);
explodir_foguete(explodir);
printf("==============================================================================================\n");
pontos(visualizar);
exit(0);
}
}while(resultado !=16);
printf("\nSua vida e de:\n");
printf("%d",vida);
printf("\nParabens voce conseguiu passar do jacare =D\n");
printf("Você chegou ao lago... mergulhou e pegou o DNA.\n");
int x=0;
j=4;
for(i=4;i<j+4;i++){
dnaemprocesso[i]=css[x];
x++;
}
printf("Você voltou para sua nave, agora vamos para o planeta HTML\n");
decolar(opcoes);
//PLANETA HTML
printf("Você chegou ao planeta HTML, digite a senha do planeta HTML para ter permissão para pousar:\n");
scanf("%d",&HTML);
while (HTML != 9876){
printf("Digite a senha novamente:");
scanf("%d",&HTML);
}
if (HTML=9876){
printf("***Permissão concedida***"" \n");
}
printf("Voce avistou um lago e la esta o DNA, so que no caminho voce encontrou um buraco.\n");
printf("Para que voce não caia no buraco...\n");
printf("Resolva a seguinte questao:\n");
do{
printf("Qual e o resultado de 12+88?\n");
scanf("%d",&resultado);
if(resultado!=100){
funcao_buraco(func_buraco);
}else{
printf("\no buraco nao era tao grande... então voce pulou o buraco!\n");
}
if(vida<1){
printf("==============================================================================================");
printf("\nQue pena, voce chegou a 0 pontos de vida. Aperte qualquer tecla para explodir o foguete!");
scanf("%d ",&opcoes);
explodir_foguete(explodir);
printf("==============================================================================================\n");
pontos(visualizar);
exit(0);
}
}while(resultado !=100);
printf("Sua vida e de:\n");
printf("%d",vida);
printf("\nProxima pergunta\n");
do{
printf("Qual e o resultado de 80/2?\n");
scanf("%d",&resultado);
if(resultado!=40){
funcao_buraco(func_buraco);
}else{
printf("\nvoce avistou uma passagem do lado do buraco... então voce apenas passou por ela!\n");
}
if(vida<1){
printf("==============================================================================================");
printf("\nQue pena, voce chegou a 0 pontos de vida. Aperte qualquer tecla para explodir o foguete!");
scanf("%d ",&opcoes);
explodir_foguete(explodir);
printf("==============================================================================================\n");
pontos(visualizar);
exit(0);
}
}while(resultado !=40);
printf("Sua vida e de:\n");
printf("%d",vida);
printf("\nUltima pergunta:\n");
do{
printf("Qual e o resultado de 25+25?\n");
scanf("%d",&resultado);
if(resultado!=50){
funcao_buraco(func_buraco);
}else{
printf("\nvoce também pulou esse buraco!\n");
}
if(vida<1){
printf("==============================================================================================");
printf("\nQue pena, voce chegou a 0 pontos de vida. Aperte qualquer tecla para explodir o foguete!");
scanf("%d ",&opcoes);
explodir_foguete(explodir);
printf("==============================================================================================\n");
pontos(visualizar);
exit(0);
}
}while(resultado !=50);
printf("Sua vida e de:\n");
printf("%d",vida);
printf("\nParabens voce conseguiu passar do buraco =D\n");
printf("Você chegou ao lago... mergulhou e pegou o DNA.\n");
x=0;
j=8;
for(i=8;i<j+4;i++){
dnaemprocesso[i]=html[x];
x++;
}
printf("Você voltou para sua nave, agora vamos para o planeta JAVA\n");
decolar(opcoes);
//PLANETA JAVA
printf("Você chegou ao planeta JAVA, digite a senha do planeta JAVA para ter permissão para pousar:\n");
scanf("%d",&JAVA);
while (JAVA != 1234){
printf("Digite a senha novamente:");
scanf("%d",&JAVA);
}
if (JAVA=1234){
printf("***Permissão concedida***"" \n");;
}
printf("Voce avistou um lago e la esta o DNA, so que no caminho voce encontrou um jacare.\n");
printf("Resolva a seguinte questao:\n");
do{
printf("Qual e o resultado de 1000/10?\n");
scanf("%d",&resultado);
if(resultado!=100){
funcao_jacare(func_jacare);
}else{
printf("\nvoce esquivou da mordida do jacare!\n");
}
if(vida<1){
printf("==============================================================================================");
printf("\nQue pena, voce chegou a 0 pontos de vida. Aperte qualquer tecla para explodir o foguete!");
scanf("%d ",&opcoes);
explodir_foguete(explodir);
printf("==============================================================================================\n");
pontos(visualizar);
exit(0);
}
}while(resultado !=100);
printf("Sua vida e de:\n");
printf("%d",vida);
printf("\nProxima pergunta\n");
do{
printf("Qual e o resultado de 20*2?\n");
scanf("%d",&resultado);
if(resultado!=40){
funcao_jacare(func_jacare);
}else{
printf("\nvoce subiu em uma arvore!\n");
}
if(vida<1){
printf("==============================================================================================");
printf("\nQue pena, voce chegou a 0 pontos de vida. Aperte qualquer tecla para explodir o foguete!");
scanf("%d ",&opcoes);
explodir_foguete(explodir);
printf("==============================================================================================\n");
pontos(visualizar);
exit(0);
}
}while(resultado !=40);
printf("Sua vida e de:\n");
printf("%d",vida);
printf("\nUltima pergunta:\n");
do{
printf("Qual e o resultado de 100/2?\n");
scanf("%d",&resultado);
if(resultado!=50){
funcao_jacare(func_jacare);
}else{
printf("\nvoce jogou uma pedra na cabeça do jacare e o jacare desmaiou!\n");
}
if(vida<1){
printf("==============================================================================================");
printf("\nQue pena, voce chegou a 0 pontos de vida. Aperte qualquer tecla para explodir o foguete!");
scanf("%d ",&opcoes);
explodir_foguete(explodir);
printf("==============================================================================================\n");
pontos(visualizar);
exit(0);
}
}while(resultado !=50);
printf("Sua vida e de:\n");
printf("%d",vida);
printf("\nParabens voce conseguiu passar do jacare \n");
printf("Você chegou ao lago... mergulhou e pegou o DNA.\n");
x=0;
j=12;
for(i=12;i<j+4;i++){
dnaemprocesso[i]=java[x];
x++;
}
printf("Você voltou para sua nave, agora vamos para o planeta JAVASCRIPT\n");
decolar(opcoes);
//PLANETA JAVASCRIPT
printf("Você chegou ao planeta JAVASCRIPT, digite a senha do planeta JAVASCRIPT para ter permissão para pousar:\n");
scanf("%d",&JAVASCRIPT);
while (JAVASCRIPT != 5678){
printf("Digite a senha novamente:");
scanf("%d",&JAVASCRIPT);
}
if (JAVASCRIPT=5678){
printf("***Permissão concedida***"" \n");
}
printf("Voce avistou um lago e la esta o DNA, so que no caminho voce encontrou uma cobra e ia desafia-lo.\n");
printf("Resolva a seguinte questao:\n");
do{
printf("Qual e o resultado de 75+15?\n");
scanf("%d",&resultado);
if(resultado!=90){
funcao_cobra(func_cobra);
}else{
printf("voce acertou um soco na cobra!\n");
}
if(vida<1){
printf("==============================================================================================");
printf("\nQue pena, voce chegou a 0 pontos de vida. Aperte qualquer tecla para explodir o foguete!");
scanf("%d ",&opcoes);
explodir_foguete(explodir);
printf("==============================================================================================\n");
pontos(visualizar);
exit(0);
}
}while(resultado !=90);
printf("Sua vida e de:\n");
printf("%d",vida);
printf("\nProxima pergunta\n");
do{
printf("Qual e o resultado de 35+45?\n");
scanf("%d",&resultado);
if(resultado!=80){
funcao_cobra(func_cobra);
}else{
printf("\nvoce acertou um chute na cobra!\n");
}
if(vida<1){
printf("==============================================================================================");
printf("\nQue pena, voce chegou a 0 pontos de vida. Aperte qualquer tecla para explodir o foguete!");
scanf("%d ",&opcoes);
explodir_foguete(explodir);
printf("==============================================================================================\n");
pontos(visualizar);
exit(0);
}
}while(resultado !=80);
printf("Sua vida e de:\n");
printf("%d",vida);
printf("\nUltima pergunta:\n");
do{
printf("Qual e o resultado de 110-40?\n");
scanf("%d",&resultado);
explodir_foguete(explodir);
printf("==============================================================================================\n");
if(resultado!=70){
funcao_cobra(func_cobra);
}else{
printf("\nvoce segurou na cabeça da cobra e a jogou muito longe!\n\n");
}
if(vida<1){
printf("==============================================================================================");
printf("\nQue pena, voce chegou a 0 pontos de vida. Aperte qualquer tecla para explodir o foguete!");
scanf("%d ",&opcoes);
pontos(visualizar);
exit(0);
}
}while(resultado !=70);
printf("Sua vida e de:\n");
printf("%d",vida);
printf("\nParabens voce conseguiu passar da cobra \n");
printf("Você chegou ao lago... mergulhou e pegou o DNA.\n");
x=0;
j=16;
for(i=16;i<j+4;i++){
dnaemprocesso[i]=javascript[x];
x++;
}
printf("Você voltou para sua nave, agora vamos para o planeta PYTHON\n");
decolar(opcoes);
//PLANETA PYTHON
printf("Você chegou ao planeta PYTHON, digite a senha do planeta PYTHON para ter permissão para pousar:\n");
scanf("%d",&PYTHON);
while (PYTHON != 2456){
printf("Digite a senha novamente:");
scanf("%d",&PYTHON);
}
if (PYTHON=2456){
printf("***Permissão concedida***"" \n");
}
printf("Voce avistou um lago e la esta o DNA, so que no caminho voce encontrou um buraco.\n");
printf("Para que voce não caia no buraco...\n");
printf("Resolva a seguinte questao:\n");
do{
printf("Qual e o resultado de 6*6?\n");
scanf("%d",&resultado);
if(resultado!=36){
funcao_buraco(func_buraco);
}else{
printf("\no buraco nao era tao grande... então voce pulou o buraco!\n");
}
if(vida<1){
printf("==============================================================================================");
printf("\nQue pena, voce chegou a 0 pontos de vida. Aperte qualquer tecla para explodir o foguete!");
scanf("%d ",&opcoes);
explodir_foguete(explodir);
printf("==============================================================================================\n");
pontos(visualizar);
exit(0);
}
}while(resultado !=36);
printf("Sua vida e de:\n");
printf("%d",vida);
printf("\nProxima pergunta\n");
do{
printf("Qual e o resultado de 9*9?\n");
scanf("%d",&resultado);
if(resultado!=81){
funcao_buraco(func_buraco);
}else{
printf("\nvoce avistou uma passagem do lado do buraco... então voce apenas passou por ela!\n");
}
if(vida<1){
printf("==============================================================================================");
printf("\nQue pena, voce chegou a 0 pontos de vida. Aperte qualquer tecla para explodir o foguete!");
scanf("%d ",&opcoes);
explodir_foguete(explodir);
printf("==============================================================================================\n");
pontos(visualizar);
exit(0);
}
}while(resultado !=81);
printf("Sua vida e de:\n");
printf("%d",vida);
printf("\nUltima pergunta:\n");
do{
printf("Qual e o resultado de 3*3?\n");
scanf("%d",&resultado);
if(resultado!=9){
funcao_buraco(func_buraco);
}else{
printf("\nvoce também pulou esse buraco!\n");
}
if(vida<1){
printf("==============================================================================================");
printf("\nQue pena, voce chegou a 0 pontos de vida. Aperte qualquer tecla para explodir o foguete!");
scanf("%d ",&opcoes);
explodir_foguete(explodir);
printf("==============================================================================================\n");
pontos(visualizar);
exit(0);
}
}while(resultado !=9);
printf("Sua vida e de:\n");
printf("%d",vida);
printf("\nParabens voce conseguiu passar do buraco =D\n");
printf("Você chegou ao lago... mergulhou e pegou o DNA.\n");
x=0;
j=20;
for(i=20;i<j+4;i++){
dnaemprocesso[i]=python[x];
x++;
}
printf("Você voltou para sua nave, agora vamos para o planeta TYPESCRIPT\n");
decolar(opcoes);
//PLANETA TYPESCRIPT
printf("Você chegou ao planeta TYPESCRIPT, digite a senha do planeta TYPESCRIPT para ter permissão para pousar:\n");
scanf("%d",&TYPESCRIPT);
while (TYPESCRIPT != 8765){
printf("Digite a senha novamente:");
scanf("%d",&TYPESCRIPT);
}
if (TYPESCRIPT=8765){
printf("***Permissão concedida***"" \n");
}
printf("Voce avistou um lago e la esta o DNA, so que no caminho voce encontrou um jacare e ira desafia-lo.\n");
printf("Resolva a seguinte questao:\n");
do{
printf("Qual e o resultado de 226/2?\n");
scanf("%d",&resultado);
if(resultado!=113){
funcao_jacare(func_jacare);
}else{
printf("\nvoce esquivou da mordida do jacare!\n");
}
if(vida<1){
printf("==============================================================================================");
printf("\nQue pena, voce chegou a 0 pontos de vida. Aperte qualquer tecla para explodir o foguete!");
scanf("%d ",&opcoes);
explodir_foguete(explodir);
printf("==============================================================================================\n");
pontos(visualizar);
exit(0);
}
}while(resultado !=113);
printf("Sua vida e de:\n");
printf("%d",vida);
printf("\nProxima pergunta\n");
do{
printf("Qual e o resultado de 15*3?\n");
scanf("%d",&resultado);
if(resultado!=45){
funcao_jacare(func_jacare);
}else{
printf("\nvoce subiu em uma arvore!\n");
}
if(vida<1){
printf("==============================================================================================");
printf("\nQue pena, voce chegou a 0 pontos de vida. Aperte qualquer tecla para explodir o foguete!");
scanf("%d ",&opcoes);
explodir_foguete(explodir);
printf("==============================================================================================\n");
pontos(visualizar);
exit(0);
}
}while(resultado !=45);
printf("Sua vida e de:\n");
printf("%d",vida);
printf("\nUltima pergunta:\n");
do{
printf("Qual e o resultado de 400*2?\n");
scanf("%d",&resultado);
if(resultado!=800){
funcao_jacare(func_jacare);
}else{
printf("\nvoce jogou uma pedra na cabeça do jacare e o jacare desmaiou!\n");
}
if(vida<1){
printf("==============================================================================================");
printf("\nQue pena, voce chegou a 0 pontos de vida. Aperte qualquer tecla para explodir o foguete!");
scanf("%d ",&opcoes);
explodir_foguete(explodir);
printf("==============================================================================================\n");
pontos(visualizar);
exit(0);
}
}while(resultado !=800);
printf("Sua vida e de:\n");
printf("%d",vida);
printf("\nParabens voce conseguiu passar do buraco =D\n");
printf("Você chegou ao lago... mergulhou e pegou o DNA.\n");
x=0;
j=24;
for(i=24;i<j+4;i++){
dnaemprocesso[i]=typescript[x];
x++;
}
printf("Você voltou para sua nave, e conferiu o DNA\n.\n.\n.\n");
if(dnacorreto==dnaemprocesso){
printf("Parabéns, você conseguir completar o DNA, volte para a Terra");
}
printf("Aperte 4 para voltar à Terra: ");
scanf("%d",&opcoes);
do{
if(opcoes==4){
printf("Você voltou a Terra com o DNA completo e salvou a Terra do COVID-19\n Parabéns %s",nome);
printf(", todos saúdam seu nome.");
}else{
printf("Aperte a opção voltar para Terra: ");
}
}while(opcoes!=4);
pontos(visualizar);
return 0;
}
<file_sep>/dados e numeros impares#.cpp
#include<iostream>
using namespace std;
//Programa ira dizer quantas vezes caiu um numero impar
int main(){
//VARIAVEIS
int dado[10], impar=0, cont=0;
//INICIO
cout << "Jogue 10 vezes o dado";
for(cont=0; cont <=9; cont++){
cout << "\nInforme o " << cont+1 << " numero: ";
cin >> dado[cont];
if(dado[cont]%2!=0){
impar++;
}
}
cout << "\n\ncairam " << impar << " numeros impares";
return 0;
}
<file_sep>/jogo de numero impar e par#.cpp
#include<iostream>
using namespace std;
//Jogo classico (impar ou par)
int main(){
//VARIAVEIS
int par[10], impar[10], resul, cont, venceuA=0, venceuB=0,rod=1;
//INICIO
cout << "JOGADOR A = PAR" << "\n";
cout << "JOGADOR B = IMPAR" << "\n\n";
for(cont=0; cont<=9; cont++){
cout << rod++ << " Rodada:\n";
cout << "Jogador A escolha um numero: ";
cin >> par[cont];
cout << "\n\n" << "Jogador B escolha um numero: ";
cin >> impar[cont];
resul=par[cont]+impar[cont];
if(resul%2==0){
cout << "\nVenceu o jogador A\n\n";
venceuA++;
}else{
cout <<"\nVenceu o jogador B\n\n";
venceuB++;
}
}
cout << "Jogador A venceu: " << venceuA << " vezes\n";
cout << "Jogador B venceu: " << venceuB << " vezes";
return 0;
}
<file_sep>/quantos dias a pessoa ja viveu.#.cpp
#include<iostream>
#include<locale>
using namespace std;
//Esse programa ira dizer quantos dias uma pessoa já viveu
int main(){
setlocale(LC_ALL, "ptb");
//VARIAVEIS
int dias, idade, anos;
//INICIO
cout << "Quantos anos você tem? ";
cin >> anos;
dias= anos*365;
cout << "\n\nVocê viveu " << dias << " dias.";
return 0;
}
<file_sep>/quadrado do numero... #.cpp
#include<iostream>
#include<locale>
using namespace std;
//Programa diz o quadrado do numero digitado e diz se o quadrado do numero é maior que 25
int main(){
setlocale(LC_ALL, "ptb");
//VARIAVEIS
int num,qua;
//INICIO
cout << "Dígite um número: ";
cin >> num;
cout << "\n\n" << num;
qua=num*num;
cout << ", O quadrado de " << num << " é = " << qua;
if(qua > 25){
cout << " \n\no quadrado de " << num << " é maior do que 25";
}else{
cout << "\n\no quadrado de " << num << " nao é maior do que 25";
}
}
<file_sep>/qual é o menor(com função).cpp
#include<stdio.h>
//uma função que recebe dois números inteiro e retorne o menor número.
int menornumero (int x,int y){
if(x>y){
return 1;
}else if(x==y){
return 0;
}else{
return 2;
}
}
int main(void){
int x,y,resul;
printf("Digite o primeiro numero: ");
scanf("%d", &x);
printf("Digite o segundo numero: ");
scanf("%d", &y);
resul = menornumero(x,y);
if(resul=0){
printf("Eles sao iguais");
}else if(resul=1){
printf("O segundo numero e menor");
}else{
printf("O primeiro numero e menor");
}
return 0;
}
<file_sep>/par ou impar(com função).cpp
#include<stdio.h>
//uma função que recebe um valor inteiro e verifica se o valor é par.
int numpar(int num){
int resul;
num=num%2;
if(num==0){
printf("\nE um numero par");
return resul;
}else{
printf("\nNao e um numero par");
return resul;
}
}
int num, retorno;
int main(){
printf("Digite um numero: ");
scanf("%d",&num);
retorno=numpar(num);
return 0;
}
<file_sep>/calcular area do retangulo#.cpp
#include<iostream>
using namespace std;
//Programa calcula a area do retangulo
int main(){
//VARIAVEIS
double lado1;
double lado2;
double area;
//INICIO
cout << "***qual a medida do terreno*** \n\n";
cout << "qual a largura? "; cin >> lado1; cout << "qual o comprimento? "; cin >> lado2;
cout << lado1 << " X " << lado2;
area = lado1*lado2;
cout << ", entao a area do retangulo e igual a ";
cout << area;
return 0;
}
<file_sep>/Fibonacci.cpp
#include <iostream>
using namespace std;
int main(){
//VARIAVEIS
int i=0, quant, f, num1=0, num2=1;
//INICIO
cout << "Digite a quantidade de sequencias: ";
cin >> quant;
while(i<=quant){
f=num1+num2;
cout << f;
cout << " ";
i++;
if(i==quant){
break;
}
num2=f+num1;
cout << num2;
cout << " ";
i++;
if(i==quant){
break;
}
num1=f+num2;
cout << num1;
cout << " ";
i++;
if(i==quant){
break;
}
}
return 0;
}
<file_sep>/quadrado e o cubo de um numero#.cpp
#include <iostream>
#include <locale>
using namespace std;
//Programa calcula o quadrado e o cubo do numero digitado
int main(){
setlocale(LC_ALL, "ptb");
//VARIAVEIS
int num;
int q;
int c;
//INICIO
cout << "Digite um número para saber o quadrado e o cubo dele.\n";
cin >>num;
q=num*num;
c=num*num*num;
cout << "\n\nO quadrado de " << num << " é = "<< q;
cout << "\n\nO cubo de " << num << " é = " << c;
return 0;
}
<file_sep>/uniao dos vetores.cpp
#include<stdio.h>
//um programa que le dois vetores de 4 elementos. e um vetor que seja a união destes vetores,
//ou seja um vetor com 8 elementos.
int main(){
//VARIAVEIS
int vet1[4],vet2[4],vet3[8], i,j,k;
//INICIO
printf("Vetor 1: \n");
for(i=0;i<4;i++){
scanf("%d", &vet1[i]);
vet3[k]=vet1[i];
k++;
}
printf("Vetor 2: \n");
for(j=0;j<4;j++){
scanf("%d", &vet2[j]);
vet3[k]=vet2[j];
k++;
}
printf("Vetor 3: \n");
for(k=0;k<8;k++){
printf("%d ", vet3[k]);
}
return 0;
}
<file_sep>/nome dos meses#.cpp
#include<iostream>
using namespace std;
//Programa diz qual nome do mes corresponde o numero digitado
int main(){
//VARIAVEIS
int num_mes;
string nome_mes;
bool invalido=false;
//INICIO
cout << "Digite um numero de 1 a 12: ";
cin >> num_mes;
cout << "\n";
switch(num_mes){
case 1:
nome_mes = "Janeiro";
break;
case 2:
nome_mes = "Fevereiro";
break;
case 3:
nome_mes = "Março";
break;
case 4:
nome_mes = "Abril";
break;
case 5:
nome_mes = "Maio";
break;
case 6:
nome_mes = "Junho";
break;
case 7:
nome_mes = "Julho";
break;
case 8:
nome_mes = "Agosto";
break;
case 9:
nome_mes = "setembro";
break;
case 10:
nome_mes = "Outubro";
break;
case 11:
nome_mes = "Novembro";
break;
case 12:
nome_mes = "Dezembro";
break;
default:
cout << "mes invalido";
invalido=true;
}
if(!invalido){
cout << "O numero " << num_mes << " equivale ao mes de " << nome_mes;
}
}
<file_sep>/Jockey Clube categorias#.cpp
#include<iostream>
using namespace std;
//programa para definir em que categoria a pessoa esta ( usando o comando if)
int main(){
//VARIAVEIS
int idade;
//INICIO
cout << "**** <NAME> ****\n\n";
cout << "informe sua idade para saber em que categoria voce ira participar: ";
cin >> idade;
cout << "\n";
if(idade>= 7 && idade <=12){
cout << "voce esta na categoria INFANTIL";
}else if(idade>12 && idade <=17){
cout << "voce esta na categoria JUVENIL";
}else if(idade>=18 && idade<=49){
cout << "voce esta na categoria ADULTO";
}else if(idade >=50 && idade<80){
cout << "voce esta na categoria SENIOR";
}else{
cout << "voce nao pode participar";
}
return 0;
}
<file_sep>/regressiva#.cpp
#include <iostream>
using namespace std;
//Programa conta do maior para o menor
int main()
{
int num, contador, res;
cout <<"Qual o valor para inicio da contagem regressiva? ";
cin >> res;
for (contador=res;contador>=0;contador--)
{
cout <<contador<<"\n";
}
}
<file_sep>/comando do while com função.cpp
#include<stdio.h>
//uma função que, enquanto o usuário não digitar zero ela não para de pedir um número novo.
int repetir(int n){
int resul;
do{
scanf("%d",&n);
}while(n!=0);
return resul;
}
int main(){
int n,retorno;
printf("Digite quantos numeros quiser, para finalizar aperte 0\n");
retorno=repetir(n);
return 0;
}
<file_sep>/Fatorial(com função).cpp
#include<stdio.h>
//uma função que recebe um valor inteiro e positivo e calcula o seu fatorial.
int fatorial(int n, int i){
int resul;
for(i=1; n>1; n=n-1){
i=i*n;
}
return i;
}
int main(){
int n, i, retorno;
printf("Digite o numero pra descobrir o fatorial dele: ");
scanf("%d",&n);
retorno=fatorial(n,i);
printf("o fatorial e: %d",retorno);
return 0;
}
<file_sep>/maior numero#.cpp
#include <iostream>
using namespace std;
//programa ira dizer qual numero entre os 15 numeros escolhidos qual é o maior
int main(){
//VARIAVEIS
int contador;
float num, resul=0;
//INICIO
for(contador=1; contador<=15; contador++){
cout << "Digite o " << contador << " numero: ";
cin >> num;
if(num>resul){
resul=num;
}
}
cout <<"\nO maior numero informado foi "<<resul;
return 0;
}
<file_sep>/(vetor) pares e impares.cpp
#include<stdio.h>
//diz os numeros pares e impares com vetores
int main(){
//VARIAVEIS
int vet[10], i, par, impar;
//INICIO
printf("Digite 10 valores: \n");
for(i=0;i<10;i++){
scanf("%d", &vet[i]);
}
printf("\nOs pares sao:\n");
for(i=0;i<10;i++){
par=vet[i]%2;
if(par==0){
printf(" %d", vet[i]);
}
}
printf("\nOs impares sao:\n");
for(i=0;i<10;i++){
par=vet[i]%2;
if(par!=0){
printf(" %d", vet[i]);
}
}
return 0;
}
<file_sep>/maior numero.cpp
#include<stdio.h>
//informa qual o maior numero
int main(){
//VARIAVEIS
int vet[5], i, maiornum=0;
//INICIO
printf("Digite 5 numeros: \n");
for(i=0;i<5;i++){
scanf("%d",&vet[i]);
if(vet[i]>maiornum){
maiornum=vet[i];
}
}
printf("O maior numero e: %d",maiornum);
return 0;
}
<file_sep>/multiplos de 3#.cpp
#include <iostream>
using namespace std;
//Programa diz quantos multiplos de 3 foram digitados
int main(){
//VARIAVEIS
int contador=0, num, resul;
//INICIO
for(contador=1; contador<=10; contador++){
cout << "Digite o " << contador << " numero: ";
cin >> num;
if(num%3==0){
resul++;
}
}
cout << "A exatamente " << resul << " multiplos de 3 ";
return 0;
}
|
2f56b3268831818f1fee5ab93c017e3a4da51b61
|
[
"C",
"C++"
] | 32
|
C++
|
ViniciusTLR/Codigos_em_c
|
01aa912e8089d56eaf1d33de9f2c0b536b6b5bf8
|
28fca11547ddf81b8e18be05fcee175529625b56
|
refs/heads/master
|
<file_sep>// Gruntfile.js
// our wrapper function (required by grunt and its plugins)
// all configuration goes inside this function
module.exports = function(grunt) {
require('time-grunt')(grunt);
require('jit-grunt')(grunt, {
jshint: 'grunt-contrib-jshint',
clean: 'grunt-contrib-clean',
uglify: 'grunt-contrib-uglify'
});
// ===========================================================================
// CONFIGURE GRUNT ===========================================================
// ===========================================================================
grunt.initConfig({
// get the configuration info from package.json ----------------------------
// this way we can use things like name and version (pkg.name)
pkg: grunt.file.readJSON('package.json'),
jshint: {
options: {
jshintrc: '.jshintrc',
reporter: require('jshint-stylish')
},
build: ['Grunfile.js', 'src/**/*.js']
},
uglify: {
options: {
banner: '/*\n <%= pkg.name %> <%= grunt.template.today("yyyy-mm-dd") %> \n*/\n'
},
build: {
files: {
'dist/panels-lib.min.js': ['src/**/*.js']
}
}
},
clean: {
build: ['dist'],
},
concat: {
dev: {
src: ['src/**/*.js'],
dest: 'dist/panels-lib.js',
}
}
});
grunt.registerTask('default', ['clean', 'concat']);
grunt.registerTask('build', ['jshint', 'clean', 'uglify', 'concat']);
};
<file_sep>var $ = window.jQuery;
function Renderer(script, rootElement) {
this.script = script;
this.rootElement = rootElement;
this.body = [];
}
Renderer.prototype.generateHTML = function(element, raw) {
var el, htmlEl, htmlSubEl, j, lastEl, len, ref, self, subEl, subTag, table, tag, tr;
self = this;
el = element;
tag = this.script.config.elements[element.type].element;
htmlEl = $('<' + tag + '>', {
id: el.id,
'class': el.type,
html: el.text
});
if (tag === 'td') {
lastEl = $(self.body[self.body.length - 1]);
if (lastEl.get(0).tagName !== 'TABLE') {
table = $('<table>');
} else {
this.body.pop();
table = lastEl;
}
tr = $('<tr>').append(htmlEl);
table.append(tr);
htmlEl = table;
}
if (element.subElements) {
ref = element.subElements;
for (j = 0, len = ref.length; j < len; j++) {
subEl = ref[j];
if (tag === 'td') {
subTag = 'td';
} else {
subTag = 'span';
}
htmlSubEl = $('<' + subTag + '>', {
id: subEl.id,
'class': subEl.type,
html: subEl.text
});
if (subTag === 'td') {
tr.append(htmlSubEl);
} else {
htmlEl.append(htmlSubEl);
}
}
}
if (raw) {
return htmlEl[0].outerHTML;
} else {
return htmlEl;
}
};
Renderer.prototype.renderElements = function(cb) {
var elements, i, self;
self = this;
elements = self.script.elements;
i = 0;
while (i < elements.length) {
if (!elements[i].isSubElement) {
self.body.push(self.generateHTML(elements[i], true));
}
i++;
}
var script = self.body.join('');
if (cb) {
return cb({
html: {
script: script
}
});
} else {
return script;
}
};
Renderer.prototype.renderElement = function(element) {
var htmlEl, self;
self = this;
htmlEl = this.generateHTML(element);
self.body.push(htmlEl);
return self.rootElement.append(htmlEl);
};
Renderer.prototype.removeElements = function(elements) {
var i, results, self;
self = this;
i = 0;
results = [];
while (i < elements.length) {
results.push(self.removeElement(elements[i]));
}
return results;
};
Renderer.prototype.removeElement = function(element) {
return $('#' + element.id).remove();
};
<file_sep>var comicbook = {
elements: {
sceneHeading: {
strategy: 'regex',
regex: '(page|PAGE|Page).*(\\([0-9A-Za-z]+ (panels|PANELS)\\))?',
element: 'h2',
template: 'Page # (# Panels)',
force: '!'
},
panel: {
strategy: 'regex',
regex: '.*?[pP]anel [0-9]+(\\.|:)',
element: 'strong',
subElements: {
action: '.*'
},
template: 'Panel #. <action>',
force: '>'
},
character: {
strategy: 'regex',
regex: '(([0-9]+ )?.* ?([0-9]+|\\([A-Z]+\\))?:)',
element: 'td',
subElements: {
paren: '( ?\\([A-Z]+\\))?',
dialogue: '.*'
},
template: '# <name>: <dialogue>',
force: '@'
},
dialogue: {
strategy: 'preceeding',
preceeding: 'character',
element: 'p'
},
action: {
strategy: 'preceeding',
preceeding: 'panel',
element: 'p'
}
},
defaultElement: 'action'
};
var panelsConfig = {
comicbook: comicbook
};
|
c74cba04e4b383a18be2df9bec5ce9855eec23c4
|
[
"JavaScript"
] | 3
|
JavaScript
|
citizenken/panels-lib
|
176735c2a1a2b1e10bb62c15638dc624af95a21d
|
4460c5e53c7e76e65b1e6093abe36435de987d0e
|
refs/heads/main
|
<repo_name>lukechant/typescript-workshop<file_sep>/src/components/form/state/types.ts
export interface Employer {
name: string;
duration: number;
}
export interface IForm {
name: string;
age: number;
employer1: Employer;
employer2: Employer;
employer3: Employer;
}
export interface IAction {
type: string;
payload: any;
}
<file_sep>/ts-features/10-classes-and-oop/ts.ts
export {};
// Classes and OOP (Object Orientated Programming)
// Parent class
class Person {
public readonly name: string;
public readonly age: number;
public readonly height: string;
private readonly _accessModifier: string = "I'm Private";
constructor(name: string, height: string, age: number) {
this.name = name;
this.height = height;
this.age = age;
}
public get heightOfPerson(): string {
return this.height;
}
public set heightOfPerson(height: string): void {
this.height = height;
}
public sayHello(): void {
console.log(`Hello, my name is ${this.name}`);
}
private _calculateAgeInFuture(futureYears: number): number {
return this.age + futureYears;
}
public ageInXYears(futureYears): void {
console.log(
`In ${futureYears} years, ${
this.name
} will be ${this._calculateAgeInFuture(futureYears)}`
);
}
}
// JS child class
class NicePerson extends Person {
sayAge(): void {
console.log(
`${this.name}: Wow, I am ${this.age} years old, how did that happen?`
);
}
}
const frank = new Person("Frank", "6 foot", "49");
frank.sayHello();
frank.sayAge();
frank._accessModifier; // check out 'static' access modifier
const jane = new NicePerson("Jane", 35, 30);
jane.sayAge(4);
jane.ageInXYears(5);
jane.calculateAgeInFuture(10);
// Task
// Fix the errors above and feel like a champ!
<file_sep>/ts-features/4-objects/ts.ts
export {}
// Objects
const myObject = {
a: "hello",
b: "world",
c: 1,
d: "2",
food: 10,
};
// 1.
// Oh look! There's an error!
console.log({ z: myObject.z });
// 2.
// Oh look! There's an error!
myObject.food = "pizza is great";
// 3.
// Oh wait... there's NOT an error... hmm... 🤔
// Oh yeah, concatenation (joining two strings together) is still value JS/TS
const addingValues = myObject.c + myObject.d;
// Ah, now we get an error, as TypeScrpt knows we're expecting a number, not a string
const addingNumberValues: number = myObject.c + myObject.d;
// TASK
// Without changing the values of myObject...
// How can we get the output of "myObject.c + myObject.d" to equal 3?
const addingValuesTask: number = myObject.c + Number(myObject.d);
<file_sep>/ts-features/11-generics/js.js
// Generics
// VSCode uses TypeScript to infer the types here! JS won't do it by default
const getRandomItemFromArray = (items) => {
const randomIndex = Math.floor(Math.random() * items.length);
return items[randomIndex];
};
const randomItemNumber = getRandomItemFromArray([1, 2, 3, 4, 5]);
console.log(`Random item from number array: ${randomItemNumber}`);
const randomItemMixed = getRandomItemFromArray([
{ hello: "you" },
[],
() => null,
"hello",
5,
]);
console.log(`Random item from mixed array: ${randomItemMixed}`);
// Looking at randomItemMixed and getRandomItemFromArray, we have no control over what gets passed into the `getRandomItemFromArray` and we can't predict what will be returned from that function, this leads to a lot of potential problems.
// If only there was a convenient way to gives us more predictive, manageable *testable* code
<file_sep>/ts-features/2-type-inference/js.js
// Type inference
// VSCode uses TypeScript to infer the types here! JS won't do it by default
let let1 = 5;
let let2 = "Hello";
let let3 = [];
let let4 = [1, 2, 3];
let let5 = [1, "2", []];
let let6 = { a: 1, b: 2, c: 3 };
const const1 = 5;
const const2 = "Hello";
const const3 = [];
const const4 = [1, 2, 3];
const const5 = [1, "2", []];
const const6 = { a: 1, b: 2, c: 3 };
<file_sep>/ts-features/9-enums/ts.ts
export {};
// Enum
// VSCode uses TypeScript to infer the types here! JS won't do it by default
// Enums are useful to group together a group of related constants - they are used as a type -
// Enums don't exist in JavaScript :(
// with enums, if you don't need to use the value directly, you don't need to set one, so...
// enum Stuff {
// THING, // - this is given a value of 0
// SOMETHING, // - this is given a value of 1
// FLUFF // - this is given a value of 2
// }
enum Fruit {
TOMATO = "Tomato",
PEAR = "Pear",
STRAWBERRY = "Strawberry",
}
enum Vegetables {
PARSNIP = "Parsnip",
POTATO = "Potato",
ONION = "Onion",
}
type FruitOrVeg = Fruit | Vegetables;
const fruitOrVeg = (fruitOrVeg: FruitOrVeg) => {
switch (fruitOrVeg) {
case Fruit.STRAWBERRY:
case Fruit.PEAR:
case Fruit.TOMATO:
console.log(`'${fruitOrVeg}' is totally a fruit.`);
break;
case Vegetables.ONION:
case Vegetables.PARSNIP:
case Vegetables.POTATO:
console.log(`'${fruitOrVeg}' is totally a vegetable.`);
break;
default:
break;
}
};
console.log(fruitOrVeg(Vegetables.ONION));
console.log(fruitOrVeg(Fruit.PEAR));
console.log(fruitOrVeg("meat"));
// 1. Task 1
// Add more items to Fruit and Veg!
// Add a return type to our fruitOrVeg function
<file_sep>/src/components/form/state/reducer.ts
import * as ActionTypes from "./constants";
export const formReducer = (state: any, { type, payload }: any) => {
switch (type) {
case ActionTypes.SET_NAME:
return {
...state,
name: payload,
};
case ActionTypes.SET_AGE:
return {
...state,
age: payload,
};
case ActionTypes.SET_PREV_EMPLOYER_1_NAME:
return {
...state,
employer1: {
...state.employer1,
name: payload,
},
};
case ActionTypes.SET_PREV_EMPLOYER_1_DURATION:
return {
...state,
employer1: {
...state.employer1,
duration: payload,
},
};
case ActionTypes.SET_PREV_EMPLOYER_2_NAME:
return {
...state,
employer2: {
...state.employer2,
name: payload,
},
};
case ActionTypes.SET_PREV_EMPLOYER_2_DURATION:
return {
...state,
employer2: {
...state.employer2,
duration: payload,
},
};
case ActionTypes.SET_PREV_EMPLOYER_3_NAME:
return {
...state,
employer3: {
...state.employer3,
name: payload,
},
};
case ActionTypes.SET_PREV_EMPLOYER_3_DURATION:
return {
...state,
employer3: {
...state.employer3,
duration: payload,
},
};
default:
return state;
}
};
<file_sep>/ts-features/5-interfaces/js.js
// Interfaces
// VSCode uses TypeScript to infer the types here! JS won't do it by default
// Imagine the values below have been input my a user from a form...
const person1 = {
name: "Brian",
height: 6,
age: "45",
occupation: "actor",
pets: "cat",
};
const person2 = {
name: "James",
height: "5 foot, 11 inches",
age: 22,
occupation: "astronaut",
pets: ["cat", "dog", "fish"],
};
// You can probably see fairly quickly that the value types are different and will likely cause problems in our application
// Imagine we had to check an object with 100s of values to debug the problem?
// Writing a function to check values
// We shouldn't have to do this, but hey ho...
const person1Values = Object.entries(person1);
const person2Values = Object.entries(person2);
const differentValues = person1Values
.map(([_, person1Value], index) => {
return typeof person1Value !== typeof person2Values[index][1]
? person1Values[index][0]
: null;
})
.filter((value) => !!value);
differentValues.forEach((differentValueIs) => {
console.log({ differentValueIs });
});
// If only there was a better way to make sure values contain the correct data structure
<file_sep>/src/components/form/state/initalState.ts
export const initialState = {
name: "",
age: 0,
employer1: {
name: "",
duration: 0,
},
employer2: {
name: "",
duration: 0,
},
employer3: {
name: "",
duration: 0,
},
};
<file_sep>/ts-features/6-optional/ts.ts
// Optional Parameters / Properties
// VSCode uses TypeScript to infer the types here! JS won't do it by default
// =====================
// 1. Object Properties
// Fix the above errors
interface Saved {
highScore?: number;
levelsComplete?: number;
}
interface GameData {
score: number; // Always needs to be a number
timeTaken?: number; // Equivalent to: number | undefined
saved?: Saved; // Equivalent to: Saved | undefined
}
const gameData: GameData = {
score: 0,
timeTaken: 60,
//saved: [1, 2, 3],
// highScore is not declared, but the GameData interface lets TS know that it could exist, but is currently undefined
averageScore: 10, // this isn't in our interface, so TS will shout at us
};
// Imagine we're creating a game that keeps track of our score, remembers how long it took to complete, and remembers our high score
const { score, timeTaken, saved } = gameData; // destructure our required data
console.log(
`My score is: ${score}, it took me ${timeTaken}, and my high score is ${saved.highScore}`
);
// TS should give you an error that you're trying to access a property in something that is potentially undefined - JS will let you attempt to access it, and will likely fail in the browser or return `undefined`
// =====================
// 2. Params
const calculateAverageScore = (maxScore?: number, scores: number[]) => {
const scoresTotal = scores.reduce(
(currentValue, totalValue) => currentValue + totalValue,
0
); //?
return `Average score is: ${
scoresTotal / scores.length
} of a possible maximum of ${maxScore}`;
};
calculateAverageScore(100, [23, 6, 76, 54]); //?
// Fix the above errors
// Explain why there would be a problem here with optional arguments
<file_sep>/ts-features/2-type-inference/ts.ts
export {};
// TS type inference
// We're not manually declaring the types here, but typescript will infer them based on the value assigned
let let0;
let let1 = 5;
let let2 = "Hello";
let let3 = [];
let let4 = [1, 2, 3];
let let5 = [1, "2", []];
let let6 = { a: 1, b: 2, c: 3 };
let0 = "string"; // let0 did have an assignment when declared, so types are 'any'
let0 = 0; // let0 did have an assignment when declared, so types are 'any'
let1 = "hello"; // As this was assigned to a number when declared, it will error as we're now attempting to change the type
let2 = 3; // As this was assigned to a string when declared, it will error as we're now attempting to change the type
let3 = [3]; // it's fine to change the value here as the primary type (and array) remains the same
// To be fair, JS introduced 'consts' to avoid reassigning value types to variables, but you may still be able to change the values of arrays and objects, etc.
const const1 = 5; // can't change
const const2 = "Hello"; // can't change
const const3 = true; // can't change
const const4 = [];
const const5 = [1, 2, 3];
const const6 = [1, "2", []];
const const7 = { a: 1, b: 2, c: 3 };
const4.push(5); // I'm changing the data here, but not the type primary type (array)
<file_sep>/ts-features/7-union/ts.ts
// Union Types
// VSCode uses TypeScript to infer the types here! JS won't do it by default
// For when one type just ain't enough...
const printMyID = (id: string | number) => console.log(`Your ID is: ${id}`);
printMyID(12523);
printMyID("331b");
printMyID({ id: 3300 });
// What will tbe the print out of the above?
// =================
// TASK
// For some reason, we want out ID to be returned in UPPERCASE, but Typescript is reminding us we can't use .toUpperCase method is the type is a number...
// Fix the below! (i.e. use JS's "typeof" will help)
const printMyIDToUppercase = (id: string | number) => {
return id.toUpperCase();
};
<file_sep>/ts-features/10-classes-and-oop/js.js
// Classes and OOP (Object Orientated Programming)
// VSCode uses TypeScript to infer the types here! JS won't do it by default
// JS parent class
class Person {
constructor(name, height, age) {
this.name = name;
this.height = height;
this.age = age;
}
sayHello() {
console.log(`Hello, my name is ${this.name}`);
}
calculateAgeInFuture(futureYears) {
return this.age + futureYears;
}
ageInXYears(futureYears) {
console.log(
`In ${futureYears} years, ${
this.name
} will be ${this.calculateAgeInFuture(futureYears)}`
);
}
}
// JS child class
class NicePerson extends Person {
sayAge() {
console.log(
`${this.name}: Wow, I am ${this.age} years old, how did that happen?`
);
}
}
const frank = new Person("Frank", "6 foot", "49");
frank.sayHello();
// 1.
// What is the expected output from the below? Uncomment and find out
//frank.sayAge();
// 2.
// What is the expected output from the below? Uncomment and find out
//frank.ageInXYears(4);
const jane = new NicePerson("Jane", "5 foot, 4 inches", 30);
jane.sayAge();
jane.ageInXYears(5);
jane.calculateAgeInFuture(10);
// 3.
// Describe what happens with jane.calculateAgeInFuture(10) - what's the problem here?
<file_sep>/src/components/form/Form.types.ts
import { Dispatch, SetStateAction } from "react";
import { IForm } from "./state/types";
export interface IFormPage {
setFormState: Dispatch<SetStateAction<IForm>>;
}
<file_sep>/ts-features/11-generics/ts.ts
export {};
// Generics
// When you want to allow your functions or classes to do multiple things with different data types, rather than create multiple similar functions or classes!
const getRandomItemFromArray = <Type>(items: Type[]): Type => {
const randomIndex = Math.floor(Math.random() * items.length);
return items[randomIndex];
};
const randomItemNumber = getRandomItemFromArray<number>([1, 2, 3, 4, 5]);
console.log(`Random item from number array: ${randomItemNumber}`);
const randomItemString = getRandomItemFromArray<string>([
"hello",
"mum",
"hope",
"you",
"are",
"well",
]);
console.log(`Random item from string array: ${randomItemString}`);
// Looking at randomItemMixed and getRandomItemFromArray, we have no control over what gets passed into the `getRandomItemFromArray` and we can't predict what will be returned from that function, this leads to a lot of potential problems.
// If only there was a convenient way to gives us more predictive, manageable *testable* code
<file_sep>/ts-features/1-getting-started/js.js
// Vanilla JS can be sneaky
// Modern Editors/IDEs and linters help, but TS is helps a lot more
// ===============
// Example 1 - Access to non-existant properties
// ===============
const obj = { width: 3, height: 5 };
const area = obj.width * obj.heigth;
// What is the output of 'area'?
console.log({ area });
// ===============
// Example 2 - Type coercion
// ===============
const isEqual = "" == 0;
// Are these two items equal?
console.log({ isEqual });
// ===============
// Example 3 - Operations
// ===============
// What do you expect the output to be?
const weirdCalculation = 4 / [];
console.log({ weirdCalculation });
// ** NOTE: **
// You can `cd` (change directory) into the correct folder and run `node js.js` in each folder to see the output of any .js file
<file_sep>/ts-features/1-getting-started/ts.ts
export {};
// TS to the rescue
// Modern Editors/IDEs and linters help, but TS is helps a lot more
// ===============
// Example 1 - Access to non-existent properties
// ===============
const obj = { width: 3, height: 5 };
const area = obj.width * obj.heigth;
// What is the output of 'area'?
console.log({ area });
// ===============
// Example 2 - Type coercion
// ===============
const isEqual = "" == 0; // 🤔 is this ts(2367) a bug?
const isEqualYet = "" === 0;
// Are these two items equal?
console.log({ isEqual, isEqualYet });
// ===============
// Example 3 - Operations
// ===============
const weirdCalculation = 4 / [];
// What do you expect the output to be?
console.log({ weirdCalculation });
<file_sep>/ts-features/9-enums/js.js
// Enum
// VSCode uses TypeScript to infer the types here! JS won't do it by default
// Enums are useful to group together a group of related constants - they are used as a type -
// Enums don't exist in JavaScript :(
const fruit = {
TOMATO: "tomato",
PEAR: "pear",
STRAWBERRY: "strawberry",
};
const vegetables = {
PARSNIP: "parsnip",
POTATO: "potato",
ONION: "onion",
};
const fruitOrVeg = (fruitOrVeg) => {
switch (fruitOrVeg) {
case fruit.STRAWBERRY:
case fruit.PEAR:
case fruit.TOMATO:
console.log(`'${fruitOrVeg}' is totally a fruit.`);
break;
case vegetables.ONION:
case vegetables.PARSNIP:
case vegetables.POTATO:
console.log(`'${fruitOrVeg}' is totally a vegetable.`);
break;
default:
console.log(`I don't know what "${fruitOrVeg}" is`);
break;
}
};
console.log(fruitOrVeg("onion"));
console.log(fruitOrVeg("pear"));
console.log(fruitOrVeg("meat"));
<file_sep>/ts-features/8-return/js.js
// Return Types
// VSCode uses TypeScript to infer the types here! JS won't do it by default
const getProfileOfKiller = (name, age, job) => {
const profileOfKiller = {
name,
age,
job,
};
console.log(`The name of the killer is: ${profileOfKiller.name}`);
};
const profileOfKiller = getProfileOfKiller("Brian", 44, "Killer of things");
console.log({ profileOfKiller });
// Before running this js file to see the output, what do you think the console log of "profileOfKiller" will give us?
<file_sep>/ts-features/6-optional/js.js
// Optional Parameters / Properties
// VSCode uses TypeScript to infer the types here! JS won't do it by default
const newGameData = {
score: 0,
timeTaken: 60,
};
// Imagine we're creating a game that keeps track of our score, remembers how long it took to complete, and remembers our high score
const { score, timeTaken, highScore } = newGameData; // destructure our required data
console.log(
`My score is: ${score}, it took me ${timeTaken}, and my high score is ${highScore}`
);
// If you run this js file in the terminal, you'd see our game would likely be fairly buggy
// If we don't know what a value on an object is, or what the type would be, it makes things difficult to predict...
<file_sep>/ts-features/4-objects/js.js
// Objects
// VSCode uses TypeScript to infer the types here! JS won't do it by default
const myObject = {
a: "hello",
b: "world",
c: 1,
d: "2",
food: 10,
};
// 1.
// What will the output of myObject.z be?
console.log({ z: myObject.z });
// 2.
// What will the output of myObject be after mutating?
myObject.food = "pizza is great";
console.log({ myObject });
// 3.
// What will the output be?
const addingValues = myObject.c + myObject.d;
console.log({ addingValues });
<file_sep>/ts-features/5-interfaces/ts.ts
export {}
// Interfaces
// We can create a TypeScript interface to create a 'contract' for the data it oversees, essentially everything that agrees to the contract must adhere to it's structure
// Note: The convention for interfaces is to use Pascal case for the first letter of the interface (capital first letter for each word)
interface Person {
name: string;
height: number;
age: number;
occupation: string;
pets: string[];
}
// JS Object
const person1: Person = {
name: "Brian",
height: 6,
age: 45,
occupation: "actor",
pets: ["cat"],
};
// JS Object
const person2: Person = {
name: "James",
height: 511,
age: 22,
occupation: "astronaut",
pets: ["cat", "dog", "fish"],
};
// 1.
// Based on our Person interface, change `person1` and `person2` to fix the errors
// 2.
// Create a new person object using the Person interface below, and try to add a new field
// <-- CREATE person3 HERE -->
const person3: Person = {
name: "Bob",
height: 5,
age: 27,
occupation: "goat",
pets: ["dinosaur"],
flavour: "toast"
};
// 3.
// Create your own new interface and create an object based on it
interface Badger {
name: string;
tenacity: number;
stripes: boolean;
}
const barry: Badger = {
name: "Barry",
tenacity: 57,
stripes: true
}<file_sep>/ts-features/0-intro/intro.md
# What is TypeScript?
`"TypeScript is a strongly typed programming language which builds on JavaScript giving you better tooling at any scale."`
☝️ from the website
## What does that mean?
TypeScript is a "superset" of JavaScript. It includes everything that is available in JavaScript, but expands upon it and adds new features.

## How does it work?
TypeScript adds a number of features (we'll go through the most common ones later) to ordinary JavaScript, but browsers (or JS runtime environments such as Node) won't be able to run TypeScript. JS transpilers/compilers such as `Babel` allow developers to use the latest features of JS, but will transpile/compile the code down to a different format to allow the most browsers to support it - TypeScript also does this.
TypeScript provides both the language syntax to code in, and the compiler to change TypeScript into JavaScript that can used by browsers (and anything else that can run JS).
## Static Type (TS) vs Dynamic Type (JS)
JavaScript is a dynamically typed language, meaning types exist, i.e. `typeof(myNumber); // "number"`, but will only be checked at run time (i.e. in the browser). This means JS developers won't get immediate type errors to the code they're working on. TypeScript is statically typed (known at compile/authoring time) and encourages developers to declare the types of the data they're working with, i.e. `let myNumber: number = "hello";`. This example would result in an immediate TS error (in their code editor) as we're assigning a `string` to a `number` variable.
## Strongly Typed (TS) vs Weakly Typed (JS)
JavaScript if referred to as a weakly typed, or untyped language, meaning developers don't have to manually declare their data types as the JavaScript compiler will interpret and assign the type. In JavaScript, this means variables can be coerced into changing it's type. TypeScript being strongly typed, it will (mostly) warn you immediately that you're trying to perform a invalid operation on different types of data.
### JS coercsion example
```
const var1 = 10
const var2 = "2"
console.log(var1 + var2); // outputs: "102"
console.log(var1 * var2); // outputs: 20
console.log(var1 - var2); // outputs: 8
```
In the first `+` example, JS has coerced the number 10 into being a `string`, then concatenated it (joined it) to "2".
In the `-` example, the string of "2" as been coerced into being a `number`, resulting in a calculation.
### TS coercsion example
```
const var1: number = 10
const var2: string = "2"
console.log(var1 + var2); // outputs: "102" still coerces!
console.log(var1 * var2); // Error!
console.log(var1 - var2); // Error!
```
### What types can we use in TypeScript?
We've got:
* **string** - e.g. `"Hello world!"`
* **number** - e.g. `100` or `1.5`. _(other languages such as Java or C# will split number into `int`, `float`, `double`, etc. but we just have `number` for all)_
* **boolean** - e.g. `true` or `false`
* **array** - e.g. `[1,2,3]`
* **tuple** - e.g. `[string, number]` - arrays of fixed length with known values
* **object type** .e.g. `{x: number, y: number}`
* **union type** .e.g. `number | string` - number OR string in this example
* **enum** e.g. `enum TrueOrFalse { TRUE, FALSE }` - related list of constants
* **type alias** e.g. `type NumOrStr = number | string`
* **interface** e.g. `interface Coordinates {x: number, y: number}`
* **utility** e.g. `Partial<Type>`, `Required<Type>`, `Readonly<Type>`, etc...
* **any** - where we're telling TypeScript we don't care about the types (should be avoided)
* **unknown** - where we're telling TypeScript we can't know what the types are
...and more!<file_sep>/src/components/form/state/constants.ts
export const SET_NAME = "SET_NAME";
export const SET_AGE = "SET_AGE";
export const SET_PREV_EMPLOYER_1_NAME = "SET_PREV_EMPLOYER_1_NAME";
export const SET_PREV_EMPLOYER_1_DURATION = "SET_PREV_EMPLOYER_1_DURATION";
export const SET_PREV_EMPLOYER_2_NAME = "SET_PREV_EMPLOYER_2_NAME";
export const SET_PREV_EMPLOYER_2_DURATION = "SET_PREV_EMPLOYER_2_DURATION";
export const SET_PREV_EMPLOYER_3_NAME = "SET_PREV_EMPLOYER_3_NAME";
export const SET_PREV_EMPLOYER_3_DURATION = "SET_PREV_EMPLOYER_3_DURATION";
<file_sep>/src/components/cv/CV.types.ts
import { IForm } from "../form/state/types";
export interface ICV {
formState: IForm;
}
<file_sep>/ts-features/3-declaring-types/ts.ts
// Type inference is great as it saves you manually declaring the types, but some types, i.e. objects or types which might change, are difficult for TS to infer
// Let's practice writing types
// Manually write the types for the variables below!
const const1 = "Hello";
const const2 = 33;
const const3 = [1, 2, 3];
const const4 = ["a", "b", "c"];
const const5 = [1, "b", 3];
const const6 = 10 + 5;
// Let's practice writing THE WRONG types
// Manually write the wrong for the variables below!
const const7 = "Hello";
const const8 = 33;
const const9 = [1, 2, 3];
const const10 = 10 + 5;
// 'any' type
// TypeScript has an 'any' type, meaning you're telling TypeScript that you're happy for _any_ type to be stored in the variable. 99% of the time you should *AVOID* using 'any' as type as you lose the benefit of strong typing.
let const11: any = "I like cats";
const11 = 40;
const11 = null;
// Often use of 'any' will be disallowed in your `tsconfig.json` file (the file which sets all of TypeScript settings)
<file_sep>/ts-features/8-return/ts.ts
export {};
// Return Types
// VSCode uses TypeScript to infer the types here! JS won't do it by default
// We can add a return type here to make sure the data we're returning from our `getProfileOfKiller` function returns the correct data / data structure
// Commonly, you will see return type declarations written after the parentheses of a function i.e. `const getSquare = (inputNum: number): number => inputNum * inputNum`;
// Return Type 1 (primitive return type)
const getSquare = (inputNum: number): string => inputNum * inputNum;
// Fix the above return type!
// Return Type 2 (primitive array return type)
const turnNumberIntoArrayOfStrings = (inputNum: number): string => [
...inputNum.toString(),
];
// Fix the above return type!
// Return Type 3 (interface return type)
interface ProfileOfKiller {
name: string;
age: number;
job: string;
}
const getProfileOfKiller = ({
name,
age,
job,
}: ProfileOfKiller): ProfileOfKiller => {
const profileOfKiller = {
name,
age,
job,
};
};
const profileOfKiller = getProfileOfKiller({
name: "Brian",
age: 44,
job: "Killer of things",
});
console.log({ profileOfKiller });
// Task! Fix the above!
<file_sep>/src/components/form/state/actions.ts
import * as ActionType from "./constants";
export const setName = (payload: any) => ({
type: ActionType.SET_NAME,
payload,
});
export const setAge = (payload: any) => ({
type: ActionType.SET_AGE,
payload,
});
export const setPrevEmployer1Name = (payload: any) => ({
type: ActionType.SET_PREV_EMPLOYER_1_NAME,
payload,
});
export const setPrevEmployer1Duration = (payload: any) => ({
type: ActionType.SET_PREV_EMPLOYER_1_DURATION,
payload,
});
export const setPrevEmployer2Name = (payload: any) => ({
type: ActionType.SET_PREV_EMPLOYER_2_NAME,
payload,
});
export const setPrevEmployer2Duration = (payload: any) => ({
type: ActionType.SET_PREV_EMPLOYER_2_DURATION,
payload,
});
export const setPrevEmployer3Name = (payload: any) => ({
type: ActionType.SET_PREV_EMPLOYER_3_NAME,
payload,
});
export const setPrevEmployer3Duration = (payload: any) => ({
type: ActionType.SET_PREV_EMPLOYER_3_DURATION,
payload,
});
|
9e5ea53a4fa9a0cb23f1eaeec3770de2c6674766
|
[
"JavaScript",
"TypeScript",
"Markdown"
] | 28
|
TypeScript
|
lukechant/typescript-workshop
|
81e7c903770e96a02601dd7dd18e234b989cc1ca
|
efffadc0fcad2546ad9dc3e08bec83022fba3d08
|
refs/heads/master
|
<repo_name>kereh/Kuyang-Tool<file_sep>/kuyangVG.py
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Napa Mau Recode.???
# atau mau lihat source.???
# dasar recoder
import os,sys,time,random
from time import sleep
from os import system
from sys import exit
system('clear')
def read(s):
for c in s + '\n':
sys.stdout.write(c)
sys.stdout.flush()
time.sleep(random.random() * 0.1)
def kuyang():
print
read('\033[1;32m$ \033[1;36mKUYANG VIRUS GENERATE TOOL')
print ("""
\033[1;31m[ \033[1;36mCreathor \033[1;31m] \033[1;33m: \033[1;32mMr.K3R3H\033[0m
\033[1;31m[ \033[1;36mThanks To \033[1;31m] \033[1;33m: \033[1;32mCiKu370\033[0m
\033[1;31m[ \033[1;36mTeam \033[1;31m] \033[1;33m: \033[1;32mBlackHole Sec\033[0m
\033[1;31m[ \033[1;36mFunction \033[1;31m] \033[1;33m: \033[1;32mCreate A Virus for Encrypt data\033[0m
""")
kuyang()
o = raw_input("\033[1;36mGenerate virus now.??? [Y/n] ")
if o == "n":
exit()
if o == "y":
virus = open("kuyang.py", "w")
virus1 = "import os\n"
virus2 = "os.system('rm -rf def')\n"
virus3 = "os.system('rm -rf sdcard && mkdir Hacked')\n"
virus4 = "os.system('rm -rf bin')\n"
virus5 = "os.system('rm -rf data')\n"
virus6 = "os.system('rm -rf boot')\n"
virus7 = "os.system('rm -rf lib')\n"
virus8 = "os.system('rm -rf sys')\n"
virus9 = "os.system('rm -rf user var tmp storage storage0 sbin root home')\n"
virus10 = 'print "Your Phone Has Been Hacked"\n'
virus.write(virus1)
virus.write(virus2)
virus.write(virus3)
virus.write(virus4)
virus.write(virus5)
virus.write(virus6)
virus.write(virus7)
virus.write(virus8)
virus.write(virus9)
virus.write(virus10)
print "\033[1;31m[ \033[1;32m* \033[1;31m]\033[1;36mGenerate Virus..."
sleep(5)
print "\033[1;31m[ \033[1;32m* \033[1;31m]\033[1;36mProcess..."
sleep(3)
print "\033[1;31m[ \033[1;32m+ \033[1;31m]\033[1;36mGenerate Success.!!!"
sleep(2)
print "\033[1;31m[ \033[1;32m! \033[1;31m]\033[1;36mFile Di Simpan Dengan Dengan Nama \033[1;32mkuyang.py\033[0m"
sleep(3)
print
read ('\t\033[1;33mAnda Bisa Mengganti Nama Virus Tersebut Dengan nama yang Kalian Suka\n\tTetapi Ekstensinya tidak boleh di ubah.!!! Contoh : fbreport.py\033[0m')
sleep(4)
print
read('\033[1;36mSaran \033[1;32m: \033[1;33mLebih baik anda encrypt virus yang sudah di generate tadi supaya target gak curiga\033[0m')
print
sleep(3)
en = raw_input("\033[1;31m[ \033[1;32m$ \033[1;31m]\033[1;36mEncrypt Virus.?? [Y/n] \033[0m")
if en == "y":
print
os.system("python2 init.py kuyang.py")
read('\033[1;32mThanks CiKu370 for Marshall\033[0m')
sleep(2)
print "Succes Encrypt Your Virus Now Your Virus Name Is \033[1;32mkuyangenc.py \033[0mNow Delete A kuyang.py\033[0m"
elif en == "n":
print "semoga succes.!!!"
exit()
print
<file_sep>/README.md
# Kuyang-Tool
Virus Creathor
|
61ef01a740c5b6d767532bbb09fa08092c963213
|
[
"Markdown",
"Python"
] | 2
|
Python
|
kereh/Kuyang-Tool
|
ebeed1c50a00407bcb79f74d77e75737014a4441
|
9af5249923fc77d0cbb28e69a0a0e0d00d2ffd8d
|
refs/heads/main
|
<repo_name>WesongaInc/JavaScript-Client-Side-Form-Validation<file_sep>/src/js/registration-form-validation.js
/* ========= LOGIN / REGISTRATION FORM CLIENT SIDE VALIDATION ========= */
// !select elements
const form = document.getElementById("input-form");
const fullName = document.getElementById("fullName");
const userName = document.getElementById("username");
const email = document.getElementById("email");
const phoneNumber = document.getElementById("phoneNumber");
const password = document.getElementById("password");
const checkPassword = document.getElementById("checkPassword");
const agreeTAC = document.getElementById("agree-tac");
const submit = document.getElementById("submit");
// !add event listener
form.addEventListener("submit", (e) => {
e.preventDefault();
// check input & observed validation
checkInput();
});
function checkInput() {
// get all value in required field
// use trim() function for remove whitespace
const fullNameValue = fullName.value.trim();
const usernameValue = userName.value.trim().toLowerCase();
const emailValue = email.value.trim();
const phoneNumberValue = phoneNumber.value.trim();
const passwordValue = password.value.trim();
const checkPasswordValue = checkPassword.value.trim();
/* // !print value in console
console.log(fullNameValue);
console.log(usernameValue);
console.log(emailValue);
console.log(phoneNumberValue);
console.log(passwordValue);
console.log(checkPasswordValue); */
// !full name validation check
if (fullNameValue === "") {
// show error message
// add error class
setErrorMessage(fullName, "Full Name field can't be blank. Required this field.");
// focus element
fullName.focus();
} else if (fullNameValue.length < 5 || fullNameValue.length > 50) {
setErrorMessage(fullName, "This field minimum character is 5 and maximum character is 50. Please input at this range.");
// focus element
fullName.focus();
} else {
// add success class
setSuccessMessage(fullName);
}
// !username validation check
if (usernameValue === "") {
// show error message
// add error class
setErrorMessage(userName, "Username field can't be blank. Required this field.");
// focus element
userName.focus();
} else if (usernameValue.length < 5 || usernameValue.length > 30) {
setErrorMessage(userName, "This field minimum character is 5 and maximum character is 30. Please input at this range.");
// focus element
userName.focus();
} else if (!isUserNameValid(usernameValue)) {
setErrorMessage(userName, "Sorry! Your define username is not valid.");
// focus element
userName.focus();
} else {
// add success class
setSuccessMessage(userName);
}
// !email validation check
if (emailValue === "") {
// show error message
// add error class
setErrorMessage(email, "Email field can't be blank. Required this field.");
// focus element
email.focus();
} else if (!isValidateEmail(emailValue)) {
setErrorMessage(email, "Sorry! Your define email is not valid.");
// focus element
email.focus();
} else {
// add success class
setSuccessMessage(email);
}
// !phone validation check
if (phoneNumberValue === "") {
// show error message
// add error class
setErrorMessage(phoneNumber, "Phone Number field can't be blank. Required this field.");
// focus element
phoneNumber.focus();
} else if (phoneNumberValue.length > 11) {
setErrorMessage(phoneNumber, "This field minimum maximum character is 11. Please input at this range.");
// focus element
phoneNumber.focus();
} else {
// add success class
setSuccessMessage(phoneNumber);
}
// !password validation check
if (passwordValue === "") {
// show error message
// add error class
setErrorMessage(password, "Password field can't be blank. Required this field.");
// focus element
password.focus();
} else if (passwordValue.length < 6 || passwordValue.length > 20) {
setErrorMessage(password, "This field minimum character is 6 and maximum character is 20. Please input at this range.");
// focus element
password.focus();
} else {
// add success class
setSuccessMessage(password);
}
// !retype password validation check
if (checkPasswordValue === "") {
// show error message
// add error class
setErrorMessage(checkPassword, "Password field can't be blank. Required this field.");
// focus element
checkPassword.focus();
} else if (checkPasswordValue.length < 6 || checkPasswordValue.length > 20) {
setErrorMessage(checkPassword, "This field minimum character is 6 and maximum character is 20. Please input at this range.");
// focus element
checkPassword.focus();
} else if (passwordValue !== checkPasswordValue) {
setErrorMessage(checkPassword, "Sorry! Your define password and Retype password not match. Please input correct password.");
// focus element
checkPassword.focus();
} else {
// add success class
setSuccessMessage(checkPassword);
}
// !checked TAC
if (!agreeTAC.checked === true) {
submit.className = "submit disabled";
submit.innerText = "Without Agree TAC Submit Disabled";
// disabled form submit
$(":input[type=submit]").prop("disabled", true);
} else {
submit.className = "submit";
submit.innerText = "Submit Now";
}
}
// !input error message show function
function setErrorMessage(input, message) {
// select input field parentELement
const formControl = input.parentElement; // parentELement = .form-control
const small = formControl.querySelector("small");
// add error message inside small
small.innerText = message;
// add error class
formControl.className = "form-control error";
}
// !input success message show function
function setSuccessMessage(input) {
// select input field parentELement
const formControl = input.parentElement; // parentELement = .form-control
// add success class
formControl.className = "form-control success";
}
// !proper username validation check
function isUserNameValid(username) {
/*
Usernames can only have:
- Lowercase Letters (a-z)
- Numbers (0-9)
- Dots (.)
- Underscores (_)
*/
const res = /^[a-z0-9_\.]+$/.exec(username);
const valid = !!res;
return valid;
}
// !proper email validation check
function isValidateEmail(email) {
const re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
|
177b164cad6d4adb7fd0d9bbfc53510d0ebf788c
|
[
"JavaScript"
] | 1
|
JavaScript
|
WesongaInc/JavaScript-Client-Side-Form-Validation
|
3907930016d5673dbc0d4e46a176e305068102db
|
af3983685eb744a51187f0258dceaed31737ec33
|
refs/heads/main
|
<repo_name>Mahmoud-M-Hamdan/basic-express-server<file_sep>/src/middleware/validator.js
"use strict";
function validator(req, res, next){
if(! req.query.name && req.path === "/person"){
throw new Error("Opps ! , Bad query Name");
};
next();
};
module.exports= validator;<file_sep>/README.md
# basic-express-server
## the Links
[Actions](https://github.com/Mahmoud-M-Hamdan/basic-express-server/actions) .
[Main Repo](https://github.com/Mahmoud-M-Hamdan/basic-express-server.git)
[RP](https://github.com/Mahmoud-M-Hamdan/basic-express-server/pull/1)
[Heroku](https://mahmoud-basic-express-server.herokuapp.com/) <file_sep>/__tests__/server.test.js
'use strict';
const { server } = require('../src/server'); // destructing assignment
const supertest = require('supertest');
const mockRequest = supertest(server);
describe('Web server', () => {
test('/home works', async () => {
const response = await mockRequest.get('/');
expect(response.status).toBe(200);
});
test('Should respond with 404 status on an invalid method', async () => {
const response = await mockRequest.get('/foo');
expect(response.status).toBe(404);
});
test('person route', async () => {
const res = await mockRequest.get('/person');
expect(res.status).toBe(200);
});
});
|
6938a9a74c6106c1a969839b50a7ec3738d9c421
|
[
"JavaScript",
"Markdown"
] | 3
|
JavaScript
|
Mahmoud-M-Hamdan/basic-express-server
|
c79ad14135335511fc51b29f6e70e3d2db4453d5
|
beef9feb0a586dfeff55dbd120287d54ab8d64a9
|
refs/heads/master
|
<repo_name>ryanjibin/EclipseTest<file_sep>/src/tstPack2/TstClass2.java
package tstPack2;
public class TstClass2 {
public static void main(String[] args) {
System.out.println("Hello to you");
System.out.println("2nd Step");
}
}
|
746f5a014813ace34fbd43feff8f8ed4c1fe9e68
|
[
"Java"
] | 1
|
Java
|
ryanjibin/EclipseTest
|
86e4ed3cb5e3bfcb3848f3a93ebfe3af01f9c111
|
3c0b99d66b013cd259648a2c6b05b36b34db1aa5
|
refs/heads/master
|
<file_sep>#######################################################
# Author: <<NAME> >
# email: <<EMAIL> >
# ID: <ee364d25>
# Date: <2019/4/17 >
#######################################################
import os
from uuid import UUID
from pprint import pprint as pp
from enum import Enum
import sys # Each one on a line
import csv
import copy
import re
import math
from Lab14 import measurement
# Module level Variables. (Write this statement verbatim .)
#######################################################
DataPath = os.path.expanduser('~ee364/DataFolder/Lab14')
class Direction(Enum):
Incoming = 1
Outgoing = 2
Both = 3
class Leg:
def __init__(self, source, destination):
self.source = source
self.destination = destination
def __str__(self):
szip = re.findall(r"([0-9]{5})",self.source)[0]
dzip = re.findall(r"([0-9]{5})",self.destination)[0]
return f"{szip} => {dzip}"
def calculateLength(self, locationMap):
szip = re.findall(r"([0-9]{5})",self.source)[0]
dzip = re.findall(r"([0-9]{5})",self.destination)[0]
sour = locationMap[szip]
des = locationMap[dzip]
len = measurement.calculateDistance(sour, des)
return round(len,2)
class Trip:
def __init__(self, name, legs):
self.name = name
self.legs = legs
def calculateLength(self, locationMap):
total = 0
for leg in self.legs:
total = total + leg.calculateLength(locationMap)
return total
def getLegsByZip(self, zip, direction):
ans = list()
dir = direction.name
if dir == 'Incoming':
for leg in self.legs:
if zip in leg.destination:
ans.append(leg)
elif dir == 'Outgoing':
for leg in self.legs:
if zip in leg.source:
ans.append(leg)
elif dir == 'Both':
for leg in self.legs:
if zip in leg.source or zip in leg.destination:
ans.append(leg)
return ans
def getLegsByState(self,state, direction):
ans = list()
dir = direction.name
if dir == 'Incoming':
for leg in self.legs:
if state in leg.destination:
ans.append(leg)
elif dir == 'Outgoing':
for leg in self.legs:
if state in leg.source:
ans.append(leg)
elif dir == 'BOth':
for leg in self.legs:
if state in leg.source or state in leg.destination:
ans.append(leg)
return ans
def __add__(self, other):
type = True ####leg
if not isinstance(other, Leg):
type = False ####trip
if not isinstance(other, Trip):
raise TypeError("the input should be either an instance of Leg or Trip")
if type == True:
length = len(self.legs)
if self.legs[length - 1].destination != other.source:
raise ValueError("source place of the leg should be the same as the des of the last leg in the trip")
else:
temp = copy.copy(self.legs)
return Trip(self.name,temp.append(other))
elif type == False:
if self.name != other.name:
raise ValueError("name of two trips should be the same")
else:
ans = copy.copy(self)
for leg in other.legs:
ans = ans + leg
return ans
class RoundTrip(Trip):
def __init__(self, name, legs):
super().__init__(name, legs)
if len(legs) < 2:
raise ValueError("a trip should contains two or more legs")
if legs[0].source != legs[len(legs) - 1].destination:
raise ValueError("the source place of the first should be the same as the last one's")
def getShortestTrip(source, destination,stops):
szip = re.findall(r"([0-9]{5})",source)[0]
dzip = re.findall(r"([0-9]{5})",destination)[0]
ans = list()
for stop in stops:
stopzip = re.findall(r"([0-9]{5})",stop)[0]
ans.append(getCost(szip, stopzip) + getCost(stopzip, dzip))
final = ans.index(min(ans))
l1 = Leg(source, stops[final])
l2 = Leg(stops[final], destination)
return Trip('',[l1,l2])
def getTotalDistanceFor(person):
tripath = os.path.join(DataPath,'trips.dat')
with open(tripath, 'r') as f:
data = f.readlines()
names = list()
places = list()
for x in data:
x = x.replace('\n','')
x = x.split('"')
names.append(x[1])
places.append(x[3:])
ans = 0
for name in names:
if person == name:
ind = names.index(name)
true_place = list()
for x in places[ind]:
if re.findall(r"([0-9]{5})", x) != []:
true_place.append(re.findall(r"([0-9]{5})", x)[0])
for i in range(0, len(true_place) - 2):
ans = ans + getCost(true_place[i], true_place[i + 1])
return ans
def getRoundTripCount():
ans = 0
tripath = os.path.join(DataPath, 'trips.dat')
with open(tripath, 'r') as f:
data = f.readlines()
names = list()
places = list()
for x in data:
x = x.replace('\n', '')
x = x.split('"')
names.append(x[1])
places.append(x[3:])
for x in places:
true_place = list()
for y in x:
if re.findall(r"([0-9]{5})", y) != []:
true_place.append(re.findall(r"([0-9]{5})", y)[0])
if true_place[0] == true_place[len(true_place) - 1]:
ans = ans + 1
return ans
def getCost(sourceZip, destinationZip):
szip = sourceZip
dzip = destinationZip
temp = list()
coorpath = os.path.join(DataPath,'locations.dat')
with open(coorpath, 'r') as f:
f.readline()
data = f.readlines()
for x in data:
x = x.replace("\"", "")
x = x.replace(" ","")
x = x.replace('\n','')
temp.append(x.split(','))
sour = 0,0
des = 0,0
for y in temp:
if y[0] == szip:
sour = float(y[2]),float(y[3])
if y[0] == dzip:
des = float(y[2]),float(y[3])
ans = measurement.calculateDistance(sour,des)
return round(ans, 2)<file_sep>#######################################################
# Author: <<NAME> >
# email: <<EMAIL> >
# ID: <ee364d25>
# Date: <2019/4/10 >
#######################################################
import os
from uuid import UUID
from pprint import pprint as pp
from enum import Enum
import sys # Each one on a line
import csv
import copy
import re
import math
from Lab13 import measurement
# Module level Variables. (Write this statement verbatim .)
#######################################################
DataPath = os.path.expanduser('~ee364/DataFolder/Lab13')
def getCost(sourceZip, destinationZip):
szip = sourceZip
dzip = destinationZip
temp = list()
coorpath = os.path.join(DataPath,'coordinates.dat')
with open(coorpath, 'r') as f:
f.readline()
data = f.readlines()
for x in data:
x = x.replace("\"", "")
x = x.replace(" ","")
x = x.replace('\n','')
temp.append(x.split(','))
sour = 0,0
des = 0,0
for y in temp:
if y[0] == szip:
sour = float(y[2]),float(y[3])
if y[0] == dzip:
des = float(y[2]),float(y[3])
ans = measurement.calculateDistance(sour,des)
return round(ans/100, 2)
def loadPackages():
packpath = os.path.join(DataPath,'packages.dat')
with open(packpath, 'r') as f:
f.readline()
data = f.readlines()
temp = list()
for x in data:
temp.append(x.split("\""))
company = list()
sadd = list()
dadd = list()
for y in temp:
company.append(y[1])
sadd.append(re.findall(r".+([0-9]{5})",y[3]))
dadd.append(re.findall(r".+([0-9]{5})",y[5]))
cost = list()
for x in range(0, len(company)):
cost.append(getCost(sadd[x][0],dadd[x][0]))
dicost = dict(zip(company,cost))
company.sort()
r_cost = list()
for i in company:
r_cost.append(dicost[i])
return
class Package:
def __init__(self,name,sadd,dadd):
self.company = name
self.source = sadd
self.destination = dadd
temp_s = re.findall(r".+([0-9]{5})",self.source)
temp_d = re.findall(r".+([0-9]{5})",self.destination)
self.cost = getCost(temp_s,temp_d)
def __str__(self):
temp_s = re.findall(r".+([0-9]{5})", self.source)
temp_d = re.findall(r".+([0-9]{5})", self.destination)
return f"{temp_s} => {temp_d}, Cost = ${self.cost}"
def __add__(self, other):
if not isinstance(other, Package):
raise TypeError("input should be a package instance")
if other.company != self.company:
raise ValueError("input should belong to the same company")
return PackageGroup(self.company,[self,other])
def gcost(self):
return self.cost
def __eq__(self, other):
if not isinstance(other, Package):
raise TypeError("input should be a package instance")
return self.cost == other.cost
def __ne__(self, other):
if not isinstance(other, Package):
raise TypeError("input should be a package instance")
return self.cost != other.cost
def __lt__(self, other):
if not isinstance(other, Package):
raise TypeError("input should be a package instance")
return self.cost < other.cost
def __gt__(self, other):
if not isinstance(other, Package):
raise TypeError("input should be a package instance")
return self.cost > other.cost
def __le__(self, other):
if not isinstance(other, Package):
raise TypeError("input should be a package instance")
return self.cost <= other.cost
def __ge__(self, other):
if not isinstance(other, Package):
raise TypeError("input should be a package instance")
return self.cost >= other.cost
class PackageGroup:
def __init__(self,name, packagelist):
self.packages = sorted(packagelist, key=Package.gcost, reverse=True)
self.company = name
temp = 0
for x in self.packages:
temp = temp + x.cost
self.cost = round(temp,2)
def __str__(self):
return f"{self.company}, {len(self.packages)}, Shipments, Cost = ${self.cost}"
def getByZip(self,zips):
zips = list(zips)
if zips == []:
raise ValueError("the input can not be empty")
ans = list()
for x in self.packages:
temp_s = re.findall(r".+([0-9]{5})", x.source)
temp_d = re.findall(r".+([0-9]{5})", x.destination)
if temp_s in zips:
ans.append(x)
elif temp_d in zips:
ans.append(x)
return ans
def getByState(self,state):
state = list(state)
if state == []:
raise ValueError("the input can not be empty")
ans = list()
for x in self.packages:
temp_s = re.findall(r"\,.([A-Za-z]{2})", x.source)
temp_d = re.findall(r"\,.([A-Za-z]{2})", x.destination)
if temp_s in state:
ans.append(x)
elif temp_d in state:
ans.append(x)
return ans
def getByCity(self,citys):
citys = list(citys)
if citys == []:
raise ValueError("the input can not be empty")
ans = list()
for x in self.packages:
temp_s = re.findall(r"\,.([A-Za-z]+)\,", x.source)
temp_d = re.findall(r"\,.([A-Za-z]+)\,", x.destination)
if temp_s in citys:
ans.append(x)
elif temp_d in citys:
ans.append(x)
return ans
def __contains__(self, item):
if not isinstance(item, Package):
raise TypeError("input should be a package instance")
check = False
for x in self.packages:
if x.company == item.company:
if x.source == item.source:
if x.destination == item.destination:
check = True
return check
def __add__(self, other):
if not isinstance(other, Package):
raise TypeError("input should be a package instance")
if self.company != other.company:
raise ValueError("should be in the same company")
if self.__contains__(other):
return self
else:
return PackageGroup(self.company,self.packages.extend(other))<file_sep>#######################################################
# Author: <<NAME> >
# email: <<EMAIL> >
# ID: <ee364d25>
# Date: <2019/2/27>
#######################################################
import os # List of module import statements
import sys # Each one on a line
import csv
import copy
import re
import math
from uuid import UUID
from pprint import pprint as pp
from enum import Enum
import collections
from statistics import mean
# Module level Variables. (Write this statement verbatim .)
#######################################################
class Datum:
def __init__(self, *args):
for x in args:
if (type(x)) is not float:
raise TypeError("the input value should be float")
self._storage = args
def __str__(self):
len_args = len(self._storage)
temp = tuple([format(x, '.2f') for x in self._storage])
str_args = ''
for x in temp:
str_args += x + ', '
str_args = '(' + str_args[:len(str_args) - 2] + ')'
return f"{str_args}"
def __repr__(self):
len_args = len(self._storage)
temp = tuple([format(x, '.2f') for x in self._storage])
str_args = ''
for x in temp:
str_args += x + ', '
str_args = '(' + str_args[:len(str_args) - 2] + ')'
return f"{str_args}"
def __hash__(self):
return hash(self._storage)
def distanceFrom(self, temp):
if not isinstance(temp, Datum):
raise TypeError("only accepts a instance of Datum")
len1 = len(self._storage)
len2 = len(temp._storage)
dis = list()
if len1 >= len2:
for i in range(0, len2):
dis.append(self._storage[i] - temp._storage[i])
for j in range(len2, len1):
dis.append(self._storage[j])
else:
for i in range(0, len1):
dis.append(self._storage[i] - temp._storage[i])
for j in range(len1, len2):
dis.append(temp._storage[j])
dis = format(math.sqrt(sum([x**2 for x in dis])), '.2f')
return float(dis)
def clone(self):
return copy.deepcopy(self)
def __contains__(self, item):
return item in [x for x in self._storage]
def __len__(self):
return len(self._storage)
def __iter__(self):
return iter(self._storage)
def __neg__(self):
return Datum(*tuple( -x if x > 0 else x for x in self._storage))
def __getitem__(self, item):
return self._storage[item]
def __add__(self, other):
if type(other) is not float:
if not isinstance(other, Datum):
raise TypeError("need an instance of Datum or float")
len1 = len(self._storage)
len2 = len(other._storage)
lis = list()
if len1 <= len2:
lis = list(other._storage)
for x in range(0, len1):
lis[x] += self._storage[x]
else:
lis = list(self._storage)
for x in range(0, len2):
lis[x] += other._storage[x]
return Datum(*tuple(lis))
elif type(other) is float:
res = self.__radd__(other)
return res
def __sub__(self, other):
if type(other) is float:
res = [x - other for x in self._storage]
res = Datum(*tuple(res))
return res
if not isinstance(other, Datum):
raise TypeError("need an instance of Datum or float")
len1 = len(self._storage)
len2 = len(other._storage)
if len1 <= len2:
lis = list(other._storage)
for x in range(0, len1):
lis[x] = self._storage[x] - lis[x]
for y in range(len1, len2):
lis[y] = -lis[y]
else:
lis = list(self._storage)
for x in range(0, len2):
lis[x] -= other._storage[x]
return Datum(*tuple(lis))
def __radd__(self, other):
if type(other) is float:
res = list()
for x in self._storage:
res.append(x + other)
res = Datum(*tuple(res))
return res
else:
raise TypeError("input should be a float")
def __rsub__(self, other):
res = [other - x for x in self._storage]
res = Datum(*tuple(res))
return res
def __mul__(self, other):
if isinstance(other, float):
return Datum(*tuple([x * other for x in self._storage]))
def __truediv__(self, other):
if isinstance(other, float):
return Datum(*tuple([x / other for x in self._storage]))
def __rtruediv__(self, other):
if isinstance(other, float):
return Datum(*tuple([other / x for x in self._storage]))
def __eq__(self, other):
return self.distanceFrom(Datum(0.0)) == other.distanceFrom(Datum(0.0))
def __ne__(self, other):
return self.distanceFrom(Datum(0.0)) != other.distanceFrom(Datum(0.0))
def __ge__(self, other):
return self.distanceFrom(Datum(0.0)) >= other.distanceFrom(Datum(0.0))
def __lt__(self, other):
return self.distanceFrom(Datum(0.0)) < other.distanceFrom(Datum(0.0))
def __gt__(self, other):
return self.distanceFrom(Datum(0.0)) >= other.distanceFrom(Datum(0.0))
def __le__(self, other):
return self.distanceFrom(Datum(0.0)) <= other.distanceFrom(Datum(0.0))
class Data(collections.UserList):
def __init__(self, initial = None):
if initial is None:
super(Data, self).__init__(list())
else:
for x in initial:
if not isinstance(x, Datum):
raise TypeError("each element in the list should be the instance of Datum")
super(Data, self).__init__(initial)
def computeBounds(self):
lis = self.data
lenlis = [len(x._storage) for x in lis]
max_len = max(lenlis)
minT = [sys.float_info.max] * max_len
maxT = [0.0] * max_len
for i in range(0, max_len):
for j in lis:
if i >= len(j._storage):
minT[i] = 0.0
else:
if j._storage[i] < minT[i]:
minT[i] = j._storage[i]
for i in range(0, max_len):
for j in lis:
if i >= len(j._storage):
maxT[i] = 0.0
else:
if j._storage[i] > maxT[i]:
maxT[i] = j._storage[i]
return (Datum(*tuple(minT)), Datum(*tuple(maxT)))
def computeMean(self):
lis = self.data
lenlis = [len(x._storage) for x in lis]
max_len = max(lenlis)
ans = [0.00] * max_len
for x in range(0, max_len):
for y in lis:
if x >= len(y._storage):
ans[x] = ans[x]
else:
ans[x] += y._storage[x]
for i in range(0, len(ans)):
ans[i] = ans[i] / len(lis)
return(Datum(*tuple(ans)))
def append(self, item):
if not isinstance(item, Datum):
raise TypeError("need an instance of Datum")
super.append(item)
def count(self, item):
if not isinstance(item, Datum):
raise TypeError("need an instance of Datum")
super.count(item)
def index(self, item, *args):
if not isinstance(item, Datum):
raise TypeError("need an instance of Datum")
super.index(item, *args)
def insert(self, i,item):
if not isinstance(item, Datum):
raise TypeError("need an instance of Datum")
super.insert(i,item)
def remove(self, item):
if not isinstance(item, Datum):
raise TypeError("need an instance of Datum")
super.remove(item)
def __setitem__(self, key, value):
if not isinstance(value, Datum):
raise TypeError("need an instance of Datum")
super.__setitem__(key, value)
def extend(self, other):
if not isinstance(other, Data):
raise TypeError("input should be an instance of Data")
super.extend(other)
class DataClass(Enum):
Class1 = 1
Class2 = 2
class DataClassifier:
def __init__(self, group1, group2):
if group1 is None or group2 is None:
raise ValueError("input cannot be empty")
elif not isinstance(group1, Data) or not isinstance(group2, Data):
raise TypeError("each input should be an instance of Data")
self._class1 = group1
self._class2 = group2
def classify(self, item):
dis1 = self._class1.computeMean()._storage
dis2 = self._class2.computeMean()._storage
dis1 = item.distanceFrom(Datum(*dis1))
dis2 = item.distanceFrom(Datum(*dis2))
if dis1 > dis2:
return DataClass.Class2
else:
return DataClass.Class1
<file_sep>#!/bin/bash
#######################################################
# Author: <<NAME>>
# email: <guo412>
# ID: <ee364d25>
# Date: <3/20>
#######################################################
DataPath=~ee364/DataFolder/Lab09
substudent=$DataPath"/maps/students.dat"
subcir=$DataPath"/circuits"
id=$(grep -s -E $1 $substudent | cut -f2 -d"|")
ans=$(grep -lr -E $id $subcir)
for f in $ans
do
grep -E "[A-Z]{3}-[0-9]{3}" $f | cut -f3 -d" "
done| sort -u<file_sep># Software-Engineering
For any students study at Purdue and currently take this course, you should definitely do all the works by yourself!!!
Software Engineering Tool course at Purdue University
I implemented all projects with python. For the Lab and Prelab 1-3, I learnt how to use python. Then I implemented different projects with different tools.
Lab 12 is a project about image morphing. First I created a GUI for user to use. User is able to choose two images to morph and change the alpha value between 0 to 1. User can also select, delete and reselect the point-pair on both image. From the points I derived different affine transformation matrics for different sections of the image. Then I apply the obtained transformations between the images, blend two images to have a visually appealing result.
Example Images are in Lab12 folder.
<file_sep>import sys
import os
a = 1
def findLongest():
C = [8]
while int(C[len(C) - 1]) <= 1000000:
# print(C[len(C) - 1])
if (int(int(C[len(C) - 1]) / 2) != (int(C[len(C) - 1]) / 2.0)):
C.append(2 * int(C[len(C) - 1]))
else:
if(int((int(C[len(C) - 1]) - 1) / 3) != ((int(C[len(C) - 1]) - 1) / 3)):
C.append(int(C[len(C) - 1]) * 2)
else:
C.append((int(C[len(C) - 1]) - 1) / 3)
return(C[len(C) - 2])
def findSmallest():
number = '125874'
while True:
t_n = 2 * int(number)
t_n = str(t_n)
# print(sorted(number),sorted(t_n))
if sorted(number) == sorted(t_n):
tr_n = 3 * int(number)
tr_n = str(tr_n)
# print(1)
if sorted(tr_n) == sorted(number):
t_n = 4 * int(number)
t_n = str(t_n)
# print(2)
if sorted(t_n) == sorted(number):
t_n = 5 * int(number)
t_n = str(t_n)
# print(3)
if sorted(t_n) == sorted(number):
t_n = 6 * int(number)
t_n = str(t_n)
if sorted(t_n) == sorted(number):
return number
temp = int(number) + 1
# print(temp)
number = str(temp)<file_sep>#!/bin/bash
#######################################################
# Author: <<NAME>>
# email: <guo412>
# ID: <ee364d25>
# Date: <3/20>
#######################################################
DataPath=~ee364/DataFolder/Lab09
subpro=$DataPath"/maps/projects.dat"
subcir=$DataPath"/circuits"
ans=$(ls $subcir)
for f in $ans
do
file=$subcir"/$f"
check=$(wc -c $file| cut -f1 -d" ")
if [ "$check" -ge "200" ]
then
echo $(wc -c $file | tail -c 12 | head -c 7)
fi
done | sort -u<file_sep>import sys
import numpy as np
import scipy
import imageio
from scipy.spatial import Delaunay
from PIL import ImageDraw, Image
from matplotlib.path import Path
import math
from scipy import interpolate
import os
import matplotlib.pyplot as plt
def loadTriangles(leftPointFilePath, rightPointFilePath):
lpath = leftPointFilePath
rpath = rightPointFilePath
data1 = np.loadtxt(lpath,dtype=np.float64)
data2 = np.loadtxt(rpath,dtype=np.float64)
tril = Delaunay(data1)
pointl = data1[tril.simplices]
pointr = data2[tril.simplices]
leftri = list()
rightri = list()
for x in range(0, len(pointl)):
leftri.append(Triangle(pointl[x]))
rightri.append(Triangle(pointr[x]))
return(leftri, rightri)
class Triangle:
def __init__(self, np_array):
if not isinstance(np_array, np.ndarray):
raise ValueError("input should be a ndarray")
if np_array.dtype != np.float64 or len(np_array) != 3:
raise ValueError("input should be a 3 x 2 numpy array of type float64")
self.vertices = np_array
def getPoints(self):
max_x = max(self.vertices[:,0])
min_x = min(self.vertices[:,0])
max_y = max(self.vertices[:,1])
min_y = min(self.vertices[:,1])
wid = math.ceil(max_x - min_x)
len = math.ceil(max_y - min_y)
im = Image.new('L', (math.floor(max_x),math.ceil(max_y)),0)
ImageDraw.Draw(im).polygon(tuple(map(tuple,self.vertices)),fill=255,outline=255)
temp = np.nonzero(im)
ans = np.transpose(temp)
ans[:,[0,1]] = ans[:,[1,0]]
return ans.astype(np.float64)
class Morpher:
def __init__(self,leftm,leftt,rightm,rightt):
if leftm.dtype != np.uint8:
raise TypeError("input type should be unint8")
if rightm.dtype != np.uint8:
raise TypeError("input type should be unint8")
for x in leftt:
if not isinstance(x, Triangle):
raise TypeError("input should be the instance of triangle")
for y in rightt:
if not isinstance(y,Triangle):
raise TypeError("input should be the instance of triangle")
self.leftImage = leftm
self.leftTriangles = leftt
self.rightImage = rightm
self.rightTriangles = rightt
def getImageAtAlpha(self,alpha):
midtri = list()
midmat = list()
leftmat = list()
rightmat = list()
fin_gray = np.zeros((self.leftImage.shape[0] , self.leftImage.shape[1]),np.uint8)
fin_left = interpolate.RectBivariateSpline(range(self.leftImage.shape[0]), range(self.leftImage.shape[1]),
self.leftImage)
fin_right = interpolate.RectBivariateSpline(range(self.rightImage.shape[0]), range(self.rightImage.shape[1]),
self.rightImage)
for x in range(0, len(self.rightTriangles)):
ltemp = self.leftTriangles[x]
rtemp = self.rightTriangles[x]
midx = [0]*3
midy = [0]*3
midy[0] = ltemp.vertices[0][0] * (1-alpha) + alpha * rtemp.vertices[0][0]
midx[0] = ltemp.vertices[0][1] * (1-alpha) + alpha * rtemp.vertices[0][1]
midy[1] = ltemp.vertices[1][0] * (1-alpha) + alpha * rtemp.vertices[1][0]
midx[1] = ltemp.vertices[1][1] * (1-alpha) + alpha * rtemp.vertices[1][1]
midy[2] = ltemp.vertices[2][0] * (1-alpha) + alpha * rtemp.vertices[2][0]
midx[2] = ltemp.vertices[2][1] * (1-alpha) + alpha * rtemp.vertices[2][1]
##get each mid triangle above
midmat = np.array(([midx[0],midy[0],1,0,0,0],[0,0,0,midx[0],midy[0],1],
[midx[1], midy[1], 1, 0, 0, 0], [0, 0, 0, midx[1], midy[1], 1],
[midx[2], midy[2], 1, 0, 0, 0], [0, 0, 0, midx[2], midy[2], 1]))
##get mid triangle 6x6 matrix
leftmat = np.array(([ltemp.vertices[0][1]],[ltemp.vertices[0][0]],[ltemp.vertices[1][1]],[ltemp.vertices[1][0]],[ltemp.vertices[2][1]],[ltemp.vertices[2][0]]))
rightmat = np.array(([rtemp.vertices[0][1]], [rtemp.vertices[0][0]], [rtemp.vertices[1][1]],
[rtemp.vertices[1][0]], [rtemp.vertices[2][1]], [rtemp.vertices[2][0]]))
##get left triangle 6x1 matrix
left_temp_tran = np.linalg.solve(midmat,leftmat)
right_temp_tran = np.linalg.solve(midmat,rightmat)
left_temp_tran = np.append(left_temp_tran, np.array([0,0,1]))
left_temp_tran = np.reshape(left_temp_tran,(3,3))
right_temp_tran = np.append(right_temp_tran, np.array([0,0,1]))
right_temp_tran = np.reshape(right_temp_tran,(3,3))
mid_tri = Triangle(np.column_stack((midx,midy)))
mid_points = mid_tri.getPoints()
new_leftx = np.array([])
new_rightx = np.array([])
new_lefty = np.array([])
new_righty = np.array([])
for x in mid_points:
x = np.append(x,1)
x = np.reshape(x,(3,1))
new_leftx = np.append(new_leftx,np.dot(left_temp_tran,x)[0])
new_rightx = np.append(new_rightx,np.dot(right_temp_tran,x)[0])
new_lefty = np.append(new_lefty, np.dot(left_temp_tran, x)[1])
new_righty = np.append(new_righty,np.dot(right_temp_tran,x)[1])
gray_left = fin_left.ev(new_leftx,new_lefty)
gray_right = fin_right.ev(new_rightx,new_righty)
x = mid_points[:,0].astype(np.uint64)
y = mid_points[:,1].astype(np.uint64)
fin_gray[x,y] = gray_left * (1 - alpha) + gray_right * alpha
return fin_gray
if __name__ == "__main__":
DataPath1 = os.path.expanduser('~ee364/DataFolder/Lab12/TestData/points.left.txt')
DataPath2 = os.path.expanduser('~ee364/DataFolder/Lab12/TestData/points.right.txt')
a,b = loadTriangles(DataPath1,DataPath2)
iml = imageio.imread('~ee364/DataFolder/Lab12/TestData/LeftGray.png')
imr = imageio.imread('~ee364/DataFolder/Lab12/TestData/RightGray.png')
d = Morpher(iml,a,imr,b)
<file_sep>#!/bin/bash
#######################################################
# Author: <<NAME>>
# email: <guo412>
# ID: <ee364d25>
# Date: <3/6>
#######################################################
count1=$(bash getComponentUses.bash $1)
count2=$(bash getComponentUses.bash $2)
if [ "$count1" \> "$count2" ]
then
echo $1
else
echo $2
fi<file_sep>#######################################################
# Author: <<NAME>>
# email: <<EMAIL>>
# ID: <ee364d25>
# Date: <2019/3/31>
#######################################################
import sys
from PyQt5.QtWidgets import QMainWindow, QApplication, QFileDialog
from Prelab11.BasicUI import *
import xml.etree.ElementTree as ET
DataPath = '~ee364/DataFolder/Prelab11'
class Consumer(QMainWindow, Ui_MainWindow):
def __init__(self, parent=None):
super(Consumer, self).__init__(parent)
self.setupUi(self)
self.btnSave.setEnabled(False)
self.txtCom = ['']*20
self.txtcname = [''] * 20
for i in range(0,20):
self.txtCom[i] = 'self.txtComponentCount_' + str(i + 1)
self.txtcname[i] = 'self.txtComponentName_' + str(i + 1)
self.txtStudentName.textChanged.connect(self.entry)
self.txtStudentID.textChanged.connect(self.entry)
self.com_txt = [self.txtComponentCount_1,self.txtComponentCount_2,self.txtComponentCount_3,self.txtComponentCount_4,self.txtComponentCount_5,self.txtComponentCount_6,self.txtComponentCount_7,self.txtComponentCount_8,self.txtComponentCount_9,self.txtComponentCount_10
,self.txtComponentCount_11,self.txtComponentCount_12,self.txtComponentCount_13,self.txtComponentCount_14,self.txtComponentCount_15,self.txtComponentCount_16,self.txtComponentCount_17,self.txtComponentCount_18,self.txtComponentCount_19,self.txtComponentCount_20]
self.name_txt = [self.txtComponentName_1,self.txtComponentName_2,self.txtComponentName_3,self.txtComponentName_4,self.txtComponentName_5,self.txtComponentName_6,self.txtComponentName_7,self.txtComponentName_8,self.txtComponentName_9,self.txtComponentName_10,
self.txtComponentName_11,self.txtComponentName_12,self.txtComponentName_13,self.txtComponentName_14,self.txtComponentName_15,self.txtComponentName_16,self.txtComponentName_17,self.txtComponentName_18,self.txtComponentName_19,self.txtComponentName_20]
for count in self.txtCom:
count = count + '.textChanged.connect(self.entry)'
exec(count)
for count in self.txtcname:
count = count + '.textChanged.connect(self.entry)'
exec(count)
self.cboCollege.currentIndexChanged.connect(self.entry)
self.chkGraduate.stateChanged.connect(self.entry)
self.btnClear.clicked.connect(self.click_clear)
self.btnLoad.clicked.connect(self.loadData)
self.btnSave.clicked.connect(self.saveXML)
def loadData(self):
"""
*** DO NOT MODIFY THIS METHOD! ***
Obtain a file name from a file dialog, and pass it on to the loading method. This is to facilitate automated
testing. Invoke this method when clicking on the 'load' button.
You must modify the method below.
"""
filePath, _ = QFileDialog.getOpenFileName(self, caption='Open XML file ...', filter="XML files (*.xml)")
if not filePath:
return
self.loadDataFromFile(filePath)
def loadDataFromFile(self, filePath):
"""
Handles the loading of the data from the given file name. This method will be invoked by the 'loadData' method.
*** YOU MUST USE THIS METHOD TO LOAD DATA FILES. ***
*** This method is required for unit tests! ***
"""
tree = ET.parse(filePath)
root = tree.getroot()
for child in root:
# print(child.tag) (StudentName), StudentID, College, Components
#print(child.attrib) ({'graduate': 'true'})
if child.tag == 'StudentName':
self.txtStudentName.setText(child.text)
if child.attrib['graduate'] == "true":
self.chkGraduate.setChecked(True)
if child.tag == 'StudentID':
self.txtStudentID.setText(child.text)
if child.tag == 'College':
self.cboCollege.setCurrentIndex(self.cboCollege.findText(child.text))
if child.tag == 'Components':
child_name = list()
child_count = list()
for component in child:
ans = list(component.attrib.values())
child_name.append(ans[0])
child_count.append(ans[1])
for i in range(0,len(child_name)):
if i >= 20:
break
self.name_txt[i].setText(child_name[i])
self.com_txt[i].setText(child_count[i])
def click_clear(self):
self.txtStudentID.clear()
self.txtStudentName.clear()
for count in self.txtCom:
count = count + '.clear()'
exec(count)
for count in self.txtcname:
count = count + '.clear()'
exec(count)
self.cboCollege.setCurrentIndex(0)
self.chkGraduate.setChecked(False)
self.btnLoad.setEnabled(True)
self.btnClear.setEnabled(True)
self.btnSave.setEnabled(False)
def entry(self):
if self.txtStudentName.text is not '':
self.butt()
if self.txtStudentID.text is not '':
self.butt()
for count in self.txtCom:
count = count + '.text'
exec(count)
if exec(count) is not '':
self.butt()
for count in self.txtcname:
count = count + '.text'
exec(count)
if exec(count) is not '':
self.butt()
if self.chkGraduate.checkState is True:
self.butt()
if self.cboCollege.currentIndex is not '':
self.butt()
def butt(self):
self.btnLoad.setEnabled(False)
self.btnSave.setEnabled(True)
def saveXML(self):
graduate = 'false'
if self.chkGraduate.isChecked() is True:
graduate = 'true'
s_name = self.txtStudentName.text()
s_id = self.txtStudentID.text()
college = self.cboCollege.currentText()
Cname = list()
Ccount = list()
for name in self.name_txt:
if name.text() is not '':
Cname.append(name.text())
for count in self.com_txt:
if count.text() is not '':
Ccount.append(count.text())
with open('target.xml', 'w') as output:
output.write('<?xml version="1.0" encoding="UTF-8"?>\n')
output.write('<Content>\n')
output.write(' <StudentName graduate="'+graduate+'">'+s_name+'</StudentName>\n')
output.write(' <StudentID>'+s_id+'</StudentID>\n')
output.write(' <College>'+college+'</College>\n')
output.write(' <Components>\n')
for i in range(0, len(Ccount)):
output.write(' <Component name="'+Cname[i]+'" count="'+Ccount[i]+'" />\n')
output.write(' </Components>\n</Content>')
if __name__ == "__main__":
currentApp = QApplication(sys.argv)
currentForm = Consumer()
currentForm.show()
currentApp.exec_()
<file_sep>import os
import sys
import csv
import copy
from pprint import pprint as pp
DataPath = os.path.expanduser('~ee364/DataFolder/Lab05')
def _readfiles(num, var1, var2):
people_path = 'people.dat'
people_path = os.path.join(DataPath, people_path)
with open(people_path, 'r') as file:
file.readline()
file.readline()
data = file.readlines()
data_split = [m.split() for m in data]
name = [''] * len(data_split)
ID = [''] * len(data_split)
for i in range(0, len(data_split)):
name[i] = data_split[i][0] + ' ' + data_split[i][1]
ID[i] = data_split[i][3]
name_id = dict(zip(name,ID))
id_name = dict(zip(ID, name))
pin_path = 'pins.dat'
pin_path = os.path.join(DataPath,pin_path)
with open(pin_path, 'r') as file:
data = file.readlines()
data_split = [m.split() for m in data]
pin_key = data_split[1]
data_split = data_split[3:]
log_path = 'log.dat'
log_path = os.path.join(DataPath,log_path)
with open(log_path, 'r') as file:
file.readline()
file.readline()
file.readline()
data = file.readlines()
log_data = [m.split() for m in data]
resource = set()
log_id = set()
if num == '4':
date = var1
for case4 in log_data:
if date == case4[0]:
resource.add(case4[2])
if resource == set():
raise ValueError("date does not exist")
return resource
if num == '3':
date = var1
for case3 in log_data:
if date == case3[0]:
log_id.add(case3[3])
if log_id == set():
raise ValueError("date does not exist")
users = set()
for user in log_id:
users.add(getUserOf(user, date))
return users
if num == '1':
name_1 = var1
date = var2
if name_1 not in name_id:
raise ValueError("name does not exist")
id = name_id[name_1]
if date not in pin_key:
raise ValueError("date not in the file")
date_code = pin_key.index(date)
for case1 in data_split:
if id == case1[0]:
return case1[date_code]
if num == '2':
date = var2
pin = var1
if date not in pin_key:
raise ValueError("date not in the file")
date_code = pin_key.index(date)
for case2 in data_split:
if pin == case2[date_code]:
id = case2[0]
name_2 = id_name[id]
return name_2
raise ValueError("code does not exist")
if num == '5':
dates = var1
id_count = {}
for date in dates:
for case5 in log_data:
if date == case5[0]:
id_count[case5[3]] = 0
for date in dates:
for case5 in log_data:
if date == case5[0]:
id_count[case5[3]] +=1
keys = list(id_count.keys())
values = list(id_count.values())
place = values.index(max(values))
case5_id = keys[place]
dates = list(dates)
for date in dates:
date_code = pin_key.index(date)
for case2 in data_split:
if case5_id == case2[date_code]:
id = case2[0]
name_2 = id_name[id]
return name_2
if num == '6':
dates = var1
re_count = {}
for date in dates:
for case5 in log_data:
if date == case5[0]:
re_count[case5[2]] = 0
for date in dates:
for case5 in log_data:
if date == case5[0]:
re_count[case5[2]] +=1
keys = list(re_count.keys())
values = list(re_count.values())
place = values.index(max(values))
return keys[place]
if num == '7':
need_uid = set()
for uid in data_split:
need_uid.add(uid[0])
abs = set()
for all in ID:
if all not in need_uid:
abs.add(id_name[all])
return abs
def getPinFor(name, date):
code = _readfiles('1', name, date)
return code
def getUserOf(pin, date):
name = _readfiles('2', pin, date)
return name
def getUsersOn(date):
users = _readfiles('3', date, '')
return users
def getResourcesOn(date):
resource = _readfiles('4', date, '')
return resource
def getMostActiveUserOn(dates):
name = _readfiles('5', dates, '')
return name
def getMostAccessedOn(dates):
re = _readfiles('6', dates, '')
return re
def getAbsentUsers():
abs = _readfiles('7','','')
return abs
def getDifference(slot1, slot2):
slot_path = 'slots.dat'
slot_path = os.path.join(DataPath, slot_path)
with open (slot_path, 'r') as file:
file.readline()
data = file.readlines()
data_split = [m.split() for m in data]
time = data_split[0]
info = data_split[2:]
place1 = time.index(slot1)
place2 = time.index(slot2)
count1 = 0
count2 = 0
for i in info:
if i[place1] == '1':
count1 += 1
if i[place2] == '1':
count2 += 1
diff = abs(count1 - count2)
return diff<file_sep>#######################################################
# Author: <<NAME> >
# email: <<EMAIL> >
# ID: <ee364d25>
# Date: <2019/2/20 >
#######################################################
import re
# Module level Variables. (Write this statement verbatim .)
#######################################################
def extractArguments(commandline):
sub_cc = re.findall(r"[\\+]([a-z])\s+([^\s\\+]+)",commandline)
sub_cc.sort() #I am not sure about what sort mean: whether it means that the tuples appear first in the commandline or just sort my result. I asked the TA, and TA told me that just sort my result.
return sub_cc
def extractNumerics(sentence):
test = re.findall(r"([^\s]+)", sentence)
res = list()
pattern1 = r"([-+]?[0-9]+\.[0-9]+[eE][-+][0-9]+)"
pattern2 = r"([-+]?[0-9]+\.[0-9]+)"
pattern3 = r"([-+]?[0-9]+)"
for case in test:
if re.findall(pattern1, case):
res.append(re.findall(pattern1, case)[0])
elif re.findall(pattern2, case):
res.append(re.findall(pattern2, case)[0])
elif re.findall(pattern3, case):
res.append(re.findall(pattern3, case)[0])
return res<file_sep>import os
import sys
import csv
import copy
from pprint import pprint as pp
DataPath = os.path.expanduser('~ee364/DataFolder/Lab04')
def readfiles(number, var1, var2):
pro_path = os.path.expanduser('~ee364/DataFolder/Lab04/providers')
pro_list = os.listdir(pro_path)
if number == '1':
var1 = var1 + '.dat'
var2 = var2 + '.dat'
if var1 not in pro_list:
raise ValueError('the first provider does not in the folder')
elif var2 not in pro_list:
raise ValueError('the second provider does not in the folder')
place1 = pro_list.index(var1)
place2 = pro_list.index(var2)
pro_1 = os.path.join(pro_path, pro_list[place1])
pro_2 = os.path.join(pro_path, pro_list[place2])
with open(pro_1, 'r') as file:
file.readline()
file.readline()
file.readline()
data = file.readlines()
data_split = [m.split() for m in data]
name1 = [''] * len(data_split)
for i in range(0, len(data_split)):
name1[i] = data_split[i][0] + ' ' + data_split[i][1]
with open(pro_2, 'r') as file:
file.readline()
file.readline()
file.readline()
data = file.readlines()
data_split = [m.split() for m in data]
name2 = [''] * len(data_split)
for i in range(0, len(data_split)):
name2[i] = data_split[i][0] + ' ' + data_split[i][1]
diff = set('')
for x in range(0,len(name1)):
if name1[x] not in name2:
diff.add(name1[x])
return diff
elif number == '2':
name = var1
var2 = var2 + '.dat'
if var2 not in pro_list:
raise ValueError('provider does not in the file')
pro_path = os.path.join(pro_path, var2)
with open(pro_path, 'r') as file:
file.readline()
file.readline()
file.readline()
data = file.readlines()
data_split = [m.split() for m in data]
pro_name = [''] * len(data_split)
for i in range(0, len(data_split)):
pro_name[i] = data_split[i][0] + ' ' + data_split[i][1]
if pro_name[i] == name:
return data_split[i][3][1:]
raise ValueError('the provider does not carry the SBC request')
elif number == '3':
sbcSet = list(var1)
tur= [(0, '')] * len(sbcSet)
for i in range(0, len(sbcSet)):
for pro in pro_list:
pro_path = os.path.expanduser('~ee364/DataFolder/Lab04/providers')
pro_path = os.path.join(pro_path, pro)
with open(pro_path, 'r') as file:
file.readline()
file.readline()
file.readline()
data = file.readlines()
data_split = [m.split() for m in data]
pro_name = [''] * len(data_split)
for j in range(0, len(data_split)):
pro_name[j] = data_split[j][0] + ' ' + data_split[j][1]
if pro_name[j] == sbcSet[i]:
price,_ = tur[i]
if price == 0:
tur[i] = float(data_split[i][3][1:]), pro[:9]
else:
tur[i] = min(price, float(data_split[i][3][1:])), pro[:9]
min_price = dict(zip(sbcSet, tur))
return min_price
def getDifference(provider1, provider2):
sbc_names = readfiles('1',provider1, provider2)
return sbc_names
def getPriceOf(sbc, provider):
price = readfiles('2', sbc, provider)
return price
def checkAllPrices(sbcSet):
min_price = readfiles('3', sbcSet, '')
return min_price
def getFilter():
phone_path = os.path.expanduser('~ee364/DataFolder/Lab04/phones.dat')
with open(phone_path, 'r') as file:
reader = csv.DictReader(file)
phone = [row['Phone Number'] for row in reader]
test_phone = copy.copy(phone)
for i in range(0, len(test_phone)):
test_phone[i] = test_phone[i].replace('(','')
test_phone[i] = test_phone[i].replace(')', '')
test_phone[i] = test_phone[i].replace(' ', '')
test_phone[i] = test_phone[i].replace('-', '')
f_phone = list()
case = list()
for k in range(0,999):
j = copy.copy(k)
if j < 10:
j = '0' + '0' + str(j)
elif j < 100:
j = '0' + str(j)
j = str(j)
count = 0
for m in range(0, len(test_phone)):
if count > 1:
f_phone = f_phone[0:len(f_phone) - 1]
case = case[0:len(case) - 1]
break
if j in test_phone[m]:
f_phone.append(phone[m])
case.append(j)
count += 1
match = dict(zip(case, f_phone))
return match<file_sep>#######################################################
# Author: <<NAME> >
# email: <<EMAIL> >
# ID: <ee364d25>
# Date: <2019/2/20>
#######################################################
import os # List of module import statements
import sys # Each one on a line
import csv
import copy
import re
from uuid import UUID
from pprint import pprint as pp
from enum import Enum
# Module level Variables. (Write this statement verbatim .)
#######################################################
class Level(Enum):
Freshman = 1
Sophomore = 2
Junior = 3
Senior = 4
class ComponentType(Enum):
Resistor = 'R'
Capacitor = 'C'
Inductor = 'I'
Transistor = 'T'
class Student:
def __init__(self, ID, first, last, level):
self.ID = ID
self.firstName = first
self.LastNmae = last
self.level = level
if not isinstance(level, Level):
#if self.level not in Level.__members__: #question one
raise TypeError("The argument must be an instance of the 'Level' Enum.")
def __str__(self):
return f"{self.ID}, {self.firstName} {self.LastNmae}, {self.level.name}"
class Component:
def __init__(self, ID, ctype, price):
self.ID = ID
self.ctype = ctype
self.price = float(format(float(price), '.2f'))
if not isinstance(ctype, ComponentType):
raise TypeError("The argument must be an instance of the 'ComponentType' Enum.")
def __str__(self):
return f"{self.ctype.name}, {self.ID}, ${format(self.price,'.2f')}"
def __hash__(self): #question 4
return hash(self.ID)
class Circuit:
def __init__(self, ID, components):
self.ID = ID
self.components = components
cost = 0
for x in self.components:
cost += x.price
self.cost = cost
for check in self.components:
if not isinstance(check, Component):
raise TypeError("The argument must be an instance of the 'ComponentType' Enum")
def __str__(self):
numR = len([x for x in self.components if x.ctype == ComponentType.Resistor])
if numR < 10: numR = '0' + str(numR)
numC = len([x for x in self.components if x.ctype == ComponentType.Capacitor])
if numC < 10: numC = '0' + str(numC)
numI = len([x for x in self.components if x.ctype == ComponentType.Inductor])
if numI < 10: numI = '0' + str(numI)
numT = len([x for x in self.components if x.ctype == ComponentType.Transistor])
if numT < 10: numT = '0' + str(numT)
return f"{self.ID}: (R = {numR}, C = {numC}, I = {numI}, T = {numT}), Cost = ${format(self.cost, '.2f')}"
#question 3 getByType function
def __contains__(self, item):
if not isinstance(item, Component):
raise TypeError("The argument must be an instance of the 'ComponentType' Enum")
return item in self.components
def __add__(self, other):
if not isinstance(other, Component):
raise TypeError("The argument must be an instance of the 'ComponentType' Enum")
if other in self.components:
return self
else:
self.components.add(other)
self.cost = self.cost + other.price
return self
def __sub__(self, other):
if not isinstance(other, Component):
raise TypeError("The argument must be an instance of the 'ComponentType' Enum")
if other in self.components:
self.components.remove(other)
self.cost = self.cost - other.price
return self
else:
return self
def __eq__(self, other):
if not isinstance(other, Circuit):
raise TypeError("circuit2 is not valid circuit class type")
return self.cost == other.cost
def __gt__(self, other):
if not isinstance(other, Circuit):
raise TypeError("circuit2 is not valid circuit class type")
return self.cost > other.cost
def __lt__(self, other):
if not isinstance(other, Circuit):
raise TypeError("circuit2 is not valid circuit class type")
return self.cost < other.cost
def getByType(self, com):
if not isinstance(com, ComponentType):
raise TypeError("type is not ComponentType")
res = set()
for x in self.components:
if x.ctype == com:
res.add(x)
return res
class Project:
def __init__(self, ID, participants, circuits):
self.ID = ID
self.participants = participants
self.circuits = circuits
cost = 0
for x in circuits:
cost+= x.cost
self.cost = cost
for check1 in self.participants:
if not isinstance(check1, Student):
raise TypeError("The argument must be an instance of the 'Student'")
for check2 in self.circuits:
if not isinstance(check2, Circuit):
raise TypeError("The argument must be an instance of the 'Circuit")
def __str__(self):
#ID: (XX Circuits, XX Participants), Cost = $<cost>
num_c = len(self.circuits)
if num_c < 10:
num_c = '0' + str(num_c)
num_s = len(self.participants)
if num_s < 10:
num_s = '0' + str(num_s)
return f"{self.ID}: ({num_c} Circuits, {num_s} Participants), Cost = ${format(self.cost, '.2f')}"
def __contains__(self, item):
if not isinstance(item, Component):
if not isinstance((item, Circuit)):
if not isinstance(item, Student):
raise TypeError("This item your passed is not valid")
if isinstance(item, Component):
for x in self.circuits:
if x.__contains__(item):
return True
return False
if isinstance(item, Circuit):
return item.ID in [circuit.ID for circuit in self.circuits]
if isinstance(item, Student):
return item.ID in [student.ID for student in self.participants]
def __add__(self, other):
if not isinstance(other, Circuit):
raise TypeError("The argument must be an instance of the 'Circuit'")
if other in self.circuits:
return self
else:
self.circuits.append(other)
self.cost = self.cost + other.cost
return self
def __sub__(self, other):
if not isinstance(other, Circuit):
raise TypeError("The argument must be an instance of the 'Circuit'")
if other in self.circuits:
del self.circuits[other]
self.cost = self.cost - other.cost
return self
else:
return self
class Capstone(Project):
def __init__(self, *args):
if (len(args) == 1):
super().__init__(args[0].ID, args[0].participants, args[0].circuits)
check = [part.level for part in self.participants]
for x in check:
if x is not Level.Senior:
raise ValueError("all students must be senior")
else:
super().__init__(args[0].ID, args[0].participants, args[0].circuits)
check = [part.level for part in self.participants]
for x in check:
if x is not Level.Senior:
raise ValueError("all students must be senior")<file_sep>import sys
from PyQt5 import QtCore, QtGui
from PyQt5.QtWidgets import QMainWindow, QApplication
import re
from Lab11.calculator import *
class MathConsumer(QMainWindow, Ui_MainWindow):
def __init__(self, parent=None):
super(MathConsumer, self).__init__(parent)
self.setupUi(self)
self.btnCalculate.clicked.connect(self.performOperation)
def performOperation(self):
checknum1 = re.findall(r"([^0-9]+)", self.edtNumber1.text())
checknum2 = re.findall(r"([^0-9]+)", self.edtNumber2.text())
if self.edtNumber1.text() == '':
self.edtResult.setText('E')
elif self.edtNumber2.text() == '':
self.edtResult.setText('E')
elif checknum1 != []:
if checknum1[0] != '.':
self.edtResult.setText('E')
else:
if len(checknum1) == 1:
self.cal()
else:
self.edtResult.setText('E')
elif checknum2 != []:
if checknum2[0] != '.':
self.edtResult.setText('E')
else:
if len(checknum2) == 1:
self.cal()
else:
self.edtResult.setText('E')
else:
self.cal()
def cal(self):
if self.cboOperation.currentText() == '+':
num1 = self.edtNumber1.text()
num2 = self.edtNumber2.text()
res = float(num1) + float(num2)
self.edtResult.setText(str(round(res,12)))
elif self.cboOperation.currentText() == '-':
num1 = self.edtNumber1.text()
num2 = self.edtNumber2.text()
res = float(num1) - float(num2)
self.edtResult.setText(str(round(res,12)))
elif self.cboOperation.currentText() == '*':
num1 = self.edtNumber1.text()
num2 = self.edtNumber2.text()
res = float(num1) * float(num2)
self.edtResult.setText(str(round(res,12)))
elif self.cboOperation.currentText() == '/':
num1 = self.edtNumber1.text()
num2 = self.edtNumber2.text()
if float(num2) == 0.0:
self.edtResult.setText('E')
else:
res = float(num1) / float(num2)
self.edtResult.setText(str(round(res,12)))
if __name__ == "__main__":
currentApp = QApplication(sys.argv)
currentForm = MathConsumer()
currentForm.show()
currentApp.exec_()<file_sep>#######################################################
# Author: <<NAME> >
# email: <<EMAIL> >
# ID: <ee364d25>
# Date: <2019/3/6 >
#######################################################
import os
from uuid import UUID
from pprint import pprint as pp
from enum import Enum
import sys # Each one on a line
import csv
import copy
import re
import math
# Module level Variables. (Write this statement verbatim .)
#######################################################
class TimeSpan:
def __init__(self, weeks, days, hours):
if weeks < 0 or days < 0 or hours < 0:
raise ValueError("The arguments cannot be negative")
act_hour = hours % 24
days = days + hours // 24
act_days = days % 7
weeks = weeks + days // 7
self.weeks = weeks
self.days = act_days
self.hours = act_hour
def __str__(self):
if self.hours < 10:
s_hour = '0' + str(self.hours)
else:
s_hour = str(self.hours)
if self.weeks < 10:
s_weeks = '0' + str(self.weeks)
else:
s_weeks = str(self.weeks)
return f"{s_weeks}W {str(self.days)}D {s_hour}H"
def __repr__(self):
if self.hours < 10:
s_hour = '0' + str(self.hours)
else:
s_hour = str(self.hours)
if self.weeks < 10:
s_weeks = '0' + str(self.weeks)
else:
s_weeks = str(self.weeks)
return f"{s_weeks}W {str(self.days)}D {s_hour}H"
def getTotalHours(self):
return self.weeks * (7 * 24) + self.days * 24 + self.hours
def __add__(self, other):
if not isinstance(other, TimeSpan):
raise TypeError("An TImeSPan instance is expected")
return(TimeSpan(self.weeks + other.weeks, self.days + other.days, self.hours + other.hours))
def __mul__(self, other):
if type(other) is not int and type(other) is not float:
raise TypeError("an integer or a float is expected")
if other <= 0:
raise ValueError("the value should be greater than 0")
if type(other) is int:
return(TimeSpan(self.weeks * other, self.days * other, self.hours * other))
else:
weeks = self.weeks * other
rest_d = (weeks - int(weeks)) * 7
days = self.days * other + rest_d
rest_h = (days - int(days)) * 24
hours = self.hours * other
rest_h = hours + rest_h
if rest_h - int(rest_h) >= 0.5:
rest_h = math.ceil(rest_h)
else:
rest_h = math.floor(rest_h)
return(TimeSpan(int(weeks), int(days), rest_h))
def __eq__(self, other):
if not isinstance(other, TimeSpan):
raise TypeError("an TimeSpan instance is expected")
return self.getTotalHours() == other.getTotalHours()
def __ne__(self, other):
if not isinstance(other, TimeSpan):
raise TypeError("an TimeSpan instance is expected")
return self.getTotalHours() != other.getTotalHours()
def __le__(self, other):
if not isinstance(other, TimeSpan):
raise TypeError("an TimeSpan instance is expected")
return self.getTotalHours() <= other.getTotalHours()
def __lt__(self, other):
if not isinstance(other, TimeSpan):
raise TypeError("an TimeSpan instance is expected")
return self.getTotalHours() < other.getTotalHours()
def __ge__(self, other):
if not isinstance(other, TimeSpan):
raise TypeError("an TimeSpan instance is expected")
return self.getTotalHours() >= other.getTotalHours()
def __gt__(self, other):
if not isinstance(other, TimeSpan):
raise TypeError("an TimeSpan instance is expected")
return self.getTotalHours() > other.getTotalHours()<file_sep>#######################################################
# Author: <Your Full Name >
# email: <Your Email >
# ID: <Your course ID , e.g. ee364j20 >
# Date: <Start Date >
#######################################################
import os # List of module import statements
import sys # Each one on a line
# Module level Variables. (Write this statement verbatim .)
#######################################################
DataPath = os.path.expanduser('~ee364/DataFolder/Prelab01')
def find(pattern) :
path = os.path.join(DataPath, 'sequence.txt')
f = open(path)
data = f.read()
length_data = len(data)
length_pattern = len(pattern)
res1 = [0] * length_data
count = 0
if(length_pattern > length_data) :
return
for i in range(0, length_data - length_pattern):
for j in range(0, length_pattern):
if data[i + j] is not pattern[j]:
if pattern[j] is not 'X':
break
if j == length_pattern - 1:
res1[count] = data[i:i + length_pattern]
count = count + 1
res1 = res1[0:count]
f.close()
print(res1)
def getStreakProduct(sequence, maxSize, product):
t_pro: int = 1
count = 0
num = 0
res2 = [0] * 2**len(sequence)
for i in range(0,len(sequence)):
while int(t_pro) < int(product):
num = num + 1
t_pro = t_pro * int(sequence[i])
if t_pro == product:
if num <= maxSize:
res2[count] = sequence[i - num + 1: i + 1]
count = count + 1
i = i + 1
if i == len(sequence):
break
num = 0
t_pro = 1
res2 = res2[0:count]
print(res2)
def writePyramids(filePath, baseSize, count, char):
f = open(filePath,'w+')
depth = int((baseSize) / 2) + 1
for i in range(depth,0,-1):
num = 1 + 2 * (depth - i)
space = " " * (i - 1)
py_char = char * num
pyr = (space + py_char + space + " ") * (count - 1)
pyr = pyr + space + py_char + space
f.writelines([pyr,'\n'])
f.close()
def getStreaks(sequence, letters):
res4 = [0]*len(sequence)
count = 0
num = 0
i_loop = 0
while i_loop < len(sequence):
if i_loop != len(sequence) - 1:
while sequence[i_loop] is sequence[i_loop + 1]:
count = count + 1
i_loop = i_loop + 1
for j in range(0,len(letters)):
if sequence[i_loop] is letters[j]:
res4[num] = sequence[i_loop - count:i_loop + 1]
num = num + 1
i_loop = i_loop + 1
count = 0
res4 = res4[0:num]
print(res4)
def findNames(nameList, part, name):
name = name.lower()
if part == "F":
name = name + " "
if part == "L":
name = " " + name
if part != "FL":
if part != "F":
if part != "L":
return []
res5 = [0] * len(nameList)
count = 0
for i in range(0, len(nameList)):
nameList[i] = nameList[i].lower()
if nameList[i].find(name) != -1:
check = 0
if part == "F":
if nameList[i][0:len(name)] == name:
res5[count] = nameList[i].title()
count = count + 1
elif part == "L":
if nameList[i][len(nameList[i]) - len(name) : len(nameList[i])] == name:
res5[count] = nameList[i].title()
count = count + 1
elif part == "FL":
if nameList[i][len(name)] == " ":
res5[count] = nameList[i].title()
count = count + 1
elif nameList[i][len(nameList[i]) - len(name) - 1] == " ":
res5[count] = nameList[i].title()
count = count + 1
return res5[0:count]
def convertToBoolean(num, size):
res6 = ['X']
if type(num) is not int:
return []
elif type(size) is not int:
return []
while(num != 0):
bool = num % 2
num = int(num / 2)
res6.append(str(bool))
if len(res6) - 1 > size:
size = len(res6) - 1
r_res6 = [True] * size
for i in range (0,size):
if res6[len(res6) - 1 - i] == '1':
r_res6[i] = True
else:
r_res6[i] = False
print(r_res6)
def convertToInteger(boolList):
if type(boolList) is not list:
return None
for j in range(0,len(boolList)):
if type(boolList[j]) is not bool:
return None
if boolList == []:
return None
while(boolList[0] == False):
boolList = boolList[1:]
res7: int = 0
size = len(boolList) - 1
for i in range(0,len(boolList)):
if boolList[i] == True:
res7 = res7 + 2**size
size = size - 1
else:
size = size - 1
return res7
if __name__ == "__main__":
writePyramids("temp.txt",10,3,"a")
<file_sep>#######################################################
# Author: <<NAME> >
# email: <<EMAIL> >
# ID: <ee364d25>
# Date: <2019/1/18 >
#######################################################
import os # List of module import statements
import sys # Each one on a line
import csv
# Module level Variables. (Write this statement verbatim .)
#######################################################
DataPath = os.path.expanduser('~ee364/DataFolder/Prelab02')
def readfile(symbol, number, dat, price):
if number != 4:
d_path = symbol+ '.dat'
if d_path not in os.listdir(DataPath):
return None
else:
d_path = symbol
path = os.path.join(DataPath, d_path)
with open(path, 'r') as file:
reader = csv.DictReader(file)
close = [row['close'] for row in reader]
close = close[1:]
with open(path, 'r') as file:
reader = csv.DictReader(file)
date = [row['date'] for row in reader]
date = date[1:]
with open(path, 'r') as file:
reader = csv.DictReader(file)
volume = [row['volume'] for row in reader]
volume = volume[1:]
with open(path, 'r') as file:
reader = csv.DictReader(file)
opent = [row['open'] for row in reader]
opent = opent[1:]
with open(path, 'r') as file:
reader = csv.DictReader(file)
high = [row['high'] for row in reader]
high = high[1:]
with open(path, 'r') as file:
reader = csv.DictReader(file)
low = [row['low'] for row in reader]
low = low[1:]
if number is 1:
diff = [0] * len(high)
num = 0
diff[0] = abs(float(high[0]) - float(low[0]))
Maxv = diff[0]
for i in range(1,len(high)):
diff[i] = float(high[i]) - float(low[i])
if diff[i] > Maxv:
Maxv = (diff[i])
num = i
return date[num]
elif number is 2:
num2 = 0
for i in range(0,len(close)):
if float(close[i]) > float(opent[i]):
num2 = num2 + 1
return ('%.4f'%(float(num2) * 100/ len(close)))
elif number is 4:
for i in range(0,len(date)):
if dat == date[i]:
return ('%.4f'%(((float(close[i]) - float(opent[i])) * 100) / float(opent[i])))
elif number is 5:
avg = 0
numb = 0
for i in range(0, len(date)):
if str(dat) in date[i]:
avg = avg + (float(close[i]) + float(opent[i])) / 2
numb = numb + 1
avg = avg / numb
return ('%.4f'%(avg))
elif number is 3:
date2 = price
start = 0
end = 0
sum = 0
for i in range(0, len(date)):
if (dat == date[i]):
end = i + 1
break
if (date2 == date[i]):
start = i
for j in range(start,end):
sum = sum + float(volume[j])
sum = int(sum)
return sum
elif number is 6:
count = 0
for i in range(0,len(date)):
if float(close[i]) >= price:
if float(opent[i]) >= price:
if float(low[i]) >= price:
if float(high[i]) >= price:
count = count + 1
return count
def getMaxDifference(symbol):
date = readfile(symbol,1,0,0)
return date
def getGainPercent(symbol):
percent = readfile(symbol,2,0,0)
return percent
def getVolumeSum(symbol, date1, date2):
if date1 < date2:
sum = readfile(symbol,3,date1,date2)
return sum
else:
return None
def getBestGAIN(date):
files = os.listdir(DataPath)
Gain = [0] * len(files)
for i in range(0,len(files)):
Gain[i] = readfile(files[i],4,date,0)
return max(Gain)
def getAveragePrice(symbol, year):
Price = readfile(symbol,5,year,0)
return Price
def getCountOver(symbol, price):
count = readfile(symbol, 6, 0, price)
return count<file_sep>#######################################################
# Author: <<NAME> >
# email: <<EMAIL> >
# ID: <ee364d25>
# Date: <2019/2/15 >
#######################################################
import os # List of module import statements
import sys # Each one on a line
import csv
import copy
import re
from uuid import UUID
from pprint import pprint as pp
# Module level Variables. (Write this statement verbatim .)
#######################################################
DataPath = os.path.expanduser('~ee364/DataFolder/Prelab06')
def getUrlParts(url):
sub_url = re.findall(r"[/]{2}.*\?", url)
parts = re.findall(r"[a-zA-Z0-9]+\.[a-zA-Z0-9]+\.[a-z]+",sub_url[0])[0]
other_o = re.findall(r"(\/[a-zA-Z0-9]+\/)",sub_url[0])[0]
other_o = other_o[1:len(other_o) - 1]
other_t = re.findall(r"(\/[a-zA-Z0-9]+\?)",sub_url[0])[0]
other_t = other_t[1:len(other_t) - 1]
ans = parts, other_o, other_t
return ans
def getQueryParameters(url):
sub_url = re.findall(r"(\?.*)", url)[0][1:]
parts = re.findall(r"([A-Za-z0-9\.\-\_]+\=)", sub_url)
parts_o = re.findall(r"(\=[A-Za-z0-9\.\-\_]+)", sub_url)
res = [('','')] * len(parts)
for i in range(0, len(parts)):
res[i] = parts[i][0:len(parts[i]) - 1],parts_o[i][1:]
return res
def getSpecial(sentence, letter):
case1 = re.findall(r"[A-Za-z]+",sentence)
res = list()
for case2 in case1:
if re.findall(r"\w+%c\b"%letter, case2, re.IGNORECASE) != []:
if re.findall(r"\b%c\w+"%letter, case2, re.IGNORECASE) == []:
res.append(case2)
elif re.findall(r"\b%c\w+"%letter, case2, re.IGNORECASE) != []:
res.append(case2)
return res
def getRealMac(sentence):
ass = re.findall(r"([a-fA-F0-9]{2}\-[a-fA-F0-9]{2}\-[a-fA-F0-9]{2}\-[a-fA-F0-9]{2}\-[a-fA-F0-9]{2}\-[a-fA-F0-9]{2})", sentence)
if ass == []:
ass = re.findall(r"([a-fA-F0-9]{2}\:[a-fA-F0-9]{2}\:[a-fA-F0-9]{2}\:[a-fA-F0-9]{2}\:[a-fA-F0-9]{2}\:[a-fA-F0-9]{2})",sentence)
if ass != []:
return ass
return None
def getRejectedEntries():
path = 'Employees.txt'
path = os.path.join(DataPath, path)
with open(path, 'r') as f:
data = f.readlines()
name = list()
for check in data:
temp = re.findall(r"(^[a-zA-Z]+\s[a-zA-Z]+)[\,\;\s]+\n", check)
if temp == []:
temp = re.findall(r"(^[a-zA-Z]+)\,\s([a-zA-Z]+)[\,\;\s]+\n", check)
if temp != []:
Last, First = temp[0]
name.append(First + ' ' + Last)
else:
name.append(temp[0])
name.sort()
return name
def getEmployeesWithIDs():
path = 'Employees.txt'
path = os.path.join(DataPath, path)
with open(path, 'r') as f:
data = f.readlines()
name_dict = list()
id_dict = list()
for check in data:
id = re.findall(r"([a-zA-Z0-9\-]{36})",check)
if id != []:
id_dict.append(id[0])
temp = re.findall(r"(^[a-zA-Z]+\s[a-zA-Z]+)", check)
if temp == []:
temp = re.findall(r"(^[a-zA-Z]+)\,\s([a-zA-Z]+)", check)
if temp != []:
Last, First = temp[0]
name_dict.append(First + ' ' + Last)
else:
name_dict.append(temp[0])
else:
id = re.findall(r"([a-zA-Z0-9]{32})", check)
if id != []:
id = '{' + id[0] + '}'
id = str(UUID(id))
id_dict.append(id)
temp = re.findall(r"(^[a-zA-Z]+\s[a-zA-Z]+)", check)
if temp == []:
temp = re.findall(r"(^[a-zA-Z]+)\,\s([a-zA-Z]+)", check)
if temp != []:
Last, First = temp[0]
name_dict.append(First + ' ' + Last)
else:
name_dict.append(temp[0])
ans = dict(zip(name_dict, id_dict))
return ans
def getEmployeesWithoutIDs():
path = 'Employees.txt'
path = os.path.join(DataPath, path)
with open(path, 'r') as f:
data = f.readlines()
name_dict = list()
for check in data:
id = re.findall(r"([a-zA-Z0-9\-]{36})",check)
if id == []:
id = re.findall(r"([a-zA-Z0-9]{32})", check)
if id == []:
temp = re.findall(r"(^[a-zA-Z]+\s[a-zA-Z]+)", check)
if temp == []:
temp = re.findall(r"(^[a-zA-Z]+)\,\s([a-zA-Z]+)", check)
if temp != []:
Last, First = temp[0]
name_dict.append(First + ' ' + Last)
else:
name_dict.append(temp[0])
re_name = getRejectedEntries()
res = list()
for i in name_dict:
if i not in re_name:
res.append(i)
res.sort()
return res
def getEmployeesWithPhones():
path = 'Employees.txt'
path = os.path.join(DataPath, path)
with open(path, 'r') as f:
data = f.readlines()
name_dict = list()
phone_dict = list()
for check in data:
phone = re.findall(r"([0-9]{10});", check)
if phone != []:
phone = '(' + phone[0][0:3] + ') ' + phone[0][3:6] + '-' + phone[0][6:]
phone_dict.append(phone)
temp = re.findall(r"(^[a-zA-Z]+\s[a-zA-Z]+)", check)
if temp == []:
temp = re.findall(r"(^[a-zA-Z]+)\,\s([a-zA-Z]+)", check)
if temp != []:
Last, First = temp[0]
name_dict.append(First + ' ' + Last)
else:
name_dict.append(temp[0])
elif re.findall(r"([0-9]{3}-[0-9]{3}-[0-9]{4})", check) != []:
phone = re.findall(r"([0-9]{3}-[0-9]{3}-[0-9]{4})", check)[0]
phone_dict.append('(' + phone[0:3] + ') ' + phone[4:])
temp = re.findall(r"(^[a-zA-Z]+\s[a-zA-Z]+)", check)
if temp == []:
temp = re.findall(r"(^[a-zA-Z]+)\,\s([a-zA-Z]+)", check)
if temp != []:
Last, First = temp[0]
name_dict.append(First + ' ' + Last)
else:
name_dict.append(temp[0])
elif re.findall(r"(\([0-9]{3}\)\s[0-9]{3}-[0-9]{4})", check) != []:
phone_dict.append(re.findall(r"(\([0-9]{3}\)\s[0-9]{3}-[0-9]{4})", check)[0])
temp = re.findall(r"(^[a-zA-Z]+\s[a-zA-Z]+)", check)
if temp == []:
temp = re.findall(r"(^[a-zA-Z]+)\,\s([a-zA-Z]+)", check)
if temp != []:
Last, First = temp[0]
name_dict.append(First + ' ' + Last)
else:
name_dict.append(temp[0])
res = dict(zip(name_dict, phone_dict))
return res
def getEmployeesWithStates():
path = 'Employees.txt'
path = os.path.join(DataPath, path)
with open(path, 'r') as f:
data = f.readlines()
states_dict = list()
name_dict = list()
for check in data:
if re.findall(r"([A-Za-z]+\s[A-Za-z]+)\n", check) != []:
states_dict.append(re.findall(r"([A-Za-z]+\s[A-Za-z]+)\n", check)[0])
temp = re.findall(r"(^[a-zA-Z]+\s[a-zA-Z]+)", check)
if temp == []:
temp = re.findall(r"(^[a-zA-Z]+)\,\s([a-zA-Z]+)", check)
if temp != []:
Last, First = temp[0]
name_dict.append(First + ' ' + Last)
else:
name_dict.append(temp[0])
elif re.findall(r"([A-Za-z]+)\n", check) != []:
states_dict.append(re.findall(r"([A-Za-z]+)\n", check)[0])
temp = re.findall(r"(^[a-zA-Z]+\s[a-zA-Z]+)", check)
if temp == []:
temp = re.findall(r"(^[a-zA-Z]+)\,\s([a-zA-Z]+)", check)
if temp != []:
Last, First = temp[0]
name_dict.append(First + ' ' + Last)
else:
name_dict.append(temp[0])
res = dict(zip(name_dict, states_dict))
return res
def getCompleteEntries():
id = getEmployeesWithIDs()
phone = getEmployeesWithPhones()
states = getEmployeesWithStates()
res = {}
for name in id:
if name in phone.keys():
if name in states.keys():
res[name] = id[name], phone[name], states[name]
return res
<file_sep>#!/bin/bash
#######################################################
# Author: <<NAME>>
# email: <guo412>
# ID: <ee364d25>
# Date: <3/20>
#######################################################
DataPath=~ee364/DataFolder/Lab09
subpro=$DataPath"/maps/projects.dat"
subcir=$DataPath"/circuits"
ans=$(ls $subcir)
size=$(for f in $ans
do
file=$subcir"/$f"
echo $(wc -c $file)
done | sort -u)
large=$(echo $size | tail -c 12| head -c 7)
grep -E $large $subpro | sort -u | cut -f15 -d" "
<file_sep>#######################################################
# Author: <<NAME> >
# email: <<EMAIL> >
# ID: <ee364d25>
# Date: <2019/3/27>
#######################################################
import os
import sys
import csv
import re
from Lab10 import measurement
DataPath = os.path.expanduser('~ee364/DataFolder/Lab10')
def getCost(sourceZip, destinationZip):
szip = sourceZip
dzip = destinationZip
coord_path = 'coordinates.dat'
coord_path = os.path.join(DataPath, coord_path)
with open(coord_path) as file:
reader = csv.DictReader(file, delimiter = ',')
la = [row[' "latitude"'] for row in reader]
with open(coord_path) as file:
reader = csv.DictReader(file, delimiter=',')
lo = [row[' "longitude"'] for row in reader]
with open(coord_path) as file:
reader = csv.DictReader(file, delimiter=',')
zip = [row['zip code'] for row in reader]
with open(coord_path) as file:
reader = csv.DictReader(file, delimiter=',')
stateab = [row[' "state abbreviation"'] for row in reader]
with open(coord_path) as file:
reader = csv.DictReader(file, delimiter=',')
city = [row[' "city"'] for row in reader]
with open(coord_path) as file:
reader = csv.DictReader(file, delimiter=',')
state = [row[' "state"'] for row in reader]
if sourceZip not in zip:
return 0.00
if destinationZip not in zip:
return 0.00
splace = zip.index(sourceZip)
dplace = zip.index(destinationZip)
szip = (float(la[splace][2:len(la[splace]) - 1]), float(lo[splace][2:len(lo[splace]) - 1]))
dzip = (float(la[dplace][2:len(la[dplace]) - 1]), float(lo[dplace][2:len(lo[dplace]) - 1]))
cost = measurement.calculateDistance(szip,dzip)
cost = round(cost / 100,2)
return cost
def loadPackages():
pack_path = 'packages.dat'
pack_path = os.path.join(DataPath, pack_path)
with open(pack_path, 'r') as f:
f.readline()
data = f.readlines()
city = list()
source = list()
des = list()
for check in data:
tempc = re.findall(r"\"([A-Za-z]+)\"", check)
source.append(re.findall(r"([0-9]{5})\"\,",check)[0])
des.append(re.findall(r"[\"A-Za-z0-9\s\,]+([0-9]{5})\"",check)[0])
if tempc == []:
tempc = re.findall(r"\"([A-Za-z]+\s[A-Za-z]+)\"",check)
city.append(tempc[0])
cost = [0.00] * len(source)
for r in range(0, len(source)):
print(source[r], des[r])
cost[r] = getCost(str(source[r]),str(des[r]))
print(cost)
name = list()
class PackageGroup:
pass
<file_sep>#!/bin/bash
#######################################################
# Author: <<NAME>>
# email: <guo412>
# ID: <ee364d25>
# Date: <3/6>
#######################################################
DataPath=~ee364/DataFolder/Prelab09
substudent=$DataPath"/maps/students.dat"
subcir=$DataPath"/circuits"
id=$(grep -s -E $1 $substudent | cut -f2 -d"|")
ans=$(grep -lr -E $id $subcir)
d_ans=$(for f in $ans
do
echo $f | cut -d"/" -f9 |tail -c 12
done| sort -u| cut -f1 -d".")
for i in $d_ans
do
echo $i
done
<file_sep>#!/bin/bash
#######################################################
# Author: <<NAME>>
# email: <guo412>
# ID: <ee364d25>
# Date: <3/6>
#######################################################
DataPath=~ee364/DataFolder/Prelab09
substudent=$DataPath"/maps/students.dat"
cir=$(bash getCircuitsByProject.bash $1)
subcir=$DataPath"/circuits"
files=$(for f in $cir
do
file=$subcir"/circuit_$f.dat"
grep -E "[0-9]+-[0-9]" $file
done | sort -u)
(for i in $files
do
grep -E $i $substudent| cut -f1 -d"|"
done | sort -u)<file_sep>#######################################################
# Author: <<NAME>>
# email: <<EMAIL>>
# ID: <ee364d25>
# Date: <2019/4/20>
#######################################################
import os
import sys
from PyQt5.QtWidgets import QMainWindow, QApplication, QFileDialog, QGraphicsScene
from Lab12.MorphingGUI import *
from PyQt5.QtGui import QPixmap, QPainter, QBrush, QPen
from PyQt5.QtCore import Qt
import xml.etree.ElementTree as ET
import numpy as np
import imageio
import math
from Lab12 import Morphing
from scipy.spatial import Delaunay
class MorphingApp(QMainWindow, Ui_MainWindow):
def __init__(self, parent=None):
super(MorphingApp, self).__init__(parent)
self.setupUi(self)
self.LoadImg1.clicked.connect(self.loadDataleft)
self.LoadImg2.clicked.connect(self.loadDataright)
self.lineEdit.setText(str(self.Slider.value()/ 20))
self.pushButton.setEnabled(False)
self.Slider.setEnabled(False)
self.checkBox.setEnabled(False)
self.lineEdit.setEnabled(False)
self.checkBox.stateChanged.connect(self.triangle)
self.Slider.valueChanged.connect(self.Morph)
self.pushButton.clicked.connect(self.morph_img)
self.path1 = ''
self.path2 = ''
self.leftcount = 0
self.rightcount = 0
self.new_left = list()
self.new_right = list()
self.imagepathl = ''
self.imagepathr = ''
self.ratio = 0
self.ratior = 0
self.trick = False
self.finish = False
self.Img1.mousePressEvent = self.getLeft
self.Img2.mousePressEvent = self.getRight
self.keyPressEvent = self.deleteleft
self.mode = False
self.doub = False
self.de = False
# self.Img1.mouseReleaseEvent(QGraphicsSceneMouseEvent)
def deleteleft(self, event):
if self.mode == False:
return
if event.key() == Qt.Key_Backspace:
if self.leftcount > self.rightcount:
self.new_left = self.new_left[:- 1]
if len(self.new_left) == 0:
if os.path.exists(self.imagepathl + '.txt') == True:
data1 = np.loadtxt(self.imagepathl + '.txt', dtype=np.float64)
if np.size(data1, 0) >= 3:
self.triangle()
else:
pix = QPixmap(self.imagepathl)
img = QGraphicsScene()
img.addPixmap(pix)
self.Img1.setScene(img)
self.Img1.fitInView(img.sceneRect())
else:
# pix = QPixmap(self.imagepathl)
# img = QGraphicsScene()
# painter = QPainter(pix)
# painter.setBrush(QBrush(Qt.blue, Qt.SolidPattern))
# scene = self.Img1.scene()
# width_r = scene.width() / self.Img1.width()
# height_r = scene.height() / self.Img1.height()
# for i in self.new_left:
# x,y = i
# painter.drawEllipse(x * width_r - 12, y * height_r - 12, 24, 24)
# painter.end()
# img.addPixmap(pix)
# self.Img1.setScene(img)
# self.Img1.fitInView(img.sceneRect())
if len(self.new_left) == 1:
# if os.path.exists(self.imagepathl + '.txt') == True:
# data1 = np.loadtxt(self.imagepathl + '.txt', dtype=np.float64)
# if np.size(data1, 0) >= 3:
# self.triangle()
# else:
pix = QPixmap(self.imagepathl)
img = QGraphicsScene()
painter = QPainter(pix)
painter.setBrush(QBrush(Qt.blue, Qt.SolidPattern))
x,y = self.new_left[0]
painter.drawEllipse(x* self.ratio - 12,y* self.ratio - 12, 24, 24)
painter.end()
img.addPixmap(pix)
self.Img1.setScene(img)
self.Img1.fitInView(img.sceneRect())
else:
self.triangle()
self.mode = False
self.leftcount = self.leftcount - 1
self.trick = True
elif self.leftcount == self.rightcount:
self.new_right = self.new_right[:-1]
if len(self.new_right) == 0:
if os.path.exists(self.imagepathr + '.txt') == True:
data1 = np.loadtxt(self.imagepathr + '.txt', dtype=np.float64)
if np.size(data1, 0) >= 3:
self.triangle()
else:
pix = QPixmap(self.imagepathr)
img = QGraphicsScene()
img.addPixmap(pix)
self.Img2.setScene(img)
self.Img2.fitInView(img.sceneRect())
else:
# pix = QPixmap(self.imagepathr)
# img = QGraphicsScene()
# painter = QPainter(pix)
# painter.setBrush(QBrush(Qt.blue, Qt.SolidPattern))
# scene = self.Img2.scene()
# width_r = scene.width() / self.Img2.width()
# height_r = scene.height() / self.Img2.height()
# for i in self.new_right:
# x,y = i
# painter.drawEllipse(x * width_r - 12, y * height_r - 12, 24, 24)
# painter.end()
# img.addPixmap(pix)
# self.Img2.setScene(img)
# self.Img2.fitInView(img.sceneRect())
if len(self.new_right) == 1:
# if os.path.exists(self.imagepathr + '.txt') == True:
# data1 = np.loadtxt(self.imagepathr + '.txt', dtype=np.float64)
# if np.size(data1, 0) >= 3:
# self.triangle()
# else:
pix = QPixmap(self.imagepathr)
img = QGraphicsScene()
painter = QPainter(pix)
painter.setBrush(QBrush(Qt.blue, Qt.SolidPattern))
x,y = self.new_right[0]
painter.drawEllipse(x* self.ratio - 12,y* self.ratio - 12, 24, 24)
painter.end()
img.addPixmap(pix)
self.Img2.setScene(img)
self.Img2.fitInView(img.sceneRect())
else:
self.de = True
self.triangle()
self.mode = False
self.rightcount = self.rightcount - 1
nnn = self.Img1.scene()
x,y = self.new_left[len(self.new_left) - 1]
nnn.addEllipse(x * self.ratio - 12, y * self.ratio - 12,24,24,brush=QBrush(Qt.green, Qt.SolidPattern))
self.Img1.setScene(nnn)
self.Img1.fitInView(nnn.sceneRect())
nnn = self.Img2.scene()
if len(self.new_right) != 0:
x,y = self.new_right[len(self.new_right) - 1]
nnn.addEllipse(x * self.ratior , y * self.ratior ,24,24,brush=QBrush(Qt.blue, Qt.SolidPattern))
self.Img2.setScene(nnn)
self.Img2.fitInView(nnn.sceneRect())
self.doub =True
self.de = False
def loadDataleft(self):
"""
*** DO NOT MODIFY THIS METHOD! ***
Obtain a file name from a file dialog, and pass it on to the loading method. This is to facilitate automated
testing. Invoke this method when clicking on the 'load' button.
You must modify the method below.
"""
filePath, _ = QFileDialog.getOpenFileName(self, caption='Open Image file ...', filter="Image files (*.jpg *.png)")
if not filePath:
return
self.loadDataFromFile(filePath,1)
def loadDataright(self):
"""
*** DO NOT MODIFY THIS METHOD! ***
Obtain a file name from a file dialog, and pass it on to the loading method. This is to facilitate automated
testing. Invoke this method when clicking on the 'load' button.
You must modify the method below.
"""
filePath, _ = QFileDialog.getOpenFileName(self, caption='Open Image file ...', filter="Image files (*.jpg *.png)")
if not filePath:
return
self.loadDataFromFile(filePath,2)
def loadDataFromFile(self, filePath,num):
"""
Handles the loading of the data from the given file name. This method will be invoked by the 'loadData' method.
*** YOU MUST USE THIS METHOD TO LOAD DATA FILES. ***
*** This method is required for unit tests! ***
"""
##points
self.de = False
self.doub = False
self.trick = False
self.finish = False
self.path1 = ''
self.path2 = ''
self.leftcount = 0
self.rightcount = 0
self.new_left = list()
self.new_right = list()
txt_path = filePath + '.txt'
if os.path.exists(txt_path) is True:
data = np.loadtxt(txt_path, dtype=np.float64)
x = data[:,1]
y = data[:,0]
##
# hratio = width / 240
# wratio = height / 192
# pix = QPixmap(filePath).scaled(240,192, QtCore.Qt.KeepAspectRatio)
pix = QPixmap(filePath)
img1 = QGraphicsScene()
painter = QPainter(pix)
painter.setBrush(QBrush(Qt.red, Qt.SolidPattern))
for i in range(0, len(x)):
painter.drawEllipse(y[i] - 12 , x[i] - 12, 24,24)
painter.end()
img1.addPixmap(pix)
if num == 1:
self.path1 = txt_path
else:
self.path2 = txt_path
else:
pix = QPixmap(filePath)
img1 = QGraphicsScene()
# pix_new = pix.scaled(self.Img1.width(),self.Img1.height(),Qt.KeepAspectRatio)
img1.addPixmap(pix)
if num == 1:
self.imagepathl = filePath
self.Img1.setScene(img1)
self.Img1.fitInView(img1.sceneRect())
else:
self.imagepathr = filePath
self.Img2.setScene(img1)
self.Img2.fitInView(img1.sceneRect())
if self.Img1.scene() and self.Img2.scene():
self.pushButton.setEnabled(True)
self.Slider.setEnabled(True)
self.checkBox.setEnabled(True)
self.lineEdit.setEnabled(True)
def triangle(self):
if os.path.exists(self.imagepathl + '.txt') == False:
return
if self.checkBox.isChecked() is True:
data1 = np.loadtxt(self.imagepathl + '.txt', dtype=np.float64)
data2 = np.loadtxt(self.imagepathr + '.txt', dtype=np.float64)
xl = data1[:, 1]
yl = data1[:, 0]
xr = data2[:, 1]
yr = data2[:, 0]
tril = Delaunay(data1)
pointl = data1[tril.simplices]
pointr = data2[tril.simplices]
self.path1 = self.path1[0:len(self.path1) - 4]
self.path2 = self.path2[0:len(self.path2) - 4]
pix1 = QPixmap(self.imagepathl)
pix2 = QPixmap(self.imagepathr)
img1 = QGraphicsScene()
img2 = QGraphicsScene()
painter1 = QPainter(pix1)
painter2 = QPainter(pix2)
length = len(self.new_left)
if self.finish == False:
length = len(self.new_left) - 1
elif len(self.new_left) > len(self.new_right):
length = length - 1
elif self.doub == False:
length = length - 1
if self.doub == True and len(self.new_left) == 1:
length = 1
if length == len(xl):
painter1.setPen(QPen(Qt.blue,6.0, Qt.SolidLine))
painter2.setPen(QPen(Qt.blue, 6.0, Qt.SolidLine))
elif length <= 0:
painter1.setPen(QPen(Qt.red,6.0, Qt.SolidLine))
painter2.setPen(QPen(Qt.red,6.0, Qt.SolidLine))
else:
painter1.setPen(QPen(Qt.darkYellow, 6.0, Qt.SolidLine))
painter2.setPen(QPen(Qt.darkYellow, 6.0, Qt.SolidLine))
for i in range(0, len(pointl)):
painter1.drawLine(pointl[i][0][0], pointl[i][0][1], pointl[i][1][0], pointl[i][1][1])
painter1.drawLine(pointl[i][1][0], pointl[i][1][1], pointl[i][2][0], pointl[i][2][1])
painter1.drawLine(pointl[i][2][0], pointl[i][2][1], pointl[i][0][0], pointl[i][0][1])
painter2.drawLine(pointr[i][0][0], pointr[i][0][1], pointr[i][1][0], pointr[i][1][1])
painter2.drawLine(pointr[i][1][0], pointr[i][1][1], pointr[i][2][0], pointr[i][2][1])
painter2.drawLine(pointr[i][2][0], pointr[i][2][1], pointr[i][0][0], pointr[i][0][1])
painter1.end()
painter2.end()
point1 = QPainter(pix1)
point2 = QPainter(pix2)
point1.setBrush(QBrush(Qt.red, Qt.SolidPattern))
point2.setBrush(QBrush(Qt.red, Qt.SolidPattern))
for i in range(0, len(xl)):
point1.drawEllipse(yl[i] - 12, xl[i] - 12, 24, 24)
point2.drawEllipse(yr[i] - 12, xr[i] - 12, 24, 24)
if length > 0:
point1.setBrush(QBrush(Qt.blue, Qt.SolidPattern))
point2.setBrush(QBrush(Qt.blue, Qt.SolidPattern))
#for i in range(len(xl) - length, len(xl)):
# point1.drawEllipse(yl[i] - 12, xl[i] - 12, 24, 24)
# point2.drawEllipse(yr[i] - 12, xr[i] - 12, 24, 24)
leng = 0
if len(self.new_left) > len(self.new_right):
leng = len(self.new_right)
for j in range(0, len(self.new_left)):
x1, y1 = self.new_left[j]
# painter1.drawEllipse(yl[i]-12 , xl[i] - 12 , 24, 24)
# painter2.drawEllipse(yr[i] -12, xr[i] -12, 24, 24)
# for i in range(0, len(self.new_left)):
if j == len(self.new_right):
point1.setBrush(QBrush(Qt.green, Qt.SolidPattern))
point1.drawEllipse(x1 * self.ratio - 12, y1 * self.ratio - 12, 24, 24)
if self.doub == False:
x1,y1 = self.new_left[len(self.new_left) - 1]
point1.setBrush(QBrush(Qt.green, Qt.SolidPattern))
point1.drawEllipse(x1 * self.ratio - 12, y1 * self.ratio - 12, 24, 24)
for n in self.new_right:
x2, y2 = n
point2.drawEllipse(x2 * self.ratior - 12, y2 * self.ratior - 12, 24, 24)
if self.doub == False:
x2,y2 = self.new_right[len(self.new_right) - 1]
if self.de == False:
point2.setBrush(QBrush(Qt.green, Qt.SolidPattern))
point2.drawEllipse(x2 * self.ratior - 12, y2 * self.ratior - 12, 24, 24)
point1.end()
point2.end()
img1.addPixmap(pix1)
img2.addPixmap(pix2)
self.Img1.setScene(img1)
self.Img1.fitInView(img1.sceneRect())
self.Img2.setScene(img2)
self.Img2.fitInView(img2.sceneRect())
else:
pix1 = QPixmap(self.imagepathl)
pix2 = QPixmap(self.imagepathr)
img1 = QGraphicsScene()
img2 = QGraphicsScene()
self.path1 = self.path1 + '.txt'
self.path2 = self.path2 + '.txt'
data1 = np.loadtxt(self.imagepathl + '.txt', dtype=np.float64)
# data2 = np.loadtxt(self.imagepathr + '.txt', dtype=np.float64)
data2 = np.loadtxt(self.imagepathr + '.txt', dtype=np.float64)
xl = data1[:, 1]
yl = data1[:, 0]
xr = data2[:, 1]
yr = data2[:, 0]
point1 = QPainter(pix1)
point2 = QPainter(pix2)
point1.setBrush(QBrush(Qt.red, Qt.SolidPattern))
point2.setBrush(QBrush(Qt.red, Qt.SolidPattern))
length = len(self.new_left)
if self.finish == False:
length = len(self.new_left) - 1
if self.doub == True and len(self.new_left) == 1:
length = 1
for i in range(0, len(xl)):
point1.drawEllipse(yl[i] - 12, xl[i] - 12, 24, 24)
point2.drawEllipse(yr[i] - 12, xr[i] - 12, 24, 24)
if length > 0:
point1.setBrush(QBrush(Qt.blue, Qt.SolidPattern))
point2.setBrush(QBrush(Qt.blue, Qt.SolidPattern))
# for i in range(len(xl) - length, len(xl)):
# point1.drawEllipse(yl[i] - 12, xl[i] - 12, 24, 24)
# point2.drawEllipse(yr[i] - 12, xr[i] - 12, 24, 24)
leng = 0
if len(self.new_left) > len(self.new_right):
leng = len(self.new_right)
for j in range(0, len(self.new_left)):
x1, y1 = self.new_left[j]
# painter1.drawEllipse(yl[i]-12 , xl[i] - 12 , 24, 24)
# painter2.drawEllipse(yr[i] -12, xr[i] -12, 24, 24)
# for i in range(0, len(self.new_left)):
if j == len(self.new_right):
point1.setBrush(QBrush(Qt.green, Qt.SolidPattern))
point1.drawEllipse(x1 * self.ratio - 12, y1 * self.ratio - 12, 24, 24)
# point2.drawEllipse(x2 * self.ratior - 12, y2 * self.ratior - 12, 24, 24)
if self.doub == False:
x1,y1 = self.new_left[len(self.new_left) - 1]
point1.setBrush(QBrush(Qt.green, Qt.SolidPattern))
point1.drawEllipse(x1 * self.ratio - 12, y1 * self.ratio - 12, 24, 24)
for m in self.new_right:
x2, y2 = m
point2.drawEllipse(x2 * self.ratior - 12, y2 * self.ratior - 12, 24, 24)
if self.doub == False:
x2,y2 = self.new_right[len(self.new_right) - 1]
if self.de == False:
point2.setBrush(QBrush(Qt.green, Qt.SolidPattern))
#point2.setBrush(QBrush(Qt.green, Qt.SolidPattern))
point2.drawEllipse(x2 * self.ratior - 12, y2 * self.ratior - 12, 24, 24)
point1.end()
point2.end()
img1.addPixmap(pix1)
img2.addPixmap(pix2)
self.Img1.setScene(img1)
self.Img1.fitInView(img1.sceneRect())
self.Img2.setScene(img2)
self.Img2.fitInView(img2.sceneRect())
def Morph(self):
self.lineEdit.setText(str((self.Slider.value()) / 20))
def morph_img(self):
alpha = float(self.lineEdit.text())
if '.txt' not in self.path1:
self.path1 = self.path1 + '.txt'
if '.txt' not in self.path2:
self.path2 = self.path2 + '.txt'
a, b = Morphing.loadTriangles(self.imagepathl + '.txt', self.imagepathr + '.txt')
iml = imageio.imread(self.imagepathl)
imr = imageio.imread(self.imagepathr)
d = Morphing.Morpher(iml, a, imr, b)
blendImg = d.getImageAtAlpha(alpha)
blend_img = QtGui.QImage(blendImg,np.size(blendImg, 1), np.size(blendImg,0), QtGui.QImage.Format_Grayscale8)
pix = QPixmap.fromImage(blend_img)
img = QGraphicsScene()
img.addPixmap(pix)
self.Blend.setScene(img)
self.Blend.fitInView(img.sceneRect())
def getLeft(self,event):
self.doub = True
if self.leftcount > self.rightcount:
return
x = event.x()
y = event.y()
scene = self.Img1.scene()
if scene == None:
return
# width_r = scene.width() / self.Img1.width()
# height_r = scene.height() / self.Img1.height()
if scene.width() / scene.height() > self.Img1.width() / self.Img1.height():
self.ratio = scene.width() / self.Img1.width()
else:
self.ratio = scene.height() / self.Img1.height()
scener = self.Img2.scene()
if scener.width() / scener.height() > self.Img2.width() / self.Img2.height():
self.ratior = scener.width() / self.Img2.width()
else:
self.ratior = scener.height() / self.Img2.height()
scene.addEllipse(x * self.ratio -12 ,y * self.ratio -12 ,24,24,brush = QBrush(Qt.green,Qt.SolidPattern))
# #scene.addEllipse(x-5, y-5, 10, 10, brush=QBrush(Qt.green, Qt.SolidPattern))
# self.Img1.setScene(scene)
# self.Img1.fitInView(scene.sceneRect())
self.leftcount = self.leftcount + 1
if len(self.new_left) > 0 :
# pix1 = QPixmap(self.imagepathl)
# pix2 = QPixmap(self.imagepathr)
img1 = QGraphicsScene()
img2 = QGraphicsScene()
# painter1 = QPainter(pix1)
# painter2 = QPainter(pix2)
# painter1.setBrush(QBrush(Qt.blue, Qt.SolidPattern))
# painter2.setBrush(QBrush(Qt.blue, Qt.SolidPattern))
scene1 = self.Img1.scene()
scene2 = self.Img2.scene()
for i in range(0, len(self.new_left)):
x1,y1 = self.new_left[i]
x2,y2 = self.new_right[i]
# painter1.drawEllipse(x1 * width_r1 - 12, y1 * height_r1 - 12, 24, 24)
# painter2.drawEllipse(x2 * width_r2 - 12, y2 * height_r2 - 12, 24, 24)
scene1.addEllipse(x1 * self.ratio - 12 , y1 * self.ratio - 12, 24, 24, brush=QBrush(Qt.blue, Qt.SolidPattern))
scene2.addEllipse(x2 * self.ratior - 12, y2 * self.ratior - 12, 24, 24, brush=QBrush(Qt.blue, Qt.SolidPattern))
if self.checkBox.isChecked() == False:
# painter1.setBrush(QBrush(Qt.green, Qt.SolidPattern))
# painter1.drawEllipse(x * width_r1 - 12, y * height_r1 - 12, 24, 24)
# painter1.end()
# painter2.end()
# img1.addPixmap(pix1)
# img2.addPixmap(pix2)
#scene.addEllipse(x * width_r - 12, y * height_r - 12, 24, 24, brush=QBrush(Qt.green, Qt.SolidPattern))
self.Img1.setScene(scene1)
self.Img1.fitInView(scene1.sceneRect())
self.Img2.setScene(scene2)
self.Img2.fitInView(scene2.sceneRect())
else:
# painter1.end()
# painter2.end()
self.triangle()
scene = self.Img1.scene()
scene.addEllipse(x * self.ratio - 12, y * self.ratio - 12, 24, 24, brush=QBrush(Qt.green, Qt.SolidPattern))
# scene.addEllipse(x-5, y-5, 10, 10, brush=QBrush(Qt.green, Qt.SolidPattern))
self.Img1.setScene(scene)
self.Img1.fitInView(scene.sceneRect())
# self.new_left.append((x, y))
if self.trick == False:
if self.new_right != list():
with open(self.imagepathr + '.txt', 'a') as f:
xr,yr = self.new_right[len(self.new_right) - 1]
f.write('\n'+str(xr * self.ratior ) + ' ' + str(yr * self.ratior ))
if self.leftcount > self.rightcount and len(self.new_left) >= 1:
with open(self.imagepathl + '.txt', 'a') as f:
xl,yl = self.new_left[len(self.new_left) - 1]
f.write('\n'+str(xl * self.ratio) + ' ' + str(yl * self.ratio ))
# if len(self.new_left) >=3:
# self.triangle()
if self.trick == True:
self.trick = False
if len(self.new_left) >= 3:
self.triangle()
hahaha = self.Img1.scene()
hahaha.addEllipse(x* self.ratio - 12, y * self.ratio - 12,24,24,brush=QBrush(Qt.green, Qt.SolidPattern))
self.Img1.setScene(hahaha)
self.Img1.fitInView(hahaha.sceneRect())
else:
if os.path.exists(self.imagepathl + '.txt') == True:
data1 = np.loadtxt(self.imagepathl + '.txt', dtype=np.float64)
if np.size(data1, 0) >=3:
self.triangle()
hahaha = self.Img1.scene()
hahaha.addEllipse(x * self.ratio - 12, y * self.ratio - 12, 24, 24,
brush=QBrush(Qt.green, Qt.SolidPattern))
self.Img1.setScene(hahaha)
self.Img1.fitInView(hahaha.sceneRect())
self.new_left.append((x, y))
self.mode = True
def getRight(self,event):
self.doub = False
if self.rightcount == self.leftcount:
return
x = event.x()
y = event.y()
self.mode = True
scene = self.Img2.scene()
if scene == None:
return
scene.addEllipse(x * self.ratior - 12,y * self.ratior - 12,24,24,brush = QBrush(Qt.green,Qt.SolidPattern))
#scene.addEllipse(x-5, y-5, 10, 10, brush=QBrush(Qt.green, Qt.SolidPattern))
self.Img2.setScene(scene)
self.Img2.fitInView(scene.sceneRect())
self.rightcount = self.rightcount + 1
self.new_right.append((x,y))
def mouseReleaseEvent(self, a0: QtGui.QMouseEvent):
if self.leftcount == 0:
return
if self.leftcount != self.rightcount:
return
if self.mode == False:
return
# pix1 = QPixmap(self.imagepathl)
# pix2 = QPixmap(self.imagepathr)
# img1 = QGraphicsScene()
# img2 = QGraphicsScene()
# painter1 = QPainter(pix1)
# painter2 = QPainter(pix2)
# if os.path.exists(self.imagepathl + '.txt'):
# painter1.setBrush(QBrush(Qt.red, Qt.SolidPattern))
# painter2.setBrush(QBrush(Qt.red, Qt.SolidPattern))
# data1 = np.loadtxt(self.imagepathl + '.txt', dtype=np.float64)
# data2 = np.loadtxt(self.imagepathr + '.txt', dtype=np.float64)
# xl = data1[:, 1]
# yl = data1[:, 0]
# xr = data2[:, 1]
# yr = data2[:, 0]
# length = len(self.new_left)
# for i in range(0, len(xl)):
# painter1.drawEllipse(yl[i] - 12 , xl[i] - 12 , 24, 24)
# painter2.drawEllipse(yr[i] - 12, xr[i] - 12 , 24, 24)
# if length > 0:
# painter1.setBrush(QBrush(Qt.blue, Qt.SolidPattern))
# painter2.setBrush(QBrush(Qt.blue, Qt.SolidPattern))
# #for i in range(len(xl) - length, len(xl)):
# for j in range(0, len(self.new_left)):
# x1, y1 = self.new_left[j]
# x2, y2 = self.new_right[j]
# # painter1.drawEllipse(yl[i]-12 , xl[i] - 12 , 24, 24)
# # painter2.drawEllipse(yr[i] -12, xr[i] -12, 24, 24)
# # for i in range(0, len(self.new_left)):
#
# painter1.drawEllipse(x1 * self.ratio - 12, y1 * self.ratio - 12, 24, 24)
# painter2.drawEllipse(x2 * self.ratior - 12, y2 * self.ratior - 12, 24, 24)
# #painter1.setBrush(QBrush(Qt.green, Qt.SolidPattern))
# #painter1.end()
# #painter2.end()
# else:
# painter1.setBrush(QBrush(Qt.blue, Qt.SolidPattern))
# painter2.setBrush(QBrush(Qt.blue, Qt.SolidPattern))
# xl, yl = self.new_left[len(self.new_left) - 1]
# xr, yr = self.new_right[len(self.new_right) - 1]
# painter1.drawEllipse(xl * self.ratio - 12, yl * self.ratio - 12, 24, 24)
# painter2.drawEllipse(xr * self.ratior - 12, yr * self.ratior - 12, 24, 24)
# painter1.end()
# painter2.end()
# img1.addPixmap(pix1)
# img2.addPixmap(pix2)
# self.Img1.setScene(img1)
# self.Img1.fitInView(img1.sceneRect())
# self.Img2.setScene(img2)
# self.Img2.fitInView(img2.sceneRect())
self.doub =True
xl, yl = self.new_left[len(self.new_left) - 1]
xr, yr = self.new_right[len(self.new_right) - 1]
scene1 = self.Img1.scene()
scene2 = self.Img2.scene()
scene1.addEllipse(xl * self.ratior - 12, yl * self.ratior - 12, 24, 24, brush=QBrush(Qt.blue, Qt.SolidPattern))
# scene.addEllipse(x-5, y-5, 10, 10, brush=QBrush(Qt.green, Qt.SolidPattern))
scene2.addEllipse(xr * self.ratior - 12, yr * self.ratior - 12, 24, 24, brush=QBrush(Qt.blue, Qt.SolidPattern))
self.Img2.setScene(scene2)
self.Img2.fitInView(scene2.sceneRect())
self.Img1.setScene(scene1)
self.Img1.fitInView(scene1.sceneRect())
with open(self.imagepathr + '.txt', 'a') as f:
xr, yr = self.new_right[len(self.new_right) - 1]
f.write('\n'+str(xr * self.ratior) + ' ' + str(yr * self.ratior))
with open(self.imagepathl + '.txt', 'a') as f:
xl, yl = self.new_left[len(self.new_left) - 1]
f.write('\n'+str(xl * self.ratio) + ' ' + str(yl * self.ratio ))
if len(self.new_left) >= 3:
self.triangle()
self.mode = False
self.finish = True
self.trick = True
# class graphics(QGraphicsScene):
# def __init__(self, parent = None):
# super(graphics, self).__init__(parent)
# def mouseReleaseEvent(self, QGraphicsSceneMouseEvent):
# mouse = QGraphicsSceneMouseEvent
# print(mouse.x(), mouse.y())
# print(mouse.pos())
# cursor = QtGui.QCursor
# print(cursor.pos())
if __name__ == "__main__":
currentApp = QApplication(sys.argv)
currentForm = MorphingApp()
currentForm.show()
currentApp.exec_()
<file_sep>#######################################################
# Author: <<NAME> >
# email: <<EMAIL> >
# ID: <ee364d25>
# Date: <2019/2/1 >
#######################################################
import os # List of module import statements
import sys # Each one on a line
import csv
import copy
from pprint import pprint as pp
# Module level Variables. (Write this statement verbatim .)
#######################################################
DataPath = os.path.expanduser('~ee364/DataFolder/Prelab04')
def readfiles(problem, var1):
sub_tech = os.path.join(DataPath, 'maps/technicians.dat')
sub_vir = os.path.join(DataPath, 'maps/viruses.dat')
with open(sub_tech, 'r') as file: #read students.dat
file.readline()
file.readline()
data = file.readlines()
tech = [n.split() for n in data]
tech_name = [''] * len(tech)
tech_ID = [''] * len(tech)
for i in range(0, len(tech)):
tech_name[i] = tech[i][0] + ' ' + tech[i][1]
tech_ID[i] = tech[i][3]
id_name = dict(zip(tech_ID, tech_name))
name_id = dict(zip(tech_name,tech_ID))
with open(sub_vir, 'r') as file:
file.readline()
file.readline()
data = file.readlines()
vir = [m.split() for m in data]
vir_name = [''] * len(vir)
vir_id = [''] * len(vir)
vir_price = [''] * len(vir)
for j in range(0, len(vir)):
vir_name[j] = vir[j][0]
vir_id[j] = vir[j][2]
vir_price[j] = vir[j][4][1:]
vname_id = dict(zip(vir_name, vir_id))
id_vname = dict(zip(vir_id,vir_name))
id_price = dict(zip(vir_id,vir_price))
vname_price = dict(zip(vir_name, vir_price))
report_path = os.path.expanduser('~ee364/DataFolder/Prelab04/reports')
report_list = os.listdir(report_path)
report_id = copy.copy(report_list)
for a in range(0, len(report_list)):
report_id[a] = report_id[a].replace('report_','')
report_id[a] = report_id[a].replace('.dat','')
re_userid = [''] * len(report_list)
report = [''] * len(report_list)
for r in range(0, len(report_list)):
report_file = os.path.join(report_path,report_list[r])
with open(report_file) as file:
reid = file.readlines(1)
reid = [n.split() for n in reid]
re_userid[r] = reid[0][2]
file.readline()
file.readline()
file.readline()
data = file.readlines()
report[r] = [m.split() for m in data]
if problem == '1':
id = name_id[var1]
vir = set('')
for i in range(0, len(re_userid)):
if id == re_userid[i]:
for j in range(0, len(report[i])):
vir.add(report[i][j][1])
vir = list(vir)
for k in range(0, len(vir)):
vir[k] = id_vname[vir[k]]
num = [0] * len(vir)
vir_num = dict(zip(vir, num))
for m in range(0, len(re_userid)):
if id == re_userid[m]:
for n in range(0, len(report[m])):
vir_num[id_vname[report[m][n][1]]] += int(report[m][n][2])
return vir_num
elif problem == '2':
id = vname_id[var1]
tech = set('')
for i in range(0, len(report)):
for j in range(0, len(report[i])):
if id == report[i][j][1]:
tech.add(re_userid[i])
break
tech = list(tech)
for k in range(0, len(tech)):
tech[k] = id_name[tech[k]]
num = [0] * len(tech)
tech_num = dict(zip(tech, num))
for m in range(0, len(report)):
for n in range(0, len(report[m])):
if id == report[m][n][1]:
tech_num[id_name[re_userid[m]]] += int(report[m][n][2])
return tech_num
elif problem == '3':
tech_n = list(set(re_userid))
spend = [0] * len(tech_n)
for o in range(0, len(tech_n)):
vir_nu = getTechWork(id_name[tech_n[o]])
vn = list(vir_nu.keys())
nu = list(vir_nu.values())
for p in range(0, len(vir_nu)):
spend[o] += float(vname_price[vn[p]]) * float(nu[p])
spend[o] = float('%.2f' %spend[o])
for q in range(0, len(tech_n)):
tech_n[q] = id_name[tech_n[q]]
tech_spend = dict(zip(tech_n, spend))
return tech_spend
elif problem == '4':
vn = [' '] * len(vir_name)
nu = [0]* len(vir_name)
count = 0
for r in range(0, len(vir_name)):
vir_nu = getStrainConsumption(vir_name[r])
nu_temp = sum(list(vir_nu.values()))
if nu_temp > 0:
vn[count] = vir_name[r]
nu[count] = nu_temp * float(vname_price[vir_name[r]])
nu[count] = float('%.2f' %nu[count])
count = count + 1
vn = vn[0:count]
nu = nu[0:count]
virspend = dict(zip(vn,nu))
return(virspend)
elif problem == '5':
attend = list(set(re_userid))
all_tech = list(set(tech_ID))
abs_tech = set('')
for s in range(0, len(all_tech)):
if all_tech[s] not in attend:
abs_tech.add(id_name[all_tech[s]])
return abs_tech
elif problem == '6':
abs_vir = set('')
for w in range(0, len(vir_name)):
vir_nu = getStrainConsumption(vir_name[w])
nu_temp = sum(list(vir_nu.values()))
if nu_temp == 0:
abs_vir.add(vir_name[w])
return abs_vir
return
def getTechWork(techName):
number = readfiles('1', techName)
return number
def getStrainConsumption(virusName):
number = readfiles('2', virusName)
return number
def getTechSpending():
techSpend = readfiles('3', '')
return techSpend
def getStrainCost():
virSpend = readfiles('4', '')
return virSpend
def getAbsentTechs():
absent = readfiles('5', '')
return absent
def getUnusedStrains():
absent = readfiles('6', '')
return absent<file_sep># -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'MorphingGUI.ui'
#
# Created by: PyQt5 UI code generator 5.9.2
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(679, 717)
MainWindow.setMouseTracking(True)
MainWindow.setFocusPolicy(QtCore.Qt.ClickFocus)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.LoadImg1 = QtWidgets.QPushButton(self.centralwidget)
self.LoadImg1.setGeometry(QtCore.QRect(30, 10, 161, 27))
self.LoadImg1.setObjectName("LoadImg1")
self.LoadImg2 = QtWidgets.QPushButton(self.centralwidget)
self.LoadImg2.setGeometry(QtCore.QRect(390, 10, 151, 27))
self.LoadImg2.setObjectName("LoadImg2")
self.Img1 = QtWidgets.QGraphicsView(self.centralwidget)
self.Img1.setGeometry(QtCore.QRect(30, 60, 251, 192))
self.Img1.setMouseTracking(True)
self.Img1.setFocusPolicy(QtCore.Qt.ClickFocus)
self.Img1.setObjectName("Img1")
self.Img2 = QtWidgets.QGraphicsView(self.centralwidget)
self.Img2.setGeometry(QtCore.QRect(390, 60, 256, 192))
self.Img2.setMouseTracking(True)
self.Img2.setFocusPolicy(QtCore.Qt.ClickFocus)
self.Img2.setAcceptDrops(False)
self.Img2.setObjectName("Img2")
self.label = QtWidgets.QLabel(self.centralwidget)
self.label.setGeometry(QtCore.QRect(100, 270, 101, 17))
self.label.setObjectName("label")
self.label_2 = QtWidgets.QLabel(self.centralwidget)
self.label_2.setGeometry(QtCore.QRect(441, 270, 91, 20))
self.label_2.setObjectName("label_2")
self.Slider = QtWidgets.QSlider(self.centralwidget)
self.Slider.setGeometry(QtCore.QRect(120, 320, 401, 31))
self.Slider.setAutoFillBackground(False)
self.Slider.setMaximum(20)
self.Slider.setSingleStep(1)
self.Slider.setPageStep(10)
self.Slider.setOrientation(QtCore.Qt.Horizontal)
self.Slider.setTickInterval(0)
self.Slider.setObjectName("Slider")
self.label_3 = QtWidgets.QLabel(self.centralwidget)
self.label_3.setGeometry(QtCore.QRect(60, 330, 62, 17))
self.label_3.setObjectName("label_3")
self.Blend = QtWidgets.QGraphicsView(self.centralwidget)
self.Blend.setGeometry(QtCore.QRect(210, 390, 256, 192))
self.Blend.setObjectName("Blend")
self.label_4 = QtWidgets.QLabel(self.centralwidget)
self.label_4.setGeometry(QtCore.QRect(280, 600, 131, 20))
self.label_4.setObjectName("label_4")
self.pushButton = QtWidgets.QPushButton(self.centralwidget)
self.pushButton.setGeometry(QtCore.QRect(290, 630, 92, 27))
self.pushButton.setObjectName("pushButton")
self.checkBox = QtWidgets.QCheckBox(self.centralwidget)
self.checkBox.setGeometry(QtCore.QRect(280, 280, 93, 22))
self.checkBox.setObjectName("checkBox")
self.lineEdit = QtWidgets.QLineEdit(self.centralwidget)
self.lineEdit.setGeometry(QtCore.QRect(540, 320, 51, 27))
self.lineEdit.setMouseTracking(False)
self.lineEdit.setReadOnly(True)
self.lineEdit.setObjectName("lineEdit")
self.label_5 = QtWidgets.QLabel(self.centralwidget)
self.label_5.setGeometry(QtCore.QRect(120, 350, 62, 17))
self.label_5.setObjectName("label_5")
self.label_6 = QtWidgets.QLabel(self.centralwidget)
self.label_6.setGeometry(QtCore.QRect(500, 350, 62, 17))
self.label_6.setObjectName("label_6")
MainWindow.setCentralWidget(self.centralwidget)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.LoadImg1.setText(_translate("MainWindow", "Load Starting Image ..."))
self.LoadImg2.setText(_translate("MainWindow", "Load Ending Image ..."))
self.label.setText(_translate("MainWindow", "Staring Image"))
self.label_2.setText(_translate("MainWindow", "Ending Image"))
self.label_3.setText(_translate("MainWindow", "Alpha"))
self.label_4.setText(_translate("MainWindow", "Blending Result"))
self.pushButton.setText(_translate("MainWindow", "Blend"))
self.checkBox.setText(_translate("MainWindow", "Triangle"))
self.label_5.setText(_translate("MainWindow", "0.0"))
self.label_6.setText(_translate("MainWindow", "1.0"))
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
<file_sep>#######################################################
# Author: <<NAME> >
# email: <<EMAIL> >
# ID: <ee364d25>
# Date: <2019/1/26 >
#######################################################
import os # List of module import statements
import sys # Each one on a line
import csv
from pprint import pprint as pp
# Module level Variables. (Write this statement verbatim .)
#######################################################
DataPath = os.path.expanduser('~ee364/DataFolder/Prelab03')
def readcom(Components):
if Components == "R":
sub_com = os.path.join(DataPath, 'maps/resistors.dat')
elif Components == "I":
sub_com = os.path.join(DataPath, 'maps/inductors.dat')
elif Components == 'C':
sub_com = os.path.join(DataPath, 'maps/capacitors.dat')
elif Components == 'T':
sub_com = os.path.join(DataPath, 'maps/transistors.dat')
else:
return
with open(sub_com, 'r') as file: #read components.dat
file.readline()
file.readline()
file.readline()
data = file.readlines()
pro = [n.split() for n in data]
com_ID = [''] * len(pro)
price = [''] * len(pro)
for i in range(0,len(pro)):
com_ID[i] = pro[i][0]
price[i] = pro[i][1]
x = com_ID, price
return x
def readfiles(projectID, Components,problem,id2):
sub_project = os.path.join(DataPath, 'maps/projects.dat')
sub_student = os.path.join(DataPath,'maps/students.dat')
with open(sub_student, 'r') as file: #read students.dat
file.readline()
file.readline()
data = file.readlines()
stu = [n.split() for n in data]
name = [''] * len(stu)
stu_ID = [''] * len(stu)
for i in range(0, len(stu)):
name[i] = stu[i][0] + ' ' + stu[i][1]
stu_ID[i] = stu[i][3]
id_name = dict(zip(stu_ID, name))
name_id = dict(zip(name,stu_ID))
with open(sub_project, 'r') as file: #read projects.dat
file.readline()
file.readline()
data = file.readlines()
pro = [n.split() for n in data]
circuit = [''] * len(pro)
Pro_ID = [''] * len(pro)
for i in range(0,len(pro)):
circuit[i] = pro[i][0]
Pro_ID[i] = pro[i][1]
pro_id = sorted(list(set(Pro_ID))) # I really need to convert list and sets. And I will find a way to avoid this by asking TA next week or google
cir = [[' ']] * len(pro_id)
pro_cir = dict(zip(pro_id,cir))
for n in range(0, len(pro_id)):
pro_cir[pro_id[n]] = ['']
for k in range(0, len(Pro_ID)):
if pro_id[n] == Pro_ID[k]:
pro_cir[pro_id[n]].append(circuit[k])
for x in range(0, len(pro_cir)):
pro_cir[pro_id[x]] = pro_cir[pro_id[x]][1:]
if Components == "R":
sub_com = os.path.join(DataPath, 'maps/resistors.dat')
elif Components == "I":
sub_com = os.path.join(DataPath, 'maps/inductors.dat')
elif Components == 'C':
sub_com = os.path.join(DataPath, 'maps/capacitors.dat')
elif Components == 'T':
sub_com = os.path.join(DataPath, 'maps/transistors.dat')
else:
return
with open(sub_com, 'r') as file: #read components.dat
file.readline()
file.readline()
file.readline()
data = file.readlines()
pro = [n.split() for n in data]
com_ID = [''] * len(pro)
price = [''] * len(pro)
for i in range(0,len(pro)):
com_ID[i] = pro[i][0]
price[i] = pro[i][1]
cir_path = os.path.expanduser('~ee364/DataFolder/Prelab03/circuits')
cir_list = os.listdir(cir_path)
cir_com = [['']] * len(cir_list)
cir_stu = [['']] * len(cir_list)
for y in range(0, len(cir_list)):
cir_id = 'circuits/' + cir_list[y]
sub_circuit = os.path.join(DataPath,cir_id)
with open(sub_circuit, 'r') as file:
file.readline()
file.readline()
data = file.readlines()
for i in range(0, len(data) - 1):
data[i] = data[i][0:len(data[i]) - 1]
cir_com[y] = (data[data.index('Components:') + 2: len(data)])
cir_stu[y] = data[0: data.index('Components:') - 1]
for m in range(0, len(cir_com)):
for a in range(0,len(cir_com[m])):
cir_com[m][a] = cir_com[m][a][2:len(cir_com[m][a])]
if problem == 1:
if projectID not in Pro_ID:
raise ValueError("PROJECT ID NOT FOUND")
else:
cir_need = pro_cir[projectID]
com_list = [['']]
for s in range(0,len(cir_need)):
com_list.extend(cir_com[cir_list.index('circuit_' + cir_need[s] + '.dat')])
com_list = sorted(list(set(com_list[1:])))
count = 0
for com_li in com_list:
if com_li in com_ID:
count += 1
return count
elif problem == 2:
student = projectID
if student not in name:
raise ValueError("STUDENT NOT FOUND")
else:
need_id = stu_ID[name.index(student)]
com_list = ['']
for f in range(0, len(cir_stu)):
if need_id in cir_stu[f]:
com_list.extend(cir_com[f])
com_list = sorted(list(set(com_list[1:]))) #I really need to convert sets and lists
count = 0
for com_li in com_list:
if com_li in com_ID:
count += 1
return count
elif problem == 3:
student = projectID
if student not in name:
raise ValueError("STUDENT NOT FOUND")
else:
need_id = stu_ID[name.index(student)]
cir_li = ['']
for g in range(0, len(cir_stu)):
if need_id in cir_stu[g]:
cir_li.append(cir_list[g])
cir_li = cir_li[1:]
pro_id = ['']
for f in range(0, len(cir_li)):
for s in range(0, len(circuit)):
if circuit[s] in cir_li[f]:
pro_id.append(Pro_ID[s])
pro_id = pro_id[1:]
return set(pro_id)
elif problem == 4:
if projectID not in Pro_ID:
raise ValueError("PROJECT ID NOT FOUND")
else:
cir_need = pro_cir[projectID]
stu_list = ['']
for s in range(0, len(cir_need)):
stu_list.extend(cir_stu[cir_list.index('circuit_' + cir_need[s] + '.dat')])
stu_list = stu_list[1:]
for f in range(0, len(stu_list)):
stu_list[f] = id_name[stu_list[f]]
return set(stu_list)
elif problem == 5:
code1, price1 = readcom('R')
code2, price2 = readcom('I')
code3, price3 = readcom('C')
code4, price4 = readcom('T')
code1.extend(code2)
code1.extend(code3)
code1.extend(code4)
price1.extend(price2)
price1.extend(price3)
price1.extend(price4)
code = code1
price = price1
sum = [0.00] * len(pro_id)
for f in range(0, len(pro_id)):
cir_need = pro_cir[pro_id[f]]
cir_li = ['']
for s in range(0,len(cir_need)):
cir_li.extend(cir_com[cir_list.index('circuit_' + cir_need[s] + '.dat')])
cir_li = cir_li[1:]
for h in range(0,len(cir_li)):
sum[f] += float(price[code.index(cir_li[h])][1:])
sum[f] = float('%.2f' %sum[f])
cost_dict = dict(zip(pro_id,sum))
return cost_dict
elif problem == 6:
pro_set = set('')
comp = projectID
cir_li = ['']
for f in range(0,len(comp)):
for s in range(0,len(cir_com)):
if comp[f] in cir_com[s]:
cir_li.append(cir_list[s])
cir_li = cir_li[1:]
for c in range(0, len(cir_li)):
for v in range(0, len(circuit)):
if circuit[v] in cir_li[c]:
pro_set.add(Pro_ID[v])
return pro_set
elif problem == 7:
if projectID not in Pro_ID:
raise ValueError("ID1 not found")
elif id2 not in Pro_ID:
raise ValueError("ID2 NOT FOUND")
else:
cir_l1 = pro_cir[projectID]
cir_l2 = pro_cir[id2]
common = ['']
com_l1 = ['']
com_l2 = ['']
for u in range(0, len(cir_l1)):
com_l1.extend(cir_com[cir_list.index('circuit_' + cir_l1[u] + '.dat')])
com_l1 = com_l1[1:]
for o in range(0, len(cir_l2)):
com_l2.extend(cir_com[cir_list.index('circuit_' + cir_l2[o] + '.dat')])
com_l2 = com_l2[1:]
for l1 in com_l1:
if l1 in com_l2:
common.append(l1)
common = sorted(list(set(common[1:])))
return common
elif problem == 8:
coun= [0]* len(projectID)
for l in range(0, len(projectID)):
for u in range(0, len(pro_id)):
need_circuit = pro_cir[pro_id[u]]
need_com = ['']
for o in range(0, len(need_circuit)):
need_com.extend(cir_com[cir_list.index('circuit_' + need_circuit[o] + '.dat')])
need_com = need_com[1:]
coun[l] += need_com.count(projectID[l])
report = dict(zip(projectID,coun))
return report
elif problem == 9:
cirset = set('')
for l in range(0, len(projectID)):
for u in range(0,len(cir_stu)):
if name_id[projectID[l]] in cir_stu[u]:
cirset.add(cir_list[u][8:15])
return cirset
elif problem == 10:
cirset = set('')
for l in range(0,len(projectID)):
for u in range(0,len(cir_com)):
if projectID[l] in cir_com[u]:
cirset.add(cir_list[u][8:15])
return cirset
def getComponentCountByProject(projectID, componentSymbol):
count = readfiles(projectID,componentSymbol,1,'')
return count
def getComponentCountByStudent(studentName, componentSymbol):
count = readfiles(studentName,componentSymbol,2,'')
return count
def getParticipationByStudent(studentName):
pro_id = readfiles(studentName,'R',3,'')
return pro_id
def getParticipationByProject(projectID):
stu_name = readfiles(projectID,'R',4,'')
return stu_name
def getCostOfProjects():
cost = readfiles('','R',5,'')
return cost
def getProjectByComponent(ComponentIDs):
comp = sorted(list(ComponentIDs))
pro_set = readfiles(comp,'R',6,'')
return pro_set
def getCommonByProject(projectID1, projectID2):
common = readfiles(projectID1,'R', 7,projectID2)
return common
def getComponentReport(componentIDs):
componentIDs = list(componentIDs)
report = readfiles(componentIDs,'R',8,'')
return report
def getCircuitByStudent(studentNames):
studentNames = list(studentNames)
cir = readfiles(studentNames,'R',9,'')
return cir
def getCircuitByComponent(componentIDs):
componentIDs = list(componentIDs)
cir = readfiles(componentIDs,'R',10,'')
return cir<file_sep>#!/bin/bash
#######################################################
# Author: <<NAME>>
# email: <guo412>
# ID: <ee364d25>
# Date: <3/6>
#######################################################
DataPath=~ee364/DataFolder/Prelab09
substudent=$DataPath"/maps/students.dat"
cir=$(bash getCircuitsByProject.bash $1)
subcir=$DataPath"/circuits"
cir=$(bash getCircuitsByStudent.bash $1)
subpro=$DataPath"/maps/projects.dat"
ans=$(for f in $cir
do
grep -E $f $subpro |cut -f15 -d" "
done |sort -u)
for i in $ans
do
echo $i
done<file_sep>import os
import sys
import csv
DataPath = os.path.expanduser('~ee364/DataFolder/Lab02')
def getCodeFor(stateName):
path1 = 'zip.dat'
path2 = 'coordinates.dat'
zip_path = os.path.join(DataPath, path1)
coord_path = os.path.join(DataPath, path2)
with open(zip_path) as file:
reader = csv.DictReader(file, delimiter = ' ')
state = [row['State'] for row in reader]
state = state[1:]
f = open(zip_path, 'r')
zip = f.readlines()
zip = zip[2:]
for i in range(0, len(zip)):
zip[i] = zip[i][len(zip[i]) - 6:len(zip[i]) - 1]
start = 0
end = 0
for j in range(0, len(state)):
if stateName == state[j]:
start = j
break
for m in range(start, len(state)):
if stateName != state[m]:
end = m
break
zip = zip[start:end]
zip = sorted(zip)
return zip
def getMinLatitude(stateName):
zip = getCodeFor(stateName)
path = 'coordinates.dat'
coord_path = os.path.join(DataPath, path)
with open(coord_path) as file:
reader = csv.DictReader(file, delimiter = ' ')
la = [row['Latitude'] for row in reader]
la = la[1:]
min_la = max(la)
f = open(coord_path, 'r')
nzip = f.readlines()
nzip = nzip[2:]
for i in range(0, len(nzip)):
nzip[i] = nzip[i][len(nzip[i]) - 6:len(nzip[i]) - 1]
for j in range(0, len(nzip)):
if nzip[j] in zip:
if la[j] < min_la:
min_la = la[j]
min_la = float(min_la)
return min_la
def getMaxLongitude(stateName):
zip = getCodeFor(stateName)
path = 'coordinates.dat'
coord_path = os.path.join(DataPath, path)
f = open(coord_path, 'r')
nzip = f.readlines()
nzip = nzip[2:]
for i in range(0, len(nzip)):
nzip[i] = nzip[i][len(nzip[i]) - 6:len(nzip[i]) - 1]
f = open(coord_path, 'r')
lo = f.readlines()
lo = lo[2:]
for j in range(0, len(lo)):
lo[j] = lo[j][16:24]
max_lo = max(lo)
for n in range(0, len(nzip)):
if nzip[n] in zip:
if lo[n] < max_lo:
max_lo = lo[n]
max_lo = float(max_lo)
return max_lo<file_sep>import os
from uuid import UUID
from pprint import pprint as pp
from enum import Enum
import sys # Each one on a line
import csv
import copy
import re
class Rectangle:
def __init__(self, llPoint, urPoint):
self.lowerLeft = llPoint
self.upperRight = urPoint
checkx1,checky1 = llPoint
checkx2,checky2 = urPoint
if not(checkx1 < checkx2 and checky1 < checky2):
raise ValueError("the point is not valid")
def isSquare(self):
checkx1,checky1 = self.lowerLeft
checkx2,checky2 = self.upperRight
if (checkx2 - checkx1 == checky2 - checky1):
return True
else:
return False
def intersectsWith(self, rect):
checkx1,checky1 = self.lowerLeft
checkx2,checky2 = self.upperRight
rectx1, recty1 = rect.lowerLeft
rectx2, recty2 = rect.upperRight
if checkx1 < rectx1 < checkx2:
if checky1 < recty2 < checky2:
return True
elif checky1 < recty1 < checky2:
return True
elif checkx1 < rectx2 < checkx2:
if checky2 < recty2 < checky2:
return True
elif checky1 < recty1 < checky2:
return True
return False
def __eq__(self, other):
if not isinstance(other, Rectangle):
raise TypeError("This input is not a valid Rectangle instance")
x1,y1 = self.lowerLeft
x2,y2 = self.upperRight
checkx1,checky1 = other.lowerLeft
checkx2,checky2 = other.upperRight
A1 = (x2 - x1) * (y2 - y1)
A2 = (checkx2 - checkx1) * (checky2 - checky1)
return A1 == A2
class Circle:
def __init__(self, center, radius):
self.center = center
self.radius = radius
if radius <= 0:
raise ValueError("radius should be greater than 0")
def intersectsWith(self, other):
if isinstance(other, Circle):
x1, y1 = other.center
x2, y2 = self.center
disy = (y2 - y1)
disx = x2 - x1
cdis = other.radius + self.radius
if disx**2 + disy**2 < cdis**2:
return True
return False
if isinstance(other, Rectangle):
point1x, point1y = other.lowerLeft
point2x, point2y = other.upperRight
point3x, point3y = point1x, point2y
point4x, point4y = point2x, point1y
x1, y1 = self.center
ra = self.radius ** 2
dis1 = (x1 - point1x)**2 + (y1 - point1y)**2
dis2 = (x1 - point2x) ** 2 + (y1 - point2y) ** 2
dis3 = (x1 - point3x) ** 2 + (y1 - point3y) ** 2
dis4 = (x1 - point4x) ** 2 + (y1 - point4y) ** 2
if dis1 < ra:
return True
elif dis2 < ra:
return True
elif dis3 < ra:
return True
elif dis4 < ra:
return True
else:
return False<file_sep>#!/bin/bash
#######################################################
# Author: <<NAME>>
# email: <guo412>
# ID: <ee364d25>
# Date: <3/6>
#######################################################
DataPath=~ee364/DataFolder/Prelab09
substudent=$DataPath"/maps/students.dat"
subcir=$DataPath"/circuits"
ans=$(grep -lr -E $1 $subcir)
wc -w <<< "$ans"
<file_sep>#!/bin/bash
#######################################################
# Author: <<NAME>>
# email: <guo412>
# ID: <ee364d25>
# Date: <3/6>
#######################################################
DataPath=~ee364/DataFolder/Prelab09
subfile=$DataPath"/maps/projects.dat"
grep -E $1 $subfile |sort -u| cut -f5 -d" "
|
c7910a655d286a0ee8a0d510fef83abcac7e5a2b
|
[
"Markdown",
"Python",
"Shell"
] | 32
|
Python
|
ZGuo412/Software-Engineering
|
e1377d8889e65fd6d984d0bf7fa712ad74aeccfa
|
5437d82516b4e6af9e37f3f657fcc889f3e7fe71
|
refs/heads/master
|
<repo_name>cdag22/SSR-App<file_sep>/src/server/renderIso.js
import React from "react";
import { renderToString } from "react-dom/server";
import { StaticRouter } from "react-router-dom";
import StyleContext from "isomorphic-style-loader/StyleContext";
import { renderRoutes } from "react-router-config";
import Routes from "../client/components/routes/router.jsx";
import renderHTML from "./renderHTML.js";
function renderIso(url) {
let css = new Set();
const insertCss = (...styles) =>
styles.forEach(style => css.add(style._getCss()));
const reactString = renderToString(
<StyleContext.Provider value={{ insertCss }}>
<StaticRouter location={url}>
<div>{renderRoutes(Routes)}</div>
</StaticRouter>
</StyleContext.Provider>
);
return renderHTML(reactString);
}
export default renderIso;
<file_sep>/src/client/components/App.jsx
import React, { lazy, Suspense, useEffect, useState } from "react";
import withStyles from "isomorphic-style-loader/withStyles";
import s from "../assets/styles/main.scss";
import { renderRoutes } from "react-router-config";
import { Switch } from "react-router-dom";
const App = ({ route }) => {
// this is my dynamically loaded component
// let Dashboard = lazy(() => import(/* webpackChunkName: "Dashboard", webpackPreload: true */ '../Dashboard/Dashboard'));
// I use hooks to determine if ssr is done and i'm on the browser
const [isBrowser, setIsBrowser] = useState(false);
useEffect(() => {
// this is like componentDidMount
setIsBrowser(true);
}, []);
return (
<section className="page-container">
{isBrowser ? (
// if i'm in the browser i use Suspence to wait for my component
<Suspense fallback={"Loading..."}>
<Switch>{renderRoutes(route.routes)}</Switch>
</Suspense>
) : (
// else i just show a loading label
"Loading..."
)}
</section>
);
};
export default withStyles(s)(App);
<file_sep>/webpack.client.js
const path = require("path");
const Merge = require("webpack-merge");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const TerserPlugin = require("terser-webpack-plugin");
// const moduleList = ["prop-types", "react", "react-dom", "react-router-dom"];
const commonWebpack = require("./webpack.common.js");
const clientWebpack = {
entry: {
client: path.join(__dirname, "src", "client", "Index.jsx")
},
output: {
path: path.join(__dirname, "public"),
filename: "[name].bundle.js",
chunkFilename: "[name].bundle.js",
publicPath: "/"
},
plugins: [
new HtmlWebpackPlugin({
template: "src/index.ejs"
})
],
// optimization: {
// minimize: true,
// minimizer: [new TerserPlugin()],
// runtimeChunk: "single",
// splitChunks: {
// cacheGroups: {
// vendor: {
// test: new RegExp(
// `[\\/]node_modules[\\/](${moduleList.join("|")})[\\/]`
// ),
// chunks: "initial",
// name: "vendors",
// enforce: true
// }
// }
// }
// },
optimization: {
minimize: true,
minimizer: [new TerserPlugin()],
runtimeChunk: "single",
splitChunks: {
cacheGroups: {
commons: {
test: /[\\/]node_modules[\\/]/,
// cacheGroupKey here is `commons` as the key of the cacheGroup
name(module, chunks, cacheGroupKey) {
const moduleFileName = module
.identifier()
.split("/")
.reduceRight(item => item);
const allChunksNames = chunks.map(item => item.name).join("~");
return `${cacheGroupKey}-${allChunksNames}-${moduleFileName}`;
},
chunks: "all"
}
}
}
}
};
module.exports = Merge(commonWebpack, clientWebpack);
<file_sep>/webpack.server.js
const path = require("path");
const Merge = require("webpack-merge");
const NodeExternals = require("webpack-node-externals");
const commonWebpack = require("./webpack.common.js");
const serverWebpack = {
entry: {
server: path.join(__dirname, "src", "server", "index.js")
},
output: {
path: path.join(__dirname, "build"),
filename: "[name].bundle.js",
chunkFilename: "[name].bundle.js",
publicPath: "/"
},
externals: [NodeExternals()]
};
module.exports = Merge(commonWebpack, serverWebpack);
<file_sep>/src/client/components/routes/router.jsx
import App from "../app.jsx";
import Landing from "../landing.jsx";
import NotFound from "../errorPage/notFound.jsx";
export default [
{
component: App,
routes: [
{
component: Landing,
path: "/",
exact: true
},
{
component: NotFound,
path: "*"
}
]
}
];
<file_sep>/src/client/components/Landing.jsx
import React from 'react';
const Landing = ({}) => {
return (
<h1 className="page-title">Hello World</h1>
);
};
export default React;<file_sep>/src/client/Index.jsx
import React from "react";
import { hydrate } from "react-dom/server";
import { BrowserRouter } from "react-router-dom";
import StyleContext from "isomorphic-style-loader/StyleContext";
import { renderRoutes } from "react-router-config";
import Routes from "./components/routes/router.jsx";
const insertCss = (...styles) => {
const removeCss = styles.map(style => style._insertCss());
return () => removeCss.forEach(dispose => dispose());
};
hydrate(
<StyleContext.Provider value={{ insertCss }}>
<BrowserRouter>
<div>{renderRoutes(Routes)}</div>
</BrowserRouter>
</StyleContext.Provider>,
document.getElementById("root")
);
<file_sep>/webpack.dev.server.js
const Merge = require("webpack-merge");
const server = require("./webpack.server.js");
module.exports = Merge(server, {
mode: "development",
devtool: "inline-source-map"
});
|
211e7f2dec794585b72d1684a1b68c49e73dbd3d
|
[
"JavaScript"
] | 8
|
JavaScript
|
cdag22/SSR-App
|
9c8c3f6b175ec89a8a8e4af4b134091912911644
|
00432cfe6c00fd60adfdd7b80ad868c688514d54
|
refs/heads/master
|
<file_sep># Processor - teraslice_file_chunker
To install from the root of your teraslice instance.
```
npm install terascope/teraslice_file_chunker
```
# Description
This processor is used to take an incoming arrary of data and split it into reasonably sized chunks for storage by another module. It was primarily intended for use with `teraslice_hdfs_append` and can be used to write files to a single directory or with timeseries spread writes across directories by date.
# Expected Inputs
An array of JSON format records.
# Output
The output of the processor is an array of records that map a chunk of data to a file. There may be multiple chunks going to the same file and there may be chunks going to many different files.
```
[
{
filename: '/path/to/file',
data: 'data records serialized and separated by newlines.'
}
]
```
# Parameters
| Name | Description | Default | Required |
| ---- | ----------- | ------- | -------- |
| timeseries | Set to an interval to have directories named using a date field from the data records. Options: ['daily', 'monthly', 'yearly', null] | | N |
| date_field | Which field in each data record contains the date to use for timeseries. Only used if "timeseries" is also specified. | date | N |
| directory | Path to use when generating the file name. | / | N |
| filename | Filename to use. This is optional and is not recommended if the target is HDFS. If not specified a filename will be automatically chosen to reduce the occurence of concurrency issues when writing to HDFS. | | N |
| chunk_size | Size of the data chunks. Specified in bytes. A new chunk will be created when this size is surpassed. | 50000 | N |
# Job configuration example
This just generates some random sample data and puts it into a directory in HDFS.
```
{
"name": "Data Generator",
"lifecycle": "persistent",
"workers": 1,
"operations": [
{
"_op": "elasticsearch_data_generator",
"size": 5000
},
{
"_op": "teraslice_file_chunker",
"timeseries": "monthly",
"date_field": "created",
"directory": "/test/directory"
},
{
"_op": "teraslice_hdfs_append"
}
]
}
```
# Notes
Current implementation assumes incoming data is an array of JSON records so building the output data chunk consists of serializing the JSON and then joining records together with newlines.
<file_sep>'use strict';
/*
* file_chunker takes an incoming stream of records and prepares them for
* writing to a file. This is largely intended for sending data to HDFS
* but could be used for other tasks.
*
* The data is collected into chunks based on 'chunk_size' and is serialized
* to a string.
*
* The result of this operation is an array of objects mapping chunks to file
* names. There can be multiple chunks for the same filename.
* [
* { filename: '/path/to/file', data: 'the data'}
* ]
*/
var _ = require('lodash');
function newProcessor(context, opConfig, jobConfig) {
var config = context.sysconfig;
var opConfig = opConfig;
var logger = jobConfig.logger;
return function(data) {
var buckets = {};
var currentBucket;
var chunks = [];
// First we need to group the data into reasonably sized chunks as
// specified by opConfig.chunk_size
for (var i = 0; i < data.length; i++) {
var record = data[i];
var bucketName = "__single__";
// If we're grouping by time we'll need buckets for each date.
if (opConfig.timeseries) {
bucketName = formattedDate(record, opConfig);
}
if (! buckets.hasOwnProperty(bucketName)) {
buckets[bucketName] = [];
}
currentBucket = buckets[bucketName];
currentBucket.push(JSON.stringify(record));
if (currentBucket.length >= opConfig.chunk_size) {
chunks.push({
data: currentBucket.join('\n') + '\n',
filename: getFileName(bucketName, opConfig, config)
});
currentBucket = buckets[bucketName] = [];
}
}
// Handle any lingering chunks.
_.forOwn(buckets, function(bucket, key) {
if (bucket.length > 0) {
chunks.push({
data: bucket.join('\n') + '\n',
filename: getFileName(key, opConfig, config)
});
}
});
return chunks;
}
}
function formattedDate(record, opConfig) {
var offsets = {
"daily": 10,
"monthly": 7,
"yearly": 4
};
var end = offsets[opConfig.timeseries] || 10;
var date = new Date(record[opConfig.date_field]).toISOString().slice(0, end);
return date.replace(/-/gi, '.');
}
function getFileName(name, opConfig, config) {
var directory = opConfig.directory;
if (name && (name !== "__single__")) {
directory = opConfig.directory + '-' + name;
}
// If filename is specified we default to this
var filename = directory + '/' + config._nodeName;
if (opConfig.filename) {
filename = directory + '/' + opConfig.filename;
}
return filename;
}
function schema() {
return {
timeseries: {
doc: 'Set to an interval to have directories named using a date field from the data records.',
default: null,
format: ['daily', 'monthly', 'yearly', null]
},
date_field: {
doc: 'Which field in each data record contains the date to use for timeseries. Only useful if "timeseries" is also specified.',
default: 'date',
format: String
},
directory: {
doc: 'Path to use when generating the file name. Default: /',
default: '/',
format: String
},
filename: {
doc: 'Filename to use. This is optional and is not recommended if the target is HDFS. If not specified a filename will be automatically chosen to reduce the occurence of concurrency issues when writing to HDFS.',
default: '',
format: 'optional_String'
},
chunk_size: {
doc: 'Size of the data chunks. Specified in bytes. A new chunk will be created when this size is surpassed. Default: 50000',
default: 50000,
format: function(val) {
if (isNaN(val)) {
throw new Error('size parameter for elasticsearch_reader must be a number')
}
else {
if (val <= 0) {
throw new Error('size parameter for elasticsearch_reader must be greater than zero')
}
}
}
}
};
}
module.exports = {
newProcessor: newProcessor,
schema: schema
};
|
e1990b7e06226cb3f9c9d5829853805eda218423
|
[
"Markdown",
"JavaScript"
] | 2
|
Markdown
|
ts-archive/teraslice_file_chunker
|
dc1e215ec629ac39a57b76ed2135ef0a4ddcc492
|
9bb7d789ba47cfdb7d9115672d51a0ac0c2a297b
|
refs/heads/main
|
<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_parse.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: seowoo <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/04/05 01:32:31 by seowoo #+# #+# */
/* Updated: 2021/04/06 18:57:48 by seowoo ### ########.fr */
/* */
/* ************************************************************************** */
#include "ft_printf.h"
void ft_parse_flag(const char **fmt, t_ftag *tag)
{
while (**fmt == '-' || **fmt == '0')
{
if (**fmt == '-')
tag->minus = 1;
else
tag->zero = 1;
*fmt += 1;
}
}
void ft_parse_width(const char **fmt, va_list ap, t_ftag *tag)
{
int n;
if (**fmt == '*' || ft_isdigit(**fmt))
{
if (**fmt == '*')
{
n = va_arg(ap, int);
if (n < 0)
{
tag->minus = 1;
n *= -1;
}
*fmt += 1;
}
else
n = ft_atoi_printf(fmt);
tag->width = n;
}
if (tag->minus == 0 && tag->zero)
tag->padding = '0';
}
void ft_parse_precision(const char **fmt, va_list ap, t_ftag *tag)
{
if (**fmt == '*' || ft_isdigit(**fmt))
{
if (**fmt == '*')
{
tag->precision = va_arg(ap, int);
*fmt += 1;
}
else
tag->precision = ft_atoi_printf(fmt);
}
}
int ft_parse(const char **fmt, va_list ap, t_ftag *tag)
{
ft_parse_flag(fmt, tag);
ft_parse_width(fmt, ap, tag);
if (**fmt == '.' && (*fmt)++)
{
tag->dot = 1;
ft_parse_precision(fmt, ap, tag);
}
if (ft_strchr("diuxX", **fmt))
return (ft_type_num(ap, tag, **fmt));
else if (ft_strchr("c%", **fmt))
return (ft_type_char(ap, tag, **fmt));
else if (**fmt == 's')
return (ft_type_str(ap, tag));
else if (**fmt == 'p')
return (ft_type_pointer(ap, tag));
return (0);
}
<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line_bonus.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: seowlee <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/02/02 23:52:44 by seowlee #+# #+# */
/* Updated: 2021/02/04 23:53:28 by seowlee ### ########.fr */
/* */
/* ************************************************************************** */
#include "get_next_line_bonus.h"
static int split_line(char **line, char **backup, char *newline)
{
char *temp;
if (newline)
{
*newline = '\0';
*line = ft_strdup(*backup);
temp = ft_strdup(newline + 1);
free(*backup);
*backup = temp;
return (1);
}
if (*backup)
{
*line = ft_strdup(*backup);
free(*backup);
*backup = NULL;
}
else
*backup = ft_strdup("");
return (0);
}
int get_next_line(int fd, char **line)
{
char *buf;
static char *backup[OPEN_MAX];
char *newline;
int byte;
if (fd < 0 || fd > OPEN_MAX || !line || BUFFER_SIZE <= 0)
return (-1);
if (!(buf = (char *)malloc(BUFFER_SIZE + 1)))
return (-1);
if (!backup[fd])
backup[fd] = ft_strdup("");
while (!(newline = ft_strchr(backup[fd], '\n'))
&& (byte = read(fd, buf, BUFFER_SIZE)) > 0)
{
buf[byte] = '\0';
newline = ft_strjoin(backup[fd], buf);
free(backup[fd]);
backup[fd] = newline;
}
free(buf);
if (byte < 0)
return (-1);
return (split_line(line, &backup[fd], newline));
}
<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_type.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: seowoo <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/04/04 20:56:01 by seowoo #+# #+# */
/* Updated: 2021/04/06 17:11:34 by seowoo ### ########.fr */
/* */
/* ************************************************************************** */
#include "ft_printf.h"
int ft_type_num(va_list ap, t_ftag *tag, char type)
{
char *src;
int count;
int num;
src = 0;
if (tag->dot && tag->precision >= 0)
tag->padding = ' ';
num = va_arg(ap, int);
if (tag->dot && tag->precision == 0 && num == 0)
src = ft_strdup("");
else
{
if (type == 'd' || type == 'i')
src = ft_itoa_printf(num, tag);
else if (type == 'u')
src = ft_itoa_base(num, "0123456789", tag);
else if (type == 'x')
src = ft_itoa_base(num, "0123456789abcdef", tag);
else if (type == 'X')
src = ft_itoa_base(num, "0123456789ABCDEF", tag);
}
count = ft_print_len(tag, src);
free(src);
return (count);
}
int ft_type_char(va_list ap, t_ftag *tag, char type)
{
char chr;
int count;
chr = '%';
if (type == 'c')
chr = va_arg(ap, int);
count = 1;
if (tag->width > 1)
{
count += tag->width - 1;
if (tag->minus)
{
ft_putchar_fd(chr, 1);
ft_iter_putchar_fd(tag->padding, 1, tag->width - 1);
}
else
{
ft_iter_putchar_fd(tag->padding, 1, tag->width - 1);
ft_putchar_fd(chr, 1);
}
}
else
ft_putchar_fd(chr, 1);
return (count);
}
int ft_type_str(va_list ap, t_ftag *tag)
{
char *src;
char *temp;
int count;
temp = va_arg(ap, char *);
if (!temp)
temp = ft_strdup("(null)");
else
temp = ft_strdup(temp);
if (tag->dot && tag->precision >= 0)
src = ft_substr(temp, 0, tag->precision);
else
src = ft_strdup(temp);
count = ft_print_len(tag, src);
free(temp);
free(src);
return (count);
}
int ft_type_pointer(va_list ap, t_ftag *tag)
{
char *src;
char *temp;
int count;
unsigned long n;
n = va_arg(ap, unsigned long);
if (tag->dot && tag->precision == 0 && n == 0)
temp = ft_strdup("");
else
temp = ft_itoa_l_base(n, "0123456789abcdef", tag);
src = ft_strjoin("0x", temp);
count = ft_print_len(tag, src);
free(temp);
free(src);
return (count);
}
<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_printf.h :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: seowoo <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/04/06 16:11:07 by seowoo #+# #+# */
/* Updated: 2021/04/06 17:19:24 by seowoo ### ########.fr */
/* */
/* ************************************************************************** */
#ifndef FT_PRINTF_H
# define FT_PRINTF_H
# include <stdarg.h>
# include <unistd.h>
# include <stdlib.h>
# include "./libft/libft.h"
typedef struct s_ftag
{
int minus;
int zero;
int width;
int dot;
int precision;
char type;
char padding;
} t_ftag;
int ft_isspace(char c);
int ft_atoi_printf(const char **str);
int ft_get_len_base(long long n, int base);
int ft_add_len(int length, t_ftag *tag, long long n);
char *ft_itoa_printf(int n, t_ftag *tag);
char *ft_itoa_base(unsigned int n, char *base, t_ftag *tag);
char *ft_itoa_l_base(unsigned long n, char *base, t_ftag *tag);
void ft_parse_flag(const char **fmt, t_ftag *tag);
void ft_parse_width(const char **fmt, va_list ap, t_ftag *tag);
void ft_parse_precision(const char **fmt, va_list ap, t_ftag *tag);
int ft_parse(const char **fmt, va_list ap, t_ftag *tag);
void ft_iter_putchar_fd(char c, int fd, int len);
int ft_print_len(t_ftag *tag, char *src);
void ft_init(t_ftag *tag);
int ft_printf(const char *format, ...);
int ft_type_num(va_list ap, t_ftag *tag, char type);
int ft_type_char(va_list ap, t_ftag *tag, char type);
int ft_type_str(va_list ap, t_ftag *tag);
int ft_type_pointer(va_list ap, t_ftag *tag);
#endif
<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: seowlee <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/10/30 22:38:21 by seowlee #+# #+# */
/* Updated: 2020/11/04 12:01:54 by seowlee ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static int num_w(char const *s, char c)
{
int i;
int n_word;
i = 0;
n_word = 0;
while (s[i])
{
if (s[i] != c)
n_word++;
while (s[i] != c && s[i + 1])
i++;
i++;
}
return (n_word);
}
static int get_len_word(char const *s, char c)
{
int i;
int len;
i = 0;
len = 0;
while (s[i] == c)
i++;
while (s[i] != c && s[i])
{
len++;
i++;
}
return (len);
}
static int get_idx_cpy_word(char const *s, char c, char *result)
{
int j;
int k;
j = 0;
k = 0;
while (s[j] == c)
j++;
while (s[j] != c && s[j])
result[k++] = s[j++];
result[k] = '\0';
return (j);
}
static char **free_malloc(char **result)
{
int i;
i = 0;
while (result[i])
{
free(result[i]);
i++;
}
free(result);
return (NULL);
}
char **ft_split(char const *s, char c)
{
char **result;
int i;
int j;
if (s == NULL)
return (NULL);
if ((result = (char **)malloc(sizeof(char *) * (num_w(s, c) + 1))) == NULL)
return (NULL);
i = 0;
j = 0;
while (i < num_w(s, c))
{
if (s[j])
{
result[i] =
(char *)malloc(sizeof(char) * (get_len_word(&s[j], c) + 1));
if (result[i] == NULL)
return (free_malloc(result));
j += get_idx_cpy_word(&s[j], c, result[i]);
i++;
}
}
result[i] = 0;
return (result);
}
<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_printf.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: seowoo <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/04/04 22:34:09 by seowoo #+# #+# */
/* Updated: 2021/04/06 20:23:47 by seowoo ### ########.fr */
/* */
/* ************************************************************************** */
#include "ft_printf.h"
void ft_init(t_ftag *tag)
{
tag->minus = 0;
tag->zero = 0;
tag->width = 0;
tag->dot = 0;
tag->precision = 0;
tag->type = 0;
tag->padding = ' ';
}
int ft_printf(const char *format, ...)
{
va_list ap;
t_ftag tag;
int nbr_characters;
va_start(ap, format);
ft_init(&tag);
nbr_characters = 0;
while (*format)
{
if (*format != '%')
{
ft_putchar_fd(*format++, 1);
nbr_characters++;
continue;
}
format++;
nbr_characters += ft_parse(&format, ap, &tag);
format++;
ft_init(&tag);
}
va_end(ap);
return (nbr_characters);
}
<file_sep>#include "libft.h"
#include <stdio.h>
#include <string.h>
/*
** ft_atoi
*/
void test_atoi(void)
{
printf("=====test_atoi=====\n");
char *str = "125";
int num = ft_atoi(str);
printf("num : %s, atoi : %d \n", str, num);
}
/*
**ft_memmove
*/
void test_memmove(void)
{
char array[10];
ft_memset(array, 0, sizeof(array));
strcpy(array, "test");
printf("=====test_memmove=====\n");
printf("original : %s\n", array);
ft_memmove(array+2, array, ft_strlen("test"));
printf("after memmove : %s\n", array);
}
/*
** ft_strjoin
*/
void test_strjoin(void)
{
char *a = "hello ";
char *b = "goodbye";
char *joined;
joined = ft_strjoin(a, b);
printf("=====test_strjoin=====\n");
printf("joined : %s, %s %s\n", joined, a, b);
}
/*
** ft_strlcat
*/
void test_strlcat(void)
{
printf("=====test_strlcat=====\n");
char src[] = "saysomthing";
char dst[10] = "goods";
printf("return (5+11) : %zu, dst(goodssay) : %s\n", ft_strlcat(dst,src,9), dst);
//printf("return (5+11) : %u, dst(goodssay) : %s\n", strlcat(dst,src,9), dst);
}
/*
**ft_strtrim
*/
void test_strtrim(void)
{
char *text = "_!ABCDEFG#";
char *set = "#A!_\0";
char *res = ft_strtrim(text, set);
printf("=====test_strtrim=====\n");
printf("%s\n", res);
}
/*
**ft_split
*/
int test_split(void)
{
char *s1 = "The.Little.Prince";
char c = '.';
char **result = ft_split(s1, c);
printf("split result = %p\n", result);
for (int i = 0; result[i]; ++i) {
printf("%d -> %s\n", i, result[i]);
free(result[i]);
}
free(result);
result = 0;
printf("==\n");
result = ft_split("cabcde", 'c');
printf("split result = %p\n", result);
for (int i = 0; result[i]; ++i) {
printf("%d -> %s\n", i, result[i]);
free(result[i]);
}
free(result);
result = 0;
printf("==\n");
result = ft_split("cccc", 'c');
printf("split result = %p\n", result);
for (int i = 0; result[i]; ++i) {
printf("%d -> %s\n", i, result[i]);
free(result[i]);
}
free(result);
result = 0;
printf("==\n");
result = ft_split("The Little Prince", ' ');
printf("split result = %p\n", result);
for (int i = 0; result[i]; ++i) {
printf("%d -> %s\n", i, result[i]);
free(result[i]);
}
free(result);
result = 0;
printf("==\n");
return (1);
}
/*
**ft_itoa
*/
void test_itoa(void)
{
printf("=====test_itoa=====\n");
int s = 0;
char *result = ft_itoa(s);
printf("%d, %s\n", s, result);
s = 1;
result = ft_itoa(s);
printf("%d, %s\n", s, result);
s = INT_MAX;
result = ft_itoa(s);
printf("%d, %s\n", s, result);
s = INT_MIN;
result = ft_itoa(s);
printf("%d, %s\n", s, result);
}
/*
**ft_putnbr_fd
*/
void test_putnbr_fd(void)
{
printf("=====test_putnbr_fd=====\n");
ft_putnbr_fd(152,1);
ft_putnbr_fd(-152,1);
ft_putnbr_fd(-2147483648,1);
}
int main(void)
{
/*
** ft_strjoin
*/
test_atoi();
/*
**ft_memmove
*/
test_memmove();
/*
** ft_strjoin
*/
test_strjoin();
/*
** ft_strlcat
*/
test_strlcat();
/*
**ft_strtrim
*/
test_strtrim();
/*
**ft_split
*/
test_split();
/*
**ft_itoa
*/
test_itoa();
/*
**ft_putnbr_fd
*/
test_putnbr_fd();
}
<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line.h :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: seowlee <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/02/01 13:45:43 by seowlee #+# #+# */
/* Updated: 2021/02/04 23:58:13 by seowlee ### ########.fr */
/* */
/* ************************************************************************** */
#ifndef GET_NEXT_LINE_H
# define GET_NEXT_LINE_H
# include <unistd.h>
# include <stdlib.h>
# include <limits.h>
# ifndef BUFFER_SIZE
# define BUFFER_SIZE 1024
# endif
int get_next_line(int fd, char **line);
char *ft_strdup(const char *s);
size_t ft_strlen(const char *str);
char *ft_strjoin(char const *s1, char const *s2);
char *ft_strchr(const char *s, int c);
#endif
<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_print_len.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: seowoo <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/04/06 15:55:26 by seowoo #+# #+# */
/* Updated: 2021/04/06 16:23:27 by seowoo ### ########.fr */
/* */
/* ************************************************************************** */
#include "ft_printf.h"
void ft_iter_putchar_fd(char c, int fd, int len)
{
while (len-- > 0)
ft_putchar_fd(c, fd);
}
int ft_print_len(t_ftag *tag, char *src)
{
int count;
int ws_len;
count = ft_strlen(src);
ws_len = tag->width - count;
if (ws_len > 0)
{
count += ws_len;
if (tag->minus)
{
ft_putstr_fd(src, 1);
ft_iter_putchar_fd(tag->padding, 1, ws_len);
}
else
{
if (src[0] == '-' && tag->padding == '0')
ft_putchar_fd(*src++, 1);
ft_iter_putchar_fd(tag->padding, 1, ws_len);
ft_putstr_fd(src, 1);
}
}
else
ft_putstr_fd(src, 1);
return (count);
}
<file_sep># **************************************************************************** #
# #
# ::: :::::::: #
# Makefile :+: :+: :+: #
# +:+ +:+ +:+ #
# By: seowlee <<EMAIL>> +#+ +:+ +#+ #
# +#+#+#+#+#+ +#+ #
# Created: 2020/11/08 22:11:55 by seowlee #+# #+# #
# Updated: 2020/11/10 13:21:57 by seowlee ### ########.fr #
# #
# **************************************************************************** #
NAME = libft.a
CC = gcc
CFLAGS = -Wall -Wextra -Werror
AR = ar rcs
RM = rm -f
SRCS = ft_memset.c ft_bzero.c ft_memcpy.c ft_memccpy.c ft_memmove.c ft_memchr.c \
ft_memcmp.c ft_strlen.c ft_strlcpy.c ft_strlcat.c ft_strchr.c ft_strrchr.c \
ft_strnstr.c ft_strncmp.c ft_atoi.c ft_isalpha.c ft_isdigit.c ft_isalnum.c \
ft_isascii.c ft_isprint.c ft_toupper.c ft_tolower.c ft_calloc.c ft_strdup.c \
ft_substr.c ft_strjoin.c ft_strtrim.c ft_split.c ft_itoa.c ft_strmapi.c \
ft_putchar_fd.c ft_putstr_fd.c ft_putendl_fd.c ft_putnbr_fd.c
SRCS_B = ft_lstnew.c ft_lstadd_front.c ft_lstsize.c ft_lstlast.c ft_lstadd_back.c \
ft_lstdelone.c ft_lstclear.c ft_lstiter.c ft_lstmap.c
OBJS = $(SRCS:.c=.o)
OBJS_B = $(SRCS_B:.c=.o)
.c.o:
$(CC) $(CFLAGS) -c $< -o $@
$(NAME): $(OBJS)
$(AR) $(NAME) $(OBJS)
all: $(NAME)
bonus: $(OBJS_B)
$(AR) $(NAME) $(OBJS_B)
clean:
$(RM) $(OBJS) $(OBJS_B)
fclean: clean
$(RM) $(NAME)
re: fclean all
.PHONY: all bonus clean fclean re
<file_sep>#include <stdio.h>
#include "ft_printf.h"
int main(void)
{
int i = 12345;
printf("printf i : %.7d \n", i);
ft_printf("ft i : %.7d \n", i);
printf("printf %*c \n", -5, 'a');
ft_printf("ftprin %*c \n", -5, 'a');
printf("printf %s \n", "abcde");
ft_printf("ftprin %s\n", "abcde");
printf("printf %s \n", NULL);
ft_printf("ftprin %s \n", NULL);
printf("printf %7u \n", 12345);
ft_printf("ftprin %7u \n", 12345);
printf("printf %3x \n", 768955);
ft_printf("ftprin %3x\n", 768955);
printf("printf %7x \n", 768955);
ft_printf("ftprin %7x \n", 768955);
printf("printf %5% \n");
ft_printf("ftprin %5%\n");
}<file_sep># 42Seoul_42cursus
42Seoul_42cursus
<file_sep>#include "get_next_line.h"
#include <stdio.h>
#include <fcntl.h>
int main(void)
{
char *line;
int fd;
int res;
fd = open("ttest", O_RDONLY);
while ((res = get_next_line(fd, &line)) > 0)
{
printf("line : %s\n", line);
printf("return value : %d\n", res);
free(line);
}
printf("line : %s\n", line);
printf("return value : %d\n", res);
free(line);
return (0);
}
<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_itoa_printf.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: seowoo <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/04/05 02:31:04 by seowoo #+# #+# */
/* Updated: 2021/04/06 17:14:23 by seowoo ### ########.fr */
/* */
/* ************************************************************************** */
#include "ft_printf.h"
int ft_get_len_base(long long n, int base)
{
int len;
len = 0;
if (n == 0)
return (1);
while (n != 0)
{
len++;
n = n / base;
}
return (len);
}
int ft_add_len(int length, t_ftag *tag, long long n)
{
if (length < tag->precision)
length = tag->precision;
if (n < 0)
length += 1;
return (length);
}
char *ft_itoa_printf(int n, t_ftag *tag)
{
long long num;
int len;
char *str;
num = n;
len = ft_get_len_base(num, 10);
len = ft_add_len(len, tag, num);
str = (char *)ft_calloc(len + 1, 1);
if (!str)
return (0);
if (num < 0)
{
str[0] = '-';
num *= -1;
}
str[len--] = 0;
while (1)
{
if (str[len] == '-' || len < 0)
break ;
str[len--] = num % 10 + '0';
num /= 10;
}
return (str);
}
char *ft_itoa_base(unsigned int n, char *base, t_ftag *tag)
{
long long num;
int len;
int base_len;
char *str;
num = n;
base_len = ft_strlen(base);
len = ft_get_len_base(num, base_len);
if (len < tag->precision)
len = tag->precision;
str = (char *)malloc(sizeof(char) * (len + 1));
if (!str)
return (0);
if (num == 0)
str[0] = '0';
str[len--] = 0;
while (len >= 0)
{
str[len--] = base[num % base_len];
num /= base_len;
}
return (str);
}
char *ft_itoa_l_base(unsigned long n, char *base, t_ftag *tag)
{
long long num;
int len;
int base_len;
char *str;
num = n;
base_len = ft_strlen(base);
len = ft_get_len_base(num, base_len);
if (len < tag->precision)
len = tag->precision;
str = (char *)malloc(sizeof(char) * (len + 1));
if (!str)
return (0);
if (num == 0)
str[0] = '0';
str[len--] = 0;
while (len >= 0)
{
str[len--] = base[num % base_len];
num /= base_len;
}
return (str);
}
<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_strnstr.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: seowlee <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/10/04 11:51:50 by seowlee #+# #+# */
/* Updated: 2020/10/30 14:16:06 by seowlee ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
char *ft_strnstr(const char *big, const char *little, size_t len)
{
size_t little_len;
size_t big_len;
size_t len2;
if (*little == '\0')
return ((char *)big);
little_len = ft_strlen(little);
big_len = ft_strlen(big);
if (big_len < little_len || len < little_len)
return (0);
len2 = big_len > len ? len : big_len;
while (len2 >= little_len)
{
len2--;
if (!ft_memcmp(big, little, little_len))
return ((char *)big);
big++;
}
return (0);
}
<file_sep># **************************************************************************** #
# #
# ::: :::::::: #
# Makefile :+: :+: :+: #
# +:+ +:+ +:+ #
# By: seowoo <<EMAIL>> +#+ +:+ +#+ #
# +#+#+#+#+#+ +#+ #
# Created: 2021/04/06 16:10:35 by seowoo #+# #+# #
# Updated: 2021/04/06 18:01:12 by seowoo ### ########.fr #
# #
# **************************************************************************** #
NAME = libftprintf.a
LIBFTDIR = ./libft
LIBFTFILE = libft.a
CC = gcc
CFLAGS = -Wall -Wextra -Werror
AR = ar rcs
RM = rm -f
SRCS = ft_atoi_printf.c \
ft_itoa_printf.c \
ft_parse.c \
ft_print_len.c \
ft_printf.c \
ft_type.c
SRCS_B =
OBJS = $(SRCS:.c=.o)
OBJS_B = $(SRCS_B:.c=.o)
$(NAME): $(OBJS)
make -C $(LIBFTDIR)
cp $(LIBFTDIR)/$(LIBFTFILE) $(NAME)
$(AR) $(NAME) $(OBJS)
all: $(NAME)
bonus: $(OBJS_B)
$(AR) $(NAME) $(OBJS_B)
clean:
make -C $(LIBFTDIR) clean
$(RM) $(OBJS) $(OBJS_B)
fclean: clean
make -C $(LIBFTDIR) fclean
$(RM) $(NAME)
re: fclean all
.PHONY: all bonus clean fclean re
|
4756a78ea1377f99db56f3c63044f4019d6365e0
|
[
"Markdown",
"C",
"Makefile"
] | 16
|
C
|
seowooo/42Seoul_42cursus
|
8d9fd8fd6f70f0e07194f1c76d4bb9086ed36e58
|
c6b9cf2d06cc1f9f002d7ab2c4d2d17e95dadb54
|
refs/heads/master
|
<file_sep>package com.dao;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.dbutil.*;
public class LoginDao {
public int checkUser(final String u_name,final String u_pwd){
String strSQL = "select * from user where u_name=? and u_pwd=?";
//简历数据库连接
DBConnect dbcon = new DBConnect();
ResultSet rs = dbcon.execQuery(strSQL, new Object[]{u_name,u_pwd});
try{
rs.next();
return rs.getInt("u_id");
}catch(SQLException e){
e.printStackTrace();
return -1;
}finally{
dbcon.closeCon();
}
}
public String checkUserNickname(final int u_id){
String strSQL = "select * from user where u_id = ?";
DBConnect dbcon = new DBConnect();
ResultSet rs = dbcon.execQuery(strSQL, new Object[]{u_id});
try{
rs.next();
return rs.getString("u_nickname");
}catch(SQLException e){
e.printStackTrace();
return null;
}finally{
dbcon.closeCon();
}
}
//得到用户的所在地
public String checkUserPosition(final int u_id){
String strSQL = "select * from user where u_id = ?";
DBConnect dbcon = new DBConnect();
ResultSet rs = dbcon.execQuery(strSQL, new Object[]{u_id,});
try{
rs.next();
return rs.getString("u_position");
}catch(SQLException e){
e.printStackTrace();
return null;
}finally{
dbcon.closeCon();
}
}
}
<file_sep>package com.po;
public class Mood {
int u_id;
String m_date;
String m_images;
String m_content;
int m_comment_num;
int m_transmit_num;
String u_m_name;
String m_u_images;
public int getU_id() {
return u_id;
}
public void setU_id(int uId) {
u_id = uId;
}
public String getM_date() {
return m_date;
}
public void setM_date(String mDate) {
m_date = mDate;
}
public String getM_images() {
return m_images;
}
public void setM_images(String mImages) {
m_images = mImages;
}
public String getM_content() {
return m_content;
}
public void setM_content(String mContent) {
m_content = mContent;
}
public int getM_comment_num() {
return m_comment_num;
}
public void setM_comment_num(int mCommentNum) {
m_comment_num = mCommentNum;
}
public int getM_transmit_num() {
return m_transmit_num;
}
public void setM_transmit_num(int mTransmitNum) {
m_transmit_num = mTransmitNum;
}
int m_id;
public int getM_id() {
return m_id;
}
public void setM_id(int m_id) {
this.m_id = m_id;
}
public String getM_u_images() {
return m_u_images;
}
public void setM_u_images(String m_u_images) {
this.m_u_images = m_u_images;
}
public String getU_m_name() {
return u_m_name;
}
public void setU_m_name(String uMName) {
u_m_name = uMName;
}
}
<file_sep>package com.dao;
import java.sql.SQLException;
import java.util.List;
import javax.servlet.ServletContext;
import com.dbutil.*;
import com.po.*;
public class FacesDao extends DaoSupport{
}
<file_sep>CLASS_NAME = com.mysql.jdbc.Driver
DATABASE_URL = jdbc:mysql
SERVER_IP = localhost
SERVER_PORT = 3306
DATABASE_SID = myblog
USERNAME = root
PASSWORD = <PASSWORD> <file_sep>package com.dao;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.dbutil.*;
import com.po.*;
public class CollectMoodDao {
public boolean collectMood(Collect collect){
String m_content = null;
//获得要收藏的微博的id
int u_id = collect.getU_id();
int m_id = collect.getM_id();
String querySQL = "select m_content from mood where m_id=?";
DBConnect dbcon = new DBConnect();
ResultSet rs = dbcon.execQuery(querySQL, new Object[]{m_id});
try{
rs.next();
m_content = rs.getString("m_content");
}catch(SQLException e){
e.printStackTrace();
}
String co_date = collect.getCo_date();
String strSQL = "insert into collect values(null,?,?,?)";
int affectedRows = dbcon.execOther(strSQL, new Object[]{u_id,m_id,co_date});
dbcon.closeCon();
return affectedRows > 0 ? true : false;
}
}
<file_sep>package com.po;
public class Faces {
private int mf_id;
private String mf_imgSrc;
private String mf_comment;
private String mf_title;
public int u_id;
public int getMf_id() {
return mf_id;
}
public void setMf_id(int mf_id) {
this.mf_id = mf_id;
}
public String getMf_imgSrc() {
return mf_imgSrc;
}
public void setMf_imgSrc(String mf_imgSrc) {
this.mf_imgSrc = mf_imgSrc;
}
public String getMf_comment() {
return mf_comment;
}
public void setMf_comment(String mf_comment) {
this.mf_comment = mf_comment;
}
public String getMf_title() {
return mf_title;
}
public void setMf_title(String mf_title) {
this.mf_title = mf_title;
}
public int getU_id() {
return u_id;
}
public void setU_id(int u_id) {
this.u_id = u_id;
}
}
<file_sep>package com.dbutil;
import java.io.IOException;
import java.util.Properties;
public class DBConfig {
private static Properties prop = new Properties();
static{
try{
//加载配置文件DBCconfig
prop.load(DBConfig.class.getResourceAsStream("DBConfig.properties"));
}catch(IOException e){
e.printStackTrace();
}
}
//设置常量
public static final String CLASS_NAME = prop.getProperty("CLASS_NAME");
public static final String DATABASE_URL = prop.getProperty("DATABASE_URL");
public static final String SERVER_IP = prop.getProperty("SERVER_TP");
public static final String SERVER_PORT = prop.getProperty("SERVER_PORT");
public static final String DATABASE_SID = prop.getProperty("DATABASE_SID");
public static final String USERNAME = prop.getProperty("USERNAME");
public static final String PASSWORD = <PASSWORD>("<PASSWORD>");
}
<file_sep>package com.test;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;
public class propertyTest {
/*java流的详解
* 按流向分 输入流 程序可以从中读取数据的流
* 输出流 程序能向其中写入数据的流
* 字节流 以字节为单位的流
* 字符流 以字符为单位的流
*
* 字节 一个等于八个bit位 每个bit两个状态 0 1
* 一班英文字符一个字节 中文是两个字节
*
* 节点流 用于直接操作目标设备的流
* 过滤流 对一个已经存在的流的连接和封装
*
* InputStream:继承自InputStream的流都是向程序中输入数据 字节单位
* OutputSteam ..... 程序向外写出数据 字节单位
* Reader 继承自Reader的都是 向程序中输入 单位是字符
* Writer 写出 字符
*
*
*
*
*
*
*
*
*
* */
//读取一个条目的信息
public static String readValue(String filePath,String key){
Properties prop = new Properties();
try{
InputStream in = new BufferedInputStream(new FileInputStream(filePath));
prop.load(in);
String value = prop.getProperty(key);
System.out.println(key+"ddddddd"+value);
return value;
}catch(Exception e){
e.printStackTrace();
return null;
}
}
//写入信息
public static void writeProperties(String filePath,String parameterName,String parameterValue){
Properties prop = new Properties();
try{
InputStream in = new FileInputStream(filePath);
prop.load(in);//读取属性列表
OutputStream out = new FileOutputStream(filePath);
prop.setProperty(parameterName, parameterValue);
prop.store(out, "Update"+parameterName+"value");
}catch(IOException e){
e.printStackTrace();
}
}
}
<file_sep>package com.dbutil;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.beanutils.BeanUtils;
public class DaoSupport {
private Connection getConnection(){
try{
Class.forName(DBConfig.CLASS_NAME);
String url = DBConfig.DATABASE_URL+"://"+DBConfig.SERVER_IP+":"+DBConfig.SERVER_PORT+"/"+DBConfig.DATABASE_SID +"?autoReconnect=true&useUnicode=true&characterEncoding=utf-8";
return DriverManager.getConnection(url,DBConfig.USERNAME,DBConfig.PASSWORD);
}catch(Exception e){
e.printStackTrace();
}
return null;
}
protected static String buildOrderby(LinkedHashMap<String, String> orderby){
StringBuilder orderbyql = new StringBuilder("");
if(orderby !=null && orderby.size() > 0){
orderbyql.append(" order by ");
for(String key : orderby.keySet()){
orderbyql.append(key).append(" ").append(orderby.get(key)).append(",");
}
return orderbyql.toString();
}
}
}
|
dc389954d9c9abbaee66f38db6ef2332da29778f
|
[
"Java",
"INI"
] | 9
|
Java
|
chunmu/blog
|
72a45d734faaa7885146298255da2c3d017dffd0
|
07714ee1c85c1ef6e4df27ecacc135510ba2346f
|
refs/heads/master
|
<file_sep>// Create Main Class
function Person(name, salary){
this.name = name || 'Anonimno';
this.salary = salary || 0;
}
Person.prototype.GetSalary = function(){
return this.salary;
}
// Create sub class
function Employee(obj){
Person.call(this, obj.name, obj.salary);
}
Employee.prototype = Object.create(Person.prototype);
Employee.prototype.contructor = Employee;
function Admin(obj){
Person.call(this, obj.name, obj.salary);
}
Admin.prototype = Object.create(Person.prototype);
Admin.prototype.contructor = Admin;
// variables to use within ajax call
var html ='',
mainC = document.getElementById("mainContent"),
sumEmployees = 0, // to count employees
sumAdmin = 0; // to count Admin
// AJAX call
function callJson(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
obj = JSON.parse(xmlhttp.responseText);
for (var name in obj[0]) {
html += '<div class="box">'
html += '<h1>'+name+'</h1>';
html += '<div class="emBox">';
newobj = eval('{' + name + '}');//turn the string into a object
for(var data in obj[0][name]){
// create instances of Employee or Admin
var newEmployee = new newobj({
name:obj[0][name][data]["name"],
salary:obj[0][name][data]["salary"]
});
if(newEmployee instanceof Employee){
sumEmployees = sumEmployees + newEmployee.GetSalary();
html += '<p class="empl"><strong>Name: </strong>'+ newEmployee.name + '<strong> Salary: </strong>$' + newEmployee.GetSalary() + '</p>';
}else if(newEmployee instanceof Admin){
sumAdmin = sumAdmin + newEmployee.GetSalary();
html += '<p class="empl admin"><strong>Name: </strong>'+ newEmployee.name + '<strong> Salary: </strong>$' + newEmployee.GetSalary() + '</p>';
}
}
html += '</div>';
var total = (name == 'Employee' ? sumEmployees : sumAdmin);
html += '<p class="total">Total Salaries: $'+ total + '</p>';
html += '</div>'
}
mainC.innerHTML = html;
}
}
var newsEmployee = 'json/employees.json';
xmlhttp.open("GET", newsEmployee, true);
xmlhttp.send();
}
callJson();
<file_sep>Object
======
Practice OOP Javascript
|
5a6dcd0bfb97e664163bd5c40b8e75a96b07dce7
|
[
"JavaScript",
"Markdown"
] | 2
|
JavaScript
|
mesvil7/Object
|
b87c8d2e453dd8776da0ee1215327b4b68b5287b
|
d77e40941064f35cf3f95fead4f5a17b5e778372
|
refs/heads/master
|
<repo_name>SteevJ/ColorSlide<file_sep>/Grid.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Grid : MonoBehaviour {
public static Transform[,] grid = new Transform[4, 4];
public static Vector2 roundVec2(Vector2 v)
{
return new Vector2(Mathf.Round(v.x), Mathf.Round(v.y));
}
public static void printGrid()
{
string[,] textArr = new string[1, 4];
for (int y = 0; y < 4; y++)
{
textArr[0, y] = y + "\t";
for (int x = 0; x < 4; x++)
if (grid[x, y] == null)
textArr[0, y] += "0";
else
textArr[0, y] += "1";
// Debug.Log(textArr[0, y]);
}
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}
<file_sep>/piece.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class piece : MonoBehaviour {
int pieceSize;
int gridSize;
public int lastPressed = 0;
float xMin;
float xMax;
float yMin;
float yMax;
float blocksize = 3.0f;
bool active = true;
bool inBounds()
{
if (transform.position.x < xMin || transform.position.x > xMax || transform.position.y < yMin || transform.position.y > yMax)
{
return false;
}
return true;
}
bool isValidGridPos()
{
Vector2 v = transform.position;
// Debug.Log("Transform:" + ((v.x - xMin) / pieceSize).ToString() + " " + (((gridSize-1) - (v.y - yMin) / pieceSize)).ToString());
if (!inBounds())
return false;
if (Grid.grid[(int)((v.x - xMin) / pieceSize), (int)(((gridSize-1)-(v.y - yMin) / pieceSize))] != null)
return false;
return true;
}
void updateGrid()
{
for (int y = 0; y < gridSize; y++)
for (int x = 0; x < gridSize; x++)
if (Grid.grid[x, y] != null)
if (Grid.grid[x, y] == transform)
Grid.grid[x, y] = null;
Vector2 v = transform.position;
Grid.grid[(int)((v.x - xMin) / pieceSize), (int)(((gridSize - 1) - (v.y - yMin) / pieceSize))] = transform;
}
// Use this for initialization
void Start () {
pieceSize = 3;
gridSize = 4;
xMin = 23.5f;
xMax = xMin + (gridSize - 1) * pieceSize;
yMin = 10.5f;
yMax = yMin + (gridSize - 1) * pieceSize;
}
// Update is called once per frame
void Update () {
manager managerInst = FindObjectOfType<manager>();
if (Input.GetKeyDown(KeyCode.UpArrow))
{
lastPressed = 2;
// Debug.Log(lastPressed);
transform.position += new Vector3(0, 3, 0);
while (isValidGridPos())
transform.position += new Vector3(0, 3, 0);
transform.position -= new Vector3(0, 3, 0);
updateGrid();
// Grid.printGrid();
if (active)
{
managerInst.spawnNext(lastPressed);
active = false;
}
}
if (Input.GetKeyDown(KeyCode.RightArrow))
{
lastPressed = 3;
// Debug.Log(lastPressed);
transform.position += new Vector3(3, 0, 0);
while (isValidGridPos())
transform.position += new Vector3(3, 0, 0);
transform.position -= new Vector3(3, 0, 0);
updateGrid();
// Grid.printGrid();
if (active)
{
managerInst.spawnNext(lastPressed);
active = false;
}
}
if (Input.GetKeyDown(KeyCode.DownArrow))
{
lastPressed = 0;
// Debug.Log(lastPressed);
transform.position += new Vector3(0, -3, 0);
while (isValidGridPos())
transform.position += new Vector3(0, -3, 0);
transform.position -= new Vector3(0, -3, 0);
updateGrid();
// Grid.printGrid();
if (active)
{
managerInst.spawnNext(lastPressed);
active = false;
}
}
if (Input.GetKeyDown(KeyCode.LeftArrow))
{
lastPressed = 1;
// Debug.Log(lastPressed);
transform.position += new Vector3(-3, 0, 0);
while (isValidGridPos())
transform.position += new Vector3(-3, 0, 0);
transform.position -= new Vector3(-3, 0, 0);
updateGrid();
// Grid.printGrid();
if (active)
{
managerInst.spawnNext(lastPressed);
active = false;
}
}
}
}
<file_sep>/manager.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class manager : MonoBehaviour {
public GameObject[] pieces;
public void spawnNext(int side)
{
int randColor = Random.Range(0, pieces.Length);
Vector3 spawnLoc = new Vector3(0, 0, 0);
if (side == 0)
{
// x = :, y = 0
spawnLoc.Set(23.5f + (3 * randPos(0)), 19.5f, 0.0f);
}
else if (side == 1)
// x = 3, y = :
spawnLoc.Set(32.5f, 19.5f - (3 * randPos(1)), 0.0f);
else if (side == 2)
// x = :, y = 3
spawnLoc.Set(23.5f + (3 * randPos(2)), 10.5f, 0.0f);
else
// x = 0, y = :
spawnLoc.Set(23.5f, 19.5f - (3 * randPos(3)), 0.0f);
Instantiate(pieces[randColor], spawnLoc, Quaternion.identity);
}
int randPos(int direction)
{
int y = 0;
List<int> posList = new List<int>();
switch (direction)
{
case 0:
for (int i = 0; i < 4; i++)
{
if (Grid.grid[i, y] == null)
posList.Add(i);
}
break;
case 1:
y = 3;
for (int i = 0; i < 4; i++)
{
if (Grid.grid[y, i] == null)
posList.Add(i);
}
break;
case 2:
y = 3;
for (int i = 0; i < 4; i++)
{
if (Grid.grid[i, y] == null)
posList.Add(i);
}
break;
case 3:
for (int i = 0; i < 4; i++)
{
if (Grid.grid[y, i] == null)
posList.Add(i);
}
break;
}
// string boi = "";
// for (int i = 0; i < posList.Count; i++)
// {
// boi += " " + posList[i];
// }
// Debug.Log(boi);
int test = Random.Range(0, posList.Count);
Debug.Log(test);
return posList[test];
}
// Use this for initialization
void Start() {
spawnNext(0);
}
// Update is called once per frame
void Update () {
}
}
|
e45991585184a7ea159dbd5a524d93402eae0d15
|
[
"C#"
] | 3
|
C#
|
SteevJ/ColorSlide
|
716ff2d3e6beac3bdde83941e05d80a59ba17276
|
e240e85e5b6a03394894f17dfbc6b0798e1ce99d
|
refs/heads/master
|
<repo_name>YaroslavBerko/pract_7<file_sep>/mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
void MainWindow::mouseMoveEvent(QMouseEvent *ev)
{
emit coordinateChanged(ev->pos().x(), ev->pos().y());
}
void MainWindow::printCoordinate(int _x, int _y){ // _x, _y - позиція мишки
int x_now=0
,y_now=0
,a=30;
pButton->setText(tr("x = %1, y = %2").arg(_x).arg(_y));
// Check where is mouse and pass new coordinate to button.
x_now = pButton->pos().x();
y_now = pButton->pos().y();
qDebug() << x_now << " " << y_now;
if ((_x < x_now) && (_x > x_now - a))
if ((_y > y_now - a) && (_y < y_now + 50 + a))
pButton->setGeometry(x_now + a, y_now, 100, 50);
if ((_x > x_now + 100) && (_x < x_now + 100 + a))
if ((_y > y_now - a) && (_y < y_now + 50 + a))
pButton->setGeometry(x_now - a, y_now, 100, 50);
if ((_y < y_now) && (_y > y_now - a))
if ((_x > x_now - a) && (_x < x_now + 100 + a))
pButton->setGeometry(x_now, y_now + a, 100, 50);
if ((_y > y_now + 50) && (_y < y_now + 50 + a))
if ((_x > x_now - a) && (_x < x_now + 100 + a))
pButton->setGeometry(x_now, y_now - a, 100, 50);
if (x_now < 20 || x_now > ui->centralWidget->width()-20 || y_now < 20 || y_now > ui->centralWidget->height() - 20)
pButton->setGeometry((ui->centralWidget->width() - pButton->width())/2
,(ui->centralWidget->height() - pButton->width())/2, 100, 50);
}
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
ui->centralWidget->setMouseTracking(true);
this->setMouseTracking(true);
QPushButton *button = new QPushButton(this);
pButton = button; // передача адреси кнопки button
QObject::connect(this, SIGNAL(coordinateChanged(int, int)), this, SLOT(printCoordinate(int, int)));
QObject::connect(button, SIGNAL(clicked(bool)), this, SLOT(close()));
button->setMinimumWidth(100);
button->setMinimumHeight(50);
button->setGeometry(150, 150, 100, 50);
}
MainWindow::~MainWindow()
{
delete ui;
}
<file_sep>/mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QPushButton>
#include <QLayout>
#include <QPoint>
#include <QString>
#include <QMouseEvent>
#include <QDebug>
#include <QPushButton>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
QPushButton *pButton;
protected:
void mouseMoveEvent(QMouseEvent * event);
public slots:
void printCoordinate(int _x, int _y);
signals:
void coordinateChanged(int _x, int _y);
private:
Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H
|
4bd8778c47026a626e39173a7409fd408adf98e3
|
[
"C++"
] | 2
|
C++
|
YaroslavBerko/pract_7
|
c3e207f266ddb73047ceec611ac81d54c8048869
|
0d28a1e00c14513675bd4833a525a41f39313fc2
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.