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>export LANG=en_US.utf8
java -jar statuses-0.1.0-SNAPSHOT-standalone.jar $*
| 2e35980a562fa839fac8dae45a60ce49f6ad60fe | [
"Shell"
] | 1 | Shell | aheusingfeld/statuses | a7ad6a18d2c9caa98639bf0cf5a79bd3ac79b317 | 09d75a1707eb8fa0fa0b5344c342dc48a0d58556 |
refs/heads/master | <file_sep>package tn.esprit.managedBeans;
import java.io.Serializable;
import java.util.List;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import myentities.Employe;
import myentities.Role;
import servicesimpl.EmployeService;
@ManagedBean(name = "employeBean")
@SessionScoped
public class EmployeBean implements Serializable {
private static final long serialVersionUID = 1L;
private String login;
private String password;
private String email;
private Boolean isActif;
private Role role;
private Employe selectedEmploye;
@EJB
EmployeService employeService;
public void addEmploye() {
employeService.ajouterEmploye(new Employe(login, password, email, isActif, role));
}
public Employe getSelectedEmploye() {
return selectedEmploye;
}
public void setSelectedEmploye(Employe selectedEmploye) {
this.selectedEmploye = selectedEmploye;
}
// getters & setters
private List<Employe> employes;
public List<Employe> getEmployes() {
employes = employeService.getAllEmployes();
return employes;
}
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 getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Boolean getIsActif() {
return isActif;
}
public void setIsActif(Boolean isActif) {
this.isActif = isActif;
}
public Role getRole() {
return role;
}
public void setRole(Role role) {
this.role = role;
}
public EmployeService getEmployeService() {
return employeService;
}
public void setEmployeService(EmployeService employeService) {
this.employeService = employeService;
}
public void setEmployes(List<Employe> employes) {
this.employes = employes;
}
public void deleteEmploye(Employe e) {
employeService.deleteEmploye(e);
}
public String initEdit(Employe e) {
this.selectedEmploye = e;
return "/pages/admin/editEmploye?faces-redirect=true";
}
public String editEmployee(Employe e) {
employeService.editEmploye(e);
return "/pages/admin/welcome?faces-redirect=true";
}
public void editInSamePage(Employe e) {
this.selectedEmploye = e;
}
}
<file_sep>package tn.esprit.managedBeans;
import java.io.Serializable;
import javax.faces.bean.ApplicationScoped;
import javax.faces.bean.ManagedBean;
import myentities.Role;
@ManagedBean(name = "data")
@ApplicationScoped
public class Data implements Serializable {
private static final long serialVersionUID = 1L;
public Role[] getRoles()
{ return Role.values(); }
}
| a35821200225ac22b5cabe6478bafccbe138e71f | [
"Java"
] | 2 | Java | YessineAmor/jsf-crud | 887ae996451b91521a98039a7a384a2ac520b827 | 2920307f355fcae12db2298b3c8d3b0b4a2df496 |
refs/heads/master | <file_sep>#pragma once
#include <lua.hpp>
#include <luabind\luabind.hpp>
#include <dzaction.h>
void init_dzAction(lua_State *state)
{
luabind::module(state)[
luabind::class_<DzAction>("Action")
];
}<file_sep>#pragma once
#include <dzaction.h>
#include <luabind\detail\conversion_policies\native_converter.hpp>
namespace luabind
{
template <>
struct default_converter<QString>
: native_converter_base<QString>
{
static int compute_score(lua_State* L, int index)
{
return lua_type(L, index) == LUA_TSTRING ? 0 : -1;
}
QString from(lua_State* L, int index)
{
return QString(lua_tostring(L, index));
}
void to(lua_State* L, QString const& x)
{
lua_pushstring(L, x.toAscii());
}
};
template <>
struct default_converter<QString const&>
: default_converter<QString>
{};
}<file_sep>#include "LuaConsolePane.h"
#include <QtGui\qlayout.h>
LuaConsolePane::LuaConsolePane()
: DzPane( "Lua Console" )
{
m_commandLineEdit = new QLineEdit(this);
m_commandLineEdit->setPlaceholderText("Enter Lua code");
m_commandResultTextEdit = new QPlainTextEdit(this);
m_commandResultTextEdit->setReadOnly(true);
m_sendCommandPushButton = new QPushButton(tr("Send..."), this);
QHBoxLayout *cmdLineLayout = new QHBoxLayout(this);
cmdLineLayout->addWidget(m_commandLineEdit);
cmdLineLayout->addWidget(m_sendCommandPushButton);
QVBoxLayout *mainLayout = new QVBoxLayout(this);
mainLayout->addWidget(m_commandResultTextEdit, 1);
mainLayout->addLayout(cmdLineLayout);
this->setLayout(mainLayout);
}
LuaConsolePane::~LuaConsolePane()
{
}
<file_sep>#include "LuaDazPlugin.h"
#include "plugininfo.h"
#include <luabind\luabind.hpp>
LuaDazPlugin::LuaDazPlugin() :
DzPlugin(PLUGIN_NAME, PLUGIN_AUTHOR, PLUGIN_DESCRIPTION, PLUGIN_MAJOR, PLUGIN_MINOR, PLUGIN_REV, PLUGIN_BUILD)
{
}
LuaDazPlugin::~LuaDazPlugin()
{
}
void LuaDazPlugin::startup()
{
luaState = luaL_newstate();
luaL_openlibs(luaState);
luabind::open(luaState);
}
void LuaDazPlugin::shutdown()
{
lua_close(luaState);
}<file_sep>#pragma once
#include <dzpane.h>
#include <dzaction.h>
#include <QtGui\qlineedit.h>
#include <QtGui\qplaintextedit.h>
#include <QtGui\qpushbutton.h>
class LuaConsolePaneAction :
public DzPaneAction
{
Q_OBJECT
public:
LuaConsolePaneAction() : DzPaneAction("LuaConsolePane") { }
void init() override
{
DzPaneAction::init();
setIcon("luadaz/images/lua-logo.png");
}
};
class LuaConsolePane :
public DzPane
{
Q_OBJECT
public:
LuaConsolePane();
~LuaConsolePane();
private:
QPlainTextEdit *m_commandResultTextEdit;
QLineEdit *m_commandLineEdit;
QPushButton *m_sendCommandPushButton;
};
<file_sep>#pragma once
#include <dzplugin.h>
#include <lua.hpp>
class LuaDazPlugin :
public DzPlugin
{
public:
LuaDazPlugin();
~LuaDazPlugin();
protected:
void startup() override;
void shutdown() override;
private:
lua_State *luaState;
};
<file_sep>#pragma once
extern "C" {
#include <lua.h>
}
#include <dzversion.h>
#define PLUGIN_MAJOR 0
#define PLUGIN_MINOR 0
#define PLUGIN_REV 1
#define PLUGIN_BUILD 0
#define PLUGIN_DESCRIPTION \
LUA_VERSION " for DAZ Studio 4.x"
#define PLUGIN_NAME \
"LuaDaz"
#define PLUGIN_AUTHOR \
"<NAME>"
<file_sep>#include "LuaDazPlugin.h"
#include "LuaConsolePane.h"
DZ_CUSTOM_PLUGIN_DEFINITION(LuaDazPlugin);
DZ_PLUGIN_CLASS_GUID(LuaConsolePane, 32C8F853-B5F3-4695-9D2E-846F0D5DE553);
DZ_PLUGIN_CLASS_GUID(LuaConsolePaneAction, 2A1B5CD4-699E-422D-907C-CF71A11C39AD); | f2fc4b20378dc0b24476caef4f558f0e7b3c6f75 | [
"C",
"C++"
] | 8 | C | mattiascibien/luadaz | 88821c00f1bf873c5a61bd8e7d99e307a4a0f55e | feb62957be8751bfbdbc4c65979fd31ea16dfa7e |
refs/heads/master | <file_sep># :cupid: Tindev
A Dating App for Developer [https://tindev-app.web.app/](https://tindev-app.web.app/)
## Plan of Action
- [x] HEADER
- [x] Tinder Card
- [x] Button at bottom
- [x] Chat Screen
- [x] Individual Chat Screen
<file_sep>import firebase from "firebase";
const firebaseConfig = {
apiKey: "<KEY>",
authDomain: "rishtey-748cc.firebaseapp.com",
databaseURL: "https://rishtey-748cc.firebaseio.com",
projectId: "rishtey-748cc",
storageBucket: "rishtey-748cc.appspot.com",
messagingSenderId: "761796471746",
appId: "1:761796471746:web:bb8247a7c6ea388a52045b",
measurementId: "G-LD9QS7BJBV"
};
const firebaseApp = firebase.initializeApp(firebaseConfig);
const database = firebaseApp.firestore();
export default database; | 59f3b126d682afc3ef0431c16047fafed86b6e29 | [
"Markdown",
"JavaScript"
] | 2 | Markdown | RocktimRajkumar/Tindev | 355a33583697758c7f506227c23a9ebadee1eb8d | cf054cd67d5d0ef974dfee647e6e58122e8eeb0c |
refs/heads/master | <file_sep>using OutraCoisaConsole.Dominio;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace OutraCoisaConsole
{
public class GeradorDeRelatorio
{
public TimeSpan MelhorVoltaCorrida(List<Corrida> listaCorrida)
{
TimeSpan melhorvolta = listaCorrida[0].Tempo;
for (int i = 1; i < listaCorrida.Count; i++)
{
if (listaCorrida[i].Tempo.CompareTo(melhorvolta) < 0)
{
melhorvolta = listaCorrida[i].Tempo;
}
}
return melhorvolta;
}
public List<Relatorio> MontaRelatorio(List<Corrida> listaCorrida)
{
List<Relatorio> relatorio = new List<Relatorio>();
int posicao = 1;
for (int i = 0; i < listaCorrida.Count; i++)
{
int codigo = listaCorrida[i].Codigo;
if (!relatorio.Any(r => r.Codigo == codigo))
{
int qtdVolta = VerificaQtdVolta(listaCorrida, codigo);
TimeSpan melhorVolta = VerificaMelhorVoltaPiloto(listaCorrida, codigo);
Decimal velocidadeMedia = VerificaVelocidadeMedia(listaCorrida, codigo, qtdVolta);
TimeSpan tempo = TempoAposVencedor(listaCorrida, codigo);
Relatorio r = new Relatorio(posicao, listaCorrida[i].Codigo, listaCorrida[i].Piloto, qtdVolta,
melhorVolta, velocidadeMedia, tempo);
relatorio.Add(r);
}
}
for (int i = 0; i < relatorio.Count; i++)
{
for (int j = 0; j < relatorio.Count; j++)
{
if (relatorio[i].TempoAposVencedor.CompareTo(relatorio[j].TempoAposVencedor) < 0)
{
Relatorio aux = relatorio[i];
relatorio[i] = relatorio[j];
relatorio[j] = aux;
}
}
}
for (int i = 0; i < relatorio.Count; i++)
{
relatorio[i].PosicaoChegada = i + 1;
}
return relatorio;
}
private int VerificaQtdVolta(List<Corrida> listaCorrida, int codigo)
{
for (int i = listaCorrida.Count - 1; i >= 0; i--)
{
if (listaCorrida[i].Codigo == codigo)
{
return listaCorrida[i].Volta;
}
}
return 0;
}
private static TimeSpan VerificaMelhorVoltaPiloto(List<Corrida> listaCorrida, int codigo)
{
TimeSpan melhorVolta = new TimeSpan();
melhorVolta = TimeSpan.MaxValue;
for (int i = listaCorrida.Count - 1; i >= 0; i--)
{
if (listaCorrida[i].Codigo == codigo)
{
if (listaCorrida[i].Tempo.CompareTo(melhorVolta) < 0)
{
melhorVolta = listaCorrida[i].Tempo;
}
}
}
return melhorVolta;
}
private Decimal VerificaVelocidadeMedia(List<Corrida> listaCorrida, int codigo, int qtdVolta)
{
Decimal velocidade = 0;
for (int i = 0; i < listaCorrida.Count; i++)
{
if (listaCorrida[i].Codigo == codigo)
{
velocidade += listaCorrida[i].Velocidade;
}
}
velocidade = velocidade / qtdVolta;
return velocidade;
}
private TimeSpan TempoAposVencedor(List<Corrida> listaCorrida, int codigo)
{
TimeSpan horaVencedor = VerificaHoraVencedor(listaCorrida);
for (int i = listaCorrida.Count - 1; i >= 0; i--)
{
if (listaCorrida[i].Codigo == codigo)
{
TimeSpan tempoApos = listaCorrida[i].Hora - horaVencedor;
return tempoApos;
}
}
return new TimeSpan();
}
private TimeSpan VerificaHoraVencedor(List<Corrida> listaCorrida)
{
for (int i = 0; i < listaCorrida.Count; i++)
{
if (listaCorrida[i].Volta == 4)
{
return listaCorrida[i].Hora;
}
}
return new TimeSpan(0, 0, 0, 0, 0);
}
}
}
<file_sep>using OutraCoisaConsole.Dominio;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
namespace OutraCoisaConsole
{
class Program
{
public static TradutorDeArquivo Tradutor { get; set; }
public static GeradorDeRelatorio Gerador { get; set; }
static void Main(string[] args)
{
Tradutor = new TradutorDeArquivo();
Gerador = new GeradorDeRelatorio();
List<Corrida> listaCorrida = new List<Corrida>();
List<Relatorio> relatorio = new List<Relatorio>();
Tradutor.SetFilePath(ConfigurationManager.AppSettings["FilePath"]);
try
{
listaCorrida = Tradutor.ReadFile();
TimeSpan melhorVolta = Gerador.MelhorVoltaCorrida(listaCorrida);
TimeSpan tempoTotal = listaCorrida[listaCorrida.Count - 1].Hora;
relatorio = Gerador.MontaRelatorio(listaCorrida);
foreach (var item in relatorio)
{
Console.WriteLine(@"Posicao: {0}",item.PosicaoChegada);
Console.WriteLine(@"Codigo: {0}", item.Codigo);
Console.WriteLine(@"Piloto: {0}", item.Piloto);
Console.WriteLine(@"Quantidade de voltas: {0}", item.QtdVolta);
Console.WriteLine(@"Melhor Volta: {0}", item.MelhorVolta);
Console.WriteLine(@"Velocidade Media: {0}", item.Velocidade);
Console.WriteLine(@"Tempo Apos o Vencedor: {0}", item.TempoAposVencedor);
Console.WriteLine();
}
Console.WriteLine(@"Tempo total de prova: {0}", tempoTotal);
Console.WriteLine(@"Melhor volta da corrida: {0}", melhorVolta);
}
catch (IOException e)
{
Console.WriteLine("Erro ao abrir o arquivo: {0}", e.GetType().Name);
}
Console.ReadKey();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace OutraCoisaConsole.Dominio
{
public class Corrida
{
public TimeSpan Hora { get; set; }
public int Codigo { get; set; }
public string Piloto { get; set; }
public int Volta { get; set; }
public TimeSpan Tempo { get; set; }
public decimal Velocidade { get; set; }
public Corrida(TimeSpan hora, int codigo, string piloto, int volta, TimeSpan tempo, decimal velocidade)
{
this.Hora = hora;
this.Codigo = codigo;
this.Piloto = piloto;
this.Volta = volta;
this.Tempo = tempo;
this.Velocidade = velocidade;
}
}
}
<file_sep>using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OutraCoisaConsole;
using System.IO;
namespace OutraCoisa.Tests
{
[TestClass]
public class TradutorDeArquivoTests
{
public TradutorDeArquivo Tradutor { get; set; }
[TestInitialize]
public void BeforeTests()
{
Tradutor = new TradutorDeArquivo();
}
[TestMethod]
public void ReadFile_WhenFileHasLines_ShowReturnListCollection()
{
Tradutor.SetFilePath(@"C:\Users\User\Documents\Visual Studio 2017\Projects\OutraCoisa\race.log");
var result = Tradutor.ReadFile();
Assert.IsTrue(result != null);
Assert.IsTrue(result.Count > 0);
}
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void ReadFile_WhenFilePathIsNull_ShowThrowAnException()
{
var result = Tradutor.ReadFile();
}
[TestMethod]
[ExpectedException(typeof(DirectoryNotFoundException))]
public void ReadFile_WhenFilePathIsInvalid_ShowThrowAnException()
{
Tradutor.SetFilePath(@"C:\Users\User\Documents\Visual Studio 2017\Projects\OutroNegocio\race.log");
var result = Tradutor.ReadFile();
Assert.IsTrue(result != null);
Assert.IsTrue(result.Count > 0);
}
[TestMethod]
[ExpectedException(typeof(FileNotFoundException))]
public void ReadFile_WhenFileNotExists_ShowThrowAnException()
{
Tradutor.SetFilePath(@"C:\Users\User\Documents\Visual Studio 2017\Projects\OutraCoisa\otherRace.log");
var result = Tradutor.ReadFile();
Assert.IsTrue(result != null);
Assert.IsTrue(result.Count > 0);
}
}
}
<file_sep>using OutraCoisaConsole.Dominio;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace OutraCoisaConsole
{
public class TradutorDeArquivo
{
private string _filePath;
public void SetFilePath(string path)
{
_filePath = path;
}
public List<Corrida> ReadFile()
{
var listaCorrida = new List<Corrida>();
string[] linhas = File.ReadAllLines(_filePath);
for (int i = 1; i < linhas.Length; i++)
{
string[] auxiliar = linhas[i].Split('\t');
TimeSpan hora = new TimeSpan(0, Convert.ToInt32(auxiliar[0].Substring(0, 2)),
Convert.ToInt32(auxiliar[0].Substring(3, 2)), Convert.ToInt32(auxiliar[0].Substring(6, 2)),
Convert.ToInt32(auxiliar[0].Substring(9, 3)));
TimeSpan volta = new TimeSpan(0, 0, Convert.ToInt32(auxiliar[3].Substring(0, 1)),
Convert.ToInt32(auxiliar[3].Substring(2, 2)), Convert.ToInt32(auxiliar[3].Substring(5, 3)));
Corrida c = new Corrida(hora, Int32.Parse(auxiliar[1].Substring(0, 3)), auxiliar[1].Substring(6, auxiliar[1].Length - 6), Convert.ToInt32(auxiliar[2]), volta,
Convert.ToDecimal(auxiliar[4]));
listaCorrida.Add(c);
}
return listaCorrida;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace OutraCoisaConsole.Dominio
{
public class Relatorio
{
public int PosicaoChegada { get; set; }
public int Codigo { get; set; }
public string Piloto { get; set; }
public int QtdVolta { get; set; }
public TimeSpan MelhorVolta { get; set; }
public decimal Velocidade { get; set; }
public TimeSpan TempoAposVencedor { get; set; }
public Relatorio(int posicaoChegada, int Codigo, string piloto, int qtdVolta, TimeSpan melhorVolta, decimal velocidade,
TimeSpan tempoAposVencedor)
{
this.PosicaoChegada = posicaoChegada;
this.Codigo = Codigo;
this.Piloto = piloto;
this.QtdVolta = qtdVolta;
this.MelhorVolta = melhorVolta;
this.Velocidade = velocidade;
this.TempoAposVencedor = tempoAposVencedor;
}
}
}
| e778a8b09b94b8984a7bbe9c7bc234a8b5f7b44c | [
"C#"
] | 6 | C# | camilamorg/OutraCoisa | 8b9653b1e3576fc0e8df833325c6e50dca190934 | 9aaac8862884e93f8f98266c4b2c69618dc6a95b |
refs/heads/master | <file_sep>/* traemos los elementos desde el formularios */
const form = document.getElementById('search-form');
const searchField = document.getElementById('search-keyword');
const responseContainer = document.getElementById('response-container');
let searchedForText;
/* Le agregamos el evento submit al formulario y las intrucciones a ejecutar */
form.addEventListener('submit', function (e) {
e.preventDefault();
responseContainer.innerHTML = '';
searchedForText = searchField.value;
getNews();
});
/* Creamos una funcion donde obtenemos la informacion desde la api */
function getNews() {
const articleRequest = new XMLHttpRequest();/* creamos el objeto XHR */
articleRequest.open('GET', `https://api.nytimes.com/svc/search/v2/articlesearch.json?q=${searchedForText}&api-key=<KEY>`);/* abrimos la conexion con .open, en este caso tomamos 2 parámetros: GET y la url de la api para obtener la info */
articleRequest.onload = addNews;/* el método .onload maneja la respuesta exitosa a nuestra solicitud XHR */
articleRequest.inerror = handleError;/* en caso de que no se muestra la solicitud, usamos .onerror y así sabremos que es lo que está fallando */
articleRequest.send();/* enviamos la solicitud al servidor */
}
/* funcion que se ejecuta cuando la respuesta es exitosa */
function addNews() {
const data = JSON.parse(this.responseText);
const article = data.response.docs[0];
const title = article.headline.main;
const snippet = article.snippet;
let li = document.createElement('li');
li.className = 'articleClass';
li.innerText = snippet;
responseContainer.appendChild(li);
}
/* funcion que se ejecuta cuando ocurre algún error */
function handleError() {
console.log('Se ha presentado un error');
}
| 4559b2fe1011ece31e328df53ffe32ec0c3db0da | [
"JavaScript"
] | 1 | JavaScript | cynthia1171/XHRProyectDemo | 4f2c1e05d64d23c3b4297b65906b84a9a644cfe2 | c3d5e0d763fa3636541a6b00bed22a1112615bd9 |
refs/heads/master | <repo_name>Quizer1349/code_parts<file_sep>/OrientalChuShing_Swift/OrientalChuShing/Views/WorkingHoursTableViewCell.swift
//
// WorkingHoursTableViewCell.swift
// OrientalChuShing
//
// Created by <NAME> on 11.09.15.
// Copyright (c) 2015 itinarray. All rights reserved.
//
import UIKit
class WorkingHoursTableViewCell: UITableViewCell {
@IBOutlet weak var dayLabel: UILabel!
@IBOutlet weak var hoursLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
<file_sep>/MyCarRadar_Swift_WatchKit2/Constants.swift
//
// Constants.swift
// MyCarRadar
//
// Created by <NAME> on 22.09.15.
// Copyright © 2015 itinarray. All rights reserved.
//
import UIKit
struct Constants {
struct AlertsTexts {
static let LocationDeniedText = NSLocalizedString("Location authorization denied. Please turn on in settings", comment: "")
static let LocationDeniedTitle = NSLocalizedString("Service denied", comment: "")
}
struct Appearence {
static let buttonsBg:UIColor = UIColor(red: 0.383, green: 1.000, blue: 0.425, alpha: 0.35)
}
}
<file_sep>/sheepGame_Spritekit_Swift/SheepSorter/Nodes/FinishLinesNodes.swift
//
// LeftFinishLineNode.swift
// SheepSorter
//
// Created by <NAME> on 01.12.15.
// Copyright © 2015 <NAME>. All rights reserved.
//
import SpriteKit
class LeftFinishLineNode: SKShapeNode {
override init() {
super.init()
// Draw Path
let leftFinishPath = UIBezierPath()
leftFinishPath.moveToPoint(CGPointMake(3, 55))
leftFinishPath.addLineToPoint(CGPointMake(3, 3))
leftFinishPath.addLineToPoint(CGPointMake(38, 3))
self.path = leftFinishPath.CGPath
// Fill
fillColor = UIColor.clearColor()
strokeColor = UIColor.clearColor()
// Physics
physicsBody = SKPhysicsBody(polygonFromPath: leftFinishPath.CGPath)
physicsBody!.categoryBitMask = PhysicsCategory.LeftFinish
physicsBody!.contactTestBitMask = PhysicsCategory.Sheep
physicsBody!.collisionBitMask = 0
physicsBody!.usesPreciseCollisionDetection = true
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class CenterFinishLineNode: SKShapeNode {
override init() {
super.init()
// Draw Path
let centerFinishPath = UIBezierPath()
centerFinishPath.moveToPoint(CGPointMake(128, 3))
centerFinishPath.addLineToPoint(CGPointMake(193, 3))
self.path = centerFinishPath.CGPath
// Fill
fillColor = UIColor.clearColor()
strokeColor = UIColor.clearColor()
// Physics
physicsBody = SKPhysicsBody(edgeChainFromPath: centerFinishPath.CGPath)
physicsBody!.categoryBitMask = PhysicsCategory.CenterFinish
physicsBody!.contactTestBitMask = PhysicsCategory.Sheep
physicsBody!.collisionBitMask = 0
physicsBody!.usesPreciseCollisionDetection = true
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class RightFinishLineNode: SKShapeNode {
override init() {
super.init()
// Draw Path
let rightFinishPath = UIBezierPath()
rightFinishPath.moveToPoint(CGPointMake(283, 3))
rightFinishPath.addLineToPoint(CGPointMake(317, 3))
rightFinishPath.addLineToPoint(CGPointMake(317, 55))
self.path = rightFinishPath.CGPath
// Fill
fillColor = UIColor.clearColor()
strokeColor = UIColor.clearColor()
// Physics
physicsBody = SKPhysicsBody(polygonFromPath: rightFinishPath.CGPath)
physicsBody!.categoryBitMask = PhysicsCategory.RightFinish
physicsBody!.contactTestBitMask = PhysicsCategory.Sheep
physicsBody!.collisionBitMask = 0
physicsBody!.usesPreciseCollisionDetection = true
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
<file_sep>/OrientalChuShing_Swift/OrientalChuShing/Vendors/PushHandler.swift
//
// PushHandler.swift
// OrientalChuShing
//
// Created by <NAME> on 08.09.15.
// Copyright (c) 2015 itinarray. All rights reserved.
//
import UIKit
class PushHandler: NSObject {
let appDelegate:AppDelegate!
class var sharedInstance : PushHandler {
struct Static {
static let instance : PushHandler = PushHandler()
}
return Static.instance
}
private override init() {
self.appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
}
func handlePushNotification(userInfo: [NSObject : AnyObject], isAppActive:Bool = false){
let pushTitle:String = (userInfo["title"] as? String)!
if let hyperlink: String = userInfo["hyperlink"] as? String{
if(hyperlink.characters.count > 0){
if isAppActive{
showPushAlert(title: pushTitle, hyperlink: hyperlink)
}else{
handlePushWithHyperlink(hyperlink)
}
}
}
}
func handlePushWithHyperlink(hyperlink: String){
showWebBrowserWithHyperlink(hyperlink)
}
func showWebBrowserWithHyperlink(hyperlink:String!){
let navVC:UINavigationController = self.appDelegate.window!.rootViewController as! UINavigationController
let storyboard:UIStoryboard = UIStoryboard(name: "Main", bundle: NSBundle.mainBundle())
let webBrowserVC:WebBrowserViewController = storyboard.instantiateViewControllerWithIdentifier(WebBrowserViewController.classNameToString) as! WebBrowserViewController
webBrowserVC.hyperlink = hyperlink
let newNavController = UINavigationController(rootViewController: webBrowserVC)
navVC.topViewController!.presentViewController(newNavController, animated: true, completion: nil)
}
private func showPushAlert(title title:String, hyperlink:String){
let alertVC = UIAlertController(title: title, message: "", preferredStyle: UIAlertControllerStyle.Alert)
let alertCancelAction = UIAlertAction(title: "Cancel".localizedWithComment(""), style: UIAlertActionStyle.Cancel, handler: nil)
alertVC.addAction(alertCancelAction)
let alertShowAction = UIAlertAction(title: "Show".localizedWithComment(""), style: UIAlertActionStyle.Default){ (alertShowAction) -> Void in
self.handlePushWithHyperlink(hyperlink)
}
alertVC.addAction(alertShowAction)
let navVC:UINavigationController = self.appDelegate.window!.rootViewController as! UINavigationController
navVC.topViewController!.presentViewController(alertVC, animated: true, completion: nil)
}
}
<file_sep>/OrientalChuShing_Swift/OrientalChuShing/Views/PlaceTableViewCell.swift
//
// PlaceTableViewCell.swift
// OrientalChuShing
//
// Created by <NAME> on 02.09.15.
// Copyright (c) 2015 itinarray. All rights reserved.
//
import UIKit
class PlaceTableViewCell: UITableViewCell {
@IBOutlet weak var placeName: UILabel!
@IBOutlet weak var placeAdress: UILabel!
@IBOutlet weak var distanceRange: UILabel!
@IBOutlet weak var distanceTitle: UILabel!
@IBOutlet weak var distanceActivity: UIActivityIndicatorView!
var place:Place? = nil{
didSet{
self.setUIForPlace()
}
}
override func awakeFromNib() {
super.awakeFromNib()
let nc = NSNotificationCenter.defaultCenter()
nc.addObserver(self, selector: "myCoordinatesUpdated:", name: Constants.kMyCoordinatesUpdatedNotification, object: nil)
distanceTitle.text = "distance".localizedWithComment("")
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
deinit{
let nc = NSNotificationCenter.defaultCenter()
nc.removeObserver(self, name: Constants.kMyCoordinatesUpdatedNotification, object: nil)
}
func setUIForPlace(){
self.placeName.text = self.place?.title
self.placeAdress.text = self.place?.address
}
func myCoordinatesUpdated(notification: NSNotification){
let userInfo:Dictionary<String,Double!> = notification.userInfo as! Dictionary<String,Double!>
let latitude:Double = userInfo["latitude"]!
let longitude:Double = userInfo["longitude"]!
if(latitude != 0 && longitude != 0){
let locationManager = LocationManager.sharedInstance
let distRangeFloat:Float = locationManager.getDistanceToCoordinates(latitude: self.place?.latitude, longitude: self.place?.longitude)
if(distRangeFloat < Constants.AppData.AppDistanceLimit){
self.distanceActivity.stopAnimating()
self.distanceRange.text = String(format: "%.1f km", (distRangeFloat/1000))
}else{
self.distanceActivity.stopAnimating()
self.distanceRange.text = ">30 km"
}
}
}
}
<file_sep>/MyCarRadar_Swift_WatchKit2/MapInterfaceController.swift
//
// MapInterfaceController.swift
// MyCarRadar
//
// Created by <NAME> on 16.09.15.
// Copyright © 2015 itinarray. All rights reserved.
//
import WatchKit
import Foundation
class MapInterfaceController: WKInterfaceController, CLLocationManagerDelegate {
@IBOutlet var mapView: WKInterfaceMap!
var carLatitude:Double! = 0
var carLongitude:Double! = 0
let lastCarLocationDic:NSDictionary = NSUserDefaults.standardUserDefaults().objectForKey("lastKnowCarLocation") as! NSDictionary
var lastCarLocation:CLLocation? = nil
/// Location manager to request authorization and location updates.
let manager = CLLocationManager()
/// Flag indicating whether the manager is requesting the user's location.
var isRequestingLocation = false
override func awakeWithContext(context: AnyObject?) {
super.awakeWithContext(context)
manager.delegate = self
manager.distanceFilter = kCLDistanceFilterNone;
manager.desiredAccuracy = kCLLocationAccuracyBestForNavigation
lastCarLocation = CLLocation(latitude: lastCarLocationDic["lat"] as! CLLocationDegrees, longitude: lastCarLocationDic["long"] as! CLLocationDegrees)
// Configure interface objects here.
}
override func willActivate() {
// This method is called when watch view controller is about to be visible to user
super.willActivate()
}
override func didDeactivate() {
// This method is called when watch view controller is no longer visible
super.didDeactivate()
}
/// MARK - CLLocationManagerDelegate Methods
/**
When the location manager receives new locations, display the latitude and
longitude of the latest location and restart the timers.
*/
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard !locations.isEmpty else { return }
dispatch_async(dispatch_get_main_queue()) {
self.isRequestingLocation = true
self.mapView.removeAllAnnotations()
let span = MKCoordinateSpanMake(0.005, 0.005)
let coordRegion = MKCoordinateRegionMake((locations.last?.coordinate)!, span)
self.mapView.setRegion(coordRegion)
self.mapView.addAnnotation((locations.last?.coordinate)!, withPinColor: .Green)
self.mapView.addAnnotation(self.lastCarLocation!.coordinate, withPinColor: .Red)
self.carLatitude = locations.last?.coordinate.latitude
self.carLongitude = locations.last?.coordinate.longitude
}
}
func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
print(error.localizedDescription)
}
}
<file_sep>/MyCarRadar_Swift_WatchKit2/RadarDrawer.swift
//
// RadarDrawer.swift
// MyCrRadar
//
// Created by <NAME> on 17.09.15.
// Copyright (c) 2015 Seanetix. All rights reserved.
//
// Generated by PaintCode (www.paintcodeapp.com)
//
import WatchKit
import Foundation
public class RadarDrawer : NSObject {
//// Cache
private struct Cache {
static let gradientColor: UIColor = UIColor(red: 0.020, green: 0.162, blue: 0.020, alpha: 1.000)
static let color2: UIColor = UIColor(red: 0.383, green: 1.000, blue: 0.425, alpha: 1.000)
}
//// Colors
public class var gradientColor: UIColor { return Cache.gradientColor }
public class var color2: UIColor { return Cache.color2 }
//// Drawing Methods
private class func drawRadar(radarHandAngle radarHandAngle: CGFloat = 0, distanceText: String = "") {
//// General Declarations
let context = UIGraphicsGetCurrentContext()
//// Color Declarations
let gradient2Color = UIColor(red: 0.013, green: 0.147, blue: 0.044, alpha: 1.000)
let gradient2Color2 = UIColor(red: 0.211, green: 0.587, blue: 0.287, alpha: 1.000)
let shadow3Color = UIColor(red: 0.014, green: 0.197, blue: 0.048, alpha: 1.000)
//// Gradient Declarations
let gradient2 = CGGradientCreateWithColors(CGColorSpaceCreateDeviceRGB(), [gradient2Color.CGColor, gradient2Color.blendedColorWithFraction(0.5, ofColor: gradient2Color2).CGColor, gradient2Color2.CGColor, gradient2Color2.blendedColorWithFraction(0.5, ofColor: UIColor.whiteColor()).CGColor, UIColor.whiteColor().CGColor], [0, 0.4, 0.56, 0.71, 0.95])!
let gradient = CGGradientCreateWithColors(CGColorSpaceCreateDeviceRGB(), [UIColor.clearColor().CGColor, UIColor.clearColor().blendedColorWithFraction(0.5, ofColor: RadarDrawer.color2).CGColor, RadarDrawer.color2.CGColor], [0, 0.51, 0.86])!
let gradient3 = CGGradientCreateWithColors(CGColorSpaceCreateDeviceRGB(), [RadarDrawer.color2.CGColor, RadarDrawer.color2.blendedColorWithFraction(0.5, ofColor: UIColor.clearColor()).CGColor, UIColor.clearColor().CGColor], [0, 0.27, 0.56])!
//// Shadow Declarations
let shadow = DrawerShadow()
shadow.shadowColor = RadarDrawer.color2
shadow.shadowOffset = CGSizeMake(0.1, -0.1)
shadow.shadowBlurRadius = 2
let shadow2 = DrawerShadow()
shadow2.shadowColor = RadarDrawer.color2
shadow2.shadowOffset = CGSizeMake(0.1, -0.1)
shadow2.shadowBlurRadius = 5
let shadow3 = DrawerShadow()
shadow3.shadowColor = shadow3Color
shadow3.shadowOffset = CGSizeMake(0.1, -0.1)
shadow3.shadowBlurRadius = 4
//// Group
//// Oval Drawing
let ovalPath = UIBezierPath(ovalInRect: CGRectMake(4, 4, 152, 152))
CGContextSaveGState(context)
CGContextSetShadowWithColor(context, shadow3.shadowOffset, shadow3.shadowBlurRadius, shadow3.shadowColor.CGColor)
CGContextBeginTransparencyLayer(context, nil)
ovalPath.addClip()
CGContextDrawRadialGradient(context, gradient2,
CGPointMake(80, 80), 14.01,
CGPointMake(80, 80), 176.53,
[CGGradientDrawingOptions.DrawsBeforeStartLocation, CGGradientDrawingOptions.DrawsAfterEndLocation])
CGContextEndTransparencyLayer(context)
CGContextRestoreGState(context)
CGContextSaveGState(context)
CGContextSetShadowWithColor(context, shadow.shadowOffset, shadow.shadowBlurRadius, shadow.shadowColor.CGColor)
RadarDrawer.gradientColor.setStroke()
ovalPath.lineWidth = 1
ovalPath.stroke()
CGContextRestoreGState(context)
//// Oval 2 Drawing
let oval2Path = UIBezierPath(ovalInRect: CGRectMake(79, 78.5, 2, 2))
CGContextSaveGState(context)
CGContextSetShadowWithColor(context, shadow.shadowOffset, shadow.shadowBlurRadius, shadow.shadowColor.CGColor)
RadarDrawer.color2.setFill()
oval2Path.fill()
CGContextRestoreGState(context)
//// Bezier Drawing
let bezierPath = UIBezierPath()
bezierPath.moveToPoint(CGPointMake(80, 4.96))
bezierPath.addCurveToPoint(CGPointMake(80, 155.04), controlPoint1: CGPointMake(80, 154.11), controlPoint2: CGPointMake(80, 155.04))
CGContextSaveGState(context)
CGContextSetShadowWithColor(context, shadow.shadowOffset, shadow.shadowBlurRadius, shadow.shadowColor.CGColor)
RadarDrawer.color2.setStroke()
bezierPath.lineWidth = 1
bezierPath.stroke()
CGContextRestoreGState(context)
//// Bezier 2 Drawing
CGContextSaveGState(context)
CGContextTranslateCTM(context, 4.48, 79.52)
CGContextRotateCTM(context, -90 * CGFloat(M_PI) / 180)
let bezier2Path = UIBezierPath()
bezier2Path.moveToPoint(CGPointMake(0, 0))
bezier2Path.addCurveToPoint(CGPointMake(0, 150.09), controlPoint1: CGPointMake(0, 149.15), controlPoint2: CGPointMake(0, 150.09))
CGContextSaveGState(context)
CGContextSetShadowWithColor(context, shadow.shadowOffset, shadow.shadowBlurRadius, shadow.shadowColor.CGColor)
RadarDrawer.color2.setStroke()
bezier2Path.lineWidth = 1
bezier2Path.stroke()
CGContextRestoreGState(context)
CGContextRestoreGState(context)
//// Oval 3 Drawing
let oval3Path = UIBezierPath(ovalInRect: CGRectMake(57, 57.5, 45, 45))
CGContextSaveGState(context)
CGContextSetShadowWithColor(context, shadow.shadowOffset, shadow.shadowBlurRadius, shadow.shadowColor.CGColor)
RadarDrawer.color2.setStroke()
oval3Path.lineWidth = 1
oval3Path.stroke()
CGContextRestoreGState(context)
//// Oval 4 Drawing
let oval4Path = UIBezierPath(ovalInRect: CGRectMake(42, 42.5, 75, 75))
CGContextSaveGState(context)
CGContextSetShadowWithColor(context, shadow.shadowOffset, shadow.shadowBlurRadius, shadow.shadowColor.CGColor)
RadarDrawer.color2.setStroke()
oval4Path.lineWidth = 1
oval4Path.stroke()
CGContextRestoreGState(context)
//// Oval 5 Drawing
let oval5Path = UIBezierPath(ovalInRect: CGRectMake(28, 28.5, 103, 103))
CGContextSaveGState(context)
CGContextSetShadowWithColor(context, shadow.shadowOffset, shadow.shadowBlurRadius, shadow.shadowColor.CGColor)
RadarDrawer.color2.setStroke()
oval5Path.lineWidth = 1
oval5Path.stroke()
CGContextRestoreGState(context)
//// Oval 6 Drawing
let oval6Path = UIBezierPath(ovalInRect: CGRectMake(12, 12.5, 135, 135))
CGContextSaveGState(context)
CGContextSetShadowWithColor(context, shadow.shadowOffset, shadow.shadowBlurRadius, shadow.shadowColor.CGColor)
RadarDrawer.color2.setStroke()
oval6Path.lineWidth = 1
oval6Path.stroke()
CGContextRestoreGState(context)
//// Bezier 3 Drawing
CGContextSaveGState(context)
CGContextTranslateCTM(context, 80, 80)
CGContextRotateCTM(context, -radarHandAngle * CGFloat(M_PI) / 180)
let bezier3Path = UIBezierPath()
bezier3Path.moveToPoint(CGPointMake(-0.07, 0))
bezier3Path.addLineToPoint(CGPointMake(0, -75.04))
bezier3Path.addLineToPoint(CGPointMake(-17.99, -73.36))
bezier3Path.addLineToPoint(CGPointMake(-0.07, 0))
bezier3Path.closePath()
bezier3Path.lineCapStyle = .Round;
CGContextSaveGState(context)
CGContextSetShadowWithColor(context, shadow2.shadowOffset, shadow2.shadowBlurRadius, shadow2.shadowColor.CGColor)
CGContextBeginTransparencyLayer(context, nil)
bezier3Path.addClip()
CGContextDrawLinearGradient(context, gradient, CGPointMake(-16.72, -36.94), CGPointMake(1.31, -37.57), CGGradientDrawingOptions())
CGContextEndTransparencyLayer(context)
CGContextRestoreGState(context)
CGContextRestoreGState(context)
//// Rectangle Drawing
let rectanglePath = UIBezierPath()
rectanglePath.moveToPoint(CGPointMake(56.58, 151.68))
rectanglePath.addCurveToPoint(CGPointMake(60.5, 153), controlPoint1: CGPointMake(56.58, 151.68), controlPoint2: CGPointMake(57.17, 152.14))
rectanglePath.addCurveToPoint(CGPointMake(80, 155.5), controlPoint1: CGPointMake(63.71, 153.83), controlPoint2: CGPointMake(69.44, 155.5))
rectanglePath.addCurveToPoint(CGPointMake(99, 153), controlPoint1: CGPointMake(89.95, 155.5), controlPoint2: CGPointMake(96, 154))
rectanglePath.addCurveToPoint(CGPointMake(103.42, 151.68), controlPoint1: CGPointMake(102.85, 152.1), controlPoint2: CGPointMake(103.42, 151.68))
rectanglePath.addLineToPoint(CGPointMake(103.42, 136.88))
rectanglePath.addLineToPoint(CGPointMake(56.58, 136.88))
rectanglePath.addLineToPoint(CGPointMake(56.58, 151.68))
rectanglePath.closePath()
CGContextSaveGState(context)
rectanglePath.addClip()
CGContextDrawLinearGradient(context, gradient3, CGPointMake(80, 155.5), CGPointMake(80, 136.88), CGGradientDrawingOptions())
CGContextRestoreGState(context)
//// Text Drawing
let textRect = CGRectMake(58, 144.5, 44, 10)
CGContextSaveGState(context)
CGContextSetShadowWithColor(context, shadow.shadowOffset, shadow.shadowBlurRadius, shadow.shadowColor.CGColor)
let textStyle = NSParagraphStyle.defaultParagraphStyle().mutableCopy() as! NSMutableParagraphStyle
textStyle.alignment = .Center
let textFontAttributes = [NSFontAttributeName: UIFont.systemFontOfSize(11), NSForegroundColorAttributeName: gradient2Color, NSParagraphStyleAttributeName: textStyle]
let textTextHeight: CGFloat = NSString(string: distanceText).boundingRectWithSize(CGSizeMake(textRect.width, CGFloat.infinity), options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: textFontAttributes, context: nil).size.height
CGContextSaveGState(context)
CGContextClipToRect(context, textRect);
NSString(string: distanceText).drawInRect(CGRectMake(textRect.minX, textRect.minY + (textRect.height - textTextHeight) / 2, textRect.width, textTextHeight), withAttributes: textFontAttributes)
CGContextRestoreGState(context)
CGContextRestoreGState(context)
}
public class func drawRadarImage(radarHandAngle radarHandAngle:CGFloat, distanceText: String, size:CGSize) {
//// General Declarations
let context = UIGraphicsGetCurrentContext()
//// Symbol Drawing
let symbolRect = CGRectMake(0.15, 0.15, size.width, size.height)
CGContextSaveGState(context)
UIRectClip(symbolRect)
CGContextTranslateCTM(context, symbolRect.origin.x, symbolRect.origin.y)
CGContextScaleCTM(context, symbolRect.size.width / 160, symbolRect.size.height / 160)
RadarDrawer.drawRadar(radarHandAngle: radarHandAngle, distanceText: distanceText)
CGContextRestoreGState(context)
}
}
extension UIColor {
func blendedColorWithFraction(fraction: CGFloat, ofColor color: UIColor) -> UIColor {
var r1: CGFloat = 1.0, g1: CGFloat = 1.0, b1: CGFloat = 1.0, a1: CGFloat = 1.0
var r2: CGFloat = 1.0, g2: CGFloat = 1.0, b2: CGFloat = 1.0, a2: CGFloat = 1.0
self.getRed(&r1, green: &g1, blue: &b1, alpha: &a1)
color.getRed(&r2, green: &g2, blue: &b2, alpha: &a2)
return UIColor(red: r1 * (1 - fraction) + r2 * fraction,
green: g1 * (1 - fraction) + g2 * fraction,
blue: b1 * (1 - fraction) + b2 * fraction,
alpha: a1 * (1 - fraction) + a2 * fraction);
}
}
class DrawerShadow: NSObject {
var shadowColor:UIColor = UIColor.blackColor()
var shadowOffset:CGSize = CGSizeMake(0, -1)
var shadowBlurRadius:CGFloat = 0
override init(){
}
}
<file_sep>/OrientalChuShing_Swift/OrientalChuShing/Controllers/MenuViewController.swift
//
// MenuViewController.swift
// OrientalChuShing
//
// Created by <NAME> on 02.09.15.
// Copyright (c) 2015 itinarray. All rights reserved.
//
import UIKit
class MenuViewController: BaseViewController, UIWebViewDelegate {
@IBOutlet weak var webView: UIWebView!
@IBOutlet weak var activityIndicator: UIActivityIndicatorView!
// MARK: - VC lifecycle
override func viewDidLoad() {
super.viewDidLoad()
self.loadWebViewRequest()
}
override func viewDidLayoutSubviews() {
self.activityIndicator.color = Constants.Appearance.GlobalTintColor
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
/*Google analytics*/
let tracker = GAI.sharedInstance().defaultTracker
tracker.set(kGAIScreenName, value: Constants.GoogleAnalytics.trackMenuWebScreenName)
let builder = GAIDictionaryBuilder.createScreenView()
tracker.send(builder.build() as [NSObject : AnyObject])
}
// MARK: - loadWebViewRequest
private func loadWebViewRequest(){
let menuURLRequest = NSMutableURLRequest(URL: Constants.URLs.MenuUrl, cachePolicy: .ReturnCacheDataElseLoad, timeoutInterval: 15)
menuURLRequest.addValue("private", forHTTPHeaderField: "Cache-Control")
self.webView.loadRequest(menuURLRequest)
}
// MARK: - UIWebViewDelegate
func webViewDidStartLoad(webView: UIWebView) {
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
}
func webViewDidFinishLoad(webView: UIWebView) {
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
self.activityIndicator.stopAnimating()
}
func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
self.activityIndicator.stopAnimating()
let alertVC = UIAlertController(title: Constants.LocalStrings.networkErrorTitle.localizedWithComment(""),
message: Constants.LocalStrings.networkErrorText.localizedWithComment(""),
preferredStyle: UIAlertControllerStyle.Alert)
let alertAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Cancel, handler: nil)
alertVC.addAction(alertAction)
self.presentViewController(alertVC, animated: true, completion: nil)
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
<file_sep>/aParts_ObjC/Podfile
platform :ios, '7.1'
pod 'AFNetworking', '~> 2.2.2'
pod 'Google-Maps-iOS-SDK', '~> 1.8'
pod 'SWRevealViewController', :head
pod 'FXBlurView', :head<file_sep>/OrientalChuShing_Swift/OrientalChuShing/Models/CurrentUser.swift
//
// CurrentUser.swift
// OrientalChuShing
//
// Created by <NAME> on 09.09.15.
// Copyright (c) 2015 itinarray. All rights reserved.
//
import UIKit
class CurrentUser: NSObject {
var userFistName:String?
var userEmail:String?
var userCity:String?
var userCountry:String?
var userState:String?
var userStateShort:String?
var userPlatform:String = "IOS"
var userDevice:String?
class var sharedInstance : CurrentUser {
struct Static {
static let instance : CurrentUser = CurrentUser()
}
return Static.instance
}
override init() {
let userDefaults = NSUserDefaults.standardUserDefaults()
userFistName = userDefaults.stringForKey(Constants.UserDefaults.UserFirstNameKey)
userEmail = userDefaults.stringForKey(Constants.UserDefaults.UserEmailKey)
userCountry = userDefaults.stringForKey(Constants.UserDefaults.UserCountryKey)
userState = userDefaults.stringForKey(Constants.UserDefaults.UserStateKey)
userStateShort = userDefaults.stringForKey(Constants.UserDefaults.UserStateShortKey)
userCity = userDefaults.stringForKey(Constants.UserDefaults.UserCityKey)
if(UIDevice.currentDevice().userInterfaceIdiom == .Pad){
userDevice = "ipad"
}else if (UIDevice.currentDevice().userInterfaceIdiom == .Phone){
userDevice = "iphone"
}else{
userDevice = "unspecified"
}
}
func createUser(fistName fistName:String!, email:String!, country:String?, state:String?, city:String?, stateShort:String?){
let userDefaults = NSUserDefaults.standardUserDefaults()
userDefaults.setObject(fistName, forKey: Constants.UserDefaults.UserFirstNameKey)
userDefaults.setObject(email, forKey: Constants.UserDefaults.UserEmailKey)
self.userFistName = fistName
self.userEmail = email
if (country != nil){
userDefaults.setObject(country, forKey: Constants.UserDefaults.UserCountryKey)
self.userCountry = country
}
if (state != nil){
userDefaults.setObject(state, forKey: Constants.UserDefaults.UserStateKey)
self.userState = state
}
if (city != nil){
userDefaults.setObject(city, forKey: Constants.UserDefaults.UserCityKey)
self.userCity = city
}
if(stateShort != nil){
userDefaults.setObject(city, forKey: Constants.UserDefaults.UserStateShortKey)
self.userStateShort = stateShort
}
userDefaults.synchronize()
}
class func isUserLoged() -> Bool{
let userDefaults = NSUserDefaults.standardUserDefaults()
let result:Bool! = userDefaults.boolForKey(Constants.UserDefaults.isLogedKey)
return result
}
}
<file_sep>/MyCarRadar_Swift_WatchKit2/TrackingManager.swift
//
// TrackingManager.swift
// MyCarRadar
//
// Created by <NAME> on 17.09.15.
// Copyright © 2015 itinarray. All rights reserved.
//
import UIKit
import CoreLocation
import CoreMotion
import MapKit
class TrackingManager: NSObject, CLLocationManagerDelegate {
let locationManager:CLLocationManager = CLLocationManager()
let motionManager:CMMotionManager = CMMotionManager()
struct Notifications {
static let DidUpdateLocation = "TrackerDidUpdateLocation"
static let DidFailWithError = "TrackerDidFailWithError"
static let DeniedLocationService = "DeniedLocationService"
}
class var sharedInstance: TrackingManager {
struct Static {
static let instance = TrackingManager()
}
return Static.instance
}
override init() {
super.init()
locationManager.delegate = self
locationManager.distanceFilter = 0.01;
locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation
if(motionManager.magnetometerAvailable){
motionManager.startMagnetometerUpdatesToQueue(NSOperationQueue.mainQueue(), withHandler: { (data, error) -> Void in
if(error != nil){
print("Magnetometer ERROR - \(error?.localizedDescription)")
}else{
print("Magnetometer DATA - \(data)")
}
})
}
}
func startTracking(){
let authorizationStatus = CLLocationManager.authorizationStatus()
switch authorizationStatus {
case .NotDetermined:
locationManager.requestWhenInUseAuthorization()
case .AuthorizedWhenInUse:
locationManager.performSelector("startUpdatingLocation")
case .Denied:
break
default:
break
}
}
func stopTracking(){
locationManager.stopUpdatingLocation()
}
/// MARK - CLLocationManagerDelegate Methods
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard !locations.isEmpty else { return }
dispatch_async(dispatch_get_main_queue()) {
let notificationCenter = NSNotificationCenter.defaultCenter()
notificationCenter.postNotificationName(TrackingManager.Notifications.DidUpdateLocation, object: nil, userInfo: ["location":locations.last!])
}
}
func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
dispatch_async(dispatch_get_main_queue()) {
if(error.code == 0){
return
}
let notificationCenter = NSNotificationCenter.defaultCenter()
notificationCenter.postNotificationName(TrackingManager.Notifications.DidFailWithError, object: nil, userInfo: ["error":error])
}
}
func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
dispatch_async(dispatch_get_main_queue()) {
switch status {
case .AuthorizedWhenInUse:
self.locationManager.performSelector("startUpdatingLocation")
case .Denied:
let notificationCenter = NSNotificationCenter.defaultCenter()
notificationCenter.postNotificationName(TrackingManager.Notifications.DeniedLocationService, object: nil)
break
default:
break
}
}
}
class func mapRegionForAnnotations(locations:[CLLocation]) -> MKCoordinateRegion{
var minLat:Double = 90.0
var maxLat:Double = -90.0
var minLon:Double = 180.0
var maxLon:Double = -180.0
for location:CLLocation in locations{
if ( location.coordinate.latitude < minLat ) {minLat = location.coordinate.latitude}
if ( location.coordinate.latitude > maxLat ) {maxLat = location.coordinate.latitude}
if ( location.coordinate.longitude < minLon ) {minLon = location.coordinate.longitude}
if ( location.coordinate.longitude > maxLon ) {maxLon = location.coordinate.longitude}
}
let latDelta = maxLat - minLat
let lonDelta = maxLon - minLon
let center:CLLocationCoordinate2D = CLLocationCoordinate2DMake((minLat + maxLat)/2.0, (minLon + maxLon)/2.0)
let span:MKCoordinateSpan = MKCoordinateSpanMake(latDelta, lonDelta)
let region:MKCoordinateRegion = MKCoordinateRegionMake(center, span)
return region
}
}
<file_sep>/OrientalChuShing_Swift/OrientalChuShing/Controllers/LangChangeViewController.swift
//
// LangChangeViewController.swift
// OrientalChuShing
//
// Created by <NAME> on 09.09.15.
// Copyright (c) 2015 itinarray. All rights reserved.
//
import UIKit
class LangChangeViewController: BaseViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var tableView: UITableView!
var listOfLocals:[String] = NSBundle.mainBundle().preferredLocalizations
// MARK: - VC lifecycle
override func viewDidLoad() {
super.viewDidLoad()
self.title = "change language".localizedWithComment("").capitalizedString
self.tableView.tableFooterView = UIView(frame: CGRectZero)
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
/*Google analytics*/
let tracker = GAI.sharedInstance().defaultTracker
tracker.set(kGAIScreenName, value: Constants.GoogleAnalytics.trackChooseLangScreenName)
let builder = GAIDictionaryBuilder.createScreenView()
tracker.send(builder.build() as [NSObject : AnyObject])
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - UITableViewDataSource
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return listOfLocals.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell:UITableViewCell = tableView.dequeueReusableCellWithIdentifier(Constants.TableCells.ChooseLangCell, forIndexPath: indexPath)
let localeCode:String = listOfLocals[indexPath.row]
let locale:NSLocale = NSLocale(localeIdentifier: localeCode)
cell.textLabel?.text = locale.displayNameForKey(NSLocaleIdentifier, value: locale.localeIdentifier)
if(locale.localeIdentifier == localeCode){
cell.accessoryType = .Checkmark
}
return cell
}
// MARK: - UITableViewDelegate
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
<file_sep>/OrientalChuShing_Swift/OrientalChuShing/Models/Place.swift
//
// Place.swift
// OrientalChuShing
//
// Created by <NAME> on 02.09.15.
// Copyright (c) 2015 itinarray. All rights reserved.
//
import UIKit
class Place: NSObject {
var title:String = ""
var phone:String = ""
var address:String = ""
var email:String = ""
var workingHours:Dictionary<String,String!> = Dictionary()
var latitude:Double = 0
var longitude:Double = 0
init(dictionary: NSDictionary) {
self.title = dictionary.objectForKey("title") as! String
self.phone = dictionary.objectForKey("phone") as! String
self.address = dictionary.objectForKey("address") as! String
self.email = dictionary.objectForKey("email") as! String
self.workingHours = dictionary.objectForKey("workingHours") as! Dictionary<String,String!>
self.latitude = (dictionary.objectForKey("latitude") as! NSString).doubleValue
self.longitude = (dictionary.objectForKey("longitude") as! NSString).doubleValue
}
}
<file_sep>/OrientalChuShing_Swift/Podfile
platform :ios, "8.0"
source 'https://github.com/CocoaPods/Specs.git'
inhibit_all_warnings!
pod 'Parse'
pod 'Fabric'
pod 'Crashlytics'
pod 'Google/Analytics', '~> 1.0.0'
pod 'ChimpKit'
#pod 'Localize-Swift', '~> 0.1'
<file_sep>/OrientalChuShing_Swift/OrientalChuShing/Vendors/DataManager.swift
//
// DataManager.swift
// OrientalChuShing
//
// Created by <NAME> on 02.09.15.
// Copyright (c) 2015 itinarray. All rights reserved.
//
import UIKit
class DataManager: NSObject, ChimpKitRequestDelegate {
let itemListFilename:String = "places"
struct Static {
static let instance = DataManager()
}
class var sharedInstance: DataManager {
return Static.instance
}
func getAllPlaces() -> NSArray{
let placesArray: NSMutableArray = NSMutableArray()
if let path = NSBundle.mainBundle().pathForResource(itemListFilename, ofType: "plist")
{
if let itemsArray = NSArray(contentsOfFile: path)
{
for item in itemsArray as! [NSDictionary]
{
let placeObj:Place = Place(dictionary: item)
placesArray.addObject(placeObj)
}
}
}
return placesArray
}
func signupUser(fistName fistName:String!, email:String!, latitude:Double?, longitude:Double?){
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
let userDefaults = NSUserDefaults.standardUserDefaults()
userDefaults.setBool(true, forKey: Constants.UserDefaults.isLogedKey)
userDefaults.synchronize()
if(latitude != 0 && longitude != 0 && latitude != nil && longitude != nil){
let locationManager = LocationManager.sharedInstance
locationManager.reverseGeocodeLocationUsingGoogleWithLatLon(latitude: latitude!, longitude: longitude!,
onReverseGeocodingCompletionHandler: { (reverseGecodeInfo, placemark, error) -> Void in
if(error == nil){
let country:String? = reverseGecodeInfo?["country"] as? String
let state:String? = reverseGecodeInfo?["state"] as? String
let stateShort:String? = reverseGecodeInfo?["shortState"] as? String
let city:String? = reverseGecodeInfo?["locality"] as? String
CurrentUser.sharedInstance.createUser(fistName: fistName, email: email, country:country, state:state, city:city, stateShort:stateShort)
}else{
CurrentUser.sharedInstance.createUser(fistName: fistName, email: email, country:nil, state:nil, city:nil, stateShort:nil)
}
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.saveToParse()
self.subscribeToMailChimp()
})
})
}else{
CurrentUser.sharedInstance.createUser(fistName: fistName, email: email, country:nil, state:nil, city:nil, stateShort:nil)
self.saveToParse()
self.subscribeToMailChimp()
}
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
}
//MARK: - Parce.com
private func saveToParse(){
let user:CurrentUser = CurrentUser.sharedInstance
if !Constants.Platform.isSimulator{
/*Parse storing*/
let installation = PFInstallation.currentInstallation()
installation.setObject(user.userFistName!, forKey: Constants.Parse_com.UserFistName)
installation.setObject(user.userEmail!, forKey: Constants.Parse_com.UserEmail)
if(user.userCountry != nil){
installation.setObject(user.userCountry!, forKey: Constants.Parse_com.UserCountry)
}
if(user.userStateShort != nil ){
installation.setObject(user.userStateShort!, forKey: Constants.Parse_com.UserStateShort)
}
if(user.userState != nil){
installation.setObject(user.userState!, forKey: Constants.Parse_com.UserState)
}
if(user.userCity != nil){
installation.setObject(user.userCity!, forKey: Constants.Parse_com.UserCity)
}
//installation.setObject(user.userPlatform, forKey: Constants.Parse_com.UserDeviceSystem)
installation.setObject(user.userDevice!, forKey: Constants.Parse_com.UserDeviceType)
installation.saveInBackground()
}
}
//MARK: - MailChimp
private func subscribeToMailChimp(){
let user:CurrentUser = CurrentUser.sharedInstance
let emailParams:[String: String] = ["email": user.userEmail!]
var userDataParams:[String: AnyObject] = ["FNAME": user.userFistName!, "platform": user.userPlatform, "device": user.userDevice!]
if(user.userCountry != nil){
userDataParams["country"] = user.userCountry
}
if(user.userStateShort != nil ){
userDataParams["state"] = user.userStateShort
}else if(user.userState != nil){
userDataParams["state"] = user.userState
}
if(user.userCity != nil){
userDataParams["city"] = user.userCity
}
let params:[NSObject: AnyObject] = ["id": Constants.MailChimp.ListID, "email":emailParams, "merge_vars": userDataParams, "double_optin" : false, "update_existing" : true];
let requestMethod:String = "lists/subscribe"
ChimpKit.sharedKit().callApiMethod(requestMethod, withParams: params, andDelegate: self)
}
//MARK: - ChimpKitRequestDelegate
func ckRequestFailedWithIdentifier(requestIdentifier: UInt, andError anError: NSError!) {
print("MailChimp Error - " + anError.localizedDescription)
}
func ckRequestIdentifier(requestIdentifier: UInt, didSucceedWithResponse response: NSURLResponse!, andData data: NSData!) {
do {
let jsonResult = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers) as? NSDictionary
if(jsonResult!.isKindOfClass(NSDictionary.self)){
print("MailChimp Response - " + jsonResult!.description)
}
} catch let error as NSError {
print(error)
}
}
}<file_sep>/sheepGame_Spritekit_Swift/SheepSorter/Configs/Types.swift
//
// Types.swift
// SheepSorter
//
// Created by <NAME> on 27.11.15.
// Copyright © 2015 <NAME>. All rights reserved.
//
import Foundation
struct ColorHex {
static let BackgroundColor = "#282554"
static let TextColor = "#e0ebed"
}
struct PhysicsCategory {
static let None: UInt32 = 0
static let Sheep: UInt32 = 0x1 << 1
static let LeftFinish: UInt32 = 0x1 << 2
static let CenterFinish: UInt32 = 0x1 << 3
static let RightFinish: UInt32 = 0x1 << 4
static let Fence: UInt32 = 0x1 << 5
static let LeftGate: UInt32 = 0x1 << 6
static let RightGate: UInt32 = 0x1 << 7
}
enum AxisType {
case Both
case X
case Y
}
struct FontName {
static let RegularFont = "Noteworthy-Bold"
}
struct EffectFileName {
static let AfterSheepDust = "DustParticle.sks"
}
struct SoundFileName {
static let BackgroundMusic = "GameMusic.mp3"
static let Flying = "Spaceship.caf"
static let Explosion = "Explosion.caf"
static let Button = "ButtonTap.caf"
static let Bonus = "MeowBonus.caf"
static let Result = "GameResult.caf"
static let Pop = "PopHigh.caf"
}
struct KeyForUserDefaults {
static let SoundDisabled = "SoundDisabled"
static let MusicDisabled = "MusicDisabled"
static let ControlSensitivity = "ControlSensitivity"
}
struct TextureAtlasFileName {
static let Environment = "Environment"
static let Character = "Character"
static let UserInterface = "UserInterface"
}
struct TextureFileName {
static let Background = "sceneBackground"
static let FullFence = "fullFence"
static let SheepImage = "sheep"
static let LeftGateImage = "leftGate"
static let RightGateImage = "rightGate"
static let LeftArrowImage = "leftArrow"
static let CenterArrowImage = "centerArrow"
static let RightArrowImage = "rightArrow"
}<file_sep>/sheepGame_Spritekit_Swift/SheepSorter/Models/GameSettings.swift
//
// GameSettings.swift
// SheepSorter
//
// Created by <NAME> on 01.12.15.
// Copyright © 2015 <NAME>. All rights reserved.
//
import UIKit
class GameSettings: NSObject {
class var sharedInstance: GameSettings {
struct Static {
static let instance = GameSettings()
}
return Static.instance
}
//MARK: Music & Sound
func isSoundEnabled() -> Bool {
let userDefaults = NSUserDefaults.standardUserDefaults()
return userDefaults.boolForKey(KeyForUserDefaults.SoundDisabled) != true
}
func isMusicEnabled() -> Bool {
let userDefaults = NSUserDefaults.standardUserDefaults()
return userDefaults.boolForKey(KeyForUserDefaults.MusicDisabled) != true
}
//MARK: Control Sensitivity
func getControlSensitivity() -> Int{
let userDefaults = NSUserDefaults.standardUserDefaults()
guard let sesitivity = userDefaults.objectForKey(KeyForUserDefaults.ControlSensitivity) as? NSNumber else {
return ControlSensitivityDef
}
return Int(sesitivity)
}
func setControlSensitivity(sesitivity:Int){
let userDefaults = NSUserDefaults.standardUserDefaults()
userDefaults.setObject(NSNumber(integer:sesitivity), forKey: KeyForUserDefaults.ControlSensitivity)
}
}
<file_sep>/OrientalChuShing_Swift/OrientalChuShing/Controllers/ContactViewController.swift
//
// ContactViewController.swift
// OrientalChuShing
//
// Created by <NAME> on 02.09.15.
// Copyright (c) 2015 itinarray. All rights reserved.
//
import UIKit
import MessageUI
class ContactViewController: BaseViewController, MFMailComposeViewControllerDelegate {
private var navBarHairlineImageView:UIImageView?
@IBOutlet weak var callButton: UIButton!
@IBOutlet weak var emailButton: UIButton!
// MARK: - VC lifecycle
override func viewDidLoad() {
super.viewDidLoad()
self.navBarHairlineImageView = self.findHairlineImageViewUnder(self.navigationController!.navigationBar)
self.setupUIElements()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
navBarHairlineImageView?.hidden = true
/*Google analytics*/
let tracker = GAI.sharedInstance().defaultTracker
tracker.set(kGAIScreenName, value: Constants.GoogleAnalytics.trackContactUsScreenName)
let builder = GAIDictionaryBuilder.createScreenView()
tracker.send(builder.build() as [NSObject : AnyObject])
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
navBarHairlineImageView?.hidden = false
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Setup UI elements
private func findHairlineImageViewUnder(view:UIView) -> UIImageView?{
if(view.isKindOfClass(UIImageView) && view.bounds.size.height <= 1.0){
return view as? UIImageView;
}
for subview:UIView in view.subviews {
let imageView:UIImageView? = self.findHairlineImageViewUnder(subview)
if imageView != nil{
return imageView!
}
}
return nil
}
func setupUIElements() {
self.callButton.backgroundColor = Constants.Appearance.GlobalTintColor
self.emailButton.backgroundColor = Constants.Appearance.GlobalTintColor
let paragraph = NSMutableParagraphStyle()
paragraph.alignment = NSTextAlignment.Center
let attrs = [NSFontAttributeName : UIFont.systemFontOfSize(16.0), NSForegroundColorAttributeName : UIColor.whiteColor(), NSParagraphStyleAttributeName : paragraph]
let attrsForEmailAndPhone = [NSFontAttributeName : UIFont.systemFontOfSize(14.0), NSForegroundColorAttributeName : UIColor.whiteColor(), NSParagraphStyleAttributeName : paragraph]
let callTitle = NSMutableAttributedString(string: "Call us".localizedWithComment(""), attributes:attrs)
let emailTitle = NSMutableAttributedString(string: "Email us".localizedWithComment(""), attributes:attrs)
let phoneString = NSAttributedString(string: ":\n" + Constants.AppData.AppBusinessPhone, attributes:attrsForEmailAndPhone)
let emailString = NSAttributedString(string: ":\n" + Constants.AppData.AppBusinessEmail, attributes:attrsForEmailAndPhone)
callTitle.appendAttributedString(phoneString)
emailTitle.appendAttributedString(emailString)
self.callButton.setAttributedTitle(callTitle, forState: UIControlState.Normal)
self.emailButton.setAttributedTitle(emailTitle, forState: UIControlState.Normal)
}
// MARK: - Buttons actions
@IBAction func callButtonPressed(sender: AnyObject) {
let phoneNumber = Constants.AppData.AppBusinessPhone.stringByReplacingOccurrencesOfString(" ", withString: "")
let phone = "tel://" + phoneNumber;
let url:NSURL = NSURL(string:phone)!;
if(UIApplication.sharedApplication().canOpenURL(url)){
UIApplication.sharedApplication().openURL(url);
}
}
@IBAction func emailButtonPressed(sender: AnyObject) {
let picker = MFMailComposeViewController()
picker.setToRecipients([Constants.AppData.AppBusinessEmail])
picker.mailComposeDelegate = self
picker.setSubject(Constants.LocalStrings.mailContactUsSubject.localizedWithComment(""))
picker.navigationBar.tintColor = UIColor.whiteColor()
picker.navigationBar.barTintColor = UIColor.whiteColor()
if(MFMailComposeViewController.canSendMail()){
picker.navigationBar.barTintColor = Constants.Appearance.GlobalTintColor
picker.navigationBar.tintColor = UIColor.whiteColor()
picker.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName : UIColor.whiteColor()]
self.presentViewController(picker, animated: true, completion: nil)
}else{
let alertVC = UIAlertController(title: Constants.LocalStrings.sendEmailErrorTitle.localizedWithComment(""),
message: Constants.LocalStrings.sendEmailErrorText.localizedWithComment(""),
preferredStyle: UIAlertControllerStyle.Alert)
let alertAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Cancel, handler: nil)
alertVC.addAction(alertAction)
self.presentViewController(alertVC, animated: true, completion: nil)
return
}
}
// MARK: - MFMailComposeViewControllerDelegate Method
func mailComposeController(controller: MFMailComposeViewController, didFinishWithResult result: MFMailComposeResult, error: NSError?) {
controller.dismissViewControllerAnimated(true, completion: nil)
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
<file_sep>/OrientalChuShing_Swift/OrientalChuShing/Controllers/PlacesViewController.swift
//
// PlacesViewController.swift
// OrientalChuShing
//
// Created by <NAME> on 02.09.15.
// Copyright (c) 2015 itinarray. All rights reserved.
//
import UIKit
class PlacesViewController: BaseViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var tableView: UITableView!
var placesArray:[Place] = NSArray() as! [Place]
var selectedIndex:Int = 0
// MARK: - VC lifecycle
override func viewDidLoad() {
super.viewDidLoad()
self.placesArray = DataManager.sharedInstance.getAllPlaces() as! [Place]
self.tableView.tableFooterView = UIView(frame: CGRectZero)
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.startLocationMonitoring()
/*Google analytics*/
let tracker = GAI.sharedInstance().defaultTracker
tracker.set(kGAIScreenName, value: Constants.GoogleAnalytics.trackFindLocationScreenName)
let builder = GAIDictionaryBuilder.createScreenView()
tracker.send(builder.build() as [NSObject : AnyObject])
}
override func viewDidDisappear(animated: Bool) {
super.viewDidDisappear(animated)
let locationManager = LocationManager.sharedInstance
locationManager.stopUpdatingLocation()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Location service
func startLocationMonitoring(){
/*Start Location Service*/
let locationManager = LocationManager.sharedInstance
locationManager.showVerboseMessage = false
locationManager.autoUpdate = true
locationManager.startUpdatingLocationWithCompletionHandler { (latitude, longitude, status, verboseMessage, error) -> () in
dispatch_async(dispatch_get_main_queue(), { () -> Void in
let nc = NSNotificationCenter.defaultCenter()
nc.postNotificationName(Constants.kMyCoordinatesUpdatedNotification, object:nil, userInfo:["latitude":latitude, "longitude":longitude])
})
}
}
// MARK: - UITableViewDataSource
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.placesArray.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell:PlaceTableViewCell = tableView.dequeueReusableCellWithIdentifier(Constants.TableCells.PlaceListCell) as! PlaceTableViewCell
let placeObj:Place! = self.placesArray[indexPath.row] as Place
if let place = placeObj{
cell.place = place
}
return cell
}
// MARK: - UITableViewDelegate
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
self.selectedIndex = indexPath.row
self.performSegueWithIdentifier(Constants.Segues.PlacesToPlaceDetailes, sender: self)
}
// MARK: - Navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let segueId:String! = segue.identifier
switch segueId{
case Constants.Segues.PlacesToPlaceDetailes:
let placeDetailedVC:PlaceDetailesViewController = segue.destinationViewController as! PlaceDetailesViewController
placeDetailedVC.place = self.placesArray[self.selectedIndex]
default:
break
}
}
}
<file_sep>/OrientalChuShing_Swift/OrientalChuShing/Controllers/SettingsViewController.swift
//
// SettingsViewController.swift
// OrientalChuShing
//
// Created by <NAME> on 09.09.15.
// Copyright (c) 2015 itinarray. All rights reserved.
//
import UIKit
class SettingsViewController: BaseViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var tableView: UITableView!
// MARK: - VC lifecycle
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Settings".localizedWithComment("")
self.tableView.tableFooterView = UIView(frame: CGRectZero)
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
/*Google analytics*/
let tracker = GAI.sharedInstance().defaultTracker
tracker.set(kGAIScreenName, value: Constants.GoogleAnalytics.trackSettingsScreenName)
let builder = GAIDictionaryBuilder.createScreenView()
tracker.send(builder.build() as [NSObject : AnyObject])
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - UITableViewDataSource
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return Constants.SettingsList.MenuItems.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell:UITableViewCell = tableView.dequeueReusableCellWithIdentifier(Constants.TableCells.SettingsMenuItem, forIndexPath: indexPath)
cell.textLabel?.text = Constants.SettingsList.MenuItems[indexPath.row].localizedWithComment("").capitalizedString
return cell
}
// MARK: - UITableViewDelegate
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
switch Constants.SettingsList.MenuItems[indexPath.row]{
case "change language":
self.performSegueWithIdentifier(Constants.Segues.SettingsToLangChoose, sender: self)
default:
break
}
}
// MARK: - Navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
}
}
<file_sep>/OrientalChuShing_Swift/OrientalChuShing/Controllers/MapViewController.swift
//
// MapViewController.swift
// OrientalChuShing
//
// Created by <NAME> on 03.09.15.
// Copyright (c) 2015 itinarray. All rights reserved.
//
import UIKit
import MapKit
class MapViewController: BaseViewController, MKMapViewDelegate {
@IBOutlet weak var mapView: MKMapView!
var place:Place? = nil
let regionRadius: CLLocationDistance = 1000
var isDirection:Bool = false
override func viewDidLoad() {
super.viewDidLoad()
// set initial location of Place
if(self.place != nil){
let initialLocation = CLLocation(latitude: self.place!.latitude, longitude: self.place!.longitude)
centerMapOnLocation(initialLocation)
let anotation = MKPointAnnotation()
anotation.coordinate = CLLocationCoordinate2D(latitude: self.place!.latitude, longitude: self.place!.longitude)
anotation.title = self.place?.title
anotation.subtitle = self.place?.address
mapView.addAnnotation(anotation)
if(isDirection){
calculateDirectionFromToPlace()
}
}
}
func calculateDirectionFromToPlace(){
let destCoordinates:CLLocationCoordinate2D = CLLocationCoordinate2D(latitude: self.place!.latitude, longitude: self.place!.longitude)
let desitnationPlacemark = MKPlacemark(coordinate: destCoordinates, addressDictionary: nil)
let destination:MKMapItem = MKMapItem(placemark: desitnationPlacemark)
// MKMapItem.openMapsWithItems([destination], launchOptions:[MKLaunchOptionsDirectionsModeKey:MKLaunchOptionsDirectionsModeDriving, MKLaunchOptionsShowsTrafficKey:true])
let request:MKDirectionsRequest = MKDirectionsRequest()
request.source = MKMapItem.mapItemForCurrentLocation()
request.destination = destination
request.transportType = MKDirectionsTransportType.Automobile
let directions = MKDirections(request: request)
directions.calculateDirectionsWithCompletionHandler ({
(response: MKDirectionsResponse?, error: NSError?) in
if error == nil {
self.showRoute(response!)
}
else{
print("trace the error \(error?.localizedDescription)")
}
})
}
func showRoute(response:MKDirectionsResponse){
for route in response.routes {
self.mapView.addOverlay(route.polyline, level: MKOverlayLevel.AboveRoads)
let routeSeconds = route.expectedTravelTime
let routeDistance = route.distance
print("distance between two points is \(routeSeconds) and \(routeDistance)")
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func centerMapOnLocation(location: CLLocation) {
let coordinateRegion = MKCoordinateRegionMakeWithDistance(location.coordinate,
regionRadius * 2.0, regionRadius * 2.0)
mapView.setRegion(coordinateRegion, animated: true)
}
// MARK: - MKMapViewDelegate
func mapViewDidFinishLoadingMap(mapView: MKMapView) {
}
func mapView(mapView: MKMapView, didUpdateUserLocation userLocation: MKUserLocation) {
if(isDirection){
let delayTime = dispatch_time(DISPATCH_TIME_NOW, Int64(2 * Double(NSEC_PER_SEC)))
dispatch_after(delayTime, dispatch_get_main_queue()) {
let curCoordinates:CLLocationCoordinate2D = userLocation.coordinate
self.mapView.setCenterCoordinate(curCoordinates, animated: true)
}
}
}
func mapView(mapView: MKMapView, rendererForOverlay overlay: MKOverlay) -> MKOverlayRenderer {
if(overlay.isKindOfClass(MKPolyline)){
let poliline:MKPolyline = overlay as! MKPolyline
let polilineRender:MKPolylineRenderer = MKPolylineRenderer(polyline: poliline)
polilineRender.strokeColor = Constants.Appearance.GlobalTintColor
return polilineRender
}else{
return MKOverlayRenderer()
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
<file_sep>/OrientalChuShing_Swift/OrientalChuShing/Controllers/SignUpViewController.swift
//
// SignUpViewController.swift
// OrientalChuShing
//
// Created by <NAME> on 08.09.15.
// Copyright (c) 2015 itinarray. All rights reserved.
//
import UIKit
class SignUpViewController: BaseViewController, UITextFieldDelegate {
@IBOutlet weak var formWrapperView: UIView!
@IBOutlet weak var firstNameField: UITextField!
@IBOutlet weak var emailField: UITextField!
@IBOutlet weak var signUpBtn: UIButton!
@IBOutlet weak var skipBtn: UIButton!
@IBOutlet weak var siteAdressLabel: UILabel!
var userLatitude:Double?
var userLongitude:Double?
// MARK: - VC lifecycle
override func viewDidLoad() {
super.viewDidLoad()
setupUIElements()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.startLocationMonitoring()
/*Google analytics*/
let tracker = GAI.sharedInstance().defaultTracker
tracker.set(kGAIScreenName, value: Constants.GoogleAnalytics.trackSignUpScreenName)
let builder = GAIDictionaryBuilder.createScreenView()
tracker.send(builder.build() as [NSObject : AnyObject])
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewDidDisappear(animated: Bool) {
super.viewDidDisappear(animated)
let locationManager = LocationManager.sharedInstance
locationManager.stopUpdatingLocation()
}
// MARK: - Location service
func startLocationMonitoring(){
/*Start Location Service*/
let locationManager = LocationManager.sharedInstance
locationManager.showVerboseMessage = false
locationManager.autoUpdate = true
locationManager.startUpdatingLocationWithCompletionHandler { (latitude, longitude, status, verboseMessage, error) -> () in
dispatch_async(dispatch_get_main_queue(), { () -> Void in
if(error == nil){
self.userLatitude = latitude;
self.userLongitude = longitude;
}
})
}
}
// MARK: - Setup UI
func setupUIElements(){
self.navigationItem.titleView = UIImageView(image: UIImage(named: "NavBarTitleLogo"))
self.view.backgroundColor = Constants.Appearance.GlobalTintColor
self.siteAdressLabel.text = Constants.AppData.AppBusinessSite
let attrNamePlaceholderText = NSAttributedString(string:"First name".localizedWithComment(""), attributes:[NSForegroundColorAttributeName: Constants.Appearance.GlobalTintColor])
self.firstNameField.attributedPlaceholder = attrNamePlaceholderText
self.firstNameField.textColor = Constants.Appearance.GlobalTintColor
let attrEmailPlaceholderText = NSAttributedString(string:"Email".localizedWithComment(""), attributes:[NSForegroundColorAttributeName: Constants.Appearance.GlobalTintColor])
self.emailField.attributedPlaceholder = attrEmailPlaceholderText
self.emailField.textColor = Constants.Appearance.GlobalTintColor
self.signUpBtn.setTitle("Sign up".localizedWithComment("").uppercaseString, forState: .Normal)
self.signUpBtn.backgroundColor = Constants.Appearance.GlobalTintColor
self.signUpBtn.setTitleColor(UIColor.whiteColor(), forState: .Normal)
self.skipBtn.setTitle("Skip".localizedWithComment(""), forState: .Normal)
self.skipBtn.backgroundColor = UIColor.clearColor()
self.skipBtn.setTitleColor(UIColor.lightGrayColor(), forState: .Normal)
let tapGesture:UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "tapOnView:")
self.view.addGestureRecognizer(tapGesture)
if(Constants.SettingsList.IsSettingsVisisble){
self.navigationItem.rightBarButtonItem = UIBarButtonItem(image: UIImage(named: "NavBarSettings") , style: UIBarButtonItemStyle.Plain, target: self, action: "navBarSettingsPressed")
}
}
// MARK: - UI actions
func tapOnView(sender:UIView){
for subview in formWrapperView.subviews{
if(subview.isKindOfClass(UITextField) && subview.isFirstResponder()){
subview.resignFirstResponder()
}
}
}
@IBAction func signUpBtnPressed(sender: AnyObject) {
if validateAllfields(firstNameField, emailField){
DataManager.sharedInstance.signupUser(fistName: firstNameField.text, email: emailField.text, latitude:self.userLatitude, longitude:self.userLongitude)
goToMainNavigationController()
}
}
@IBAction func skipBtnPressed(sender: AnyObject) {
goToMainNavigationController()
}
func navBarSettingsPressed(){
self.performSegueWithIdentifier(Constants.Segues.SignUpToSettings, sender: self)
}
// MARK: - Text fields validation
func isValidEmail(testStr:String) -> Bool {
// println("validate calendar: \(testStr)")
let emailRegEx = "^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$"
let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
return emailTest.evaluateWithObject(testStr)
}
func isValidFirstName(fistName:String) -> Bool {
return fistName.characters.count > 0
}
func validateAllfields(textFields:UITextField...) -> Bool{
for textField in textFields{
if textField == emailField {
if(!self.isValidEmail(textField.text!)){
markFieldAsNotValid(textField)
return false
}
} else if textField == firstNameField{
if(!self.isValidFirstName(textField.text!)){
markFieldAsNotValid(textField)
return false
}
}
}
return true
}
func markFieldAsNotValid(textField:UITextField){
textField.text = ""
var fieldErrorString = ""
if textField == emailField{
fieldErrorString = "*" + "Incorrect Email".localizedWithComment("") + "*"
}else if textField == firstNameField{
fieldErrorString = "*" + "Name can`t be empty".localizedWithComment("") + "*"
}
let attrEmailPlaceholderText = NSAttributedString(string:fieldErrorString, attributes:[NSForegroundColorAttributeName: Constants.Appearance.GlobalTintColor])
textField.attributedPlaceholder = attrEmailPlaceholderText
textField.becomeFirstResponder()
}
// MARK: - UITextFieldDelegate
func textFieldShouldReturn(textField: UITextField) -> Bool {
if textField == emailField {
self.view.endEditing(true)
} else if textField == firstNameField{
emailField.becomeFirstResponder()
}
validateAllfields(textField)
return true
}
// MARK: - Navigation
func goToMainNavigationController(){
let appDelegate:AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
appDelegate.transitionToMainNavigationController()
}
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
}
<file_sep>/OrientalChuShing_Swift/OrientalChuShing/Controllers/PlaceDetailesViewController.swift
//
// PlaceDetailesViewController.swift
// OrientalChuShing
//
// Created by <NAME> on 03.09.15.
// Copyright (c) 2015 itinarray. All rights reserved.
//
import UIKit
import MessageUI
import MapKit
class PlaceDetailesViewController: BaseViewController, UITableViewDataSource, UITableViewDelegate, MFMailComposeViewControllerDelegate {
@IBOutlet weak var hoursTableTitle: UILabel!
@IBOutlet weak var hoursTableView: UITableView!
@IBOutlet weak var placeTitleLabel: UILabel!
@IBOutlet weak var phoneBtn: UIButton!
@IBOutlet weak var emailBtn: UIButton!
@IBOutlet weak var directionMapBtn: UIButton!
@IBOutlet weak var tableBottomSpace: NSLayoutConstraint!
var place:Place!
// MARK: - VC lifecycle
override func viewDidLoad() {
super.viewDidLoad()
self.setupUIElements()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
/*Google analytics*/
let tracker = GAI.sharedInstance().defaultTracker
tracker.set(kGAIScreenName, value: Constants.GoogleAnalytics.trackPlaceScreenName + " " + place.title)
let builder = GAIDictionaryBuilder.createScreenView()
tracker.send(builder.build() as [NSObject : AnyObject])
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Setup UI
func setupUIElements() {
self.title = "Details".localizedWithComment("")
self.placeTitleLabel.text = self.place.title
self.phoneBtn.backgroundColor = Constants.Appearance.GlobalTintColor
self.emailBtn.backgroundColor = Constants.Appearance.GlobalTintColor
self.directionMapBtn.setTitle("Get Direction".localizedWithComment(""), forState: .Normal)
self.directionMapBtn.backgroundColor = Constants.Appearance.GlobalTintColor
let paragraph = NSMutableParagraphStyle()
paragraph.alignment = NSTextAlignment.Center
let attrs = [NSFontAttributeName : UIFont.systemFontOfSize(16.0), NSForegroundColorAttributeName : UIColor.whiteColor(), NSParagraphStyleAttributeName : paragraph]
let phoneBtnTitle = NSAttributedString(string: "Call Us".localizedWithComment(""), attributes:attrs)
let emailBtnTitle = NSAttributedString(string: "Email Us".localizedWithComment(""), attributes:attrs)
self.phoneBtn.setAttributedTitle(phoneBtnTitle, forState: UIControlState.Normal)
self.emailBtn.setAttributedTitle(emailBtnTitle, forState: UIControlState.Normal)
self.hoursTableTitle.text = "Working Hours".localizedWithComment("")
//Fix table height for iphone4
if(UIScreen.mainScreen().bounds.height == 480){
self.tableBottomSpace.constant = 20;
}
}
// MARK: - Buttons Actions
@IBAction func phoneBtnPressed(sender: AnyObject) {
let phoneNumber = Constants.AppData.AppBusinessPhone.stringByReplacingOccurrencesOfString(" ", withString: "")
let phone = "tel://" + phoneNumber;
let url:NSURL = NSURL(string:phone)!;
if(UIApplication.sharedApplication().canOpenURL(url)){
UIApplication.sharedApplication().openURL(url);
}
}
@IBAction func emailBtnPressed(sender: AnyObject) {
let picker = MFMailComposeViewController()
picker.setToRecipients([self.place.email])
picker.mailComposeDelegate = self
picker.setSubject("To " + self.place.title)
picker.navigationBar.tintColor = UIColor.whiteColor()
picker.navigationBar.barTintColor = UIColor.whiteColor()
if(MFMailComposeViewController.canSendMail()){
picker.navigationBar.barTintColor = Constants.Appearance.GlobalTintColor
picker.navigationBar.tintColor = UIColor.whiteColor()
picker.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName : UIColor.whiteColor()]
self.presentViewController(picker, animated: true, completion: nil)
}else{
let alertVC = UIAlertController(title: Constants.LocalStrings.sendEmailErrorTitle.localizedWithComment(""),
message: Constants.LocalStrings.sendEmailErrorText.localizedWithComment(""),
preferredStyle: UIAlertControllerStyle.Alert)
let alertAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Cancel, handler: nil)
alertVC.addAction(alertAction)
self.presentViewController(alertVC, animated: true, completion: nil)
return
}
}
//Not used
@IBAction func showOnMapBtnPressed(sender: AnyObject) {
self.performSegueWithIdentifier(Constants.Segues.PlaceDetailesToMap, sender: sender)
}
@IBAction func directionBtnPressed(sender: AnyObject) {
let locationManager:LocationManager = LocationManager.sharedInstance
let destCoordinates:CLLocationCoordinate2D = CLLocationCoordinate2D(latitude: self.place!.latitude, longitude: self.place!.longitude)
let coordinates:CLLocation = CLLocation(latitude: self.place!.latitude, longitude: self.place!.longitude)
locationManager.reverseGeocodeLocationWithCoordinates(coordinates) { (reverseGecodeInfo, placemark, error) -> Void in
if((error) != nil){
let desitnationPlacemark = MKPlacemark(coordinate: destCoordinates, addressDictionary: nil)
let destinationEmpty:MKMapItem = MKMapItem(placemark: desitnationPlacemark)
MKMapItem.openMapsWithItems([destinationEmpty], launchOptions:[MKLaunchOptionsDirectionsModeKey:MKLaunchOptionsDirectionsModeDriving, MKLaunchOptionsShowsTrafficKey:true])
return
}
let desitnationPlacemark = MKPlacemark(placemark: placemark!)
let destination:MKMapItem = MKMapItem(placemark: desitnationPlacemark)
MKMapItem.openMapsWithItems([destination],
launchOptions:[MKLaunchOptionsDirectionsModeKey:MKLaunchOptionsDirectionsModeDriving, MKLaunchOptionsShowsTrafficKey:true])
}
//self.performSegueWithIdentifier(Constants.Segues.PlaceDetailesToMap, sender: sender)
}
// MARK: - UITableViewDataSource
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 7
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell:WorkingHoursTableViewCell = tableView.dequeueReusableCellWithIdentifier(Constants.TableCells.WorkingHoursCell) as! WorkingHoursTableViewCell
let day:String = Constants.AppData.AppWeekDaysArray[indexPath.row] as! String
cell.dayLabel.text = day.localizedWithComment("") + ":"
cell.hoursLabel.text = self.place.workingHours[day]!;
return cell
}
// MARK: - MFMailComposeViewControllerDelegate Method
func mailComposeController(controller: MFMailComposeViewController, didFinishWithResult result: MFMailComposeResult, error: NSError?) {
controller.dismissViewControllerAnimated(true, completion: nil)
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return tableView.frame.size.height / 7
}
// MARK: - Navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if(segue.identifier == Constants.Segues.PlaceDetailesToMap){
let mapVC:MapViewController = segue.destinationViewController as! MapViewController
mapVC.title = self.place.title
mapVC.place = self.place
if(sender === self.directionMapBtn){
mapVC.isDirection = true
}
}
}
}
<file_sep>/sheepGame_Spritekit_Swift/SheepSorter/Nodes/SheepNode.swift
//
// SheepNode.swift
// SheepSorter
//
// Created by <NAME> on 27.11.15.
// Copyright © 2015 <NAME>. All rights reserved.
//
import SpriteKit
enum SheepType {
case Regular
case Left
case Center
case Right
static func randomSheepType() -> SheepType {
var types = [SheepType]()
types << .Regular
types << .Left
types << .Center
types << .Right
let randTypeInt = Int.random(min:1, max:3)
return types[randTypeInt]
}
}
class SheepNode: SKSpriteNode {
var sheepType:SheepType!;
private var dustEmitterNode = SKEmitterNode(fileNamed: EffectFileName.AfterSheepDust)
init(sheepType:SheepType, position:CGPoint) {
let texture = SKTexture(imageNamed: TextureFileName.SheepImage)
super.init(texture: texture, color: UIColor.clearColor(), size: SheepSize)
name = "Sheep"
anchorPoint = CGPointMake(0.5, 0.5)
self.position = position
zPosition = 6
physicsBody = addPhysicsBodyToFence()
physicsBody!.pinned = false
physicsBody!.dynamic = true
physicsBody!.allowsRotation = true
physicsBody!.density = 0.1
physicsBody!.restitution = 0.1
physicsBody!.linearDamping = 0.3
physicsBody!.angularDamping = 0.7
physicsBody!.usesPreciseCollisionDetection = true
physicsBody!.categoryBitMask = PhysicsCategory.Sheep
physicsBody!.contactTestBitMask = PhysicsCategory.LeftGate | PhysicsCategory.RightGate | PhysicsCategory.Fence
physicsBody!.collisionBitMask = PhysicsCategory.LeftGate | PhysicsCategory.RightGate | PhysicsCategory.Fence | PhysicsCategory.Sheep
self.sheepType = sheepType;
addArrowOnSheep()
self.addDustForRunningSheep()
}
init(color: UIColor, size: CGSize) {
super.init(texture: nil, color: color, size: size)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func addPhysicsBodyToFence() -> SKPhysicsBody{
let sheepBodySize = CGSizeMake(self.size.width - 10, self.size.height - 10)
let sheepBodyPath = CGPathCreateWithEllipseInRect(CGRectMake(-sheepBodySize.width / 2, -sheepBodySize.height / 2, sheepBodySize.width, sheepBodySize.height), nil)
let sheepBody = SKPhysicsBody(polygonFromPath: sheepBodyPath)
return sheepBody;
}
private func addArrowOnSheep(){
switch self.sheepType!{
case .Left:
createArrowNode(TextureFileName.LeftArrowImage)
case .Center:
createArrowNode(TextureFileName.CenterArrowImage)
case .Right:
createArrowNode(TextureFileName.RightArrowImage)
default:
break
}
}
private func createArrowNode(imageNamed:String) -> SKSpriteNode{
let arrowNode = SKSpriteNode(imageNamed: imageNamed)
arrowNode.anchorPoint = CGPointMake(0.5, 0.4)
arrowNode.size = ArrowSize
arrowNode.zPosition = 1
self.addChild(arrowNode)
return arrowNode
}
private func addDustForRunningSheep(){
dustEmitterNode!.position = CGPoint(x: 0, y: 10)
dustEmitterNode!.resetSimulation()
//dustEmitterNode!.zPosition = zPosition
self.addChild(dustEmitterNode!)
}
}
<file_sep>/OrientalChuShing_Swift/OrientalChuShing/Application/Constants.swift
//
// Constants.swift
// OrientalChuShing
//
// Created by <NAME> on 02.09.15.
// Copyright (c) 2015 itinarray. All rights reserved.
//
import Foundation
import UIKit
struct Constants {
static let kMyCoordinatesUpdatedNotification = "kMyCoordinatesUpdatedNotification"
/*******************************
* *
* App Personalization *
* *
*******************************/
struct URLs {
static let MenuUrl:NSURL! = NSURL(string: "http://m.orientalchushing.com/menu")
}
struct SettingsList {
static let IsSettingsVisisble:Bool = false
static let MenuItems:[String] = ["change language"] //Array with strings
}
struct Appearance {
//static let NavBarColor:UIColor = UIColor(red:0.824, green:0, blue:0, alpha:1)
static let GlobalTintColor:UIColor = UIColor(red:0.824, green:0, blue:0, alpha:1)
}
struct AppData {
static let MenuMenuItems = ["Menu", "Find a Location", "Contact Us"]
static let AppBusinessSite:String = "orientalchushing.com"
static let AppBusinessPhone:String = "(613) 233-8818"
static let AppBusinessEmail:String = "<EMAIL>"
static let AppDistanceLimit:Float = 30000 //meters
static let AppWeekDaysArray:NSArray = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
}
struct GoogleAnalytics {
static let TrackID:String = "UA-67438303-1"
//screens
static let trackSignUpScreenName = "sign up"
static let trackMainScreenName = "menu"
static let trackMenuWebScreenName = "menu web"
static let trackContactUsScreenName = "contact us"
static let trackFindLocationScreenName = "find a location"
static let trackPlaceScreenName = "place details:"
static let trackSettingsScreenName = "settings"
static let trackChooseLangScreenName = "lang selection"
static let trackPushWebScreenName = "push hyperlink"
//events
}
struct Parse_com {
static let AppID:String = "y8PgMMVMhWBdVU5KImHPGAiOLHaEna1iwXTghwE5"
static let ClientID:String = "Z1Gk3oScPkSKnh9Nq8egIVgm4ZORXQY5E3EbSOKt"
static let UserEmail:String = "email"
static let UserFistName:String = "firstName"
static let UserCountry:String = "country"
static let UserState:String = "state"
static let UserStateShort:String = "stateShort"
static let UserCity:String = "city"
static let UserDeviceSystem:String = "deviceType"
static let UserDeviceType:String = "deviceSize"
static let UserPushType:String = "pushType"
}
struct MailChimp {
static let ApiKey:String = "<KEY>"
static let ListID:String = "f61631794f"
}
/*******************************
* *
* System Constants *
* *
*******************************/
struct Path {
static let Documents = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0]
static let Tmp = NSTemporaryDirectory()
}
struct Segues {
static let SignUpToSettings:String = "SignUpToSettings"
static let MainToSettings:String = "MainToSettings"
static let MainToMenu:String = "MainToMenu"
static let MainToPlaces:String = "MainToPlaces"
static let MainToAboutUs:String = "MainToAboutUs"
static let MainToContactUs:String = "MainToContactUs"
static let PlacesToPlaceDetailes:String = "PlacesToPlaceDetailes"
static let PlaceDetailesToMap:String = "PlaceDetailesToMap"
static let MainToWebBrowser:String = "MainToWebBrowser"
static let SettingsToLangChoose:String = "SettingsToLangChoose"
}
struct TableCells {
static let MainMenuCell = "mainMenuCell"
static let PlaceListCell = "placeListCell"
static let WorkingHoursCell = "WorkingHoursCell"
static let SettingsMenuItem = "SettingsMenuItem"
static let ChooseLangCell = "ChooseLangCell"
}
struct ViewControllersId {
static let SignUpVCId = "signUpNavVC"
static let MainVCId = "mainNavVC"
}
struct UserDefaults {
static let isLogedKey = "isUserLogedInApp"
static let UserFirstNameKey = "userFirstName"
static let UserEmailKey = "userEmail"
static let UserCountryKey = "userCountry"
static let UserStateKey = "userState"
static let UserStateShortKey = "userStateShort"
static let UserCityKey = "userCity"
}
struct LocalStrings{
static let networkErrorTitle = "networkErrorTitle"
static let networkErrorText = "networkErrorText"
static let sendEmailErrorTitle = "sendEmailErrorTitle"
static let sendEmailErrorText = "sendEmailErrorText"
static let mailContactUsSubject = "mailContactUsSubject"
}
struct Platform {
static let isSimulator: Bool = {
var isSim = false
#if arch(i386) || arch(x86_64)
isSim = true
#endif
return isSim
}()
}
}
public extension NSObject{
public class var classNameToString: String{
return NSStringFromClass(self).componentsSeparatedByString(".").last!
}
public var classNameToString: String{
return NSStringFromClass(self.dynamicType).componentsSeparatedByString(".").last!
}
}
extension String {
func localizedWithComment(comment:String) -> String {
return NSLocalizedString(self, tableName: nil, bundle: NSBundle.mainBundle(), value: "", comment: comment)
}
}
<file_sep>/sheepGame_Spritekit_Swift/SheepSorter/Nodes/GatesNode.swift
//
// GatesNode.swift
// SheepSorter
//
// Created by <NAME> on 27.11.15.
// Copyright © 2015 <NAME>. All rights reserved.
//
import SpriteKit
enum GateSide {
case Left
case Right
}
class LeftGatesNode: SKSpriteNode{
var side:GateSide?
init(position:CGPoint){
let texture = SKTexture(imageNamed: TextureFileName.LeftGateImage)
super.init(texture: texture, color: UIColor.clearColor(), size: texture.size())
self.position = position
zPosition = 3
anchorPoint = CGPointMake(0.5, 0.06)
size = GatesSize
side = .Left
physicsBody = SKPhysicsBody(polygonFromPath: CGPathCreateWithRect(CGRectMake(0, 0, size.width / 4, size.height - 7), nil))
physicsBody!.pinned = true
physicsBody!.density = 1
physicsBody!.restitution = 0
physicsBody!.linearDamping = 0;
physicsBody!.angularDamping = 0;
physicsBody!.usesPreciseCollisionDetection = true
physicsBody!.categoryBitMask = PhysicsCategory.LeftGate
physicsBody!.contactTestBitMask = PhysicsCategory.Fence | PhysicsCategory.RightGate
physicsBody!.collisionBitMask = PhysicsCategory.Fence | PhysicsCategory.RightGate
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class RightGatesNode: SKSpriteNode{
var side:GateSide?
init(position:CGPoint){
let texture = SKTexture(imageNamed: TextureFileName.RightGateImage)
super.init(texture: texture, color: UIColor.clearColor(), size: texture.size())
self.position = position
zPosition = 3
anchorPoint = CGPointMake(0.5, 0.06)
size = GatesSize
side = .Right
physicsBody = SKPhysicsBody(polygonFromPath: CGPathCreateWithRect(CGRectMake(-size.width / 4, 0, size.width / 4, size.height - 7), nil))
physicsBody!.pinned = true
physicsBody!.density = 1
physicsBody!.restitution = 0
physicsBody!.linearDamping = 0;
physicsBody!.angularDamping = 0;
physicsBody!.usesPreciseCollisionDetection = true
physicsBody!.categoryBitMask = PhysicsCategory.RightGate
physicsBody!.contactTestBitMask = PhysicsCategory.Fence | PhysicsCategory.LeftGate
physicsBody?.collisionBitMask = PhysicsCategory.Fence | PhysicsCategory.LeftGate
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
<file_sep>/sheepGame_Spritekit_Swift/SheepSorter/Scenes/GameScene.swift
//
// GameScene.swift
// SheepSorter
//
// Created by <NAME> on 19.11.15.
// Copyright (c) 2015 <NAME>. All rights reserved.
//
import SpriteKit
class GameScene: SKScene, SKPhysicsContactDelegate {
// MARK: - Nodes
let background = BackgroundNode(imageNamed: TextureFileName.Background)
let leftGate = LeftGatesNode(position: CGPointMake(124, 100))
let rightGate = RightGatesNode(position: CGPointMake(196, 100))
let fence = FenceNode()
let scoreLabel = ScoreLabelNode()
// MARK: - Data
let gameSettings = GameSettings.sharedInstance
// MARK: - Scene vars
var leftTouch:UITouch?;
var rightTouch:UITouch?;
private var touchPosition: CGFloat = 0
private var targetZRotation: CGFloat = 0
var scoreValue:Int = 0;
private lazy var popSoundAction = SKAction.playSoundFileNamed(SoundFileName.Pop, waitForCompletion: false)
private lazy var failSoundAction = SKAction.playSoundFileNamed(SoundFileName.Explosion, waitForCompletion: false)
// MARK: - Init
override init(size: CGSize) {
super.init(size: size)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func didMoveToView(view: SKView) {
self.setupScene()
// Background
addChild(background)
//Fence
addChild(fence)
//Finishes
addChild(LeftFinishLineNode())
addChild(CenterFinishLineNode())
addChild(RightFinishLineNode())
//Gates
addGatesToFence()
//HUD
addChild(scoreLabel)
runAction(SKAction.repeatActionForever(
SKAction.sequence([
SKAction.runBlock(createSheep),
SKAction.waitForDuration(3.0)])))
}
func addGatesToFence(){
addChild(leftGate)
addChild(rightGate)
}
func setupScene(){
backgroundColor = UIColor(hexString: ColorHex.BackgroundColor)
self.physicsWorld.gravity = CGVectorMake(0, 0);
self.physicsWorld.contactDelegate = self;
}
func createSheep(){
let startPoint = CGPointMake(160, 588)
let sheep = SheepNode(sheepType: SheepType.randomSheepType(), position: startPoint)
self.addChild(sheep)
}
func destroySheep(sheep : SKNode){
print("Sheep destroyed")
let destroyAction = SKAction.removeFromParentAfterDelay(1)
sheep.runAction(destroyAction)
}
override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
if(self.leftTouch != nil && touches.contains(self.leftTouch!)){
let leftGateVector = CGVectorMake((self.leftTouch!.locationInNode(self).x - self.leftTouch!.previousLocationInNode(self).x) * 20, (self.leftTouch!.locationInNode(self).y - self.leftTouch!.previousLocationInNode(self).y) * CGFloat(gameSettings.getControlSensitivity()))
leftGate.physicsBody!.velocity = leftGateVector
}
if(self.rightTouch != nil && touches.contains(self.rightTouch!)){
let rightGateVector = CGVectorMake((self.rightTouch!.locationInNode(self).x - self.rightTouch!.previousLocationInNode(self).x) * 20, (self.rightTouch!.locationInNode(self).y - self.rightTouch!.previousLocationInNode(self).y) * CGFloat(gameSettings.getControlSensitivity()))
rightGate.physicsBody!.velocity = rightGateVector
}
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
if(self.leftTouch != nil && self.rightTouch != nil){
return;
}
for obj in touches {
let touch = obj as UITouch
let location = touch.locationInNode(self.background)
let screenMedian = UIScreen.mainScreen().bounds.width / 2
switch location.x{
case 0...screenMedian:
self.leftTouch = touch
default:
self.rightTouch = touch
}
}
}
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
if(self.leftTouch != nil && touches.contains(self.leftTouch!)){
self.leftTouch = nil
}
if(self.rightTouch != nil && touches.contains(self.rightTouch!)){
self.rightTouch = nil
}
}
func sheepGotFinishWithContact(contact: SKPhysicsContact, finish:SheepType){
if let sheep = nodeInContact(contact, withCategoryBitMask: PhysicsCategory.Sheep) as? SheepNode {
if(sheep.sheepType == finish){
self.scoreValue++
scoreLabel.text = "\(self.scoreValue)"
runAction(popSoundAction, when: isSoundEnabled())
}else{
runAction(failSoundAction, when: isSoundEnabled())
}
self.destroySheep(sheep);
}
}
func didBeginContact(contact: SKPhysicsContact) {
let collision = contact.bodyA.categoryBitMask | contact.bodyB.categoryBitMask
switch collision {
case PhysicsCategory.Sheep | PhysicsCategory.LeftFinish:
sheepGotFinishWithContact(contact, finish:.Left)
print("Left Finish")
case PhysicsCategory.Sheep | PhysicsCategory.CenterFinish:
sheepGotFinishWithContact(contact, finish:.Center)
print("Center Finish")
case PhysicsCategory.Sheep | PhysicsCategory.RightFinish:
sheepGotFinishWithContact(contact, finish:.Right)
print("Right Finish")
case PhysicsCategory.Sheep | PhysicsCategory.RightGate:
print("Sheep to Right Gate")
if let sheep = nodeInContact(contact, withCategoryBitMask: PhysicsCategory.Sheep) as? SKSpriteNode {
//print(contact.collisionImpulse)
/*...*/
}
case PhysicsCategory.Sheep | PhysicsCategory.LeftGate:
print("Sheep to Left Gate")
if let sheep = nodeInContact(contact, withCategoryBitMask: PhysicsCategory.Sheep) as? SKSpriteNode {
/*...*/
}
case PhysicsCategory.Sheep | PhysicsCategory.Fence:
print("Sheep to Fence")
case PhysicsCategory.LeftGate | PhysicsCategory.Fence:
//print("Left to Fence")
let currentVector = leftGate.physicsBody!.velocity
leftGate.physicsBody!.velocity = CGVectorMake(-currentVector.dx / 10, -currentVector.dy / 10)
case PhysicsCategory.RightGate | PhysicsCategory.Fence:
//print("Right to Fence")
let currentVector = leftGate.physicsBody!.velocity
rightGate.physicsBody!.velocity = CGVectorMake(-currentVector.dx / 10, -currentVector.dy / 10)
case PhysicsCategory.LeftGate | PhysicsCategory.RightGate:
//print("Left to Right")
leftGate.physicsBody!.velocity = leftGate.physicsBody!.velocity.normalized()
rightGate.physicsBody!.velocity = rightGate.physicsBody!.velocity.normalized()
default:
break
}
}
func didEndContact(contact: SKPhysicsContact) {
let collision = contact.bodyA.categoryBitMask | contact.bodyB.categoryBitMask
switch collision {
case PhysicsCategory.Sheep | PhysicsCategory.LeftGate:
if let sheep = nodeInContact(contact, withCategoryBitMask: PhysicsCategory.Sheep) as? SKSpriteNode {
/*...*/
}
default:
break
}
}
override func update(currentTime: CFTimeInterval) {
if(leftTouch == nil){
leftGate.physicsBody!.velocity = leftGate.physicsBody!.velocity.normalized()
}
if(rightTouch == nil){
rightGate.physicsBody!.velocity = rightGate.physicsBody!.velocity.normalized()
}
self.enumerateChildNodesWithName("Sheep") {(sheep, stop) in
var velocity = sheep.physicsBody!.velocity
if (sheep.zRotation.radiansToDegrees() > 50 || sheep.zRotation.radiansToDegrees() < -50){
let defAngle:CGFloat = 0
let rotateToGoAction = SKAction.rotateToAngle(defAngle.degreesToRadians(), duration: 0.5, shortestUnitArc: true)
sheep.runAction(rotateToGoAction)
}
if sheep.physicsBody!.velocity.length() > 0 {
sheep.rotateToVelocity(CGVectorMake(-sheep.physicsBody!.velocity.dx, -sheep.physicsBody!.velocity.dy), rate:0.2)
}
let wiatAction = SKAction.waitForDuration(0.3)
let runAgainAction = SKAction.applyImpulse(CGVector(dx:0, dy:-0.1), duration: 5)
let commonAction = SKAction.sequence([wiatAction, runAgainAction])
sheep.runAction(commonAction)
}
}
override func didSimulatePhysics() {
}
}
<file_sep>/sheepGame_Spritekit_Swift/SheepSorter/Nodes/ScoreLabelNode.swift
//
// ScoreLabelNode.swift
// SheepSorter
//
// Created by <NAME> on 01.12.15.
// Copyright © 2015 <NAME>. All rights reserved.
//
import SpriteKit
class ScoreLabelNode: SKLabelNode {
override init() {
super.init()
horizontalAlignmentMode = .Center
position = CGPoint(x: 70, y: 410)
zPosition = 1000
text = "0"
fontSize = 38
fontName = FontName.RegularFont
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
<file_sep>/OrientalChuShing_Swift/OrientalChuShing/Application/AppDelegate.swift
//
// AppDelegate.swift
// OrientalChuShing
//
// Created by <NAME> on 01.09.15.
// Copyright (c) 2015 itinarray. All rights reserved.
//
import UIKit
import Fabric
import Crashlytics
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
//MARK: - App lifecycle
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
/*Set initial controller*/
self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
let storyboard = UIStoryboard(name: "Main", bundle: nil)
var rootController:UINavigationController
if(CurrentUser.isUserLoged()){
rootController = storyboard.instantiateViewControllerWithIdentifier(Constants.ViewControllersId.MainVCId) as! UINavigationController
}else{
rootController = storyboard.instantiateViewControllerWithIdentifier(Constants.ViewControllersId.SignUpVCId) as! UINavigationController
}
if let window = self.window{
window.tintColor = Constants.Appearance.GlobalTintColor
window.backgroundColor = UIColor.whiteColor()
window.rootViewController = rootController
window.makeKeyAndVisible()
}
/*App appearance*/
UINavigationBar.appearance().barTintColor = Constants.Appearance.GlobalTintColor
UINavigationBar.appearance().tintColor = UIColor.whiteColor()
UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName : UIColor.whiteColor()]
UIApplication.sharedApplication().setStatusBarStyle(UIStatusBarStyle.LightContent, animated: false)
/*Crashlytics*/
Fabric.with([Crashlytics.self()])
/*Parse.com*/
Parse.setApplicationId(Constants.Parse_com.AppID, clientKey: Constants.Parse_com.ClientID)
/*APNS settings and tracking*/
registerForPushNotificationsCustom(application, launchOptions: launchOptions)
trackRecievedPushNotification(application, launchOptions: launchOptions)
/*Googla Analytics*/
let gai = GAI.sharedInstance()
let tracker = gai.trackerWithTrackingId(Constants.GoogleAnalytics.TrackID)
gai.defaultTracker = tracker
gai.trackUncaughtExceptions = true // report uncaught exceptions
gai.logger.logLevel = GAILogLevel.Error // remove before app release
/*MailChimp*/
ChimpKit.sharedKit().apiKey = Constants.MailChimp.ApiKey
/*Cache settings*/
let URLCache = NSURLCache(memoryCapacity: 10 * 1024 * 1024, diskCapacity: 20 * 1024 * 1024, diskPath: "cache")
NSURLCache.setSharedURLCache(URLCache)
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
let currentInstallation = PFInstallation.currentInstallation()
if currentInstallation.badge != 0 {
currentInstallation.badge = 0
currentInstallation.saveEventually()
}
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
//MARK: - APNS methods
func registerForPushNotificationsCustom(application : UIApplication , launchOptions: [NSObject: AnyObject]?){
// Register for Push Notitications
if application.applicationState != UIApplicationState.Background {
// Track an app open here if we launch with a push, unless
// "content_available" was used to trigger a background push (introduced in iOS 7).
// In that case, we skip tracking here to avoid double counting the app-open.
let preBackgroundPush = !application.respondsToSelector("backgroundRefreshStatus")
let oldPushHandlerOnly = !self.respondsToSelector("application:didReceiveRemoteNotification:fetchCompletionHandler:")
var pushPayload = false
if let options = launchOptions {
pushPayload = options[UIApplicationLaunchOptionsRemoteNotificationKey] != nil
}
if (preBackgroundPush || oldPushHandlerOnly || pushPayload) {
PFAnalytics.trackAppOpenedWithLaunchOptions(launchOptions)
}
}
if application.respondsToSelector("registerUserNotificationSettings:") {
let settings = UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Alert], categories: nil)
application.registerUserNotificationSettings(settings)
application.registerForRemoteNotifications()
}
}
func trackRecievedPushNotification(application : UIApplication , launchOptions: [NSObject: AnyObject]?){
let noPushPayload: AnyObject? = launchOptions?[UIApplicationLaunchOptionsRemoteNotificationKey]
if noPushPayload != nil{
PushHandler.sharedInstance.handlePushNotification(noPushPayload as! [NSObject : AnyObject], isAppActive:false)
}
}
func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
let installation = PFInstallation.currentInstallation()
installation.setDeviceTokenFromData(deviceToken)
installation.setValue("apns", forKey: Constants.Parse_com.UserPushType)
installation.saveInBackground()
}
func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) {
if error.code == 3010 {
print("Push notifications are not supported in the iOS Simulator.")
} else {
print("application:didFailToRegisterForRemoteNotificationsWithError: %@", error)
}
}
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
//PFPush.handlePush(userInfo)
PushHandler.sharedInstance.handlePushNotification(userInfo, isAppActive:application.applicationState == UIApplicationState.Active)
if application.applicationState == UIApplicationState.Inactive {
PFAnalytics.trackAppOpenedWithRemoteNotificationPayload(userInfo)
}
}
//MARK: - Transitions
func transitionToMainNavigationController(){
let storyboard:UIStoryboard = UIStoryboard(name: "Main", bundle: NSBundle.mainBundle())
let mainNavVC:UINavigationController = storyboard.instantiateViewControllerWithIdentifier(Constants.ViewControllersId.MainVCId) as! UINavigationController
UIView.transitionWithView(self.window!, duration: 0.5, options: .TransitionFlipFromRight, animations: {
let oldState: Bool = UIView.areAnimationsEnabled()
UIView.setAnimationsEnabled(false)
self.window!.rootViewController = mainNavVC
UIView.setAnimationsEnabled(oldState)
}, completion: { (finished: Bool) -> () in
})
}
func transitionToSignUpNavigationController(){
let storyboard:UIStoryboard = UIStoryboard(name: "Main", bundle: NSBundle.mainBundle())
let signUpNavVC:UINavigationController = storyboard.instantiateViewControllerWithIdentifier(Constants.ViewControllersId.SignUpVCId) as! UINavigationController
UIView.transitionWithView(self.window!, duration: 0.5, options: .TransitionFlipFromLeft, animations: {
let oldState: Bool = UIView.areAnimationsEnabled()
UIView.setAnimationsEnabled(false)
self.window!.rootViewController = signUpNavVC
UIView.setAnimationsEnabled(oldState)
}, completion: { (finished: Bool) -> () in
})
}
// //The iOS 7-only handler
// func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
// if application.applicationState == .Inactive {
// PFAnalytics.trackAppOpenedWithRemoteNotificationPayload(userInfo)
// }
// }
}
<file_sep>/sheepGame_Spritekit_Swift/SheepSorter/Nodes/FenceNode.swift
//
// FenceNode.swift
// SheepSorter
//
// Created by <NAME> on 27.11.15.
// Copyright © 2015 <NAME>. All rights reserved.
//
import SpriteKit
class FenceNode: SKSpriteNode {
init() {
let texture = SKTexture(imageNamed: TextureFileName.FullFence)
super.init(texture: texture, color: UIColor.clearColor(), size: texture.size())
zPosition = 2
anchorPoint = CGPointZero
position = CGPointZero
physicsBody = SKPhysicsBody(bodies: addPhysicsBodiesToFence())
physicsBody!.restitution = 0
physicsBody!.density = 1
physicsBody!.dynamic = false
physicsBody!.categoryBitMask = PhysicsCategory.Fence
//physicsBody!.contactTestBitMask = PhysicsCategory.LeftGate | PhysicsCategory.RightGate | PhysicsCategory.Fence
}
init(color: UIColor, size: CGSize) {
super.init(texture: nil, color: color, size: size)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func addPhysicsBodiesToFence() -> [SKPhysicsBody]{
/*Top Left Section*/
let topLeftPBPath = UIBezierPath()
topLeftPBPath.moveToPoint(CGPointMake(120, 460))
topLeftPBPath.addLineToPoint(CGPointMake(120, 195))
topLeftPBPath.addLineToPoint(CGPointMake(0, 55))
let topLeftPB = SKPhysicsBody(edgeLoopFromPath: topLeftPBPath.CGPath)
/*Top Right Section*/
let topRightPBPath = UIBezierPath()
topRightPBPath.moveToPoint(CGPointMake(200, 460))
topRightPBPath.addLineToPoint(CGPointMake(200, 195))
topRightPBPath.addLineToPoint(CGPointMake(320, 55))
let topRightPB = SKPhysicsBody(edgeLoopFromPath: topRightPBPath.CGPath)
/*Bottom Left Section*/
let bottomLeftPBPath = UIBezierPath()
bottomLeftPBPath.moveToPoint(CGPointMake(38, 0))
bottomLeftPBPath.addLineToPoint(CGPointMake(120, 95))
bottomLeftPBPath.addLineToPoint(CGPointMake(127, 85))
bottomLeftPBPath.addLineToPoint(CGPointMake(127, 0))
let bottomLeftPB = SKPhysicsBody(edgeLoopFromPath: bottomLeftPBPath.CGPath)
/*Bottom Right Section*/
let bottomRightPBPath = UIBezierPath()
bottomRightPBPath.moveToPoint(CGPointMake(283, 0))
bottomRightPBPath.addLineToPoint(CGPointMake(200, 95))
bottomRightPBPath.addLineToPoint(CGPointMake(193, 85))
bottomRightPBPath.addLineToPoint(CGPointMake(193, 0))
let bottomRightPB = SKPhysicsBody(edgeLoopFromPath: bottomRightPBPath.CGPath)
return [topLeftPB, topRightPB, bottomLeftPB, bottomRightPB];
}
}
<file_sep>/MyCarRadar_Swift_WatchKit2/RadarInterfaceController.swift
//
// RadarInterfaceController.swift
// MyCarRadar
//
// Created by <NAME> on 14.09.15.
// Copyright © 2015 itinarray. All rights reserved.
//
import WatchKit
import Foundation
import CoreGraphics
class RadarInterfaceController: WKInterfaceController, CLLocationManagerDelegate {
// MARK: - Properties
var timer:NSTimer? = nil
@IBOutlet var targetDotImage: WKInterfaceImage!
let lastCarLocationDic:NSDictionary = NSUserDefaults.standardUserDefaults().objectForKey("lastKnowCarLocation") as! NSDictionary
var lastCarLocation:CLLocation? = nil
var dotAlpha:CGFloat = 0
var radarHandAngle:CGFloat = 0
var heading:Double = 0
var distance:Double = 0
var isDotInvisible:Bool = true
var radarCycles = 0
// MARK: - Localized String Convenience
var interfaceTitleWalking: String {
return NSLocalizedString("Keep walking...", comment: "")
}
var interfaceTitleBack: String {
return NSLocalizedString("Tap to go back", comment: "")
}
var alertDissmisBtn: String {
return NSLocalizedString("Dissmis", comment: "")
}
var alertErrorTitle: String {
return NSLocalizedString("Error", comment: "")
}
// MARK: - Interface Controller
override func awakeWithContext(context: AnyObject?) {
super.awakeWithContext(context)
blinkOut()
timer = NSTimer.scheduledTimerWithTimeInterval(0.06, target: self, selector: "blinkOut", userInfo: nil, repeats: true)
timer!.fire()
lastCarLocation = CLLocation(latitude: lastCarLocationDic["lat"] as! CLLocationDegrees, longitude: lastCarLocationDic["long"] as! CLLocationDegrees)
setTitle(interfaceTitleWalking)
}
override func willActivate() {
super.willActivate()
self.addObserverForTrackingManager()
}
override func didAppear() {
super.didAppear()
}
override func willDisappear() {
super.willDisappear()
self.removeObserverForTrackingManager()
timer?.invalidate()
timer = nil
}
// MARK: - Add/Remove Observer
func addObserverForTrackingManager(){
let notificationCenter = NSNotificationCenter.defaultCenter()
notificationCenter.addObserver(self, selector: "trackerDidUpdateLocation:", name: TrackingManager.Notifications.DidUpdateLocation, object: nil)
notificationCenter.addObserver(self, selector: "trackerDidFailedWithError:", name: TrackingManager.Notifications.DidFailWithError, object: nil)
notificationCenter.addObserver(self, selector: "trackerDeniedLocationService", name: TrackingManager.Notifications.DeniedLocationService, object: nil)
}
func removeObserverForTrackingManager(){
let notificationCenter = NSNotificationCenter.defaultCenter()
notificationCenter.removeObserver(self, name: TrackingManager.Notifications.DidUpdateLocation, object: nil)
notificationCenter.removeObserver(self, name: TrackingManager.Notifications.DidFailWithError, object: nil)
notificationCenter.removeObserver(self, name: TrackingManager.Notifications.DidFailWithError, object: nil)
}
// MARK: - TrackingManager Observer methods
func trackerDidUpdateLocation(notification: NSNotification) {
dispatch_async(dispatch_get_main_queue()) {
if let currentLocation:CLLocation = notification.userInfo?["location"] as? CLLocation{
let distance:CLLocationDistance = currentLocation.distanceFromLocation(self.lastCarLocation!)
print("Distance to car: \(distance)")
let curentCourse:Double = currentLocation.valueForKey("course") as! Double
print("Direction of moving: \(curentCourse)")
let heading = self.calculateHeading(currentLocation.coordinate, distLoc: (self.lastCarLocation?.coordinate)!)
print("HEADING- \(heading)")
self.distance = distance
self.heading = heading + curentCourse
}
}
}
func trackerDidFailedWithError(notification: NSNotification) {
dispatch_async(dispatch_get_main_queue()) {
let error:NSError = notification.userInfo?["error"] as! NSError
let alertView = WKAlertAction(title: self.alertDissmisBtn, style: WKAlertActionStyle.Destructive){}
self.presentAlertControllerWithTitle(self.alertErrorTitle, message: error.localizedDescription, preferredStyle: .Alert, actions: [alertView])
}
}
func trackerDeniedLocationService() {
dispatch_async(dispatch_get_main_queue()) {
let alertView = WKAlertAction(title: "OK", style: .Cancel){}
self.presentAlertControllerWithTitle(Constants.AlertsTexts.LocationDeniedTitle, message:Constants.AlertsTexts.LocationDeniedText, preferredStyle: .Alert, actions: [alertView])
}
}
// MARK: - Heading calculation
func RAD_TO_DEG(r:Double) ->Double{return r * 180 / M_PI}
func calculateHeading(currentLocation:CLLocationCoordinate2D , distLoc:CLLocationCoordinate2D) -> Double{
let coord1:CLLocationCoordinate2D = currentLocation;
let coord2:CLLocationCoordinate2D = distLoc;
let deltaLong = log(tan(coord1.latitude / 2 + M_PI / 4) / tan(coord2.latitude / 2 + M_PI / 4));
let yComponent = abs(coord2.longitude - coord1.longitude);
let radians = atan2(yComponent, deltaLong);
let degrees = RAD_TO_DEG(radians) + 360;
return fmod(degrees, 360);
}
// MARK: - UI + animation
func redrawDisplay(){
let screenSize = CGSizeMake(WKInterfaceDevice.currentDevice().screenBounds.width / 2, WKInterfaceDevice.currentDevice().screenBounds.height / 2 - 19)
var targetX:CGFloat = 0
var targetY:CGFloat = 0
var targetSizeWidth:CGFloat = 17.0
var radius:CGFloat = 0.0
switch true{
case distance < 1:
targetSizeWidth = 17
radius = CGFloat(0)
case (distance > 10 && distance < 20):
targetSizeWidth = 15
radius = CGFloat(33 - 30)
case (distance > 20 && distance < 30):
targetSizeWidth = 13
radius = CGFloat(33 - 25)
case (distance > 30 && distance < 50):
targetSizeWidth = 11
radius = CGFloat(33 - 20)
case (distance > 50 && distance < 60):
targetSizeWidth = 9
radius = CGFloat(33 - 15)
case (distance > 60 && distance < 70):
targetSizeWidth = 7
radius = CGFloat(33 - 10)
case (distance > 70 && distance < 80):
targetSizeWidth = 5
radius = CGFloat(33 - 5)
case (distance > 80):
targetSizeWidth = 3
radius = CGFloat(33)
default:
break
}
let centerX:CGFloat = screenSize.width / 2
let centerY:CGFloat = screenSize.width / 2
targetX = centerX + (radius * CGFloat(cos(heading * M_PI / 180)))
targetY = centerY + (radius * CGFloat(sin(heading * M_PI / 180)))
// Radar Drawing
UIGraphicsBeginImageContextWithOptions(CGSizeMake(screenSize.width, screenSize.width), false, 4.0)
let radarSize = CGSizeMake(screenSize.width, screenSize.width)
RadarDrawer.drawRadarImage(radarHandAngle: self.radarHandAngle, distanceText: "\(round(distance))m", size: radarSize)
// Raget Dot Drawing
let dotImage = UIImage(named:"target_dot")
let imageRect = CGRectMake(targetX - (targetSizeWidth / 2), targetY - (targetSizeWidth / 2), targetSizeWidth, targetSizeWidth)
dotImage?.drawInRect(imageRect, blendMode: .Normal, alpha: self.dotAlpha)
let resultingImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
self.targetDotImage.setImage(resultingImage)
}
func blinkOut(){
if(self.isDotInvisible){
dotAlpha = self.dotAlpha + 0.033
}else{
dotAlpha = self.dotAlpha - 0.033
}
if dotAlpha <= 0{
self.isDotInvisible = true
}else if dotAlpha >= 1{
self.isDotInvisible = false
}
radarHandAngle = self.radarHandAngle - 5
if radarHandAngle == -360{
radarHandAngle = 0
self.radarCycles++
}
if(self.radarCycles != 0 && self.radarCycles % 2 == 0){
self.setTitle(self.interfaceTitleBack)
}else{
self.setTitle(self.interfaceTitleWalking)
}
self.redrawDisplay()
}
}
<file_sep>/OrientalChuShing_Swift/OrientalChuShing/Controllers/MainViewController.swift
//
// ViewController.swift
// OrientalChuShing
//
// Created by <NAME> on 01.09.15.
// Copyright (c) 2015 itinarray. All rights reserved.
//
import UIKit
class MainViewController: BaseViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var siteAdressLabel: UILabel!
var menuElements:[String] = Constants.AppData.MenuMenuItems
// MARK: - VC lifecycle
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.titleView = UIImageView(image: UIImage(named: "NavBarTitleLogo"))
//self.view.backgroundColor = Constants.Appearance.GlobalTintColor
self.siteAdressLabel.text = Constants.AppData.AppBusinessSite
if(Constants.SettingsList.IsSettingsVisisble){
self.navigationItem.rightBarButtonItem = UIBarButtonItem(image: UIImage(named: "NavBarSettings") , style: UIBarButtonItemStyle.Plain, target: self, action: "navBarSettingsPressed")
}
if(!CurrentUser.isUserLoged()){
menuElements.append("Sign up".localizedWithComment(""))
}
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
/*Google analytics*/
let tracker = GAI.sharedInstance().defaultTracker
tracker.set(kGAIScreenName, value: Constants.GoogleAnalytics.trackMainScreenName)
let builder = GAIDictionaryBuilder.createScreenView()
tracker.send(builder.build() as [NSObject : AnyObject])
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - UI actions
func navBarSettingsPressed(){
self.performSegueWithIdentifier(Constants.Segues.MainToSettings, sender: self)
}
// MARK: - UITableViewDataSource
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return menuElements.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: Constants.TableCells.MainMenuCell)
cell.textLabel?.text = menuElements[indexPath.row].localizedWithComment("")
cell.accessoryType = .DisclosureIndicator
return cell
}
// MARK: - UITableViewDelegate
func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 0.01
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return self.tableView.frame.size.height / CGFloat(menuElements.count)
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
switch indexPath.row{
case 0:
self.performSegueWithIdentifier(Constants.Segues.MainToMenu, sender: self)
case 1:
self.performSegueWithIdentifier(Constants.Segues.MainToPlaces, sender: self)
//case 2:
// self.performSegueWithIdentifier(Constants.Segues.MainToAboutUs, sender: self)
case 2:
self.performSegueWithIdentifier(Constants.Segues.MainToContactUs, sender: self)
case 3:
let appDelegate:AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
appDelegate.transitionToSignUpNavigationController()
default:
break
}
}
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let segueId:String! = segue.identifier
switch segueId{
case Constants.Segues.MainToMenu:
let menuVC:MenuViewController! = segue.destinationViewController as! MenuViewController
menuVC.title = Constants.AppData.MenuMenuItems[0].localizedWithComment("").capitalizedString
case Constants.Segues.MainToPlaces:
let placesVC:PlacesViewController! = segue.destinationViewController as! PlacesViewController
placesVC.title = Constants.AppData.MenuMenuItems[1].localizedWithComment("")
// case Constants.Segues.MainToAboutUs:
//
// var aboutVC:AboutViewController! = segue.destinationViewController as! AboutViewController
// aboutVC.title = Constants.AppData.MenuMenuItems[2].localizedWithComment("").capitalizedString
case Constants.Segues.MainToContactUs:
let contactVC:ContactViewController! = segue.destinationViewController as! ContactViewController
contactVC.title = Constants.AppData.MenuMenuItems[2].localizedWithComment("").capitalizedString
default:
break
}
}
}
<file_sep>/OrientalChuShing_Swift/OrientalChuShing/Vendors/NetworkManager.swift
//
// NetworkManager.swift
// OrientalChuShing
//
// Created by <NAME> on 12.09.15.
// Copyright (c) 2015 itinarray. All rights reserved.
//
import UIKit
import SystemConfiguration
class NetworkManager: NSObject {
struct Static {
static let instance = NetworkManager()
}
class var sharedInstance: NetworkManager {
return Static.instance
}
private override init() {
super.init()
}
class func isConnectionAvailble()->Bool{
var zeroAddress = sockaddr_in()
zeroAddress.sin_len = UInt8(sizeofValue(zeroAddress))
zeroAddress.sin_family = sa_family_t(AF_INET)
let defaultRouteReachability = withUnsafePointer(&zeroAddress) {
SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0))
}
var flags = SCNetworkReachabilityFlags.ConnectionAutomatic
if !SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) {
return false
}
let isReachable = (flags.rawValue & UInt32(kSCNetworkFlagsReachable)) != 0
let needsConnection = (flags.rawValue & UInt32(kSCNetworkFlagsConnectionRequired)) != 0
return (isReachable && !needsConnection)
}
}
<file_sep>/MyCarRadar_Swift_WatchKit2/PinCarInterfaceController.swift
//
// InterfaceController.swift
// MyCarRadar WatchKit Extension
//
// Created by <NAME> on 14.09.15.
// Copyright © 2015 itinarray. All rights reserved.
//
import WatchKit
import Foundation
class PinCarInterfaceController: WKInterfaceController {
// MARK: - Properties
@IBOutlet var mapView: WKInterfaceMap!
@IBOutlet var requestLocationButton: WKInterfaceButton!
@IBOutlet var saveLocationButton: WKInterfaceButton!
@IBOutlet var setNewButton: WKInterfaceButton!
@IBOutlet var radarButton: WKInterfaceButton!
var carLatitude:Double? = nil
var carLongitude:Double? = nil
// MARK: - Localized String Convenience
var interfaceTitle: String {
return NSLocalizedString("Pin a Car", comment: "")
}
var requestLocationTitle: String {
return NSLocalizedString("Pin my car", comment: "")
}
var saveTitle: String {
return NSLocalizedString("Save", comment: "")
}
var cancelTitle: String {
return NSLocalizedString("Reset", comment: "")
}
var radarlTitle: String {
return NSLocalizedString("Radar", comment: "")
}
// MARK: - Interface Controller
override func awakeWithContext(context: AnyObject?) {
super.awakeWithContext(context)
setTitle(interfaceTitle)
self.saveLocationButton.setTitle(saveTitle.uppercaseString)
self.requestLocationButton.setTitle(requestLocationTitle.uppercaseString)
self.setNewButton.setTitle(cancelTitle.uppercaseString)
self.radarButton.setTitle(radarlTitle.uppercaseString)
if let lastCarLocationDic:NSDictionary = (NSUserDefaults.standardUserDefaults().objectForKey("lastKnowCarLocation") as? NSDictionary){
let lastCarLocation:CLLocation = CLLocation(latitude: lastCarLocationDic["lat"] as! CLLocationDegrees, longitude: lastCarLocationDic["long"] as! CLLocationDegrees)
let carIcon = UIImage(named:"car_icon")
self.mapView.addAnnotation(lastCarLocation.coordinate, withImage:carIcon, centerOffset: CGPointMake((carIcon?.size.width)! / 2, (carIcon?.size.height)!))
self.requestLocationButton.setHidden(true)
self.saveLocationButton.setHidden(true)
self.radarButton.setHidden(false)
self.setNewButton.setHidden(false)
}
}
override func willActivate() {
super.willActivate()
self.addObserverForTrackingManager()
TrackingManager.sharedInstance.startTracking()
}
override func willDisappear() {
super.willDisappear()
self.removeObserverForTrackingManager()
}
// MARK: - Add/Remove Observer
func addObserverForTrackingManager(){
let notificationCenter = NSNotificationCenter.defaultCenter()
notificationCenter.addObserver(self, selector: "trackerDidUpdateLocation:", name: TrackingManager.Notifications.DidUpdateLocation, object: nil)
notificationCenter.addObserver(self, selector: "trackerDidFailedWithError:", name: TrackingManager.Notifications.DidFailWithError, object: nil)
notificationCenter.addObserver(self, selector: "trackerDeniedLocationService", name: TrackingManager.Notifications.DeniedLocationService, object: nil)
}
func removeObserverForTrackingManager(){
let notificationCenter = NSNotificationCenter.defaultCenter()
notificationCenter.removeObserver(self, name: TrackingManager.Notifications.DidUpdateLocation, object: nil)
notificationCenter.removeObserver(self, name: TrackingManager.Notifications.DidFailWithError, object: nil)
notificationCenter.removeObserver(self, name: TrackingManager.Notifications.DidFailWithError, object: nil)
}
// MARK: - Buttons actions
@IBAction func requestLocation(sender: AnyObject) {
guard TrackingManager.sharedInstance.locationManager.location != nil else {return}
if let lastCarLocation:CLLocation = TrackingManager.sharedInstance.locationManager.location! {
let carIcon = UIImage(named:"car_icon")
self.mapView.addAnnotation(lastCarLocation.coordinate, withImage:carIcon, centerOffset: CGPointMake(0, 0 - (carIcon?.size.height)! / 2))
self.carLatitude = lastCarLocation.coordinate.latitude
self.carLongitude = lastCarLocation.coordinate.longitude
self.requestLocationButton.setHidden(true)
self.saveLocationButton.setHidden(false)
self.setNewButton.setHidden(false)
self.radarButton.setHidden(true)
}
}
@IBAction func saveCarLocationPressed() {
let carLocationDic:NSDictionary = NSDictionary(dictionary: ["lat":self.carLatitude!, "long":self.carLongitude!]);
let userDefaults = NSUserDefaults.standardUserDefaults()
userDefaults.setObject(carLocationDic, forKey: "lastKnowCarLocation")
userDefaults.synchronize()
self.requestLocationButton.setHidden(true)
self.saveLocationButton.setHidden(true)
self.setNewButton.setHidden(false)
self.radarButton.setHidden(false)
}
@IBAction func resetCarLocation() {
self.requestLocationButton.setHidden(false)
self.saveLocationButton.setHidden(true)
self.setNewButton.setHidden(true)
self.radarButton.setHidden(true)
let userDefaults = NSUserDefaults.standardUserDefaults()
userDefaults.setObject(nil, forKey: "lastKnowCarLocation")
userDefaults.synchronize()
self.carLatitude = nil
self.carLongitude = nil
self.mapView.removeAllAnnotations()
}
@IBAction func radarButtonPressed() {
self.presentControllerWithName("RadarInterfaceController", context: nil)
}
// MARK: - TrackingManager Observer methods
func trackerDidUpdateLocation(notification: NSNotification) {
dispatch_async(dispatch_get_main_queue()) {
let myLocation:CLLocation = notification.userInfo?["location"] as! CLLocation
self.mapView.removeAllAnnotations()
let myIcon:UIImage = UIImage(named: "target_dot_dark")!
self.mapView.addAnnotation(myLocation.coordinate, withImage:myIcon, centerOffset: CGPointMake(0, 0))
let span = MKCoordinateSpanMake(0.001, 0.001)
var coordRegion = MKCoordinateRegionMake(myLocation.coordinate, span)
var lastCarLocation:CLLocation = CLLocation(latitude: 0, longitude: 0)
if let lastCarLocationDic:NSDictionary = NSUserDefaults.standardUserDefaults().objectForKey("lastKnowCarLocation") as? NSDictionary {
lastCarLocation = CLLocation(latitude: lastCarLocationDic["lat"] as! CLLocationDegrees, longitude: lastCarLocationDic["long"] as! CLLocationDegrees)
let carIcon = UIImage(named:"car_icon")
self.mapView.addAnnotation(lastCarLocation.coordinate, withImage:carIcon, centerOffset: CGPointMake(0, 0 - (carIcon?.size.height)! / 2))
coordRegion = TrackingManager.mapRegionForAnnotations([myLocation, lastCarLocation])
}else if (self.carLatitude != nil && self.carLongitude != nil){
lastCarLocation = CLLocation(latitude: self.carLatitude!, longitude: self.carLongitude!)
let carIcon = UIImage(named:"car_icon")
self.mapView.addAnnotation(lastCarLocation.coordinate, withImage:carIcon, centerOffset: CGPointMake(0, 0 - (carIcon?.size.height)! / 2))
coordRegion = TrackingManager.mapRegionForAnnotations([myLocation, lastCarLocation])
}
self.mapView.setRegion(coordRegion)
}
}
func trackerDidFailedWithError(notification: NSNotification) {
dispatch_async(dispatch_get_main_queue()) {
let error:NSError = notification.userInfo?["error"] as! NSError
let alertView = WKAlertAction(title: "Dissmis", style: WKAlertActionStyle.Destructive){}
self.presentAlertControllerWithTitle("Error", message: error.localizedDescription, preferredStyle: .Alert, actions: [alertView])
}
}
func trackerDeniedLocationService() {
dispatch_async(dispatch_get_main_queue()) {
let alertHandler:WKAlertActionHandler = {
dispatch_async(dispatch_get_main_queue()){
self.requestLocationButton.setHidden(false)
self.saveLocationButton.setHidden(true)
self.setNewButton.setHidden(true)
self.radarButton.setHidden(true)
}
}
let alertView = WKAlertAction(title: "OK", style: .Cancel, handler: alertHandler)
self.presentAlertControllerWithTitle(Constants.AlertsTexts.LocationDeniedTitle, message:Constants.AlertsTexts.LocationDeniedText, preferredStyle: .Alert, actions: [alertView])
}
}
/// MARK: - Segue
override func contextForSegueWithIdentifier(segueIdentifier: String) -> AnyObject? {
if(segueIdentifier == "MainToRadar"){
saveCarLocationPressed()
return nil
}
return nil
}
}
| a5850af8fef25e2e03db202d84c9a8308140669a | [
"Swift",
"Ruby"
] | 34 | Swift | Quizer1349/code_parts | 48f27a977d747a60eba19e2c4aaf2b2ae307a848 | 26e06dcc2becff64b20c25618b09c7ace72f49bc |
refs/heads/master | <file_sep># Artifactory
Terraform automation for artifactory
<file_sep>#!/bin/bash
logfile="/var/log/aws_userdata.log"
echo "$(date):start of userdata script" >> $logfile 2>&1
# Mount EBS volume /data/artifactory
/sbin/mkfs -t ext4 /dev/xvdf >> $logfile 2>&1
/bin/mkdir -p /data/artifactory >> $logfile 2>&1
/bin/echo "/dev/xvdf /data/artifactory ext4 defaults,nofail 0 2" >> /etc/fstab
# Mount EBS volume /data/postgresql
/sbin/mkfs -t ext4 /dev/xvdh >> $logfile 2>&1
/bin/mkdir -p /data/postgresql >> $logfile 2>&1
/bin/echo "/dev/xvdh /data/postgresql ext4 defaults,nofail 0 2" >> /etc/fstab
# Mount All EBS volumes
/bin/mount -av >> $logfile 2>&1
rf -rf /data/artifactory/* /data/postgresql/*
# Install docker
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -
add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable"
apt-get update
apt-get install -y docker-ce >> $logfile 2>&1
# Install Docker compose
curl -L https://github.com/docker/compose/releases/download/${docker_compose_version}/docker-compose-`uname \
-s`-`uname -m` -o /usr/local/bin/docker-compose >> $logfile 2>&1
chmod +x /usr/local/bin/docker-compose >> $logfile 2>&1
mkdir /opt/artifactory-docker-compose
## source of compose file
## https://github.com/JFrogDev/artifactory-docker-examples/blob/master/docker-compose/artifactory-oss-postgresql.yml
cat > /opt/artifactory-docker-compose/docker-compose.yml << EOF
version: '2'
services:
postgresql:
image: docker.bintray.io/${postgres_docker_image}
container_name: postgresql
ports:
- 5432:5432
environment:
- POSTGRES_DB=artifactory
# The following must match the DB_USER and DB_PASSWORD values passed to Artifactory
- POSTGRES_USER=artifactory
- POSTGRES_PASSWORD=${<PASSWORD>}
volumes:
- /data/postgresql/data:/var/lib/postgresql/data
restart: always
ulimits:
nproc: 65535
nofile:
soft: 32000
hard: 40000
artifactory:
image: docker.bintray.io/jfrog/${artifactory_docker_image}
container_name: artifactory
ports:
- 80:8081
depends_on:
- postgresql
links:
- postgresql
volumes:
- /data/artifactory/data:/var/opt/jfrog/artifactory
environment:
- DB_TYPE=postgresql
# The following must match the POSTGRES_USER and POSTGRES_PASSWORD values passed to PostgreSQL
- DB_USER=artifactory
- DB_PASSWORD=${<PASSWORD>}
# Add extra Java options by uncommenting the following line
#- EXTRA_JAVA_OPTIONS=-Xmx4g
restart: always
ulimits:
nproc: 65535
nofile:
soft: 32000
hard: 40000
EOF
cd /opt/artifactory-docker-compose
docker-compose up -d >> $logfile 2>&1
docker ps -a >> $logfile 2>&1
echo "$(date):end of userdata script" >> $logfile 2>&1
| 45cb630ee613f2eb6658f56be6bbece562379299 | [
"Markdown",
"Shell"
] | 2 | Markdown | ecogit-stage/artifactory | a43091c3dff36dba3337780e59994300ca848a32 | fb0f1f2ed2ca18cba66ccd75dec09980ddc058d6 |
refs/heads/master | <file_sep> ---Binary Search---
# Write a function that takes in a sorted array of integers as well as target integer.
# The function should use binary search algo to determine if the target integer is contained in the array and should return its index if it is, otherwise -1
def solution(arr,target):
mid=len(arr)//2
while(mid>=0 and mid<len(arr)):
if arr[mid]==target:
return mid
elif target<arr[mid]:
mid=mid//2
else:
mid=mid+mid//2
return -1
<file_sep># Coding-Problems-Arth
Under DSA for FAANG
| 69c648ed531898d123c77eb9123d8a3453bd7406 | [
"Markdown",
"Python"
] | 2 | Python | P-Bharti20/Coding-Problems-Arth | 8a33283fc017c1251c64e05fbfa0678518904857 | abb75f4839dfa7797113d334a49027979c07fb73 |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TakeAction.Models.Task
{
public class TaskEdit
{
public int TaskId { get; set; }
public string TaskName { get; set; }
public string TaskSummary { get; set; }
[DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}", ApplyFormatInEditMode = true)]
public DateTimeOffset? DueDate { get; set; }
public bool Flagged { get; set; }
public bool Completed { get; set; }
}
}
<file_sep>namespace TakeAction.Data.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class AddDept : DbMigration
{
public override void Up()
{
AddColumn("dbo.Employee", "Dept", c => c.Int(nullable: false));
}
public override void Down()
{
DropColumn("dbo.Employee", "Dept");
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static TakeAction.Data.Manager;
namespace TakeAction.Models.Manager
{
public class ManagerCreate
{
[Required]
[Display(Name ="Manager First Name")]
public string ManagerFirstName { get; set; }
[Required]
[Display(Name ="Manager Last Name")]
public string ManagerLastName { get; set; }
[Display(Name = "Manager Name")]
public string ManagerFullName
{
get
{
var fullName = $"{ManagerFirstName} {ManagerLastName}";
return fullName;
}
}
[Display(Name = "Hired Date")]
[DisplayFormat(DataFormatString = "{0:MM/dd/yyyy", ApplyFormatInEditMode = true)]
public DateTimeOffset? HiredDate { get; set; }
[Display(Name ="# of Subordinates")]
public int Subordinates { get; set; }
[Required]
[Display(Name ="Manager's Department")]
public DepartmentM DeptM { get; set; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static TakeAction.Data.Employee;
namespace TakeAction.Models.Employee
{
public class EmployeeDetailTwo
{
[Display(Name = "Employee ID")]
public int? EmployeeId { get; set; }
[Display(Name = "First Name")]
public string EmployeeFirstName { get; set; }
[Display(Name = "Last Name")]
public string EmployeeLastName { get; set; }
[Display(Name = "Employee Name")]
public string EmployeeFullName
{
get
{
var fullName = $"{EmployeeFirstName} {EmployeeLastName}";
return fullName;
}
}
[Display(Name = "Manager ID")]
public int? ManagerId { get; set; }
[Display(Name = "First Name")]
public string ManagerFirstName { get; set; }
[Display(Name = "Last Name")]
public string ManagerLastName { get; set; }
[Display(Name = "Employee Name")]
public string ManagerFullName
{
get
{
var fullName = $"{ManagerFirstName} {ManagerLastName}";
return fullName;
}
}
[Required]
[Display(Name = "Hired Date")]
public DateTimeOffset? HiredDate { get; set; }
[Display(Name = "Department")]
public Department Dept { get; set; }
}
}
<file_sep>using Microsoft.AspNet.Identity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TakeAction.Data;
using TakeAction.Models.Assignment;
using TakeAction.Services;
namespace TakeAction.WebMVC.Controllers
{
[Authorize]
public class AssignmentController : Controller
{
private ApplicationDbContext _db = new ApplicationDbContext();
// GET: Assignment
public ActionResult Index()
{
var userId = Guid.Parse(User.Identity.GetUserId());
var service = new AssignmentService(userId);
var model = service.GetAssignments();
return View(model);
}
public ActionResult Create()
{
ViewData["Employees"] = _db.Employees.Select(e => new SelectListItem
{
Text = e.EmployeeFirstName + " " + e.EmployeeLastName,
Value = e.EmployeeId.ToString()
});
ViewData["Tasks"] = _db.Tasks.Select(e => new SelectListItem
{
Text = e.TaskName,
Value = e.TaskId.ToString()
});
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(AssignmentCreate model)
{
//if (!ModelState.IsValid) return View(model);
var service = CreateAssignmentService();
if (service.CreateAssignment(model))
{
TempData["SaveResult"] = "The assignment was created successfully!";
return RedirectToAction("Index");
};
//ModelState.AddModelError("", "The assignment could not be created!");
return View(model);
}
public ActionResult Details(int id)
{
var svc = CreateAssignmentService();
var model = svc.GetAssignmentById(id);
return View(model);
}
public ActionResult AssignmentsByEmployeeId(int? employeeId)
{
var svc = CreateAssignmentService();
var model = svc.GetAssignmentsByEmployeeId(employeeId);
return View(model);
}
public ActionResult FlaggedAssignments()
{
var svc = CreateAssignmentService();
var model = svc.GetFlaggedAssignments();
return View(model);
}
public ActionResult UnflaggedAssignments()
{
var svc = CreateAssignmentService();
var model = svc.GetUnflaggedAssignments();
return View(model);
}
public ActionResult CompletedAssignments()
{
var svc = CreateAssignmentService();
var model = svc.GetCompletedAssignments();
return View(model);
}
public ActionResult OutstandingAssignments()
{
var svc = CreateAssignmentService();
var model = svc.GetOutstandingAssignments();
return View(model);
}
public ActionResult DetailsByDueDate(DateTimeOffset? dueDate)
{
var svc = CreateAssignmentService();
var model = svc.GetAssignmentsByDueDate(dueDate);
return View(model);
}
public ActionResult Edit(int id)
{
ViewData["Employees"] = _db.Employees.Select(e => new SelectListItem
{
Text = e.EmployeeFirstName + " " + e.EmployeeLastName,
Value = e.EmployeeId.ToString()
});
ViewData["Tasks"] = _db.Tasks.Select(e => new SelectListItem
{
Text = e.TaskName,
Value = e.TaskId.ToString()
});
var service = CreateAssignmentService();
var detail = service.GetAssignmentById(id);
var model =
new AssignmentEdit
{
EmployeeId = detail.EmployeeId,
EmployeeFullName = detail.EmployeeFullName,
TaskId = detail.TaskId,
TaskName = detail.TaskName,
DueDate = detail.DueDate,
AssignmentId = detail.AssignmentId,
AssignerFirstName = detail.AssignerFirstName,
AssignerLastName = detail.AssignerLastName,
DeptA = detail.DeptA,
AssignedDate = detail.AssignedDate,
};
return View(model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(AssignmentEdit model)
{
//if (!ModelState.IsValid) return View(model);
//if (model.AssignmentId != id)
//{
// ModelState.AddModelError("", "Id Mismatch");
// return View(model);
//}
//var service = CreateAssignmentService();
//if (service.UpdateAssignment(model))
//{
// TempData["SaveResult"] = "The assignment was updated!";
// return RedirectToAction("Index");
//}
//ModelState.AddModelError("", "The assignment could not be updated!");
//return View(model);
//if (!ModelState.IsValid)
//{
// return View(model);
//}
var service = CreateAssignmentService();
if (service.UpdateAssignment(model))
{
TempData["SaveResult"] = "The Assignment was updated successfully!";
return RedirectToAction("Index");
};
//ModelState.AddModelError("", "The assignment could not be created!");
return View(model);
}
[ActionName("Delete")]
public ActionResult Delete(int id)
{
var svc = CreateAssignmentService();
var model = svc.GetAssignmentById(id);
return View(model);
}
[HttpPost]
[ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteAssignment(int id)
{
var service = CreateAssignmentService();
service.DeleteAssignment(id);
TempData["SaveResult"] = "The assignment was deleted!";
return RedirectToAction("Index");
}
private AssignmentService CreateAssignmentService()
{
var userId = Guid.Parse(User.Identity.GetUserId());
var service = new AssignmentService(userId);
return service;
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TakeAction.Data;
using TakeAction.Models.Task;
namespace TakeAction.Services
{
public class TaskService
{
private readonly Guid _userId;
public TaskService(Guid userId)
{
_userId = userId;
}
public bool CreateTask(TaskCreate model)
{
var entity =
new Taskl()
{
TaskOwnerId = _userId,
TaskName = model.TaskName,
TaskSummary = model.TaskSummary,
DueDate = model.DueDate,
Flagged = model.Flagged,
Completed = model.Completed,
};
using (var ctx = new ApplicationDbContext())
{
ctx.Tasks.Add(entity);
return ctx.SaveChanges() == 1;
}
}
public IEnumerable<TaskListItem> GetTasks()
{
using (var ctx = new ApplicationDbContext())
{
var query =
ctx
.Tasks
.Where(e => e.TaskOwnerId == _userId)
.Select(
e =>
new TaskListItem
{
TaskId = e.TaskId,
TaskName = e.TaskName,
TaskSummary = e.TaskSummary,
DueDate = e.DueDate,
Flagged = e.Flagged,
Completed = e.Completed,
}
);
return query.ToArray();
}
}
public TaskDetail GetTaskById(int id)
{
using (var ctx = new ApplicationDbContext())
{
var entity =
ctx
.Tasks
.Single(e => e.TaskId == id && e.TaskOwnerId == _userId);
return
new TaskDetail
{
TaskId = entity.TaskId,
TaskName = entity.TaskName,
TaskSummary = entity.TaskSummary,
DueDate = (DateTimeOffset)entity.DueDate,
Flagged = entity.Flagged,
Completed = entity.Completed,
};
}
}
public IEnumerable<TaskListItem> GetFlaggedTasks()
{
using (var ctx = new ApplicationDbContext())
{
var query =
ctx
.Tasks
.Where(e => e.Flagged == true && e.TaskOwnerId == _userId)
.Select(
e =>
new TaskListItem
{
TaskId = e.TaskId,
TaskName = e.TaskName,
TaskSummary = e.TaskSummary,
DueDate = (DateTimeOffset)e.DueDate,
Flagged = e.Flagged,
Completed = e.Completed,
}
);
return query.ToArray();
}
}
public IEnumerable<TaskListItem> GetUnflaggedTasks()
{
using (var ctx = new ApplicationDbContext())
{
var query =
ctx
.Tasks
.Where(e => e.Flagged == false && e.TaskOwnerId == _userId)
.Select(
e =>
new TaskListItem
{
TaskId = e.TaskId,
TaskName = e.TaskName,
TaskSummary = e.TaskSummary,
DueDate = (DateTimeOffset)e.DueDate,
Flagged = e.Flagged,
Completed = e.Completed,
}
);
return query.ToArray();
}
}
public IEnumerable<TaskListItem> GetCompletedTasks()
{
using (var ctx = new ApplicationDbContext())
{
var query =
ctx
.Tasks
.Where(e => e.Completed == true && e.TaskOwnerId == _userId)
.Select(
e =>
new TaskListItem
{
TaskId = e.TaskId,
TaskName = e.TaskName,
TaskSummary = e.TaskSummary,
DueDate = (DateTimeOffset)e.DueDate,
Flagged = e.Flagged,
Completed = e.Completed,
}
);
return query.ToArray();
}
}
public IEnumerable<TaskListItem> GetOutstandingTasks()
{
using (var ctx = new ApplicationDbContext())
{
var query =
ctx
.Tasks
.Where(e => e.Completed == false && e.TaskOwnerId == _userId)
.Select(
e =>
new TaskListItem
{
TaskId = e.TaskId,
TaskName = e.TaskName,
TaskSummary = e.TaskSummary,
DueDate = (DateTimeOffset)e.DueDate,
Flagged = e.Flagged,
Completed = e.Completed,
}
);
return query.ToArray();
}
}
public TaskDetail GetTasksByDueDate(DateTimeOffset? dueDate)
{
using (var ctx = new ApplicationDbContext())
{
var entity =
ctx
.Tasks
.Single(e => e.DueDate == dueDate);
return
new TaskDetail
{
TaskId = entity.TaskId,
TaskName = entity.TaskName,
TaskSummary = entity.TaskSummary,
DueDate = (DateTimeOffset)entity.DueDate,
Flagged = entity.Flagged,
Completed = entity.Completed,
};
}
}
public bool UpdateTask(TaskEdit model)
{
using(var ctx = new ApplicationDbContext())
{
var entity =
ctx
.Tasks
.Single(e => e.TaskId == model.TaskId && e.TaskOwnerId == _userId);
entity.TaskName = model.TaskName;
entity.TaskSummary = model.TaskSummary;
entity.DueDate = model.DueDate;
entity.Flagged = model.Flagged;
entity.Completed = model.Completed;
return ctx.SaveChanges() == 1;
}
}
public bool DeleteTask(int TaskId)
{
using(var ctx = new ApplicationDbContext())
{
var entity =
ctx
.Tasks
.Single(e => e.TaskId == TaskId && e.TaskOwnerId == _userId);
var entity2 =
ctx
.Assignments
.Where(e => e.TaskId == TaskId);
foreach(var item in entity2)
{
item.TaskId = null;
}
ctx.Tasks.Remove(entity);
var assignmentCount = entity2.Count();
return ctx.SaveChanges() == assignmentCount + 1;
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TakeAction.Models.Task
{
public class TaskListItem
{
[Display(Name= "Task Id")]
public int TaskId { get; set; }
[Display(Name = "Task Name")]
public string TaskName { get; set; }
[Display(Name = "Task Summary")]
public string TaskSummary { get; set; }
[Display(Name = "Due Date")]
[DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}", ApplyFormatInEditMode = true)]
public DateTimeOffset? DueDate { get; set; }
[Display(Name = "Flagged")]
public bool Flagged { get; set; }
[Display(Name = "Completed")]
public bool Completed { get; set; }
}
}
<file_sep>namespace TakeAction.Data.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class update4 : DbMigration
{
public override void Up()
{
AddColumn("dbo.Assignment", "TaskSummary", c => c.String());
}
public override void Down()
{
DropColumn("dbo.Assignment", "TaskSummary");
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TakeAction.Data
{
public class Manager
{
[Key]
[Display(Name ="Manager Id")]
public int? ManagerId { get; set; }
[Required]
public Guid ManagerOwnerId { get; set; }
[Required]
[Display(Name = "First Name")]
public string ManagerFirstName { get; set; }
[Required]
[Display(Name = "Last Name")]
public string ManagerLastName { get; set; }
[Display(Name = "Manager Name")]
public string ManagerFullName
{
get
{
var fullName = $"{ManagerFirstName} {ManagerLastName}";
return fullName;
}
}
public DateTimeOffset? HiredDate { get; set; }
[Required]
[Display(Name = "Department")]
public DepartmentM DeptM { get; set; }
public enum DepartmentM
{
Finance = 1,
Marketing = 2,
IT = 3,
HR = 4,
Management = 5,
Other = 6,
}
}
}
<file_sep>namespace TakeAction.Data.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class ManagerAdded : DbMigration
{
public override void Up()
{
CreateTable(
"dbo.Manager",
c => new
{
ManagerId = c.Int(nullable: false, identity: true),
ManagerOwnerId = c.Guid(nullable: false),
ManagerFirstName = c.String(nullable: false),
ManagerLastName = c.String(nullable: false),
Subordinates = c.Int(nullable: false),
})
.PrimaryKey(t => t.ManagerId);
AddColumn("dbo.Employee", "ManagerId", c => c.Int());
CreateIndex("dbo.Employee", "ManagerId");
AddForeignKey("dbo.Employee", "ManagerId", "dbo.Manager", "ManagerId");
}
public override void Down()
{
DropForeignKey("dbo.Employee", "ManagerId", "dbo.Manager");
DropIndex("dbo.Employee", new[] { "ManagerId" });
DropColumn("dbo.Employee", "ManagerId");
DropTable("dbo.Manager");
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TakeAction.Data
{
public class Taskl
{
[Key]
public int TaskId { get; set; }
[Required]
public Guid TaskOwnerId { get; set; }
[Required]
[MinLength(3, ErrorMessage = "The name needs to be at least 3 characters long")]
[MaxLength(50, ErrorMessage = "The name is too long")]
[Display(Name = "Task")]
public string TaskName { get; set; }
[Required]
[MaxLength(750, ErrorMessage = "You have entered too many charcters")]
[Display(Name = "Summary")]
public string TaskSummary { get; set; }
public string ManagerFullName { get; set; }
[Required]
public DateTimeOffset? DueDate { get; set; }
public bool Flagged { get; set; }
public bool Completed { get; set; }
}
}
<file_sep>Boats-4-U
Boats-4-U is an ASP.NET Web Application (.NET Framework) in the C# programming language. The purpose of this application is to create a platform in which Tasks to be completed can be added. These tasks can then be assigned to any of the employees and completion of these tasks can be tracked.
Version
Version 1 was "released" on May 11, 2021.
This ReadMe file was created for the release of Version 1.
Description
This app enables the creation, management, and deletion of: Managers, Employees, Tasks and Assignments.
More specifically, Managers can create, update, and delete a profile that includes:
the manager's name
the manager's hired date
the manager's department
Employees can create, update, and delete a profile that includes:
the employee's name
the employee's manager
the employee's hired date
the employee's department
Tasks can be created, updated and deleted which includes:
the task name
the task summary
the assigner name
the task due date
the task importance
the task completed
Assignments can be created, updated and deleted which includes:
the employee's name
the task name
the assigner's name
the assignment's department
This app was optimized for running with Visual Studio Community 2019 Version 16.8.5
Instructions for downloading and installing it are here. Microsoft .NET Framework Version 4.8 was used
A web browser (Chrome, Edge, Firefox, etc) is required.
Requirements
The following Nuget packages may need to be loaded/updated for Visual Studio:
Microsoft.AspNet.Identity.EntityFramework by Microsoft, Version: 2.2.3
Microsoft.AspNet.Identity.Owin by Microsoft, Version: 2.2.3
Microsoft.AspNet.WebApi.Owin by Microsoft, Version 5.2.7
Usage
Initial Setup and Account Setup
Open the TakeAction solution in Visual Studio and run the program by pressing the ISS Express icon
Run the program
This should open your browser.
Copy the URL https://localhost:XXXXX
Under Account you should see a Register endpoint. Click on it.
Register Browser
You are now registered. Repeat these steps each time you are creating a new user account.
Adding a Manager
After the program is running, and you have created a user account, the following steps may be used to create a Manager
From the Home Page:
1. Click on the Managers link in the NavBar
2. Click on the Create New link
3. Enter the Managers First Name, Last Name and Hired Date
4. Select the Managers Department from the Drop Down list
5. Hit the create button
Adding an Employee
After the program is running, and you have created a user account, the following steps may be used to create an Employee
From the Home Page:
1. Click on the Employees link in the NavBar
2. Click on the Create New link
3. Enter the Employees First Name, Last Name and Hired Date
4. Select the Employees Department and Managers Name from the Drop Down list
5. Hit the create button
Adding a Task
After the program is running, and you have created a user account, the following steps may be used to create a Task
From the Home Page:
1. Click on the Tasks link in the NavBar
2. Click on the Create New link
3. Enter the Task Name, TAsk Summary and Due Date
4. Check the boxes if the task is Flagged/Important of Completed when applicable
5. Hit the create button
Adding an Assignment
After the program is running, and you have created a user account, the following steps may be used to create an Assignment
From the Home Page:
1. Click on the Assignments link in the NavBar
2. Click on the Create New link
3. Enter the Assigner First Name and Assigner Last Name
4. Select the Employees Name and Task Name from the Drop Down list
5. Select the Assignment's Department from the Drop Down list
6. Hit the create button
Viewing a Manager
After the program is running, and you have created a user account, the following steps may be used to edit a Manager
From the Home Page:
1. Click on the Managers link in the NavBar
2. Click on the Details link in the desired Manager's card
4. Click on the Edit link to edit the Manager or click on the Back to list link to return to a list of Managers
Viewing a Employee
After the program is running, and you have created a user account, the following steps may be used to edit an Employee
From the Home Page:
1. Click on the Managers link in the NavBar
2. Click on the Details link in the desired Employee's card
4. Click on the Edit link to edit the Employee or click on the Back to list link to return to a list of Employees
Viewing a Task
After the program is running, and you have created a user account, the following steps may be used to edit a Task
From the Home Page:
1. Click on the Managers link in the NavBar
2. Click on the Details link in the desired Task's card
4. Click on the Edit link to edit the Task or click on the Back to list link to return to a list of Tasks
Viewing an Assignment
After the program is running, and you have created a user account, the following steps may be used to edit an Assignment
From the Home Page:
1. Click on the Managers link in the NavBar
2. Click on the Details link in the desired Assignment's card
4. Click on the Edit link to edit the Assignment or click on the Back to list link to return to a list of Assignments
Editing a Manager
After the program is running, and you have created a user account, the following steps may be used to edit a Manager
From the Home Page:
1. Click on the Managers link in the NavBar
2. Click on the Edit link in the desired Manager's card
3. Change the Manager's First Name, Last Name and Hired Date when applicable
4. Change the Manager's Department from the Drop Down list when applicable
5. Hit the Save button
Editing a Employee
After the program is running, and you have created a user account, the following steps may be used to edit an Employee
From the Home Page:
1. Click on the Employees link in the NavBar
2. Click on the Edit link in the desired Employee's card
3. Change the Employee's First Name, Last Name and Hired Date when applicable
4. Change the Employee's Department and Manager Name from the Drop Down list when applicable
5. Hit the Save button
Editing a Task
After the program is running, and you have created a user account, the following steps may be used to edit a Task
From the Home Page:
1. Click on the Tasks link in the NavBar
2. Click on the Edit link in the desired Task's card
3. Change the Task's Name, Summary and Due Date when applicable
4. Change the completed Flagged and Completed check marks when applicable
5. Hit the Save button
Editing an Assignment
After the program is running, and you have created a user account, the following steps may be used to edit an Assignment
From the Home Page:
1. Click on the Assignments link in the NavBar
2. Click on the Edit link in the desired Assignment's card
3. Change the Assigner's First Name and Last Name when applicable
4. Change the Employee Name and Task Name from the Drop Down list when applicable
6. Hit the Save button
Deleting a Manager
After the program is running, and you have created a user account, the following steps may be used to delete an Manager
From the Home Page:
1. Click on the Managers link in the NavBar
2. Click on the Delete link in the desired Manager's card
3. Click on the Delete button
Deleting an Employee
After the program is running, and you have created a user account, the following steps may be used to delete an Employee
From the Home Page:
1. Click on the Employees link in the NavBar
2. Click on the Delete link in the desired Employee's card
3. Click on the Delete button
Deleting a Task
After the program is running, and you have created a user account, the following steps may be used to delete a Task
From the Home Page:
1. Click on the Tasks link in the NavBar
2. Click on the Delete link in the desired Task's card
3. Click on the Delete button
Deleting an Assignment
After the program is running, and you have created a user account, the following steps may be used to delete an Assignment
From the Home Page:
1. Click on the Assignments link in the NavBar
2. Click on the Delete link in the desired Assignment's card
3. Click on the Delete button
Resources
General resources for creation of this README file are:
Make a README
Basic Syntax | Markdown Guide
This project was modeled after the Eleven-Fifty Academy Blue Badge tutorial for Eleven Note
Eleven Note Tutorial
The information in Eleven Note was also used to help create this README.
Resources for implementing Day of the Week Availability for Drivers
Enum.HasFlag(Enum) Method
Enum, Flags, and Bitwise Operators
C# Json.NET Render Flags Enum as String Array
How do you pass multiple enum values in C#?
<file_sep>namespace TakeAction.Data.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class InitialCreate : DbMigration
{
public override void Up()
{
CreateTable(
"dbo.Assignment",
c => new
{
AssignmentId = c.Int(nullable: false, identity: true),
EmployeeId = c.Int(),
TaskId = c.Int(),
AssignerFirstName = c.String(nullable: false),
AssignerLastName = c.String(nullable: false),
AssignedDate = c.DateTime(nullable: false),
})
.PrimaryKey(t => t.AssignmentId)
.ForeignKey("dbo.Employee", t => t.EmployeeId)
.ForeignKey("dbo.TaskL", t => t.TaskId)
.Index(t => t.EmployeeId)
.Index(t => t.TaskId);
CreateTable(
"dbo.Employee",
c => new
{
EmployeeId = c.Int(nullable: false, identity: true),
EmployeeFirstName = c.String(nullable: false),
EmployeeLastName = c.String(nullable: false),
ManagerFirstName = c.String(nullable: false),
ManagerLastName = c.String(nullable: false),
})
.PrimaryKey(t => t.EmployeeId);
CreateTable(
"dbo.TaskL",
c => new
{
TaskId = c.Int(nullable: false, identity: true),
TaskName = c.String(nullable: false, maxLength: 50),
TaskSummary = c.String(nullable: false, maxLength: 750),
DueDate = c.DateTime(nullable: false),
Flagged = c.Boolean(nullable: false),
Completed = c.Boolean(nullable: false),
})
.PrimaryKey(t => t.TaskId);
CreateTable(
"dbo.IdentityRole",
c => new
{
Id = c.String(nullable: false, maxLength: 128),
Name = c.String(),
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.IdentityUserRole",
c => new
{
UserId = c.String(nullable: false, maxLength: 128),
RoleId = c.String(),
IdentityRole_Id = c.String(maxLength: 128),
ApplicationUser_Id = c.String(maxLength: 128),
})
.PrimaryKey(t => t.UserId)
.ForeignKey("dbo.IdentityRole", t => t.IdentityRole_Id)
.ForeignKey("dbo.ApplicationUser", t => t.ApplicationUser_Id)
.Index(t => t.IdentityRole_Id)
.Index(t => t.ApplicationUser_Id);
CreateTable(
"dbo.ApplicationUser",
c => new
{
Id = c.String(nullable: false, maxLength: 128),
Email = c.String(),
EmailConfirmed = c.Boolean(nullable: false),
PasswordHash = c.String(),
SecurityStamp = c.String(),
PhoneNumber = c.String(),
PhoneNumberConfirmed = c.Boolean(nullable: false),
TwoFactorEnabled = c.Boolean(nullable: false),
LockoutEndDateUtc = c.DateTime(),
LockoutEnabled = c.Boolean(nullable: false),
AccessFailedCount = c.Int(nullable: false),
UserName = c.String(),
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.IdentityUserClaim",
c => new
{
Id = c.Int(nullable: false, identity: true),
UserId = c.String(),
ClaimType = c.String(),
ClaimValue = c.String(),
ApplicationUser_Id = c.String(maxLength: 128),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.ApplicationUser", t => t.ApplicationUser_Id)
.Index(t => t.ApplicationUser_Id);
CreateTable(
"dbo.IdentityUserLogin",
c => new
{
UserId = c.String(nullable: false, maxLength: 128),
LoginProvider = c.String(),
ProviderKey = c.String(),
ApplicationUser_Id = c.String(maxLength: 128),
})
.PrimaryKey(t => t.UserId)
.ForeignKey("dbo.ApplicationUser", t => t.ApplicationUser_Id)
.Index(t => t.ApplicationUser_Id);
}
public override void Down()
{
DropForeignKey("dbo.IdentityUserRole", "ApplicationUser_Id", "dbo.ApplicationUser");
DropForeignKey("dbo.IdentityUserLogin", "ApplicationUser_Id", "dbo.ApplicationUser");
DropForeignKey("dbo.IdentityUserClaim", "ApplicationUser_Id", "dbo.ApplicationUser");
DropForeignKey("dbo.IdentityUserRole", "IdentityRole_Id", "dbo.IdentityRole");
DropForeignKey("dbo.Assignment", "TaskId", "dbo.TaskL");
DropForeignKey("dbo.Assignment", "EmployeeId", "dbo.Employee");
DropIndex("dbo.IdentityUserLogin", new[] { "ApplicationUser_Id" });
DropIndex("dbo.IdentityUserClaim", new[] { "ApplicationUser_Id" });
DropIndex("dbo.IdentityUserRole", new[] { "ApplicationUser_Id" });
DropIndex("dbo.IdentityUserRole", new[] { "IdentityRole_Id" });
DropIndex("dbo.Assignment", new[] { "TaskId" });
DropIndex("dbo.Assignment", new[] { "EmployeeId" });
DropTable("dbo.IdentityUserLogin");
DropTable("dbo.IdentityUserClaim");
DropTable("dbo.ApplicationUser");
DropTable("dbo.IdentityUserRole");
DropTable("dbo.IdentityRole");
DropTable("dbo.TaskL");
DropTable("dbo.Employee");
DropTable("dbo.Assignment");
}
}
}
<file_sep>using Microsoft.AspNet.Identity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TakeAction.Data;
using TakeAction.Models.Manager;
using TakeAction.Services;
using static TakeAction.Data.Employee;
using static TakeAction.Data.Manager;
namespace TakeAction.WebMVC.Controllers
{
[Authorize]
public class ManagerController : Controller
{
private ApplicationDbContext _db = new ApplicationDbContext();
// GET: Manager
public ActionResult Index()
{
var userId = Guid.Parse(User.Identity.GetUserId());
var service = new ManagerService(userId);
var svc = CreateManagerService();
var model = svc.GetManagers();
foreach(var manager in model)
{
manager.Subordinates = svc.GetEmployeeCountIndex(manager);
}
return View(model);
}
public ActionResult Create()
{
ViewData["Managers"] = _db.Managers.Select(m => new SelectListItem
{
Text = m.ManagerFullName,
Value = m.ManagerId.ToString()
});
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(ManagerCreate model)
{
var service = CreateManagerService();
if (service.CreateManager(model))
{
TempData["SaveResult"] = "The Manager was created successfully!";
return RedirectToAction(nameof(Index));
};
return View(model);
}
public ActionResult Details(int id)
{
var svc = CreateManagerService();
var model = svc.GetManagerById(id);
model.Subordinates = svc.GetEmployeeCount(model);
return View(model);
}
public ActionResult DetailsByDept(DepartmentM dept)
{
var svc = CreateManagerService();
var model = svc.GetManagersByDept(dept);
return View(model);
}
public ActionResult Edit(int id)
{
var service = CreateManagerService();
var detail = service.GetManagerById(id);
var model =
new ManagerEdit
{
ManagerId = detail.ManagerId,
ManagerFirstName = detail.ManagerFirstName,
ManagerLastName = detail.ManagerLastName,
ManagerFullName = detail.ManagerFullName,
HiredDate = detail.HiredDate,
DeptM = detail.DeptM,
};
return View(model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(ManagerEdit model)
{
if (!ModelState.IsValid) return View(model);
//if(model.ManagerId != id)
//{
// ModelState.AddModelError("", "Id Mismatch");
// return View(model);
//}
var service = CreateManagerService();
if (service.UpdateManager(model))
{
TempData["SaveResult"] = "The manager was updated!";
return RedirectToAction("Index");
}
ModelState.AddModelError("", "The manager could not be updated!");
return View(model);
}
[ActionName("Delete")]
public ActionResult Delete(int id)
{
var svc = CreateManagerService();
var model = svc.GetManagerById(id);
model.Subordinates = svc.GetEmployeeCount(model);
return View(model);
}
[HttpPost]
[ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeletePost(int id)
{
var service = CreateManagerService();
service.DeleteManager(id);
TempData["SaveResult"] = "The manager was successfully deleted!";
return RedirectToAction("Index");
}
private ManagerService CreateManagerService()
{
var userId = Guid.Parse(User.Identity.GetUserId());
var service = new ManagerService(userId);
return service;
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static TakeAction.Data.Manager;
namespace TakeAction.Models.Manager
{
public class ManagerEdit
{
[Display(Name= "Manager Id")]
public int? ManagerId { get; set; }
[Display(Name ="Manager First Name")]
public string ManagerFirstName { get; set; }
[Display(Name = "Manager Last Name")]
public string ManagerLastName { get; set; }
[Display(Name = "Manager Name")]
public string ManagerFullName { get; set; }
[Required]
[DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}", ApplyFormatInEditMode = true)]
[Display(Name = "Hired Date")]
public DateTimeOffset? HiredDate { get; set; }
[Display(Name ="Manager Department")]
public DepartmentM DeptM { get; set; }
}
}
<file_sep>namespace TakeAction.Data.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class AddDeptM : DbMigration
{
public override void Up()
{
AddColumn("dbo.Employee", "ManagerOwnerId", c => c.Guid(nullable: false));
AddColumn("dbo.Manager", "DeptM", c => c.Int(nullable: false));
DropColumn("dbo.Employee", "EmployeeOwnerId");
}
public override void Down()
{
AddColumn("dbo.Employee", "EmployeeOwnerId", c => c.Guid(nullable: false));
DropColumn("dbo.Manager", "DeptM");
DropColumn("dbo.Employee", "ManagerOwnerId");
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static TakeAction.Data.Employee;
namespace TakeAction.Models
{
public class EmployeeCreate
{
[Required]
[Display(Name ="Employee First Name")]
public string EmployeeFirstName { get; set; }
[Required]
[Display(Name ="Employee Last Name")]
public string EmployeeLastName { get; set; }
[Display(Name = "Manager Id")]
public int? ManagerId { get; set; }
[Required]
[Display(Name ="Manager Name")]
public string ManagerFullName { get; set; }
[Required]
[Display(Name ="Employee's Department")]
public Department Dept { get; set; }
[Required]
[Display(Name = "Hired Date")]
[DisplayFormat(DataFormatString = "{0:MM/dd/yyyy", ApplyFormatInEditMode = true)]
public DateTimeOffset? HiredDate { get; set; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TakeAction.Data;
using TakeAction.Models;
using TakeAction.Models.Employee;
using TakeAction.Models.Manager;
using static TakeAction.Data.Employee;
namespace TakeAction.Services
{
public class EmployeeService
{
private readonly Guid _userId;
public EmployeeService(Guid userId)
{
_userId = userId;
}
public bool CreateEmployee(EmployeeCreate model)
{
using (var ctx = new ApplicationDbContext())
{
var managerName = ctx.Managers.Find(model.ManagerId);
var entity =
new Employee()
{
EmployeeOwnerId = _userId,
OwnerId = _userId,
EmployeeFirstName = model.EmployeeFirstName,
EmployeeLastName = model.EmployeeLastName,
ManagerId = model.ManagerId,
HiredDate = model.HiredDate,
Dept = model.Dept,
};
ctx.Employees.Add(entity);
return ctx.SaveChanges() == 1;
}
}
public IEnumerable<EmployeeListItem> GetEmployees()
{
using (var ctx = new ApplicationDbContext())
{
var query =
ctx
.Employees
.Where(e => e.EmployeeOwnerId == _userId)
.Select(
e =>
new EmployeeListItem
{
EmployeeId = e.EmployeeId,
EmployeeFirstName = e.EmployeeFirstName,
EmployeeLastName = e.EmployeeLastName,
ManagerFirstName = e.Manager.ManagerFirstName,
ManagerLastName = e.Manager.ManagerLastName,
HiredDate = e.HiredDate,
Dept = e.Dept,
}
);
return query.ToArray();
}
}
public EmployeeDetail GetEmployeeById(int id)
{
using (var ctx = new ApplicationDbContext())
{
var entity =
ctx
.Employees
.Single(e => e.EmployeeId == id && e.EmployeeOwnerId == _userId);
return
new EmployeeDetail
{
EmployeeId = entity.EmployeeId,
EmployeeFirstName = entity.EmployeeFirstName,
EmployeeLastName = entity.EmployeeLastName,
ManagerFirstName = entity.Manager.ManagerFirstName,
ManagerLastName = entity.Manager.ManagerLastName,
HiredDate = entity.HiredDate,
ManagerId = entity.ManagerId,
Dept = entity.Dept,
};
}
}
public IEnumerable<EmployeeDetailTwo> GetEmployeesByManagerId(int? managerId)
{
using (var ctx = new ApplicationDbContext())
{
var query =
ctx
.Employees
.Where(e => e.ManagerId == managerId)
.Select(e => new EmployeeDetailTwo
{
EmployeeId = e.EmployeeId,
EmployeeFirstName = e.EmployeeFirstName,
EmployeeLastName = e.EmployeeLastName,
ManagerId = e.ManagerId,
HiredDate = e.HiredDate,
Dept = e.Dept,
});
return query.ToArray();
}
}
public IEnumerable<EmployeeDetailTwo> GetEmployeesByDept(Department dept)
{
using (var ctx = new ApplicationDbContext())
{
var query =
ctx
.Employees
.Where(e => e.Dept == dept)
.Select(e => new EmployeeDetailTwo
{
EmployeeId = e.EmployeeId,
EmployeeFirstName = e.EmployeeFirstName,
EmployeeLastName = e.EmployeeLastName,
ManagerId = e.ManagerId,
HiredDate = e.HiredDate,
Dept = e.Dept,
});
return query.ToArray();
}
}
public bool UpdateEmployee(EmployeeEdit model)
{
using (var ctx = new ApplicationDbContext())
{
var employeeName = ctx.Employees.Find(model.EmployeeId);
var managerName = ctx.Managers.Find(model.ManagerId);
var entity =
ctx
.Employees
.Single(e => e.EmployeeId == model.EmployeeId && e.EmployeeOwnerId == _userId);
entity.EmployeeFirstName = model.EmployeeFirstName;
entity.EmployeeLastName = model.EmployeeLastName;
entity.HiredDate = model.HiredDate;
entity.ManagerId = model.ManagerId;
entity.Dept = model.Dept;
return ctx.SaveChanges() == 1;
}
}
public bool DeleteEmployee(int employeeId)
{
using (var ctx = new ApplicationDbContext())
{
var entity =
ctx
.Employees
.Single(e => e.EmployeeId == employeeId && e.OwnerId == _userId);
var entity2 =
ctx
.Assignments
.Where(e => e.EmployeeId == employeeId);
foreach(var item in entity2)
{
item.EmployeeId = null;
}
ctx.Employees.Remove(entity);
var assignmentCount = entity2.Count();
return ctx.SaveChanges() == assignmentCount + 1;
}
}
}
}
<file_sep>using Microsoft.AspNet.Identity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TakeAction.Data;
using TakeAction.Models.Task;
using TakeAction.Services;
namespace TakeAction.WebMVC.Controllers
{
[Authorize]
public class TaskController : Controller
{
private ApplicationDbContext _db = new ApplicationDbContext();
// GET: Task
public ActionResult Index()
{
var userId = Guid.Parse(User.Identity.GetUserId());
var service = new TaskService(userId);
var model = service.GetTasks();
return View(model);
}
public ActionResult Create()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(TaskCreate model)
{
if (!ModelState.IsValid) return View(model);
var service = CreateTaskService();
if(service.CreateTask(model))
{
TempData["SaveResult"] = "Your task was created!";
return RedirectToAction("Index");
};
ModelState.AddModelError("", "The task could not be created!");
return View(model);
}
public ActionResult Details(int id)
{
var svc = CreateTaskService();
var model = svc.GetTaskById(id);
return View(model);
}
public ActionResult CompletedTasks()
{
var svc = CreateTaskService();
var model = svc.GetCompletedTasks();
return View(model);
}
public ActionResult FlaggedTasks()
{
var svc = CreateTaskService();
var model = svc.GetFlaggedTasks();
return View(model);
}
public ActionResult UnflaggedTasks()
{
var svc = CreateTaskService();
var model = svc.GetUnflaggedTasks();
return View(model);
}
public ActionResult OutstandingTasks()
{
var svc = CreateTaskService();
var model = svc.GetOutstandingTasks();
return View(model);
}
public ActionResult DetailsByDueDate(DateTimeOffset? dueDate)
{
var svc = CreateTaskService();
var model = svc.GetTasksByDueDate(dueDate);
return View(model);
}
public ActionResult Edit(int id)
{
var service = CreateTaskService();
var detail = service.GetTaskById(id);
var model =
new TaskEdit
{
TaskId = detail.TaskId,
TaskName = detail.TaskName,
TaskSummary = detail.TaskSummary,
DueDate = detail.DueDate,
Flagged = detail.Flagged,
Completed = detail.Completed,
};
return View(model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(int id, TaskEdit model)
{
if (!ModelState.IsValid) return View(model);
if(model.TaskId != id)
{
ModelState.AddModelError("", "Id Mismatch");
return View(model);
}
var service = CreateTaskService();
if(service.UpdateTask(model))
{
TempData["SaveResult"] = "Your task was updated!";
return RedirectToAction("Index");
}
ModelState.AddModelError("", "Your note could not be updated!");
return View(model);
}
[ActionName("Delete")]
public ActionResult Delete(int id)
{
var svc = CreateTaskService();
var model = svc.GetTaskById(id);
return View(model);
}
[HttpPost]
[ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteTask(int id)
{
var service = CreateTaskService();
service.DeleteTask(id);
TempData["SaveResult"] = "Your task was deleted!";
return RedirectToAction("Index");
}
private TaskService CreateTaskService()
{
var userId = Guid.Parse(User.Identity.GetUserId());
var service = new TaskService(userId);
return service;
}
}
}<file_sep>namespace TakeAction.Data.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class AddedEmployeeDropDown : DbMigration
{
public override void Up()
{
AddColumn("dbo.Assignment", "EmployeeFullName", c => c.String());
}
public override void Down()
{
DropColumn("dbo.Assignment", "EmployeeFullName");
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TakeAction.Data
{
public class Assignment
{
[Key]
[Display(Name ="Assignment Id")]
public int? AssignmentId { get; set; }
[Required]
public Guid AssignmentOwnerId { get; set; }
[ForeignKey(nameof(Employ))]
[Display(Name ="Employee Id")]
public int? EmployeeId { get; set; }
public virtual Employee Employ { get; set; }
[Display(Name = "Employee Name")]
public string EmployeeFullName { get; set; }
[ForeignKey(nameof(Man))]
[Display(Name = "Manager Id")]
public int? ManagerId { get; set; }
public virtual Manager Man { get; set; }
[ForeignKey(nameof(Task))]
[Display(Name ="Task Id")]
public int? TaskId { get; set; }
public virtual Taskl Task { get; set; }
[Display(Name = "Task Name")]
public string TaskName { get; set; }
[Display(Name = "Task Summary")]
public string TaskSummary { get; set; }
[Display(Name = "Due Date")]
public DateTimeOffset? DueDate { get; set; }
[Required]
[Display(Name = "Assigner First Name")]
public string AssignerFirstName { get; set; }
[Required]
[Display(Name = "Assigner Last Name")]
public string AssignerLastName { get; set; }
[Display(Name = "Assigner Name")]
public string AssignerFullName
{
get
{
var fullName = $"{AssignerFirstName} {AssignerLastName}";
return fullName;
}
}
[Required]
[Display(Name = "Department")]
public AssignmentDepartment DeptA { get; set; }
public Guid OwnerId { get; set; }
[Required]
[Display(Name = "Assigned Date")]
public DateTimeOffset? AssignedDate { get; set; }
public enum AssignmentDepartment
{
Finance = 1, Marketing = 2, IT = 3, HR = 4, Management = 5, Other = 6,
}
[Display(Name = "Flagged")]
public bool Flagged { get; set; }
[Display(Name = "Completed")]
public bool Completed { get; set; }
}
}
<file_sep>namespace TakeAction.Data.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class removedsubordinates : DbMigration
{
public override void Up()
{
DropColumn("dbo.Manager", "Subordinates");
}
public override void Down()
{
AddColumn("dbo.Manager", "Subordinates", c => c.Int(nullable: false));
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TakeAction.Data;
using TakeAction.Models.Manager;
using static TakeAction.Data.Employee;
using static TakeAction.Data.Manager;
namespace TakeAction.Services
{
public class ManagerService
{
private readonly Guid _userId;
public ManagerService(Guid userId)
{
_userId = userId;
}
public bool CreateManager(ManagerCreate model)
{
var entity =
new Manager()
{
ManagerOwnerId = _userId,
ManagerFirstName = model.ManagerFirstName,
ManagerLastName = model.ManagerLastName,
HiredDate = model.HiredDate,
DeptM = model.DeptM,
};
using (var ctx = new ApplicationDbContext())
{
ctx.Managers.Add(entity);
return ctx.SaveChanges() == 1;
}
}
public IEnumerable<ManagerListItem> GetManagers()
{
using (var ctx = new ApplicationDbContext())
{
var query =
ctx
.Managers
.Where(e => e.ManagerOwnerId == _userId)
.Select(
e =>
new ManagerListItem
{
ManagerId = e.ManagerId,
ManagerFirstName = e.ManagerFirstName,
ManagerLastName = e.ManagerLastName,
HiredDate = e.HiredDate,
DeptM = e.DeptM,
}
);
return query.ToArray();
}
}
public int GetEmployeeCountIndex(ManagerListItem model)
{
using (var ctx = new ApplicationDbContext())
{
var query =
ctx
.Employees
.Where(e => e.ManagerId == model.ManagerId
);
return query.Count();
}
}
public int GetEmployeeCount(ManagerDetail model)
{
using (var ctx = new ApplicationDbContext())
{
var query =
ctx
.Employees
.Where(e => e.ManagerId == model.ManagerId
);
return query.Count();
}
}
public ManagerDetail GetManagerById(int id)
{
using (var ctx = new ApplicationDbContext())
{
var entity =
ctx
.Managers
.Single(e => e.ManagerId == id && e.ManagerOwnerId == _userId);
return
new ManagerDetail
{
ManagerId = entity.ManagerId,
ManagerFirstName = entity.ManagerFirstName,
ManagerLastName = entity.ManagerLastName,
HiredDate = entity.HiredDate,
DeptM = entity.DeptM,
};
}
}
public IEnumerable<ManagerDetail> GetManagersByDept(DepartmentM dept)
{
using (var ctx = new ApplicationDbContext())
{
var query =
ctx
.Managers
.Where(e => e.DeptM == dept)
.Select(e => new ManagerDetail
{
ManagerId = e.ManagerId,
ManagerFirstName = e.ManagerFirstName,
ManagerLastName = e.ManagerLastName,
HiredDate = e.HiredDate,
DeptM = e.DeptM,
});
return query.ToArray();
}
}
public bool UpdateManager(ManagerEdit model)
{
using (var ctx = new ApplicationDbContext())
{
var entity =
ctx
.Managers
.Single(e => e.ManagerId == model.ManagerId && e.ManagerOwnerId == _userId);
entity.ManagerFirstName = model.ManagerFirstName;
entity.ManagerLastName = model.ManagerLastName;
entity.HiredDate = model.HiredDate;
entity.DeptM = model.DeptM;
return ctx.SaveChanges() == 1;
}
}
public bool DeleteManager(int managerId)
{
using (var ctx = new ApplicationDbContext())
{
var entity =
ctx
.Managers
.Single(e => e.ManagerId == managerId && e.ManagerOwnerId == _userId);
var entity2 =
ctx
.Employees
.Where(e => e.ManagerId == managerId);
foreach(var item in entity2)
{
item.ManagerId = null;
}
ctx.Managers.Remove(entity);
var managerCount = entity2.Count();
return ctx.SaveChanges() == managerCount + 1;
}
}
}
}
<file_sep>using Microsoft.AspNet.Identity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TakeAction.Data;
using TakeAction.Models;
using TakeAction.Services;
using static TakeAction.Data.Employee;
namespace TakeAction.WebMVC.Controllers
{
[Authorize]
public class EmployeeController : Controller
{
private ApplicationDbContext _db = new ApplicationDbContext();
// GET: Employee
public ActionResult Index()
{
var userId = Guid.Parse(User.Identity.GetUserId());
var service = new EmployeeService(userId);
var model = service.GetEmployees();
return View(model);
}
public ActionResult Create()
{
ViewData["Managers"] = _db.Managers.Select(m => new SelectListItem
{
Text = m.ManagerFirstName + " " + m.ManagerLastName,
Value = m.ManagerId.ToString()
});
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(EmployeeCreate model)
{
var service = CreateEmployeeService();
//service.CreateEmployee(model);
if (service.CreateEmployee(model))
{
TempData["SaveResult"] = "The Employee was created successfully!";
return RedirectToAction(nameof(Index));
}
//if(_db.SaveChanges() == 1)
//{
// return RedirectToAction("Index");
//}
return View(model);
}
public ActionResult Details(int id)
{
var svc = CreateEmployeeService();
var model = svc.GetEmployeeById(id);
return View(model);
}
public ActionResult EmployeesByManagerId(int? managerId)
{
var svc = CreateEmployeeService();
var model = svc.GetEmployeesByManagerId(managerId);
return View(model);
}
public ActionResult DetailsByDept(Department dept)
{
var svc = CreateEmployeeService();
var model = svc.GetEmployeesByDept(dept);
return View(model);
}
public ActionResult Edit(int id)
{
ViewData["Managers"] = _db.Managers.Select(e => new SelectListItem
{
Text = e.ManagerFirstName + " " + e.ManagerLastName,
Value = e.ManagerId.ToString()
});
var service = CreateEmployeeService();
var detail = service.GetEmployeeById(id);
var model =
new EmployeeEdit
{
EmployeeId = detail.EmployeeId,
EmployeeFirstName = detail.EmployeeFirstName,
EmployeeLastName = detail.EmployeeLastName,
ManagerId = detail.ManagerId,
ManagerFullName = detail.ManagerFullName,
HiredDate = detail.HiredDate,
Dept = detail.Dept,
};
return View(model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(EmployeeEdit model)
{
//if (!ModelState.IsValid) return View(model);
//if(model.EmployeeId != id)
//{
// ModelState.AddModelError("", "Incorrect Id");
// return View(model);
//}
var service = CreateEmployeeService();
if(service.UpdateEmployee(model))
{
TempData["SaveResult"] = "The Employee was updated successfully!";
return RedirectToAction("Index");
}
//ModelState.AddModelError("", "The Employee was not updated!");
return View(model);
}
public ActionResult Delete(int id)
{
var svc = CreateEmployeeService();
var model = svc.GetEmployeeById(id);
return View(model);
}
[HttpPost]
[ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeletePost(int id)
{
var service = CreateEmployeeService();
service.DeleteEmployee(id);
TempData["SaveResult"] = "The Employee was deleted!";
return RedirectToAction("Index");
}
private EmployeeService CreateEmployeeService()
{
var userId = Guid.Parse(User.Identity.GetUserId());
var service = new EmployeeService(userId);
return service;
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TakeAction.Models.Task
{
public class TaskCreate
{
[Required]
[MinLength(3, ErrorMessage = "The name needs to be at least 3 characters long")]
[MaxLength(50, ErrorMessage = "The name is too long")]
[Display(Name ="Task")]
public string TaskName { get; set; }
[Required]
[MaxLength(750, ErrorMessage = "You have entered too many charcters")]
[Display(Name = "Summary")]
public string TaskSummary { get; set; }
[Required]
[DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}", ApplyFormatInEditMode = true)]
public DateTimeOffset? DueDate { get; set; }
public bool Flagged { get; set; }
public bool Completed { get; set; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TakeAction.Data;
using TakeAction.Models.Assignment;
using static TakeAction.Data.Assignment;
namespace TakeAction.Services
{
public class AssignmentService
{
private readonly Guid _userId;
public AssignmentService(Guid userId)
{
_userId = userId;
}
public bool CreateAssignment(AssignmentCreate model)
{
using (var ctx = new ApplicationDbContext())
{
var employeeName = ctx.Employees.Find(model.EmployeeId);
var taskName = ctx.Tasks.Find(model.TaskId);
var taskSummary = ctx.Tasks.Find(model.TaskId);
var taskDueDate = ctx.Tasks.Find(model.TaskId);
var taskFlagged = ctx.Tasks.Find(model.TaskId);
var taskCompleted = ctx.Tasks.Find(model.TaskId);
var entity =
new Assignment()
{
AssignmentOwnerId = _userId,
OwnerId = _userId,
EmployeeId = model.EmployeeId,
EmployeeFullName = employeeName.EmployeeFullName,
TaskId = model.TaskId,
TaskName = taskName.TaskName,
TaskSummary = taskSummary.TaskSummary,
DueDate = taskDueDate.DueDate,
AssignerFirstName = model.AssignerFirstName,
AssignerLastName = model.AssignerLastName,
DeptA = model.DeptA,
AssignedDate = DateTimeOffset.Now,
Flagged = taskFlagged.Flagged,
Completed = taskCompleted.Completed,
};
ctx.Assignments.Add(entity);
return ctx.SaveChanges() == 1;
}
}
public IEnumerable<AssignmentListItem> GetAssignments()
{
using (var ctx = new ApplicationDbContext())
{
var query =
ctx
.Assignments
.Where(e => e.AssignmentOwnerId == _userId)
.Select(
e =>
new AssignmentListItem
{
AssignmentId = e.AssignmentId,
EmployeeFullName = e.EmployeeFullName,
TaskName = e.TaskName,
TaskSummary = e.TaskSummary,
DueDate = e.DueDate,
AssignerFirstName = e.AssignerFirstName,
AssignerLastName = e.AssignerLastName,
DeptA = e.DeptA,
AssignedDate = e.AssignedDate,
Flagged = e.Flagged,
Completed = e.Completed,
}
);
return query.ToArray();
}
}
public IEnumerable<AssignmentListItem> GetFlaggedAssignments()
{
using (var ctx = new ApplicationDbContext())
{
var query =
ctx
.Assignments
.Where(e => e.Flagged == true && e.AssignmentOwnerId == _userId)
.Select(
e =>
new AssignmentListItem
{
AssignmentId = e.AssignmentId,
EmployeeFullName = e.EmployeeFullName,
TaskName = e.TaskName,
TaskSummary = e.TaskSummary,
DueDate = e.DueDate,
AssignerFirstName = e.AssignerFirstName,
AssignerLastName = e.AssignerLastName,
DeptA = e.DeptA,
AssignedDate = e.AssignedDate,
Flagged = e.Flagged,
Completed = e.Completed,
}
);
return query.ToArray();
}
}
public IEnumerable<AssignmentListItem> GetUnflaggedAssignments()
{
using (var ctx = new ApplicationDbContext())
{
var query =
ctx
.Assignments
.Where(e => e.Flagged == false && e.AssignmentOwnerId == _userId)
.Select(
e =>
new AssignmentListItem
{
AssignmentId = e.AssignmentId,
EmployeeFullName = e.EmployeeFullName,
TaskName = e.TaskName,
TaskSummary = e.TaskSummary,
DueDate = e.DueDate,
AssignerFirstName = e.AssignerFirstName,
AssignerLastName = e.AssignerLastName,
DeptA = e.DeptA,
AssignedDate = e.AssignedDate,
Flagged = e.Flagged,
Completed = e.Completed,
}
);
return query.ToArray();
}
}
public IEnumerable<AssignmentListItem> GetCompletedAssignments()
{
using (var ctx = new ApplicationDbContext())
{
var query =
ctx
.Assignments
.Where(e => e.Completed == true && e.AssignmentOwnerId == _userId)
.Select(
e =>
new AssignmentListItem
{
AssignmentId = e.AssignmentId,
EmployeeFullName = e.EmployeeFullName,
TaskName = e.TaskName,
TaskSummary = e.TaskSummary,
DueDate = e.DueDate,
AssignerFirstName = e.AssignerFirstName,
AssignerLastName = e.AssignerLastName,
DeptA = e.DeptA,
AssignedDate = e.AssignedDate,
Flagged = e.Flagged,
Completed = e.Completed,
}
);
return query.ToArray();
}
}
public IEnumerable<AssignmentListItem> GetOutstandingAssignments()
{
using (var ctx = new ApplicationDbContext())
{
var query =
ctx
.Assignments
.Where(e => e.Completed == false && e.AssignmentOwnerId == _userId)
.Select(
e =>
new AssignmentListItem
{
AssignmentId = e.AssignmentId,
EmployeeFullName = e.EmployeeFullName,
TaskName = e.TaskName,
TaskSummary = e.TaskSummary,
DueDate = e.DueDate,
AssignerFirstName = e.AssignerFirstName,
AssignerLastName = e.AssignerLastName,
DeptA = e.DeptA,
AssignedDate = e.AssignedDate,
Flagged = e.Flagged,
Completed = e.Completed,
}
);
return query.ToArray();
}
}
public AssignmentDetail GetAssignmentById(int id)
{
using (var ctx = new ApplicationDbContext())
{
var entity =
ctx
.Assignments
.Single(e => e.AssignmentId == id && e.AssignmentOwnerId == _userId);
return
new AssignmentDetail
{
AssignmentId = entity.AssignmentId,
EmployeeId = entity.EmployeeId,
EmployeeFullName = entity.EmployeeFullName,
TaskId = entity.TaskId,
TaskName = entity.TaskName,
TaskSummary = entity.TaskSummary,
DueDate = entity.DueDate,
AssignerFirstName = entity.AssignerFirstName,
AssignerLastName = entity.AssignerLastName,
DeptA = entity.DeptA,
AssignedDate = entity.AssignedDate,
Flagged = entity.Flagged,
Completed = entity.Completed,
};
}
}
public IEnumerable<AssignmentDetail> GetAssignmentsByEmployeeId(int? employeeId)
{
using (var ctx = new ApplicationDbContext())
{
var query =
ctx
.Assignments
.Where(e => e.EmployeeId == employeeId)
.Select(e => new AssignmentDetail
{
AssignmentId = e.AssignmentId,
EmployeeId = e.EmployeeId,
EmployeeFullName = e.EmployeeFullName,
TaskId = e.TaskId,
TaskName = e.TaskName,
TaskSummary = e.TaskSummary,
DueDate = e.DueDate,
AssignerFirstName = e.AssignerFirstName,
AssignerLastName = e.AssignerLastName,
DeptA = e.DeptA,
AssignedDate = e.AssignedDate,
Flagged = e.Flagged,
Completed = e.Completed,
});
return query.ToArray();
}
}
public IEnumerable<AssignmentDetailTwo> GetAssignmentsByDueDate(DateTimeOffset? dueDate)
{
using (var ctx = new ApplicationDbContext())
{
var query =
ctx
.Assignments
.Where(e => e.DueDate == dueDate)
.Select(e => new AssignmentDetailTwo
{
AssignmentId = e.AssignmentId,
EmployeeId = e.EmployeeId,
EmployeeFullName = e.EmployeeFullName,
TaskId = e.TaskId,
TaskName = e.TaskName,
TaskSummary = e.TaskSummary,
DueDate = e.DueDate,
AssignerFirstName = e.AssignerFirstName,
AssignerLastName = e.AssignerLastName,
DeptA = e.DeptA,
AssignedDate = e.AssignedDate,
Flagged = e.Flagged,
Completed = e.Completed,
});
return query.ToArray();
}
}
public bool UpdateAssignment(AssignmentEdit model)
{
using(var ctx = new ApplicationDbContext())
{
var employeeName = ctx.Employees.Find(model.EmployeeId);
var taskName = ctx.Tasks.Find(model.TaskId);
var taskSummary = ctx.Tasks.Find(model.TaskId);
var taskDueDate = ctx.Tasks.Find(model.TaskId);
var taskFlagged = ctx.Tasks.Find(model.TaskId);
var taskCompleted = ctx.Tasks.Find(model.TaskId);
var entity =
ctx
.Assignments
.Single(e => e.AssignmentId == model.AssignmentId && e.AssignmentOwnerId == _userId);
entity.TaskId = model.TaskId;
entity.TaskName = taskName.TaskName;
entity.TaskSummary = taskSummary.TaskSummary;
entity.DueDate = taskDueDate.DueDate;
entity.EmployeeId = model.EmployeeId;
entity.EmployeeFullName = employeeName.EmployeeFullName;
entity.AssignerFirstName = model.AssignerFirstName;
entity.AssignerLastName = model.AssignerLastName;
entity.DeptA = model.DeptA;
entity.Flagged = taskFlagged.Flagged;
entity.Completed = taskCompleted.Completed;
return ctx.SaveChanges() == 1;
}
}
public bool DeleteAssignment(int assignmentId)
{
using(var ctx = new ApplicationDbContext())
{
var entity =
ctx
.Assignments
.Single(e => e.AssignmentId == assignmentId && e.AssignmentOwnerId == _userId);
ctx.Assignments.Remove(entity);
return ctx.SaveChanges() == 1;
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static TakeAction.Data.Assignment;
namespace TakeAction.Models.Assignment
{
public class AssignmentDetail
{
[Display(Name = "Assignment Id")]
public int? AssignmentId { get; set; }
[Display(Name = "Employee Id")]
public int? EmployeeId { get; set; }
[Required]
[Display(Name = "Employee Name")]
public string EmployeeFullName { get; set; }
[Display(Name = "Task Id")]
public int? TaskId { get; set; }
[Required]
[Display(Name = "Task Name")]
public string TaskName { get; set; }
[Display(Name = "Manager Name")]
public string ManagerFullName { get; set; }
[Display(Name = "Assigner Name")]
public string AssignerFirstName { get; set; }
[Display(Name = "Task Summary")]
public string TaskSummary { get; set; }
[Display(Name = "Due Date")]
public DateTimeOffset? DueDate { get; set; }
[Display(Name = "Assigner Last Name")]
public string AssignerLastName { get; set; }
[Display(Name = "Assigner Name")]
public string AssignerFullName
{
get
{
var fullName = $"{AssignerFirstName} {AssignerLastName}";
return fullName;
}
}
[Display(Name = "Assignment Department")]
public AssignmentDepartment DeptA { get; set; }
[Display(Name = "Assigned Date")]
public DateTimeOffset? AssignedDate { get; set; }
[Display(Name ="Flagged")]
public bool Flagged { get; set; }
[Display(Name ="Completed")]
public bool Completed { get; set; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TakeAction.Data
{
public class Employee
{
[Key]
[Display(Name ="Employee Id")]
public int? EmployeeId { get; set; }
[Required]
public Guid EmployeeOwnerId { get; set; }
[ForeignKey(nameof(Manager))]
[Display(Name ="Manager Id")]
public int? ManagerId { get; set; }
public virtual Manager Manager { get; set; }
[Required]
[Display(Name = "First Name")]
public string EmployeeFirstName { get; set; }
[Required]
[Display(Name = "Last Name")]
public string EmployeeLastName { get; set; }
[Display(Name = "Employee Name")]
public string EmployeeFullName
{
get
{
var fullName = $"{EmployeeFirstName} {EmployeeLastName}";
return fullName;
}
}
[Required]
[Display(Name = "Hired Date")]
public DateTimeOffset? HiredDate { get; set; }
[Required]
[Display(Name = "Department")]
public Department Dept { get; set; }
public Guid OwnerId { get; set; }
public enum Department
{
Finance = 1,
Marketing = 2,
IT = 3,
HR = 4,
Management = 5,
Other = 6,
}
}
}
| ae0d68dafd78ebe452b2e888404459f476ea0568 | [
"Markdown",
"C#"
] | 28 | C# | kinnejs/TakeAction | 63f915ec29e127b596aeb106a3c2f1983514f4a9 | 650314a75fa09176f316846dbbb5c6614d7c4949 |
refs/heads/master | <file_sep>const bodyParser = require('body-parser')
const authRoutes = require('./routes/auth')
module.exports = app => {
app.use(bodyParser.json())
authRoutes(app)
}
<file_sep>// Mock axios in our unit tests, so that no one
const axios = require('axios')
const mockApiPort = 9090
const axiosInstance = axios.create({
baseURL: process.env.API_BASE_URL || `http://localhost:${mockApiPort}`,
})
if (!process.env.API_BASE_URL) {
let mockApiServer
axiosInstance.interceptors.request.use(config => {
mockApiServer = startMockApiServer()
return config
})
axiosInstance.interceptors.response.use(
response => {
mockApiServer.close()
return response
},
error => {
mockApiServer.close()
return Promise.reject(error)
}
)
}
module.exports = axiosInstance
function startMockApiServer() {
const app = require('express')()
app.use((request, response, next) => {
response.header('Access-Control-Allow-Origin', '*')
next()
})
require('../../mock-api')(app)
return app.listen(mockApiPort)
}
<file_sep>import Profile from './profile'
describe('@views/profile', () => {
it('is a valid view', () => {
expect(Profile).toBeAViewComponentUsing({ currentUser: { name: '' } })
})
it(`includes the logged in user's name`, () => {
const { element } = mountShallowView(
Profile,
createComponentMocks({
store: {
auth: {
state: {
currentUser: {
name: '<NAME>',
},
},
},
},
})
)
expect(element.textContent).toMatch(/My Name\s+Profile/)
})
})
<file_sep>import store from '@state/store'
export default [
{
path: '/',
name: 'home',
component: require('@views/home').default,
},
{
path: '/login',
name: 'login',
component: require('@views/login').default,
beforeEnter(routeTo, routeFrom, next) {
// If the user is already logged in
if (store.getters['auth/loggedIn']) {
// Redirect to the home page instead
next({ name: 'home' })
} else {
// Continue to the login page
next()
}
},
},
{
path: '/profile',
name: 'profile',
component: require('@views/profile').default,
meta: {
authRequired: true,
},
},
{
path: '/logout',
name: 'logout',
meta: {
authRequired: true,
},
beforeEnter(routeTo, routeFrom, next) {
store.dispatch('auth/logOut')
// Navigate back to previous page
const authRequiredOnPreviousRoute = routeFrom.matched.some(
route => route.meta.authRequired
)
next(authRequiredOnPreviousRoute ? next({ name: 'home' }) : routeFrom)
},
},
]
<file_sep>const _ = require('lodash')
module.exports = app => {
// Log in a user with a username and password
app.post('/api/session', (request, response) => {
authenticate(request.body)
.then(user => {
response.json(user)
})
.catch(error => {
response.status(401).json({ message: error.message })
})
})
// Get the user of a provided token, if valid
app.get('/api/session', (request, response) => {
const token = request.headers.authorization
const matchedUser = users.find(user => user.token === token)
if (!matchedUser) {
return response.status(401).json({
message:
'The token is either invalid or has expired. Please log in again.',
})
}
response.json(_.omit(matchedUser, ['password']))
})
}
function authenticate({ username, password }) {
return new Promise((resolve, reject) => {
const matchedUser = users.find(
user => user.username === username && user.password === <PASSWORD>
)
if (matchedUser) {
resolve(_.omit(matchedUser, ['password']))
} else {
reject(new Error('Invalid user credentials.'))
}
})
}
const users = [
{
id: 1,
username: 'admin',
password: '<PASSWORD>',
name: 'Vue Master',
},
].map(user => {
return {
...user,
token: `valid-token-for-${user.username}`,
}
})
<file_sep>import Vue from 'vue'
// Globally register all base components, because they
// will be used very frequently.
const requireComponent = require.context('.', false, /_base-[\w-]+\.vue$/)
requireComponent.keys().forEach(fileName => {
const componentConfig = requireComponent(fileName)
const componentName = require('lodash/upperFirst')(
require('lodash/camelCase')(
fileName.replace(/^\.\//, '').replace(/\.\w+$/, '')
)
)
Vue.component(componentName, componentConfig.default || componentConfig)
})
| e58d42d8877caed6b741310e0a4d3b29e8d74108 | [
"JavaScript"
] | 6 | JavaScript | stonetingxin/vue-enterprise-boilerplate | df5609e76aa901a9161c5fd87fc19fb5eb387b2c | 0116b4f545c2c343f02c821f5fcaa4eff00fefae |
refs/heads/master | <file_sep># Recycler-View-android-BJP
A custom recycler view for an private application called bharat
<file_sep>package Adapter;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.TextView;
import com.example.hitesh.recyclerview.R;
import java.util.List;
import Model.ListItem;
/**
* Created by hitesh on 12/02/18.
*/
public class myadapter extends RecyclerView.Adapter<myadapter.ViewHolder> {
private Context context;
private List<ListItem> listItems;
public myadapter(Context context,List<ListItem> listitem){
this.context = context;
this.listItems = listitem;
}
/**
* Called when RecyclerView needs a new {@link ViewHolder} of the given type to represent
* an item.
* <p>
* This new ViewHolder should be constructed with a new View that can represent the items
* of the given type. You can either create a new View manually or inflate it from an XML
* layout file.
* <p>
* The new ViewHolder will be used to display items of the adapter using
* {@link #onBindViewHolder(ViewHolder, int, List)}. Since it will be re-used to display
* different items in the data set, it is a good idea to cache references to sub views of
* the View to avoid unnecessary {@link View#findViewById(int)} calls.
*
* @param parent The ViewGroup into which the new View will be added after it is bound to
* an adapter position.
* @param viewType The view type of the new View.
* @return A new ViewHolder that holds a View of the given view type.
* @see #getItemViewType(int)
* @see #onBindViewHolder(ViewHolder, int)
*/
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_row, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(myadapter.ViewHolder holder, int position) {
ListItem item = listItems.get(position);
holder.name.setText(item.getName());
holder.description.setText(item.getDescription());
holder.rating.setText(item.getRating());
}
@Override
public int getItemCount() {
return listItems.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView name;
public TextView description;
public TextView rating;
public ViewHolder(View itemView) {
super(itemView);
name = itemView.findViewById(R.id.title);
description = itemView.findViewById(R.id.discription);
rating = itemView.findViewById(R.id.rating);
rating.setVisibility(View.VISIBLE);
}
}
}
| 2ae0e9c4ecb2ca94dbeac3e986bce6f6d4176533 | [
"Markdown",
"Java"
] | 2 | Markdown | Hiteshgautam01/Recycler-View-android-BJP | fef72a73010123a9f9ac12427cf5e96df13be2b1 | 08d9b9898eb347aabdf08cdae25b1eab44148848 |
refs/heads/master | <repo_name>LublubXT/Azi-Tec-Team<file_sep>/app.js
const express = require("express");
const bodyParser = require("body-parser");
const ejs = require("ejs");
const mongoose = require("mongoose");
const session = require('express-session');
const passport = require("passport");
const passportLocalMongoose = require("passport-local-mongoose");
const GoogleStrategy = require('passport-google-oauth20').Strategy;
const findOrCreate = require('mongoose-findorcreate');
require('dotenv').config();
const AdmZip = require('adm-zip');
const app = express();
var counter = 0;
var viewsList = [];
var dateList = [];
var today = new Date();
var date = today.getFullYear() + '_' + (today.getMonth() + 1) + '_' + today.getDate();
var date1 = today.getFullYear() + '_' + (today.getMonth() + 1) + '_' + today.getDate() + '_' + today.getTime();
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static("public"));
app.use(session({
secret: "Our little item.",
resave: false,
saveUninitialized: false
}));
app.use(passport.initialize());
app.use(passport.session());
const Schema = mongoose.Schema;
const url2 = "mongodb://localhost:27017/views";
const url1 = "mongodb+srv://caleb:<EMAIL>@<EMAIL>.i6h4q.mongodb.net/sermontracker?retryWrites=true&w=majority";
mongoose.connect(url1, { useNewUrlParser: true, useUnifiedTopology: true });
mongoose.set("useCreateIndex", true);
const userSchema = new mongoose.Schema({
fname: String,
lname: String,
email: String,
password: String,
googleId: String,
items: Array,
app: String
});
const ItemSchema = new mongoose.Schema({
date: String,
loc: String,
title: String,
passage: String,
file: String
});
const ViewSchema = new mongoose.Schema({
_id: String,
number: Number,
date: String
});
const BlogSchema = new mongoose.Schema({
title: String,
date: String,
main: String
});
const QuestSchema = new mongoose.Schema({
name: String,
useremail: String,
message: String,
date: String
});
userSchema.plugin(passportLocalMongoose);
userSchema.plugin(findOrCreate);
const User = new mongoose.model("User", userSchema);
const Item = new mongoose.model("Item", ItemSchema);
const Views = new mongoose.model("View", ViewSchema);
const Blog = new mongoose.model("Blog", BlogSchema);
const Quest = new mongoose.model("Quest", QuestSchema);
passport.use(User.createStrategy());
passport.serializeUser(function(user, done) {
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
User.findById(id, function(err, user) {
done(err, user);
});
});
function log(text) {
console.log(text);
}
app.get("/", function(req, res) {
counter += 1;
res.render("main/Home");
alowed = false;
Views.find({ _id: date }, function(err, view) {
if (err) {
console.log(err);
} else if (view == "") {
const views = new Views({
_id: date,
number: 0,
date: date
});
views.save();
} else {
view.forEach(function(v) {
if (v.date == date) {
counter + v.number;
Views.updateOne({ date: date }, { number: counter }, function(err) {
if (err) {
console.log(err);
}
});
} else if (v.date != date) {
const views = new Views({
_id: date,
number: 0,
date: date
});
views.save();
}
if (v.date != date) {
views.save();
} else if (v.date == date) {
counter + v.number;
Views.updateOne({ _id: date }, { number: counter }, function(err) {});
}
});
}
});
Views.find(function(err, view) {
if (err) {
console.log(err);
} else {
view.forEach(function(v) {
viewsList.push(v.number + 1);
dateList.push(v.date);
});
}
});
});
app.get("/downloadpage", function(req, res) {
res.render("main/DownloadPage");
});
app.get("/contact", function(req, res) {
res.render("main/Contact");
});
app.get("/numberline", function(req, res) {
res.render("main/Number_LineDownload");
});
app.get("/onlineapps", function(req, res) {
res.render("main/OnlineApps");
});
app.get("/signup", function(req, res) {
res.render("main/SignIn");
});
app.post("/signup", function(req, res) {
var username = req.body.username;
var firstname = req.body.firstName;
var lastname = req.body.lastName;
const newClient = new User({
email: username,
lname: lastname,
fname: firstname,
app: "Azi Tec Team Website"
});
newClient.save(function(err) {
if (err) {
console.log(err);
} else {
res.redirect("/");
}
});
});
app.get("/thanks", function(req, res) {
res.render("main/Thanks");
});
app.get("/timeline", function(req, res) {
res.render("main/Time_LineDownload");
});
app.get("/about", function(req, res) {
res.render("main/About");
});
app.get("/timelinedownload", function(req, res) {
res.download(__dirname + 'uploads/Timeline/Time Line 1.0.zip', 'Time Line 1.0.zip');
});
app.get("/numberlinedownload", function(req, res) {
res.download(__dirname + 'uploads/Numberline/Number_Line_3.0.zip', 'Number_Line_3.0.zip');
});
app.get("/sermontrackerhome", function(req, res) {
res.render("sermontracker/home");
});
app.get("/sermontrackerlogin", function(req, res) {
res.render("sermontracker/login");
});
app.get("/sermonsignup", function(req, res) {
res.render("sermontracker/signup");
});
app.get("/workspace", function(req, res) {
User.find({ _id: req.user._id }, function(err, foundItems) {
if (err) {
console.log(err);
} else if (foundItems) {
for (var i = 0; i < foundItems.length; i++) {
res.render("sermontracker/workspace", { itemList: foundItems[i].items });
}
}
});
});
app.post("/workspace", function(req, res) {
const date = req.body.input1;
const location = req.body.input2;
const title = req.body.input3;
const passage = req.body.input4;
const file = req.body.input5;
const item = new Item({
date: date,
loc: location,
title: title,
passage: passage,
file: file
});
User.findById(req.user._id, function(err, foundUser) {
if (err) {
console.log(err);
} else {
if (foundUser) {
foundUser.items.push(item);
foundUser.save(function() {
res.redirect("/workspace");
});
}
}
});
});
app.get("/workspaceLight", function(req, res) {
User.find({ _id: req.user._id }, function(err, foundItems) {
if (err) {
console.log(err);
} else if (foundItems) {
for (var i = 0; i < foundItems.length; i++) {
res.render("sermontracker/workspaceLight", { itemList: foundItems[i].items });
}
}
});
});
app.post("/delete", function(req, res) {
const delBut = req.body.deleteItem;
User.find({ _id: req.user._id }, function(err, foundItemList) {
if (err) {
console.log(err);
} else {
if (foundItemList) {
for (var i = 0; i < foundItemList.length; i++) {
var itemList = foundItemList[i].items;
itemList.forEach(function(item) {
if (item._id == delBut) {
//foundItemList[i].items.splice(i, 1);
User.findByIdAndUpdate({ _id: req.user._id }, { $pull: { 'items': { _id: item._id } } }, function(err, model) {
if (err) {
console.log(err);
} else {
if (model) {
console.log(model);
}
}
});
res.redirect("/workspace");
}
});
}
}
}
});
});
app.post("/delete1", function(req, res) {
const delBut = req.body.deleteItem;
User.find({ _id: req.user._id }, function(err, foundItemList) {
if (err) {
console.log(err);
} else {
if (foundItemList) {
for (var i = 0; i < foundItemList.length; i++) {
var itemList = foundItemList[i].items;
itemList.forEach(function(item) {
if (item._id == delBut) {
//foundItemList[i].items.splice(i, 1);
User.findByIdAndUpdate({ _id: req.user._id }, { $pull: { 'items': { _id: item._id } } }, function(err, model) {
if (err) {
console.log(err);
} else {
if (model) {}
}
});
res.redirect("/workspaceLight");
}
});
}
}
}
});
})
app.post("/workspaceLight", function(req, res) {
const date = req.body.input1;
const location = req.body.input2;
const title = req.body.input3;
const passage = req.body.input4;
const file = req.body.input5;
const item = new Item({
date: date,
loc: location,
title: title,
passage: passage,
file: file
});
User.findById(req.user._id, function(err, foundUser) {
if (err) {
console.log(err);
} else {
if (foundUser) {
foundUser.items.push(item);
foundUser.save(function() {
res.redirect("/workspaceLight");
});
}
}
});
});
app.get("/logout", function(req, res) {
req.logout();
res.redirect("/sermontrackerhome");
});
app.post("/logout", function(req, res) {
req.logout();
res.redirect("/sermontrackerhome");
});
app.post("/sermonsignup", function(req, res) {
User.register({ username: req.body.username, fname: req.body.firstName, lname: req.body.lastName, app: "Sermon Tracker" }, req.body.password, function(err, user) {
if (err) {
console.log(err);
res.redirect("/sermonsignup");
} else {
passport.authenticate("local")(req, res, function() {
res.redirect("/workspace");
});
}
});
});
app.get("/secrets", function(req, res) {
res.render("main/secretlogin");
});
app.get("/secretsworkspaceblog", function(req, res) {
User.find({ _id: req.user._id }, function(err, foundItems) {
if (err) {
console.log(err);
} else if (foundItems) {
Blog.find({}, function(err, foundItems) {
res.render("main/secretsworkspaceblog", { post: foundItems });
});
}
});
});
app.get("/secretsworkspacequestions", function(req, res) {
User.find({ _id: req.user._id }, function(err, foundItems) {
if (err) {
console.log(err);
} else if (foundItems) {
Quest.find({}, function(err, foundItems) {
res.render("main/secretsworkspacequestions", { questions: foundItems });
});
}
});
});
app.get("/secretsworkspaceclients", function(req, res) {
User.find({ _id: req.user._id }, function(err, foundItems) {
if (err) {
console.log(err);
} else if (foundItems) {
User.find({}, function(err, foundItems) {
res.render("main/secretsworkspaceclients", { clients: foundItems });
});
}
});
});
app.post("/deleteclient", function(req, res) {
const checkedItem = req.body.deleteclient;
if (checkedItem === "6090f79df8ffc1215322a17d") {
console.log("You cannot delete this one!")
} else if (checkedItem !== "6090f79df8ffc1215322a17d") {
User.findByIdAndRemove(checkedItem, function(err) {
console.log("Deleted User");
});
}
res.redirect("/secretsworkspaceclients");
});
app.get("/secretsworkspace", function(req, res) {
User.find({ _id: req.user._id }, function(err, foundItems) {
if (err) {
console.log(err);
} else if (foundItems) {
Views.find({}, function(err, foundItems) {
res.render("main/secretsworkspace", { views: viewsList, dates: dateList, dates1: date1, newListItems: foundItems });
});
}
});
});
app.get("/blog", function(req, res) {
Blog.find({}, function(err, foundItems) {
res.render("main/blog", { post: foundItems });
});
});
app.post("/sendmess", function(req, res) {
var n = req.body.name;
var e = req.body.email;
var m = req.body.message;
var d = Date();
log(n);
log(e);
log(m);
const message = new Quest({
name: n,
useremail: e,
message: m,
date: d
});
message.save(function(err) {
if (err) {
console.log(err);
} else {
res.redirect("/");
}
});
});
app.post("/secretsworkspaceblog", function(req, res) {
const blogPost = new Blog({
title: req.body.title,
date: date,
main: req.body.main
});
blogPost.save(function(err) {
if (err) {
console.log(err);
} else {
res.redirect("/secretsworkspaceblog");
}
});
});
app.post("/deletepost", function(req, res) {
const checkedItem = req.body.deletepost;
Blog.findByIdAndRemove(checkedItem, function(err) {
console.log("Deleted item");
});
res.redirect("/secretsworkspaceblog");
});
app.post("/deletequestion", function(req, res) {
const checkedItem = req.body.deletequestion;
Quest.findByIdAndRemove(checkedItem, function(err) {
console.log("Deleted Question");
});
res.redirect("/secretsworkspacequestions");
});
app.post("/login", function(req, res) {
const user = new User({
username: req.body.username,
password: <PASSWORD>
});
req.login(user, function(err) {
if (err) {
console.log(err);
} else {
passport.authenticate("local")(req, res, function() {
res.redirect("/workspace");
});
}
});
});
// Un comment this to fix the secrets login
// app.post("/secrets", function (req, res) {
// User.register({ username: req.body.username, app: "Secrets" }, req.body.password, function (err, user) {
// if (err) {
// console.log(err);
// res.redirect("signup");
// } else {
// passport.authenticate("local")(req, res, function () {
// res.redirect("/secretsworkspace");
// });
// }
// });
// });
app.post("/secrets", function(req, res) {
const user = new User({
username: req.body.username,
password: <PASSWORD>
});
req.login(user, function(err) {
if (err) {
console.log(err);
} else {
passport.authenticate("local")(req, res, function() {
res.redirect("/secretsworkspace");
});
}
});
});
let port = process.env.PORT;
if (port == null || port == "") {
port = 3000;
}
app.listen(port, function() {
console.log("Server started on port 3000");
});<file_sep>/README.md
# Azi-Tec-Web-Site
# Azi-Tec-Web-Site
| 3da7d0263b9e112712fdb9498c113b1c09ba14b9 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | LublubXT/Azi-Tec-Team | 668a1c031c8a08e7d5556b11dba84a9069d767b4 | 65d2344ed6819f31f3d97a69af02b7cff5ed104e |
refs/heads/master | <repo_name>zyyang/fuguang<file_sep>/server/bin/openerp-server.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
"""
OpenERP - Server
OpenERP is an ERP+CRM program for small and medium businesses.
The whole source code is distributed under the terms of the
GNU Public Licence.
(c) 2003-TODAY, <NAME> - OpenERP s.a.
"""
#----------------------------------------------------------
# python imports
#----------------------------------------------------------
import logging
import os, sys
import signal
import sys
import threading
import traceback
import release
__author__ = release.author
__version__ = release.version
if sys.getdefaultencoding() != 'utf-8':
reload(sys)
sys.setdefaultencoding('utf-8')
if os.name == 'posix':
import pwd
# We DON't log this using the standard logger, because we might mess
# with the logfile's permissions. Just do a quick exit here.
if pwd.getpwuid(os.getuid())[0] == 'root' :
sys.stderr.write("Attempted to run OpenERP server as root. This is not good, aborting.\n")
sys.exit(1)
#----------------------------------------------------------
# get logger
#----------------------------------------------------------
import netsvc
logger = logging.getLogger('server')
#-----------------------------------------------------------------------
# import the tools module so that the commandline parameters are parsed
#-----------------------------------------------------------------------
import tools
logger.info("OpenERP version - %s", release.version)
for name, value in [('addons_path', tools.config['addons_path']),
('database hostname', tools.config['db_host'] or 'localhost'),
('database port', tools.config['db_port'] or '5432'),
('database user', tools.config['db_user'])]:
logger.info("%s - %s", name, value)
# Don't allow if the connection to PostgreSQL done by postgres user
if tools.config['db_user'] == 'postgres':
logger.error("Connecting to the database as 'postgres' user is forbidden, as it present major security issues. Shutting down.")
sys.exit(1)
import time
#----------------------------------------------------------
# init net service
#----------------------------------------------------------
logger.info('initialising distributed objects services')
#---------------------------------------------------------------
# connect to the database and initialize it with base if needed
#---------------------------------------------------------------
import pooler
#----------------------------------------------------------
# import basic modules
#----------------------------------------------------------
import osv
import workflow
import report
import service
#----------------------------------------------------------
# import addons
#----------------------------------------------------------
import addons
#----------------------------------------------------------
# Load and update databases if requested
#----------------------------------------------------------
import service.http_server
if not ( tools.config["stop_after_init"] or \
tools.config["translate_in"] or \
tools.config["translate_out"] ):
service.http_server.init_servers()
service.http_server.init_xmlrpc()
service.http_server.init_static_http()
import service.netrpc_server
service.netrpc_server.init_servers()
if tools.config['db_name']:
for dbname in tools.config['db_name'].split(','):
db,pool = pooler.get_db_and_pool(dbname, update_module=tools.config['init'] or tools.config['update'], pooljobs=False)
cr = db.cursor()
if tools.config["test_file"]:
logger.info('loading test file %s', tools.config["test_file"])
tools.convert_yaml_import(cr, 'base', file(tools.config["test_file"]), {}, 'test', True)
cr.rollback()
pool.get('ir.cron')._poolJobs(db.dbname)
cr.close()
#----------------------------------------------------------
# translation stuff
#----------------------------------------------------------
if tools.config["translate_out"]:
import csv
if tools.config["language"]:
msg = "language %s" % (tools.config["language"],)
else:
msg = "new language"
logger.info('writing translation file for %s to %s', msg, tools.config["translate_out"])
fileformat = os.path.splitext(tools.config["translate_out"])[-1][1:].lower()
buf = file(tools.config["translate_out"], "w")
dbname = tools.config['db_name']
cr = pooler.get_db(dbname).cursor()
tools.trans_export(tools.config["language"], tools.config["translate_modules"] or ["all"], buf, fileformat, cr)
cr.close()
buf.close()
logger.info('translation file written successfully')
sys.exit(0)
if tools.config["translate_in"]:
context = {'overwrite': tools.config["overwrite_existing_translations"]}
dbname = tools.config['db_name']
cr = pooler.get_db(dbname).cursor()
tools.trans_load(cr,
tools.config["translate_in"],
tools.config["language"],
context=context)
tools.trans_update_res_ids(cr)
cr.commit()
cr.close()
sys.exit(0)
#----------------------------------------------------------------------------------
# if we don't want the server to continue to run after initialization, we quit here
#----------------------------------------------------------------------------------
if tools.config["stop_after_init"]:
sys.exit(0)
#----------------------------------------------------------
# Launch Servers
#----------------------------------------------------------
LST_SIGNALS = ['SIGINT', 'SIGTERM']
SIGNALS = dict(
[(getattr(signal, sign), sign) for sign in LST_SIGNALS]
)
netsvc.quit_signals_received = 0
def handler(signum, frame):
"""
:param signum: the signal number
:param frame: the interrupted stack frame or None
"""
netsvc.quit_signals_received += 1
if netsvc.quit_signals_received > 1:
sys.stderr.write("Forced shutdown.\n")
os._exit(0)
def dumpstacks(signum, frame):
# code from http://stackoverflow.com/questions/132058/getting-stack-trace-from-a-running-python-application#answer-2569696
# modified for python 2.5 compatibility
thread_map = dict(threading._active, **threading._limbo)
id2name = dict([(threadId, thread.getName()) for threadId, thread in thread_map.items()])
code = []
for threadId, stack in sys._current_frames().items():
code.append("\n# Thread: %s(%d)" % (id2name[threadId], threadId))
for filename, lineno, name, line in traceback.extract_stack(stack):
code.append('File: "%s", line %d, in %s' % (filename, lineno, name))
if line:
code.append(" %s" % (line.strip()))
logging.getLogger('dumpstacks').info("\n".join(code))
for signum in SIGNALS:
signal.signal(signum, handler)
if os.name == 'posix':
signal.signal(signal.SIGQUIT, dumpstacks)
def quit():
netsvc.Agent.quit()
netsvc.Server.quitAll()
if tools.config['pidfile']:
os.unlink(tools.config['pidfile'])
logger = logging.getLogger('shutdown')
logger.info("Initiating OpenERP Server shutdown")
logger.info("Hit CTRL-C again or send a second signal to immediately terminate the server...")
logging.shutdown()
# manually join() all threads before calling sys.exit() to allow a second signal
# to trigger _force_quit() in case some non-daemon threads won't exit cleanly.
# threading.Thread.join() should not mask signals (at least in python 2.5)
for thread in threading.enumerate():
if thread != threading.currentThread() and not thread.isDaemon():
while thread.isAlive():
# need a busyloop here as thread.join() masks signals
# and would present the forced shutdown
thread.join(0.05)
time.sleep(0.05)
sys.exit(0)
if tools.config['pidfile']:
fd = open(tools.config['pidfile'], 'w')
pidtext = "%d" % (os.getpid())
fd.write(pidtext)
fd.close()
netsvc.Server.startAll()
logger.info('OpenERP server is running, waiting for connections...')
while netsvc.quit_signals_received == 0:
time.sleep(60)
quit()
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
| 595c2060573ae684c80e9ad5df0f0242b6ef80f4 | [
"Python"
] | 1 | Python | zyyang/fuguang | 5553a33e9e498ec25512cf7854113cae1aebecb6 | 9830ba4f6b75ccb025e406aae402d8b56d7912c7 |
refs/heads/master | <file_sep>import os
import matplotlib.pyplot as plt
import pandas as pd
def core_nmr_T2dist(nmr_df, micp_df, common_id_list):
"""
:param df: T2, Por, BVIPorがあるdf。複数サンプルが縦に共存することを前提としている(groupbyで回す)
:return:
"""
# T2 distributionのグラフ描画
# 参考 (http://sinhrks.hatenablog.com/entry/2015/11/15/222543)
fig, axes = plt.subplots(5, 4, figsize=(10, 8))
plt.subplots_adjust(wspace=0.5, hspace=0.5)
for ax, id in zip(axes.flatten(), common_id_list):
# 共通したidを持つサンプルのデータを抽出
nmr_group = nmr_df[nmr_df['ID']==id]
micp_group = micp_df[micp_df['ID']==id]
# x軸は対数目盛
ax.set_xscale("log")
# 横軸T2で、Sw= 100とirreducible conditionのPorを縦軸に重ねて描画
ax.plot(nmr_group.T2, nmr_group.Por, linewidth = 0.8)
ax.plot(micp_group["PTR"], micp_group["Por_micp"], linewidth=0.8)
ax.set_ylim(0, 4)
ax.set_ylabel("")
ax.set_title(id, fontsize=8)
ax.legend()
plt.show()
if __name__ == "__main__":
the_nmr_df = pd.read_csv(r"D:\tmp\calliance1_nmr.csv")
the_micp_df = pd.read_csv(r"D:\tmp\calliance1_micp.csv")
the_common_id_list = list(set(the_nmr_df["ID"].unique()) & set(the_micp_df["ID"].unique()))
# グラフ描画
core_nmr_T2dist(the_nmr_df, the_micp_df, the_common_id_list)
<file_sep>import os
import pandas as pd
import numpy as np
def calc_t2_cumulative(df):
"""
csvにcumulative porosity行と、cumulative BVI行を追記
:param df:
:return:
"""
group_list = []
for key, group in df.groupby("ID"):
group["Por_cum"] = np.cumsum(group.Por)
group["BVI_Por_cum"] = np.cumsum(group.BVI_Por)
group_list.append(group)
output_df = pd.concat(group_list)
return output_df
if __name__ == "__main__":
# ---------inputs-------------------
input_folderpath = r"D:\tmp"
input_filename = "calliance1_nmr.csv"
# ---------------------------------
input_file = os.path.join(input_folderpath, input_filename)
the_df = pd.read_csv(input_file)
the_new_df = calc_t2_cumulative(the_df)
the_new_df.to_csv(os.path.join(input_folderpath, input_filename), index=False)<file_sep>import os
import pandas as pd
from scipy import interpolate
import numpy as np
import itertools
def BVI_cutoff(df, C):
"""
cutoff BVIを計算
"""
return np.sum(df.Por[df.T2 < C])
def calc_cutoff_C(df):
"""
各コアで最適なcutff Cの値を算出する。
:param df: groupbyで単一sampleについてのデータにしてからinputする必要ある。
:return: t2_cutoff 最適化されたcutoff値
"""
# xの増分が0だとうまくinterpolateできないため、微小量増加を入れる
cum_por = []
for i, cum_por_ in enumerate(df.Por_cum):
cum_por_ = cum_por_ + 0.00001 * i
cum_por.append(cum_por_)
# cutoff値を計算
t2_cutoff = float(interpolate.interp1d(cum_por, df.T2, kind="linear")(df.BVI_Por_cum.iloc[-1]))
return t2_cutoff
def BVI_spectral_theoretical(x, df, Pci=50):
"""
X, df, Pciをインプットとして、コアサンプルのspectral BVIおよびそのx微分値を返す。
ただしx = sigma / rho2 とする。
"""
# 各T2におけるSwiの列を作成
T2i = x / Pci
df["Swi"] = T2i / df.T2.copy() * (2 - T2i / df.T2.copy())
# 微分した式
df["Swi_dx"] = 2 / (df.T2 * Pci) - 2 * x / (df.T2 * df.T2 * Pci * Pci)
# T2 < T2i(すなわちWi > W) のところではSwi = 1, Swiの傾きは0
df.Swi[df.T2 < T2i] = 1
df.Swi_dx[df.T2 < T2i] = 0
# spectral BVIを産出
BVI = df.Por.dot(df.Swi)
# spectral BVIのx微分の値は
BVI_dx = df.Por.dot(df.Swi_dx)
return BVI, BVI_dx
def X_spectral_theoretical(x0, df, Pci=50):
"""
spectral BVIをtheoreticalにやった時、
各コアで最適化したx = sigma / Rho_2 (岩相に依存した係数)の値を求める。
:inputs
x first pint of sigma / rho_2
df
Pci irreducible conditionにおけるcapillary pressure.
xの値を知りたいときは正しい値をinputにする必要があるが、BVIを計算する段階ではx/pciが決まるので、default値を適当に設定
"""
# 初期値を指定
x = x0
# 解きたい方程式 objective
objective = BVI_spectral_theoretical(x, df, Pci)[0] - df.BVI_Por_cum.iloc[-1]
objective_dx = BVI_spectral_theoretical(x, df, Pci)[1]
# Newton法で解く。
for count in range(10000):
x_next = x - objective / objective_dx
diff_x = abs(x - x_next)
if diff_x > 1:
x = x_next
objective = BVI_spectral_theoretical(x, df, Pci)[0] - df.BVI_Por_cum.iloc[-1]
objective_dx = BVI_spectral_theoretical(x, df, Pci)[1]
else:
x = x_next
# print("sample={4}, count={0}, x={1}, objective={2}, diff_x={3}, dx={5}".format(
# count, x, objective, diff_x, df.ID.iloc[1], objective_dx))
break
return x
def BVI_spectral_empirical(df, m, b):
"""
経験式に基づいたspectral BVIの算出
"""
# 各T2におけるSwiの列を作成
df["Swi"] = 1 / (m * df.T2.copy() + b)
# mについて微分した式
df["Swi_dm"] = -1 * (df.T2.copy() / ((m * df.T2.copy() + b) ** 2))
# bについて微分した式
df["Swi_db"] = -1 / ((m * df.T2.copy() + b) ** 2)
# T2 < T2i(すなわちWi > W) のところではSwi = 1, Swiの傾きは0
df.Swi[df.Swi > 1] = 1
df.Swi[df.Swi < 0] = 0
df.Swi_dm[df.Swi > 1] = 0
df.Swi_dm[df.Swi < 0] = 0
df.Swi_db[df.Swi > 1] = 0
df.Swi_db[df.Swi < 0] = 0
# spectral BVIを産出
BVI = df.Por.dot(df.Swi)
# BVIの偏微分を算出
BVI_dm = df.Por.dot(df.Swi_dm)
BVI_db = df.Por.dot(df.Swi_db)
return BVI, BVI_dm, BVI_db
def m_b_spectral_empirical(df, m0, b0):
"""
このモジュールのinput dfは,複数サンプルを含んだdf
"""
m_list = []
b_list = []
# inputから,あらゆる組み合わせでsampleを取り出す
for combi_group in itertools.combinations(df.groupby("ID"), 2):
key_1, group_1 = combi_group[0]
key_2, group_2 = combi_group[1]
# 初期設定のmとb
m = m0
b = b0
# objective_1とobjective_2の連立方程式をm, bについて解く
# ニュートン法を用いる
for count in range(1000):
objective_1 = BVI_spectral_empirical(group_1, m, b)[0] - group_1.BVI_Por_cum.iloc[-1]
objective_2 = BVI_spectral_empirical(group_2, m, b)[0] - group_2.BVI_Por_cum.iloc[-1]
objective_dm_1 = BVI_spectral_empirical(group_1, m, b)[1]
objective_db_1 = BVI_spectral_empirical(group_1, m, b)[2]
objective_dm_2 = BVI_spectral_empirical(group_2, m, b)[1]
objective_db_2 = BVI_spectral_empirical(group_2, m, b)[2]
# 計算をしやすくするために行列の形にする
var_array = np.array([m, b])
objective_array = np.array([objective_1, objective_2])
gradient_matrix = np.array([[objective_dm_1, objective_db_1],
[objective_dm_2, objective_db_2]])
# 漸化式を解き、次のステップのm, bを算出
next_var_array = var_array - np.dot(
np.linalg.pinv(gradient_matrix), objective_array)
m = next_var_array[0]
b = next_var_array[1]
diff = np.sqrt(np.sum((var_array - next_var_array) ** 2))
if diff > 0.1:
# print("m={0}, b={1}, continue".format(m, b))
continue
else:
print("break! k1={0}, k2={1}, m={3}, b={4}, count={2}".format(
key_1, key_2, count, m, b))
m_list.append(m)
b_list.append(b)
break
# 条件で搾れるようarrayに直す
m_list = np.array(m_list)
b_list = np.array(b_list)
# 0 < m < 0.1, b > 0 を満たすべき
m_list_adopted = m_list[(0 < m_list) & (m_list < 0.2) & (0 < b_list) & (b_list < 3)]
b_list_adopted = b_list[(0 < m_list) & (m_list < 0.2) & (0 < b_list) & (b_list < 3)]
# m_listおよびb_listの平均値を最適なm, bの値とする
optimized_m = sum(m_list_adopted) / len(m_list_adopted)
optimized_b = sum(b_list_adopted) / len(b_list_adopted)
return m_list_adopted, b_list_adopted, optimized_m, optimized_b
if __name__ == "__main__":
# ---------inputs-------------------
input_folderpath = r"C:\Users\02217013\Documents"
input_filename = "calliance1_nmr.csv"
# newton法をすたーとするx, m, bの値
x0 = 1000
m0 = 0.055
b0 = 1
# default cutoff値
C = 33
# ---------------------------------
input_file = os.path.join(input_folderpath, input_filename)
the_df = pd.read_csv(input_file)
# the_cut_coates_dict = main(the_df)
m_list, b_list, optimized_m, optimized_b = m_b_spectral_empirical(the_df, m0, b0)
"""
for key, group in the_df.groupby("ID"):
# cutoff BVIを算出
the_BVI_cutoff = BVI_cutoff(group, C)
# calc_T2_cutoff
the_t2_cutoff = calc_cutoff_C(group)
# calc best x using newton method
optimized_x = X_spectral_theoretical(x0, group)
print(the_BVI_cutoff, the_t2_cutoff, optimized_x)
"""<file_sep>import sys
import os
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# my module
current_dir = os.path.dirname(os.path.abspath(__file__))
sys.path.append(os.path.join(current_dir, '../'))
import timor_coates as ktim
import calc_cutoff_BVI
def confirm_c_coates(Calliance1_nmr_df):
"""
c_coatesを変えると、プロット上ではどんな変化をするのか(平行移動?)確認.
:param Calliance1_nmr_df:
:return:
"""
c_coates_list = [0.1, 0.2, 0.4, 0.8]
# predicted permeability vs core permeability
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
for c_coates_ in c_coates_list:
Calliance1_result_df = ktim.main(Calliance1_nmr_df, c_coates=c_coates_)
print(Calliance1_result_df)
x = Calliance1_result_df["ktim"]
y = Calliance1_result_df["cperm"]
ax.scatter(x, y, label=c_coates_)
for i, row in Calliance1_result_df.iterrows():
ax.annotate(row["ID"], (row["ktim"], row["cperm"]), size=8)
ax.set_xscale("log")
ax.set_yscale("log")
ax.set_xlim([0.000001, 1000000])
ax.set_ylim([0.000001, 1000000])
ax.legend()
plt.show()
if __name__ == "__main__":
# ---------inputs-------------------
input_folderpath = r"D:"
input_filename_list = ["Calliance1.csv"]
# output_file = r"D:\PPRT関係\result\Caliance1_ktim.csv"
# ---------------------------------
# csvファイル読み込み
the_input_df = pd.concat(pd.read_csv(os.path.join(input_folderpath, input_filename)) for input_filename in input_filename_list)
# cut_coatesを辞書型で取得
the_cut_coates_dict = calc_cutoff_BVI.main(the_input_df)
# c_coatesを変えると、プロット上ではどんな変化をするのか(平行移動?)確認.
# confirm_c_coates(Calliance1_nmr_df)
# cut_coatesをしていしたverと指定しないverでそれぞれcperm vs ktimのプロットを作成し、どの程度それっぽさがアップするかを確認
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
the_nmr_result_df_dict = {}
# default cut_coates
the_nmr_result_df_dict["default_cut"] = ktim.main(the_input_df)
# my defined cut coates
the_nmr_result_df_dict["my_cut"] = ktim.main(the_input_df, cut_coates_dict=the_cut_coates_dict)
for key, the_result_df in the_nmr_result_df_dict.items():
print(key, the_result_df)
x = the_result_df["ktim"]
y = the_result_df["cperm"]
ax.scatter(x, y, label=key)
for i, row in the_result_df.iterrows():
ax.annotate(row["ID"], (row["ktim"], row["cperm"]), size=8)
# 描画範囲の指定
pict_range = [0.001, 100000]
# 参考にx=yのラインを追加。
x = np.arange(pict_range[0], pict_range[1])
y = x
ax.plot(x, y)
# 軸の設定など
ax.set_xscale("log")
ax.set_yscale("log")
ax.set_xlim(pict_range)
ax.set_ylim(pict_range)
ax.set_xlabel('perm_pred')
ax.set_ylabel('perm_core')
ax.legend()
plt.show()<file_sep>import os
import matplotlib.pyplot as plt
import pandas as pd
def core_nmr_T2dist(df):
"""
:param df: T2, Por, BVIPorがあるdf。複数サンプルが縦に共存することを前提としている(groupbyで回す)
:return:
"""
# T2 distributionのグラフ描画
# 参考 (http://sinhrks.hatenablog.com/entry/2015/11/15/222543)
fig, axes = plt.subplots(5, 4, figsize=(10, 8))
plt.subplots_adjust(wspace=0.5, hspace=0.5)
for ax, (key, group) in zip(axes.flatten(), df.groupby("ID")):
# x軸は対数目盛
ax.set_xscale("log")
# 横軸T2で、Sw= 100とirreducible conditionのPorを縦軸に重ねて描画
ax.plot(group["T2"], group["Por"], linewidth = 0.8)
ax.plot(group["T2"], group["BVI_Por"], linewidth = 0.8)
# cumulative porosityも描画
ax2 = ax.twinx()
ax2.plot(group["T2"], group["Por_cum"], linestyle='dashed', linewidth = 0.8)
ax2.plot(group["T2"], group["BVI_Por_cum"], linestyle='dashed', linewidth = 0.8)
ax.set_ylim(0, 4)
ax2.set_ylim(0, 25)
ax.set_ylabel("")
ax.set_title(key, fontsize=8)
plt.show()
if __name__ == "__main__":
# ---------inputs-------------------
input_folderpath = r"D:"
input_filename = "Calliance1.csv"
# ---------------------------------
input_file = os.path.join(input_folderpath, input_filename)
Calliance1_nmr_df = pd.read_csv(input_file)
print(Calliance1_nmr_df["ID"].unique())
# T2 distributionのグラフ描画
core_nmr_T2dist(Calliance1_nmr_df)
<file_sep>import os
import pandas as pd
import numpy as np
from scipy import interpolate
def k_timor_coates(df, cut_coates, c_coates, phit):
"""
T2 distributionからtimor coats permeabilityを計算。
:param df: T2 distributionのdf. "T2" columnと"Por" columnは必須。"BVI_Por" columnもあったほうがいい。
:param cut_coates: T2のカットオフ値. これ以下のT2はBVIとして扱う
:param c_coates: 地層に依存して決まる定数
:param por: den-neu phitなど、使いたい孔隙率があればinput. なければNMR phitを用いる
:return:
"""
# defaultで値を入れるのではなくこうすることで、一部のデータだけphitを指定することができる。
if phit == None:
t2cum = np.cumsum(df.Por) / 100
phit = t2cum.iloc[-1]
if cut_coates == None:
cut_coates = 33
# cut_coatesの時のt2cumの値。(T2-t2cumの関係を、スプライン補完でインターポレートして算出)
bvi = float(interpolate.interp1d(df.T2, t2cum, kind="cubic")(cut_coates))
ffi = max(0, phit - bvi)
ktim = (phit / c_coates) ** 4 * (ffi / bvi) ** 2
return ktim
def main(df, cut_coates_dict={}, c_coates=0.1, phit=None):
print(cut_coates_dict)
output_dict = {"ID": [], "ktim": [], "cperm": []}
for key, group in df.groupby("ID"):
ktim = k_timor_coates(group, cut_coates=cut_coates_dict.get(key),
c_coates=c_coates, phit=phit)
output_dict["ID"].append(key)
output_dict["ktim"].append(ktim)
output_dict["cperm"].append(group.cperm.iloc[1])
# print("{0}のcperm={1}, ktim={2}".format(key, group.cperm.iloc[1], ktim))
output_df = pd.DataFrame(output_dict)
# print(output_df)
return output_df
if __name__ == "__main__":
# ---------inputs-------------------
input_folderpath = r"D:\PPRT関係\data"
input_filename = "Calliance1.csv"
# output_file = r"D:\PPRT関係\result\Caliance1_ktim.csv"
# ---------------------------------
# csvファイル読み込み
input_file = os.path.join(input_folderpath, input_filename)
Calliance1_nmr_df = pd.read_csv(input_file)
# グラフをみてじぶんで定義したcut_coates
the_cut_coates_dict = {"Calliance1_22": 15,
"Calliance1_24": 20,
"Calliance1_28": 26
}
ktim_result_df = main(Calliance1_nmr_df)
print(ktim_result_df) | 1aafc4537426d353ee41e47b902c0a690d573142 | [
"Python"
] | 6 | Python | griCe14807/PPRT | e6a0c3c96d20996c973c6f5c42e71227d7c19967 | 5dcc197db501953b9906b71f293273ef9420651e |
refs/heads/gh-pages | <file_sep>module.exports = {
currencies: {
url: 'https://openexchangerates.org/api/latest.json?app_id=8556217a83d84985930d67d6cf934289',
symbols: {
USD: 'US$',
CAD: 'CA$',
HKD: 'HK$',
SGD: 'SG$',
AUD: 'AU$',
THB: '฿',
JPY: '¥',
GBP: '£',
EUR: '€',
CZK: 'Kč',
UAH: '₴',
BTC: 'BTC'
},
sorter: ['USD', 'EUR', 'GBP', 'RUB', 'UAH', 'BTC']
},
subjectiveWords: {
crime: ['very high', 'high', 'moderate', 'low', 'very low'],
prices: ['very expensive', 'expensive', 'moderate', 'cheap', 'very cheap'],
business: ['very hard', 'hard', 'moderate', 'easy', 'very easy'],
corruption: ['very bad', 'bad', 'moderate', 'good', 'very good'],
total: ['very bad', 'bad', 'moderate', 'good', 'very good']
}
};
<file_sep>var symbols = require('config').currencies.symbols;
var utils = require('utils');
App.ApplicationController = Ember.Controller.extend({
currencyCode: 'USD'
});
App.NavbarController = Ember.Controller.extend({
needs: ['application'],
currencyCode: Ember.computed.alias('controllers.application.currencyCode')
});
App.RatingsController = Ember.ArrayController.extend({
});
var filterNames = [
'noEducationWorkVisa', 'warmClimate', 'ruleOfLaw',
'lowCrime',
'lowTaxes', 'noWorkVisaQuotas', 'simpleStartupVisa'
];
App.FilterSet = Ember.Object.extend({
noEducationWorkVisa: false,
warmClimate: false,
ruleOfLaw: false,
lowTaxes: false,
noWorkVisaQuotas: false,
simpleStartupVisa: false,
allFiltersChanged: function() {
this.notifyPropertyChange('allFilters');
}.observes('noEducationWorkVisa', 'warmClimate', 'ruleOfLaw', 'lowCrime', 'lowTaxes', 'noWorkVisaQuotas', 'simpleStartupVisa'),
doesMatch: function(country) {
var subj = function(type, keyName, desired) {
var value = country.get(keyName);
return utils.subjectiveWord(type, value) === desired;
};
var matches = function(name) {
switch (name) {
case 'noEducationWorkVisa':
var work = country.get('immigration.work');
return work.degreeReq === false;
case 'warmClimate':
return subj('climate', 'climate.low', 'very hot');
case 'ruleOfLaw':
return subj('corruption', 'ratings.corruption', 'very good');
case 'lowCrime':
return subj('crime', 'ratings.crime', 'very low');
case 'lowTaxes':
var sum = 100000;
var rate = utils.getRate(sum, 'USD', 'USD', country.get('rates'));
var percent = (rate / sum) * 100;
return percent < 20;
case 'noWorkVisaQuotas':
var work = country.get('immigration.work');
return work && !work.quota;
case 'simpleStartupVisa':
return ;
}
};
var filters = filterNames.map(function(name) {
var value = this.get(name);
return {
name: name, isEnabled: value,
doesMatch: value ? matches(name) : false
};
}, this);
var enabled = filters.filter(function(filter) {
return filter.isEnabled;
});
console.log('Test', country.name, enabled);
if (!enabled.length) return true;
return enabled.every(function(filter) {
return filter.doesMatch;
});
}
});
App.ChooseDestinyController = Ember.ArrayController.extend({
filterSet: function() {
return App.FilterSet.create();
}.property(),
results: function() {
var countries = this.get('model');
var filters = this.get('filterSet');
return countries.filter(function(country) {
return filters.doesMatch(country);
});
}.property('@each', 'filterSet.allFilters')
});
App.TaxRatingController = Ember.Controller.extend({
needs: ['application'],
queryParams: ['income', 'currencyCode'],
currencyCode: Ember.computed.alias('controllers.application.currencyCode'),
income: null,
currency: function() {
return symbols[this.get('currencyCode')];
}.property('currencyCode'),
results: function() {
var self = this;
return App.COUNTRIES.reduce(function(memo, item) {
if (item.get('hasStates')) {
return memo.concat(item.get('states'));
} else {
return memo.concat([item]);
}
}, []).map(function(countryOrState) {
var country, state;
if (countryOrState.get('isCountry')) {
country = countryOrState;
} else {
country = countryOrState.get('country');
state = countryOrState;
}
return App.CalculationEntry.create({
country: country,
state: state,
source: self,
incomeBinding: 'source.income',
currencyCodeBinding: 'source.currencyCode'
});
});
}.property(),
actions: {
setIncome: function(value) {
this.set('currencyCode', 'USD');
this.set('income', value);
}
}
});
App.ResultsController = Ember.ArrayController.extend({
sortProperties: ['taxAmount'],
needs: ['tax_rating'],
currencyCode: Ember.computed.alias('controllers.tax_rating.currencyCode'),
currency: Ember.computed.alias('controllers.tax_rating.currency')
});
App.DetailsController = Ember.ObjectController.extend({
needs: ['application'],
currencyCode: Ember.computed.alias('controllers.application.currencyCode'),
country: Ember.computed.alias('model'),
state: null,
countryOrState: function() {
return this.get('state') || this.get('country');
}.property('country', 'state')
});
<file_sep>App.Router.map(function() {
this.resource('tax-rating', { path: '/taxes' });
this.resource('ratings');
this.resource('choose-destiny');
this.resource('details', { path: '/c/:country_slug' });
this.resource('details_state', { path: '/c/:country_slug/:state_slug' });
});
App.RatingsRoute = Ember.Route.extend({
model: function() {
return App.COUNTRIES;
}
});
App.DetailsRoute = Ember.Route.extend({
model: function(params) {
return App.COUNTRIES.findBy('slug', params.country_slug);
}
});
App.ChooseDestinyRoute = Ember.Route.extend({
model: function() {
return App.COUNTRIES;
}
});
App.DetailsStateRoute = Ember.Route.extend({
controllerName: 'details',
model: function(params) {
var country = App.COUNTRIES.findBy('slug', params.country_slug);
var state = country.get('states').findBy('slug', params.state_slug);
return [country, state];
},
setupController: function(controller, model) {
controller.set('model', model[0]);
controller.set('state', model[1]);
},
renderTemplate: function() {
this.render('details');
}
});
<file_sep>var symbols = require('config').currencies.symbols;
var utils = require('utils');
App.SubjectiveBaseComponent = Ember.Component.extend({
tagName: 'b',
classNameBindings: ['descriptionClass'],
descriptionClass: function() {
return this.get('description').replace(/\s+/g, '-');
}.property('description')
});
App.SubjectiveClimateComponent = App.SubjectiveBaseComponent.extend({
layout: Ember.Handlebars.compile('{{description}}'),
climate: null,
avg: function() {
return (this.get('climate.high') + this.get('climate.low')) / 2;
}.property('climate.{high,low}'),
description: function() {
return utils.subjectiveWord('climate', this.get('avg'));
}.property('avg')
});
App.CountryRatingComponent = Ember.Component.extend({
name: null,
rating: null,
sources: {
crime: 'http://www.numbeo.com/crime/rankings_by_country.jsp',
prices: 'http://www.numbeo.com/cost-of-living/rankings_by_country.jsp',
business: 'http://www.doingbusiness.org/rankings',
corruption: 'http://cpi.transparency.org/cpi2013/results/'
},
labels: {
crime: 'Crime index',
prices: 'Consumer price index',
business: 'Doing business',
corruption: 'Corruption perception'
},
source: function() {
var name = this.get('name');
return this.get('sources')[name];
}.property('name', 'sources'),
label: function() {
var name = this.get('name');
return this.get('labels')[name];
}.property('name', 'labels')
});
App.TaxBandsComponent = Ember.Component.extend({
countryOrState: null,
currencyCode: null,
currency: function() {
return symbols[this.get('currencyCode')];
}.property('currencyCode'),
sourceCurrencyCode: Ember.computed.alias('countryOrState.code'),
rates: Ember.computed.alias('countryOrState.rates'),
isFlatTax: Ember.computed.alias('countryOrState.isFlatTax'),
flatTaxRate: Ember.computed.alias('countryOrState.flatTaxRate'),
bands: function() {
var rates = this.get('rates').slice();
var currency = this.get('currencyCode');
var sourceCurrency = this.get('sourceCurrencyCode');
rates.shift();
return rates.map(function(rate) {
var newMax = utils.toCurrency(rate.max, currency, sourceCurrency);
return { max: newMax, rate: rate.rate };
});
}.property('rates', 'currencyCode', 'sourceCurrencyCode')
});
App.SampleRatesComponent = Ember.Component.extend({
countryOrState: null,
currencyCode: null,
demoIncome: null,
currency: function() {
return symbols[this.get('currencyCode')];
}.property('currencyCode'),
sampleIncomes: function() {
var currency = this.get('currencyCode');
var incomes = [25000, 50000, 75000, 100000, 250000, 500000, 1000000];
return incomes.map(function(usd) {
return utils.toCurrency(usd, currency, 'USD');
});
}.property('currencyCode'),
samples: function() {
var country = this.get('countryOrState');
var currency = this.get('currencyCode');
return this.get('sampleIncomes').map(function(income) {
return App.TaxCalculator.calculateTotalWithStats(country, income, currency);
});
}.property('countryOrState', 'sampleIncomes'),
result: function() {
var income = this.get('demoIncome');
var country = this.get('countryOrState');
var currency = this.get('currencyCode');
return App.TaxCalculator.calculateTotalWithStats(country, income, currency);
}.property('countryOrState', 'demoIncome')
});
App.MoneyInputComponent = Ember.Component.extend({
currencyCode: null,
value: null,
placeholder: null,
autofocus: false,
debounce: null,
setFmt: function() {
this.updateMoney();
}.on('init'),
fmtValue: null,
updateMoney: function() {
this.set('fmtValue', accounting.formatNumber(this.get('value')));
}.observes('value'),
inputValueDidChange: function() {
this.set('fmtValue', accounting.formatNumber(this.get('fmtValue')));
var debounce = this.get('debounce');
if (debounce) {
Ember.run.debounce(this, this.updateValue, debounce);
} else {
this.updateValue();
}
}.observes('fmtValue'),
updateValue: function() {
this.set('value', accounting.unformat(this.get('fmtValue')));
}
});
App.CheckMarkComponent = Ember.Component.extend({
tagName: 'span',
value: null
});
App.BsPanelComponent = Ember.Component.extend({
classNames: ['panel panel-default']
});
App.VisaCardComponent = Ember.Component.extend({
visa: null,
title: null
});
App.SubjectiveRatingComponent = App.SubjectiveBaseComponent.extend({
layout: Ember.Handlebars.compile('{{#if rating}}{{description}} ({{numDesc}}){{else}}&emdash;{{/if}}'),
name: null, // rating name
rating: null, // rating value
isBusiness: Ember.computed.equal('name', 'business'),
isCorruption: Ember.computed.equal('name', 'corruption'),
numDesc: function() {
var num = this.get('rating');
if (this.get('isBusiness')) {
return '#' + num
} else if (this.get('isCorruption')) {
return num + ' / 100';
} else {
return num;
}
}.property('rating', 'isBusiness'),
description: function() {
return utils.subjectiveWord(this.get('name'), this.get('rating'));
}.property('name', 'rating')
});
App.TotalRatingComponent = App.SubjectiveBaseComponent.extend({
layout: Ember.Handlebars.compile('{{description}}'),
ratings: null, // rating value
description: function() {
return utils.subjectiveWord('total', this.get('ratings'));
}.property('name', 'rating')
});
| 4dd17944031eb6024e5eedc2793100860752df12 | [
"JavaScript"
] | 4 | JavaScript | paulmillr/mnp | e7b5b8f79f26d5d9ba111fd71863dfde07979a32 | 0348953711cb5a1f8dd2fbe2196f2137fd8622bf |
refs/heads/master | <file_sep>import { Component, TemplateRef, Inject } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { RequestOptions } from '@angular/http';
import { IBook } from './book';
import { Observable } from 'rxjs';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import { Router } from '@angular/router';
@Component({
selector: 'book-list',
templateUrl: './booklist.component.html'
})
export class BookListComponent {
public bookDetails: IBook[];
baseURL = "https://localhost:44383";
constructor(private http: HttpClient, @Inject('BASE_URL') baseUrl: string, private router: Router) {
http.get<IBook[]>(baseUrl + 'api/Book/Index')
.subscribe(result => {
this.bookDetails = result;
console.log(result);
}, error => console.error(error));
}
deleteBook(id: number){
console.log(id)
let headers = new HttpHeaders({
'Content-Type': 'application/json'
});
return this.http.post(this.baseURL + '/api/Book/DeleteBook/',id, { headers: headers }).
subscribe(data => {
this.router.navigate(['booklist']);
},
error => {
alert(error);
});
}
editBook(id: number) {
console.log(id);
localStorage.removeItem("editBookId");
localStorage.setItem("editBookId", id.toString());
this.router.navigate(['bookedit']);
}
private handleError(error: Response) {
console.error(error);
return Observable.throw(error.json() || 'Server error');
}
}
<file_sep>export class IBook {
id: number;
title: string;
author: string;
genre: string;
constructor(data) { (<any>Object).assign(this, data); }
}
<file_sep>import { Component, TemplateRef, Inject, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { IBook } from './book';
import { FormGroup, FormBuilder, Validators, ReactiveFormsModule } from '@angular/forms';
import { HttpHeaders, HttpRequest } from '@angular/common/http';
import { RequestOptions } from '@angular/http';
import { Router } from '@angular/router';
import { first } from "rxjs/operators";
@Component({
selector: 'book-edit',
templateUrl: './bookedit.component.html'
})
export class BookEditComponent implements OnInit {
public submitted: boolean;
book: IBook;
headers: any;
editForm: FormGroup;
baseURL = "https://localhost:44383";
constructor(private formBuilder: FormBuilder, private router: Router, private http: HttpClient) { }
ngOnInit() {
let bookId = localStorage.getItem("editBookId");
if (!bookId) {
alert("Invalid action.")
this.router.navigate(['booklist']);
return;
}
this.editForm = this.formBuilder.group({
id: [],
title: ['', Validators.required],
author: ['', Validators.required],
genre: ['', Validators.required]
});
console.log(bookId);
return this.http.get<IBook>(this.baseURL + '/api/Book/GetBook/' + bookId)
.subscribe(data => {
this.editForm.setValue(data);
console.log(data)
}, error => console.error(error));
}
onSubmit() {
let bookId = localStorage.getItem("editBookId");
console.log(this.editForm.value);
this.http.put(this.baseURL + '/api/Book/Edit/' + bookId, this.editForm.value).pipe(first())
.subscribe(
data => {
this.router.navigate(['booklist']);
},
error => {
alert(error);
});
//this.submitted = true;
//console.log(value, valid);
//let body = JSON.stringify(value);
//console.log(body);
//let header = {
// header: new HttpHeaders({
// 'Content-Type': 'application/json'
// })
//}
//return this.http.post(this.baseURL + '/api/Book/Edit', value, { headers : header }).
// subscribe(data => {
// this.router.navigate(['booklist']);
// },
// error => {
// alert(error);
// });
}
}
<file_sep>import { Component, TemplateRef, Inject, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { IBook } from './book';
import { FormGroup, FormBuilder, Validators, ReactiveFormsModule } from '@angular/forms';
import { HttpHeaders, HttpRequest } from '@angular/common/http';
import { RequestOptions } from '@angular/http';
import { Router } from '@angular/router';
@Component({
selector: 'bookcreate',
templateUrl: './bookcreate.component.html'
})
export class BookCreateComponent implements OnInit {
public bookForm: FormGroup;
public submitted: boolean;
baseURL = "https://localhost:44383";
constructor(private formBuilder: FormBuilder, private http: HttpClient, private router: Router) {
this._http = http;
}
ngOnInit() {
this.bookForm = this.formBuilder.group({
title: ['', Validators.required],
author: ['', Validators.required],
genre: ['', [Validators.required]]
});
}
_http: any;
onSubmit({ value, valid }: { value: IBook, valid: boolean }) {
this.submitted = true;
console.log(value, valid);
let body = JSON.stringify(value);
console.log(body);
const header = {
header: new HttpHeaders({
'Content-Type': 'application/json'
})
}
return this._http.post(this.baseURL + '/api/Book/Create', value, { headers: header }).
subscribe(data => {
this.router.navigate(['booklist']);
},
error => {
alert(error);
});
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Hosting;
using Microsoft.AspNetCore.Hosting;
using NHibernate;
using NHibernate.Cfg;
namespace NHibernateAngular
{
public class NHibernateSession
{
private readonly IHostingEnvironment _hostingEnvironment;
public NHibernateSession(IHostingEnvironment hostingEnvironment)
{
_hostingEnvironment = hostingEnvironment;
}
public static ISession OpenSession()
{
var configuration = new NHibernate.Cfg.Configuration();
var configurationPath = Path.Combine(@"C:\Users\prajapatis\source\repos\NHibernateAngular\NHibernateAngular\Models\hibernate.cfg.xml");
configuration.Configure(configurationPath);
var bookConfigurationFile = Path.Combine(@"C:\Users\prajapatis\source\repos\NHibernateAngular\NHibernateAngular\Mappings\Book.cfg.xml");
configuration.AddFile(bookConfigurationFile);
ISessionFactory sessionFactory = configuration.BuildSessionFactory();
return sessionFactory.OpenSession();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using NHibernateAngular.Domain;
using NHibernate;
using Microsoft.AspNetCore.Http;
using System.Web.Http;
namespace NHibernateAngular.Controllers
{
[Route("api/[controller]")]
public class BookController : ControllerBase
{
[HttpGet("[action]")]
public IEnumerable<Book> Index()
{
List<Book> books = new List<Book>();
using (NHibernate.ISession session = NHibernateSession.OpenSession()) // Open a session to conect to the database
{
using (ITransaction transaction = session.BeginTransaction())
{
books = session.Query<Book>().ToList(); // Querying to get all the books
transaction.Commit();
}
}
return books.AsEnumerable();
}
[HttpGet("[action]/{id}")]
public Book GetBook(int id)
{
Book book = new Book();
using (NHibernate.ISession session = NHibernateSession.OpenSession())
{
book = session.Query<Book>().Where(b => b.Id == id).FirstOrDefault();
}
return book;
}
[HttpPut("[action]/{id}")]
public void Edit([FromBody] Book book)
{
if (ModelState.IsValid)
{
using (NHibernate.ISession session = NHibernateSession.OpenSession())
{
using (ITransaction transaction = session.BeginTransaction())
{
session.SaveOrUpdate(book);
transaction.Commit();
}
}
}
}
[HttpPost("[action]")]
public void Create([FromBody] Book book)
{
if (ModelState.IsValid)
{
using (NHibernate.ISession session = NHibernateSession.OpenSession())
{
using (ITransaction transaction = session.BeginTransaction())
{
session.Save(book);
transaction.Commit();
}
}
}
}
[HttpPost("[action]")]
public void DeleteBook([FromBody] int? id)
{
if (id != null)
{
using (NHibernate.ISession session = NHibernateSession.OpenSession())
{
Book book = session.Get<Book>(id);
using (ITransaction trans = session.BeginTransaction())
{
session.Delete(book);
trans.Commit();
}
}
}
}
}
} | e7850acfe6d595c0b506336f1139974606778dce | [
"C#",
"TypeScript"
] | 6 | TypeScript | sp1805/NHibrenateAngularNetCore | 515bdd4453ede1cc437559f94666f4e35f935b35 | fe9075a1e2ce3fa35113c6dfe5ab9488556c620b |
refs/heads/master | <file_sep>import {ParseModel, ParseCollection} from '../parse';
var Message = ParseModel.extend({
});
var MessageCollection = ParseCollection.extend({
model: Message,
url: 'https://dietz-server.herokuapp.com/classes/ChatMessage?include=owner'
});
export {MessageCollection as default, Message};
<file_sep>var Backbone = require('backbone');
import {ParseModel} from '../parse';
var ParseFile = ParseModel.extend({
urlRoot: function(){
return 'https://dietz-server.herokuapp.com/files/' + this.get('name');
}
});
export default ParseFile;
<file_sep>import React, { Component } from 'react';
import {Switch, BrowserRouter as Router, Route} from 'react-router-dom';
import authRequired from '../components/Authentication';
import AuthContainer from './Auth';
import MessageContainer from './Messages';
class App extends Component {
render() {
return (
<Router>
<div className="App">
<Route path='/' exact component={AuthContainer} />
<Route path='/messages/' exact component={authRequired(MessageContainer)} />
</div>
</Router>
);
}
}
export default App;
<file_sep>import React from 'react';
function Card(props){
return (
<div className="card">
<CardBody>
<h4 className="card-title"><span className="lstick"></span>{props.title}</h4>
{props.children}
</CardBody>
</div>
)
}
function CardBody(props){
return (
<div className={props.className + " card-body"}>
{props.children}
</div>
);
}
export {Card as default, CardBody};
<file_sep>import parse, {ParseModel} from '../parse';
var $ = require('jquery');
var Backbone = require('backbone');
var User = ParseModel.extend({
urlRoot: 'https://dietz-server.herokuapp.com/users'
}, {
login: function(cridentials, callback){
var url = 'https://dietz-server.herokuapp.com/login?' + $.param(cridentials);
parse.initialize();
$.get(url).then(data => {
var newUser = new User(data);
User.store(newUser);
callback(newUser);
});
parse.deinitialize();
},
logout: function(callback){
var url = 'https://dietz-server.herokuapp.com/logout';
parse.initialize();
$.post(url).then(data => {
localStorage.removeItem('user');
callback();
});
parse.deinitialize();
},
signup: function(creds, callback){
var newUser = new User(creds);
return newUser.save().then(() => {
User.store(newUser);
callback(newUser);
});
// return newUser;
},
store: function(user){
localStorage.setItem('user', JSON.stringify(user.toJSON()));
},
current: function(){
var user = localStorage.getItem('user');
// if no user in local storage, bail
if(!user){
return false;
}
var currentUser = new User(JSON.parse(user));
// If we don't have a token, bail
if(!currentUser.get('sessionToken')){
return false;
}
return currentUser;
}
});
export default User;
<file_sep>import React from 'react';
import BaseLayout from '../layouts/Base';
import Card, {CardBody} from '../components/Card';
import User from '../models/user';
import MessageCollection, {Message} from '../models/message';
class MessageContainer extends React.Component{
constructor(props){
super(props);
this.state = {
messageCollection: new MessageCollection()
}
}
componentWillMount(){
let messageCollection = this.state.messageCollection;
messageCollection.fetch().then(() => {
this.setState({messageCollection: messageCollection});
});
}
addMessage = (messageData) => {
let message = new Message(messageData);
message.setPointer('owner', '_User', User.current().id);
let acl = {'*': {'read': true, 'write': false}};
acl[User.current().id] = {
"read": true,
"write": true,
};
message.set('ACL', acl);
let messageCollection = this.state.messageCollection;
messageCollection.create(message);
this.setState({messageCollection: messageCollection});
}
render(){
return (
<BaseLayout>
<Card title="Recent Messages">
<MessageList messageCollection={this.state.messageCollection} />
<CardBody className="t-b">
<MessageForm addMessage={this.addMessage} />
</CardBody>
</Card>
</BaseLayout>
)
}
}
function MessageList(props){
let user = User.current();
let listItems = props.messageCollection.map((message) => {
let ownerId = message.get('owner').objectId;
let messageClass = (ownerId == user.id ? 'my-message' : 'other-message');
return (
<li className={messageClass} key={message.cid}>
<strong>{message.get('owner').username}</strong>:
{message.get('body')}
</li>
);
});
// <li>
// <div class="chat-img"><img src="../assets/images/users/1.jpg" alt="user"></div>
// <div class="chat-content">
// <h5><NAME></h5>
// <div class="box bg-light-info">Lorem Ipsum is simply dummy text of the printing & type setting industry.</div>
// </div>
// <div class="chat-time">10:56 am</div>
// </li>
return (
<div className="chat-box">
<ul className="chat-list">
{listItems}
</ul>
</div>
);
}
class MessageForm extends React.Component{
constructor(props){
super(props);
this.state = {
'body': ''
};
}
_onChange = (e) => {
this.setState({body: e.target.value});
}
_onSubmit = (e) => {
e.preventDefault();
this.props.addMessage(this.state);
this.setState({body: ''});
}
render(){
// <div class="card-body b-t">
// <div class="row">
// <div class="col-8">
// <textarea placeholder="Type your message here" class="form-control b-0"></textarea>
// </div>
// <div class="col-4 text-right">
// <button type="button" class="btn btn-info btn-circle btn-lg"><i class="fa fa-paper-plane-o"></i> </button>
// </div>
// </div>
// </div>
return (
<form onSubmit={this._onSubmit}>
<input onChange={this._onChange} value={this.state.body} type="text" name="body" />
<button className="btn btn-primary" type="submit">Say It!</button>
</form>
)
}
}
export default MessageContainer;
<file_sep>import React from 'react';
import PropTypes from 'prop-types';
import BaseLayout from '../layouts/Base';
import User from '../models/user';
class AuthContainer extends React.Component{
login = (userData) => {
let creds = {
username: userData.email,
password: userData.<PASSWORD>
};
User.login(creds, (user)=>{
this.props.history.push('/messages/');
});
}
signup = (userData) => {
let creds = {
username: userData.email,
password: <PASSWORD>
};
User.signup(creds, (user)=>{
this.props.history.push('/messages/');
});
}
render(){
let signupDs = "Don't have an account? Signup here!"
return (
<BaseLayout>
<div className="row">
<div className="col-md-6">
<LoginForm formAction={this.login} title="Login" />
</div>
<div className="col-md-6">
<SignupForm formAction={this.signup} title="Signup" description={signupDs}/>
</div>
</div>
</BaseLayout>
)
}
}
class AuthForm extends React.Component{
constructor(props){
super(props);
this.state = {
email: '',
password: ''
};
}
_onChangeEmail = (e) => {
this.setState({'email': e.target.value});
}
_onChangePassword = (e) => {
this.setState({'password': e.target.value});
}
_onSubmit = (e) => {
e.preventDefault();
this.props.formAction(this.state);
this.setState({username: '', password: ''});
}
render(){
return (
<form onSubmit={this._onSubmit}>
{this.props.title ? <h2>{this.props.title}</h2> : null}
{this.props.description ? <p>{this.props.description}</p> : null}
<div className="form-group">
<label htmlFor="email">Email address</label>
<input onChange={this._onChangeEmail} value={this.state.email} type="email" className="form-control" id="email" placeholder="Email" />
</div>
<div className="form-group">
<label htmlFor="password">Password</label>
<input onChange={this._onChangePassword} value={this.state.password} type="password" className="form-control" id="password" placeholder="<PASSWORD>" />
</div>
<button type="submit" className="btn btn-default">Submit</button>
</form>
);
}
}
AuthForm.propTypes = {
'formAction': PropTypes.func.isRequired,
'title': PropTypes.string,
'description': PropTypes.string
};
class LoginForm extends AuthForm{
}
class SignupForm extends AuthForm{
}
export default AuthContainer;
| 20eb95e26625f8cd1b5e8ed9d9e226bbc05cdc18 | [
"JavaScript"
] | 7 | JavaScript | tiy-greenville-july-2017/11.4-react-review | ebf232dc1920d7966d91cfbb14a8a2bd7999d955 | 5273d5c41edfcecd62472112134bab1351fda2b2 |
refs/heads/master | <file_sep>//
// Mission.swift
// CryptoniteCev
//
// Created by alumnos on 09/03/2021.
// Copyright © 2021 user177257. All rights reserved.
//
import Foundation
import UIKit
class Mission{
private var _id : Int
private var _icon : UIImage
private var _description : String
private var _isFinished : Int
init(id:Int, icon:UIImage, description: String, isFinished:Int){
self._id = id
self._icon = icon
self._description = description
self._isFinished = isFinished
}
public var id: Int {
get {
return self._id;
}
set {
self._id = newValue
}
}
public var icon: UIImage {
get {
return self._icon;
}
set {
self._icon = newValue
}
}
public var description: String {
get {
return self._description;
}
set {
self._description = newValue
}
}
public var isFinished: Int {
get {
return self._isFinished;
}
set {
self._isFinished = newValue
}
}
}
<file_sep>//
// MainScreenExtension.swift
// CryptoniteCev
//
// Created by alumnos on 27/01/2021.
// Copyright © 2021 user177257. All rights reserved.
//
import UIKit
import SkeletonView
var images : [UIImage] = []
var imageSelected : UIImage?
//imagen que venga con el token
var myProfilePic = #imageLiteral(resourceName: "gamifiLogo")
var selectedCoin:String?
var roundingQuantity: Double = 100000
extension MainScreenController: UICollectionViewDelegateFlowLayout, UICollectionViewDataSource, UICollectionViewDelegate,SkeletonTableViewDataSource , UITableViewDelegate {
func collectionSkeletonView(_ skeletonView: UITableView, cellIdentifierForRowAt indexPath: IndexPath) -> ReusableCellIdentifier {
return "cellActivity"
}
//Devuelve la cantidad de items dependiendo del collection view
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if collectionView == storiesCollectionView {
return followings.count
} else if collectionView == coinCollectionView {
if coins.count>0{
return coins.count
}else{
return coinImages.count
}
} else {
return users.count
}
}
//Rellena labels e imagenes de los datos recibidos en las peticiones
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
//Rellena las imagenes de las stories
if collectionView == storiesCollectionView {
let cell = storiesCollectionView.dequeueReusableCell(withReuseIdentifier: "CellStories", for: indexPath) as! StoriesCell
if indexPath.row == 0 {
cell.storiesImageView?.image = myProfilePic
}else if followings.count > 1{
cell.storiesImageView?.image = followings[indexPath.row].profilePic
cell.storiesImageView.layer.cornerRadius = cell.storiesImageView.frame.height/2
}
cell.layer.cornerRadius = cell.frame.width/2
cell.layer.borderWidth = 3
cell.layer.borderColor = #colorLiteral(red: 0.262745098, green: 0.8509803922, blue: 0.7411764706, alpha: 1)
return cell
}
//Rellena labels e imagenes de las monedas
if collectionView == coinCollectionView{
let cell = coinCollectionView.dequeueReusableCell(withReuseIdentifier: "cellCoins", for: indexPath) as! CoinCellMainController
if coins.count>0{
cell.iconImageView?.image = Images.shared.coins[coins[indexPath.row].name]
if(coins[indexPath.row].name != "DogeCoin"){
cell.coinNameLabel?.text = coins[indexPath.row].name
}else{
cell.coinNameLabel?.text = "Doge"
}
cell.ammountLabel?.text = currencyFormatter(numberToFormat: coins[indexPath.row].price) + "$"
cell.percentageLabel?.text = currencyFormatterTwoDecimals(numberToFormat: coins[indexPath.row].change) + "%"
if(coins[indexPath.row].change < 0) {
cell.percentageLabel?.textColor = #colorLiteral(red: 0.9490196078, green: 0.2862745098, blue: 0.4509803922, alpha: 1)
}else {
cell.percentageLabel?.textColor = #colorLiteral(red: 0.262745098, green: 0.8509803922, blue: 0.7411764706, alpha: 1)
}
}else{
cell.iconImageView?.image = coinImages[indexPath.row]
if(coinNames[indexPath.row] != "DogeCoin"){
cell.coinNameLabel?.text = coinNames[indexPath.row]
}else{
cell.coinNameLabel?.text = "Doge"
}
}
cell.layer.cornerRadius = cell.frame.height/8
return cell
}
//Rellena labels e imagenes de los usuarios
else {
let cellUser = usersCollectionView.dequeueReusableCell(withReuseIdentifier: "cellUsers", for: indexPath) as! UserCellMainController
if users.count > 0{
cellUser.profilePicIV.image = users[indexPath.row].profilePic
cellUser.profilePicIV.layer.cornerRadius = cellUser.profilePicIV.frame.height/2
cellUser.usernameL.text = users[indexPath.row].username
cellUser.percentageUserL.text = "Lvl. " + String(getCurrentLvl(experience: users[indexPath.row].experience))
if(cellUser.percentageUserL.text?.first == "-") {
cellUser.percentageUserL.textColor = #colorLiteral(red: 0.9490196078, green: 0.2862745098, blue: 0.4509803922, alpha: 1)
}else {
cellUser.percentageUserL.textColor = #colorLiteral(red: 0.262745098, green: 0.8509803922, blue: 0.7411764706, alpha: 1)
}
cellUser.layer.cornerRadius = cellUser.frame.height/8
}
return cellUser
}
}
//segues que te conduciran al item especifico
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if coins.count>0 && collectionView == coinCollectionView{
let selectedItem = coins[indexPath.row].name
performSegue(withIdentifier: "coinViewID", sender: selectedItem)
}else if users.count>0 && collectionView == usersCollectionView {
let selectedItem = users[indexPath.row].username
performSegue(withIdentifier: "stories", sender: selectedItem)
} else if followings.count>0 && collectionView == storiesCollectionView {
let cell = storiesCollectionView.cellForItem(at: indexPath)
cell?.layer.borderColor = #colorLiteral(red: 0.2549019754, green: 0.2745098174, blue: 0.3019607961, alpha: 1)
if indexPath.row == 0 {
performSegue(withIdentifier: "gaming", sender: (Any).self)
}else {
var selectedItem:String
if isConnected && !attemptsMaxed{
selectedItem = followings[indexPath.row].username
}else{
selectedItem = "N/A"
}
performSegue(withIdentifier: "stories", sender: selectedItem)
}
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return trades.count
}
//Rellena los labels e imagenes de los tradeos
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cellActivity") as! ActivityRow
if(trades.count>0){
cell.profilePicActivityIV.image = Images.shared.users[trades[indexPath.row].profilePic]
cell.profilePicActivityIV.layer.cornerRadius = cell.profilePicActivityIV.frame.height/2
cell.usernameActivityL.text = trades[indexPath.row].username
roundingQuantity = setRounding(symbol: trades[indexPath.row].coinFrom)
cell.coinSellingL.text = currencyFormatter(numberToFormat: (round(roundingQuantity * trades[indexPath.row].quantity)/roundingQuantity))
cell.iconSellingIV.image = Images.shared.coins[trades[indexPath.row].coinFrom]
roundingQuantity = setRounding(symbol: trades[indexPath.row].coinTo)
cell.coinBuyingL.text = currencyFormatter(numberToFormat: (round(roundingQuantity * trades[indexPath.row].converted)/roundingQuantity))
cell.iconBuyingIV.image = Images.shared.coins[trades[indexPath.row].coinTo]
}
return cell
}
//Devuelve el nivel actual en base a la experiencia
func getCurrentLvl(experience:Double)->Int{
var n = 0
var level:Int = 0
while true {
if experience < neededExperience(level: Double(n)) {
level = n
return level
}
n += 1
}
}
//Experiencia necesaria para subir de nivel
func neededExperience(level: Double) -> Double {
if level != 0 {
return neededExperience(level: level-1) + level * self.experiencePerMission
}
return 0
}
//envia datos en el segue
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if (segue.identifier == Identifiers.shared.stories) {
let storiesController = segue.destination as! StoriesController
storiesController.onDoneBlock = {
self.fillFollowings()
}
if isConnected{
storiesController.username = sender as? String
}
}else if(segue.identifier == "coinViewID"){
let coinController = segue.destination as! CoinViewController
coinController.coinName = sender as? String
coinController.onDoneBlock = { result in
self.tabBarController?.selectedIndex = 0
let tradeVC = self.tabBarController!.viewControllers![0] as! TradingController
tradeVC.coinForSC = result
}
}else if(segue.identifier == "gaming"){
let gamingController = segue.destination as! GamificationController
gamingController.mainClass = self
gamingController.onDoneBlock = {
self.tabBarController?.selectedIndex = 2
}
gamingController.didLogout = {
self.navigationController?.popToRootViewController(animated: true)
}
}
}
}
<file_sep>import Foundation
import Charts
class Colors{
let graph:[String:NSUIColor]
private init() {
//colores de la grafica dependiendo de la moneda
self.graph = [
"ETH":NSUIColor(red: 98/255.0, green: 126/255.0, blue: 224/255.0, alpha: 0.95),
"BTC":NSUIColor(red: 242/255.0, green: 127/255.0, blue: 27/255.0, alpha: 0.95),
"DOGE":NSUIColor(red: 244/255.0, green: 245/255.0, blue: 121/255.0, alpha: 0.96),
"LTC":NSUIColor(red: 192/255.0, green: 192/255.0, blue: 192/255.0, alpha: 0.75),
"USDT":NSUIColor(red: 80/255.0, green: 175/255.0, blue: 149/255.0, alpha: 0.69)
]
}
static let shared = Colors()
}
<file_sep>
import Foundation
import UIKit
/**
Comprueba que el email sea correcto en función de ciertas validaciones del string del textfield, devielve true o false
*/
public func checkEmail(textFieldEmail:UITextField/*, errorLabel:UILabel*/) -> Bool
{
do
{
try textFieldEmail.validatedText(.email)
//errorLabel.isHidden = true
}
catch let error
{
let validationError = error as! ValidationError
//errorLabel.isHidden = false
//errorLabel.text = validationError.localizedDescription
return false
}
return true
}
/**
Comprueba que el password textfield no este vacio, devielve true o false
En caso de false hace animación en textfield
*/
public func checkPassword(textFieldPass:UITextField/*, errorLabel:UILabel*/) -> Bool
{
do
{
try textFieldPass.validatedText(.password)
//errorLabel.isHidden = true
}
catch let error
{
let validationError = error as! ValidationError
//errorLabel.isHidden = false
//errorLabel.textColor = #colorLiteral(red: 0.9490196078, green: 0.2862745098, blue: 0.4509803922, alpha: 1)
//errorLabel.text = validationError.localizedDescription
return false
}
return true
}
/**
Comprueba que el username textfield no este vacio, devielve true o false
En caso de false hace animación en textfield
*/
public func checkUsername(textFieldUsername:UITextField/*, errorLabel:UILabel*/) -> Bool
{
do
{
try textFieldUsername.validatedText(.username)
//errorLabel.isHidden = true
}
catch let error
{
let validationError = error as! ValidationError
//errorLabel.isHidden = false
//errorLabel.text = validationError.localizedDescription
return false
}
return true
}
/**
Comprueba que el name textfield no este vacio, devielve true o false
En caso de false hace animación en textfield
*/
public func checkName(textFieldName:UITextField/*, errorLabel:UILabel*/) -> Bool
{
do
{
try textFieldName.validatedText(.name)
//errorLabel.isHidden = true
}
catch let error
{
let validationError = error as! ValidationError
//errorLabel.isHidden = false
//errorLabel.text = validationError.localizedDescription
return false
}
return true
}
<file_sep>
import Foundation;
import UIKit;
class Wallet {
private var _coin:String
private var _symbol:String
private var _quantity:Double
private var _inDollars:Double
init(coin:String, symbol:String, quantity:Double, inDollars:Double){
self._coin = coin
self._symbol = symbol
self._quantity = quantity
self._inDollars = inDollars
}
public var coin: String {
get {
return self._coin;
}
set {
self._coin = newValue
}
}
public var symbol: String {
get {
return self._symbol;
}
set {
self._symbol = newValue
}
}
public var quantity: Double {
get {
return self._quantity;
}
set {
self._quantity = newValue
}
}
public var inDollars: Double {
get {
return self._inDollars;
}
set {
self._inDollars = newValue
}
}
}
<file_sep>
import Foundation
/**
Funcion que formateará número double y lo devolverá en forma de string
*/
func currencyFormatter(numberToFormat: Double) -> String {
let currencyFormatter = NumberFormatter()
currencyFormatter.usesGroupingSeparator = true
currencyFormatter.numberStyle = .currency
currencyFormatter.locale = Locale.current
currencyFormatter.currencySymbol = ""
currencyFormatter.maximumFractionDigits = 5
return currencyFormatter.string(from: NSNumber(value: numberToFormat))!
}
/**
Funcion que formateará número double y lo devolverá en forma de string con solo 2 decimales
*/
func currencyFormatterTwoDecimals(numberToFormat: Double) -> String {
let currencyFormatter = NumberFormatter()
currencyFormatter.usesGroupingSeparator = true
currencyFormatter.numberStyle = .currency
currencyFormatter.locale = Locale.current
currencyFormatter.currencySymbol = ""
currencyFormatter.maximumFractionDigits = 2
return currencyFormatter.string(from: NSNumber(value: numberToFormat))!
}
/**
Funcion que decidirá el tipo de redondeo según la moneda
*/
func setRounding(symbol:String) -> Double {
let roundingPair = ["DogeCoin", "Tether", "DOGE", "USDT"]
if(roundingPair.contains(symbol)){
return 100
} else {
return 100000
}
}
/**
Funcion que formateará número float y lo devolverá en forma de string
*/
func currencyFormatterFloat(numberToFormat: Float, decimalsQuantity:Int ) -> String {
let currencyFormatter = NumberFormatter()
currencyFormatter.usesGroupingSeparator = true
currencyFormatter.numberStyle = .currency
currencyFormatter.locale = Locale.current
currencyFormatter.currencySymbol = ""
currencyFormatter.maximumFractionDigits = decimalsQuantity
return currencyFormatter.string(from: NSNumber(value: numberToFormat))!
}
<file_sep>import Foundation
//Tipos de validación
enum ValidatorType
{
case email
case name
case password
case username
}
//tipos de error
enum ValidationError: Error, LocalizedError
{
case invalidUserName
case invalidEmail
case invalidPassword
case invalidName
//Errores concretos
var localizedDescription: String
{
let userMessages = UserMessages.shared
switch self
{
case .invalidEmail:
return userMessages.invalidEmail
case .invalidUserName:
return userMessages.invalidUsername
case .invalidPassword:
return userMessages.invalidPass
case .invalidName:
return userMessages.invalidName
}
}
}
<file_sep>//
// CoinCell.swift
// CryptoniteCev
//
// Created by user177260 on 1/27/21.
// Copyright © 2021 user177257. All rights reserved.
//
import UIKit
protocol CoinCellDelegate: class {
// Funcion delegado que tendrá la refencia de la instancia `UICollectionViewCell`
func collectionViewCell(_ cell: UICollectionViewCell, buttonTapped: UIButton)
}
class CoinCell: UICollectionViewCell {
static var index = 0
var isLoaded = false
let coinCardButton: UIButton = {
let coinCardButton = UIButton()
//Estética del boton
coinCardButton.frame = CGRect(x: 160, y: 100, width: 50, height: 50)
coinCardButton.translatesAutoresizingMaskIntoConstraints = false
coinCardButton.clipsToBounds = true
coinCardButton.layer.cornerRadius = 5
coinCardButton.setImage(images[CoinCell.index], for: .normal)
coinCardButton.imageView?.contentMode = .scaleAspectFill
return coinCardButton
}()
override init(frame: CGRect) {
super.init(frame: .zero)
//estética del view
contentView.addSubview(coinCardButton)
coinCardButton.topAnchor.constraint(equalTo: contentView.topAnchor).isActive = true
coinCardButton.leftAnchor.constraint(equalTo: contentView.leftAnchor).isActive = true
coinCardButton.rightAnchor.constraint(equalTo: contentView.rightAnchor).isActive = true
coinCardButton.bottomAnchor.constraint(equalTo: contentView.bottomAnchor).isActive = true
CoinCell.index += 1
coinCardButton.addTarget(self, action: #selector(thumbsUpButtonPressed), for: .touchUpInside)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
@objc func thumbsUpButtonPressed(_ sender: UIButton){
sender.layer.borderColor = #colorLiteral(red: 0.2549019754, green: 0.2745098174, blue: 0.3019607961, alpha: 1)
}
}
<file_sep>
import Foundation
import UIKit
class Images{
let coins:[String:UIImage]
let users:[UIImage]
/**
Arrays de imagenes
*/
private init() {
self.coins = ["Bitcoin":#imageLiteral(resourceName: "Bitcoin"), "Ethereum": #imageLiteral(resourceName: "eth"), "Litecoin": #imageLiteral(resourceName: "LITE"), "DogeCoin":#imageLiteral(resourceName: "doge"), "Tether": #imageLiteral(resourceName: "tether")]
self.users = [#imageLiteral(resourceName: "user1"), #imageLiteral(resourceName: "user2"), #imageLiteral(resourceName: "user3"), #imageLiteral(resourceName: "user4"), #imageLiteral(resourceName: "user5"), #imageLiteral(resourceName: "user6"), #imageLiteral(resourceName: "user7"), #imageLiteral(resourceName: "user8"), #imageLiteral(resourceName: "user9"), #imageLiteral(resourceName: "user10"), #imageLiteral(resourceName: "user11"), #imageLiteral(resourceName: "user12"), #imageLiteral(resourceName: "user13"), #imageLiteral(resourceName: "user14"), #imageLiteral(resourceName: "user15")]
}
static let shared = Images()
}
<file_sep>
import Foundation;
import UIKit;
class Trade {
private let _coin:String
private let _date:String
private let _quantity:Double
private let _price:Double
private let _isSell:Int
init(coin:String, date: String, quantity:Double, price:Double, isSell:Int){
self._coin = coin
self._date = date
self._quantity = quantity
self._price = price
self._isSell = isSell
}
public var coin: String {
get {
return self._coin;
}
}
public var date: String {
get {
return self._date;
}
}
public var quantity: Double {
get {
return self._quantity;
}
}
public var price: Double {
get {
return self._price;
}
}
public var isSell: Int {
get {
return self._isSell;
}
}
}
<file_sep>import Foundation
import UIKit
class TradesRow: UITableViewCell {
//Referencias de outlets
@IBOutlet weak var coinLabel: UILabel!
@IBOutlet weak var buyOrSellImage: UIImageView!
@IBOutlet weak var tradeDateLabel: UILabel!
@IBOutlet weak var amountLabel: UILabel!
@IBOutlet weak var priceLabel: UILabel!
}
<file_sep>//
// ApiBodyNames.swift
// CryptoniteCev
//
// Created by <NAME> on 28/2/21.
// Copyright © 2021 user177257. All rights reserved.
//
import Foundation
class ApiBodyNames {
private init() {}
static let shared = ApiBodyNames()
//nombres pasados por el key en los parametros que recibira la api
let email = "email"
let username = "username"
let password = "<PASSWORD>"
let newPassword = "<PASSWORD>"
let apiToken = "Authorization"
}
<file_sep>import UIKit
import Charts
class LineChart: UIViewController, ChartViewDelegate{
public func impirmirGrafica(lineChart: LineChartView, screen: UIView, values:[ChartDataEntry], coinSymbol:String){
lineChart.frame = CGRect(
x: 0,y: 0,
width: screen.frame.width,
height: screen.frame.height
)
//estetica del linechart
screen.addSubview(lineChart)
lineChart.topAnchor.constraint(equalTo: screen.topAnchor, constant: screen.frame.height).isActive = true
lineChart.leadingAnchor.constraint(equalTo: screen.leadingAnchor, constant: screen.frame.width).isActive = true
lineChart.trailingAnchor.constraint(equalTo: screen.trailingAnchor, constant: -screen.frame.width).isActive = true
lineChart.heightAnchor.constraint(equalToConstant: screen.frame.height).isActive = true
let set = LineChartDataSet(entries: values)
set.drawValuesEnabled = false
set.drawCirclesEnabled = false
set.colors = [Colors.shared.graph[coinSymbol]!]
set.highlightColor = #colorLiteral(red: 0.262745098, green: 0.8509803922, blue: 0.7411764706, alpha: 1)
//quita las lineas del grid
lineChart.rightAxis.drawAxisLineEnabled = false
lineChart.rightAxis.drawGridLinesEnabled = false
lineChart.leftAxis.drawGridLinesEnabled = false
lineChart.xAxis.drawGridLinesEnabled = false
//quita los labels
lineChart.xAxis.labelPosition = XAxis.LabelPosition.bottom
lineChart.rightAxis.drawLabelsEnabled = false
lineChart.legend.enabled = false
//crea el linechart con la estructura
let data = LineChartData(dataSet: set)
//linechart recoge los datos que mostrará
lineChart.data = data
}
}
<file_sep>
import UIKit
import Charts
import SkeletonView
class WalletViewController: UIViewController, SkeletonTableViewDataSource, UITableViewDelegate,
ChartViewDelegate
{
@IBOutlet weak var container: UIView!
var balance:Double = 0
var coinsQuantities:[CoinsQuantities] = []
var percentages:[String:Double] = [:]
@IBOutlet weak var totalCash: UILabel!
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var porgress: UIProgressView!
var graph = PieChart()
var pieChart = PieChartView()
var roundingQuantity: Double = 100000
let anim = SkeletonableAnim()
/**
Al iniciarse el view crea el gesto easter egg, coloca la estetica del tableview e inicia el placeholder
*/
override func viewDidLoad() {
super.viewDidLoad()
let swipeRight = UISwipeGestureRecognizer(target: self, action: #selector(respondToSwipeGesture))
swipeRight.direction = .right
swipeRight.numberOfTouchesRequired = 2
self.view.addGestureRecognizer(swipeRight)
pieChart.delegate = self
tableView.delegate = self
tableView.dataSource = self
pieChart.drawEntryLabelsEnabled = false
tableView.rowHeight = 68
tableView.estimatedRowHeight = 68
anim.placeholder(view: totalCash)
}
/**
Apaga el nav controller, comprueba mission de checkear wallet, reinicia el balance, comprueba los wallets para que en caso de que esten vacios coloca el placeholder y despues recoge los wallets
*/
override func viewDidAppear(_ animated: Bool) {
navigationController?.setNavigationBarHidden(true, animated: true)
isMissionFinished(parameters: ["id":"14"])
balance = 0
if(coinsQuantities.count == 0){
anim.placeholder(view: tableView)
}
coinsQuantities = []
getWallets()
}
//petición que recoge los wallets del user
func getWallets(){
if isConnected {
if (UserDefaults.standard.string(forKey: Identifiers.shared.auth) != nil) {
let request = Service.shared.getWallets()
request.responseJSON { (response) in
if let body = response.value as? [String:Any] {
if(response.response?.statusCode == StatusCodes.shared.OK){
attemptsMaxed = false
if let data = body["data"] as? [String:Any]{
let wallets = data["Wallets"] as! [[String:Any]]
let cash = data["Cash"]
for i in 0..<wallets.count {
self.coinsQuantities.append(CoinsQuantities(name: (wallets[i]["Name"] as? String)!, symbol: (wallets[i]["Symbol"]! as? String)!, quantity: (wallets[i]["Quantity"] as? Double)!, inDollars: (wallets[i]["inDollars"] as? Double)!))
}
self.balance = cash as! Double
self.totalCash.text = currencyFormatter(numberToFormat: (round(100*(cash as? Double)!)/100)) + "$"
self.percentages = self.getPercentages(myWallets: self.coinsQuantities)
self.anim.hidePlaceholder(view: self.totalCash)
self.anim.hidePlaceholder(view: self.tableView)
self.viewDidLayoutSubviews()
}else{
if !unknownBanner.isDisplaying{
unknownBanner.show()
}
}
self.tableView.reloadData()
}else{
attemptsMaxed = true
if !unknownBanner.isDisplaying{
unknownBanner.show()
}
}
}
}
}
}
}
//Calcula los porcentages que apareceran en el piechart en base a los wallets del user
func getPercentages(myWallets:[CoinsQuantities]) -> [String:Double]{
var values:[String:Double] = [:];
var percentage:Double = 0
for i in 0..<myWallets.count {
if(myWallets[i].inDollars > 0){
percentage = (myWallets[i].inDollars * 100) / balance;
if(percentage > 2){
values[myWallets[i].symbol] = percentage
}
}
}
return values;
}
/**
cantidad de items en tableview
*/
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.coinsQuantities.count
}
/**
Coloca la información en los labels e imageviews que se recibe de la peticion de wallets
*/
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: Identifiers.shared.coinID) as! CoinRowWalletController
if coinsQuantities.count>0{
cell.coin.text = coinsQuantities[indexPath.row].name
cell.symbol.text = coinsQuantities[indexPath.row].symbol
cell.icon.image = Images.shared.coins[coinsQuantities[indexPath.row].name]
roundingQuantity = setRounding(symbol: "Tether")
cell.price.text = currencyFormatter(numberToFormat: (round(roundingQuantity*coinsQuantities[indexPath.row].inDollars)/roundingQuantity)) + "$"
roundingQuantity = setRounding(symbol: coinsQuantities[indexPath.row].symbol)
let quantity = currencyFormatter(numberToFormat: (round(roundingQuantity * (coinsQuantities[indexPath.row].quantity)) / roundingQuantity))
cell.quantity.text = quantity + " " + coinsQuantities[indexPath.row].symbol
}
return cell
}
//imprime piechart
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
graph.impirmirGrafica(pieChart: pieChart, screen: container, percentages: percentages)
}
func collectionSkeletonView(_ skeletonView: UITableView, cellIdentifierForRowAt indexPath: IndexPath) -> ReusableCellIdentifier {
return Identifiers.shared.coinID
}
//Easter egg que muestra banner al mover el pestaña con dos dedos
@objc func respondToSwipeGesture(gesture: UIGestureRecognizer) {
Banners.shared.creatorsBanner()
}
}
<file_sep>
import Foundation;
import UIKit;
class User : Encodable, Decodable{
private var _username:String
private var _email:String
private var _name:String
private var _profilePic:Int
private var _password:String
enum CodingKeys:String, CodingKey {
case _name = "name"
case _username = "username"
case _email = "email"
case _password = "<PASSWORD>"
case _profilePic = "profile_pic"
}
init(username:String, email:String, name:String, password:String, profilePic:Int){
self._username = username
self._email = email
self._name = name
self._password = <PASSWORD>
self._profilePic = profilePic
}
public var name: String {
get {
return self._name;
}
set {
self._name = newValue
}
}
public var username: String {
get {
return self._username;
}
}
public var email: String {
get {
return self._email;
}
}
public var profilePic: Int {
get {
return self._profilePic;
}
set {
self._profilePic = newValue
}
}
}
<file_sep>
import Foundation
import UIKit
class StoriesCell: UICollectionViewCell {
//Referencias de outlets
@IBOutlet weak var storiesImageView: UIImageView!
}
<file_sep>import Foundation
extension String
{
// MARK:- Properties
//comprueba email valido
var isValidEmail: Bool
{
let emailFormat = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}"
let emailPredicate = NSPredicate(format:"SELF MATCHES %@", emailFormat)
return emailPredicate.evaluate(with: self)
}
// MARK:- Methods
//llama a la validación en concreto dependiendo del param recibido
func validatedText(_ validationType: ValidatorType) throws
{
switch validationType
{
case .username:
try validateUsername()
case .email:
try validateEmail()
case .password:
try validatePassword()
case .name:
try validateName()
}
}
// MARK:- Private Methods
//si username vacio devuelve error
private func validateUsername() throws
{
if isEmpty
{
throw ValidationError.invalidUserName
}
}
//si email erróneo devuelve error
private func validateEmail() throws
{
if !isValidEmail
{
throw ValidationError.invalidEmail
}
}
//si pass vacio devuelve error
private func validatePassword() throws
{
if isEmpty
{
throw ValidationError.invalidPassword
}
}
//si name vacio devuelve error
private func validateName() throws
{
if isEmpty
{
throw ValidationError.invalidPassword
}
}
}
<file_sep>//
// Banners.swift
// CryptoniteCev
//
// Created by user177260 on 3/10/21.
// Copyright © 2021 user177257. All rights reserved.
//
import Foundation
import UIKit
import NotificationBannerSwift
class Banners{
static let shared = Banners()
private init(){
}
private var normalDuration : TimeInterval = 1
private var longDuration : TimeInterval = 2
private var normalHeight : CGFloat = 110
private var smallHeight : CGFloat = 80
//Banner de subir de nivel
func levelUpBanner(title: String){
let leftView = UIImageView(image: #imageLiteral(resourceName: "logoNoText"))
let banner = NotificationBanner(title: title, leftView: leftView, style: .info)
banner.haptic = .heavy
banner.backgroundColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
banner.bannerHeight = self.normalHeight
banner.titleLabel?.textColor = #colorLiteral(red: 0.07058823529, green: 0.1215686275, blue: 0.2078431373, alpha: 1)
banner.duration = self.longDuration
banner.show()
}
//Banner de mostrar error
func errorBanner(title: String, subtitle: String){
let leftView = UIImageView(image: #imageLiteral(resourceName: "error"))
let banner = NotificationBanner(title: title, subtitle: subtitle,leftView: leftView, style: .danger)
banner.haptic = .heavy
banner.bannerHeight = self.normalHeight
banner.duration = self.longDuration
banner.show()
}
//Banner de error desconocido, normalmente too many attempts
func unknownErrorBanner() -> NotificationBanner{
let leftView = UIImageView(image: #imageLiteral(resourceName: "error"))
let banner = NotificationBanner(title: "An unknown error is ocurring right now", subtitle: "Please do not touch your phone or it will autodestroy",leftView: leftView, style: .danger)
banner.haptic = .heavy
banner.bannerHeight = self.normalHeight
banner.duration = self.longDuration
return banner
}
//Banner de que ha salido todo bien
func successBanner(title: String, subtitle: String){
let banner = NotificationBanner(title: title, subtitle: subtitle, style: .success)
banner.haptic = .heavy
banner.bannerHeight = self.normalHeight
banner.duration = self.normalDuration
banner.backgroundColor = #colorLiteral(red: 0.262745098, green: 0.8509803922, blue: 0.7411764706, alpha: 1)
banner.applyStyling(cornerRadius: .none, titleFont: .none, titleColor: #colorLiteral(red: 0.2, green: 0.2235294118, blue: 0.2784313725, alpha: 1), titleTextAlign: .center, subtitleFont: .none, subtitleColor: #colorLiteral(red: 0.2, green: 0.2235294118, blue: 0.2784313725, alpha: 1), subtitleTextAlign: .center)
banner.show()
}
//Banner que se mostrara al completar una mision
func missionCompletedBanner(view: UIView) {
let leftView = view
let banner = NotificationBanner(title: "Mission completed, go claim your rewards", leftView: leftView, style: .info)
banner.haptic = .heavy
banner.backgroundColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
banner.bannerHeight = self.normalHeight
banner.titleLabel?.textColor = #colorLiteral(red: 0.07058823529, green: 0.1215686275, blue: 0.2078431373, alpha: 1)
banner.duration = self.longDuration
banner.show()
}
//Banner de no conexion
func noConnectionBanner() -> StatusBarNotificationBanner{
let banner = StatusBarNotificationBanner(title: "No Internet Connection", style: .danger)
banner.autoDismiss = false
banner.bannerHeight = 80
return banner
}
//Banner easter egg que se mostrará en wallet
func creatorsBanner(){
let leftView = UIImageView(image: #imageLiteral(resourceName: "logoNoText"))
let banner = NotificationBanner(title: "Created by Marxtodon, Cyrexx, <NAME> Sharkteeth", leftView: leftView, style: .info)
banner.haptic = .heavy
banner.dismissOnTap = false
banner.backgroundColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
banner.bannerHeight = self.normalHeight
banner.titleLabel?.textColor = #colorLiteral(red: 0.07058823529, green: 0.1215686275, blue: 0.2078431373, alpha: 1)
banner.duration = self.longDuration
banner.show()
}
}
<file_sep>//
// MissionRequest.swift
// CryptoniteCev
//
// Created by <NAME> on 14/3/21.
// Copyright © 2021 user177257. All rights reserved.
//
import Foundation
import Lottie
func isMissionFinished(parameters:[String:String]){
//comprueba si una mission la posee el usuario y en caso de poseerla la pondrá como acabada
if isConnected {
if (UserDefaults.standard.string(forKey: Identifiers.shared.auth) != nil) {
let request = Service.shared.updateMission(params: parameters)
request.responseJSON { (response) in
if(response.response?.statusCode == StatusCodes.shared.OK){
Banners.shared.missionCompletedBanner(view: lottieAnim())
}
}
}
}
}
//animacion de el regalo
func lottieAnim() -> UIView {
var animationView: AnimationView?
animationView = .init(name: "gift")
let view = UIView()
view.frame = CGRect(x: 0, y: 0, width: 50, height: 50)
animationView!.frame = view.bounds
animationView!.loopMode = .loop
animationView!.animationSpeed = 0.5
view.addSubview(animationView!)
animationView?.play()
return view
}
<file_sep>import Foundation
import CoreGraphics
open class PieChartColors: NSObject
{
@objc open class func currencies () -> [NSUIColor]
{
return [
NSUIColor(red: 242/255.0, green: 127/255.0, blue: 27/255.0, alpha: 0.95),
NSUIColor(red: 148/255.0, green: 212/255.0, blue: 212/255.0, alpha: 1.0),
NSUIColor(red: 136/255.0, green: 180/255.0, blue: 187/255.0, alpha: 1.0),
NSUIColor(red: 118/255.0, green: 174/255.0, blue: 175/255.0, alpha: 1.0),
NSUIColor(red: 42/255.0, green: 109/255.0, blue: 130/255.0, alpha: 1.0)
]
}
}
<file_sep>
import Foundation;
import UIKit;
class TradesProfile : Decodable, Encodable{
private var _coinFrom:String
private var _coinTo:String
private var _coinFromSymbol:String
private var _coinToSymbol:String
private var _quantity:Double
private var _converted:Double
init(coinFrom:String, coinTo:String, coinFromSymbol:String, coinToSymbol:String ,quantity:Double, converted:Double){
self._coinFrom = coinFrom
self._coinTo = coinTo
self._coinFromSymbol = coinFromSymbol
self._coinToSymbol = coinToSymbol
self._quantity = quantity
self._converted = converted
}
public var coinFrom: String {
get {
return self._coinFrom;
}
set {
self._coinFrom = newValue
}
}
public var coinTo: String {
get {
return self._coinTo;
}
set {
self._coinTo = newValue
}
}
public var coinFromSymbol: String {
get {
return self._coinFromSymbol;
}
set {
self._coinFromSymbol = newValue
}
}
public var coinToSymbol: String {
get {
return self._coinToSymbol;
}
set {
self._coinToSymbol = newValue
}
}
public var quantity: Double {
get {
return self._quantity;
}
set {
self._quantity = newValue
}
}
public var converted: Double {
get {
return self._converted;
}
set {
self._converted = newValue
}
}
}
<file_sep>//
// OtherUserCell.swift
// CryptoniteCev
//
// Created by user177257 on 3/1/21.
// Copyright © 2021 user177257. All rights reserved.
//
import UIKit
class OtherUserCell: UITableViewCell{
//Referencias de outlets
@IBOutlet weak var profile: UIImageView!
@IBOutlet weak var username: UILabel!
@IBOutlet weak var quantity: UILabel!
@IBOutlet weak var converted: UILabel!
@IBOutlet weak var symbol_from: UIImageView!
@IBOutlet weak var symbol_to: UIImageView!
}
<file_sep>//
// StatusCodes.swift
// Agenda
//
// Created by alumnos on 05/02/2021.
// Copyright © 2021 <NAME>. All rights reserved.
//
import Foundation
class StatusCodes {
static let shared = StatusCodes()
private init(){}
//tipos de status codes
let OK = 200
let created = 201
}
<file_sep>
import UIKit
import Charts
class CoinViewController: UIViewController, ChartViewDelegate {
@IBOutlet weak var containerView: UIView!
@IBOutlet weak var tradeButton: UIButton!
@IBOutlet weak var coinIconIV: UIImageView!
@IBOutlet weak var aboutTitleLabel: UILabel!
@IBOutlet weak var aboutCoinLabel: UILabel!
@IBOutlet weak var currencyNameL: UILabel!
@IBOutlet weak var coinValueL: UILabel!
@IBOutlet weak var marketCapLabel: UILabel!
@IBOutlet weak var volumeLabel: UILabel!
@IBOutlet weak var coinPercentageL: UILabel!
var onDoneBlock : ((String?) -> Void)?
var values:[ChartDataEntry] = []
var graph = LineChart()
var lineChart = LineChartView()
var coinSymbol:String = "BTC"
var coinName:String?
//Al iniciarse el view genera valores para la grafica con x e y en 0 como placeholder, recibe las monedas, comprueba la mission, y pone el boton de trade con redondeo
override func viewDidLoad() {
super.viewDidLoad()
lineChart.delegate = self
for i in 0..<30{
self.values.append(ChartDataEntry(x: Double(i), y: 1))
}
getCoin()
if(coinName! == "Bitcoin"){
isMissionFinished(parameters: ["id":"3"])
}
tradeButton.layer.cornerRadius = tradeButton.frame.height / 8
}
//antes de iniciarse el view recibe el historial de la moneda escogida
override func viewWillAppear(_ animated: Bool) {
getCoinHistory()
}
//Al pulsar el boton de trade hace dismis y ejecuta el closure que te redirigira a la pantalla de trade
@IBAction func TradeViewButton(_ sender: Any) {
self.dismiss(animated: true) {
self.onDoneBlock!(self.coinSymbol)
}
}
//imprime la grafica con los valores correctos
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
graph.impirmirGrafica(lineChart: lineChart, screen: containerView, values:values, coinSymbol: coinSymbol)
lineChart.data?.notifyDataChanged()
lineChart.notifyDataSetChanged()
lineChart.setNeedsDisplay()
lineChart.reloadInputViews()
}
//funcion que recoge la informacion de la moneda pulsada en la pantalla main
func getCoin(){
if isConnected {
if (UserDefaults.standard.string(forKey: Identifiers.shared.auth) != nil) {
let parameters = ["name":coinName!]
let request = Service.shared.getCoinInfo(parameters: parameters)
request.responseJSON { (response) in
if let body = response.value as? [String:Any] {
if(response.response?.statusCode == StatusCodes.shared.OK){
attemptsMaxed = false
if let data = body["data"] as? [String:Any]{
self.currencyNameL.text = data["Name"]! as! String + "'s price"
self.coinSymbol = data["Symbol"] as! String
let coinValue = currencyFormatter(numberToFormat: (data["Price"] as? Double)!)
self.coinValueL.text = coinValue + "$"
self.aboutCoinLabel.text = AboutCoins.shared.coins[data["Name"]! as! String]
self.aboutTitleLabel.text = "About " + (data["Name"]! as! String)
self.coinIconIV.image = Images.shared.coins[data["Name"]! as! String]
let percentage = data["Change"]!
self.coinPercentageL.text = String(round(100*(percentage as? Double)!)/100) + "%"
var volume = String(((data["Volume"]! as? Double)!) / 1000000000)
volume = self.removeDecimals(numberToRound: volume)
self.volumeLabel.text = volume + "B $"
var marketCap = String(((data["Cap"]! as? Double)!)/1000000000)
marketCap = self.removeDecimals(numberToRound: marketCap)
self.marketCapLabel.text = marketCap + "B $"
if((data["Change"] as! Double) < 0) {
self.coinPercentageL?.textColor = #colorLiteral(red: 0.9490196078, green: 0.2862745098, blue: 0.4509803922, alpha: 1)
}else {
self.coinPercentageL?.textColor = #colorLiteral(red: 0.262745098, green: 0.8509803922, blue: 0.7411764706, alpha: 1)
}
}
}else{
attemptsMaxed = true
if !unknownBanner.isDisplaying{
unknownBanner.show()
}
}
}
}
}
}
}
//funcion que realiza la peticion de recoger el historial de la moneda
func getCoinHistory(){
if isConnected {
if (UserDefaults.standard.string(forKey: Identifiers.shared.auth) != nil) {
let parameters = ["coin":coinName!]
let request = Service.shared.getCoinHistory(params: parameters)
request.responseJSON { (response) in
if let body = response.value as? [String:Any] {
if(response.response?.statusCode == StatusCodes.shared.OK){
attemptsMaxed = false
if let data = body["data"] as? [[Double]]{
self.values = []
for i in 0..<data.count{
self.values.append(ChartDataEntry(x: Double(i+1), y: data[i][1]))
}
self.viewDidLayoutSubviews()
}
}else{
attemptsMaxed = true
if !unknownBanner.isDisplaying{
unknownBanner.show()
}
}
}
}
}
}
}
//quita los decimales de ciertos valores
func removeDecimals(numberToRound: String) -> String{
let splitter = numberToRound.components(separatedBy: ".")
var splitted: String = splitter[1]
let lastDecimal = splitted.first
splitted = splitter[0] + "." + String(lastDecimal!)
return splitted
}
}
<file_sep>import Foundation
class Score : Decodable, Encodable{
private var _experience:Int
init(experience:Int){
self._experience = experience
}
public var experience: Int {
get {
return self._experience;
}
set {
self._experience = newValue
}
}
}
<file_sep>//
// TradingController.swift
// CryptoniteCev
//
// Created by user177260 on 3/1/21.
// Copyright © 2021 user177257. All rights reserved.
//
import UIKit
import SkeletonView
class TradingController: UIViewController {
@IBOutlet weak var amountValue: UISlider!
@IBOutlet weak var curentPrice: UILabel!
@IBOutlet weak var tradeTableView: UITableView!
@IBOutlet weak var coinsSC: UISegmentedControl!
@IBOutlet weak var buySellSC: UISegmentedControl!
@IBOutlet var buyOrSellButton: UIButton!
@IBOutlet var amountTextfield: UITextField!
var trades:[Trade] = []
var coins:[Coin] = []
var wallets:[CoinsQuantities] = []
var coinForSC:String?
var cryptoPos = 0
var dollarPos = 0
var isSell = 0
var tradeType = "Buy "
let anim = SkeletonableAnim()
//ibaction de tradeos, generara un nuevo tradeo en base a ciertos parametros y reiniciara los valores además de apaga el boton para que no ocurran errores
@IBAction func tradeButton(_ sender: UIButton) {
if(amountValue.value > 0){
newTrade(is_sell: isSell, quantity: Double(amountValue.value), coin: coinsSC.titleForSegment(at: cryptoPos)!)
amountValue.value = 0
amountTextfield.text = "0"
buyOrSellButton.isEnabled = false
setProperButtonBuySellColor()
}
if(wallets.count>0){
if buySellSC.selectedSegmentIndex == 0{
amountValue.maximumValue = Float(self.wallets[dollarPos].inDollars)
}else{
amountValue.maximumValue = Float(self.wallets[cryptoPos+1].quantity)
}
}
}
//ibaction del slider, dependiendo de si es compra o venta y la posicion elegira unos decimales u otros ademas de modificar a 0 cuando ponga 0.0 en el textfield. Tambien pondrá el boton del color debido
@IBAction func amountSlider(_ sender: UISlider) {
var decimalQuantity = 0
if isSell == 0 || cryptoPos == 2{
decimalQuantity = 2
}else{
decimalQuantity = 7
}
amountTextfield.text = currencyFormatterFloat(numberToFormat: sender.value, decimalsQuantity: decimalQuantity)
if(amountTextfield.text == "0.00" || amountTextfield.text == "0.0"){
amountTextfield.text = "0"
}
setProperButtonBuySellColor()
if amountTextfield.text == "0.0"{
amountTextfield.text = "0"
}
}
//funcion que se dedica a poner el color correcto del boton de buy/sell
func setProperButtonBuySellColor(){
if amountValue.value>0{
buyOrSellButton.isEnabled = true
if isSell == 0{
buyOrSellButton.backgroundColor = #colorLiteral(red: 0.262745098, green: 0.8509803922, blue: 0.7411764706, alpha: 1)
buyOrSellButton.setTitleColor(#colorLiteral(red: 0.2, green: 0.2235294118, blue: 0.2784313725, alpha: 1), for: .normal)
}else{
buyOrSellButton.backgroundColor = #colorLiteral(red: 0.9490196078, green: 0.2862745098, blue: 0.4509803922, alpha: 1)
buyOrSellButton.setTitleColor(#colorLiteral(red: 1, green: 1, blue: 1, alpha: 1), for: .normal)
}
}else{
buyOrSellButton.isEnabled = false
buyOrSellButton.backgroundColor = #colorLiteral(red: 0.2, green: 0.2235294118, blue: 0.2784313725, alpha: 1)
buyOrSellButton.setTitleColor(UIColor.lightGray, for: .normal)
}
if isSell == 0{
buySellSC.setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.black], for: UIControl.State.selected)
}else{
buySellSC.setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.white], for: UIControl.State.selected)
}
buyOrSellButton.setTitle(self.tradeType + coinsSC.titleForSegment(at: cryptoPos)!, for: .normal)
}
/*
Al iniciarse el view se generan los wallets, la lista de tradeos y las monedas.
El sc pondrá la posicion adecuada en base al nombre además de colocar el titulo del botón dependiendo de la moneda seleccionada
*/
override func viewDidAppear(_ animated: Bool) {
setWallet(fromTrades: false)
trades = getTrades()
coins = getCoins()
if coinForSC != nil {
coinsSC.selectedSegmentIndex = getPositionInSGFromName()
self.cryptoPos = coinsSC.selectedSegmentIndex
if coins.count > 0{
curentPrice.text = currencyFormatter(numberToFormat: self.coins[self.cryptoPos].price) + "$"
}else{
curentPrice.text = "N/A"
}
buyOrSellButton.setTitle(self.tradeType + coinsSC.titleForSegment(at: cryptoPos)!, for: .normal)
}
}
//Al poner cantidad en el textfield pone la cantidad maxima si la cantidad introducida es mayor
@IBAction func onSelectAmountField(_ sender: Any) {
if (amountTextfield.text! as NSString).floatValue > amountValue.maximumValue{
amountTextfield.text = String(amountValue.maximumValue)
}
setProperButtonBuySellColor()
}
//Al modificarse el textfield se comprueba la cantidad introducida para poner la maxima posible
@IBAction func onTextFieldValueChanged(_ sender: UITextField) {
if(sender.text == ""){
amountValue.value = 0
}else{
amountValue.value = (sender.text! as NSString).floatValue
if (amountTextfield.text! as NSString).floatValue > amountValue.maximumValue{
amountTextfield.text = String(amountValue.maximumValue)
}
}
setProperButtonBuySellColor()
}
//Al seleccionar una moneda se modifica el label del precio, se guarda la posición y se modifica el max value del slider
@IBAction func onSelectCoin(_ sender: Any) {
cryptoPos = coinsSC.selectedSegmentIndex
if(coins.count>0){
curentPrice.text = currencyFormatter(numberToFormat: self.coins[self.cryptoPos].price) + "$"
}else{
curentPrice.text = "N/A"
}
amountValue.value = 0
amountTextfield.text = "0"
if(wallets.count>0){
if buySellSC.selectedSegmentIndex == 0{
amountValue.maximumValue = Float(self.wallets[dollarPos].inDollars)
}else{
amountValue.maximumValue = Float(self.wallets[cryptoPos+1].quantity)
}
}
setProperButtonBuySellColor()
}
//Cambia el color y texto del boton buy/sell al cambiar el sc
@IBAction func onSelectBuySell(_ sender: Any) {
amountValue.maximumValue = 0
if buySellSC.selectedSegmentIndex == 0{
isSell = 0
self.tradeType = "Buy "
buySellSC.selectedSegmentTintColor = #colorLiteral(red: 0.262745098, green: 0.8509803922, blue: 0.7411764706, alpha: 1)
if(wallets.count>0){
amountValue.maximumValue = Float(self.wallets[dollarPos].inDollars)
}
}else{
isSell=1
self.tradeType = "Sell "
buySellSC.selectedSegmentTintColor = #colorLiteral(red: 0.9490196078, green: 0.2862745098, blue: 0.4509803922, alpha: 1)
if(wallets.count>0){
amountValue.maximumValue = Float(self.wallets[cryptoPos+1].quantity)
}
}
setProperButtonBuySellColor()
amountValue.value = 0
amountTextfield.text = "0"
}
//Al cargar el view coloca el placeholder, activa el toggle del teclado, coloca el nombre de la moneda y si es compra/venta en el boton además de poner los textos de los sc en color negro
override func viewDidLoad() {
super.viewDidLoad()
self.hideKeyboardWhenTappedAround()
anim.placeholder(view: curentPrice)
tradeTableView.delegate = self
tradeTableView.dataSource = self
tradeTableView.rowHeight = 68
tradeTableView.estimatedRowHeight = 68
anim.self.placeholder(view: tradeTableView)
buyOrSellButton.setTitle(self.tradeType + coinsSC.titleForSegment(at: cryptoPos)!, for: .normal)
amountValue.maximumValue = 0
amountTextfield.text = "0"
coinsSC.setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.black], for: UIControl.State.selected)
buySellSC.setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.black], for: UIControl.State.selected)
}
//peticion que recoge las monedas y precios
func getCoins()->[Coin]{
coins = []
if isConnected {
if (UserDefaults.standard.string(forKey: Identifiers.shared.auth) != nil) {
let requestCoins = Service.shared.getCoins()
requestCoins.responseJSON { (response) in
if let body = response.value as? [String: Any]{
if(response.response?.statusCode == StatusCodes.shared.OK){
attemptsMaxed = false
let data = body["data"] as! [[String:Any]]
for i in 1..<data.count {
self.coins.append(Coin(name: (data[i]["Name"] as? String)!, symbol: (data[i]["Symbol"]! as? String)!, price: (data[i]["Price"] as? Double)!, change: (data[i]["Change"] as? Double)!))
}
self.curentPrice.text = currencyFormatter(numberToFormat: self.coins[self.cryptoPos].price) + "$"
self.anim.hidePlaceholder(view: self.curentPrice)
}else{
attemptsMaxed = true
if !unknownBanner.isDisplaying{
unknownBanner.show()
}
}
}
}
}
}
return coins
}
//Peticion que recibe todos los tradeos
func getTrades() -> [Trade]{
trades = []
if isConnected {
if (UserDefaults.standard.string(forKey: Identifiers.shared.auth) != nil) {
let requestTrades = Service.shared.getTradesInfo()
requestTrades.responseJSON { (response) in
if let body = response.value as? [String:Any] {
if(response.response?.statusCode == StatusCodes.shared.OK){
attemptsMaxed = false
if let data = body["data"] as? [[String:Any]]{
for i in 0..<data.count {
self.trades.append(Trade(coin: (data[i]["Coin"] as? String)!, date: self.timestampToDate(date: data[i]["Date"] as! Double), quantity: (data[i]["Quantity"] as? Double)!, price: (data[i]["Price"] as? Double)!, isSell: (data[i]["Is_sell"] as? Int)!))
}
}
self.tradeTableView.reloadData()
self.anim.hidePlaceholder(view: self.tradeTableView)
}else{
attemptsMaxed = true
if !unknownBanner.isDisplaying{
unknownBanner.show()
}
}
}
}
}
}
return trades;
}
//genera nuevo trade en base a compra/venta, moneda y cantidad además de comprobar las misiones
func newTrade(is_sell:Int, quantity: Double, coin:String) {
if isConnected {
if (UserDefaults.standard.string(forKey: Identifiers.shared.auth) != nil) {
let parameters:[String:String] = [
"is_sell":String(is_sell),
"quantity":String(quantity),
"coin":coin
]
let requestTrades = Service.shared.newTrade(parameters: parameters)
requestTrades.responseJSON { (response) in
if let body = response.value as? [String: Any]{
if(response.response?.statusCode == StatusCodes.shared.OK){
attemptsMaxed = false
Banners.shared.successBanner(title: body["message"]! as! String, subtitle: "")
self.setWallet(fromTrades: true)
isMissionFinished(parameters: ["id":"4"])
self.trades = self.getTrades()
if(self.coinsSC.titleForSegment(at: self.cryptoPos) == "DOGE"){
isMissionFinished(parameters: ["id":"1"])
}
if(self.coinsSC.titleForSegment(at: self.cryptoPos) == "LTC" && self.isSell==1){
isMissionFinished(parameters: ["id":"6"])
}
var numberOfFollows = UserDefaults.standard.integer(forKey: "numberOfFollows")
numberOfFollows += 1
UserDefaults.standard.set(numberOfFollows, forKey: "numberOfFollows")
if (UserDefaults.standard.integer(forKey: "numberOfFollows") >= 3){
isMissionFinished(parameters: ["id":"10"])
}
self.tradeTableView.reloadData()
self.anim.hidePlaceholder(view: self.tradeTableView)
}else{
attemptsMaxed = true
if !unknownBanner.isDisplaying{
unknownBanner.show()
}
}
}
}
}
}
}
//peticion que recibe los wallets ademas de comprobar las misiones correspondientes
func setWallet(fromTrades:Bool){
wallets = []
if isConnected {
if (UserDefaults.standard.string(forKey: Identifiers.shared.auth) != nil) {
let request = Service.shared.getWallets()
request.responseJSON { (response) in
if let body = response.value as? [String: Any]{
if(response.response?.statusCode == StatusCodes.shared.OK){
attemptsMaxed = false
if let data = body["data"]! as? [String:Any]{
let walletsReceived = data["Wallets"] as! [[String:Any]]
for i in 0..<walletsReceived.count {
self.wallets.append(CoinsQuantities(name: (walletsReceived[i]["Name"] as? String)!, symbol: (walletsReceived[i]["Symbol"]! as? String)!, quantity: (walletsReceived[i]["Quantity"] as? Double)!, inDollars: (walletsReceived[i]["inDollars"] as? Double)!))
}
if self.isSell == 0{
self.amountValue.maximumValue = Float(self.wallets[0].inDollars)
}else{
self.amountValue.maximumValue = Float(self.wallets[self.cryptoPos+1].quantity)
}
var walletsWithCash:[String] = []
for i in 0..<self.wallets.count{
if self.wallets[i].quantity > 0{
walletsWithCash.append(self.wallets[i].symbol)
}
}
if(fromTrades){
if self.wallets[0].quantity == 0 && self.isSell == 0{
isMissionFinished(parameters: ["id":"11"])
}
}
if(fromTrades){
if walletsWithCash.count == 1{
if walletsWithCash[0] == "BTC" {
isMissionFinished(parameters: ["id":"8"])
}
}
}
if(fromTrades){
if walletsWithCash.count == 1{
if walletsWithCash[0] == "USDT" {
isMissionFinished(parameters: ["id":"7"])
}
}
}
}
}else{
attemptsMaxed = true
if !unknownBanner.isDisplaying{
unknownBanner.show()
}
}
}
}
}
}
}
//Comprueba nombre y devuelve positicion en el segmented control
func getPositionInSGFromName()->Int{
for i in 0..<coinsSC.numberOfSegments{
if coinForSC == coinsSC.titleForSegment(at: i)!{
return i
}
}
return 0
}
//Recibe timestamp devuelve date
func timestampToDate(date: Double) -> String {
let tradeDate = Date(timeIntervalSince1970: date )
let formatter1 = DateFormatter()
formatter1.dateStyle = .long
return formatter1.string(from: tradeDate)
}
}
<file_sep>import Foundation
import UIKit
class Welcomings{
let phrases:[String]
private init() {
//Frases que apareceran en login de forma aleatoria
self.phrases = ["Jealous of Bruce Wayne? \n Let’s go to the mooooon!",
"<NAME>? Who?",
"HOOOOOOODL!",
"Buy the dip, sell the rip",
"What are you buying today?",
"Are you a paper or a diamond hand?",
"Dogecoin is my kryptonite"]
}
static let shared = Welcomings()
}
<file_sep>//
// storiesController.swift
// CryptoniteCev
//
// Created by user177260 on 1/24/21.
// Copyright © 2021 user177257. All rights reserved.
//
import UIKit
import Charts
import SkeletonView
class StoriesController: UIViewController, ChartViewDelegate, SkeletonTableViewDataSource, UITableViewDelegate {
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var usernameLabel: UILabel!
var storieImage : UIImage?
var username : String?
var trades:[TradesProfile] = []
var wallets:[CoinsQuantities] = []
var cash:Double = 0
var percentages:[String:Double] = [:]
var followings:[String] = []
var following:Bool = false
var graph = PieChart()
var onDoneBlock : (() -> Void)?
let anim = SkeletonableAnim()
@IBOutlet weak var unfollowButton: UIButton!
var pieChart = PieChartView()
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var container: UIView!
let roundingPair = ["DogeCoin", "Tether"]
var roundingQuantity: Double = 100000
/**
Al iniciarse el view realiza las peticiones de recoger porcentages, rellenar los followings para comprobar si el user logged sigue a este user, se pone la estetica del table view y del boton de unfollow
*/
override func viewDidLoad() {
super.viewDidLoad()
getPercentages()
fillFollowings()
pieChart.drawEntryLabelsEnabled = false
unfollowButton.layer.cornerRadius = 15
imageView.layer.cornerRadius = imageView.bounds.size.width / 2
imageView.layer.borderColor = #colorLiteral(red: 0.0733634308, green: 0.1234697327, blue: 0.2026597559, alpha: 1)
imageView.layer.borderWidth = 3
tableView.rowHeight = 68
tableView.estimatedRowHeight = 68
tableView.delegate = self
tableView.dataSource = self
tableView.reloadData()
anim.placeholder(view: nameLabel)
anim.placeholder(view: usernameLabel)
anim.placeholder(view: tableView)
}
//antes de desaparecer la vista se llama al closure onDoneBlock para actulizar las stories al volver a main, esto se hace para comprobar si se ha followeado o unfolloweado a la persona
override func viewWillDisappear(_ animated: Bool) {
onDoneBlock!()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return trades.count
}
/**
Coloca los labels e imagenes en base a lo recibido en la petición de trades
*/
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "otherCell") as! OtherUserCell
if trades.count > 0{
cell.profile.image = storieImage
cell.profile.layer.cornerRadius = cell.profile.bounds.size.width / 2
roundingQuantity = setRounding(symbol: trades[indexPath.row].coinTo)
cell.converted.text = currencyFormatter(numberToFormat: round(roundingQuantity * trades[indexPath.row].converted) / roundingQuantity)
roundingQuantity = setRounding(symbol: trades[indexPath.row].coinFrom)
cell.quantity.text = currencyFormatter(numberToFormat: round(roundingQuantity * trades[indexPath.row].quantity) / roundingQuantity)
cell.symbol_from.image = Images.shared.coins[trades[indexPath.row].coinFrom]
cell.symbol_to.image = Images.shared.coins[trades[indexPath.row].coinTo]
}
return cell
}
//imprime el piechart con los porcentages recogidos
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
graph.impirmirGrafica(pieChart: pieChart, screen: container, percentages: percentages)
}
//al aparecer el view se llama a trades y se guarda en la variable
override func viewDidAppear(_ animated: Bool) {
trades = getTrades()
}
//Botón de follow llama a peticion follow o unfollow dependiendo del estado
@IBAction func followUserButton(_ sender: Any) {
if(!following){
unfollowButton.isEnabled = false
followSomeone()
}else{
unfollowButton.isEnabled = false
unfollowSomeone()
}
}
/**
Petición que recoge tradeos e información del user
*/
func getTrades() -> [TradesProfile]{
trades = []
if isConnected {
if (UserDefaults.standard.string(forKey: Identifiers.shared.auth) != nil) {
let parameters = ["username":username!]
let requestTrades = Service.shared.getProfileTradesInfo(parameters: parameters)
requestTrades.responseJSON { (response) in
if let body = response.value as? [String:Any] {
if(response.response?.statusCode == StatusCodes.shared.OK){
attemptsMaxed = false
if let data = body["data"] as? [String:Any]{
let tradeHistory = data["Trades"] as! [[String:Any]]
let user = data["User"] as! [String:Any]
self.nameLabel.text = user["Name"] as? String
self.usernameLabel.text = "@" + (user["Username"] as! String)
self.imageView.image = Images.shared.users[user["Profile_pic"] as! Int]
self.anim.hidePlaceholder(view: self.usernameLabel)
self.anim.hidePlaceholder(view: self.nameLabel)
for i in 0..<tradeHistory.count {
self.trades.append(TradesProfile(coinFrom: (tradeHistory[i]["Coin_from"] as? String)!, coinTo: (tradeHistory[i]["Coin_to"] as? String)!, coinFromSymbol: (tradeHistory[i]["Coin_from_symbol"] as? String)!, coinToSymbol: (tradeHistory[i]["Coin_to_symbol"] as? String)!, quantity: (tradeHistory[i]["Quantity"] as? Double)!, converted: (tradeHistory[i]["Converted"] as? Double)!))
}
}
self.tableView.reloadData()
self.anim.hidePlaceholder(view: self.tableView)
}else{
attemptsMaxed = true
if !unknownBanner.isDisplaying{
unknownBanner.show()
}
}
}
}
}
}
return trades;
}
//Petición que ecoge los porcentajes que se mostrarán en el piechart
func getPercentages(){
if isConnected {
if (UserDefaults.standard.string(forKey: Identifiers.shared.auth) != nil) {
let parameters = ["username":username!]
let request = Service.shared.getPercentages(parameters: parameters)
request.responseJSON { (response) in
if let body = response.value as? [String:Any] {
if(response.response?.statusCode == StatusCodes.shared.OK){
attemptsMaxed = false
if let data = body["data"] as? [String:Any]{
let wallets = data["Wallets"] as! [[String:Any]]
for i in 0..<wallets.count{
self.percentages[wallets[i]["Symbol"] as! String] = wallets[i]["Percentage"] as? Double
}
}
}else{
attemptsMaxed = true
if !unknownBanner.isDisplaying{
unknownBanner.show()
}
}
}
}
}
}
}
//devuelve identifier del collection view
func collectionSkeletonView(_ skeletonView: UITableView, cellIdentifierForRowAt indexPath: IndexPath) -> ReusableCellIdentifier {
return "otherCell"
}
//Petición de hacer follow
func followSomeone(){
if isConnected {
if (UserDefaults.standard.string(forKey: Identifiers.shared.auth) != nil) {
let parameters = ["username":username!]
let request = Service.shared.followUser(params: parameters)
request.responseJSON { (response) in
if let body = response.value as? [String:Any] {
if(response.response?.statusCode == StatusCodes.shared.OK){
attemptsMaxed = false
if let data = body["data"] as? String{
self.following=true
self.unfollowButton.backgroundColor = #colorLiteral(red: 0.9490196078, green: 0.2862745098, blue: 0.4509803922, alpha: 1)
self.unfollowButton.setTitleColor(#colorLiteral(red: 1, green: 1, blue: 1, alpha: 1), for: .normal)
self.unfollowButton.setTitle("Unfollow", for: .normal)
isMissionFinished(parameters: ["id":"5"])
var numberOfFollows = UserDefaults.standard.integer(forKey: "numberOfFollows")
numberOfFollows += 1
UserDefaults.standard.set(numberOfFollows, forKey: "numberOfFollows")
self.unfollowButton.isEnabled = true
if (UserDefaults.standard.integer(forKey: "numberOfFollows") >= 2){
isMissionFinished(parameters: ["id":"9"])
}
}
}else{
attemptsMaxed = true
if !unknownBanner.isDisplaying{
unknownBanner.show()
}
}
}
}
}
}
}
//recoger las personas que sigue el user logged
func fillFollowings(){
followings = []
if isConnected {
if (UserDefaults.standard.string(forKey: Identifiers.shared.auth) != nil) {
let request = Service.shared.getFollowings()
request.responseJSON { (response) in
if let body = response.value as? [String:Any] {
if(response.response?.statusCode == StatusCodes.shared.OK){
attemptsMaxed = false
if let data = body["data"] as? [[String:Any]]{
for i in 0..<data.count{
self.followings.append(data[i]["username"] as! String)
}
self.setProperButton()
}
}else{
attemptsMaxed = true
if !unknownBanner.isDisplaying{
unknownBanner.show()
}
}
}
}
}
}
}
//Pondrá el boton de follow de la manera correcta dependiendo del estado
func setProperButton(){
if !self.followings.contains(self.username!){
self.following = false
self.unfollowButton.backgroundColor = #colorLiteral(red: 0.262745098, green: 0.8509803922, blue: 0.7411764706, alpha: 1)
self.unfollowButton.setTitleColor(#colorLiteral(red: 0.2, green: 0.2235294118, blue: 0.2784313725, alpha: 1), for: .normal)
self.unfollowButton.setTitle("Follow", for: .normal)
}else{
self.following = true
self.unfollowButton.backgroundColor = #colorLiteral(red: 0.9490196078, green: 0.2862745098, blue: 0.4509803922, alpha: 1)
self.unfollowButton.setTitleColor(#colorLiteral(red: 1, green: 1, blue: 1, alpha: 1), for: .normal)
self.unfollowButton.setTitle("Unfollow", for: .normal)
}
}
//Petición de hacer unfollow
func unfollowSomeone(){
if isConnected {
if (UserDefaults.standard.string(forKey: Identifiers.shared.auth) != nil) {
let parameters = ["username":username!]
let request = Service.shared.stopFollowing(params: parameters)
request.responseJSON { (response) in
if let body = response.value as? [String:Any] {
if(response.response?.statusCode == StatusCodes.shared.OK){
attemptsMaxed = false
if let message = body["message"] as? String{
self.following=false
self.unfollowButton.backgroundColor = #colorLiteral(red: 0.262745098, green: 0.8509803922, blue: 0.7411764706, alpha: 1)
self.unfollowButton.setTitleColor(#colorLiteral(red: 0.2, green: 0.2235294118, blue: 0.2784313725, alpha: 1), for: .normal)
self.unfollowButton.setTitle("Follow", for: .normal)
self.unfollowButton.isEnabled = true
}
}else{
attemptsMaxed = true
if !unknownBanner.isDisplaying{
unknownBanner.show()
}
}
}
}
}
}
}
}
<file_sep>
import Foundation
import Alamofire
class Service {
static let shared = Service()
private init() {}
/**
Comprueba si hay comexión a internet
*/
class var isConnectedToInternet:Bool {
return NetworkReachabilityManager()?.isReachable ?? false
}
//Recibe params (user y pass) , devuelve datos de la petición
func login(parameters:[String:String])-> DataRequest{
return AF.request(Endpoints.domain + Endpoints.path + Endpoints.User.login, method: .post, parameters: parameters, encoder: JSONParameterEncoder.default)
}
/**
Recibe un usuario que registrará en la petición
*/
func register(user:User)-> DataRequest {
return AF.request(Endpoints.domain + Endpoints.path+Endpoints.User.register, method: .post, parameters: user, encoder: JSONParameterEncoder.default)
}
//Recibe params (email) , devuelve datos de la petición
func restorePassword(parameters:[String:String])-> DataRequest {
return AF.request(Endpoints.domain + Endpoints.path+Endpoints.User.restorePassword, method: .put, parameters:parameters , encoder: JSONParameterEncoder.default)
}
/**
Petición de recoger monedas
*/
func getCoins()->DataRequest{
let headers:HTTPHeaders = [
ApiBodyNames.shared.apiToken : "Bearer " + UserDefaults.standard.string(forKey: Identifiers.shared.auth)!
]
return AF.request(Endpoints.domain + Endpoints.path + Endpoints.Coin.getList, method: .get, encoding: URLEncoding.default, headers: headers)
}
/**
Petición de recoge wallets que posee el usuario loggeado
*/
func getCoinsWithQuantities()->DataRequest{
let headers:HTTPHeaders = [
ApiBodyNames.shared.apiToken : "Bearer " + UserDefaults.standard.string(forKey: Identifiers.shared.auth)!
]
return AF.request(Endpoints.domain + Endpoints.path + Endpoints.Coin.quantities, method: .get, encoding: URLEncoding.default, headers: headers)
}
/**
Petición de recoge wallets que posee el usuario loggeado
*/
func getWallets()->DataRequest{
let headers:HTTPHeaders = [
ApiBodyNames.shared.apiToken : "Bearer " + UserDefaults.standard.string(forKey: Identifiers.shared.auth)!
]
return AF.request(Endpoints.domain + Endpoints.path + Endpoints.Wallet.getInfo, method: .get, encoding: URLEncoding.default, headers: headers)
}
/**
Petición de recoge el cash total que posee el usuario loggeado
*/
func getCash()->DataRequest{
let headers:HTTPHeaders = [
ApiBodyNames.shared.apiToken : "Bearer " + UserDefaults.standard.string(forKey: Identifiers.shared.auth)!
]
return AF.request(Endpoints.domain + Endpoints.path + Endpoints.Wallet.cash, method: .get, encoding: URLEncoding.default, headers: headers)
}
/**
Historial de transacciones general
*/
func getTradingHistory()->DataRequest{
let headers:HTTPHeaders = [
ApiBodyNames.shared.apiToken : "Bearer " + UserDefaults.standard.string(forKey: Identifiers.shared.auth)!
]
return AF.request(Endpoints.domain + Endpoints.path + Endpoints.Trading.getTradingHistory, method: .get, encoding: URLEncoding.default, headers: headers)
}
/**
Trades de un usuario diferente del logeado
*/
func getProfileTradesInfo(parameters:[String:String])->DataRequest{
let headers:HTTPHeaders = [
ApiBodyNames.shared.apiToken : "Bearer " + UserDefaults.standard.string(forKey: Identifiers.shared.auth)!
]
return AF.request(Endpoints.domain + Endpoints.path + Endpoints.User.userProfileTrades, method: .get,parameters: parameters ,encoding: URLEncoding.default, headers: headers)
}
/**
Tradeos del usuario loggeado
*/
func getTradesInfo()->DataRequest{
let headers:HTTPHeaders = [
ApiBodyNames.shared.apiToken : "Bearer " + UserDefaults.standard.string(forKey: Identifiers.shared.auth)!
]
return AF.request(Endpoints.domain + Endpoints.path + Endpoints.User.userTrades, method: .get ,encoding: URLEncoding.default, headers: headers)
}
/**
Crea un nuevo tradeo
*/
func newTrade(parameters:[String:String])-> DataRequest{
let headers:HTTPHeaders = [
ApiBodyNames.shared.apiToken : "Bearer " + UserDefaults.standard.string(forKey: Identifiers.shared.auth)!
]
return AF.request(Endpoints.domain + Endpoints.path + Endpoints.User.trade, method: .post, parameters: parameters, encoder: JSONParameterEncoder.default,headers: headers)
}
/**
Recibe usuarios
*/
func getUsers()->DataRequest{
let headers:HTTPHeaders = [
ApiBodyNames.shared.apiToken : "Bearer " + UserDefaults.standard.string(forKey: Identifiers.shared.auth)!
]
return AF.request(Endpoints.domain + Endpoints.path + Endpoints.User.all, method: .get, encoding: URLEncoding.default, headers: headers)
}
/**
Porcentajes de monedas que posee un user
*/
func getPercentages(parameters:[String:String])->DataRequest{
let headers:HTTPHeaders = [
ApiBodyNames.shared.apiToken : "Bearer " + UserDefaults.standard.string(forKey: Identifiers.shared.auth)!
]
return AF.request(Endpoints.domain + Endpoints.path + Endpoints.Wallet.percentages, method: .get, parameters: parameters, encoding: URLEncoding.default, headers: headers)
}
/**
Información de la moneda pasada
*/
func getCoinInfo(parameters:[String:String])->DataRequest{
let headers:HTTPHeaders = [
ApiBodyNames.shared.apiToken : "Bearer " + UserDefaults.standard.string(forKey: Identifiers.shared.auth)!
]
return AF.request(Endpoints.domain + Endpoints.path + Endpoints.Coin.coinInfo, method: .get, parameters:parameters, encoding: URLEncoding.default, headers: headers)
}
/**
Genera un nuevo follow en el usuario registrado
*/
func followUser(params:[String:String])->DataRequest {
let headers:HTTPHeaders = [
ApiBodyNames.shared.apiToken : "Bearer " + UserDefaults.standard.string(forKey: Identifiers.shared.auth)!
]
return AF.request(Endpoints.domain + Endpoints.path + Endpoints.User.followUser, method: .post, parameters: params, encoder: JSONParameterEncoder.default, headers: headers)
}
/**
Recibe toda la gente seguida por el user loggeado
*/
func getFollowings()->DataRequest{
let headers:HTTPHeaders = [
ApiBodyNames.shared.apiToken : "Bearer " + UserDefaults.standard.string(forKey: Identifiers.shared.auth)!
]
return AF.request(Endpoints.domain + Endpoints.path + Endpoints.User.getFollowings, method: .get, encoding: URLEncoding.default, headers: headers)
}
/**
Petición que se encargará de hacer unfollow
*/
func stopFollowing(params:[String:String])->DataRequest {
let headers:HTTPHeaders = [
ApiBodyNames.shared.apiToken : "Bearer " + UserDefaults.standard.string(forKey: Identifiers.shared.auth)!
]
return AF.request(Endpoints.domain + Endpoints.path + Endpoints.User.stopFollowing, method: .delete, parameters: params, encoder: JSONParameterEncoder.default, headers: headers)
}
/**
Historial de una moneda de los ultimos 30 dias, usado para representar en gráficas
*/
func getCoinHistory(params:[String:String])->DataRequest{
let headers:HTTPHeaders = [
ApiBodyNames.shared.apiToken : "Bearer " + UserDefaults.standard.string(forKey: Identifiers.shared.auth)!
]
return AF.request(Endpoints.domain + Endpoints.path + Endpoints.Coin.history, method: .get,parameters: params, encoding: URLEncoding.default, headers: headers)
}
//devuelve las missiones del usuario, genera una nueva mission y borra la terminada
func assignNewMission(params:[String:String])->DataRequest{
let headers:HTTPHeaders = [
ApiBodyNames.shared.apiToken : "Bearer " + UserDefaults.standard.string(forKey: Identifiers.shared.auth)!
]
return AF.request(Endpoints.domain + Endpoints.path + Endpoints.User.assignNewMission, method: .post,parameters: params, encoding: URLEncoding.default, headers: headers)
}
//Recibe la que se acaba de hacer para actualizarla a finish en la bbdd
func updateMissionToFinish(params:[String:String])->DataRequest{
let headers:HTTPHeaders = [
ApiBodyNames.shared.apiToken : "Bearer " + UserDefaults.standard.string(forKey: Identifiers.shared.auth)!
]
return AF.request(Endpoints.domain + Endpoints.path + Endpoints.User.missionFinished, method: .post,parameters: params, encoding: URLEncoding.default, headers: headers)
}
/**
info que se mostrará en la pantalla de gamificación del usuario
*/
func gamification()->DataRequest{
let headers:HTTPHeaders = [
ApiBodyNames.shared.apiToken : "Bearer " + UserDefaults.standard.string(forKey: Identifiers.shared.auth)!
]
return AF.request(Endpoints.domain + Endpoints.path + Endpoints.User.gamification, method: .get, encoding: URLEncoding.default, headers: headers)
}
/**
envia la nueva experiencia tras terminar una mision
*/
func updateExp(params:[String:Int])->DataRequest{
let headers:HTTPHeaders = [
ApiBodyNames.shared.apiToken : "Bearer " + UserDefaults.standard.string(forKey: Identifiers.shared.auth)!
]
return AF.request(Endpoints.domain + Endpoints.path + Endpoints.User.updateExperience, method: .put, parameters: params, encoding: URLEncoding.default, headers: headers)
}
func updateMission(params:[String:String])->DataRequest{
let headers:HTTPHeaders = [
ApiBodyNames.shared.apiToken : "Bearer " + UserDefaults.standard.string(forKey: Identifiers.shared.auth)!
]
return AF.request(Endpoints.domain + Endpoints.path + Endpoints.User.updateMission, method: .post,parameters: params, encoding: URLEncoding.default, headers: headers)
}
//Deposita dinero en forma de doges
func desposit(params:[String:Double])->DataRequest{
let headers:HTTPHeaders = [
ApiBodyNames.shared.apiToken : "Bearer " + UserDefaults.standard.string(forKey: Identifiers.shared.auth)!
]
return AF.request(Endpoints.domain + Endpoints.path + Endpoints.Wallet.deposit, method: .put,parameters: params, encoding: URLEncoding.default, headers: headers)
}
//recoge porcentajes del user logged
func getOwnPercentages()->DataRequest{
let headers:HTTPHeaders = [
ApiBodyNames.shared.apiToken : "Bearer " + UserDefaults.standard.string(forKey: Identifiers.shared.auth)!
]
return AF.request(Endpoints.domain + Endpoints.path + Endpoints.Wallet.percentagesOwn, method: .get, encoding: URLEncoding.default, headers: headers)
}
/**
Recibe las misiones del usuario logeado
*/
func getMissions()->DataRequest{
let headers:HTTPHeaders = [
ApiBodyNames.shared.apiToken : "Bearer " + UserDefaults.standard.string(forKey: Identifiers.shared.auth)!
]
return AF.request(Endpoints.domain + Endpoints.path + Endpoints.User.getMissions, method: .get, encoding: URLEncoding.default, headers: headers)
}
}
<file_sep>
import Foundation
import UIKit
class UserCellMainController: UICollectionViewCell {
//referencias de outlets
@IBOutlet weak var profilePicIV: UIImageView!
@IBOutlet weak var usernameL: UILabel!
@IBOutlet weak var percentageUserL: UILabel!
}
<file_sep>
import UIKit
import NotificationBannerSwift
import Network
let connectionBanner = Banners.shared.noConnectionBanner()
let unknownBanner = Banners.shared.unknownErrorBanner()
var isConnected:Bool = true
var attemptsMaxed:Bool = false
class LogInController: UIViewController {
@IBOutlet weak var logInButton: UIButton!
@IBOutlet weak var usernameTF: UnderlinedTextField!
@IBOutlet weak var passwordTF: UnderlinedTextField!
@IBOutlet weak var introLabel: UILabel!
//let apiBodyResponses = ApiBodyResponses.shared
let identifiers = Identifiers.shared
let monitor = Monitor()
/**
Al iniciarse el view activa el toggle de teclado, redondea el boton de login y genera una nueva frase random que pondrá en el label
*/
override func viewDidLoad() {
super.viewDidLoad()
self.hideKeyboardWhenTappedAround()
logInButton.layer.cornerRadius = 5
introLabel.text = Welcomings.shared.phrases[Int.random(in: 0..<Welcomings.shared.phrases.count)]
}
/*
Antes de iniciarse la vista comienza a monitorear los posibles cambios de internet ademas de habilitar el boton de login
*/
override func viewWillAppear(_ animated: Bool) {
logInButton.isEnabled = true
monitor.startMonitoring { [weak self] connection, reachable in
if reachable == Reachable.yes && connection == Connection.wifi{
DispatchQueue.main.async {
isConnected = true
connectionBanner.dismiss()
}
}else{
DispatchQueue.main.async {
isConnected = false
connectionBanner.show()
}
}
}
//si hay internet y ya estas loggeado de antes irás directamente a la pantalla de main
if isConnected{
if UserDefaults.standard.string(forKey: Identifiers.shared.auth) != nil {
self.navigationController?.setNavigationBarHidden(true, animated: true)
self.performSegue(withIdentifier: self.identifiers.toMain, sender: (Any).self)
}
}
}
/**
Al pulsar el boton de login se hara la peticion pasando los parametros de los fields, además de comprobar que estos campos sean correctos
*/
@IBAction func LogInButton(_ sender: Any) {
if checkUsername(textFieldUsername: usernameTF) && checkPassword(textFieldPass: <PASSWORD>){
let apiBodyNames = ApiBodyNames.shared
let parameters =
[apiBodyNames.username:usernameTF.text!,
apiBodyNames.password:<PASSWORD>.text!]
login(parameters: parameters, sender: sender)
}
}
/**
Petición de loggeo con sus respectivas comprobaciones
*/
func login(parameters:[String:String], sender:Any){
if isConnected {
logInButton.isEnabled = false
let request = Service.shared.login(parameters: parameters)
request.responseJSON { (response) in
if let body = response.value as? [String: Any]{
if(response.response?.statusCode == StatusCodes.shared.OK){
attemptsMaxed = false
self.logInButton.isEnabled = false
UserDefaults.standard.set(body["data"], forKey: self.identifiers.auth)
self.navigationController?.setNavigationBarHidden(true, animated: true)
UserDefaults.standard.set(0, forKey: "numberOfTransactions")
UserDefaults.standard.set(0, forKey: "numberOfFollows")
self.performSegue(withIdentifier: self.identifiers.toMain, sender: sender)
}else{
self.logInButton.isEnabled = true
Banners.shared.errorBanner(title: body["message"] as! String, subtitle: "Try again!")
}
}else{
self.logInButton.isEnabled = true
Banners.shared.errorBanner(title: "Something strange has occured", subtitle: "Try again!")
}
}
}
}
//Antes de iniciarse el view quitara el nav controller
override func viewDidAppear(_ animated: Bool) {
navigationController?.setNavigationBarHidden(true, animated: true)
}
//AL pulsar el boton de signup habilitara el boton de login y nos llevara a la pantalla de signup
@IBAction func signUpButton(_ sender: Any) {
logInButton.isEnabled = true
performSegue(withIdentifier: "signup", sender: sender)
}
}
<file_sep>
import UIKit
class ActivityRow: UITableViewCell {
//Referencias de outlets
@IBOutlet weak var profilePicActivityIV: UIImageView!
@IBOutlet weak var usernameActivityL: UILabel!
@IBOutlet weak var coinSellingL: UILabel!
@IBOutlet weak var iconSellingIV: UIImageView!
@IBOutlet weak var coinBuyingL: UILabel!
@IBOutlet weak var iconBuyingIV: UIImageView!
}
<file_sep>
import UIKit
import Foundation
class CoinRowWalletController: UITableViewCell{
//Referencias de outlets
@IBOutlet weak var icon: UIImageView!
@IBOutlet weak var coin: UILabel!
@IBOutlet weak var symbol: UILabel!
@IBOutlet weak var price: UILabel!
@IBOutlet weak var quantity: UILabel!
}
<file_sep>
import UIKit
class UnderlinedTextField: UITextField {
private let underline = CALayer()
private func setupUnderline() {
// Borramos los bordes que tienen los UITextField por defecto.
borderStyle = .none
// Borramos los horrorosos bordes que tienen los UITextField por defecto.
let lineWidth: CGFloat = 1.0
underline.borderColor = UIColor.lightGray.cgColor
underline.frame = CGRect(
x: 0,
y: frame.size.height - lineWidth,
width: frame.size.width,
height: frame.size.height
)
underline.borderWidth = lineWidth
// Añadimos la línea a la pila de capas (layer stack)3
layer.addSublayer(underline)
layer.masksToBounds = true
}
override func setNeedsLayout() {
super.setNeedsLayout()
setupUnderline()
}
}
<file_sep>//
// CircleCellClass.swift
// CryptoniteCev
//
// Created by user177260 on 1/21/21.
// Copyright © 2021 user177257. All rights reserved.
//
import UIKit
protocol CircleCellDelegate: class {
// Funcion delegado que tendrá la refencia de la instancia `UICollectionViewCell`
func collectionViewCell(_ cell: UICollectionViewCell, buttonTapped: UIButton)
}
class CircleCell: UICollectionViewCell {
static var index = 0
var isLoaded = false
let bg: UIButton = {
let circularButton = UIButton()
//estetica de los botones
circularButton.frame = CGRect(x: 160, y: 100, width: 50, height: 50)
circularButton.translatesAutoresizingMaskIntoConstraints = false
circularButton.clipsToBounds = true
circularButton.layer.cornerRadius = 0.8 * circularButton.bounds.size.width
circularButton.setImage(images[CircleCell.index], for: .normal)
circularButton.imageView?.contentMode = .scaleAspectFill
circularButton.layer.borderColor = #colorLiteral(red: 0.262745098, green: 0.8509803922, blue: 0.7411764706, alpha: 1)
circularButton.layer.borderWidth = 3
return circularButton
}()
override init(frame: CGRect) {
super.init(frame: .zero)
//estetica de la vista
contentView.addSubview(bg)
bg.topAnchor.constraint(equalTo: contentView.topAnchor).isActive = true
bg.leftAnchor.constraint(equalTo: contentView.leftAnchor).isActive = true
bg.rightAnchor.constraint(equalTo: contentView.rightAnchor).isActive = true
bg.bottomAnchor.constraint(equalTo: contentView.bottomAnchor).isActive = true
CircleCell.index += 1
bg.addTarget(self, action: #selector(thumbsUpButtonPressed), for: .touchUpInside)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
@objc func thumbsUpButtonPressed(_ sender: UIButton){
sender.layer.borderColor = #colorLiteral(red: 0.2549019754, green: 0.2745098174, blue: 0.3019607961, alpha: 1)
}
}
<file_sep>import Foundation
class AboutCoins{
let coins:[String:String]
private init() {
//información que aparecera en la pantalla de la moneda
self.coins = ["Bitcoin":"The world’s first cryptocurrency, Bitcoin is stored and exchanged securely on the internet through a digital ledger known as a blockchain. Bitcoins are divisible into smaller units known as satoshis — each satoshi is worth 0.00000001 bitcoin.",
"Ethereum": "Ethereum is a decentralized computing platform that uses ETH (also called Ether) to pay transaction fees (or “gas”). Developers can use Ethereum to run decentralized applications (dApps) and issue new crypto assets, known as Ethereum tokens.",
"Litecoin": "Litecoin is a cryptocurrency that uses a faster payment confirmation schedule and a different cryptographic algorithm than Bitcoin.",
"DogeCoin":"Dogecoin is a cryptocurrency that was created as a joke — its name is a reference to a popular Internet meme. It shares many features with Litecoin. However, unlike Litecoin, there is no hard cap on the number of Dogecoins that can be produced."]
}
static let shared = AboutCoins()
}
<file_sep>//
// userMessages.swift
// Agenda
//
// Created by alumnos on 05/02/2021.
// Copyright © 2021 <NAME>. All rights reserved.
//
import Foundation
class UserMessages {
static let shared = UserMessages()
private init(){}
//mensajes para mostrar al user
let noMatchingPasswords = "Passwords do not match"
let unknownUser = "This user does not exist"
let passwordChanged = "Password succesfully changed"
let invalidEmail = "Please enter a valid email"
let invalidName = "Please enter a valid name"
let invalidPass = "Please enter a valid password"
let invalidUsername = "Please enter a valid username"
}
<file_sep>import UIKit
extension UITextField
{
/**
Comprueba validación dependiendo del tipo, en caso de no ser correcto hace animación y lanza error de validación
*/
func validatedText(_ validationType: ValidatorType) throws
{
do
{
try text?.validatedText(validationType)
}
catch let validationError
{
shake()
throw validationError
}
}
// MARK:- Private Methods
/**
Animación de agitar
*/
private func shake()
{
let animation = CABasicAnimation(keyPath: "position")
animation.duration = 0.1
animation.repeatCount = 5
animation.fromValue = NSValue(cgPoint: CGPoint(x: center.x + 6, y: center.y))
animation.toValue = NSValue(cgPoint: CGPoint(x: center.x - 6, y: center.y))
layer.add(animation, forKey: "position")
}
}
<file_sep>import Foundation
class Endpoints {
private init() {}
let shared = Endpoints()
static let domain = "http://52.90.76.43"
static let path = "/api-cryptonite/public/api"
//User´s endpoints
enum User {
static let register:String = "/users/register"
static let login:String = "/users/login"
static let restorePassword:String = <PASSWORD>"
static let updatePassword:String = "/users/update/password"
static let getProfileInfo:String = "/users/profile/info"
static let updateProfile:String = "/users/update"
static let followUser:String = "/users/follow"
static let getFollowings:String = "/users/followings/list"
static let updateExperience:String = "/users/update/exp"
static let getFollowers:String = "/users/followers/list"
static let trade:String = "/users/trade/coin"
static let all:String = "/users/list"
static let userTrades:String = "/users/trades/info"
static let userProfileTrades:String = "/users/trades/profile/info"
static let someonesInfo:String = "/users/info"
static let stopFollowing:String = "/users/stop/following"
static let assignNewMission:String = "/users/assign/mission"
static let missionFinished:String = "/users/update/mission"
static let gamification:String = "/users/gamification"
static let updateMission:String = "/users/update/mission"
static let getMissions:String = "/users/missions"
}
//Score´s endpoints
enum Score {
static let getScores:String = "/scores/list"
}
//Trading´s endpoints
enum Trading{
static let getTradingHistory:String = "/trades/history"
}
//Deposit´s endpoints
enum Wallet{
static let getInfo:String = "/wallets/info"
static let deposit:String = "/wallets/deposit/doge"
static let cash:String = "/wallets/cash"
static let percentages:String = "/wallets/percentages"
static let percentagesOwn:String = "/wallets/percentages/own"
}
//Currency´s endpoints
enum Coin{
static let getList:String = "/coins/list"
static let getPrice:String = "/coins/get/price"
static let convertQuantity:String = "/coins/convert/quantity"
static let history:String = "/coins/history"
static let quantities:String = "/coins/quantities"
static let coinInfo:String = "/coins/info"
}
}
<file_sep>//
// TradeScreenTableViewExtension.swift
// CryptoniteCev
//
// Created by alumnos on 03/03/2021.
// Copyright © 2021 user177257. All rights reserved.
//
import Foundation
import UIKit
import SkeletonView
extension TradingController: SkeletonTableViewDataSource, UITableViewDelegate {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return trades.count
}
func collectionSkeletonView(_ skeletonView: UITableView, cellIdentifierForRowAt indexPath: IndexPath) -> ReusableCellIdentifier {
return "trades"
}
//Rellena los labels e imagenes de los tradeos con la info recibida de la petición
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "trades") as! TradesRow
if trades.count > 0 {
if trades[indexPath.row].isSell == 0 {
cell.buyOrSellImage.image = #imageLiteral(resourceName: "buy")
roundingQuantity = 100
}else{
cell.buyOrSellImage.image = #imageLiteral(resourceName: "sell")
roundingQuantity = setRounding(symbol: trades[indexPath.row].coin)
}
cell.coinLabel.text = trades[indexPath.row].coin + "/USD"
cell.tradeDateLabel.text = String(trades[indexPath.row].date)
cell.amountLabel.text = currencyFormatter(numberToFormat: round(roundingQuantity * trades[indexPath.row].quantity) / roundingQuantity)
cell.priceLabel.text = currencyFormatter(numberToFormat: trades[indexPath.row].price)
}
return cell
}
}
<file_sep>//
// Identifiers.swift
// Agenda
//
// Created by <NAME> on 4/2/21.
// Copyright © 2021 <NAME>. All rights reserved.
//
import Foundation
class Identifiers {
private init() {}
static let shared = Identifiers()
//identificadores que se usaran a lo largo de la app
let coinID = "coinID"
let toDetail = "toDetail"
let toMain = "toMain"
let toCompletion = "toCompletion"
let signUp = "signup"
let auth = "Authorization"
let stories = "stories"
let logout = "logout"
}
<file_sep>import UIKit
import Charts
class PieChart: UIViewController, ChartViewDelegate{
public func impirmirGrafica(pieChart: PieChartView, screen: UIView, percentages: [String:Double]){
pieChart.frame = CGRect(
x: 0,y: 0,
width: screen.frame.width,
height: screen.frame.height
)
//Estilo del piechart
pieChart.drawHoleEnabled = false
screen.addSubview(pieChart)
pieChart.topAnchor.constraint(equalTo: screen.topAnchor, constant: screen.frame.height).isActive = true
pieChart.leadingAnchor.constraint(equalTo: screen.leadingAnchor, constant: screen.frame.width).isActive = true
pieChart.trailingAnchor.constraint(equalTo: screen.trailingAnchor, constant: -screen.frame.width).isActive = true
pieChart.heightAnchor.constraint(equalToConstant: screen.frame.height).isActive = true
var entries:[PieChartDataEntry] = []
var colorsGraph:[NSUIColor] = []
//Coloca los colores y los entries de forma ordenada para luego ser mostrados correctamente
for (name, value) in percentages {
entries.append(PieChartDataEntry(value: value, label: name))
colorsGraph.append(Colors.shared.graph[name]!)
}
let set = PieChartDataSet(entries: entries)
//colores
let valueColor = NSUIColor(red: 0/255.0, green: 0/255.0, blue: 0/255.0, alpha: 0.95)
let labelEntryColor = NSUIColor(red: 0/255.0, green: 0/255.0, blue: 0/255.0, alpha: 0.95)
set.colors = colorsGraph
set.valueColors = [valueColor]
set.entryLabelColor = labelEntryColor
//labels con porcentajes
let formatter = NumberFormatter()
formatter.numberStyle = .percent
formatter.maximumFractionDigits = 1
formatter.multiplier = 1.0
let data = PieChartData(dataSet: set)
data.setValueFormatter(DefaultValueFormatter(formatter:formatter))
pieChart.data = data
}
}
<file_sep>
import Foundation
import UIKit
class UserMain {
private var _profilePic:UIImage
private var _username:String
private var _experience:Double
enum CodingKeys: String, CodingKey {
case _profilePic = "profilePic"
case _username = "username"
case _experience = "experience"
}
init(profilePic:UIImage, username:String, experience:Double){
self._profilePic = profilePic
self._username = username
self._experience = experience
}
public var profilePic: UIImage{
set {
self._profilePic = newValue
}
get{
return self._profilePic
}
}
public var username: String {
set {
self._username = newValue
}
get {
return self._username
}
}
public var experience: Double {
set {
self._experience = newValue
}
get {
return self._experience
}
}
}
<file_sep>//
// SkeletonableAnim.swift
// CryptoniteCev
//
// Created by alumnos on 15/03/2021.
// Copyright © 2021 user177257. All rights reserved.
//
import UIKit
import SkeletonView
class SkeletonableAnim: UIViewController {
//estilo del placeholder
public func placeholder(view : UIView){
view.isSkeletonable = true
let animation = GradientDirection.leftRight.slidingAnimation()
let gradient = SkeletonGradient.init(baseColor: .wetAsphalt)
view.showAnimatedGradientSkeleton(usingGradient: gradient, animation: animation)
}
//apaga placehiolder
public func hidePlaceholder(view : UIView){
view.stopSkeletonAnimation()
view.hideSkeleton()
}
}
<file_sep>//
// GamificationController.swift
// CryptoniteCev
//
// Created by alumnos on 04/03/2021.
// Copyright © 2021 user177257. All rights reserved.
//
import UIKit
import SwiftConfettiView
import CircleProgressBar
import NotificationBannerSwift
import BLTNBoard
import Lottie
class GamificationController: UIViewController {
@IBOutlet var circleProgressBar: CircleProgressBar!
@IBOutlet var levelLabel: UILabel!
@IBOutlet var missionsCard: UIView!
@IBOutlet var walletCard: UIView!
var viewConfetti: SwiftConfettiView?
@IBOutlet weak var mission1Button: UIButton!
@IBOutlet weak var mission2Button: UIButton!
@IBOutlet weak var mission3Button: UIButton!
@IBOutlet var profileImage: UIImageView!
@IBOutlet weak var cashLabel: UILabel!
@IBOutlet weak var mission1Image: UIImageView!
@IBOutlet weak var mission1Label: UILabel!
@IBOutlet weak var mission2Image: UIImageView!
@IBOutlet weak var mission2Label: UILabel!
@IBOutlet weak var mission3Image: UIImageView!
@IBOutlet weak var mission3Label: UILabel!
@IBOutlet var toWalletButton: UIButton!
@IBOutlet var logoutButton: UIButton!
@IBOutlet weak var welcomeLabel: UILabel!
var onDoneBlock : (() -> Void)?
var didLogout : (() -> Void)?
var mainClass:MainScreenController?
var experience : Double = 0
let experiencePerMission : Double = 200
let startingReward:Double = 250
var level : Int = 0
var prevLevel : Int = 0
var cash:Double = 0
var prevBalance:Double = 0
var missions:[Mission] = []
let anim = SkeletonableAnim()
//Al pulsar el boton de completar mision se realiza la peticion de asignar nueva mision, se recibe la nueva experiencia, se comprueba el nivel, realiza la peticion de actualizar la experiencia del usuario, comprueba el nivel y coloca la barra de progreso
@IBAction func mission1Cleared(_ sender: UIButton) {
assigNewMission(parameters: ["id":String(missions[0].id)])
getExperience()
level = levelManagement()
updateUser()
checkHasLeveledUp()
setProgressLabel()
}
//Al pulsar el boton de completar mision se realiza la peticion de asignar nueva mision, se recibe la nueva experiencia, se comprueba el nivel, realiza la peticion de actualizar la experiencia del usuario, comprueba el nivel y coloca la barra de progreso
@IBAction func mission2Cleared(_ sender: UIButton) {
assigNewMission(parameters: ["id":String(missions[1].id)])
getExperience()
level = levelManagement()
updateUser()
checkHasLeveledUp()
setProgressLabel()
}
//Al pulsar el boton de completar mision se realiza la peticion de asignar nueva mision, se recibe la nueva experiencia, se comprueba el nivel, realiza la peticion de actualizar la experiencia del usuario, comprueba el nivel y coloca la barra de progreso
@IBAction func mission3Cleared(_ sender: UIButton) {
assigNewMission(parameters: ["id":String(missions[2].id)])
getExperience()
level = levelManagement()
updateUser()
checkHasLeveledUp()
setProgressLabel()
}
//actualiza la experiencia del user y realiza la peticion de depositar doges si se ha subido de nivel
func updateUser() {
updateExp(parameters: ["new_exp" : Int(experience)])
if level != prevLevel {
deposit(parameters: ["quantity":calculateReward(level: level)])
}
}
//Boton que te conduce hacia la pantalla de wallet
@IBAction func toWalletButton(_ sender: Any) {
self.dismiss(animated: true) {
self.onDoneBlock!()
}
}
//este boton te redirige a la pantalla de login
@IBAction func logout(_ sender: UIButton) {
UserDefaults.standard.removeObject(forKey: Identifiers.shared.auth)
self.dismiss(animated: true) {
self.didLogout!()
}
}
//AL iniciarse el view imprime la barra de progreso, redondea los botones, se colocan los textos en los labels y crea el view de confetti
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Rewards"
circleProgressBar.setProgress(0.0, animated: false)
roundButton(button: mission1Button)
roundButton(button: mission2Button)
roundButton(button: mission3Button)
roundButton(button: toWalletButton)
roundButton(button: logoutButton)
self.levelLabel.text = String(Int(level))
self.viewConfetti = SwiftConfettiView(frame: self.view.bounds)
self.viewConfetti?.tag = 200
missionsCard.layer.cornerRadius = 7
walletCard.layer.cornerRadius = 7
profileImage.layer.cornerRadius = profileImage.frame.width / 2
profileImage.layer.borderWidth = 4
profileImage.layer.borderColor = #colorLiteral(red: 0.262745098, green: 0.8509803922, blue: 0.7411764706, alpha: 1)
anim.placeholder(view: cashLabel)
anim.placeholder(view: mission1Label)
anim.placeholder(view: mission2Label)
anim.placeholder(view: mission3Label)
}
//Al aparecer el view se realizan las peticiones de cash y gamificacion que rellenaran los datos de los labels de usuario y misiones
override func viewDidAppear(_ animated: Bool) {
getCash(fromMain: true)
getGamification()
bulletinManager.backgroundColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
bulletinManager.backgroundViewStyle = .dimmed
}
//redondea un boton
func roundButton(button: UIButton) {
button.layer.cornerRadius = 7
}
//inicia el confetti
func startConfetti(view: SwiftConfettiView){
self.view.addSubview(self.viewConfetti!)
view.startConfetti()
}
//apaga el confetti
func stopConfetti(view: SwiftConfettiView){
DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
view.stopConfetti()
let confeti = self.view.viewWithTag(200)
confeti!.removeFromSuperview()
self.setProgressLabel()
}
}
//al reclamar el premio se ejecuta el confetti
func claimRewards() {
self.startConfetti(view: self.viewConfetti!)
self.stopConfetti(view: self.viewConfetti!)
}
//experiencia necesaria para subir de nivel
func neededExperience(level: Int) -> Double {
if level != 0 {
return neededExperience(level: level-1) + Double(level) * self.experiencePerMission
}
return 0
}
//nueva experiencia al subir de nivel
func getExperience(){
experience += experiencePerMission
}
//devuelve nivel del user
func levelManagement()->Int {
prevLevel = level
var n = 0
while true {
if experience < neededExperience(level: n) {
return n
}
n += 1
}
}
//devuelve nivel del user
func getCurrentLvl(experience:Double)->Int{
var n = 0
var level:Int = 0
while true {
if experience < neededExperience(level: n) {
level = n
return level
}
n += 1
}
}
//si el usuario ha subido de nivel se modifica el progress bar con animacion y el label de nivel
func checkHasLeveledUp(){
if level != prevLevel {
self.claimRewards()
prevLevel = level
DispatchQueue.main.async {
self.circleProgressBar.setProgress(CGFloat(1), animated: true)
Banners.shared.levelUpBanner(title: "Congrats! You have just reached level " + String(Int(self.level)))
DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
self.bulletinManager.showBulletin(above: self)
}
}
}
self.levelLabel.text = String(Int(level))
}
//se coloca la experiencia en el progress bar
func setProgressLabel() {
let progress = (experience - neededExperience(level: level-1)) / (neededExperience(level: level) - neededExperience(level: level - 1))
self.circleProgressBar.setProgress(CGFloat(progress), animated: true)
}
//funcion que realiza la peticion para recibir los datos de la pantalla de gamificacion, tanto missiones como user
func getGamification(){
if isConnected {
if (UserDefaults.standard.string(forKey: Identifiers.shared.auth) != nil) {
let request = Service.shared.gamification()
request.responseJSON { (response) in
if let body = response.value as? [String:Any] {
if(response.response?.statusCode == StatusCodes.shared.OK){
attemptsMaxed = false
if let data = body["data"] as? [String:Any]{
let missions = data["Missions"] as! [[String:Any]]
let userInfo = data["User"] as! [String:Any]
let user = UserMain(profilePic: Images.shared.users[(userInfo["ProfilePic"] as? Int)!], username: (userInfo["Username"] as? String)!, experience: (userInfo["Exp"] as? Double)!)
self.missions = []
for i in 0..<missions.count{
self.missions.append(Mission(id: missions[i]["id"] as! Int, icon: Missions.shared.missions[missions[i]["icon"] as! Int], description: missions[i]["description"] as! String, isFinished: missions[i]["is_finished"] as! Int))
}
self.setMissions()
self.experience = user.experience
self.level = self.getCurrentLvl(experience: user.experience)
self.setProgressLabel()
self.profileImage.image = user.profilePic
self.welcomeLabel.text = "Good earnings @" + user.username
self.levelLabel.text = String(self.level)
self.anim.hidePlaceholder(view: self.mission1Label)
self.anim.hidePlaceholder(view: self.mission2Label)
self.anim.hidePlaceholder(view: self.mission3Label)
}
}else{
attemptsMaxed = true
if !unknownBanner.isDisplaying{
unknownBanner.show()
}
}
}
}
}
}
}
//Coloca las misiones en los labels e imagenes
func setMissions(){
mission1Label.text = missions[0].description
mission1Image.image = missions[0].icon
if missions[0].isFinished == 0{
mission1Button.backgroundColor = #colorLiteral(red: 0.2, green: 0.2235294118, blue: 0.2784313725, alpha: 1)
mission1Button.isEnabled = false
}else{
mission1Button.backgroundColor = #colorLiteral(red: 0.262745098, green: 0.8509803922, blue: 0.7411764706, alpha: 1)
mission1Button.isEnabled = true
}
mission2Label.text = missions[1].description
mission2Image.image = missions[1].icon
if missions[1].isFinished == 0{
mission2Button.backgroundColor = #colorLiteral(red: 0.2, green: 0.2235294118, blue: 0.2784313725, alpha: 1)
mission2Button.isEnabled = false
}else{
mission2Button.backgroundColor = #colorLiteral(red: 0.262745098, green: 0.8509803922, blue: 0.7411764706, alpha: 1)
mission2Button.isEnabled = true
}
mission3Label.text = missions[2].description
mission3Image.image = missions[2].icon
if missions[2].isFinished == 0{
mission3Button.backgroundColor = #colorLiteral(red: 0.2, green: 0.2235294118, blue: 0.2784313725, alpha: 1)
mission3Button.isEnabled = false
}else{
mission3Button.backgroundColor = #colorLiteral(red: 0.262745098, green: 0.8509803922, blue: 0.7411764706, alpha: 1)
mission3Button.isEnabled = true
}
}
//peticion que recibe el cash del usuario logged
func getCash(fromMain:Bool){
if isConnected {
if (UserDefaults.standard.string(forKey: Identifiers.shared.auth) != nil) {
let request = Service.shared.getCash()
request.responseJSON { (response) in
if let body = response.value as? [String:Any] {
if(response.response?.statusCode == StatusCodes.shared.OK){
attemptsMaxed = false
if let data = body["data"] as? String{
if fromMain{
self.cash = Double(data)!
self.prevBalance = self.cash
self.cashLabel.text = currencyFormatterTwoDecimals(numberToFormat: Double(self.cash)) + " $"
}else{
self.prevBalance = self.cash
self.cash = Double(data)!
for i in 1...Int(self.calculateReward(level: self.level)) {
DispatchQueue.main.asyncAfter(deadline: .now() + 0.01 * Double(i) ) {
if self.cash > self.prevBalance {
self.prevBalance += 0.5
self.cashLabel.textColor = #colorLiteral(red: 0.262745098, green: 0.8509803922, blue: 0.7411764706, alpha: 1)
self.cashLabel.text = currencyFormatterTwoDecimals(numberToFormat: Double(self.prevBalance)) + " $"
}else{
self.cashLabel.text = currencyFormatterTwoDecimals(numberToFormat: Double(self.cash)) + " $"
self.cashLabel.textColor = #colorLiteral(red: 0.2, green: 0.2235294118, blue: 0.2784313725, alpha: 1)
}
}
}
}
self.cashLabel.text = currencyFormatterTwoDecimals(numberToFormat: self.cash) + " $"
self.anim.hidePlaceholder(view: self.cashLabel)
}
}else{
attemptsMaxed = true
if !unknownBanner.isDisplaying{
unknownBanner.show()
}
}
}
}
}
}
}
//asigna una nueva mision al hacer claim rewards
func assigNewMission(parameters:[String:String]){
missions = []
if isConnected {
if (UserDefaults.standard.string(forKey: Identifiers.shared.auth) != nil) {
let request = Service.shared.assignNewMission(params: parameters)
request.responseJSON { (response) in
if let body = response.value as? [String:Any] {
if(response.response?.statusCode == StatusCodes.shared.OK){
attemptsMaxed = false
if let data = body["data"] as? [[String:Any]]{
for i in 0..<data.count{
self.missions.append(Mission(id: data[i]["id"] as! Int, icon: Missions.shared.missions[data[i]["icon"] as! Int], description: data[i]["description"] as! String, isFinished: data[i]["is_finished"] as! Int))
}
self.setMissions()
}
}else{
attemptsMaxed = true
if !unknownBanner.isDisplaying{
unknownBanner.show()
}
}
}
}
}
}
}
//peticion que actualiza la experiencia al terminar una mision
func updateExp(parameters:[String:Int]){
missions = []
if isConnected {
if (UserDefaults.standard.string(forKey: Identifiers.shared.auth) != nil) {
let request = Service.shared.updateExp(params: parameters)
request.responseJSON { (response) in
if let body = response.value as? [String:Any] {
if(response.response?.statusCode != StatusCodes.shared.OK){
attemptsMaxed = false
if !unknownBanner.isDisplaying{
unknownBanner.show()
}
}
}
}
}
}
}
//peticion que deposita doges en el wallet del usuario al subir de nivel
func deposit(parameters:[String:Double]){
if isConnected {
if (UserDefaults.standard.string(forKey: Identifiers.shared.auth) != nil) {
let request = Service.shared.desposit(params: parameters)
request.responseJSON { (response) in
if let body = response.value as? [String:Any] {
if(response.response?.statusCode != StatusCodes.shared.OK){
attemptsMaxed = false
if !unknownBanner.isDisplaying{
unknownBanner.show()
}
}
}
}
}
}
}
//calcula el premio recibido
func calculateReward(level:Int)-> Double{
return startingReward + (Double(level) * startingReward/2)
}
//muestra el bulletin de doge al subir de nivel
lazy var bulletinManager: BLTNItemManager = {
let page = showClaimLevelBanner()
return BLTNItemManager(rootItem: page)
}()
//muestra el banner de reclamar doges al subir de nivel, ademas de recibir el nuevo dinero actualizado
func showClaimLevelBanner() -> BLTNPageItem {
let page = BLTNPageItem(title: "To the moooon!!")
page.image = #imageLiteral(resourceName: "dogecoin128")
page.appearance.titleTextColor = #colorLiteral(red: 0.07058823529, green: 0.1215686275, blue: 0.2078431373, alpha: 1)
page.appearance.descriptionTextColor = #colorLiteral(red: 0.07058823529, green: 0.1215686275, blue: 0.2078431373, alpha: 1)
page.appearance.actionButtonColor = #colorLiteral(red: 0.262745098, green: 0.8509803922, blue: 0.7411764706, alpha: 1)
page.appearance.actionButtonCornerRadius = 7
page.requiresCloseButton = false
page.descriptionText = "Congratulations you have just received some DOGES. Keep digging!"
page.actionButtonTitle = "Shut up and give me my money!"
page.actionHandler = { (item: BLTNActionItem) in
self.getCash(fromMain: false)
self.bulletinManager.dismissBulletin()
}
return page
}
}
<file_sep>//
// TabBarController.swift
// CryptoniteCev
//
// Created by <NAME> on 5/3/21.
// Copyright © 2021 user177257. All rights reserved.
//
import Foundation
import UIKit
class TabBarController:UITabBarController{
/**
Iniciará como primera pantalla el index 1 del tab bar que será la main screen
*/
override func viewDidLoad() {
self.selectedIndex = 1
}
}
<file_sep># Uncomment the next line to define a global platform for your project
# platform :ios, '9.0'
target 'CryptoniteCev' do
# Comment the next line if you don't want to use dynamic frameworks
use_frameworks!
pod 'Alamofire', '~> 5.2'
pod 'Charts'
pod 'SwiftConfettiView'
pod 'CircleProgressBar', '~> 0.32’
pod 'NotificationBannerSwift', '~> 3.0.0'
pod 'BulletinBoard'
pod 'lottie-ios'
# Pods for CryptoniteCev
end
<file_sep>//
// Missions.swift
// CryptoniteCev
//
// Created by alumnos on 09/03/2021.
// Copyright © 2021 user177257. All rights reserved.
//
import Foundation
import UIKit
class Missions{
static let shared = Missions()
private init(){}
//Listado de imagenes que representará una mission
let missions = [#imageLiteral(resourceName: "023-coin stacks"), #imageLiteral(resourceName: "009-bitcoin tag"), #imageLiteral(resourceName: "034-trading"), #imageLiteral(resourceName: "049-currency exchange"), #imageLiteral(resourceName: "045-digital investment"), #imageLiteral(resourceName: "021-Litecoin"), #imageLiteral(resourceName: "008-cryptovault"), #imageLiteral(resourceName: "038-bitcoin presentation"), #imageLiteral(resourceName: "044-investors"), #imageLiteral(resourceName: "004-bitcoin up"), #imageLiteral(resourceName: "027-digital wallet"), #imageLiteral(resourceName: "047-global"), #imageLiteral(resourceName: "010-bitcoin encryption"), #imageLiteral(resourceName: "002-bitcoin wallet")]
}
<file_sep>
import Foundation
import UIKit
class CoinCellMainController: UICollectionViewCell {
//referencias de outlets
@IBOutlet weak var iconImageView: UIImageView?
@IBOutlet weak var coinNameLabel: UILabel?
@IBOutlet weak var ammountLabel: UILabel?
@IBOutlet weak var percentageLabel: UILabel?
}
<file_sep>//
// MainScreenController.swift
// CryptoniteCev
//
// Created by alumnos on 21/01/2021.
// Copyright © 2021 user177257. All rights reserved.
//
import UIKit
import SkeletonView
import BLTNBoard
class MainScreenController: UIViewController {
var storiesCollection: UICollectionView?
var coinsCollection : UICollectionView?
var usersCollection : UICollectionView?
@IBOutlet weak var coinCollectionView: UICollectionView!
@IBOutlet weak var usersCollectionView: UICollectionView!
@IBOutlet weak var storiesCollectionView: UICollectionView!
@IBOutlet weak var activityTableView: UITableView!
var coins:[Coin] = []
var trades:[TradeHistory] = []
var users:[UserMain] = []
var followings:[UserStories] = [UserStories(profilePic: Images.shared.users[0], username: "")]
var coinImages:[UIImage] = []
var coinNames:[String] = []
let experiencePerMission : Double = 200
let anim = SkeletonableAnim()
/**
Al iniciarse el view comprueba las misiones de register y login pone el estilo oscuro, modifica los delegdos de los collection y tableviews y actualiza el feed de tradeos
*/
override func viewDidLoad() {
view.overrideUserInterfaceStyle = .dark
isMissionFinished(parameters: ["id":"13"])
isMissionFinished(parameters: ["id":"2"])
storiesCollectionView.dataSource = self
storiesCollectionView.delegate = self
coinCollectionView.dataSource = self
coinCollectionView.delegate = self
usersCollectionView.dataSource = self
usersCollectionView.delegate = self
activityTableView.dataSource = self
activityTableView.delegate = self
activityTableView.rowHeight = 68
activityTableView.estimatedRowHeight = 68
anim.placeholder(view: activityTableView)
self.activityTableView.reloadData()
/**
Rellena el tableview de monedas como placeholders cuando no haya conexión
*/
for (key, value) in Images.shared.coins {
coinNames.append(key)
coinImages.append(value)
}
//muestra banner de no conexion si no hay conexion
if !Service.isConnectedToInternet{
isConnected = false
connectionBanner.show()
}
}
//al aparecer el view realiza las peticiones de followings, monedas, usuarios y trades
override func viewDidAppear(_ animated: Bool) {
fillFollowings()
getCoins()
getUsers()
tradingHistory()
}
//Peticion de recibir monedas
func getCoins(){
if isConnected {
if (UserDefaults.standard.string(forKey: Identifiers.shared.auth) != nil) {
let requestCoins = Service.shared.getCoins()
requestCoins.responseJSON { (response) in
if let body = response.value as? [String: Any]{
if(response.response?.statusCode == StatusCodes.shared.OK){
attemptsMaxed = false
let data = body["data"] as! [[String:Any]]
self.coins = []
for i in 1..<data.count {
self.coins.append(Coin(name: (data[i]["Name"] as? String)!, symbol: (data[i]["Symbol"]! as? String)!, price: (data[i]["Price"] as? Double)!, change: (data[i]["Change"] as? Double)!))
}
self.coinCollectionView.reloadData()
}else{
attemptsMaxed = true
if !unknownBanner.isDisplaying{
unknownBanner.show()
}
}
}
}
}
}
}
//Petición de recibir todos los trades
func tradingHistory(){
if isConnected {
if (UserDefaults.standard.string(forKey: Identifiers.shared.auth) != nil) {
let requestTrades = Service.shared.getTradingHistory()
requestTrades.responseJSON { (response) in
if let body = response.value as? [String: Any]{
if(response.response?.statusCode == StatusCodes.shared.OK){
attemptsMaxed = false
let data = body["data"]! as! [[String:Any]]
self.trades = []
for i in 0..<data.count {
self.trades.append(TradeHistory(coinFrom: (data[i]["Coin_from"] as? String)!, coinTo: (data[i]["Coin_to"] as? String)!,coinFromSymbol: (data[i]["Coin_from_symbol"] as? String)! , coinToSymbol: (data[i]["Coin_to_symbol"] as? String)!, quantity: (data[i]["Quantity"] as? Double)!, username: (data[i]["Username"] as? String)!, converted: (data[i]["Converted"] as? Double)!, profilePic: (data[i]["Profile_pic"] as? Int)!))
}
self.activityTableView.reloadData()
self.anim.hidePlaceholder(view: self.activityTableView)
}else{
attemptsMaxed = true
if !unknownBanner.isDisplaying{
unknownBanner.show()
}
}
}
}
}
}
}
//Recibe todos los usuarios
func getUsers(){
if isConnected {
if (UserDefaults.standard.string(forKey: Identifiers.shared.auth) != nil) {
let requestUsers = Service.shared.getUsers()
requestUsers.responseJSON { (response) in
if let body = response.value as? [String: Any]{
if(response.response?.statusCode == StatusCodes.shared.OK){
attemptsMaxed = false
let data = body["data"]! as! [[String:Any]]
self.users = []
for i in 0..<data.count {
self.users.append(UserMain(profilePic: Images.shared.users[(data[i]["ProfilePic"] as? Int)!], username: (data[i]["Username"] as? String)!, experience: (data[i]["Exp"] as? Double)!))
}
self.usersCollectionView.reloadData()
}else{
attemptsMaxed = true
if !unknownBanner.isDisplaying{
unknownBanner.show()
}
}
}
}
}
}
}
//Peticion de rellenar los followings
func fillFollowings(){
followings = [UserStories(profilePic: Images.shared.users[0], username: "")]
if isConnected {
if (UserDefaults.standard.string(forKey: Identifiers.shared.auth) != nil) {
let request = Service.shared.getFollowings()
request.responseJSON { (response) in
if let body = response.value as? [String:Any] {
if(response.response?.statusCode == StatusCodes.shared.OK){
attemptsMaxed = false
if let data = body["data"] as? [[String:Any]]{
for i in 0..<data.count{
self.followings.append(UserStories(profilePic: Images.shared.users[data[i]["profile_pic"] as! Int], username: data[i]["username"] as! String))
}
self.storiesCollectionView.reloadData()
}
}else{
attemptsMaxed = true
if !unknownBanner.isDisplaying{
unknownBanner.show()
}
}
}
}
}
}
}
}
<file_sep>import Foundation
import UIKit
class UserStories {
private var _profilePic:UIImage
private var _username:String
enum CodingKeys: String, CodingKey {
case _profilePic = "profilePic"
case _username = "username"
}
init(profilePic:UIImage, username:String){
self._profilePic = profilePic
self._username = username
}
public var profilePic: UIImage{
get{
return self._profilePic
}
}
public var username: String {
get {
return self._username
}
}
}
<file_sep>
import Foundation;
import UIKit;
class CoinsQuantities : Decodable, Encodable{
private var _name:String
private var _symbol:String
private var _quantity:Double
private var _inDollars:Double
init(name:String, symbol:String, quantity:Double, inDollars:Double){
self._name = name
self._symbol = symbol
self._quantity = quantity
self._inDollars = inDollars
}
public var name: String {
get {
return self._name;
}
set {
self._name = newValue
}
}
public var symbol: String {
get {
return self._symbol;
}
set {
self._symbol = newValue
}
}
public var quantity: Double {
get {
return self._quantity;
}
set {
self._quantity = newValue
}
}
public var inDollars: Double {
get {
return self._inDollars;
}
set {
self._inDollars = newValue
}
}
}
<file_sep>
import UIKit
class SignUpController: UIViewController {
@IBOutlet weak var backButton: UINavigationItem!
@IBOutlet weak var continue_button: UIButton!
@IBOutlet weak var emailTF: UnderlinedTextField!
@IBOutlet weak var passwordTF: UnderlinedTextField!
@IBOutlet weak var usernameTF: UnderlinedTextField!
@IBOutlet weak var nameTF: UnderlinedTextField!
let identifiers = Identifiers.shared
@IBOutlet weak var isAdultSW: UISwitch!
/**
Al iniciarse el view por primera vez el botón de continuar se redondea y
se llama a la función que permitirá cerrar el teclado
*/
override func viewDidLoad() {
super.viewDidLoad()
self.hideKeyboardWhenTappedAround()
continue_button.layer.cornerRadius = 5
}
/**
Al aparecer el view el botón se habilita y el nav controller aparece
*/
override func viewDidAppear(_ animated: Bool) {
continue_button.isEnabled = true
navigationController?.setNavigationBarHidden(false, animated: true)
}
/**
Al pulsar el botón de continuar, se comprueban los datos introducidos, si son correcto se llama a la petición de registrar, en caso de ser erróneos se mostrará el mensaje en forma de banner y se habilitará el botón de continuar
*/
@IBAction func ContinueButton(_ sender: Any) {
if checkEmail(textFieldEmail: emailTF) && checkPassword(textFieldPass: <PASSWORD>){
if isAdultSW.isOn{
let user = User(username: usernameTF.text!, email: emailTF.text!, name: nameTF.text!, password: <PASSWORD>!, profilePic: Int.random(in: 0..<Images.shared.users.count))
register(user: user)
}else {
Banners.shared.errorBanner(title: "You have to agree our Terms and conditions ", subtitle: "Try again")
continue_button.isEnabled = true
}
}
}
/**
Función engargada de mostrar el banner una vez te registres correctamente
*/
func showBanner(completion: @escaping (_ success: Bool) -> Void, message: String) {
Banners.shared.successBanner(title: message, subtitle: "Log in now!")
DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
completion(true)
}
}
/**
Función que se encargará de las peticiones de registro con las comprobaciones necesarias además de llevarte a login una vez esto ocurra correctamente, en caso de ocurrir cualquier error se mostrará un mensaje en forma de banner
*/
func register(user:User){
if isConnected {
let request = Service.shared.register(user: user)
continue_button.isEnabled = false
request.responseJSON { (response) in
if let body = response.value as? [String:Any]{
if(response.response?.statusCode == StatusCodes.shared.OK){
self.showBanner(completion: { (success) in
if success {
attemptsMaxed = false
self.continue_button.isEnabled = true
self.goToLogInScreen()
}
}, message: body["message"]! as! String)
}else{
let errorMessages = body["message"] as! [String:[String]]
let firstKey = Array(errorMessages.keys).first
Banners.shared.errorBanner(title: (errorMessages[firstKey!]?.first)!, subtitle: "Try again")
self.continue_button.isEnabled = true
}
}
}
}
}
/**
Ibaction que te llevará a la pantalla de login una vez se pulse el botón de "log in"
*/
@IBAction func goToLogIn(_ sender: Any) {
navigationController?.popToRootViewController(animated: true)
}
/**
Función que te devolverá a la pantalla de login
*/
func goToLogInScreen() {
navigationController?.popToRootViewController(animated: true)
}
}
<file_sep>
import Foundation;
import UIKit;
class Coin : Decodable, Encodable{
private var _name:String
private var _symbol:String
private var _price:Double
private var _change:Double
init(name:String, symbol:String, price:Double, change:Double){
self._name = name
self._symbol = symbol
self._price = price
self._change = change
}
public var name: String {
get {
return self._name;
}
set {
self._name = newValue
}
}
public var symbol: String {
get {
return self._symbol;
}
set {
self._symbol = newValue
}
}
public var price: Double {
get {
return self._price;
}
set {
self._price = newValue
}
}
public var change: Double {
get {
return self._change;
}
set {
self._change = newValue
}
}
}
| fcc73469d08eb62356e9bd803613a85c292eae91 | [
"Swift",
"Ruby"
] | 54 | Swift | CryptoniteCEV/app-cryptonite | 401d33302e19ec1724cfc2774c1a8b07da5f39b1 | 9cd05fddd75bb888e964bfa9921aa5d96f74a8cc |
refs/heads/master | <file_sep># Generated by Django 2.2.7 on 2019-12-05 06:37
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('TechnicalCourses', '0004_allcourses_startedfrom'),
]
operations = [
migrations.AlterField(
model_name='allcourses',
name='startedfrom',
field=models.DateTimeField(verbose_name='Started from'),
),
]
<file_sep>from django.test import TestCase
import datetime
from django.utils import timezone
from .models import Allcourses
class AllcoursesModelTests(TestCase):
def test_was_published_recently_with_future_course(self):
time = timezone.now() + datetime.timedelta(days=30)
future_question = Allcourses(startedfrom=time)
self.assertIs(future_question.was_published_recently(), False)
def test_was_published_recently_with_old_course(self):
time = timezone.now() - datetime.timedelta(days=1, seconds=1)
old_course = Allcourses(startedfrom=time)
self.assertIs(old_course.was_published_recently(), False)
def test_was_published_recently_with_recent_course(self):
time = timezone.now() - datetime.timedelta(hours=23, minutes=59, seconds=59)
recent_course = Allcourses(startedfrom=time)
self.assertIs(recent_course.was_published_recently(), True)
<file_sep>django==2.2.7
pip==19.3.1
pytz==2019.3
setuptools==28.8.0
sqlparse==0.3.0
| bf2594051ad5978f6a43b78a399ab260e84987b8 | [
"Python",
"Text"
] | 3 | Python | shinystaratnight/djangorest-website-serializer | 76644c6ee7ef78ac57bdded0c9a889e4bc7143a6 | c5fcfe8cb1197ef6b150b51607150cc1dfaea873 |
refs/heads/master | <file_sep>var ReasonReact = require("reason-react/lib/js/src/reasonReact.js")
var ReactMotion = require('react-motion')
exports.motion = function (props) {
var motionProps = Object.assign({}, props)
delete motionProps.render
return ReasonReact.wrapJsForReason(ReactMotion.Motion, motionProps, props.render)
}
exports.staggeredMotion = function (props) {
var motionProps = Object.assign({}, props)
delete motionProps.render
return ReasonReact.wrapJsForReason(ReactMotion.StaggeredMotion, motionProps, props.render)
}
exports.staggeredMotion = function (props) {
var motionProps = Object.assign({}, props)
delete motionProps.render
return ReasonReact.wrapJsForReason(ReactMotion.StaggeredMotion, motionProps, props.render)
}
exports.spring = function (value, _config) {
let config = Object.keys(_config)
.filter(function (key) {
return _config[key] !== undefined
})
.reduce(function (acc, key) {
acc[key] = _config[key]
return acc
}, {})
return ReactMotion.spring(value, config)
}; | 0dca030ecabb60d43a8b6fe912f260e96ea7a4a1 | [
"JavaScript"
] | 1 | JavaScript | SentiaAnalytics/bs-react-motion | 4e90b2d56347b92d25d924b57df8c61449c4c8fc | e41a1ce368a2714da956ee1e556d7cb81ccdf250 |
refs/heads/master | <repo_name>alokedip20/AI_LAB<file_sep>/Assignment3/8puzzle.py
import sys
goal_state = [1,2,3,8,0,4,7,6,5]
FLAG = 0
class node:
def __init__(self, state,parent,move,depth,h_val,node_cost):
self.state = state
self.parent = parent
self.move = move
self.depth = depth
self.heuristic_value = h_val
self.cost = node_cost
def create_node(state,parent,move,depth,h_val = 0,node_cost = 0):
return node(state,parent,move,depth,h_val,node_cost)
def generate_children(node,open_list,close_list):
children = []
children.append(create_node(tile_up(node.state),node,'up',node.depth + 1,heuristic(tile_up(node.state),goal_state , FLAG)))
children.append(create_node(tile_down(node.state),node,'down',node.depth + 1,heuristic(tile_down(node.state),goal_state , FLAG)))
children.append(create_node(tile_left(node.state),node,'left',node.depth + 1,heuristic(tile_left(node.state),goal_state , FLAG)))
children.append(create_node(tile_right(node.state),node,'right',node.depth + 1,heuristic(tile_right(node.state),goal_state , FLAG)))
children = [child for child in children if child.state != None]
children = [child for child in children if not member_o(child,open_list)]
children = [child for child in children if not member_c(child,close_list)]
return children
def member_c(i,close_list,flag = 0):
for index,elem in enumerate(close_list):
if i.state == elem.state:
if not flag:
print (str(index)+' element is in close list : '+str(i.state))
return True
return False
def member_o(i,open_list):
for index,elem in enumerate(open_list):
if i.state == elem.state:
print (str(index)+' element is in open list : '+str(i.state))
return True
return False
def tile_up(state):
modified_state = state[:]
index = modified_state.index(0)
if index not in [0,1,2]:
temp = modified_state[index -3]
modified_state[index - 3] = modified_state[index]
modified_state[index] = temp
return modified_state
return None
def tile_down(state):
modified_state = state[:]
index = modified_state.index(0)
if index not in [6,7,8]:
temp = modified_state[index + 3]
modified_state[index + 3] = modified_state[index]
modified_state[index] = temp
return modified_state
return None
def tile_left(state):
modified_state = state[:]
index = modified_state.index(0)
if index not in [0,3,6]:
temp = modified_state[index - 1]
modified_state[index - 1] = modified_state[index]
modified_state[index] = temp
return modified_state
return None
def tile_right(state):
modified_state = state[:]
index = modified_state.index(0)
if index not in [2,5,8]:
temp = modified_state[index + 1]
modified_state[index + 1] = modified_state[index]
modified_state[index] = temp
return modified_state
return None
def display(Node):
s = Node.state
print('------------------- H = '+ str(Node.heuristic_value) + ' ----------------------------')
print(str(s[0]) + "\t" + str(s[1]) + "\t" + str(s[2]))
print(str(s[3]) + "\t" + str(s[4]) + "\t" + str(s[5]))
print(str(s[6]) + "\t" + str(s[7]) + "\t" + str(s[8]))
def dfs(start,goal,limit = 20):
open_list = []
close_list = []
open_list.append(create_node(start,None,None,1))
comparison = 0
while True:
if len(open_list) == 0:
return None , 0
node = open_list.pop(0)
if not member_c(node,close_list):
close_list.append(node)
if node.state == goal:
temp = node
moves = []
while True:
if temp.depth == 1:
break
else:
moves.insert(0,temp.move)
temp = temp.parent
return moves , comparison
else:
comparison += 1
if node.depth < limit :
gen_children = generate_children(node,open_list,close_list)
gen_children.extend(open_list)
open_list = gen_children
def bfs(start,goal):
open_list = []
close_list = []
open_list.append(create_node(start,None,None,1))
comparison = 0
while True:
if len(open_list) == 0:
return None , 0
else:
node = open_list.pop(0)
if not member_c(node,close_list):
close_list.append(node)
if node.state == goal:
temp = node
moves = []
while True:
if temp.depth == 1:
break
else:
moves.insert(0,temp.move)
temp = temp.parent
return moves , comparison
comparison += 1
open_list.extend(generate_children(node,open_list,close_list))
def iterative_deepening(start,goal,limit = 20):
level = 1
comparison = 0
while True:
Moves , comparison = dfs(start,goal,level)
if Moves == None:
level += 1
if level > limit:
return None
else:
return Moves , comparison
def hill_climbing(start,goal,limit = 20):
open_list = []
close_list = []
open_list.append(create_node(start,None,None,1))
comparison = 0
while True:
if len(open_list) == 0:
return None , 0
node = open_list.pop(0)
if not member_c(node,close_list):
close_list.append(node)
if node.state == goal:
temp = node
moves = []
while True:
if temp.depth == 1:
break
else:
moves.insert(0,temp.move)
temp = temp.parent
return moves , comparison
if node.depth < limit:
comparison += 1
gen_children = generate_children(node,open_list,close_list)
gen_children.sort(custom_cmp)
gen_children.extend(open_list)
open_list = gen_children
def best_first(start,goal):
open_list = []
close_list = []
open_list.append(create_node(start,None,None,1))
comparison = 0
while True:
if len(open_list) == 0:
return None , 0
node = open_list.pop(0)
if not member_c(node,close_list):
close_list.append(node)
if node.state == goal:
temp = node
moves = []
while True:
if temp.depth == 1:
break
else:
moves.insert(0,temp.move)
temp = temp.parent
return moves , comparison
comparison += 1
gen_children = generate_children(node,open_list,close_list)
open_list.extend(gen_children)
open_list.sort(custom_cmp)
def a_star(start,goal):
open_list , close_list = [],[]
open_list.append(create_node(start,None,None,1))
heuristic_score = heuristic(start,goal,FLAG)
comparison = 0
while True:
if len(open_list) == 0:
return None , 0
open_list.sort(custom_cmp_astar)
local_optimum_node = open_list.pop(0)
if local_optimum_node.state == goal:
temp = local_optimum_node
moves = []
while True:
if temp.depth == 1:
break
else:
moves.insert(0,temp.move)
temp = temp.parent
return moves , comparison
comparison += 1
successor = generate_children(local_optimum_node,[],[])
for child in successor:
child.cost = local_optimum_node.cost + (child.depth - local_optimum_node.depth)
child_fscore = child.cost + heuristic(child,goal,FLAG)
if child.state == goal:
temp = child
moves = []
while True:
if temp.depth == 1:
break
else:
moves.insert(0,temp.move)
temp = temp.parent
return moves , comparison
elif member_o(child,open_list):
comparison += 1
old_child = [i for i in open_list if i.state == child.state][0]
old_child_fscore = old_child.cost + heuristic(old_child,goal,FLAG)
if child_fscore < old_child_fscore:
old_child.parent = local_optimum_node
old_child.cost = child_fscore
elif member_c(child,close_list):
comparison += 1
old_child = [i for i in close_list if i.state == child.state][0]
old_child_fscore = old_child.cost + heuristic(old_child,goal,FLAG)
if child_fscore < old_child_fscore:
open_list.append(child)
else:
comparison += 1
open_list.append(child)
close_list.append(local_optimum_node)
def heuristic(state,goal,flag):
if not flag:
return manhattan(state,goal)
return hamming_distance(state,goal)
def hamming_distance(state,goal):
distance = 0
try:
for i in range(9):
if state[i] != 0 and goal[i] != 0 and state[i] != goal[i]:
distance += 1
return distance
except :
return distance
def manhattan(state,goal):
distance = 0
try:
for i in range(1,9):
state_x,state_y = index_pos(state.index(i))
goal_x,goal_y = index_pos(goal.index(i))
distance += abs(goal_x - state_x) + abs(goal_y - state_y)
return distance
except:
return 0
def custom_cmp(i,j):
return (i.heuristic_value - j.heuristic_value)
def custom_cmp_astar(i,j):
return ((i.depth + i.heuristic_value) - (j.depth + j.heuristic_value))
def index_pos(index):
return (int(index / 3) , index % 3)
def solvable(state):
inv = 0
for i in range(8):
for j in range(i+1,9):
if state[i] and state[j] and state[i] > state[j]:
inv += 1
if inv % 2 != 0: #based upon goal state...... inv must be either in odd space or even space..
return True
return False
def main():
initial_state = [int(a) for a in raw_input('Give the initial state: ').split()]
if not solvable(initial_state):
print ('Not solvable')
return 0
algorithms = ['dfs','bfs','iterative_deepening','best_first','a_star','hill_climbing']
comparison = 0
for al in algorithms:
cmd = 'press any key to run the algo: ' + al
raw_input(cmd)
algorithm = eval(al)
Moves , comparison = algorithm(initial_state,goal_state)
if Moves == None:
print ('No path found')
else:
print ('Goal node has been found by '+ al + ' with comp = ' + str(comparison))
print (Moves)
if __name__ == '__main__':
main()<file_sep>/Assignment4/tictactoe.py
import random
human , computer = 'o','x'
computer_win , human_win = 20,-20
INF = float('inf')
def board_full(board):
for cell in board:
if cell == '_':
return False
return True
def evaluation_board_state(board):
for i in [0,3,6]:
if ((board[i] == board[i+1]) and (board[i+1] == board[i+2])):
if board[i] == human:
return human_win
elif board[i] == computer:
return computer_win
for i in [0,1,2]:
if ((board[i] == board[i+3]) and (board[i+3] == board[i+6])):
if board[i] == human:
return human_win
elif board[i] == computer:
return computer_win
if board[0] == board[4] and board[4] == board[8]:
if board[0] == human:
return human_win
elif board[0] == computer:
return computer_win
if board[2] == board[4] and board[4] == board[6]:
if board[2] == human:
return human_win
elif board[2] == computer:
return computer_win
return 0
def minimax(board,depth,ismax,alpha,beta):
score = evaluation_board_state(board)
if score == computer_win:
#print ('found goal node for win or loose is = '+str(depth))
return score - depth
if score == human_win:
return score + depth
if board_full(board):
#print ('found goal node for draw is = '+str(depth))
return 0
if ismax:
best = -INF
for i in range(9):
if board[i] == '_':
board[i] = computer
best = max(best,minimax(board,depth + 1,not ismax,alpha,beta))
board[i] = '_'
alpha = max(alpha,best)
if beta <= alpha:
#print ('Alpha Beta pruning occured')
break
return best
else:
best = INF
for i in range(9):
if board[i] == '_':
board[i] = human
best = min(best,minimax(board,depth + 1,not ismax,alpha,beta))
board[i] = '_'
beta = min(beta,best)
if beta <= alpha:
#print ('Alpha Beta pruning occured')
break
return best
def best_move(board):
best_val = -INF
optimum_cell = -1
for i in range(9):
if board[i] == '_':
board[i] = computer
move_val = minimax(board,0,False,-INF,INF)
board[i] = '_'
if move_val > best_val:
optimum_cell = i
best_val = move_val
print ("Best Val: "+str(best_val))
return optimum_cell,best_val
def initialise_board():
return ['_'] * 9
def valid_move(board,index):
return board[index] == '_'
def display_board(board):
print (board[0] + '\t' + board[1] + '\t' + board[2])
print (board[3] + '\t' + board[4] + '\t' + board[5])
print (board[6] + '\t' + board[7] + '\t' + board[8])
def main():
board = initialise_board()
chance = random.randint(1,101)
if chance % 2 == 0:
print ('Computer will start.... better luck next time')
cell , score = best_move(board)
board[cell] = computer
display_board(board)
while True and not board_full(board):
human_move = int(raw_input('Give index in between 0 - 9 : \n'))
if valid_move(board,human_move):
board[human_move] = human
opt_cell,score = best_move(board)
print ('Computer chooses cell : '+str(opt_cell))
board[opt_cell] = computer
if score == computer_win:
print('Computer wins')
display_board(board)
return 0
elif score == human_win:
print ('Human wins')
display_board(board)
return 0
else:
display_board(board)
else:
print ('Not a valid move')
print ('Draw match')
if __name__ == '__main__':
main()
| 8e6b35d2fab8118c42d2850f2064d89298fa95d2 | [
"Python"
] | 2 | Python | alokedip20/AI_LAB | 551edff7e7ac302df76cf32707d480ec867d8393 | 04553a2d14f3bae9985813f455d493b90b588171 |
refs/heads/master | <repo_name>ZHNLN0/js_fullStack<file_sep>/js/leetcode/LRU/readme.md
LRU 缓存 最近最少使用原则
Least Recently Used
操作系统
node fs 硬盘,内存
内存有一定的大小,比较精贵
硬盘用不完
内存是代码的运行空间 空间有限
假如现在空间为2 存放变量 2个
第三个变量
<!-- 1 put(1)
2 put(2)
3 放不下了 -->
[] 数组 内存2就是 length 2
原则:最近最少使用
1 put(1,1)
2 put(2,2)
3 get(1) 从内存中取出值 返回1 1最近使用了 2最近最少使用
4 put(3,3) 3进去了,2就要丢掉
5 get(2)拿不到
6 put(4,4) 431 1丢掉
假如内存是数组 怎么实现?
7 get(1)拿不到 返回-1
8 get(3) 3
9 get(4) 4
- cache 内存 LRUCache 实现
get
put
- 对象字面量有利于get put方法的实现
- 最近最少使用,JSON搞不定
数组可以,有头有尾有下标 [0] [length -1]
在一头进行操作 需要操作的unshift添加至头部 越靠近头部的使用最频繁,越靠近尾部的越少使用
一半的工作交给数组,一半的工作交给jsonObject对象字面量
让它们成为LRUCache的两个属性
- get set arr + obj 组织在LRUCache
indexOf pop unshift splice
<file_sep>/CSS/stylus/xiaoce/README.md
不再写CSS,写的是CSS的预编译语言stylus
stylus有以下能力:
快
一套语法,支持现代CSS开发,compile过程
stylus style.styl -o style.css -o output 输出的
stylus -w style.styl -o style.css -w watch 一直监听文件的修改,实时的生成CSS文件
1. 跟CSS的规则说拜拜 不需要 {} : ; 需要的是tab键
2. stylus 提供嵌套功能 可以帮我们补上前面的选择器 现在我们的CSS就模块化了 从此CSS就有编程的感觉了
3. &运算符 依然使用tab缩进,但是他与上一级同级,适合于同一个元素多个类名,.active 或者伪类,伪状态
4. 变量定义 将常用的,重复使用(CSS不是编程语言,表达性的) 在最上面统一定义后,可以修改一处,所有使用了此变量的地方都会跟着修改。 成为网站的风格。
CSS 语法
1. overflow:hidden
2. flex alihn-items 搞定vertical-align 又是不好搞的情况 vertical-align 兄弟之间 img + 兄弟
3. text-randering:optimizeLegibility; 抗锯齿 高清手机上文字的边缘不出现锯齿
4. flex-shrink:0 flex-grow
5. 第几个元素的选择 :first-child :last-child :nth-child(2n) :nth-child(2n+1)
6. -apple-system<file_sep>/js/node/event/index.js
const Events = require('events');
const ev = new Events();
const request = require('./lib/request.js');
const Player = require('player')
// ev.on('search')
['search','choose'].forEach(evName => { //forEach 循环绑定
const fn = require(`./lib/${evName}`)
ev.on(evName, async function (...args) {
const res = await fn(...args);
ev.emit('handle', evName,res,...args)
// console.log(res);
})
})
ev.on('afterSearch', (res, keyWord) => {
if (!res.result || !res.result.songs) {
console.log(`没有搜到${keyWord}的信息`);
return false;
}
const songs = res.result.songs;
ev.emit('choose',songs);
})
ev.on('afterChoose', async (selected, songs) => {
const selectSong = songs.find((song, i) => {
return selected == `${i}${song.name}`
})
if(selectSong) {
const {id} = selectSong;
// 请求歌曲详情
let url = 'http://neteasecloudmusicapi.zhaoboy.com/song/url?id=347230' + id;
const songDetail = await request(url);
const {url: songUrl} = songDetail.data[0];
const Player = new player(songUrl);
Player.player();
}
})
ev.on('handle', (key, res, ...args) => {
switch (key) {
case 'search':
return ev.emit('afterSearch', res, args[0])
case 'choose':
return ev.emit('afterChoose', res, args[0])
}
})
function main() {
// 在一个进程模块里面 process在node中是一个全局变量 截取这个数字组中的第三项 歌名
const argv = process.argv.slice(2);
let keyWord = argv[0];
ev.emit('search', keyWord);
// console.log(keyWord);
}
main();
<file_sep>/vue-learn/vuex-counter/README.md
## vue 最难的是数据管理 mvvm
- 1.0时代,组件在我们阳历是最大的,data() 私有状态,自给自足的状态 不足以成为一个应用
- 2.0时代,很多的组件,组建的层次及关系,兄弟组件,共享数据的时候找到共同的父组件,管理这个状态,通过prop+emit 方式 登陆状态
- 3.0时代 vuex 简单项目不要用他,管理应用状态 2.0太麻烦, 跨组件,跨层级,轻松共享应用状态,
很多组件,多个路由,要共享的状态太多时,它太有用了。<file_sep>/wxapp/CAX/README.md
小程序 canvas 找 cax
引入 cax组件
new cax.Stage()
cax.Rect
add
update
- countdown 组件
文案,获取验证码 开始计时
false || true
Page 为组件的调用者 properties
组件 data(内部) + properties(外界传入)
<countdown start="{{start}}">
- properties 有个observer选项
当外界选的值改变时,会执行
组建是构成页面的,是为页面打工的
- start 由外传到内properties
有利于页面操作关键状态
内部组件通知页面?可以做<file_sep>/INTERVIEW-QUESTIONS/Q11/README.md
- 冒泡排序
O(n^2)
O(nlogN)<file_sep>/js/skill/flatten.js
const _ = require('lodash');
const arr1 = [99, 0, 33, [101, 202, [303]], 1, 2];
const arr2 = [2, 1, 2];
const flattenArr1 = _.flattenDeep(arr1);
console.log(flattenArr1);
const users = [
{ user: 'fred', age: 48},
{ user: 'barney', age: 36},
{ user: 'fred', age: 40},
{ user: 'barney', age: 34},
]
const sortedUser = _.sortBy(users, ['user','age']);
console.log(sortedUser);<file_sep>/js/33-js-concepts/this_call_bind/README.md
- 阮一峰的继承
先继承构造函数的属性
构造函数被new 的方式运行 this 指向实例对象
子类要拿到父类构造函数属性,父类构造函数运行一下,call/apply 指定this为子类对象
- call/apply的区别
手动指定函数内部this的指向
参数用法不一样,偏向于用apply,[] arguments
- this 函数内部的this
有运行的方式决定,而非声称是决定
1. 普通函数
2. 对象的方法
3. call apply 指定
4. 构造函数
5. 事件回调函数内部 this 会时事件发生的对象
6. bind 指定this 返回新的函数,<file_sep>/js/leetcode/valid_parentheses/index.js
let arr = []; //数据集合
arr.push("{");
arr.push("}");
console.log(arr);
arr.pop();
console.log(arr);
arr.unshift("]");
console.log(arr);
arr.shift();
console.log('--------------',arr);
arr.forEach(item =>{
console.log(item);
})
<file_sep>/vue-learn/vue-router-demo/history_api/README.md
- 理论支持
SPA 单页应用开发,导航(nav)不动,footer也不动,中间body(main,content)时切换的,页面不需要刷新的
传统web开发中,空白(新的web请求) 页(get) 白一下,加载一下,这个体验很糟糕,对应路由,把相应组件切换出来,像APP一样。
- jquery on 时间api
$(document).on(event_type, child_nodes, fn);
- 没有前端路由,但是可以通过后端路由 (restful, mvc router) /xxx.html
- 前端路由两种做法,hashtag #
history pushState api url path 部分改变了,但是没有刷新页面。
state? 这次跳转url对应的状态数据
title,
url, <file_sep>/wxapp/todos/README.md
- wxml 是模板,{{}} 是要被编译的,用户看到的不是wxml,是wxml被js data 填充编译后的页面
Page 不是wxml 是 wxml + js + wxss 合体 compile
- setData({
相应数据时,
}) 触发重新compile
- 我们会在wxml里把所有的逻辑及对数据的渴求都表达,在某一刻页面只会显示当前状态的页面状态 跟数据相关
状态 由数据决定
改变数据, setData 界面自动变,数据驱动的界面 MVVM
数据要和界面状态唯一
- todos
健身
表单
js dom + todos [] appendChild
data: {
todos: []
}
form submit this.setData()
- {{js 运行区域}}
- input 有意思?<file_sep>/scorecode/jquery/README.md
DOM 树 有html结构,再加上css,DOM树将被生成,静态页面就有了。
document DOMContentLoaded 有了元素节点就可以做js的交互了
页面上还依赖于其他的一些资源 js,阻塞下载,img 是网页性能的杀手
window.onload 此时写js 就晚了
如果不等事件的发生,js操作有可能无效<file_sep>/CSS/jd-2018-campus/README.md
## css
- text-indent: 首行文本缩进 有利于seo<file_sep>/js/node/spider-ajax/README.md
## 传统后端渲染的页面
html 分析
## spa
<div id="app"></div>
全靠js生成的
无头浏览器
headless browser
看不到界面的浏览器 用代码操作他
<file_sep>/vue-learn/element-starter/src/utils/axios.js
import Vue from 'vue'
import axios from 'axios'
import VueAxios from 'vue-axios'
export default function({
}) {
}<file_sep>/INTERVIEW-QUESTIONS/index.js
// function Person(name) {
// this.name = name
// }
// let p = new Person('wn')
// 1. p.__proto__等于什么 Person.prototype
// 2. Person.__proto__ == Function.prototype
// 实例的__proto__等于其构造函数的prototype
// var foo = {},
// F = function() {};
// Object.prototype.a = 'valA'
// Function.prototype.b = 'valB'
// console.log(foo.a)
// console.log(foo.b)
// console.log(F.a)
// console.log(F.b)
// function Person(name) {
// this.name = name
// return 666
// }
// let p = new Person('wn')
// console.log(p)
// ---------- 构造函数是不需要返回值的,使用new来创建对象时,
// 如果return的非对象类型,会忽略返回值,如果return 的是对象,则返回该对象
// 若return null 也会忽略返回值
// function Student() {
// }
// Student.prototype = Person.prototype
// Student.prototype.constructor = Student
// let s = new Student('wn')
// console.log(s instanceof Person)
// for(let i = 0; i < 10; i++) {
// setTimeout(() => {
// console.log(i)
// },0)
// }
// for(var i = 0; i < 10; i++) {
// (function(i) {
// setTimeout(() => {
// console.log(i)
// }, 0);
// })(i)
// }
// ------- let 每次循环会生成一个封闭的作用域和setTimeoit绑定,var每次循环会覆盖点上一次的作用域
// Array.prototype.method = function() {
// console.log('wn')
// }
// var myArr = [1, 2, 3, 4, 5, 6, 7]
// myArr.name = 'wn'
// for (let index of myArr) {
// console.log(index)
// }
// for in
// 1. index 索引为字符串型的数字,不能直接进行集合运算
// 2. 遍历顺序有可能不是按照实际数组的内部顺序进行的
// 3. for in 会遍历数组所有可枚举的属性,包括原型链,所以for in 跟适合遍历对象
// for of
// 1. for in 遍历的是数组的索引,for of 遍历的数组的元素
// 2. for of 遍历的知识数组内的元素,而不包括数组原型属性和索引
let gArr = [1, 2, [3, 4], 5, [2, 7, [3, 9]]]
let oArr = [1, 2, 3, 4, 5, 2, 7, 3, 9]
// function outputArr(arr) {
// let res = []
// for(let i = 0; i < arr.length; i++) {
// if(Array.isArray(arr[i])) {
// res = res.concat(outputArr(arr[i]))
// } else {
// res.push(arr[i])
// }
// }
// return res
// }
function outputArr(arr) {
return arr.reduce(function(pre, item) {
return pre.concat(Array.isArray(item) ? outputArr(item) : item)
}, [])
}
console.log(outputArr(gArr))
<file_sep>/js/leetcode/sort/index.js
function bubbleSort(arr) {
let len = arr.length, temp;
for(var i = 0; i < len; i++) {
for(var j = 0; j < len -1 -i; j++) {
if(arr[j] > arr[j + 1]) {
temp = arr[j + 1]
arr[j + 1] = arr[j]
arr[j] = temp
}
}
}
return arr
}
console.log(bubbleSort([3,6,8,5,3,4,2]))<file_sep>/js/ES6/arrow-function/README.md
## 怎么用
- 只有一个参数省略括号
- 函数只有一条语句省略{} return 返回对象时候 ()
## arguments
- 所有函数中(除了箭头函数)都有可用的局部变量
- [arg1,arg2,arg3]
## 普通函数箭头函数 区别
- 箭头函数不支持重名形参,普通函数可以
- 箭头函数没有 this , 它的 this 指向定义时所处的上下文(外部函数) this
- 箭头函数不能通过 .call .apply ... 改变箭头函数的 this
- 箭头函数没有 .prototype
- 箭头函数不能作为构造函数
- 箭头函数没有 arguments
- 箭头函数没有 new.target
## new.target
es6 新增 一般构造函数之内 返回 new 作用于的那个构造函数
## 类数组
- 有 length 属性
- 可以用过 索引 获取值
- Array.from 从类数组对象中创建一个新的数组<file_sep>/book/the_good_parts/chapter3.md
# 对象字面量学习笔记
- 对象字面量
1. JavaScript是弱类型,在定义数据是只用 let 数据类型的输出时用typeof可以确定定义后的具体数据类型,如数字,字符串,布尔值,null值和undefined。对象是容器,属性值可以除undefined外的任何值。
2. 对象字面量可以为空,属性名也可以用引号括住,对象是可以嵌套的。
- 检索
1. 对象字面量的检索式可以用表示法如 x["y"],优先考虑使用.表示法如 x.y.
2. 检索不存在的成员元素时,将返回undefined。也可以用 || 运算符代替,如 let a = x.y || "unkonwn" 由原来输出的undefined 输出为 unkonwn.
- 更新
1. 当属性名存在时,对象中的值可以用赋值来更新。
2. 没有属性名时,会添加到对象中。
- 引用
1. 举例 let a = b; z.x = 'str'; 对象不会被拷贝,通过引用来传递,即此时也存在 b.x == 'str';
2. let a = {},b = {},c = {};时每一个引用不同的空对象,而 let a=b=c={};是a,b,c 引用同一个空对象。
- 原型
1. 对象可以以一个对象为原型,当对该对象更新时,原型不更新。当原型添加一个属性时,所有基于该原型的对象可见。
2. 原型连接的检索时,如果该对象没有时会一直向上一个原型检索,如果最后不存在那么结果是undefined。
- 反射
1. typeof 可以确定属性的类型,但是原型链中的任何属性也会产生一个值。
2. hasOwnProperty方法对对象中有独立的属性则返回 true ,不会检查原型链。
- 枚举
1. for in 会发掘原型链中的属性,而 for 不会,同时可以使用 typeof 等方法进一步得到想要的属性。
- 删除
1. delete 删除不会删除原型链中的对象。
- 减少全局变量的污染
1. 全局变量消弱程序的灵活性,只创建一个全局变量作为容器。<file_sep>/js/node/http_server/main.js
// require 关键字 引入一个模块,COMMONJS
const http = require('http');
let i = 0;
http
.createServer(function(request,response) {
response.end(`hello world${++i}`);
})
.listen(8080);<file_sep>/js/node/spider-schedule-email/README.md
## $
x.find() 查找 x 元素下面的内容 $('.box').find('p');
\s 空白字符 .replace(/\s/g, "") 去除无用的空白符
## promise
proise.all([promise组成的数组])
返回一个promise 所有promise resolve 的时候 他才是 resolve
resolve 时候的值 就是 [所有promise] resolve 组成的数组
## 模板引擎
发漂亮的邮件 需要发送 html
html 不是静态的 需要数据填充
模板引擎 同理
编译成 html
MVC
jsp
node 模板引擎 承载页面 (view)
ejs jade
<%= %> 变量
<% %> js 执行<file_sep>/js/leetcode/swap_node/README.md
- 无编译 不代码
webpack 已经成为 工作流程的霸主
编译过程和js的promise异步
1. 代码写在 dev
2. 上线在build dist/
3. 启动web 服务器 webpack-dev-server
- webpack html template
plugin html-webpack-plugin
- log 不在根目录下,怎么找到它,多写点地址 ./utils/log.js
resolve -> module
rules
.js babel-loader
babel-core babel-cli babel-preset-env
babel-loader 有点兼容性
module
rules: [
{
test: /\.js$/,
use: 'babel-loader'
}
]
resolve: {
extensions: ['.js']
}
8080 webpack-dev-server html-webpack-plugin
template ./src/index.html
html + js
- webpack 一切皆可打包,打包到 js 里
css 对于js 来说就是个文本
img 对于js 打包成 base64
但是css 应该独立打包,性能优化的需要
main.js 显示值最慢的<file_sep>/CSS/algorithm/README.md
动态规划入门
老虎吃羊
500只老虎 1只羊
都吃草
虎可以吃羊,一只虎吃一只羊
吃完羊后,这只老虎会变成羊
会不会吃掉这只羊
找到规律后,可以递归,或类推
n
1. 吃什么羊,虎变羊 被欺
2. 吃,羊肉好吃
3. 不吃,羊那么可爱,
一只老虎 一只羊 吃
两只老虎 一只羊 不吃
三只老虎 一只羊 吃
四只老虎 一只羊 不吃
五只老虎 一只羊 吃
六只老虎 一只羊 不吃
奇数就吃,偶数就不吃 500 不吃
动态规划:大事化小,小事化了,找到规律,
最优子结构 上一次不吃,下一次就吃
边界 n = 1 吃 n =2 不吃 递归子结构
状态转移 F(n) = !F(n-1)
楼梯只有12阶,一步走一阶或两阶,请问走完楼梯多少种走法?
1. 边界 n = 1 1种,走一步 n = 2 2种
2. 子结构 n = 12时 ,有多少种走法
n - 1 = 11 一步 n - 2 = 10 2步
3. 状态转移公式
F(n) = F(n-1) + F(n-2)<file_sep>/koa/koa-block/README.md
- node开发常用npm包,以KOA为例
1. MVC koa koa-router koa-views koa-static
M mysql2 koa-masql-session koa-bodyparser (表单提交)
2. md5 加密 moment markdown-it chai 工具业务
<file_sep>/react/react-ant-practice/README.md
## touchStart
按下去的时候
opacity 0.6
## touchEnd
opacity 1
## ref
string ref
function ref
object ref
## 受控组件 非受控组件
<file_sep>/INTERVIEW/render/index.js
function render(tpl, data) {
// 1. 找到所有的{{}} regExp /{\{\(.+)\}\}/g
return tpl.replace(/\{\{(.+?)\}\}/g, function($1, $2) {
console.log($1, $2)
return data[$2]
})
}
var tmpl = `
<div>
<p>{{name}}</p>
<p>{{age}}</p>
</div>
`
console.log(render(tmpl, {name: '张三', age: 18})) <file_sep>/js/leetcode/tree/README.md
树是数据结构
节点构成
val
单链表 next
树 left right
- 根节点
- 叶子节点
- 边
- 节点 left right
- 满二叉树
- 完全二叉树
[[3], [9, 20], [15, 7]]
遍历
- 一次一层 队列
<file_sep>/js/table/README.md
form +table DOM 数据的表格化
专业版本
<file_sep>/react/context/README.md
## context
跨组件之间的数据传递
this.props
父 -> 子 -> 孙
父 -> 孙
被 react-router react-redux 广泛使用
16.0
## 问题
shouldComponentUpdate
尽可能少渲染
return true
return false 不更新
如果中间某个组件 shouldComponentUpdate false 后代组件不会更新
## context 16<file_sep>/js/game/snake/README.md
phaser 是游戏框架
canvas 绘图API<file_sep>/react/beer/README.md
- es6 class 新特性
ref = this.createRef()
ref = {this.ref}
- history html5 API
Search Main 的子组件
window.history
hoc props history
<Router><Search /></Router>
- 高阶组件
能返回组件的函数,接受组件做为参数,高阶组件
withRouter react-router-dom 封装一个组件并为之提供 this.props.location<file_sep>/js/qq/README.md
45
789
12345678
- 正则
确定待检测的字符是否正是符合规则的对象
js除了简单类型之外,一切都是对象
/ /正则对象RegExp
运算符号,用于表达规则[0-9]
[0-9]范围数字
[a-z]小写字母
[A-Z]大写字母
{5, 13}限定长度
^$字符串开始,字符串结束
631758924 加密
规则是第一个数删除,第二个数移动末尾,第三个数删除,第四个数移动到末尾,直到最后一个也删除
数组是最廉价的数据结构
本身就是一个线性的连续的存储空间 下标 head 指向头部 tail 指向尾部
尾部插入和删除 栈 先进后出
在头部删除,在尾部添加元素 队列 Queue 先进先出
<file_sep>/wxapp/miShopping/pages/category/category.js
// pages/category/category.js
const res = require('../../wxapi/request')
const app = getApp()
Page({
/**
* 页面的初始数据
*/
data: {
category: [],
curIndex: 0,
toView: "xinping",
scrollL: true,
scrollR: true,
topArr: [],
heightArr: [10, 735.4000244140625, 1395.800048828125, 2539.800048828125, 3483.60009765625, 4144, 4562.60009765625, 5046.2001953125, 5553.2001953125, 5948.39990234375, 6432, 6892.2001953125, 7310.80029296875, 7617.60009765625, 8254.6005859375, 8826.6005859375, 9398.6005859375, 9640.400390625, 9970.6005859375, 10212.400390625, 10696, 11114.6005859375, 11444.7998046875, 11686.6005859375, 11928.400390625, 12081.7998046875, 12323.6005859375]
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
this.getCategoryLeft()
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function () {
var that = this
setTimeout(function() {
var query = wx.createSelectorQuery()
//选择id
let topArr = []
query.selectAll('.categoryItem').boundingClientRect(function(rect) {
console.log('------------------',rect)
rect.forEach((item) => {
// console.log(item.top)
topArr.push(item.top)
})
console.log(topArr)
that.setData({
topArr: topArr
})
console.log(that.data.topArr)
}).exec()
},2000)
},
getCategoryLeft() {
res
.loadCategory()
.then((res) => {
console.log(res,'----',this)
this.setData({
category: res.data
})
})
},
switchTab(e) {
console.log(e)
this.setData({
curIndex: e.target.dataset.index,
toView: e.target.dataset.id
})
},
onScroll(e){
console.log(e)
let self = this
let scrollTop = e.detail.scrollTop
let heightArr = self.data.heightArr
let length = heightArr.length
console.log(length)
for (let i = 0; i < length; i++) {
console.log(111)
if (scrollTop >= 0 && scrollTop < heightArr[0]) {
console.log(222)
this.setData({
curIndex: 0
})
} else if(scrollTop >= heightArr[i-1] && scrollTop < heightArr[i]) {
console.log(333)
this.setData({
curIndex: i
})
}
}
console.log(heightArr)
console.log(scrollTop)
console.log(this.data.curIndex)
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function () {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function () {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function () {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function () {
},
/**
* 用户点击右上角分享
*/
onShareAppMessage: function () {
}
})<file_sep>/vue-learn/full_history/READMD.md
前端路由实现方式 history.pushState(data, title, url) 改变url 的 path 部分,跟hashChange实现方案,不一样的地方是改变的url部位不一样(#home), 前端就可以处理路由了
像极了后端路由,支持前后切换,
浏览历史,history onpopstate
push pop 数组只在尾部操作,栈
<file_sep>/wxapp/LookWeather/miniprogram/lib/api.js
const QQ_MAP_KEY = '<KEY>'
wx.cloud.init({
env: 'zhn-wxapp-i44x0'
})
// 获取服务器句柄
const db = wx.cloud.database()
// 封装一个往服务器添加数据的 方法(添加心情)
// 提前写抛出
export const addEmotion = (openid, emotion) => {
return db.collection('diary').add({
data: {
openid,
emotion,
teModified: Date.now()
}
})
}
// 获取位置
export const geocoder = (lat, lon, success = () => { }, fail = () => { }) => {
return wx.request({
url: 'https://apis.map.qq.com/ws/geocoder/v1/',
data: {
location: `${lat},${lon}`,
key: QQ_MAP_KEY,
get_poi: 0
},
success,
fail
})
}
// 获取天气
export const getWeather = (lat, lon) => {
return wx.cloud.callFunction({
name: 'he-weather',
data: {
lat,
lon
}
})
}
// 往数据库里面查询到用户的openid和具体的时间段,然后获取信息
export const getEmotionByOpenidAndData = (openid, year, month) => {
const _ = db.command
year = passInt(year)
month = passInt(month)
let start = new Date(year, month - 1, 1).getTime()
let end = new Date(year, month, 1).getTime()
return db.collection('diary').where({
openid,
tsModified: _.get(start).and(_.lt(end))
})
.get()
}
export const jscode2session = (code) => {
return wx.cloud.callFunction({
name: 'jscode2sessio',
data: {
code
}
})
}<file_sep>/react/react-ant-practice/src/TouchableOpacity.jsx
import React, {Component} from 'react'
import './btn.css'
class TouchableOpacity extends Component {
state = {
active: false
}
handleStart = () => {
this.setState({
active: true
})
}
handleEnd = () => {
this.setState({
active: false
})
}
render() {
const {active} = this.state
const styleObj = {
opacity: active ? 0.3 : 1
}
return (
<div className="btn" style={styleObj} onTouchStart = {this.handleStart} onTouchEnd = {this.handleEnd}>
{this.props.children}
</div>
)
}
}
export default TouchableOpacity<file_sep>/wxapp/lol/pages/legends/legends.js
Page({
data: {
legends: [
{
name: '阿卡丽',
title: '刺客',
src: 'https://ossweb-img.qq.com/images/lol/img/champion/Akali.png'
},
{
name: '亚索',
title: '风男',
src: 'https://ossweb-img.qq.com/images/lol/img/champion/Yasuo.png'
},
{
name: '火男',
title: '法师',
src: 'https://ossweb-img.qq.com/images/lol/img/champion/Brand.png'
},
{
name: '盖伦',
title: '战士',
src: 'https://ossweb-img.qq.com/images/lol/img/champion/Garen.png'
},
{
name: '寒冰',
title: 'ADC',
src: 'https://ossweb-img.qq.com/images/lol/img/champion/Ashe.png'
}
]
}
})
<file_sep>/vue-learn/do_vuex_counter/README.md
- data 是组件自有数据,没有多少,思考会不会被共享,应用层共享的,只要多于一个组件要用,且关系鄙视简单的兄弟,就用vuex
- 共享状态,
vuex state 管理
mutatios 才能修改
actions 被触发动作,提交 mutations
getters 对state的包装
mapActions mapGetters 引入组件<file_sep>/react/react-state-flow/src/App.js
import React, { Component } from 'react';
import List from './list'
import CommentInput from './CommentInput'
import CommentList from './CommentList'
// import logo from './logo.svg';
import './App.css';
let generateID = 1
class App extends Component {
state= {
lists: [
{
name: 'tom1',
age: 19,
school: 'school1',
id: 0
},
{
name: 'tom2',
age: 19,
school: 'school2',
id: 1
}
],
commentList: []
}
handlePublish = (item) => {
// push 新数据 再 setState
const commentList = this.state.commentList.slice(0);
console.log(item)
commentList.push(item)
this.setState({
commentList
})
}
handleAddInfo = () => {
const lists = this.state.lists.slice(0);
generateID++;
lists.push({
name: 'tom2',
age: 19,
school: 'school2',
id: generateID
})
this.setState({
lists
})
}
handleListDelete = (id) => {
console.log('父组件收到id ', id)
const lists = this.state.lists.slice(0)
const index = lists.findIndex(list => list.id === id)
lists.splice(index, 1)
this.setState({
lists
})
}
render() {
const {lists, commentList} = this.state
return (
<>
<ul>
<button onClick={this.handleAddInfo}>
添加一条数据
</button>
{
lists.map((list, i) => {
return (
<List key={list.id} list = {list} onDelete={this.handleListDelete}/>
)
})
}
</ul>
<div>
<CommentInput onPublish={this.handlePublish}/>
{
commentList.map((comment, i) => {
return (
<CommentList Comment={comment} />
)
})
}
</div>
</>
)
}
}
export default App;
<file_sep>/js/node/cookie-session/README.md
## why
http 无状态的
客户端 服务器 再次请求的时候 知道客户端是谁
## -S
--save
放"dependencies": {}
npm i, 在json 文件里面寻找各个依赖并安装
本地开发 安装的 node_module
服务器上线 自需要写的代码 不需要 上传 node_module
## cookie
存在客户端:
js 操作:
doucument.cookie
后端:响应头
Set-Cookie: name=value; path=/user; httponly
浏览器检查需哦有存储的 cookie 把符合当前作用范围的cookie 放在 http 请求头发给服务器。
cookie 有可能被用户禁用
内容:
name
value
path: 规定 cookie 生效的路径
/ 所有的路径
/user /user 以及 /user/xxxx
/user/xxx /user/xxx 以及 /user/xxx/xxxx
httpOnly: true / false true 就不能通过 js 获取 cookie
max-age: 在几秒后过期
作用范围
path
domain
用途:会话的状态管理,保存用户的个性化设置
## session
保存在服务端
靠后台语言实现,
有很多个 session
有很多个用户 sessionID
## koa 第三方中间件
ctx req + res
ctx: {
req,
res
}
koa-viwes ejs
往 ctx 上面扩展 80%
ctx: {
req,
res,
rander: () => {}
}
调用提供的 rander()
##localSorage sessionStorage cookie session <file_sep>/js/leetcode/valid_parentheses/README.md
数值 字符串 布尔值 null undefined 基本数据类型
其他的都是Object Array 可遍历的对象
JSON Object 对象字面量 可枚举的对象 for()
function 也是对象
document.querySelectorAll('a'); 数组类
arr.push()
- 字符串是字符的数组 具有 .length str[0]
- 运算符匹配的问题是,选择数组作为数据结构,只在顶部做操作(push pop) 栈Stack
算法+数据结构
1. sta = [] 空 ( sta.push("(") 入栈
2. ) 栈不为空 跟顶部袁旭比较,如果是一对 顶部的元素pop() 或者 push为新的顶部
3. sta 为空 true |false
<file_sep>/wxapp/msgbox/README.md
- 组件思维
弹窗组合了一些标签,形成了独立的弹窗共能,在其他页面也要用到,组合一个人独立的组件
<dialog />
页面是由组件拼装而成的。
- 组件语法
同于Page 又有异
Component({
data: {},
properties: {
<!-- 属性类型定义 -->
title: {
type: String,
value: '标题'
}
},
methods: {
}
})
- bind tap 区别
bindtap 向外冒泡
catch:tap 不会<file_sep>/wxapp/wxapp-mi/pages/index/index.js
//index.js
//获取应用实例
const WXAPI = require('../../wxapi/main')
const app = getApp()
Page({
data: {
indicatorDots: true,
autoplay: true,
interval: 3000,
duration: 500,
indicatorColor: "#f4f4fd",
indicatorActiveColor: "#fcfcff",
swiperImgUrls: [],
navBarUrl: [],
recommendList: []
},
//事件处理函数
onLoad: function () {
this.getSwiperImg(),
this.getNavBarUrl(),
this.getRecommend()
},
getSwiperImg () {
WXAPI
.loadSwip({recommendStatus: 1})
.then((res) => {
if(res.data.code === 0) {
// console.log(res.data.swiperImgUrl)
this.setData({
swiperImgUrls: res.data.swiperImgUrl
})
}
})
},
getNavBarUrl () {
WXAPI
.loadNavBar()
.then((res) => {
if(res.data.code === 0) {
// console.log(res.data.navBarUrl)
this.setData({
navBarUrl: res.data.navBarUrl
})
}
})
},
getRecommend () {
WXAPI
.loadRecommend()
.then((res) => {
if(res.data.code === 0) {
console.log(res.data.recommendList)
this.setData({
recommendList: res.data.recommendList
})
}
})
}
})
<file_sep>/wxapp/wxapp-mi/pages/category/category.js
// pages/category/category.js
const WXAPI = require('../../wxapi/main')
Page({
/**
* 页面的初始数据
*/
data: {
category: [],
categoryItem:[]
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
this.getCategory(),
this.getCategoryItem()
},
getCategory() {
WXAPI
.loadCategory()
.then((res) => {
// console.log(res.data.category)
if(res.data.code === 0) {
this.setData({
category: res.data.category
})
}
})
},
getCategoryItem() {
WXAPI
.loadCategoryItem()
.then((res) => {
if(res.data.code === 0) {
console.log(res.data.categoryItem)
this.setData({
categoryItem: res.data.categoryItem
})
}
})
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function () {
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function () {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function () {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function () {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function () {
},
/**
* 用户点击右上角分享
*/
onShareAppMessage: function () {
}
})<file_sep>/INTERVIEW-QUESTIONS/Q11/valid-palindrome/README.md
# 验证回文 空间复杂度0
1. 验证会问 指针遇
2. K大数 要快速<file_sep>/js/let_const/README.md
# 作用域 Scope
document DOM
getElementByTagName
getElementByClassName
querySelector
querySelectorAll
window BOM
全局定义了 var name = "张三";
全局变量 前端 js window
局部变量 function() { }
window js 内嵌在浏览器中的脚本语言,他与其他语言不一样的地方在于 window 全局变量挂载window上
console.log(name); console.log(window.name);
window 类型 typeof windown = "Object";
数值,字符串,布尔值,null,undefined,Symbol object
const let 比 var 优秀的地方遵守块级作用域
全局 -> 函数局部 -> 块级作用域
scope 范围
setTimeout 异步的内置函数 for 循环立即同步执行 1000 之后 i var 变成了10
let 块级作用域 for { 块级作用域 let } 1000后 <file_sep>/koa/koa-block/routers/signup.js
const router = require('koa-router')();
const controller = require('../controllers/c-signup')
// router -> controller -> modek | view
// render ejs
router.get('/signup', controller.getSignup)
// model save
router.get('/signin')
module.exports = router<file_sep>/js/duckSing/README.md
- 箭头函数
- es6 新二代函数定义方式
- () => {}
- 弱类型
- 相比于静态类型(c,c++),没有严格的类型的要求。
- 灵活
- undefined,变量的类型由值来决定(优/劣)
- 动态类型语言 鸭子类型 如果他走起来像鸭子,加起来也是鸭子,那么他就是鸭子。 使用了类型检 typeof 保证了灵活性的同时代码更加严谨。<file_sep>/react/redux-comment/src/component/APP.js
import React, { Component } from 'react';
class App extends Component {
componentDidMount() {
const {addComment} = this.props;
setTimeout(() => {
addComment('userName1', 'content1')
addComment('userName2', 'content2')
},2000)
}
render() {
const {commentList} = this.props
return (
<div>
{commentList.length === 0 ? '暂无评论' : <ul>
{
commentList.map((comment, i) => {
return <li>userName: {comment.userName} content: {comment.content}</li>
})
}
</ul>}
</div>
)
}
}
export default App<file_sep>/wxapp/github-programm/README.md
- 一套好的UI
app.wxss 全局样式
- 组件思想
界面中相对独立的显示区块,抽成组件
意义: 界面有组件构成,不是由标签构成,组件可以复用
- 项目之中所有的请求都封装带 api 目录下面
module.exports =
require
- wx.startPullDownRefresh(); 下拉刷新 onload 把生命周期交给 onPullDownRefresh()
api 请求
wx.stopPullDownRefresh()
- 复杂羡慕的组件数量比较多
/style/base.wxss 多个组件都依赖的基础样式
<file_sep>/js/calculate/README.md
- 计算函数,可以拆 更灵活 将计算与发钱策略函数解耦了。
n 个策略函数
如何干掉分支 if else switch
XXX.caculate();<file_sep>/js/skill/README.md
## URL
- protocol : host:port pathname search
- ?name=lilei&sex=female<file_sep>/INTERVIEW/talk_vue/README.md
基于 Vue 2.0 + vuex + vueRouter 全家桶实现方案来模拟网易云音乐WebApp项目 css预编译工具的Sass, 音乐上下滚动加载用的是betterscroll,全面采用ES6风格代码
解决了哪些问题
- 图片懒加载 vue-lazyload
- 前后端分离
使用node.js NeteaseCloudMusicAPI Proxy 8080 + 3000
- fastclick
- 设计了store
songs index song singer mode favoriteList searchHistory playHistory
- iconfont
- eslint
- 上班,vue项目,分析清楚目录结构
1. components/ 跟路由挂钩 工作的路口
2. store/ 全局共享 分模块 了解关键状态
3. common/ 公共组件不用谢
4. api/ 前后端的写作方式<file_sep>/wxapp/lol/README.md
- 小程序开发工具,初始化了一个项目框架
小程序是架构在微信(原生App),使用前端技术和思想,来快速开发,一份代码,到处运行。
不用下载,
不用写两次
快速高效
- html => wxml (新标签)
css => wxss
js => js bindtap => onclick
page = wxml + wxss + js
小程序有一个个page组成,每个page又由这三部分组成
weixin wxml? xml 为了它的性能优化以及新功能
有哪些新的标签 view = div
app.json是项目描述文件 添加的page要在app.json里声名切页面时,wx.navigateTo()
- MVVM
只要你有了数据,Model,在js中用data声名
Page({
data:{
legends:[]
}
})
View 视图层 WXML 等待的数据编译输出的html模板 {{}}
指令,wx:for <file_sep>/js/33-js-concepts/30seconds/demo1.js
// 高阶函数的考题
// ary 运行结果是函数
const ary = (fn, n) => (...args) => fn(...args.slice(0, n));
const firstTwoMax = ary(Math.max, 2)
console.log([[2,6,'a'], [8,4,6],[10]].map(x => firstTwoMax(...x)));
<file_sep>/js/promisebyjs/promise.js
function MyPromise(callback) {
var self = this
var state = null
// 记录resolve的参数
var param = null
// 执行传入的**并改变promise对象的状态
callback(resolve, reject)
// resolve方法
function resolve(data) {
let parmise
// 改变状态
state = true
param = data
nextResolve(asynconFulfilled(param))
// 执行记录onFulfilled
parmise = asynconFulfilled(param)
if(parmise === undefined) {
// 如果 parmise === undefined ,就不能解析 parmise.constructor
}else if (parmise.constructor == self.constructor) {
// 等待传递进来的promise对象执行完毕,然后根据传递进来的promise对象的执行状态执行resolve 或 reject
// 注意,这个param是个形参,在then方法的promise中执行
promise.then(function (param) {
resolve(param)
}, function(param) {
reject(param)
})
}else {
// 这是前面的then方法没有放回promise对象
resolve(promise)
}
}
// reject方法
function reject(err) {
// 改变状态
state = false
param = err
nextReject(asynconRejected(param))
}
var nextResolve = null
var nextReject = null
// 记录then方法的参数,onFulfilled, onRejected
var asynconFulfilled = null
var asynconRejected = null
this.then = function(onFullfilled, onRejected) {
// 返回一个新的promise 对象
return new self.constructor(function(resolve, reject) {
if(state === true) {
// param 是prmoise对象完成后的结果
resolve(onFullfilled(param))
}else if(state === false){
reject(onRejected(param))
}else {
nextResolve = resolve
nextReject = reject
asynconFulfilled = onFullfilled
asynconRejected = onRejected
}
})
}
}<file_sep>/INTERVIEW/typescript/type/main.ts
console.log('hello ts');
let decLiteral: number = 1;
// decLiteral = "12121";
let hexLiteral: number = 0xf00d;
let user_name: string = "bob";
let sentence: string = `Hell0, my name is ${name}`
let list: number[] = [1, 2, 3]
let list2: Array<number> = [1, 2, 3]
function div(x) {
if (isFinite(1000/x)) {
return 'Number is not infinity'
}
return 'Number is Infinity'
}
console.log(div(0))<file_sep>/wxapp/wxmall/wxapi/config.js
module.exports = {
subDomain: 'tz'
}<file_sep>/js/cors/READMD.md
跨域问题
前后端分离 不同端口
- 前端解决方案
proxy 代理, 原来的请求被后端同源的代替了,拿到数据后,再交给原请求
- 后端解决方案
让后端同意所有或者部分 可以跨域访问资源 用中间件来处理, cors 放在路由之前<file_sep>/js/leetcode/banana/index.js
/**
*
* @param {number[]} piles
* @param {number} H
* @param {number} mid
* @return {boolean}
*/
function canEatAllBananas(piles,H,mid){
let h = 0
for (let pile of piles){
h+= Math.ceil(pile / mid);
}
return h <= H
}
/**
*
* @param {Number[]} piles
* @param {Number} H
* @return {number}
*/
function minEatingSpeed(piles,H){
let lo = 1;
let hi = Math.max(...piles)
console.log(hi)
while(lo <= hi){
// lo试试
let mid = lo + ((hi-lo) >> 1);
// console.log('-------',m);
// m正好可以?
if(canEatAllBananas(piles, H, m)){
hi = mid - 1; // 该为中间值 - 1
}else{
lo = mid + 1; // 将最小值改为中间值 + 1
}
}
return lo;
}
console.log(minEatingSpeed([3,6,7,11],8))
// console.log(canEatAllBananas([3,6,7,11],8,1))<file_sep>/react/react-new-feature/README.md
## why
以前async mode 现在 concurrent mode
目的:让react 整体渲染有一个有一个优先级的排比
1. js 单线程
2. 浏览器 多线程
1. ui 渲染线程
2. js 解析
3. http
3. js 线程和 ui 是互斥的, js 可以操作 dom
4. 卡顿,js 执行占据了很大的空间,导致 ui 得不到响应
<file_sep>/js/leetcode/swap_node/src/index.js
// console.log('张三');
// log 日志
require('./styles/normalize')
const log = require('log');
log('hello wold')<file_sep>/vue-learn/element-starter/README.md
- 相应框架或技术栈的快速启动github项目Starter .git删除
- 组件,路由接管一切
最好用目录
<router-view /> install ?
- 全家桶
vue-router 路由
vuex 数据流管理
axios 负责 API
- alias
短路径,常用的
- 目录架构
- components 组件
- pages 页面级别的组件
- commons header, footer, dialog 等跨页面的通用组件
- element-ui 框架级别组件,全局可用了
- 在components pages 目录下加一个index.js 模块化输出所有的文件,可读性
- transition name
v-enter(短) -> v-enter-active(1s) Enter
v-leave -> v-leave-active Leave <file_sep>/react/react-ant-router-demo/src/page/Label.jsx
import React, { Component } from 'react';
import {Spin, Alert, notification, Button} from 'antd'
const openNotificationWithIcon = type => {
notification[type]({
message: 'Notification Title',
description:
'This is the content of the notification. This is the content of the notification. This is the content of the notification.',
});
};
class Label extends Component {
state = {
spinning: true
}
componentDidMount() {
setTimeout(() => {
this.setState({
spinning: false
})
},2000)
}
render() {
const {spinning} = this.state
return (
<div>
<Spin tip="Loading..." spinning={spinning}>
<Alert
message="Alert message title"
description="Further details about the context of this alert."
type="info"
/>
</Spin>
<div>
<Button onClick={() => openNotificationWithIcon('success')}>Success</Button>
<Button onClick={() => openNotificationWithIcon('info')}>Info</Button>
<Button onClick={() => openNotificationWithIcon('warning')}>Warning</Button>
<Button onClick={() => openNotificationWithIcon('error')}>Error</Button>
</div>
</div>
);
}
}
export default Label;<file_sep>/js/node/event/readme.md
## event
click
http ((req,res)=>{
res.on('data')
res.on('end')
})
onClick
onDbClick
订阅发布者模式。
<file_sep>/CSS/cande/README.md
1. mixin 与函数的区别
mixin 是一段样式的封装,可以在引用的地方复用 stylus 是用的最多的
函数有返回值, random(min,max)
2. stylus 有内置的函数库
floor math(0,'random') unit( ,'px')
3. 200个元素 stylus for
for num in 1..200
.g-ball:nth-child({num})
$width = random(0,40)
width unit($width,'px')<file_sep>/CSS/douban/README.md
- css 命名词汇
feeds *-item
- html结构及布局
从上到下,从左到右,语义化和功能化
1. 套路
content>h3+p
2. 盒子
3. a 作为盒子,在移动端很正常。 display:block;
4. 盒子模型
文字line-height padding margin
5. 文字阶段
tmall 商铺信息是由商家填的,他的高度不被限制,
display:-webkit-box; 新的盒子模型,像flex 来划分父元素的空间。
overflow:hidden;
-webkit-line-clamp 行数
-webkit-box-orient:vertical;
6. 浮动 float: left | right
离开文档流
在一个盒子里,将要浮动的元素写在最前面,左右布局,
在flex 布局之前,我们一般借助于float 来布局
图片的宽高? div padding-top: 自身的宽高来做比例100% 正方形
自适应设备里合资的等比例设置 width 百分比 高度用 padding-top<file_sep>/js/leetcode/sort/quickSort.js
// 快排,
// 抽象 a b c 递归
function quickSort(arr) {
if(arr.length <= 1) {
return arr
}
var left = [], right = [], baseDot = Math.round(arr.length / 2),base = arr.splice(baseDot, 1)[0]
// 中间值
for(var i = 0; i < arr.length; i++) {
if(arr[i] < base) {
left.push(arr[i])
}else {
right.push(arr[i])
}
}
// left a
// base 中间值
// right b
return quickSort(left).concat([base], quickSort(right))
}
console.log(quickSort([1,2,3,9,5,6,7]));<file_sep>/vue-learn/vue-chart-demo/README.md
- vuex 大型化 modules 来支持
this.$store.user.
- user
state info 登录 注册 退出/
actions
vuex先设计, 搭好结构 围绕着我们的状态
token 令牌环 this.$store.user.token
跳转到登录页
- 登录鉴权
1. 延迟加载路由,性能优化<file_sep>/INTERVIEW-QUESTIONS/note.md
8. 下面代码的输出是什么?
class Chameleon {
static colorChange(newColor) {
this.newColor = newColor;
}
constructor({ newColor = "green" } = {}) {
this.newColor = newColor;
}
}
const freddie = new Chameleon({ newColor: "purple" });
freddie.colorChange("orange");
复制代码
A: orange
B: purple
C: green
D: TypeError
答案
答案: D
colorChange方法是静态的。 静态方法仅在创建它们的构造函数中存在,并且不能传递给任何子级。 由于freddie是一个子级对象,函数不会传递,所以在freddie实例上不存在freddie方法:抛出TypeError。
作者:ConardLi
链接:https://juejin.im/post/5d0644976fb9a07ed064b0ca
来源:掘金
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。<file_sep>/js/hongbao/README.md
如何实现红包算法
固定金额的红包, 有若干人来抢, 规则
1. 抢到金额之和等于红包金额,不能超过,也不能少于。
2. 手气王,0.01至少,
3. 金额随机,随机数,公平,每个人抢到金额的概率要相同
计算过程,变量计算的本质
发钱? total = restAmount--
restNum-- == num
随机一次,restAmont = restAmont - 随机数 restNum--
最后一个人,拿最后的钱 for(i=0;i<num-1;i++;i++)
每次随机,钱数是我们需要的, push 数组里面,
总合,
math是数学对象
math.random() 产生随机数
parseFloat() 解析为浮点数
类型转换 "23.1" => 23.1 parseFloat
0-9之间的整数
let max = 100;
let min = 0;
最小值与最大值之间的整数 min +Math.floor(Math.random()*(max-min))<file_sep>/js/leetcode/partition_linked_list/README.md
- 抽象 ADT 具象来引导
- 解决特定问题
1. Leetcode 数据结构题
LinkedLise
2. github algorithm oo写法
封装成 class export default
3. webpack 可见即可得
- 有一个链表 服务于各种算法
1 -> 4 -> 3 -> 2 -> 5 -> 2
存放数据, 不连续的, head 1
- node(n) -> linkedList
模块化 一个文件一个类
es 6 模块化
append()
- index.js
业务代码
- node 不支持 es5 模块化
原生支持的是require commonJS compile presets
- ADT
抽象数据类型
链表 数据解构 配套方法
<file_sep>/js/hongbao/index.js
// let ran_num =parseFloat(Math.random()).toFixed(2);
// console.log(ran_num);
// console.log(Math.floor(Math.random()*10));
// let min = 1;
// let max = 100;
// console.log(min +Math.floor(Math.random()*(max-min)));
function hongbao(total,num){
const arr = [];
let restAmount = total;//余额初始化为总金额
let restNum = num;
for(let i = 0;i <num - 1; i++){//还余一个不发
//平均值的2倍
let amount =parseFloat(Math.random() * (restAmount/restNum * 2)).toFixed(2);
restAmount -= amount;
restNum--;
arr.push(amount);
}
//最后一个人restAmount
arr.push(restAmount.toFixed(2));
return arr;
}
console.log(hongbao(20,40)); <file_sep>/react/redux-comment/README.md
## flux
单向数据流
用户 dispatch(action) -> reducer(纯函数) -> state -> 页面重新渲染
redux: js 的库
react-redux: react 的组件
container 组件 connect
component 组件 直接接受<file_sep>/CSS/svg/README.md
svg 矢量图绘制API
数学图形,点,线,圆,折线,椭圆。。。。
比对于由像素,img,png,可以无限放大,
- 数据可视化
- 代替图片<file_sep>/js/node/restful/README.md
- json 格式是标准的数据交换
- 前后端开发, /api json 格式来交流
- 全栈 fullstatc
- restful 一切皆资源 暴露资源
- 设计良好的URL
/post /post/:id
/comments /comments/:id
/posts/1/comments
HTTP 动词
GET 查询
发一条评论 增加一条资源
POST /comments
DELETE动词 /posts/2
修改 PUT / PATCH
/comments/2 body 最美不过下雨天,是与你。。。。
PUT 把全新的所有的内容,去替换掉旧的内容
PATCH 只要传要更新的字段,局部
- RESTFUL 考点
认为一切皆资源,URL 是唯一定位资源的符号,他有一定的设计原则
HTTP动词是web资源的状态转换动词
操作 SQL方法 HTTP动词
CREATE INSERT POST
READ SELECT GET
UPDATAE UPDATE PUT/PATCH
DELETE DELETE DELETE<file_sep>/js/node/跨域/README.md
## 跨域
浏览器的安全策略
同源策略:
同协议 域名 端口 同源 不存在跨域的
不同源 存在跨域
## CORS
规定了一组 http 的头部字段 作用是:
允许哪些网站通过浏览器有访问的权限
1. access-X
2. cookie
3. 浏览器会先 以 OPTIONS 请求方法发起一个预检(preflight) 请求 ,获取一下允许不允许当前的域请求,服务器允许之后才会发起正式的请求.
## 代理
1. nginx
反向代理
http://localhost:9999/api/
http://localhost:8888/api/
不知道 请求的是哪一个服务器
正向代理
A->proxy->goole.com
## iframe + postMessage
1. 前端页面 通过iframe 引入一个后端目录下面的html
iframe 是不受同源策略限制的
2. postMessage 用于在两个窗口之间传递数据
3. 前端页面 通过 possMessage 向 后端目录下面的HTML 传递接口需要的请求参数
4. 后端页面 通过 possMessage 向 前端页面 传递接口结果
## iframe + window.name
iframe 共享 window.name
没有postMessage 只能借助 中间页面 通知前端页面
window.parent.callback(window.name)
## jsonp
1. 定义一个回调
2. 将回调函数的名字 告诉后端 后端会返回
···js
回调(res)
···
3. script 标签 加载过后 执行 返回的内容
缺点 : 只能发起get 请求 .
写一个jsonp 的函数,以promise 的方式调用
json(url)
.then(res =>{
})<file_sep>/js/node/event/lib/choose.js
// 命令行交互
const inquirer = require('inquirer')
module.exports = (songs) => inquirer.prompt([{
type: 'list',
name: 'song',
message: `共有${songs.length}首歌,按下回车键播放`,
choices: songs.map((song, index) => `${index + 1}${song.name}`)
}])<file_sep>/js/drum-kit/README.md
## h5
1. flex 布局 适合移动端 大小弹性 支持不同的设备
display: flex|block
块级元素 div.keys
- .keys 有什么异常?
9 .key 被flex 管理起来
- 水平居中 justify-centent 水平 主轴
- align-item
2. 相对单位
px 绝对大小 不适用于移动
- vh 相对于屏幕
- rem 相对于html 根元素
<file_sep>/react/react-ant-router-demo/README.md
## vs
// hashRouter #
// historyRouter 不带 #
刷新这个行为
/#a -> /#b js 刷新 /#b
/a -> /b 刷新 请求后端的 /b 后端肯定没有 /b 后端再次交给前端处理
1. nginx
2. 后端的代码<file_sep>/js/args/README.md
函数参数在怎么变化
es5 -> es6 parmas 在怎么变,为什么变
function abc(a, b, c) {
}
- 参数一个个列出来的原始方案
- 如果参数多的时候,同时又是一个对象的,请{}
表单操作时,username, password, sex ...
let user = {}
让代码好读一些
- reset destruct...
用于增强代码的可读性及例利性
写代码时要考虑看代码的人的感受
提供初值,让代码更加适用
- 参数考题请想起默认参数 + 参数可以是函数
用来做参数缺失报错是最好的<file_sep>/CSS/svg/svg_animation/README.md
html 处理文本的排列和显示的 css
SVG 是用来处理图形的 css js<file_sep>/react/rdeux_counter/src/Counter.jsx
import React, { Component } from 'react';
import {connect} from 'react-redux'
class Counter extends Component {
state = { }
render() {
return (
<p>
Clicked: {this.props.count}times
</p>
);
}
}
// 1. map 共享状态
// 2. 做为参数传给组件
const mapStateToProps = (state) => {
// connect 找到这个参数,把state交给你
return {
count: state.count
}
}
export default connect(mapStateToProps)(Counter);
<file_sep>/js/args/demo3,.js
function information ({name = '没有留下', age = 0, height = 174}) {
console.log(name, age, height)
}
information({})<file_sep>/js/node/koa-template/README.md
## koa
node 框架
tj : koa co command
## 中间件 middleWare
流水线
一个中间件处理完可以交给下一个中间件
Koa 特色
是一个 async 方法
洋葱模型
作用:解耦 一个中间件负责一件事
## http
自定义响应头,通常以 X 开头
## ejs
<%= %> 输出数据到模板(转义过的)
<%- %> 输出数据到模板 (未转义的)
include 引入其他模板<file_sep>/webpack/details/src/index.js
// console.log('将张三打包带走');
require('./styles/normalize.css'); //一切皆可打包
<file_sep>/CSS/baymax/README.md
# 相对单位,为了自适应
不同的移动设备
750px
vw vh 按比例分配宽高
em 移动端少用px rem 细致的每个盒子或盒子模型的大小等
em 是相对自身的字体大小来比例
10em 10*14px = 140px
rem html 根元素的fontsize
:befor :after 伪元素 没有标签但却可以像真正的元素一样来在页面上占位置。
dom 文档流里不需要写这个元素,副作用,不会影响到内容的显示。
使用css来声明,content属性是必须的
html 默认的字体大小是16px 如果没有设置,会使用父级,或body font-size<file_sep>/js/node/redux/index.js
const { createStore, combineReducers } = require('redux');
// action.type 常量 决定了 这次 dispatch
// 要干什么
// reducer 可以收到 action的信息
const add = {
type: 'INCREMENT'
}
const reduce = {
type: 'DECREMENT'
}
// 加 ADD_FILM
// type + payload
function filmReducer(state = [], action) {
switch (action.type) {
case 'ADD_FILM':
return [...state, action.film];
default :
return state;
}
}
function reducer(state, action) {
console.log('reducer->>>>', action);
if (action.type === 'INCREMENT') {
return state + 1;
} else if (action.type === 'DECREMENT') {
return state - 1;
} else {
return 0;
}
}
const index = combineReducers({
count: reducer,
films: filmReducer
})
// createStore 只接受 reducer
const store = createStore(index);
store.subscribe(() => {
console.log(store.getState());
});
store.dispatch(add);
store.dispatch(add);
store.dispatch(reduce);
store.dispatch({
type: 'ADD_FILM',
a: 1,
b: 2,
id: 0,
film: { name: '狮子王' }
})
<file_sep>/taro/README.md
- 小程序为什么要框架?
原生写小程序有组件化,但是语法好怪, vue,react开发者,学习成本高
taro(react) mpvue(vue) 让开发者不用学小程序就可以学了。
命令行工具,可以安装一堆的npm包,极大的扩展了小程序的功能
compile src -> dist/
- JSX
XML in JS , react template 的新语法
jsx -> babel -> preset react -> JS
render() {
return ()
}
react 没有 v-for v-if 指令
原生写
<view>
{
this.data.list.map((item, index) => {
return (
.....
)
})
}
</view><file_sep>/taro/todoLIst/src/reducers/index.js
import {combinReducers} from 'redux'
// 将很多的状态 reduce 最终的状态
const INITITAL_STATE = {
todos: [
{
id: 0,
text: '第一条'
}
]
}
function todos () {
return INITITAL_STATE
}
export default combinReducers({
todos
})<file_sep>/js/leetcode/banana/README.md
蜗牛爱吃香蕉
N piles bananas 每 pile bananas 有不同数量的bananas
[3,6,7,11]
[30,11,23,4,20]
每个小时可以吃某一pile里的n 只香蕉,规定H小时内吃完 吃没把的时候,要不就是吃 m 只,要不就吃余下的
koko bananas
- 把香蕉吃完的函数 canEatAllBanans
h 来自吃法规则 一小时mid 一次只吃一把
return h >= H
- while 去疯狂的试
1,2,3,4,5,6,。。。。 Math.max(...piles)
能拿到结果,就是太慢了
中间 最大概率最快的 二分查找
二分查找优化查找的效率
简单查找 时间开销是n 二分查找的写法是有规律的
min max 要找的是最小可以min 可以来优化的
找中间 mid = min + ((max-min) >> 1) ,
小了 mid +1 新的min 大了 mid-1 新的y
log2(N) <file_sep>/js/skill/arr.js
const arr = [99, 0, 33, 1, 2];
const min = Math.min(...arr);
const max = Math.max(...arr);
<file_sep>/js/game/木乃伊/README.md
phaser 是非常友好的 2D h5 游戏开发框架
game 是游戏对象
preload, create update, 不同的游戏时期的回调函数
精灵,精灵图,加上animation 就动起来。
将游戏的制作交给phaser, 我们只要写逻辑<file_sep>/react/context/src/Context15.jsx
import React, {Component} from 'react'
import propTypes from 'prop-types'
class Context15 extends Component {
state = {
theme: 'red'
}
getChildContext() {
return {
theme: this.state.theme
}
}
// 1
// handleToggleTheme = (e) => {
// const theme = e.target.dataset.theme
// this.setState({
// theme
// })
// }
// 2 调用要传参 this.handleToggleTheme('purple')
// handleToggleTheme = (theme) => () => {
// this.setState({
// theme
// })
// }
// 3 () => {this.handleToggleTheme('purple')} 在函数中调用
handleToggleTheme = (theme) => {
this.setState({
theme
})
}
render() {
const msg = ['aaa', 'add', 'vvvv']
return (
<div>
{
msg.map((item, i) => {
return (
<Message key={i} text={item} />
)
})
}
<button onClick={() => {this.handleToggleTheme('purple')}} data-theme="purple">purple</button>
<button onClick={() => {this.handleToggleTheme('yellow')}} data-theme="yellow">yellow</button>
</div>
)
}
}
Context15.childContextTypes = {
theme: propTypes.string
}
class Message extends Component {
shouldComponentUpdate() {
return false
}
render() {
const {text} = this.props
return (
<li>
{text}
<MyButton />
</li>
)
}
}
class MyButton extends Component {
static contextTypes = {
theme: propTypes.string
}
render() {
const {theme} = this.context
return (
<button style={{color: theme}}>delete</button>
)
}
}
export default Context15<file_sep>/CSS/svg/path/README.md
defs 后台 做准备
g 组合 id
use href="#" x="" y=""
symbol 模板 viewbox<file_sep>/wxapp/sg/README.md
- 全局配置
window + tabbar
assets目录 pages
- UI 框架
app.wxss 引入weui
数据
生命周期 wx.request
- list 有套路
onLoad onReachBottom onPullDownRefresh isLoading 加载 状态
currentPage 传参 totalPage 最后一页
- tempalte
共用的界面
<template data={{}}>
<template name="loading"/>
<file_sep>/js/30-seconds-code/promisify/REDAME.md
## promisify
promise 风格
回调版本:
fs.readFile('', (err, data) => {});
promisify: readFile('').then() 让符合 (err, data) => {} 回调函数 是最后一个参数的函数,包裹之后返回 promise 版本的函数
## 实现这样一个 promisify <file_sep>/wxapp/pinxixi/README.md
## session_key
当前用户会话操作的时效性,维护用户的登录状态。
时效性: 和用户的使用频率
## getUserInfo
返回的敏感数据 可以配合 session_key解密<file_sep>/js/compose/README.md
## 函数式编程
go
抽象能力更高
## 面向对象编程
<file_sep>/js/node/fs/demo.js
// fs 模块 是 node 后端开发的一部分
const fs = require('fs');
// // 读文件是异步的,使用回调函数
// fs.readFile('./a.txt','utf-8',function(err,data){
// console.log(data);
// })
// fs.readFile('./b.txt','utf-8',function(err,data){
// console.log('-------------------------------------',data);
// })
// 将callback处理异步的方案抛弃
const fileAPromise = new Promise((resolve,reject) => {
// 花时间的语言 耗时任务
fs.readFile('./a.txt','utf-8',(err,data) => {
// 流程的控制权怎么移交
resolve(data);
})
})
const fileBPrimise = new Promise((resolve,reject) => {
fs.readFile('./b.txt','utf-8',(err,data) => {
if(err){
reject(err);
}else{
resolve(data);
}
})
})
// 将内部的耗时任务运行起来
fileAPromise
.then(data => {
console.log(data);
return fileBPrimise;
})
.then(data => {
console.log(data);
})<file_sep>/js/node/http_server/README.md
- MVVM 前端新贵
Model 数据 Page({data:{
legends:[]
}})
View 视图
WXML
VM {{}} wx:for .....
- MVC 经典的web开发模式
Model => SQL
View => 静态页面
Controller => 路由
- WebServer 软件程序
Web服务器硬件运行webServer程序的 ip http 协议 http://127.0.0.1:8080 端口 不止一个服务
3306 MySQL
80 Web 服务
http
.createServer(function(request,response) {
response.end('hello world')
})
.listen(3000)
request 用户 N Web Server 一直在3000端口上伺服
request 就能找到店,每位用户到达,触发 事件,调用 createServer 回调函数, request用户身份,
response ?相应请求 响应请求 http 响应后就断开
<file_sep>/js/leetcode/merge_tow_sorted_list/README.md
l1 链表 1 -> 2 -> 4
l2 链表 1 -> 3 -> 4
结果
1 -> 1 -> 3 -> 4 -> 4
head1
head2
指针的方便
sorted <file_sep>/scorecode/weui/README.md
1. @import 文件引入,一个文件做一件事,有利于代码的维护及管理 多人协作
/base.reset 基础的 reset 任务
base 核心 wideg
@import 让我们可以做文件的分离和管理,多人协作,目录让我们看到思想和野心。
variable 当时个大项目时,有大量的变量要维护,variable 目录
weui.style 入口文件 @import 串起来各个部分
base / widget
- reset.style
- variable
- global.styl
- weui-button.styl
- weui-button
<file_sep>/js/node/static-resource-server/staticServer.js
const http = require('http');
const fs = require('fs');
const path = require('path');
// 浏览器转圈 说明没有响应
// localhost:8080/static/index.html
http.createServer((req, res) => {
console.log(req.url)
// /static/index.html -> /static/xxx.png
const url = req.url;
// ^
if(/^\/static\//.test(url)) {
staticServer(req, res);
return false;
}
// fs.readFile('./static/index.html', 'binary', (err, file) => {
// res.write(file, 'binary');
// res.end();
// })
}).listen(8080, () => {
console.log('server is running 8080')
})
function staticServer(req, res) {
let url = req.url;
console.log('url', url)
if(url === '/static/') url += 'index.html';
const filePath = path.join(__dirname, url);
fs.exists(filePath, exists => {
if (!exists) {
res.end(`the request url: ${url} was not found`)
}else {
fs.readFile(filePath, 'binary', (err, file) => {
if(!err) {
res.write(file, 'binary');
res.end()
}
})
}
})
}<file_sep>/js/args/demo4.js
const err = (message) => {
throw new Error(message)
}
function sun(num = err('first param is not defined'), otherNum = err('second param is not defined')) {
return num + otherNum;
}
console.log(sun(1, 2)) //3
console.log(sun(undefined, 2)); //报错,第一个参数没有定义
console.log(sun(10)) //报错,第二个参数没有定义
<file_sep>/wxapp/miShopping/wxapi/request.js
const BASE_URL = "http://v.juhe.cn/movie"
const res = (url, method, data) => {
return new Promise((resolve, reject) => {
let _url = BASE_URL + '/' + url
wx.request({
url: _url,
method: method,
data: data,
header: {
'Content-Type': 'application/x-www-form-urllencoded'
},
success(request) {
resolve(request.data)
},
fail(error) {
reject(error)
}
});
})
}
module.exports = {
loadIndex: (data) => {
return res('citys?key=5d4ddcaea7adad60fb9e45681514f87e','get', data)
},
// loadCategory: (data) => {
// return res('category', 'get', data)
// },
// loadProducts: (data) => {
// return res('products', 'get', data)
// },
// loadDetail: (data) => {
// return res('detail/10000134', 'get', data)
// }
}<file_sep>/INTERVIEW-QUESTIONS/README.md
# Q1 js全局执行上下文为我们创建了两个东西:全局对象和this关键字
new的实现原理:
1. 创建一个空对象,构造函数的this指向这个空对象
2. 这个新对象被执行[原型]连接
3. 执行构造函数,将属性或者方法添加到this应用的对象上
4. 如果构造函数中没有返回其他对象,那么返回this,即创建的新对象。否则,返回构造函数返回的对象
# Q2 call bind apply
1. b.call(a) 就相当于把b里面的作用域强行指向到a里面去,第一个参数一定是this作用域要去到的地方,第二三四...个参数是该参数作用域里用到的值
2. b.apply(a) 就相当于把b里面的作用域强行指向到a里面去,第一个参数一定是this作用域要去到的地方,但是第二三四...个参数是该参数作用域里用到的值,需要用数组类型
3. b.call 或者 b.apply() 此时this的作用域会指向windonw
4. c = b.bind(a)
c()
bind方法返回的是一个修改后的函数,所以该用函数该有的姿态去调用bind方法接受bing方法的参数是按照形参的顺序进行的
# Q3 浅拷贝 深拷贝
1. 数组解构:
let [x, y] = [1, 2]
// x = 1,
// y = 2
2. 对象解构:
let {foo, bar} = {foo: "aa", bar: "bb"}
// foo = "aa"
// bar = "bb"
另:(允许给赋值的变量重命名)
let {foo: baz} = {foo: "ab"}
// baz = "ab"
3. 浅拷贝只是第一层属性进行拷贝,当第一层的属性为基本数据类型时,新对象和原对象互不影响,但是如果第一层的属性值是 # 复杂数据类型 # 那么新对象和原对象的属性值其指向的是同一块内存地址
4. 深拷贝是将对象及值复制过来,两个对象修改其中任意一个的值其他一个不会改变
# Q4 闭包
闭包是值由权限访问另一个函数作用域中的变量的函数
1. 能够访问函数定义时所在的词法作用域 (阻止其被回收)
2. 私有化变量
3. 模拟块级作用域
4. 闭包不会回收,会影响性能
# Q5 数组去重
1. Set
2. indexOf
3. includes
4. reduce
# Q6 防抖节流函数原理
# Q7 __proto__ 和 prototype 关联
__proto__ 是每一个实例上都有的属性,可以访问[prototype]属性,实例的__proto__ 与其构造函数的prototype指向的是一个对象
# Q10 get post 请求在缓存方面的区别
1. get请求类似于查找到过程,用户获取数据可以不用每次都与数据库链接,所以可以使用缓存
post不同,post一般做的是修改和删除数据的工作,所以必须与数据库交互,所以不能使用缓存,因此get请求更适合于请求缓存
# Q11 url长度限制
http协议并没有限制url的长度,是浏览器或者web浏览器做了url长度的限制,并且只针对get请求做的限制
# Q12 前端事件流
在DOM标准的事件模型中,事件流包括下面几个阶段:
1. 事件捕获阶段
2. 处于目标阶段
3. 事件冒泡阶段
addEventListener第三个参数为 true 时, 捕获, false时,冒泡, 默认是false (IE只支持事件冒泡)
# Q13 图片懒加载和预加载的区别
预加载:提前加载图片,当用户需要查看图片时可直接从本地缓存中渲染
懒加载:做为服务器的前端优化,减少请求或延迟请求(懒加载对服务器有一定的缓解压力作用,预加载则会增加服务器压力)
# Q14 js中的各种位置
clientHeight: 表示可视区域的高度,不包含border和滚动条
offsetHeight: 表示可视区域的高度,包含border和滚动条
scrollHeight: 表示所有区域的高度, 包含因为滚动被隐藏的部分
clientTop: 表示边框border的厚度,在为指定的情况下一般为0
scrollTop: 滚动后被隐藏的高度
# Q15 js拖拽功能的实现
# Q16 类的创建和继承
# Q17 click在ios手机上有300ms的延迟,原因及解决方法
1. <meta name="voewport" content="width=device-width, initial-scale=no">
2. fastClick, 其原理时:检测到touchend事件后,立刻发出模拟click事件,并把浏览器300ms之后真实发出的事件阻断
# Q18 Cookie, sessionStorage, localStorage的区别
1. Cookie: 数据始终在同源的http请求中携带(即使不需要),即cookie在浏览器和服务器之间来回传递,而sessionStorage, localStorage不会自动把数据发给服务器,仅在本地保存,cookie还有路径(path)的概念,可以限制cookie只属于某个路径下,存储大小只有4K左右
2. sessionStorage: 仅在当前浏览器窗口关闭前有效,不能长久保存
3. localStorage: 在所有的同源窗口都是共享的,cookie也是在所有同源窗口是共享的,localStorage的大小在5M左右
<file_sep>/js/33-js-concepts/值类型和引用类型/README.md
## 基本类型
- null 空值
- undefined 未赋值
- number
- string
- bool
- Symbol (es6 + )
## 复杂类型
- Object
function array {} ...<file_sep>/webpack/babel/index.js
const a = 1,
b = 2,
c = a + b;
console.log(c);
// [1, 2, 3].map(item => `${item}item`);
// // es6的大部分功能,其实es5也是能实现的,只不过不够优雅
// let xlz = {name: '张三', hometown: '江西'}
// xlz = {...xlz, "company": '新浪'}<file_sep>/js/node/redux/README.md
## redux 数据流
全局
action 一个纯对象 {}
reducer 纯函数 函数的返回值决定 store 里面的值 只依赖于传入参数 (state, action)
dispatch dispath(action) 修改数据
store 状态的集合<file_sep>/js/dom-operation/README.md
## dom
## dom 节点类型
元素节点 创建 creatElement
注释节点
文本节点 创建 createTextNode<file_sep>/INTERVIEW-QUESTIONS/Q11/index.js
function findKthLargest(nums, k) {
if (k < 0 || k > nums.length - 1) return NaN;
return nums.sort((a, b) => {
return b - a;
})[k - 1]
}
console.log(findKthLargest([1, 4, 2, 6, 9, 10], 2))
<file_sep>/webpack/babel/text.js
let a = 1;
a++;
a;<file_sep>/wxapp/miShopping/pages/index/index.js
//index.js
//获取应用实例
const res = require('../../wxapi/request')
const app = getApp()
Page({
data: {
indicatorDots: true,
autoplay: true,
interval: 3000,
duration: 500,
indicatorColor: "#f4f4fd",
indicatorActiveColor: "#fcfcff",
swiper: [],
cells: [],
products:[],
test: true
},
onLoad: function () {
// this.getSwiper()
this.getCells()
// this.getProducts()
},
getSwiper() {
var that = this
res
.loadIndex()
.then((res) => {
console.log(res.data.data.sections[0])
that.setData({
swiper: res.data.data.sections[0]
})
})
},
getCells() {
var that = this
res
.loadIndex()
.then((res) => {
console.log(res)
that.setData({
cells: res
})
})
},
getProducts() {
res.loadProducts()
.then((res) => {
console.log(res)
this.setData({
products: res.data
})
})
},
})<file_sep>/js/leetcode/partition_linked_list/index.js
import LinkedList from './LinkedList.js'
const list = new LinkedList();
// 1 -> 4 -> 3 -> 2 -> 5 -> 2
list
.append(1)
.append(4)
.append(3)
.append(2)
.append(5)
.append(2)
<file_sep>/webpack/babel/README.md
生产线 Webpack 代码生产工艺 工作流 work Flow
- html + css + js = development
html template {{}}
css stylus
js es6,7,8,9 => es5
最后代码运行的env
- js
babel
使用最新的技术,babel 编译成es5
- babel-core 核心的转译库
npm run build "babel ..."
babe-cli
babel-preset-env .babelrc
{
"presets": ["env"]
}
build
dev
- preset 预处理
env 搞不定 安装插件
- webpack 是一切工作流的主宰
webpack --mode development
/src 开发目录
/dist 上线的项目
- 开发时 development 代码的可读性 dev 本地 localhost
- 上线时 production 代码要压缩,混淆代码 build 服务器上 域名
- 测试时 test 局域网<file_sep>/js/calculate/index.js
// 会计 计算年终奖
// 绩效 S 5 A 3 B 2 C 1 D
// 可以如何优化? 分支太多,计算策略太简陋 会计发钱,制定发钱策略的区分开来,
var
var perfomanceS = function(salary){
return salary * 5;
}
var perfomanceA = function(salary){
return salary * 4;
}
var calculateBounce = function(perfomanceLevel, salary){
if(perfomanceLevel === 'S') {
return perfomanceS(salary);
}
if(perfomanceLevel === 'A') {
return perfomanceA(salary);
}
}
console.log(calculateBounce('S',20000))
console.log(calculateBounce('A',20000))<file_sep>/CSS/douban_pc/README.md
PC 相对mobile 更复杂 布局 layout
文档流 从上到下 从左到右
flex 要使用前思考一下 最新 css3 技术 考虑兼容性
float 会影响其他相邻的元素
离开文档流 float 跟 position: absolute 区别
PC端 先布局 layout float inline-block 但是要处理兄弟间的间隔 ie8以下不支持 inline-block<file_sep>/js/30-seconds-code/promisify/index.js
const fs = require('fs');
const util = require('util');
// const foo = () => {}
// foo 函数体
// foo() 执行了函数
// 1 输入一个函数
const promisify = (func) => {
// args promisify 返回函数的参数
// 第一个 ...args 将传入的参数整理为数组
// 第二个 ...args 将上一个的数组的每一项一次展开
return (...args) => {
return new Promise((resolve, reject) => {
func(...args, (err, data) => {
if(err) reject(err)
resolve(data);
})
})
}
}
console.log(typeof fs.readFile); //输出的时function
//
const readFile = promisify(fs.readFile);
readFile('./index.html', {encoding: 'utf8'}).then(res => {
console.log(res);
})
// fs.readFile('./index.html', {encoding: 'utf8'},(err, data) => {
// if(!err) {
// console.log(data);
// }
// });
// fs.stat('.', (err, stats) => {
// if(!err) {
// console.log(stats);
// }
// })<file_sep>/react/react-state-flow/src/CommentInput.jsx
import React, { Component } from 'react';
class CommentInput extends Component {
handlePublish = () => {
const {onPublish} = this.props
const userName = this.refs.userName.value
const commentContent = this.refs.commentContent.value
let item = {userName, commentContent}
console.log(item)
onPublish(item)
}
state = { }
render() {
return (
<div>
用户名:<input type="text" ref="userName"></input>
评论内容:<textarea name="" id="" ref="commentContent" cols="30" rows="10"></textarea>
<button onClick={this.handlePublish}></button>
</div>
);
}
}
export default CommentInput;
<file_sep>/vue-learn/vue-plan/src/vuex/modules/com.js
import * as types from '../types'
const state = {
lists: [
{
avatar: "http://img2.imgtn.bdimg.com/it/u=1080760116,732088640&fm=26&gp=0.jpg",
name: "LN0",
date: "2019-06-25",
totalTime: "23",
comment: "今天天气真好"
}
],
totalTime: 23
}
const getters = {
lists: state => state.lists,
totalTime: state => state.totalTime
}
const mutations = {
[types.ADD_TOTAL_TIME] (state, time) {
state.totalTime += time
},
[types.DEC_TOTAL_TIME] (state, time) {
state.totalTime -= time
},
[types.SAVE_PLAN] (state, plan) {
state.lists.push(Object.assign({
avatar: "http://img2.imgtn.bdimg.com/it/u=1080760116,732088640&fm=26&gp=0.jpg",
name: "LN0"
}, plan))
}
}
const actions = {
addTotalTime({commit}, time) {
commit(ADD_TOTAL_TIME, time)
},
decTotalTime({commit} , time) {
commit(DEC_TOTAL_TIME, time)
},
savePlan({commit}, plan) {
commit(types.SAVE_PLAN, plan)
}
}
export default {
state,
mutations,
actions,
getters
}<file_sep>/CSS/BFC/README.md
# BFC 是一个什么概念
Block Formatting Context (块级格式化上下文)
# BFC 的原理 (渲染规则)
1. 正常的文档流会存在边距折叠的问题 (父子元素,兄弟元素)水平方向的外边距不存在折叠的情况(因为水平方向不存在块级元素)
2. BFC 容器不会与浮动元素的box重叠
3. BFC 在页面上是一个独立的容器,最显著的效果就是建立一个隔离的空间,外面的元素不会影响容器里面的元素,反之,里面的元素也不会影响容器外面的元素。
4. 计算 BFC 容器高度时,浮动元素也会参与高度的计算(也是通常清除浮动的原理)
# 创建 BFC 的条件
1. float的值不为none
2. <file_sep>/wxapp/miShopping/pages/mine/mine.js
// pages/mine/mine.js
const res = require('../../wxapi/request')
const app = getApp()
Page({
/**
* 页面的初始数据
*/
data: {
index: []
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function () {
this.getIndex()
},
getIndex() {
res
.loadIndex()
.then((res) => {
console.log(res.data)
this.setData({
index: res.data.sections
})
})
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function () {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function () {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function () {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function () {
},
/**
* 用户点击右上角分享
*/
onShareAppMessage: function () {
}
})<file_sep>/CSS/apple- watch/README.md
- h5 新标签 语义化
- sectio 部分
- header 头
- 居中
- 定位 50% 50%
- transform 适用于 不知道元素宽高
- margin 负值适用于 知道元素宽高<file_sep>/CSS/svg/jd_loading/README.md
loading 菊花图 gif
gif 设计 4kb -> 14kb
svg 省空间<file_sep>/js/33-js-concepts/30seconds/README.md
- 正则知识点
贪婪匹配 [0-9] +
+ 一次或多次
* 零次或多次
^ 的第二种用法 [^>]
- 函数参数
写一个函数,返回最大的两个数 [2,6,'a'], [8,4,6], [10] , 返回 [10,8]
1. Math.max 最便宜的求最大值
2. ...spread 展示一个数组
3. n个数? slice方法
综合题
- args
1. map + spread 运算符
2. 闭包
遍历每一项,
取前两个 slice + n + Math.max()
求最大值
取前两个 + 求最大值 做为一个功能 Math.max.slice(n)<file_sep>/js/game/invaders/README.md
- tileSprite 滚动背景
- bullets 30 个 性能
- SPACEBAR
update isDown<file_sep>/webpack/babel/babel-compiled.js
'use strict';
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var a = 1,
b = 2,
c = a + b;
console.log(c);
[1, 2, 3].map(function (item) {
return item + 'item';
});
// es6的大部分功能,其实es5也是能实现的,只不过不够优雅
var xlz = { name: '张三', hometown: '江西' };
xlz = _extends({}, xlz, { "company": '新浪' });
<file_sep>/js/node/spider/README.md
## 爬虫
http 请求
html -> 浏览器 解析
-> 服务器 普通文本信息 有价值的 解析出来 爬虫
## node
cheerio $ 解析 html 标签里的属性 attr('src') 标签的内容 text()
去浏览器看节点<file_sep>/INTERVIEW/es6/README.md
对es6的理解
es6 相对于 es5 ECMAScript 的第六次修订 ES2015 随着babel webpack构建工具的成熟,es6已成为js 编程的事实标准
es6 比 es5 更加简洁, 提高了开发效率,让 js 代码更优雅
- 新增的特性
let变量声明 const变量声明, 具有 var 没有的块级作用域,比如循环事件监听时闭包就不需要了,让代码更好理解
var 有变量提升的能力,let const 不会到顶级对象,使用的变量或常量要声明
- 箭头函数
简化了函数的表达形式
1. 不用 function 关键字 () => {}
2. 如果只有一个参数,() 也可以省
3. 如果代码直接返回,{} 也可以省
4. 有效的规避了this丢失的问题 指向上一级
- 模板字符串
增强版的字符串,用 `` , 他的多行表达方法,特别适合REACT JSX template 的书写
DOM 或 html 模板的构建 更加优雅
- 解构赋值
可解,可合,reset 从对象或数组中提取值, 对变量进行赋值,提高开发效率
- for of 循环
for 计步,数组友好,但是 对象, Set Map 类数组 以及字符串都可以遍历
- SET es6 新增的数据解构,类似数组。唯一的,没有重复的值
- import export es6的模块化, es6原生支持的module, 将js代码分割成不同的小块独立开发,一个文件一个类,一个独立的米快,比如说 utils api
- ...展开运算符
- 终于支持原生的class 关键字了,js 有了传统面向对象的写法, extends 不过只是语法糖,底层还是基于原型的面向对象
- promise 为 js 提供了异步解决方案, 规避了回调地狱
- es7 async await
koa 就是基于 asunc await 快速取代了express
- vue react 响应式编程依赖的proxy defineProperty 监听对象的改变,做一些事情
- es6 提供了新的数据类型,Symbol<file_sep>/js/leetcode/LRU/lru.js
//不用每次都去硬盘内查找,在内存中,缓存是一个很重要的概念
var LRUCache = function (capacity) {
this.capacity = capacity;
this.obj = {};//对象 key的设计方案 便于查找
this.arr = [];//数组
}
// 先设计两个方法 用jsonObject对象字面量 来实现 get set
LRUCache.prototype.get = function (key) {
// 使用伪代码 假设key只存正值
// 有返回值 设置为最近使用
// 没有 返回-1
// 以最小的空间换来最有效的空间存储,容量不大的内存服务于最多的进程
var val = this.obj[key];
if (val>0){
var index = this.arr.indexOf(key);
this.arr.splice(index,1);
this.arr.unshift(key);
}else{
return -1;
}
}
LRUCache.prototype.set = function (key, value) {
if (this.obj[key]) {
this.obj[key] = value;//之前已经有了,现在进来属于更新 最近使用 放置在数组最前面 下标为0
//操作数组
var index = this.arr.indexOf(key);//根据值,通过indexOf得到位置 key 值?
this.arr.splice(index, 1);//用splice方法根据下标删除
this.arr.unshift(key);//将此项用unshift操作放置于数组最前面
}
// 如有有key就返回,没有的话有两种可能
// 如果内存满了,arr.pop()从数组弹出去 维持了数组长度的不变
// 没满 直接unshift存进第0位
if (this.capacity === this.arr.length) {//放满了
var k = this.arr.pop();//最近最少使用
this.obj[k] = undefined;//找不到
}
this.obj[key] = value;
this.arr.unshift(key);
}
<file_sep>/js/33-js-concepts/30seconds/index.js
const htmlStr = '<p><em>lorem</em><strong>ipsum</strong></p>'
// 去除标签 输出lorem ipsum
// 正则 replace splice 规则
const stripHTMLTags = str => str.replace(/<[^>]*>/g, '')<file_sep>/webpack/details/READMD.md
devDependencies 开发阶段
Dependencies 开发阶段
webpack 是打包工具 构建应用
打包之前 development
打包之后 build dist/ 不再需要webpack 部署到服务器
- webpack-dev-server
webpack 打包好之后,将打包后的内容,在浏览器中的8080端口启动,是前端开发的标准
在一个端口打开web server
实时的编译 watch HMR
网页webpack打包的过程是这样的
index.js 是入口,打包成为 main.js index.html 首页的模板 main.js 会有 webpack-dev-server自动的放在index.html 的最后面script 引入<file_sep>/CSS/starwars/readme.md
#前端
- ! + tab emmet插件 emmet 以CSS query selector 完成快速输入
- CSS选择器运算符
1. [] 属性选择器
2. >子元素选择器
3. +兄弟选择器
4. <file_sep>/INTERVIEW-QUESTIONS/async-await/README.md
## async
async 函数就是 Generator 函数的语法糖。
## generate 函数
```js
function* test() {
let a = yield 1
console.log(a)
let b = yield 2
console.log(b)
let c = yield 3
console.log(c)
}
// 惰性的
var g = test()
```
通过 g.next() 一步一步调用 每一步调用执行到 yield 关键词
通过传参 可做为上一个 yield语句的返回值
## Promise.resolve
返回 Promise
1. 如果是 一个 promise 返回该 promise
2. 如果是一个值 resolve (该值)<file_sep>/js/node/static-resource-server/fileUpload.js
const http = require('http');
// 解析请求
const formidable = require('formidable');
const fs = require('fs');
const path = require('path');
http.createServer((req, res) => {
if (req.url === '/upload' &&
req.method.toLowerCase() === 'post') {
// 解析文件
const form = new formidable.IncomingForm();
form.uploadDir = './static/';
form.parse(req, (err, fields, files) => {
console.log(fields, files);
// <input type="file" name="upload">
const oldPath = files.upload.path;
const fileName = files.upload.name;
// static/upload_80d15cce58027743204875913f28271a
const dirname = path.dirname(oldPath);
// dirname === static/
const newPath = path.join(dirname, fileName);
fs.rename(oldPath, newPath, (err) => {
res.writeHead(200, {
'Content-Type': 'text/html;charset=utf8'
});
res.end('文件上传完毕');
})
})
return false;
}
res.writeHead(200, {
'Content-Type': 'text/html;charset=utf8'
});
res.end(
`
<form action="/upload" method="POST"
enctype="multipart/form-data">
<input type="file" name="upload">
<input type="text" name="nickname">
<input type="submit" value="submit">
</form>
`
)
})
.listen(8080, () => {
console.log('server is running port 8080');
})<file_sep>/js/leetcode/valid_parentheses/main.js
//验证的字符串的正确性
/**
* 功能是 决定字符串中的符号是正确的
* @params str 字符串,包含()[]{}
*/
const isValid = (str) =>{
let obj = {};
obj["{"] = "}";
obj["["] = "]";
obj["("] = ")";
let sta =[];
for(let i=0;i<str.length;i++){
if(!sta.length){
sta.push(str[i]);
}else{
if(str[i]===obj[sta[sta.length-1]]){
sta.pop();
}else{
sta.push(str[i]);
}
}
}
console.log(!sta.length);
}
isValid("({)");
isValid("(){}[]");
isValid("({})");<file_sep>/INTERVIEW/status_code/README.md
http req + res
状态码:HTTP响应的一部分
具体数值:浏览器 用户代理 发送正确的代码
statusCode 200 浏览器 成功
header 内容 text/plain
hello world 响应体
1xx 请求正在处理
2xx 请求成功处理
3xx 重新定向
301 永久跳转 会让浏览器缓存, http://loacalhost:8080/ 不会再走服务器
302 临时跳转<file_sep>/js/extend/README.md
person 由 prototype 属性来解决他自身构造之外的原型上的属性或方法
原型对象会由它的构造函数 person.prototype.constructor属性
实例 跟 person 有什么关系,person.prototype 有关系
js 实力跟类其实不是 java 等语言的血缘关系
zs 实例是 new person() 得到的
1. person 函数运行 new 的方式, this=> new Object();
2. zs 怎么得到person.prototype原型对象上定义的方法 __proto__ 属性
3. 方法有prototype属性,值为对象 对象上就可以开支
4. 任何对象都有 __proto__ 指向它的原型对象
5. 原型对象上 有 constrctor 属性指向它的构造函数
原型<file_sep>/CSS/xiaoce/README.md
## 界面大框架及经验
水平方向禁止滚动条,垂直方向出现滚动条
- 水平和垂直两个方向都滚动,页面摇晃,容易误操作
- 垂直方向一直滚动是开发的主要方式
- margin:0 auto; max-width:960px;
- flex 布局
flex-grow 放大 flex-basis flex-shrink 缩小 flex-wrap
当网页由PC到mobile时,缩小阵仗
经验 简单适配PC -> mobile 照顾所有的用户 PC端 大手大脚一点, max-width margin: aotu padding margin
mobile flex-shrink 让关键部分坚挺一点<file_sep>/wxapp/wxmall/README.md
开发流程和工艺
1. 细化模块,api模块
module.exports = {
api列表...
}
如果代码再重复,请封装
2. 前后端分离
后端API 看文档
url method data
前后端怎么配合?
3. UI 选框架
4. 没有后台怎么办
easy-mock
request 方法改写 database
5. weui(推荐) / vant
界面,小程序就是切页面
6. 将每个页面,每个功能封装一个函数 unit
小米商城 快够打车 丁香医车 优衣库 有赞优选 小红书 51信用卡助手 毛豆二手车 携程 马蜂窝 京东购物 美团外卖 口碑 膜拜单车
青桔单车 思否课堂 二维火点餐 58同城二手房 微博鲜知 新浪新闻 小米有品 网易云课堂 肯德基 拉勾网 滴滴出行 爱奇艺 美丽说
蘑菇街 沪江英语 拼多多
写代码,设定一个任务
<file_sep>/vue-learn/mp-vue/todolista/note.md
## miniprogramRoot
/dist/wx
指定了小程序的源码目录
整份目录是 mpvue 定制化过的
/src 目录 vue 的风格
以 vue 写小程序
mpvue 1.x 微信小程序
mpvue 2.x 主流小程序
## mpvue
模板: vue 组件 和 小程序组件
js: vue.js + wxScript
<file_sep>/js/node/express/READMD.md
- exprcess
- cros 跨域
- cross-env 跨系统设置process
- webpack 工作流
- eslint 代码风格<file_sep>/js/dom-event/README.md
dom event(事件)
- dom
onclick 事件注册只有一个 dom-0
addEventListener('click') 不限 dom-2
addEventListener('keyup') 不限 dom-3
- event
event.stopProgration() 阻止事件冒泡
event.stopTmmediatePropagation() 阻止后面注册的事件
- dom 事件流
捕获 (capture)
window -> document(documentElement) -> body -> 父级 -> 目标元素
冒泡 (bubble)
window <- document(documentElement) <- body <- 父级 <- 目标元素
时间按照 dom流的顺序执行我们的事件回调
处于目标阶段的时候 事件调用顺序取决于时间注册的顺序
- 事件代理 (事件委托)
event-question.html
原理:冒泡<file_sep>/vue-learn/full_history/index.js
var http = require('http');
var fs = require('fs');
// 前端路由,spa 用户体验 快,没有白屏 vue router component
// 后端路由 http server api 数据 ajax
http.createServer(function(req, res) {
var filepath = '.' + req.url;
if (filepath === './') {
filepath = './index.html';
}
readFile(filepath, res);
}).listen(80);
function readFile (path, res) {
fs.readFile(path, 'utf-8', function(err, data) {
if(err) {
readFile('./index.html', res)
// throw new Error('出错了')
}else {
res.write(data);
res.end();
}
});
}<file_sep>/wxapp/wxapp-mi/wxapi/main.js
const BASE_URL = "https://www.easy-mock.com/mock/5cd75ce0b05b3355ce10ea3d/wxapp-mi"
const request = (url, needSubDomain, method, data) => {
return new Promise ((resolve, reject) => {
let _url = BASE_URL + '/' + url
wx.request({
url: _url,
method: method,
data: data,
header: {
'Content-Type': 'application/x-www-form-urllencoded'
},
success(request) {
resolve(request.data)
},
fail(error) {
reject(error)
}
});
})
}
module.exports = {
loadSwip: (data) => {
return request('index', true, 'get', data)
},
loadNavBar: (data) => {
return request('index', true, 'get', data)
},
loadRecommend: (data) => {
return request('index', true, 'get', data)
},
loadCategory: (data) => {
return request('category', true, 'get', data)
},
loadCategoryItem: (data) => {
return request('category', true, 'get', data)
}
}<file_sep>/webgl/earth/README.md
引入一个 js 库 jquery react vue , 有点大, 90kb 下载的过程, 还要运行。
script 标签时阻塞型的,放在页面的底部,让 html,css 先看到良好的页面,网页的响应会更快
three.js 有点大<file_sep>/vue-learn/vue-music/src/vuex/types.js
export const COM_SHOW_SIDE_BAR = 'COM_SHOW_SIDE_BAR' // 侧边栏
export const SET_FULL_SCREEN ='SET_FULL_SCREEN' //设置播放器是否全屏展示
export const COM_SAVE_SEARCH_HISTORY = 'COM_SAVE_SEARCH_HISTORY' //保存搜索历史
export const SET_PLAYLIST = 'SET_PLAYLIST' // 播放列表
export const SET_CURRENT_INDEX = 'SET_CURRENT_INDEX' //设置播放音乐的索引
export const SET_PLAYING = 'SET_PLAYING' // 播放状态
export const SAVE_PLAY_HISTORY = 'SAVE_PLAY_HISTORY' // 保存播放历史
export const SAVE_FAVORITE_LIST = 'SAVE_FAVORITE_LIST' //保存喜欢歌曲<file_sep>/CSS/weui/REadme.md
#WEUI
来自于微信的前端开发框架,
- 微信生态 公众号 小程序
weui.css 在基础上做开发
- app 生态
内嵌的html
- pc 传统网站 Bootstrap
- 界面的编写过程
- html 结构,独立于样式
DOM文档流 从左到右,从上到下
- 取类名很重要
BEM 规范
Block 区块 weui-cell
weui-button 30-50个复用的组件
Element 元素
weui-cell__hd
weui-cell__bd
weui-cell__ft
通用的词汇 hd + bd + ft
- 再写样式
- 离开文档流
里面的元素不再受影响,before absolute 脱离了正常的文档流
weui-cells border-top 使用了盒子模型,元素在页面上的占位,是需要综合考虑 内容 w*h
padding border margin position
- 1px 边框
css 像素 1px 在手机里
硬件物理像素 retina 2px 3倍retina 3px 使用 transform scaleY(.5) 压一下
浏览器不会处理小数点像素
transform-origin: 基点,那个点不动 上边线,从下往上压 scaleY
- flex
不受块级的约束,他的内部是一个新的世界 弹性布局是父与子们的一起的布局
好用的对齐方式 align-items 纵轴对齐方式 居中 justify-content 横轴在一堆子元素中,只给一个元素设置 flex:1 这个元素成为主元素,
其他元素占完自己该占的盒子模型的内容后,余下的空间都交给主体元素。
var 与 let
let 支持块级作用域{}
let 变量不会污染window
var 时代没有 const 可以window.<file_sep>/js/security/sql_injection/README.md
前端安全
表单
form -> onsubmit -> url
POST data:
email: '<EMAIL>'
password: '<PASSWORD>'
后端 登陆过程sql查找的过程 sql 语法报错,服务器出错
用户的输入不可信任
password' sql 的提前结束或多了一个 500 编码解码
登陆账号
SELECT * from users
WHERE email = '<EMAIL>'
AND password = '<PASSWORD>'<file_sep>/INTERVIEW-QUESTIONS/Q11/demo2.js
function findKthLargest(nums, k) {
const arr = quick_sort(nums)
return arr[k-1]
}
function quick_sort(arr) {
if (arr.length <= 1) return arr;
var left = [],
right = [],
baseDot = Math.round(arr.length / 2),
base = arr.splice(baseDot, 1)[0];
for(var i = 0; i < arr.length; i++) { //O(n)
if(arr[i] < base) {
left.push(arr[i])
}else {
right.push(arr[i])
}
}
return quick_sort(left).concat([base], quick_sort(right)); // O(log2N)
}<file_sep>/react/react-state-flow/src/CommentList.jsx
import React, { Component } from 'react';
class CommentList extends Component {
render() {
const {Comment} = this.props
return (
<>
<li>
user: {Comment.userName}
content: {Comment.commentContent}
</li>
</>
);
}
}
export default CommentList;
<file_sep>/webpack/js_test/README.md
代码测试 代码测试工程师
代码 + 测试 = 上线
自己写的代码自己测试
babel js es6 => es5
eslint js 是否工整
stylus
mocha
webpack<file_sep>/js/node/static-resource-server/README.md
## 静态资源
不会随着服务运行二改变内容: html css js 图片
1. 如果有 index.html打开
2. 否则列出所有文件
3. 请求 路径和磁盘路径一一对应
## 打开方式
file:// 本地文件读取协议 ./xx.png ok
http://localhost:8080/ http 协议
html 里面引入的资源,都会发出请求
请求: /static/*.* 磁盘位置static目录下面 --对应
1. 拿到 req.url
2. 读取磁盘下面的同一个位置 返回
3. 静态资源通常会放在某一个目录下面 /static/ 所有请求都以某个目录开头 ……
## 上传图片
### formidable
处理请求的
fileds 是input [type="file"] 的提交项
files input[type="file] 提交项
根据 input 的 name 属性来获取值<file_sep>/js/args/demo2.js
// 1. userObj 一个参数带来了新的问题,代码的函数编写者, user 里面的key 要去了解 只需要用一部分, 解构可以帮助,
// 提高代码的可读性
function infomation({name, age, height}) {
console.log(name, age, height)
}
const user = {
name: '李四',
age: 22,
height: 1.8,
sex: '男',
hobbies: ['打游戏']
}
infomation(user)<file_sep>/INTERVIEW-QUESTIONS/Q11/valid-palindrome/index.js
// function validPalindrome(str) {
// var a = str.split('').reverse().join('')
// return a === str
// }
// console.log(validPalindrome('aba'))
var isValidChar = (c) => { // abc 123
return /^[\w]$/.test(c)
}
var isPalindrom = (s) => {
s = s.toLowerCase();
let left = 0,
right = s.length - 1;
while(left < right) {
if(!isValidChar(s[left])) {
left++;
container;
}
if(!isValidChar(s[right])) {
right--;
continue;
}
if(s[left] == s[right]) {
left++;
right--;
} else {
break
}
}
return right <= left;
}<file_sep>/js/node/event/event.js
// 原生的模块
// 供其他模块使用 比如 http res 继承自 Event
const Event = require('events');
const ev = new Event();
ev.on('open', () => {
console.log('open 发生了');
})
function callBack(){
console.log('第二个 回调');
}
ev.on('open', callBack);
// removeEventListener
ev.emit('open');
ev.removeListener('open',callBack);
ev.emit('open');
ev.once('one',(data)=>{
console.log(data)
})
ev.emit('one','form emit data ');
ev.emit('one');<file_sep>/js/node/跨域/fe/跨域/README.md
## 跨域
浏览器的安全策略
同源策略:
同协议 域名 端口 同源 不存在跨域
不同源 存在跨域
## CORS
规定了一组 http 的头部字段作用是:
允许哪些网站通过浏览器有访问的权限
1. access-X
2. cookie
3. 浏览器会先 以 OPTIONS 请求方法发起一个预检
(preflight) 请求,获取一下允不允许当前的域请求,服务器允许之后才会发起正式的请求。
## 代理
1. nginx
反向代理:
http://localhost:9999/api/
http://localhost:8888/api/
不知道 请求的是哪个服务器
正向代理:
google
A -> proxy -> google.com
B -> proxy -> google.com
## iframe + postMessage
1. 前端页面 通过 iframe 引入一个 后端目录下面的 html,
iframe 是不受同源策略限制的,
2. postMessage 用于在两个窗口之间传递数据
3. 前端页面 通过 postMessage 向 后端目录下面的 html 传递
接口需要的请求参数
4. 后段页面 通过 postMessage 向前端页面 传递 接口结果
## iframe + window.name
iframe 共享 window.name
## jsonp
<file_sep>/js/leetcode/demo1/README.md
[twitter]()
写一个函数 参数为 一句话,英文的
- 如果字符超过140字,返回false
- 如果是空字符,返回false
- 以#开始
- 每个单词首字母大写
hello miss dong<file_sep>/js/throttle/README.MD
search suggest 帮助用户快速找到他想找的内容
根据词匹配 分词
adc def 有必要每打一次keyup 都去搜索吗? 防止多次,性能问题
打完一个单词再去搜 basketball
定时器实现了防抖 debounce 函数利用闭包(放回新函数),将定时器id ,封闭在闭包空间中,下一次的keyup 会消除上一次的timeout,只有最后一个keyup 间隔时间超过delay 得以执行,在频繁触发时,只执行一次<file_sep>/js/ES6/template-string/README.md
ECMAScript ES
说我们的 JS 语法 类型。。。
## js
模板字符串
- 增强版字符串
- 用 ` 表示
- 变量放在 ${} 任意JS<file_sep>/js/node/fs/README.md
node 让 js 来到后端
服务器 linux
文件系统操作 fs
没有DOM
文件读取 要花时间 定位文件参数1,打开文件,将文件内容读到内存中 输出到命令行
js是单线程语言 花时间 js 中就要异步
1. callback fs.readFile(path,'utf-8',function(err,data){})
2. promise
分开,Promise 是类 是用于畜栏里异步问题的类,为了防止回调地狱,看到好事问题就用出一个 Promise 实例
resolve 将控制权交给 then 并且将结果 resolve(data) reject 失败 catch{ } <file_sep>/js/leetcode/sort/README.md
- 最简单的排序算法
选择排序 bubbleSort
排序的过程,两两相比,如果 j 小于 i 的位置上的数,互换i ,j 两重循环
一重循环之后,我们一定可以得到最小值在相应的位置上每次解决一个位置
i = 0 i < length - 1 i++
j = i + 1 j< length j++
时间复杂度 n^2
- 冒泡排序 index
相邻元素的比较,一次外层循环,将一个数排好,每次内层循环要执行 len - i - 1
时间复杂度 n^2
- 快排
递归 时间复杂度 log2 N
- 中序遍历
<file_sep>/js/calculate/demo.js
var PerformanceS = function(){
}
PerformanceS.prototype.calculate = function(salary){
return salary * 5;
}
var PerformanceA = function(){
}
PerformanceA.prototype.calculate = function(salary){
return salary * 4;
}
var Bounce = function(salary){
this.salary = salary;
}
Bounce.prototype.setStrategy = function(strategy){
this.strategy = strategy;
}
Bounce.prototype.getBounce = function(){
return this.strategy.calculate(this.salary);
}
var Bounce = new Bounce(4000);
Bounce.setStrategy(new PerformanceS());
console.log(Bounce.getBounce());
| 04bee861ce1366832ba203beb05d86b352086ed0 | [
"Markdown",
"TypeScript",
"JavaScript"
] | 164 | Markdown | ZHNLN0/js_fullStack | 9f3c9a0f5b428d9c5b5063fa7479d0875e822615 | 834b67a59634245447d82c5e63fa0b688f455a38 |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static System.Math; //Usando using static
using static System.Console; //Usando using static
using System.Globalization;
namespace NovidadesCSharp6
{
class Program
{
static void Main(string[] args)
{
string texto = "Teste utilizando expressões lambda na janela watch do visual studio";
string[] array = texto.Split(new string[] { " " }, StringSplitOptions.None);
//array.Where(x => x.Contains("a")).ToArray();
//Usando Static
//versão anteriores do c#
int numero = 4;
Console.WriteLine("Número: " + numero);
Console.WriteLine("Raiz quadrada = " + Math.Sqrt(numero));
Console.WriteLine(string.Format("{0} ^ 5 = {1}",numero,Math.Pow(numero, 5)));
Console.WriteLine(string.Format("{0} ^ 10 = {1}", numero, Math.Pow(numero, 10)));
Console.WriteLine();
//Usando using static
//Forma simples para invocação do métodos estáticos
//using static System.Math;
//using static System.Console;
WriteLine($"Número {numero}");
WriteLine($"Raiz quadrada = {Sqrt(numero)}");
WriteLine($"{numero} ^ 5 = {Pow(numero, 5)}");
WriteLine($"{numero} ^ 10 = {Pow(numero, 10)}");
WriteLine();
//Operdor nameof
string strExemplo1 = "Exemplo1";
string strExemplo2 = "Exemplo2";
WriteLine($"Variável 1: {nameof(strExemplo1)}");
WriteLine($"Variável 2: {nameof(strExemplo2)}");
//Dictionary
Dictionary<string, string> capitais = new Dictionary<string, string>();
capitais.Add("SP", "São Paulo");
capitais.Add("RJ", "Rio de Janeiro");
capitais.Add("DF", "Distrito Federal");
//nova forma de inicializar um dictionary. Semelhante a com o padrão JSON
Dictionary<string, string> capitaisNova = new Dictionary<string, string>()
{
["SP"] = "São Paulo",
["RJ"] = "Rio de Janeiro",
["DF"] = "Distrito Federal"
};
//Capiturando diferentes "Niveis" de uma mesma exception sem precisar usar if
try
{
throw new TesteException("Gerado um erro para demostração.");
}catch (TesteException ex) when (ex.NivelSeveridade ==1)
{
WriteLine("Aconteceu um erro com um nivel serveridade baixo.");
}
catch (TesteException ex) when (ex.NivelSeveridade <= 3)
{
WriteLine("Aconteceu um erro com um nivel serveridade moderado.");
}
catch (TesteException ex)
{
WriteLine("Aconteceu um erro com um nivel serveridade alto.");
}
//Trabalhando com formatação de strings
DateTime dataAtual = DateTime.Now;
CultureInfo configLocal = new CultureInfo("pt-BR");
var msg = string.Format("Brasilia, {0} de {1} de {2} - {3:HH:MM:ss}",
dataAtual.Day,
configLocal.DateTimeFormat.GetMonthName(dataAtual.Month),
dataAtual.Year,
dataAtual);
var msgNova =
$"Brasilia , {configLocal.DateTimeFormat.GetDayName(dataAtual.DayOfWeek)}, {dataAtual.Day} " +
$"de {configLocal.DateTimeFormat.GetMonthName(dataAtual.Month)} de {dataAtual.Year} - {dataAtual:HH:MM:ss}";
WriteLine(msg);
WriteLine(msgNova);
ReadKey();
}
}
public enum TipoLog
{
Informacao,
Alerta,
Erro
}
public class MessagemLog
{
public DateTime Data { get; } = DateTime.Now;
public TipoLog Tipo { get; set; } = TipoLog.Informacao;
public string Mesagem { get; set; }
}
public class ItemPedido
{
public string CodigoBarras { get; set; }
public int Quantidade { get; set; }
public double Preco { get; set; }
public double TotalItem => Quantidade * Preco;
//public double TotalItem
//{
// get { return Quantidade * Preco; }
//}
public override string ToString() => CodigoBarras;
//public override string ToString()
//{
// return CodigoBarras;
//}
}
public class TesteException: Exception
{
public int NivelSeveridade { get; }
public TesteException(string msg) : base(msg)
{
Random r = new Random();
NivelSeveridade = r.Next(1, 5);
}
}
}
| ca266adf108588489a8940d0634977dddfa29c5a | [
"C#"
] | 1 | C# | higorcesarqn/novidades-C-Shape-6.0 | 3fb6dde09717335e5789f0a204f470be5853b932 | 7419ea39bae3fe7b6945d6fd88df789b4cc91b11 |
refs/heads/main | <repo_name>Cyao118/DenseNet-with-pytorch<file_sep>/README.md
# DenseNet-with-pytorch
使用pytorch实现DenseNet,完成完整的代码框架,从建立数据集、设置参数、训练网络到推理测试。
使用方法详见知乎:https://zhuanlan.zhihu.com/p/385606979
<file_sep>/dataloaders/cfg.py
# -*- coding:utf-8 -*-
##数据集的类别
NUM_CLASSES = 2
#数据集的存放位置
DATASET_DIR = r'/media/jzdyjy/EEB2EF73B2EF3EA9/workstore/lekang/DenseNet/densenet_v0/data'
TRAIN_DATASET_DIR = r'/media/jzdyjy/EEB2EF73B2EF3EA9/workstore/lekang/DenseNet/densenet_v0/data/train'
VAL_DATASET_DIR = r'/media/jzdyjy/EEB2EF73B2EF3EA9/workstore/lekang/DenseNet/densenet_v0/data/val'
TEST_DATASET_DIR = r'/media/jzdyjy/EEB2EF73B2EF3EA9/workstore/lekang/DenseNet/densenet_v0/inference/image'
# DATASET_DIR = r'F:/lekang/PycharmPreject/NeralNetwork/DenseNet/densenet_lk/data'
# TRAIN_DATASET_DIR = r'F:/lekang/PycharmPreject/NeralNetwork/DenseNet/densenet_lk/data/train'
# VAL_DATASET_DIR = r'F:/lekang/PycharmPreject/NeralNetwork/DenseNet/densenet_lk/data/val'
# TEST_DATASET_DIR = r'F:/lekang/PycharmPreject/NeralNetwork/DenseNet/densenet_lk/inference/image'
#这里需要加入自己的最终预测对应字典,例如:'0': '花'
labels_to_classes = {
'0' : 'OK',
'1' : 'NG'
}
| 1004d92df4cd61f13772f26151212d0fb68a8715 | [
"Markdown",
"Python"
] | 2 | Markdown | Cyao118/DenseNet-with-pytorch | 1d3c5241c63a71e353e55260a89e36467bbdb1f1 | 015d47741545a7ba7533df3a5caf11973cbc1551 |
refs/heads/main | <file_sep># database-manager
Application for managing PostgreSQL database
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Npgsql;
namespace projekt38
{
public partial class Form1 : Form
{
NpgsqlConnection conn = new NpgsqlConnection();
DataSet ds = new DataSet();
DataTable dt = new DataTable();
NpgsqlDataAdapter da = new NpgsqlDataAdapter();
NpgsqlCommand nc = new NpgsqlCommand();
string sql = "";
bool wlacznik = true;
string wybranaZakladka = "INSERT";
string id, nazwaFirmy, branza, adres1, adres2, telefonSta, telefonKom, fax, email, stronaWWW;
string imie, nazwisko, wydzial;
string szukanaFraza;
string usuwaneID;
public Form1()
{
InitializeComponent();
textBox20.CharacterCasing = CharacterCasing.Lower;
}
protected override void WndProc(ref Message m)
{
if (m.Msg == 0x00A4)
{
if (button1.Text == "DISCONNECT")
{
if (wybranaZakladka == "SHOW")
{
try
{
WyswietlDane();
}
catch (Exception msg)
{
MessageBox.Show(msg.ToString());
throw;
}
}
if (wybranaZakladka == "INSERT")
{
try
{
if (SprawdzDane())
{
UstawId();
nazwaFirmy = textBox6.Text;
branza = comboBox1.Text;
wydzial = textBox7.Text;
imie = textBox8.Text;
nazwisko = textBox9.Text;
adres1 = textBox10.Text + " " + textBox11.Text + "/" + textBox12.Text;
adres2 = textBox13.Text + " " + textBox14.Text;
telefonSta = textBox15.Text;
telefonKom = textBox16.Text;
fax = textBox17.Text;
email = textBox18.Text;
stronaWWW = textBox19.Text;
WstawDane();
}
}
catch (Exception msg)
{
MessageBox.Show(msg.ToString());
throw;
}
}
if (wybranaZakladka == "FIND")
{
try
{
szukanaFraza = textBox20.Text;
SzukajDanych();
}
catch (Exception msg)
{
MessageBox.Show(msg.ToString());
throw;
}
}
if (wybranaZakladka == "DELETE")
{
try
{
if (textBox22.Text.All(Char.IsDigit) && textBox22.Text.Length > 0)
{
usuwaneID = textBox22.Text;
UsunDane();
}
}
catch (Exception msg)
{
MessageBox.Show(msg.ToString());
throw;
}
}
}
}
else
{
base.WndProc(ref m);
}
}
void UstawId()
{
try
{
sql = "SELECT adresy.id FROM adresy;";
da = new NpgsqlDataAdapter(sql, conn);
id = da.Fill(ds).ToString();
}
catch (Exception msg)
{
MessageBox.Show(msg.ToString());
throw;
}
}
void WypelnijCombobox()
{
try
{
sql = "SELECT branze.nazwa FROM branze;";
nc = new NpgsqlCommand(sql, conn);
NpgsqlDataReader mr;
mr = nc.ExecuteReader();
while (mr.Read())
{
comboBox1.Items.Add(mr["nazwa"].ToString());
}
comboBox1.SelectedIndex = 0;
}
catch (Exception msg)
{
MessageBox.Show(msg.ToString());
throw;
}
}
void UstawElementy()
{
if (!wlacznik)
{
label1.ForeColor = Color.Red;
label2.ForeColor = Color.Red;
label3.ForeColor = Color.Red;
label4.ForeColor = Color.Red;
label5.ForeColor = Color.Red;
tabControl1.Enabled = false;
textBox1.Enabled = true;
textBox2.Enabled = true;
textBox3.Enabled = true;
textBox4.Enabled = true;
textBox5.Enabled = true;
wlacznik = true;
button1.Text = "CONNECT";
comboBox1.Items.Clear();
dataGridView1.DataSource = null;
dataGridView1.Rows.Clear();
textBox1.Clear();
textBox2.Clear();
textBox3.Clear();
textBox4.Clear();
textBox5.Clear();
textBox6.Clear();
textBox7.Clear();
textBox8.Clear();
textBox9.Clear();
textBox10.Clear();
textBox11.Clear();
textBox12.Clear();
textBox13.Clear();
textBox14.Clear();
textBox15.Clear();
textBox16.Clear();
textBox17.Clear();
textBox18.Clear();
textBox19.Clear();
textBox6.BackColor = Color.White;
textBox7.BackColor = Color.White;
textBox8.BackColor = Color.White;
textBox9.BackColor = Color.White;
textBox10.BackColor = Color.White;
textBox11.BackColor = Color.White;
textBox12.BackColor = Color.White;
textBox13.BackColor = Color.White;
textBox14.BackColor = Color.White;
textBox15.BackColor = Color.White;
textBox16.BackColor = Color.White;
textBox17.BackColor = Color.White;
textBox18.BackColor = Color.White;
textBox19.BackColor = Color.White;
}
else
{
label1.ForeColor = Color.Green;
label2.ForeColor = Color.Green;
label3.ForeColor = Color.Green;
label4.ForeColor = Color.Green;
label5.ForeColor = Color.Green;
tabControl1.Enabled = true;
textBox1.Enabled = false;
textBox2.Enabled = false;
textBox3.Enabled = false;
textBox4.Enabled = false;
textBox5.Enabled = false;
wlacznik = false;
button1.Text = "DISCONNECT";
WypelnijCombobox();
MessageBox.Show("Ustanowiono połączenie z bazą danych.");
WyswietlDane();
}
}
void WyswietlDane()
{
try
{
sql = "SELECT adresy.id, adresy.nazwa_firmy, adresy.branza, uzytkownicy.wydzial, uzytkownicy.imie_pracownika, uzytkownicy.nazwisko_pracownika, adresy.adres1, adresy.adres2, adresy.telefon_sta, adresy.telefon_kom, adresy.fax, adresy.email, adresy.strona_www FROM adresy INNER JOIN uzytkownicy ON adresy.id=uzytkownicy.id;";
da = new NpgsqlDataAdapter(sql, conn);
ds.Reset();
da.Fill(ds);
dt = ds.Tables[0];
dataGridView1.DataSource = dt;
}
catch (Exception msg)
{
MessageBox.Show(msg.ToString());
throw;
}
}
void SzukajDanych()
{
try
{
sql = string.Format("SELECT adresy.id, adresy.nazwa_firmy, adresy.branza, uzytkownicy.wydzial, uzytkownicy.imie_pracownika, uzytkownicy.nazwisko_pracownika, adresy.adres1, adresy.adres2, adresy.telefon_sta, adresy.telefon_kom, adresy.fax, adresy.email, adresy.strona_www FROM adresy INNER JOIN uzytkownicy ON adresy.id=uzytkownicy.id WHERE CAST(adresy.id as VARCHAR(10)) LIKE '%{0}%' OR LOWER(adresy.nazwa_firmy) LIKE '%{0}%' OR LOWER(adresy.branza) LIKE '%{0}%' OR LOWER(uzytkownicy.wydzial) LIKE '%{0}%' OR LOWER(uzytkownicy.imie_pracownika) LIKE '%{0}%' OR LOWER(uzytkownicy.nazwisko_pracownika) LIKE '%{0}%' OR LOWER(adresy.adres1) LIKE '%{0}%' OR LOWER(adresy.adres2) LIKE '%{0}%' OR CAST(adresy.telefon_sta as VARCHAR(10)) LIKE '%{0}%' OR CAST(adresy.telefon_kom as VARCHAR(10)) LIKE '%{0}%' OR CAST(adresy.fax as VARCHAR(10)) LIKE '%{0}%' OR LOWER(adresy.email) LIKE '%{0}%' OR LOWER(adresy.strona_www) LIKE '%{0}%';", szukanaFraza);
da = new NpgsqlDataAdapter(sql, conn);
ds.Reset();
da.Fill(ds);
dt = ds.Tables[0];
dataGridView1.DataSource = dt;
}
catch (Exception msg)
{
MessageBox.Show(msg.ToString());
throw;
}
}
void WstawDane()
{
try
{
sql = string.Format("INSERT INTO adresy (id, nazwa_firmy, branza, adres1, adres2, telefon_sta, telefon_kom, fax, email, strona_www) VALUES ('{0}', '{1}', '{2}', '{3}', '{4}', '{5}', '{6}', '{7}', '{8}', '{9}');", id, nazwaFirmy, branza, adres1, adres2, telefonSta, telefonKom, fax, email, stronaWWW);
da = new NpgsqlDataAdapter(sql, conn);
da.Fill(ds);
sql = string.Format("INSERT INTO uzytkownicy (id, imie_pracownika, nazwisko_pracownika, wydzial) VALUES ('{0}', '{1}', '{2}', '{3}')", id, imie, nazwisko, wydzial);
da = new NpgsqlDataAdapter(sql, conn);
da.Fill(ds);
WyswietlDane();
}
catch (Exception msg)
{
MessageBox.Show(msg.ToString());
throw;
}
}
void UsunDane()
{
try
{
sql = string.Format("DELETE FROM adresy WHERE adresy.id={0};", usuwaneID);
da = new NpgsqlDataAdapter(sql, conn);
da.Fill(ds);
sql = string.Format("DELETE FROM uzytkownicy WHERE uzytkownicy.id={0};", usuwaneID);
da = new NpgsqlDataAdapter(sql, conn);
da.Fill(ds);
WyswietlDane();
}
catch (Exception msg)
{
MessageBox.Show(msg.ToString());
throw;
}
}
bool SprawdzDane()
{
bool stan = true;
if (textBox6.Text.Length > 2)
{
textBox6.BackColor = Color.LimeGreen;
}
else
{
textBox6.BackColor = Color.Red;
stan = false;
}
if (textBox7.Text.Length > 2)
{
textBox7.BackColor = Color.LimeGreen;
}
else
{
textBox7.BackColor = Color.Red;
stan = false;
}
if (textBox8.Text.All(Char.IsLetter) && textBox8.Text.Length > 2)
{
textBox8.BackColor = Color.LimeGreen;
}
else
{
textBox8.BackColor = Color.Red;
stan = false;
}
if (textBox9.Text.All(Char.IsLetter) && textBox9.Text.Length > 2)
{
textBox9.BackColor = Color.LimeGreen;
}
else
{
textBox9.BackColor = Color.Red;
stan = false;
}
if (textBox10.Text.All(Char.IsLetter) && textBox10.Text.Length > 2)
{
textBox10.BackColor = Color.LimeGreen;
}
else
{
textBox10.BackColor = Color.Red;
stan = false;
}
if (textBox11.Text.All(Char.IsDigit) && textBox11.Text.Length > 0)
{
textBox11.BackColor = Color.LimeGreen;
}
else
{
textBox11.BackColor = Color.Red;
stan = false;
}
if (textBox12.Text.All(Char.IsDigit) && textBox12.Text.Length > 0)
{
textBox12.BackColor = Color.LimeGreen;
}
else
{
textBox12.BackColor = Color.Red;
stan = false;
}
if (textBox13.Text.All(Char.IsDigit) && textBox13.Text.Length.Equals(5))
{
textBox13.BackColor = Color.LimeGreen;
}
else
{
textBox13.BackColor = Color.Red;
stan = false;
}
if (textBox14.Text.All(Char.IsLetter) && textBox14.Text.Length > 2)
{
textBox14.BackColor = Color.LimeGreen;
}
else
{
textBox14.BackColor = Color.Red;
stan = false;
}
if (textBox15.Text.All(Char.IsDigit) && textBox15.Text.Length.Equals(9))
{
textBox15.BackColor = Color.LimeGreen;
}
else
{
textBox15.BackColor = Color.Red;
stan = false;
}
if (textBox16.Text.All(Char.IsDigit) && textBox16.Text.Length.Equals(9))
{
textBox16.BackColor = Color.LimeGreen;
}
else
{
textBox16.BackColor = Color.Red;
stan = false;
}
if (textBox17.Text.All(Char.IsDigit) && textBox17.Text.Length.Equals(9))
{
textBox17.BackColor = Color.LimeGreen;
}
else
{
textBox17.BackColor = Color.Red;
stan = false;
}
if (textBox18.Text.Length > 6)
{
textBox18.BackColor = Color.LimeGreen;
}
else
{
textBox18.BackColor = Color.Red;
stan = false;
}
if (textBox19.Text.Length > 4)
{
textBox19.BackColor = Color.LimeGreen;
}
else
{
textBox19.BackColor = Color.Red;
stan = false;
}
return stan;
}
private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
{
if (tabControl1.SelectedTab == tabPage1)
{
wybranaZakladka = "SHOW";
}
if (tabControl1.SelectedTab == tabPage2)
{
wybranaZakladka = "INSERT";
}
if (tabControl1.SelectedTab == tabPage3)
{
wybranaZakladka = "FIND";
}
if (tabControl1.SelectedTab == tabPage4)
{
wybranaZakladka = "DELETE";
}
}
private void button1_Click(object sender, EventArgs e)
{
try
{
if (wlacznik)
{
string connstring = String.Format("Server={0};Port={1};User Id={2};Password={3};Database={4};", textBox1.Text, textBox2.Text, textBox3.Text, textBox4.Text, textBox5.Text);
conn = new NpgsqlConnection(connstring);
conn.Open();
UstawElementy();
}
else
{
conn.Close();
UstawElementy();
}
}
catch
{
}
}
}
}
| 12169a19040f432109d40969721169d193cd255b | [
"Markdown",
"C#"
] | 2 | Markdown | michal-skowron-dev/database-manager | 14af3356d3f410a9ebf0b8c376e07d351ab349d5 | 5c891448e0205b121dd5c2891edb5fd60a3ddde4 |
refs/heads/master | <repo_name>ApplicationPlatformForIoT/sample-collection<file_sep>/sdk/gateway/ingest/nodejs/index.js
var httpServiceUri = "<from registration ticket of gateway>";
var httpServicePath = "<from registration ticket of gateway>";
var gatewayID = '<from registration ticket of gateway, tag DataCollectorId>';
var sensorID = '<in developer portal, get internal id from the sensor you would like to upload data from>';
var httpSAS = '<from registration ticket of gateway>';
// Import standard node.js libraries
var https = require('https');
var url = require('url');
// Import moment.js library for Unix timestamp conversion
var moment = require('moment');
// Import readline.js ibrary to enable command line communication
var readline = require('readline');
console.log('Welcome to the temperature emulator');
var rl = readline.createInterface(process.stdin, process.stdout);
rl.question("Current temperature? ", function (answer) {
console.log("Uploading temperature: " + answer);
SendPayload(answer);
rl.close();
});
function SendPayload(temperature) {
// Timestamp of measurement from sensors, can be a historical value due to occasionally connected devices
var timestamp = moment().valueOf();
var post_req = null,
post_data = '[{"id":"' + sensorID + '","v":[{"m":[' + temperature + '],"t":' + timestamp + '}]}]';
var postURL = httpServiceUri + "/" + httpServicePath + "/messages";
// parse url to chunks
var reqUrl = url.parse(postURL);
var post_options = {
hostname: reqUrl.hostname,
path: reqUrl.pathname,
port: 443,
protocol: 'https:',
method : 'POST',
headers : {
'Authorization': httpSAS,
'DataCollectorId': gatewayID,
'PayloadType': 'Measurements',
'Timestamp': moment().valueOf(), // This timestamp should be "now"
'Content-Type': 'application/atom+xml;type=entry;charset=utf-8',
'Cache-Control': 'no-cache',
'Content-Length': post_data.length
}
};
post_req = https.request(post_options, function (res) {
console.log('STATUS: ' + res.statusCode);
console.log('HEADERS: ' + JSON.stringify(res.headers));
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log('Response: ', chunk);
});
});
post_req.on('error', function (e) {
console.log('problem with request: ' + e.message);
});
post_req.write(post_data);
post_req.end();
}<file_sep>/sdk/gateway/ingest/web/index.js
<script>
var httpServiceUri = "<from registration ticket of gateway>";
var httpServicePath = "<from registration ticket of gateway>";
var gatewayID = '<from registration ticket of gateway, tag DataCollectorId>';
var sensorID = '<in developer portal, get internal id from the sensor you would like to upload data from>';
var httpSAS = '<from registration ticket of gateway>';
function SendPayLoad(s, m) {
var timestamp = Date.now(); // This is which time sensor data was read, Unix timestamp in milliseconds
var post_data = '[{"id":"' + s + '","v":[{"m":[' + m + '],"t":' + timestamp + '}]}]';
var postURL = httpServiceUri + "/" + httpServicePath + "/messages";
$.ajax({
url: postURL,
type: 'post',
data: post_data,
headers: {
'Authorization': httpSAS,
'DataCollectorId': gatewayID,
'PayloadType': 'Measurements',
'Timestamp': Date.now(), // This timestamp should be "now"
'Content-Type': 'application/atom+xml;type=entry;charset=utf-8',
'Cache-Control': 'no-cache'
},
dataType: 'text',
error: function (error) {
console.log('error: ' + error);
}
});
}
</script><file_sep>/sdk/gateway/ingest/nodejs/README.md
The code is node.js server code to upload sensor data/telemetric payloads to AppIoT. This can for instance be from a Raspberry Pi or other hardware acting as a gateway or device with Internet connectivity.
For demo purpose the code below also reads the sensor value (temperature sensor) from the command line.
To execute the code 4 libraries need to be imported which are:
https
url
moment
readline<file_sep>/README.md
# sample-collection
A collection of samples for AppIoT
<file_sep>/sdk/gateway/ingest/web/README.md
The code is JavaScript client code which can be embedded into a HTML page to upload sensor data/telemetric payloads to AppIoT.
Since this is a cross-domain call (must be https) the server need to advise client that it is allowed to do this cross-domain call by adding the HTTP header “Access-Control-Allow-Origin” as part of the response which includes the client side script code below. | 2202a55c141b13b675a5ddb899e7f41d2afbe232 | [
"JavaScript",
"Markdown"
] | 5 | JavaScript | ApplicationPlatformForIoT/sample-collection | 0cbe41e4f6925c00f289262d5f538e90b5a599cb | f33be9c168694ae374944f7a39378da2085cbe71 |
refs/heads/master | <repo_name>afrixea/TimberWordpress<file_sep>/includes/analytics.php
<?php
if (defined('WP_ENV') && 'production' === WP_ENV) {
add_filter('wp_resource_hints', function ($hints, $type) {
if ('dns-prefetch' === $type) {
$hints[] = '//www.google-analytics.com';
}
return $hints;
}, 10, 2);
/*
add_action('wp_head', function () {
?>
<script>
(function (i, s, o, g, r, a, m) {
i['GoogleAnalyticsObject'] = r;
i[r] = i[r] || function () {
(i[r].q = i[r].q || []).push(arguments)
}, i[r].l = 1 * new Date();
a = s.createElement(o),
m = s.getElementsByTagName(o)[0];
a.async = 1;
a.src = g;
m.parentNode.insertBefore(a, m)
})(window, document, 'script', 'https://www.google-analytics.com/analytics.js', 'ga');
ga('create', '', 'auto');
ga('send', 'pageview');
</script>
<?php
}, 1);
*/
add_action('wp_head', function () {
?>
<script src="https://cdn.jsdelivr.net/ga-lite/latest/ga-lite.min.js" async></script>
<script>var galite = galite || {}; galite.UA = 'UA-7923073-5';</script>
<?php
}, 1);
}
<file_sep>/includes/wpml/wpml.php
<?php
if ( ! class_exists('SitePress')) {
return;
}
function vg_language_switcher()
{
$languages = apply_filters('wpml_active_languages', null, ['skip_missing' => 0]);
if ( ! empty($languages)) {
echo '<div class="language-switcher">';
foreach ($languages as $language) {
if ($language['active']) {
echo '<span>' . $language['native_name'] . '</span>';
}
}
echo '<ul class="languages">';
foreach ($languages as $language) {
if ( ! $language['active']) {
echo '<li><a href="' . $language['url'] . '">' . $language['native_name'] . '</a></li>';
}
}
echo '</ul>';
echo '</div>';
}
}
<file_sep>/classes/Site.php
<?php
use Timber\Loader;
use Timber\Menu;
use Timber\Site;
use Timber\Timber;
class App extends Site
{
public function __construct()
{
add_action('init', [$this, 'types']);
add_filter('timber_context', [$this, 'context']);
add_filter('get_twig', [$this, 'add']);
// add_filter('post_type_labels_post', [$this, 'labelsPost']);
// add_filter('timber/cache/mode', [$this, 'cacheMode']);
// $this->cache();
parent::__construct();
}
public function types()
{
}
public function context($context)
{
$context['settings'] = (function_exists('get_fields')) ? get_fields('options') : [];
$context['menu'] = new Menu('primary');
$context['sidebar'] = Timber::get_sidebar('sidebar.php');
$context['site'] = $this;
return $context;
}
public function add($twig)
{
// $twig->addExtension(new \nochso\HtmlCompressTwig\Extension(true));
$twig->addExtension(new Twig_Extension_StringLoader());
return $twig;
}
public function labelsPost($labels)
{
$labels->add_new = 'Νέο άρθρο';
$labels->add_new_item = 'Προσθήκη άρθρου';
$labels->all_items = 'Όλα τα άρθρα';
$labels->archives = 'Αρχείο Άρθρων';
$labels->attributes = 'Χαρακτηριστικά άρθρου';
$labels->edit_item = 'Επεξεργασία άρθρου';
$labels->featured_image = 'Επιλεγμένη εικόνα';
$labels->filter_items_list = 'Φίλτρο λίστας άρθρων';
$labels->insert_into_item = 'Εισαγωγή στο άρθρο';
$labels->items_list = 'Λίστα άρθρων';
$labels->items_list_navigation = 'Λίστα πλοήγησης άρθρων';
$labels->menu_name = 'Άρθρα';
$labels->name = 'Άρθρα';
$labels->name_admin_bar = 'Άρθρου';
$labels->new_item = 'Νέο άρθρο';
$labels->not_found = 'Δεν βρέθηκαν άρθρα. ';
$labels->not_found_in_trash = 'Δεν βρέθηκαν άρθρα στα διαγραμένα.';
$labels->remove_featured_image = 'Αφαίρεση επιλεγμένης εικόνας';
$labels->search_items = 'Αναζήτηση άρθρων';
$labels->set_featured_image = 'Ορισμός επιλεγμένης εικόνας ';
$labels->singular_name = 'Άρθρο';
$labels->uploaded_to_this_item = 'Μεταφορτώθηκε στο άρθρο';
$labels->use_featured_image = 'Χρήση ως επιλεγμένη εικόνα';
$labels->view_item = 'Προβολή άρθρου';
$labels->view_items = 'Προβολή Άρθρων';
return $labels;
}
public function cacheMode($mode)
{
$mode = Loader::CACHE_OBJECT;
return $mode;
}
private function cache()
{
Timber::$cache = defined('WP_ENV') && 'production' === WP_ENV;
}
}
<file_sep>/includes/wordpress/dashboard.php
<?php
add_filter('screen_options_show_screen', '__return_false');
//add_filter('user_contactmethods', function ($methods) {
//
// return $methods;
//});
<file_sep>/includes/wordpress/assets.php
<?php
if (defined('WP_ENV') && 'production' === WP_ENV) {
add_filter('style_loader_src', 'vg_remove_asset_version', 15, 1);
add_filter('script_loader_src', 'vg_remove_asset_version', 15, 1);
function vg_remove_asset_version($src)
{
$parts = explode('?ver', $src);
return $parts[0];
}
}
//add_filter('script_loader_tag', function ($tag, $handle) {
// if ( ! is_admin()) {
// $asyncScripts = [];
// $deferScripts = [];
// foreach ($asyncScripts as $asyncScript) {
// if ($asyncScript === $handle) {
// return str_replace(' src', ' async="async" src', $tag);
// }
// }
// foreach ($deferScripts as $deferScript) {
// if ($deferScript === $handle) {
// return str_replace(' src', ' defer="defer" src', $tag);
// }
// }
// }
//
// return $tag;
//}, 10, 2);
//add_filter('wp_resource_hints', function ($hints, $type) {
// /*
// if ('prerender' === $type) {
// $hints[] = 'https://cdnjs.cloudflare.com';
// }
// */
// if ('dns-prefetch' === $type) {
// $hints[] = '//cdn.jsdelivr.net';
// $hints[] = '//cdnjs.cloudflare.com';
// }
//
// return $hints;
//}, 10, 2);
add_action('wp_enqueue_scripts', function () {
$cacheBuster = '1.0.0';
// remove_action('wp_head', 'wp_print_scripts');
// remove_action('wp_head', 'wp_print_head_scripts', 9);
// remove_action('wp_head', 'wp_enqueue_scripts', 1);
wp_scripts()->add_data('jquery', 'group', 1);
wp_scripts()->add_data('jquery-core', 'group', 1);
wp_scripts()->add_data('jquery-migrate', 'group', 1);
// wp_dequeue_style('nanga');
// wp_dequeue_script('nanga');
wp_enqueue_style('app', get_stylesheet_directory_uri() . '/build/app.css', false, $cacheBuster);
// wp_enqueue_script('modernizr', get_stylesheet_directory_uri() . '/build/modernizr-bundle.js', [], $cacheBuster, true);
// wp_enqueue_script('app', get_stylesheet_directory_uri() . '/build/app.js', ['jquery'], $cacheBuster, true);
wp_enqueue_script('app', get_stylesheet_directory_uri() . '/build/app.js', [], $cacheBuster, true);
$options = [
'_nonce' => wp_create_nonce(),
'endpoint' => admin_url('admin-ajax.php'),
];
// wp_localize_script('app', 'app', $options);
if (is_singular() && comments_open() && get_option('thread_comments')) {
wp_enqueue_script('comment-reply');
}
}, 100);
//add_action('wp_enqueue_scripts', function () {
// if (defined('WP_ENV') && 'development' === WP_ENV) {
// wp_enqueue_script('html-inspector', 'http://cdnjs.cloudflare.com/ajax/libs/html-inspector/0.8.2/html-inspector.js', [], null, true);
// }
//}, 100);
//add_action('wp_footer', function () {
// if (defined('WP_ENV') && 'development' === WP_ENV) {
// echo '<script>HTMLInspector.inspect({ domRoot: "body", excludeRules: ["inline-event-handlers", "script-placement", "unused-classes"], excludeElements: ["svg", "iframe", "form", "input", "textarea", "font"] });</script>';
// }
//}, 101);
<file_sep>/single.php
<?php
use Timber\Helper;
use Timber\Post;
use Timber\Timber;
$context = Timber::get_context();
$post = new Post();
$context['post'] = $post;
if (comments_open()) {
$context['comment_form'] = Helper::get_comment_form();
}
if (post_password_required($post->ID)) {
Timber::render(['single-password.twig'], $context);
} else {
Timber::render(['single-' . $post->ID . '.twig', 'single-' . $post->post_type . '.twig', 'single.twig'], $context);
}
<file_sep>/includes/nanga/nanga.php
<?php
add_theme_support('nanga-airplane-mode');
// add_theme_support('nanga-analytics');
add_theme_support('nanga-branded-login');
add_theme_support('nanga-cookies');
add_theme_support('nanga-disable-authors');
// add_theme_support('nanga-disable-categories');
// add_theme_support('nanga-disable-comments');
add_theme_support('nanga-disable-dates');
add_theme_support('nanga-disable-embeds');
add_theme_support('nanga-disable-emoji');
add_theme_support('nanga-disable-feeds');
// add_theme_support('nanga-disable-pages');
add_theme_support('nanga-disable-post-formats');
// add_theme_support('nanga-disable-posts');
// add_theme_support('nanga-disable-quick-edit');
// add_theme_support('nanga-disable-rest');
add_theme_support('nanga-disable-revisions');
add_theme_support('nanga-disable-search');
add_theme_support('nanga-disable-sidebars');
add_theme_support('nanga-disable-tags');
add_theme_support('nanga-disable-trackbacks');
// add_theme_support('nanga-disable-widgets');
// add_theme_support('nanga-errorception');
// add_theme_support('nanga-image-sanity');
// add_theme_support('nanga-legacy');
// add_theme_support('nanga-legacy-support');
// add_theme_support('nanga-pagespeed');
// add_theme_support('nanga-support');
//add_filter('nanga_login_css', function () {
// return get_stylesheet_directory_uri() . '/assets/css/login.css';
//});
//add_filter('nanga_airplane_mode', '__return_false');
//add_filter('nanga_allowed_hosts', function ($hosts) {
// $hosts[] = '*.facebook.com';
// $hosts[] = '*.mailchimp.com';
//
// return $hosts;
//});
<file_sep>/app/routes.php
<?php
//Routes::map('experiments', function ($params) {
// if ( ! current_user_can('manage_options')) {
// wp_redirect(home_url());
// exit;
// }
// var_dump($params);
// Routes::load('template-experiments.php', $params, false, 200);
//});
Routes::map('webmail', function ($params) {
wp_redirect('https://apps.rackspace.com/');
exit;
});
<file_sep>/includes/wordpress/wordpress.php
<?php
add_action('after_setup_theme', function () {
add_theme_support('html5', ['caption', 'comment-form', 'comment-list', 'gallery', 'search-form']);
add_theme_support('menus');
add_theme_support('post-thumbnails');
add_theme_support('title-tag');
// add_theme_support('widgets');
add_theme_support('woocommerce');
load_theme_textdomain('vg', get_stylesheet_directory() . '/languages');
register_nav_menus([
'primary' => 'Primary Menu',
'footer' => 'Footer Menu',
]);
});
add_action('widgets_init', function () {
register_sidebar([
'name' => 'Sidebar',
'id' => 'sidebar',
'before_widget' => '<aside class="widget %2$s">',
'after_widget' => '</aside>',
'before_title' => '<h5 class="widget-title">',
'after_title' => '</h5>',
]);
});
<file_sep>/includes/wordpress/rewrites.php
<?php
//add_filter('rest_authentication_errors', function ($access) {
// if ( ! is_user_logged_in() || ! current_user_can('manage_options')) {
// return new WP_Error('rest_cannot_access', 'Only authenticated users can access the REST API.', ['status' => rest_authorization_required_code()]);
// }
//
// return $access;
//});
<file_sep>/includes/wordpress/mailer.php
<?php
if (defined('WP_ENV') && 'production' !== WP_ENV) {
add_action('phpmailer_init', function ($phpmailer) {
$phpmailer->isSMTP();
$phpmailer->Host = 'smtp.mailtrap.io';
$phpmailer->SMTPAuth = true;
$phpmailer->Port = 2525;
$phpmailer->Username = MAILTRAP_USERNAME;
$phpmailer->Password = <PASSWORD>;
});
}
<file_sep>/includes/gravity-forms/gravity-forms.php
<?php
if ( ! class_exists('GFForms')) {
return;
}
//add_filter('gform_confirmation_anchor', '__return_false');
//add_filter('gform_enable_shortcode_notification_message', '__return_false');
//add_filter('gform_init_scripts_footer', '__return_true');
//add_filter('gform_cdata_open', function ($content = '') {
// $content = 'document.addEventListener( "DOMContentLoaded", function() { ';
//
// return $content;
//});
//add_filter('gform_cdata_close', function ($content = '') {
// $content = ' }, false );';
//
// return $content;
//});
//add_action('wp_ajax_nopriv_vg_get_form', 'vg_get_form');
//add_action('wp_ajax_vg_get_form', 'vg_get_form');
//function vg_get_form()
//{
// $formId = isset($_GET['form_id']) ? absint($_GET['form_id']) : 0;
// gravity_form($formId, false, false, false, false, true);
// wp_die();
//}
<file_sep>/includes/woocommerce/woocommerce.php
<?php
if ( ! class_exists('WooCommerce')) {
return;
}
//add_action('wp_enqueue_scripts', function () {
// global $product;
// if (is_singular('product') && $product->is_type('variable')) {
// wp_enqueue_script('wc-add-to-cart-variation');
// }
//}, 100);
add_filter('woocommerce_enqueue_styles', '__return_empty_array');
add_action('after_setup_theme', function () {
add_theme_support('wc-product-gallery-zoom');
add_theme_support('wc-product-gallery-lightbox');
add_theme_support('wc-product-gallery-slider');
});
remove_action('woocommerce_before_main_content', 'woocommerce_output_content_wrapper', 10);
remove_action('woocommerce_after_main_content', 'woocommerce_output_content_wrapper_end', 10);
add_action('woocommerce_before_main_content', function () {
echo '<div class="woocommerce-container">';
}, 10);
add_action('woocommerce_after_main_content', function () {
echo '</div>';
}, 10);
<file_sep>/includes/acf/acf.php
<?php
if ( ! function_exists('acf_add_options_page')) {
return;
}
if (defined('GOOGLE_API_KEY')) {
add_action('acf/init', function () {
acf_update_setting('google_api_key', GOOGLE_API_KEY);
});
}
acf_add_options_page([
'capability' => 'edit_pages',
'menu_slug' => 'vg-settings',
'menu_title' => __('Settings', 'nanga'),
'page_title' => __('Settings', 'nanga'),
'position' => false,
'redirect' => false,
]);
<file_sep>/functions.php
<?php
if ( ! class_exists('Timber')) {
return;
}
require_once 'vendor/autoload.php';
require_once 'app/routes.php';
require_once 'includes/helpers.php';
require_once 'includes/analytics.php';
require_once 'includes/wordpress/assets.php';
require_once 'includes/wordpress/dashboard.php';
require_once 'includes/wordpress/mailer.php';
require_once 'includes/wordpress/rewrites.php';
require_once 'includes/wordpress/wordpress.php';
require_once 'includes/acf/acf.php';
require_once 'includes/gravity-forms/gravity-forms.php';
require_once 'includes/nanga/nanga.php';
require_once 'includes/woocommerce/woocommerce.php';
require_once 'includes/wpml/wpml.php';
require_once 'classes/Site.php';
$app = new App();
| bbe8d0b753b622e7f4a3ca2e30dd9de14d778a41 | [
"PHP"
] | 15 | PHP | afrixea/TimberWordpress | e42c6ba58de57ac86ae7f1d5c7492735673182b6 | 74d55639223c70989f5c52cbba06ce59716b05ec |
refs/heads/master | <repo_name>haensl/pwm-season-simulation<file_sep>/season-simulation.ino
// uncomment to do a dry run
// #define DRY_RUN
#include <Process.h>
#include <Math.h>
#define COLON ":"
#ifdef DRY_RUN
#include <Console.h>
const byte DRY_RUN_DAYS_PER_MONTH = 30;
#endif
typedef struct Time {
byte hours;
byte minutes;
byte seconds;
} Time;
const byte PIN_MOONLIGHT = 6;
const byte LUMINOSITY_MAX_MOONLIGHT = 16; // maximum luminosity -- i.e. pwm at full moon
const byte MAX_MOONLIGHT_HOURS_PER_DAY = 12;
const byte HOURS_PER_DAY = 24;
const unsigned long MILLIS_PER_DAY = HOURS_PER_DAY * 60L * 60L * 1000L;
/**
* Skews adjust the moonlight luminosity based on location around the globe.
*/
const float SKEW_START_OF_YEAR_MOONLIGHT_LUMINOSITY = 4.2f;
const float SKEW_MONTHLY_MOONLIGHT_LUMINOSITY = 4.3f;
/**
* Set correct baut rate depending on board.
*/
const unsigned long BAUT_BRIDGE = 115200L;
/**
* Wait this many milliseconds before initializing the bridge, to give the linux kernel time to boot.
*/
const unsigned int BOOT_DELAY = 5000;
boolean lunarCycleCompleted;
boolean moonlightShiningAtLastIteration;
void setup() {
lunarCycleCompleted = true;
moonlightShiningAtLastIteration = false;
pinMode(PIN_MOONLIGHT, OUTPUT);
analogWrite(PIN_MOONLIGHT, 0);
delay(BOOT_DELAY);
Bridge.begin(BAUT_BRIDGE);
#ifdef DRY_RUN
Console.begin();
while(!Console);
Console.println("Starting dry run.");
Console.print("Assuming ");
Console.print(DRY_RUN_DAYS_PER_MONTH);
Console.print(" days per month.\n");
for (unsigned int dayOfYear = 45; dayOfYear < 357; dayOfYear++) {
byte dayOfMonth = max(dayOfYear % DRY_RUN_DAYS_PER_MONTH, 1);
for (byte hour = 0; hour < HOURS_PER_DAY; hour++) {
for (byte i = 1; i < 3; i++) {
if (i % 2 == 0) {
lunarCycleDryRun(dayOfYear, dayOfMonth, { hour, 30, 0 });
} else {
lunarCycleDryRun(dayOfYear, dayOfMonth, { hour, 0, 0 });
}
}
}
}
#endif
}
void loop() {
#ifdef DRY_RUN
#else
analogWrite(PIN_MOONLIGHT, lunarCycle());
#endif
}
#ifdef DRY_RUN
byte lunarCycleDryRun(unsigned int dayOfYear, byte dayOfMonth, Time t) {
Console.println("");
Console.print(dayOfYear);
Console.print(". day of year\n");
Console.print(dayOfMonth);
Console.print(". day of month\n");
Console.print("\nlunar cycle completed ");
Console.print(lunarCycleCompleted);
Console.print("\nmoonlight shining at last iteration ");
Console.print(moonlightShiningAtLastIteration);
static byte hoursOfMoonlight;
static byte hourOfMoonrise;
static byte maximumMoonlightLuminosityOfDay;
if (lunarCycleCompleted || (hoursOfMoonlight == 0 && t.hours == 0 && t.minutes == 0)) {
hoursOfMoonlight = getHoursOfMoonlight(dayOfYear, DRY_RUN_DAYS_PER_MONTH);
hourOfMoonrise = getHourOfMoonrise(dayOfYear, DRY_RUN_DAYS_PER_MONTH);
maximumMoonlightLuminosityOfDay = getMaximumMoonlightLuminosity(dayOfMonth, DRY_RUN_DAYS_PER_MONTH);
}
Console.print("\nhours of moonlight ");
Console.print(hoursOfMoonlight);
Console.print("\nhour of moonrise ");
Console.print(hourOfMoonrise);
Console.print("\nmaximum moonlight luminosity of day ");
Console.print(maximumMoonlightLuminosityOfDay);
byte moonlightLuminosity = getMoonlightLuminosity(hoursOfMoonlight, hourOfMoonrise, maximumMoonlightLuminosityOfDay, t);
Console.print("\nmoonlight luminosity\n");
Console.print(t.hours);
Console.print(":");
Console.print(t.minutes);
Console.print(" - ");
Console.print(moonlightLuminosity);
Console.print("\n ---");
Console.flush();
lunarCycleCompleted = moonlightShiningAtLastIteration && moonlightLuminosity <= 0;
moonlightShiningAtLastIteration = moonlightLuminosity > 0;
return moonlightLuminosity;
}
#endif
byte lunarCycle() {
static unsigned int dayOfYear;
static byte dayOfMonth;
static byte daysInMonth;
static byte hoursOfMoonlight;
static byte hourOfMoonrise;
static byte maximumMoonlightLuminosityOfDay;
Time t = getTime();
if (lunarCycleCompleted || (hoursOfMoonlight == 0 && t.hours == 0 && t.minutes == 0)) {
dayOfYear = getDayOfYear();
dayOfMonth = getDayOfMonth();
if (dayOfMonth == 1) {
daysInMonth = getDaysInMonth();
}
hoursOfMoonlight = getHoursOfMoonlight(dayOfYear, daysInMonth);
hourOfMoonrise = getHourOfMoonrise(dayOfYear, daysInMonth);
maximumMoonlightLuminosityOfDay = getMaximumMoonlightLuminosity(dayOfMonth, daysInMonth);
}
byte moonlightLuminosity = getMoonlightLuminosity(hoursOfMoonlight, hourOfMoonrise, maximumMoonlightLuminosityOfDay, t);
lunarCycleCompleted = moonlightShiningAtLastIteration && moonlightLuminosity <= 0;
moonlightShiningAtLastIteration = moonlightLuminosity > 0;
return moonlightLuminosity;
}
byte getHoursOfMoonlight(unsigned int dayOfYear, byte daysInMonth) {
return (byte)round((MAX_MOONLIGHT_HOURS_PER_DAY / M_PI) * asin(cos(M_PI * dayOfYear / daysInMonth + SKEW_START_OF_YEAR_MOONLIGHT_LUMINOSITY)) + (MAX_MOONLIGHT_HOURS_PER_DAY / 2.0f));
}
byte getHourOfMoonrise(unsigned int dayOfYear, byte daysInMonth) {
return (byte)round((HOURS_PER_DAY / M_PI) * asin(cos(M_PI * dayOfYear / daysInMonth + SKEW_MONTHLY_MOONLIGHT_LUMINOSITY)) + (HOURS_PER_DAY / 2.0f)) % HOURS_PER_DAY;
}
byte getMaximumMoonlightLuminosity(byte dayOfMonth, byte daysInMonth) {
return (byte)round(-(LUMINOSITY_MAX_MOONLIGHT / 2.0f) * (2.0f / M_PI) * asin(cos(M_PI * dayOfMonth / (daysInMonth / 2.0f))) + (LUMINOSITY_MAX_MOONLIGHT / 2.0f));
}
byte getMoonlightLuminosity(byte hoursOfMoonlight, byte hourOfMoonrise, byte maxLuminosity, Time t) {
float currentMoonhour;
if (t.hours - hourOfMoonrise >= 0) {
currentMoonhour = (t.hours - hourOfMoonrise) + (t.minutes / 60.0f);
} else {
currentMoonhour = (HOURS_PER_DAY + t.hours - hourOfMoonrise) + (t.minutes / 60.0f);
}
float hourOfMaximumLuminosity = hoursOfMoonlight / 2.0f;
if (currentMoonhour >= 0 && currentMoonhour <= hoursOfMoonlight) {
return (byte)round((maxLuminosity / M_PI) * asin(cos(M_PI * ((currentMoonhour + hourOfMaximumLuminosity) / hourOfMaximumLuminosity))) + (maxLuminosity / 2.0f));
}
return 0;
}
Time getTime() {
Time t;
Process date;
date.begin("/bin/date");
date.addParameter("+%T");
date.run();
String timeString;
while (date.available() > 0) {
timeString = date.readString();
}
byte firstColon = timeString.indexOf(COLON);
byte secondColon = timeString.lastIndexOf(COLON);
t = {
(byte)timeString.substring(0, firstColon).toInt(),
(byte)timeString.substring(firstColon + 1, secondColon).toInt(),
(byte)timeString.substring(secondColon + 1).toInt()
};
return t;
}
unsigned int getDayOfYear() {
Process date;
date.begin("/bin/date");
date.addParameter("+%j");
date.run();
String doy;
while (date.available() > 0) {
doy = date.readString();
}
return doy.toInt();
}
byte getDayOfMonth() {
Process date;
date.begin("/bin/date");
date.addParameter("+%d");
date.run();
String dom;
while (date.available() > 0) {
dom = date.readString();
}
return (byte)dom.toInt();
}
byte getDaysInMonth() {
byte days = 31;
byte daysInMonth = 31;
while (days > 26) {
Process date;
date.begin("/bin/date");
date.addParameter("+%d");
date.addParameter("-d \"" + String(days) + "\"");
date.addParameter("-D \"%d\"");
date.run();
while (date.available() > 0) {
daysInMonth = (byte)date.readString().toInt();
}
if (daysInMonth == days) {
return days;
}
days--;
}
return days;
}
/**
unsigned long getTimestamp() {
date.begin("/bin/date");
date.addParameter("+%s");
date.run();
unsigned long timestamp = 0;
while(date.available() > 0) {
timestamp = date.parseInt();
}
return timestamp;
}*/
<file_sep>/CHANGELOG.md
## 2.1.2
* Fix a bug that causes lunar cycles not to be reset when there is no moon.
## 2.1.1
* Fix a bug that causes moonlight luminosity to be miscalculated upon day change.
## 2.1.0
* Work with accurate days per month.
## 2.0.0
* Add lunar cycle simulation.
* Add dry run capability.
## 1.0.3
* Fix non-incrementing luminosity timer.
## 1.0.2
* Fix luminosity calculation leftover bug.
## 1.0.1
* Fix compiler warnings.
## 1.0.0
* Initial project setup.
<file_sep>/README.md
# PWM season simulation
Timed and season aware Arduino PWM dimming, e.g. to controll aquarium lighting.
## Features
- Moonlight simulation incorporating lunar cycles.
- [Dry run](#dry-run) to verify/test your configuration.
## Requirements
- Arduino board with [Bridge](https://www.arduino.cc/en/Reference/YunBridgeLibrary) capabilities, e.g. YUN, Industrial 101, etc.
## Usage
Adjust relevant variables and upload to your board.
## Settings
The sketch contains several adjustable parameters:
#### `BAUT_BRIDGE`
The baut rate for the bridge of your board.
#### `BOOT_DELAY`
Time in `[ms]` to wait before initializing the bridge in order to give the linux kernel time to boot.
#### <a name="dry-run"></a>`DRY_RUN`
Uncomment the `DRY_RUN` flag to do a dry run and debug/verify your setup. State data is output via [Console](https://www.arduino.cc/en/Reference/YunConsoleConstructor).
#### `DRY_RUN_DAYS_PER_MONTH`
How many days to assume per month in a dry run.
#### `LUMINOSITY_MAX_MOONLIGHT`
Maximum PWM value for moonlight. I.e. your moon will not become brighter than this. Set to 255 for maximum brightness.
#### `MAX_MOONLIGHT_HOURS_PER_DAY`
Maximum hours of moonlight per day.
#### `PIN__MOONLIGHT`
The PWM pin to use for moonlight simulation.
#### `SKEW_START_OF_YEAR_MOONLIGHT_LUMINOSITY`
This is used to adjust the lunar cycle based on location. To find a suitable value for your desired simulation location it is easiest to plot the `getHoursOfMoonlight()` function and adjust until satisfied (`4.2f ==` Rio De Janeiro).
```
f(x) = (MAX_MOONLIGHT_HOURS_PER_DAY / PI) * asin(cos(PI * x / DAYS_PER_MONTH + SKEW_START_OF_YEAR_MOONLIGHT_LUMINOSITY)) + (MAX_MOONLIGHT_HOURS_PER_DAY / 2)
```
#### `SKEW_MONTHLY_MOONLIGHT_LUMINOSITY`
This is used to adjust the lunar cycle based on location. To find a suitable value for your desired simulation location it is easiest to plot the `getHourOfMoonrise()` function and adjust until satisfied (`4.3f ==` Rio De Janeiro).
```
f(x) = (HOURS_PER_DAY / PI) * asin(cos(PI * x / DAYS_PER_MONTH + SKEW_MONTHLY_MOONLIGHT_LUMINOSITY)) + (HOURS_PER_DAY / 2)
```
## [Changelog](CHANGELOG.md)
## [License](LICENSE)
| 3951206ac85f9380d6968a0d846a1c57e6c9f0f2 | [
"Markdown",
"C++"
] | 3 | C++ | haensl/pwm-season-simulation | 23b7b3de051de125cf38693050c85b33bc78b753 | 13c80739a29b16177d6cde24588f67d86046cd0b |
refs/heads/master | <file_sep>from data_source import DataSource
import argparse
import json
class IngestWorker:
def __init__(self):
self.__ds=DataSource.get_postgis_idc()
self.__cursor = self.__ds.cursor()
def __del__(self):
self.__ds.close()
def has_scene(self, scene_id):
sql = f'SELECT count(id) FROM tbl_sia_scenes WHERE scene_name = upper("{scene_id}")'
self.__cursor.execute(sql)
count = self.__cursor.fetchone()
return count > 0
def main(scenes_filepath):
scenes = json.load(scenes_filepath)
worker = IngestWorker()
for id, path in enumerate(scenes):
if worker.has_scene(id):
continue
if __name__ == '__main__':
parser = argparse.ArgumentParser(
description = 'Scene ingest'
)
parser.add_argument(
'--scene_filepath',
default=None,
metavar='PATH',
help='scene id-path dictionary file location'
type=str
)
args = parser.parse_args()
main(**vars(args))<file_sep>print('test_sia')
print('git_commit_test')
print('git commit test2')
print('llll')
print('git commit test2')
print('git commit test2')
print('git branch test') | 721f0ec8f6a1ae2dfcccfc486d3fe51e64392cd4 | [
"Python"
] | 2 | Python | kbae1230/GIS_data_preprocessing | 820b8a38546eac3fde298ce67b749a4683d375a4 | 6228b965324fdd7c2f153b902d2b1bf361deb37e |
refs/heads/main | <repo_name>ErminDZ/FridayEx1<file_sep>/src/main/java/ci/Friday.java
package ci;
public class Friday {
public Friday() {
}
}
| cbc50bb8b9ec1e39b18fc956c355d939f3fd1085 | [
"Java"
] | 1 | Java | ErminDZ/FridayEx1 | 065ce43c208d4d0ae434c8b5347072ac1e9af48f | 6961ba022c56450dfedc89204e5f52b3f754d5e2 |
refs/heads/master | <file_sep>const express = require('express');
const app = express();
const session = require('express-session');
const server = require('http').createServer(app);
const io = require('socket.io')(server);
//-----------------------------------------------------------------------------
server.listen(process.env.PORT || 3000);
app.use(session({
secret: 'keyboard cat',
resave: false,
saveUninitialized: true,
cookie: { secure: true }
}));
//-----------------------------------------------------------------------------
session.mang_room = [];
session.array_chat = [];
io.on('connection',(socket) => {
var room = '';
socket.on('user_client_room',(data)=>{
socket.join(data);
socket.room = data;
room = data;
var mang_room = session.mang_room;
const count = mang_room.length;
var flag = 0;
if(count == 0){
session.mang_room.push(data);
}
else{
for(let i = 0 ; i < count ; i++){
if(mang_room[i] == data){
flag++;
}
}
if(flag == 0){
mang_room.push(data);
}
}
session.mang_room = mang_room;
socket.emit('server-send-room-socket',data);
io.sockets.emit('server-send-rooms',mang_room);
var data_chat = [];
session.array_chat.forEach((item)=>{
var user_admin = "Admin_"+data;
if(item.user == data || item.user == user_admin ){
data_chat.push(item);
}
})
io.sockets.in(data).emit('server-send-data-chat-user',data_chat);
})
socket.on('admin_choose_room',(data)=>{
socket.join(data);
room = data;
var data_chat = [];
session.array_chat.forEach((item)=>{
var user_admin = "Admin_"+data;
if(item.user == data || item.user == user_admin ){
data_chat.push(item);
}
})
io.sockets.in(data).emit('server-send-data-chat-admin-choose-room',data_chat);
})
socket.on('client-send-data-chat', (data)=>{
if(data.user == "Admin"){
var user = "Admin_"+room;
var ob = {
user : user,
noidung : data.noidung
}
session.array_chat.push(ob);
}
else{
var ob = {
user : data.user,
noidung : data.noidung
}
session.array_chat.push(ob);
}
var data_chat = [];
session.array_chat.forEach((item)=>{
var user_admin = "Admin_"+room;
if(item.user == room || item.user == user_admin ){
data_chat.push(item);
}
})
io.sockets.in(room).emit('sever-send-data-chat',{data,data_chat});
})
socket.on('load_noidung_chat',(data)=>{
var data_chat = [];
session.array_chat.forEach((item)=>{
var user_admin = "Admin_"+room;
if(item.user == data.user || item.user == user_admin ){
data_chat.push(item);
}
})
io.sockets.in(room).emit('server-send-data-load-noidung-chat',{data_chat});
})
socket.on('load-user',()=>{
io.sockets.emit('server-send-rooms',session.mang_room);
})
socket.on("disconnect",()=>{
session.mang_room.splice(session.mang_room.indexOf(room),1);
io.sockets.emit('server-send-rooms',session.mang_room);
});
}); | 2deddcdaf2e8a04bc2460e5c0454a4771f059589 | [
"JavaScript"
] | 1 | JavaScript | legendstrange1992/server-fashion-shop | c817a1555e995d696ec04299bf62648fdedc0634 | 3c84737af6c36ebaca0343c211e35624feb209fe |
refs/heads/master | <repo_name>GitShini/Demo<file_sep>/src/test/java/Learn/UdemyE2EProject/Listeners.java
package Learn.UdemyE2EProject;
import java.io.IOException;
import org.openqa.selenium.WebDriver;
import org.testng.ITestContext;
import org.testng.ITestListener;
import org.testng.ITestResult;
import com.aventstack.extentreports.ExtentReports;
import com.aventstack.extentreports.ExtentTest;
import com.aventstack.extentreports.Status;
import resources.Base;
import resources.ExtentReporterNG;
public class Listeners extends Base implements ITestListener {
ExtentTest test;
ExtentReports extent = ExtentReporterNG.extentRepo();
ThreadLocal<ExtentTest> extentTest = new ThreadLocal<ExtentTest>();
public void onFinish(ITestContext arg0) {
extent.flush();
}
public void onStart(ITestContext arg0) {
}
public void onTestFailedButWithinSuccessPercentage(ITestResult arg0) {
// TODO Auto-generated method stub
}
public void onTestFailure(ITestResult arg0) {
extentTest.get().fail(arg0.getThrowable());
WebDriver driver;
String testCaseName=arg0.getMethod().getMethodName();
System.out.println("From listener: "+testCaseName);
try {
driver=(WebDriver)arg0.getTestClass().getRealClass().getDeclaredField("driver").get(arg0.getInstance());
//getScreenShot(testCaseName,driver);
extentTest.get().addScreenCaptureFromPath(getScreenShot(testCaseName,driver), testCaseName);
} catch (Exception e) {
e.printStackTrace();
}
}
public void onTestSkipped(ITestResult arg0) {
// TODO Auto-generated method stub
}
public void onTestStart(ITestResult arg0) {
test = extent.createTest(arg0.getMethod().getMethodName());
extentTest.set(test);
}
public void onTestSuccess(ITestResult arg0) {
extentTest.get().log(Status.PASS, "TestPassed");
}
}
<file_sep>/src/main/java/pageObjects/LoginPageObj.java
package pageObjects;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
public class LoginPageObj {
WebDriver driver;
public LoginPageObj(WebDriver driver) {
this.driver=driver;
PageFactory.initElements(driver, this);
}
private @FindBy (css=("[id=user_email]"))
WebElement email;
private @FindBy (css=("[id=user_password]"))
WebElement password;
private @FindBy (css=("[type=submit]"))
WebElement submit;
public WebElement email() {
return email;
}
public WebElement password() {
return password;
}
public WebElement submit() {
return submit;
}
}
<file_sep>/src/test/java/Learn/UdemyE2EProject/PracticePage.java
package Learn.UdemyE2EProject;
import java.io.IOException;
import org.openqa.selenium.WebDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.Test;
import pageObjects.HomePageObj;
import pageObjects.PracticePageObj;
public class PracticePage {
WebDriver driver;
public void navigateToPractice() {
HomePageObj hpo = new HomePageObj(driver);
hpo.practice().click();
}
@Test
public void goingToPractice() throws IOException {
HomePage hp = new HomePage();
driver =hp.initializeDriver();
navigateToPractice();
PracticePageObj ppo = new PracticePageObj(driver);
ppo.country().sendKeys("India");
}
@AfterTest
public void close() {
driver.close();
}
}
<file_sep>/src/test/java/Learn/UdemyE2EProject/LoginPage.java
package Learn.UdemyE2EProject;
import java.io.IOException;
import org.openqa.selenium.WebDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import pageObjects.HomePageObj;
import pageObjects.LoginPageObj;
public class LoginPage {
WebDriver driver;
public void navigateToLogin() {
HomePageObj hpo = new HomePageObj(driver);
hpo.login().click();
}
@Test(dataProvider ="getData")
public void login(String username, String password) throws IOException {
HomePage hp = new HomePage();
driver =hp.initializeDriver();
navigateToLogin();
LoginPageObj lpo = new LoginPageObj(driver);
lpo.email().sendKeys(username);
lpo.password().sendKeys(<PASSWORD>);
lpo.submit();
driver.close();
}
@DataProvider
public Object[][] getData() {
Object[][] data = new Object[2][2];
data[0][0]="<EMAIL>";
data[0][1]="123";
data[1][0]="<EMAIL>";
data[1][1]="456";
return data;
}
}
<file_sep>/src/main/java/pageObjects/HomePageObj.java
package pageObjects;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
public class HomePageObj {
WebDriver driver;
public HomePageObj(WebDriver driver) {
this.driver=driver;
PageFactory.initElements(driver, this);
}
private @FindBy (css=("a[href*=sign_in]"))
WebElement signin;
private @FindBy (xpath="//section[@id='content']/div/div/h2")
WebElement courses;
private @FindBy(css=("[class='navbar-collapse collapse']"))
WebElement navigationbar;
private @FindBy(css=("[href*=sign_up]"))
WebElement register;
private @FindBy(css=("[href*=Practice]"))
WebElement practice;
public WebElement login() {
return signin;
}
public WebElement courses() {
return courses;
}
public WebElement navigationBar() {
return navigationbar;
}
public WebElement register() {
return register;
}
public WebElement practice() {
return practice;
}
}
| 61b3b1a38684e7f6f5ac2e6dbdf21ac82de2be21 | [
"Java"
] | 5 | Java | GitShini/Demo | 24e0a9d29acc7d4b15e4755205358cc02ce482f1 | d5da7d7a6d5a4e16694827b4837e6c19c14e685b |
refs/heads/master | <file_sep>package cma.otto.spacetaxi;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
public class Exercises {
private final RouteParser routeParser = new RouteParser(DefaultDataset.highwaysByStartSystem);
private final RouteFinder routeFinder = new RouteFinder(DefaultDataset.highways);
@Test
@DisplayName("The distance of route Solar System -> Alpha Centauri -> Sirius")
public void exercise1() {
assertThat(routeParser.parse("Solar System -> Alpha Centauri -> Sirius").calculateTravelTime()).isEqualTo(9);
}
@Test
@DisplayName("The distance of route Solar System -> Betelgeuse")
public void exercise2() {
assertThat(routeParser.parse("Solar System -> Betelgeuse").calculateTravelTime()).isEqualTo(5);
}
@Test
@DisplayName("The distance of route Solar System -> Betelgeuse -> Sirius")
public void exercise3() {
assertThat(routeParser.parse("Solar System -> Betelgeuse -> Sirius").calculateTravelTime()).isEqualTo(13);
}
@Test
@DisplayName("The distance of route Solar System -> Vega -> Alpha Centauri -> Sirius -> Betelgeuse")
public void exercise4() {
assertThat(routeParser.parse("Solar System -> Vega -> Alpha Centauri -> Sirius -> Betelgeuse").calculateTravelTime()).isEqualTo(22);
}
@Test
@DisplayName("The distance of route Solar System -> Vega -> Betelgeuse")
public void exercise5() {
Exception ex = Assertions.assertThrows(
NoSuchRouteException.class,
() -> assertThat(routeParser.parse("Solar System -> Vega -> Betelgeuse").calculateTravelTime()).isEqualTo(9)
);
assertThat(ex).hasMessage("NO SUCH ROUTE");
}
@Test
@DisplayName("Determine all routes starting at Sirius and ending at Sirius with a maximum of 3 stops")
public void exercise6() {
List<Route> routes = routeFinder.findRouteWithMaxStops("Sirius", "Sirius", 3);
assertThat(routes)
.containsOnly(
routeParser.parse("Sirius -> Betelgeuse -> Sirius"),
routeParser.parse("Sirius -> Vega -> Alpha Centauri -> Sirius")
);
}
@Test
@DisplayName("Determine the number of routes starting at the solar system and ending at Sirius with exactly 3 stops in between.")
public void exercise7() {
List<Route> routes = routeFinder.findRoutesWithExactStops("Solar System", "Sirius", 4);
assertThat(routes)
.containsExactlyInAnyOrder(
routeParser.parse("Solar System -> Alpha Centauri -> Sirius -> Betelgeuse -> Sirius"),
routeParser.parse("Solar System -> Betelgeuse -> Sirius -> Betelgeuse -> Sirius"),
routeParser.parse("Solar System -> Betelgeuse -> Vega -> Alpha Centauri -> Sirius")
);
}
@Test
@DisplayName("Determine the duration of the shortest routes (in travel time) between solar system and Sirius")
public void exercise8() {
assertThat(routeFinder.findShortestRoute("Solar System", "Sirius"))
.extractingResultOf("calculateTravelTime")
.containsOnly(9);
}
@Test
@DisplayName("Determine the duration of the shortest routes (in travel time) starting at Alpha Centauri and ending at Alpha Centauri")
public void exercise9() {
assertThat(routeFinder.findShortestRoute("Alpha Centauri", "Alpha Centauri"))
.extractingResultOf("calculateTravelTime")
.containsOnly(9);
}
@Test
@DisplayName("Determine all different routes starting at Sirius and ending at Sirius with an over travel time less than 30.")
public void exercise10() {
List<Route> routes = routeFinder.findRoutesWithMaxTravelTime("Sirius", "Sirius", 29);
assertThat(routes)
.containsOnly(
routeParser.parse("Sirius -> Betelgeuse -> Sirius"),
routeParser.parse("Sirius -> Vega -> Alpha Centauri -> Sirius"),
routeParser.parse("Sirius -> Vega -> Alpha Centauri -> Sirius -> Betelgeuse -> Sirius"),
routeParser.parse("Sirius -> Betelgeuse -> Sirius -> Vega-> Alpha Centauri -> Sirius"),
routeParser.parse("Sirius -> Betelgeuse -> Vega-> Alpha Centauri -> Sirius"),
routeParser.parse("Sirius -> Vega -> Alpha Centauri -> Sirius -> Vega-> Alpha Centauri -> Sirius"),
routeParser.parse("Sirius -> Vega -> Alpha Centauri -> Sirius -> Vega -> Alpha Centauri -> Sirius -> Vega -> Alpha Centauri -> Sirius")
);
}
}
<file_sep><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>cma.otto</groupId>
<artifactId>spacetaxi</artifactId>
<version>0.0.1-SNAPSHOT</version>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>13</maven.compiler.source>
<maven.compiler.target>${maven.compiler.source}</maven.compiler.target>
<junit.jupiter.version>5.6.0</junit.jupiter.version>
</properties>
<dependencies>
<dependency>
<groupId>info.picocli</groupId>
<artifactId>picocli</artifactId>
<version>4.1.4</version>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>${junit.jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>3.15.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>3.2.4</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-junit-jupiter</artifactId>
<version>2.23.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>5.6.0</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<annotationProcessorPaths>
<path>
<groupId>info.picocli</groupId>
<artifactId>picocli-codegen</artifactId>
<version>4.1.4</version>
</path>
</annotationProcessorPaths>
<compilerArgs>
<arg>-Aproject=${groupId}/${artifactId}</arg>
</compilerArgs>
</configuration>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.2</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<configuration>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<mainClass>cma.otto.spacetaxi.App</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
<configuration>
<archive>
<manifest>
<mainClass>
cma.otto.spacetaxi.App
</mainClass>
</manifest>
</archive>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project><file_sep>###Ideas for further extension, modification or refactoring
* Add parameter to supply a different or additional Highway information. e.G.: `taxi --highways=.... path ....`
* Create a model class representing a system
* Different commands and parameters. Im not quite satisfied with the current solution.
* A more generic support for search
* More possible search criteria<file_sep>package cma.otto.spacetaxi;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class SmokeTest {
@Test
public void testRun() {
assertThat(App.run(new String[]{"path", "Sirius -> Vega"})).isEqualTo(0);
assertThat(App.run(new String[]{"path", "Vega -> Sirius"})).isEqualTo(1);
}
}
<file_sep>package cma.otto.spacetaxi;
import java.util.*;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import static java.util.Collections.emptyList;
import static java.util.stream.Collectors.groupingBy;
import static java.util.stream.Collectors.toCollection;
/**
* Service that searches the {@link Highway}s for a {@link Route} from one System to another.
*/
public class RouteFinder {
private final Map<String, List<Highway>> highwaysByStartSystem;
public RouteFinder(List<Highway> highways) {
this.highwaysByStartSystem = highways.stream()
.collect(Collectors.groupingBy(highway -> highway.start));
}
/**
* Finds the shortest {@link Route} by travel time between two systems.
*
* @param start the start system
* @param target the target system
* @return the shortest {@link Route}. May return more than one if travel time is equal.
*/
public List<Route> findShortestRoute(String start, String target) {
List<Route> routesWith = findRoutesWith(start, route1 -> !route1.containsLoop(), reached(target));
Map<Integer, List<Route>> collect = routesWith.stream().collect(groupingBy(Route::calculateTravelTime));
return collect.getOrDefault(collect.keySet().stream().min(Integer::compareTo).orElse(0), emptyList());
}
/**
* Finds {@link Route}s from start to target with the exact amount of stops including the start system.
*
* @param start the start system
* @param target the target system
* @param exactStops the exact amount of stops
* @return the {@link Route}s matching the criteria
*/
public List<Route> findRoutesWithExactStops(String start, String target, int exactStops) {
return findRoutesWith(start, maxStops(exactStops), reached(target).and(route -> route.getStopsCount(route) == exactStops));
}
/**
* Finds {@link Route}s from start to target with the maximum amount of stops including the start system.
*
* @param start the start system
* @param target the target system
* @param maxStops the maximum amount of stops
* @return the {@link Route}s matching the criteria
*/
public List<Route> findRouteWithMaxStops(String start, String target, int maxStops) {
return findRoutesWith(start, target, maxStops(maxStops));
}
/**
* Finds {@link Route}s from start to target with the maximum amount of travel time.
*
* @param start the start system
* @param target the target system
* @param maxTravelTime the maximum amount of travel time
* @return the {@link Route}s matching the criteria
*/
public List<Route> findRoutesWithMaxTravelTime(String start, String target, int maxTravelTime) {
return findRoutesWith(start, target, route -> route.calculateTravelTime() <= maxTravelTime);
}
private List<Route> findRoutesWith(String start, String target, Predicate<Route> routeCondition) {
return findRoutesWith(start, routeCondition, reached(target));
}
private List<Route> findRoutesWith(String start, Predicate<Route> routeCondition, Predicate<Route> addCondition) {
Queue<Route> candidateRoutes = findInitialCandidates(start);
List<Route> routes = new ArrayList<>();
while (!candidateRoutes.isEmpty()) {
Route candidate = candidateRoutes.poll();
if (routeCondition.test(candidate)) {
if (addCondition.test(candidate)) {
routes.add(candidate);
}
candidateRoutes.addAll(findNewCandidates(candidate));
}
}
return routes;
}
private Queue<Route> findInitialCandidates(String start) {
List<Highway> highways = this.highwaysByStartSystem.get(start);
return highways.stream()
.map(Route::new)
.collect(toCollection(LinkedList::new));
}
private List<Route> findNewCandidates(Route start) {
List<Highway> highways = start.getFinalTarget()
.map(target -> this.highwaysByStartSystem.getOrDefault(target, emptyList()))
.orElse(emptyList());
return highways.stream()
.map(start::extendBy)
.collect(toCollection(LinkedList::new));
}
private Predicate<Route> maxStops(int exactStops) {
return route -> route.getStopsCount(route) <= exactStops;
}
private Predicate<Route> reached(String target) {
return route -> route.hasReached(target);
}
}<file_sep>package cma.otto.spacetaxi.commands;
import cma.otto.spacetaxi.DefaultDataset;
import cma.otto.spacetaxi.Route;
import cma.otto.spacetaxi.RouteFinder;
import picocli.CommandLine.Command;
import picocli.CommandLine.Option;
import java.util.List;
@Command(
name = "max",
mixinStandardHelpOptions = true,
description = "Finds routes that fit the specified maximum value."
)
public class MaxCommand extends TravelCommand {
@Option(names = "--type", defaultValue = "time", required = true, description = "Search either by travel time or stops.")
Type type;
@Option(names = "--value", required = true, description = "The maximum amount of the given type.")
Integer value;
@Override
protected List<Route> findRoutes(Travel travel) {
RouteFinder routeFinder = new RouteFinder(DefaultDataset.highways);
if (type.equals(Type.stops)) {
return routeFinder.findRouteWithMaxStops(travel.start, travel.destination, value);
} else {
return routeFinder.findRoutesWithMaxTravelTime(travel.start, travel.destination, value);
}
}
protected void printHeaderMessage(Travel travel) {
String typeString = type.equals(Type.stops) ? "stops" : "days travel time";
System.out.println(String.format("Routes with a maximum of %s %s between %s and %s:", value, typeString, travel.start, travel.destination));
}
}
<file_sep>package cma.otto.spacetaxi;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
public class RouteTest {
private RouteParser routeParser;
@BeforeEach
void setUp() {
List<Highway> highways = Arrays.asList(
new Highway("A", "B", 1),
new Highway("B", "C", 1),
new Highway("B", "A", 1),
new Highway("C", "B", 1)
);
routeParser = new RouteParser(highways);
}
@Test
public void testFindLoop() {
assertThat(routeParser.parse("A -> B -> A -> B").containsLoop()).isTrue();
}
@Test
public void testFindLoop2() {
assertThat(routeParser.parse("A -> B -> A").containsLoop()).isFalse();
}
@Test
public void testFindLoop3() {
assertThat(routeParser.parse("A -> B -> C -> B -> A -> B").containsLoop()).isTrue();
}
@Test
public void testHasReachedTarget() {
assertThat(routeParser.parse("A -> B").hasReached("B")).isTrue();
assertThat(routeParser.parse("A -> B").hasReached("A")).isFalse();
}
@Test
public void testHasReachedTargetEmptyRoute() {
assertThat(new Route().hasReached("404")).isFalse();
}
/**
* Test toString because it is used as visible output.
*/
@Test
public void testToStringForOutput() {
assertThat(routeParser.parse("A -> B").toString()).isEqualTo("Route{2 steps: A -> B}(travel time: 1)");
}
}
<file_sep>package cma.otto.spacetaxi;
public class NoSuchRouteException extends IllegalArgumentException {
public NoSuchRouteException() {
super("NO SUCH ROUTE");
}
}
<file_sep>package cma.otto.spacetaxi.commands;
import picocli.CommandLine;
import picocli.CommandLine.Command;
import picocli.CommandLine.Model.CommandSpec;
import picocli.CommandLine.Spec;
import java.util.concurrent.Callable;
//TODO: All commands need more tests
/**
* Main command for the App. All other Commands are loaded via this.
*/
@Command(
name = "taxi",
synopsisSubcommandLabel = "COMMAND",
mixinStandardHelpOptions = true,
subcommands = {PathCommand.class, ShortestCommand.class, MaxCommand.class, ExactCommand.class}
)
public class Commands implements Callable<Integer> {
@Spec
private CommandSpec spec;
@Override
public Integer call() {
throw new CommandLine.ParameterException(spec.commandLine(), "Missing required subcommand");
}
}
<file_sep># Spacetaxi
_It's dangerous to go alone! Take this_
This piece of technology will help you navigate between the explored systems using the established space highways.
## How to run?
You will need Maven3 and Java13 installed on your space cruiser (the only allowed technologies decided by the council).
Execute `mvn clean install` inside this directory. As soon as the build finishes you should be able to run it with the `taxi` command. If you are not able to execute `taxi` you are probably running an unauthorized operation system on your space cruiser. In that case you could try `java -jar target\spacetaxi-0.0.1-SNAPSHOT-jar-with-dependencies.jar` and hope that the council will not detect your disobedience.
Being successful you should see the help and further usage information displayed.
### Features
* You can lookup if your desired route is valid and how long it will take via the `taxi route` command. Example:
* `taxi route "Solar System -> Sirius"`
* You can search for valid routes between two systems. There are multiple command to find the desired routes
* Search by shortest travel time: `taxi shortest "Alpha Centauri" Betelgeuse`
* Search by exact amounts of stops: `taxi exact --value 4 Sirius Sirius`
* Search by maximum stops or travel time: `taxi max --type=time --value 29 Sirius Sirius`
As already mentioned you can use the help system to see a more options and explanation `taxi --help`.
### Assumptions
The current interstellar highway structure only supports travel time in full hours, as a experience space traveller should know.<file_sep>package cma.otto.spacetaxi.commands;
public enum Type {
time, stops
}
<file_sep>package cma.otto.spacetaxi.commands;
import cma.otto.spacetaxi.DefaultDataset;
import cma.otto.spacetaxi.Route;
import cma.otto.spacetaxi.RouteFinder;
import picocli.CommandLine;
import java.util.List;
@CommandLine.Command(
name = "exact",
mixinStandardHelpOptions = true,
description = "Finds routes that fit the specified exact amount of stops."
)
public class ExactCommand extends TravelCommand {
@CommandLine.Option(names = "--value", required = true, description = "The exact amount of steps that the routes need to have.")
Integer value;
@Override
protected List<Route> findRoutes(Travel travel) {
RouteFinder routeFinder = new RouteFinder(DefaultDataset.highways);
return routeFinder.findRoutesWithExactStops(travel.start, travel.destination, value);
}
protected void printHeaderMessage(Travel travel) {
System.out.println(String.format("Routes with exact %s steps between %s and %s:", value, travel.start, travel.destination));
}
}
| fde98b88cb29159ee56ffa14730800297f01f094 | [
"Markdown",
"Java",
"Maven POM"
] | 12 | Java | holzig/spacetaxi | 691e9d2ef25f33cbe0a46ca49477aa0a983ec0fc | af638fcb499db6d0d2ed1695303e3c4d728e8196 |
refs/heads/main | <file_sep>import { Fragment, useEffect, useState } from 'react';
import { getRandomNames } from '../api';
const PokemonForm = ({
pokemonName: externalPokemonName,
initialPokemonName = externalPokemonName || '',
onSubmit,
}) => {
const [pokemonName, setPokemonName] = useState(initialPokemonName);
useEffect(() => {
if (typeof externalPokemonName === 'string') {
setPokemonName(externalPokemonName);
}
}, [externalPokemonName]);
const handleChange = (e) => setPokemonName(e.target.value.toLowerCase());
const handleSubmit = (e) => {
e.preventDefault();
onSubmit(pokemonName);
};
const handleSelect = (name) => {
setPokemonName(name);
onSubmit(name);
};
const [btns, setBtns] = useState([]);
useEffect(() => {
changeNames();
}, []);
const changeNames = () => {
getRandomNames().then(({ results }) => setBtns(results));
};
return (
<form className='form' onSubmit={handleSubmit}>
<div className='form__title'>
<label htmlFor='pokemonNameInput'>Pokemon Name</label>
{btns && (
<small className='form__btns'>
Try{''}
{btns.map((btn, index) => (
<Fragment key={index}>
<button type='button' onClick={() => handleSelect(btn.name)}>
{btn.name}
</button>
{index === btns.length - 1 ? '' : index === btns.length - 2 ? ' or' : ' ,'}
</Fragment>
))}
</small>
)}
<button className='form__submitBtn' onClick={changeNames} type='button'>
Change random Names
</button>
</div>
<div className='form__action'>
<input
className='form__input'
id='pokemonNameInput'
type='text'
placeholder='Pokemon Name....'
value={pokemonName}
onChange={handleChange}
/>
<button className='form__submitBtn' type='submit'>
Submit
</button>
</div>
</form>
);
};
export default PokemonForm;
<file_sep>import { useRef } from 'react';
import PokemonDataView from './PokemonDataView';
const PokemonInfoFallback = ({ name }) => {
const initialName = useRef(name).current;
const fallbckPokemonData = {
name: initialName,
id: '00',
img: '/img/fallback-pokemon.jpg',
abilities: ['ability', 'ability'],
types: ['type', 'type'],
};
return <PokemonDataView pokemon={fallbckPokemonData} />;
};
export default PokemonInfoFallback;
<file_sep>import { useState } from 'react';
import PokemonForm from './components/PokemonForm';
import PokemonSection from './components/pokemonSection/PokemonSection';
const App = () => {
const [pokemonName, setPokemonName] = useState(null);
const handleSubmit = (name) => setPokemonName(name);
const handleSelect = (name) => setPokemonName(name);
return (
<div className='container'>
<PokemonForm pokemonName={pokemonName} onSubmit={handleSubmit} />
<hr />
<PokemonSection pokemonName={pokemonName} onSelect={handleSelect} />
</div>
);
};
export default App;
<file_sep>import { usePokemonCache } from '../../context';
const PokemonPrevius = ({ onSelect }) => {
const { cache } = usePokemonCache();
return (
<div className='pokemon__previus'>
<ul className='pokemon__previusList'>
{Object.keys(cache).map((pokemonName) => (
<li key={pokemonName}>
<button onClick={() => onSelect(pokemonName)}>{pokemonName}</button>
</li>
))}
</ul>
</div>
);
};
export default PokemonPrevius;
<file_sep>export const fetchPokemon = async (query, delay = 1500) => {
const res = await fetch(`https://pokeapi.co/api/v2/pokemon/${query}`, {
headers: {
delay: delay,
},
});
const data = await res.json();
return data;
};
export const getRandomNames = async (limit = 3) => {
const count = 1118;
const offset = Math.floor(Math.random() * (count - limit));
const res = await fetch(`https://pokeapi.co/api/v2/pokemon?limit=${limit}&offset=${offset}`);
const data = await res.json();
return data;
};
<file_sep>import { PokemonCacheProvider } from '../../context';
import PokemonErrorBoundry from '../PokemonErrorBoundry';
import PokemonInfo from './PokemonInfo';
import PokemonPrevius from './PokemonPrevius';
const PokemonSection = ({ onSelect, pokemonName }) => {
return (
<PokemonCacheProvider>
<section className='pokemon__section'>
<PokemonPrevius onSelect={onSelect} />
<PokemonErrorBoundry resetKeys={[pokemonName]} onReset={() => onSelect('')}>
<PokemonInfo pokemonName={pokemonName} />
</PokemonErrorBoundry>
</section>
</PokemonCacheProvider>
);
};
export default PokemonSection;
<file_sep>import { useEffect } from 'react';
import { fetchPokemon } from '../../api';
import { usePokemonCache } from '../../context';
import useAsync from '../../useAsync';
import PokemonDataView from './PokemonDataView';
import PokemonInfoFallback from './PokemonInfoFallback';
const PokemonInfo = ({ pokemonName }) => {
const { cache, dispatch } = usePokemonCache();
const { data: pokemon, status, run, setData, error } = useAsync();
useEffect(() => {
if (!pokemonName) {
return;
} else if (cache[pokemonName]) {
setData(cache[pokemonName]);
} else {
run(
fetchPokemon(pokemonName).then((pokemonData) => {
let {
abilities,
name,
sprites: { front_default: img },
types,
id,
} = pokemonData;
types = types.map((i) => i.type.name);
abilities = abilities.map((i) => i.ability.name);
dispatch({
type: 'ADD_POKEMON',
pokemonName,
pokemonData: { abilities, name, img, types, id },
});
return pokemonData;
})
);
}
}, [cache, dispatch, pokemonName, run, setData]);
if (status === 'idle') {
return 'Submit a pokemon';
} else if (status === 'pending') {
return <PokemonInfoFallback name={pokemonName} />;
} else if (status === 'rejected') {
throw error;
} else if (status === 'resolved') {
return <PokemonDataView pokemon={pokemon} />;
}
};
export default PokemonInfo;
<file_sep>const PokemonDataView = ({ pokemon }) => {
return (
<div className='pokemon__info'>
<h5>
<span className='pokemon__number'>{pokemon.id}</span> -{' '}
<span className='pokemon__name'>{pokemon.name}</span>
</h5>
<img
className='pokemon__image'
src={pokemon.img || '/img/fallback-pokemon.jpg'}
alt={pokemon.name}
/>
<figure>
<figcaption>Types :</figcaption>
<ul className='pokemon__list'>
{pokemon.types.map((type, index) => (
<li className='pokemon__badge' key={index}>
{type}
</li>
))}
</ul>
</figure>
<hr />
<figure>
<figcaption>Abilities :</figcaption>
<ul className='pokemon__list'>
{pokemon.abilities.map((ability, index) => (
<li className='pokemon__badge' key={index}>
{ability}
</li>
))}
</ul>
</figure>
</div>
);
};
export default PokemonDataView;
| 0c370b122411af77d6ac8e408b9dca00a1109aff | [
"JavaScript"
] | 8 | JavaScript | zetsme/pokemon-cache-context | 2de62bcdcd0b9899db9b33f52b3aa0837803eff9 | fafffe8cdca92de6312a2238b82a291ebd9bf646 |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using COMMON;
namespace DAL
{
public class CategoriaDAL : AbstractDAL
{
#region propiedades y constructores
public Categoria Cat { get; set; }
public CategoriaDAL()
{
}
public CategoriaDAL(Categoria Cat)
{
this.Cat = Cat;
}
#endregion
#region Metodos de clase
public override void delete()
{
string query = @"Update Categoria SET estado=0, fechaActualizacion = CURRENT_TIMESTAMP, idUsuario = @IdUsuario
WHERE IdCategoria = @IdCategoria";
SqlCommand cmd;
try
{
cmd = Methods.CreateBasicCommand(query);
cmd.Parameters.AddWithValue("@IdCategoria", Cat.IdCategoria);
cmd.Parameters.AddWithValue("@idUsuario", '1');
Methods.ExecuteBasicCommand(cmd);
}
catch (Exception ex)
{
//OJO agregar al LOG de errores
throw ex;
}
}
public override void insert()
{
string query = @"insert into categoria (nombreCategoria, idUsuario)
values (@nombreCategoria, @idusuario)";
SqlCommand cmd;
try
{
cmd = Methods.CreateBasicCommand(query);
cmd.Parameters.AddWithValue("@nombreCategoria", Cat.NombreCategoria);
cmd.Parameters.AddWithValue("@idusuario", Cat.IdUsuario);
Methods.ExecuteBasicCommand(cmd);
}
catch (Exception ex)
{
//OJO agregar al LOG de errores
throw ex;
}
}
public override DataTable select()
{
//esta consulta en vez del * puedes colocar le idestablecimiento nombre, municipio o el dato que quiera seleccionar, etc
string consulta = @"select * from vwCategoria";
DataTable res; //variable que almacenara los datos de la tabla
SqlCommand cmd; //variable para almacenar la conexion
try
{
cmd = Methods.CreateBasicCommand(consulta); //cremoa el comando basico
res = Methods.ExecuteDataTableCommand(cmd); //llenamos en dr la tabla que queremos mostrar
}
catch (Exception err)
{
//OJO Escribir en el LOG
throw err;
}
return res;
}
public override void update()
{
string query = @"Update Categoria SET nombreCategoria = @nombreCategoria, fechaActualizacion = CURRENT_TIMESTAMP, idusuario=@idUsuario
WHERE IdCategoria = @IdCategoria";
SqlCommand cmd;
try
{
cmd = Methods.CreateBasicCommand(query);
cmd.Parameters.AddWithValue("@nombreCategoria", Cat.NombreCategoria);
cmd.Parameters.AddWithValue("@idusuario", Cat.IdUsuario);
cmd.Parameters.AddWithValue("@IdCategoria", Cat.IdCategoria);
Methods.ExecuteBasicCommand(cmd);
}
catch (Exception ex)
{
//OJO agregar al LOG de errores
throw ex;
}
}
public Categoria Get(int id)
{
Categoria res = null;
string query = @"Select idCategoria, nombreCategoria, estado, fechaRegistro, fechaActualizacion, idusuario
From Categoria
where idCategoria = @idcategoria;";
SqlCommand cmd = null;
SqlDataReader dr = null;
try
{
cmd = Methods.CreateBasicCommand(query);
cmd.Parameters.AddWithValue("@idCategoria", id);
dr = Methods.ExecuteDataReaderCommand(cmd);
while (dr.Read())
{
res = new Categoria(byte.Parse(dr[0].ToString()),dr[1].ToString(),byte.Parse(dr[2].ToString()),DateTime.Parse(dr[3].ToString()),DateTime.Parse(dr[4].ToString()),int.Parse(dr[5].ToString()));
}
}
catch (Exception err)
{
throw err;
}
finally
{
cmd.Connection.Close();
dr.Close();
}
return res;
}
#endregion
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
namespace DAL
{
public abstract class AbstractDAL
{
public abstract void insert();
public abstract void update();
public abstract void delete();
public abstract DataTable select();
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace COMMON
{
public class Categoria
{
#region Propiedades
public byte IdCategoria { get; set; }
public string NombreCategoria { get; set; }
public byte Estado { get; set; }
public DateTime FechaRegistro { get; set; }
public DateTime FechaActualizacion { get; set; }
public int IdUsuario { get; set; }
#endregion
#region Constructores
/// <summary>
/// Constructor para el GET
/// </summary>
/// <param name="IdCategoria"></param>
/// <param name="NombreCategoria"></param>
/// <param name="Estado"></param>
/// <param name="FechaRegistro"></param>
/// <param name="FechaActualizacion"></param>
/// <param name="IdUsuario"></param>
public Categoria(byte IdCategoria, string NombreCategoria, byte Estado, DateTime FechaRegistro, DateTime FechaActualizacion, int IdUsuario)
{
this.IdCategoria = IdCategoria;
this.NombreCategoria = NombreCategoria;
this.Estado = Estado;
this.FechaRegistro = FechaRegistro;
this.FechaActualizacion = FechaActualizacion;
this.IdUsuario = IdUsuario;
}
/// <summary>
/// Constructor para el Insert
/// </summary>
/// <param name="NombreCategoria"></param>
/// <param name="IdUsuario"></param>
public Categoria(string NombreCategoria, int IdUsuario)
{
this.NombreCategoria = NombreCategoria;
this.IdUsuario = IdUsuario;
}
#endregion
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using COMMON;
using DAL;
namespace BRL
{
public class CategoriaBRL : AbstractBRL
{
#region Propiedades y constructores
public Categoria Cat { get; set; }
public CategoriaDAL Dal { get; set; }
public CategoriaBRL()
{
Dal = new CategoriaDAL();
}
public CategoriaBRL(Categoria Cat)
{
this.Cat = Cat;
Dal = new CategoriaDAL(Cat);
}
#endregion
#region Métodos de la Clase
public override void delete()
{
Dal.delete();
}
public override void insert()
{
Dal.insert();
}
public override DataTable select()
{
return Dal.select();
}
public override void update()
{
Dal.update();
}
public Categoria Get(int idCategoria)
{
return Dal.Get(idCategoria);
}
#endregion
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BRL
{
public abstract class AbstractBRL
{
public abstract void insert();
public abstract void update();
public abstract void delete();
public abstract DataTable select();
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
using System.Data;
namespace DAL
{
public class Methods
{
static string cadconnection = @"Data Source=localhost;Initial Catalog=dbpedidos;User ID=user; Password=<PASSWORD>";
static SqlConnection connection;
#region Crear Comandos
public static SqlCommand createBasicCommand ()
{
connection = new SqlConnection(cadconnection);
SqlCommand res = new SqlCommand();
res.Connection = connection;
return res;
}
public static SqlCommand CreateBasicCommand(string query)
{
SqlConnection connection = new SqlConnection(cadconnection);
SqlCommand cmd = new SqlCommand(query);
cmd.Connection = connection;
return cmd;
}
#endregion
#region Ejecucion de comandos
public static void ExecuteBasicCommand(SqlCommand cmd)
{
try
{
cmd.Connection.Open();
cmd.ExecuteNonQuery();
}
catch (Exception err)
{
throw err;
}
finally
{
cmd.Connection.Close();
}
}
public static DataTable ExecuteDataTableCommand(SqlCommand cmd)
{
DataTable dt = new DataTable(); // componente ADO
try
{
cmd.Connection.Open();
SqlDataAdapter adaptador = new SqlDataAdapter(cmd);
adaptador.Fill(dt);
}
catch (Exception ex)
{
throw ex;
}
finally
{
cmd.Connection.Close();
}
return dt;
}
//Este metodo es usado solo por el GET
public static SqlDataReader ExecuteDataReaderCommand(SqlCommand cmd)
{
SqlDataReader dr = null;
try
{
cmd.Connection.Open();
dr = cmd.ExecuteReader();
}
catch (Exception err)
{
throw err;
}
return dr;
}
#endregion
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using COMMON;
using BRL;
using System.Data;
namespace Distribuidora.Categorias
{
/// <summary>
/// Interaction logic for winAdmCategorias.xaml
/// </summary>
public partial class winAdmCategorias : Window
{
byte option = 0;
Categoria cat;
CategoriaBRL brl;
public winAdmCategorias()
{
InitializeComponent();
}
void Habilitar(byte option)
{
btnGuardar.IsEnabled = true;
btnCancelar.IsEnabled = true;
txtCategoria.IsEnabled = true;
btnInsertar.IsEnabled = false;
btnModificar.IsEnabled = false;
btnEliminar.IsEnabled = false;
this.option = option;
}
void DesHabilitar()
{
txtCategoria.Text = "";
btnGuardar.IsEnabled = false;
btnCancelar.IsEnabled = false;
txtCategoria.IsEnabled = false;
btnInsertar.IsEnabled = true;
btnModificar.IsEnabled = true;
btnEliminar.IsEnabled = true;
}
void LlenarDataGrid()
{
try
{
brl = new CategoriaBRL();
dgvDatos.ItemsSource = null;
dgvDatos.ItemsSource = brl.select().DefaultView;
dgvDatos.Columns[0].Visibility = Visibility.Hidden;
}catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void btnClose_Click(object sender, RoutedEventArgs e)
{
this.Close();
}
private void btnInsertar_Click(object sender, RoutedEventArgs e)
{
Habilitar(1);
txtCategoria.Text = "";
txtCategoria.Focus();
}
private void btnModificar_Click(object sender, RoutedEventArgs e)
{
Habilitar(2);
}
private void btnEliminar_Click(object sender, RoutedEventArgs e)
{
if(dgvDatos.SelectedItem!= null && cat!= null)
{
if (MessageBox.Show("Esta realmente seguro de eliminar el registro?","Eliminar", MessageBoxButton.YesNo,MessageBoxImage.Question)== MessageBoxResult.Yes)
{
brl = new CategoriaBRL(cat);
brl.delete();
LlenarDataGrid();
DesHabilitar();
}
}
}
private void btnCancelar_Click(object sender, RoutedEventArgs e)
{
DesHabilitar();
}
private void btnGuardar_Click(object sender, RoutedEventArgs e)
{
switch(option)
{
case 1: //Insertar
//Creamos el Objeto
try
{
cat = new Categoria(txtCategoria.Text, 1);
brl = new CategoriaBRL(cat);
brl.insert();
MessageBox.Show("Categoria creada con extio..");
DesHabilitar();
LlenarDataGrid();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
break;
case 2: // Modificar
try
{
cat.NombreCategoria = txtCategoria.Text;
brl = new CategoriaBRL(cat);
brl.update();
MessageBox.Show("Categoria actualizada con extio..");
DesHabilitar();
LlenarDataGrid();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
break;
}
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
LlenarDataGrid();
}
private void dgvDatos_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (dgvDatos.SelectedItem !=null && dgvDatos.Items.Count>0)
{
try
{
DataRowView dataRow = (DataRowView)dgvDatos.SelectedItem; //lo que se ah seleccionado lo convertimos en una fila
byte id = byte.Parse(dataRow.Row.ItemArray[0].ToString());
brl = new CategoriaBRL();
cat = brl.Get(id);
if (cat != null)
{
txtCategoria.Text = cat.NombreCategoria;
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
/*
private void btnModificar_Click_1(object sender, RoutedEventArgs e)
{
}*/
}
}
| cf06c55ea7dfba1760bde40b97c9aa9088e29fc3 | [
"C#"
] | 7 | C# | aspeti/Distribuidora | 09d7e5c75f85ad7421d840a1b5d9375b58df4915 | b6dfff910a9afc46056b514da9e190d96a7b79a4 |
refs/heads/master | <file_sep>//通用帮助类
export class ComHelper {
static PageSize: number = 15;
//判断是否空值(null或者undefined)
//val:需判断的内容
static isEmptry(val: any): boolean {
if (val == null || typeof (val) == 'undefined' || val == '') {
return true;
}
return false;
}
//字符串填充
//str:需填充的字符串
//len:填充到个数
//padStr:填充内容
static padding(str: any, len: number, padStr: string): string {
let padLen = len - (str + '').length;
for (let i = 0; i < padLen; i++) {
str = padStr + str;
}
return str;
}
}
<file_sep>import { Injectable } from '@angular/core';
import { API } from 'src/api/API';
import { AmountAccountListInfo } from 'src/model/basic/AmountAccountListInfo';
import { ResultList } from 'src/model/comm/ResultList';
import { AmountAccountInfo } from 'src/model/basic/AmountAccountInfo';
import { ResultInfo } from 'src/model/comm/ResultInfo';
import { IDReq } from 'src/model/comm/IDReq';
import { InTypeListInfo } from 'src/model/basic/InTypeListInfo';
import { InTypeInfo } from 'src/model/basic/InTypeInfo';
import { OutCategoryTypeListInfo } from 'src/model/basic/OutCategoryTypeListInfo';
import { OutCategoryInfo } from 'src/model/basic/OutCategoryInfo';
import { OutTypeInfo } from 'src/model/basic/OutTypeInfo';
import { BasicStore } from 'src/store/BasicStore';
import { IDNameInfo } from 'src/model/comm/IDNameInfo';
@Injectable()
export class BasicAPI {
//构造函数
constructor(private api: API, private basicStore: BasicStore) {}
/********************** 账户 Start **********************/
//查询账户列表
async queryAmountAccount(showLoader: boolean = true): Promise<ResultList<AmountAccountListInfo>> {
let list = await this.api.get<ResultList<AmountAccountListInfo>>(
'/api/Basic/QueryAmountAccount',
null,
showLoader
);
//缓存
this.basicStore.setAmountAccountList(list.lstInfo);
return list;
}
//获取账户
async getAmountAccount(id: number): Promise<ResultInfo<AmountAccountInfo>> {
const url = '/api/Basic/GetAmountAccount/' + id;
return await this.api.get<ResultInfo<AmountAccountInfo>>(url, null, false);
}
//保存资金账户
async saveAmountAccount(info: AmountAccountInfo): Promise<ResultInfo<number>> {
const url = '/api/Basic/SaveAmountAccount';
return await this.api.postInfo<ResultInfo<number>>(url, info, true);
}
//删除资金账户
async deleteAmountAccount(id: number): Promise<ResultInfo<boolean>> {
const url = '/api/Basic/DeleteAmountAccount';
const req: IDReq = new IDReq();
req.id = id;
return await this.api.postInfo<ResultInfo<boolean>>(url, req, true);
}
/********************** 账户 End **********************/
/********************** 收入类型 Start **********************/
//查询收入类型列表
async queryInType(showLoader: boolean = true): Promise<ResultList<InTypeListInfo>> {
let list = await this.api.get<ResultList<InTypeListInfo>>(
'/api/Basic/QueryInType',
null,
showLoader
);
//缓存
this.basicStore.setInTypeList(list.lstInfo);
return list;
}
//获取收入类型
async getInType(id: number): Promise<ResultInfo<InTypeInfo>> {
const url = '/api/Basic/GetInType/' + id;
return await this.api.get<ResultInfo<InTypeInfo>>(url, null, false);
}
//保存收入类型
async saveInType(info: InTypeInfo): Promise<ResultInfo<number>> {
const url = '/api/Basic/SaveInType';
return await this.api.postInfo<ResultInfo<number>>(url, info, true);
}
//删除收入类型
async deleteInType(id: number): Promise<ResultInfo<boolean>> {
const url = '/api/Basic/DeleteInType';
const req: IDReq = new IDReq();
req.id = id;
return await this.api.postInfo<ResultInfo<boolean>>(url, req, true);
}
/********************** 收入类型 End **********************/
/********************** 支出类型/类型 Start **********************/
//查询支出分类类型列表
async queryOutCategoryType(showLoader: boolean = true): Promise<ResultList<OutCategoryTypeListInfo>> {
let list = await this.api.get<ResultList<OutCategoryTypeListInfo>>(
'/api/Basic/QueryOutCategoryType',
null,
showLoader
);
//缓存
this.basicStore.setOutCategoryTypeList(list.lstInfo);
return list;
}
//获取支出分类
async getOutCategory(id: number): Promise<ResultInfo<OutCategoryInfo>> {
const url = '/api/Basic/GetOutCategory/' + id;
return await this.api.get<ResultInfo<OutCategoryInfo>>(url, null, false);
}
//保存支出分类
async saveOutCategory(info: OutCategoryInfo): Promise<ResultInfo<number>> {
const url = '/api/Basic/SaveOutCategory';
return await this.api.postInfo<ResultInfo<number>>(url, info, true);
}
//删除支出分类
async deleteOutCategory(id: number): Promise<ResultInfo<boolean>> {
const url = '/api/Basic/DeleteOutCategory';
const req: IDReq = new IDReq();
req.id = id;
return await this.api.postInfo<ResultInfo<boolean>>(url, req, true);
}
//获取支出类型
async getOutType(id: number): Promise<ResultInfo<OutTypeInfo>> {
const url = '/api/Basic/GetOutType/' + id;
return await this.api.get<ResultInfo<OutTypeInfo>>(url, null, false);
}
//保存支出类型
async saveOutType(info: OutTypeInfo): Promise<ResultInfo<number>> {
const url = '/api/Basic/SaveOutType';
return await this.api.postInfo<ResultInfo<number>>(url, info, true);
}
//删除支出类型
async deleteOutType(id: number): Promise<ResultInfo<boolean>> {
const url = '/api/Basic/DeleteOutType';
const req: IDReq = new IDReq();
req.id = id;
return await this.api.postInfo<ResultInfo<boolean>>(url, req, true);
}
/********************** 支出类型/类型 End **********************/
/********************** 下拉框 Start **********************/
//获取借还类型
async queryBorrowRepayType(): Promise<ResultList<IDNameInfo>> {
const url = '/api/Basic/QueryBorrowRepayType';
let list = await this.api.get<ResultList<IDNameInfo>>(url, null, false);
//缓存
this.basicStore.setBorrowRepayList(list.lstInfo);
return list;
}
/********************** 下拉框 End **********************/
}
<file_sep>import { BaseReq } from '../comm/BaseReq';
//账号流水 请求类
export class AccountTurnoverListReq extends BaseReq {
month: Date; //月份
lstAmountAccountID: Array<number>; //账户ID集合
}<file_sep>//列表结果
export class ResultList<T> implements IResult {
isOK: boolean; //是否成功
code: string; //消息编码
msg: string; //信息
lstInfo: Array<T>; //结果
}<file_sep>import { BaseInfo } from './BaseInfo';
//列表用信息基类
export class BaseListInfo extends BaseInfo {
}
<file_sep>import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { Routes, RouterModule } from '@angular/router';
import { IonicModule } from '@ionic/angular';
import { OutTypeListPage } from './out-type-list.page';
import { OutCategoryDetailPage } from '../out-category-detail/out-category-detail.page';
import { OutTypeDetailPage } from '../out-type-detail/out-type-detail.page';
import { ComponentsModule } from 'src/app/components/components.module';
const routes: Routes = [
{
path: '',
component: OutTypeListPage
}
];
@NgModule({
imports: [
CommonModule,
FormsModule,
IonicModule,
RouterModule.forChild(routes),
ComponentsModule
],
declarations: [OutTypeListPage, OutCategoryDetailPage, OutTypeDetailPage],
entryComponents: [OutCategoryDetailPage, OutTypeDetailPage]
})
export class OutTypeListPageModule {}
<file_sep>import { Component, OnInit } from '@angular/core';
import { InComeInfo } from 'src/model/inout/InComeInfo';
import { BasePage } from 'src/app/base/BasePage';
import { ModalController, NavParams } from '@ionic/angular';
import { InOutAPI } from 'src/api/InOutAPI';
import { MsgboxUtil } from 'src/helper/MsgboxUtil';
import { ComHelper } from 'src/helper/comHelper';
import { isNumeric } from 'rxjs/util/isNumeric';
import { PickerColumnOption } from '@ionic/core';
import { PickerAccColOption } from 'src/model/comm/PickerColOption';
@Component({
selector: 'app-in-come-detail',
templateUrl: './in-come-detail.page.html',
styleUrls: ['./in-come-detail.page.scss'],
})
export class InComeDetailPage extends BasePage implements OnInit {
//收入信息
item: InComeInfo = new InComeInfo();
//是否查看模式
isView: boolean;
constructor(
private modalCtrl: ModalController,
private navParams: NavParams,
private inoutAPI: InOutAPI,
private msgBox: MsgboxUtil
) {
super();
}
ngOnInit() {
//传入的参数
const id = this.navParams.get('id');
const date = this.navParams.get('date');
this.isView = this.navParams.get('isView');
//初始化页面
this.initPage(id, date);
}
//获取操作模式:添加/修改
getOpeModel() {
if (this.isView) {
return '查看';
}
if (this.item.id > 0) {
return '修改';
}
return '添加';
}
//初始化页面
async initPage(id: number, date: Date) {
//添加
if (id === 0) {
this.item.id = id;
this.item.inDate = date;
return;
}
//修改
try {
const ret = await this.inoutAPI.getInCome(id);
if (ret.isOK) {
this.item = ret.info;
}
} catch (err) {
//异常,销毁本页面
this.dismiss(false);
}
}
//类型选择事件
selectedInType(val: PickerColumnOption) {
let accVal = val as PickerAccColOption;
if (accVal) {
this.item.amountAccountID = accVal.amountAccountID;
}
}
//检查输入是否合法
chkInput() {
if (ComHelper.isEmptry(this.item.inDate)) {
this.msgBox.infoDanger('请选择日期');
return false;
}
if (ComHelper.isEmptry(this.item.inTypeID) || this.item.inTypeID <= 0) {
this.msgBox.infoDanger('请选择类型');
return false;
}
if (ComHelper.isEmptry(this.item.amountAccountID) || this.item.amountAccountID <= 0) {
this.msgBox.infoDanger('请选择账户');
return false;
}
if (isNumeric(this.item.amount) === false) {
this.msgBox.infoDanger('请输入金额');
return false;
}
return true;
}
//保存
async save() {
if (this.chkInput() === false) {
return;
}
await this.msgBox.actSheet(
[
{
text: '保存',
role: 'destructive',
handler: () => {
this.inoutAPI
.saveInCome(this.item)
.then(result => {
if (result.isOK) {
this.dismiss(true);
} else {
this.msgBox.infoDanger(result.msg);
}
})
.catch(err => {
//异常,销毁本页面
this.dismiss(false);
});
}
},
{
text: '取消',
role: 'cancel'
}
]);
}
//销毁页面
dismiss(isSave: boolean) {
this.modalCtrl.dismiss(isSave);
}
}
<file_sep>import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { Routes, RouterModule } from '@angular/router';
import { IonicModule } from '@ionic/angular';
import { MonthSumListPage } from './month-sum-list.page';
import { MonthSumPopComponent } from 'src/app/components/month-sum-pop/month-sum-pop.component';
const routes: Routes = [
{
path: '',
component: MonthSumListPage
}
];
@NgModule({
imports: [
CommonModule,
FormsModule,
IonicModule,
RouterModule.forChild(routes)
],
declarations: [MonthSumListPage, MonthSumPopComponent],
entryComponents: [MonthSumPopComponent]
})
export class MonthSumListPageModule {}
<file_sep>import { LoginReq } from 'src/model/account/LoginReq';
import { Store } from './Store';
import { LoginInfo } from 'src/model/account/LoginInfo';
import { Injectable } from '@angular/core';
@Injectable()
export class ConfigStore {
constructor(private store: Store) { }
//保存接口地址
setApiBaseUrl(val: string) {
this.store.setLocal('ApiBaseUrl', val);
}
//获取接口地址
getApiBaseUrl(): string {
let apiBaseUrl = this.store.getLocal<string>('ApiBaseUrl');
if (apiBaseUrl == null) {
apiBaseUrl = 'http://192.168.3.11:20001';
this.setApiBaseUrl(apiBaseUrl);
}
return apiBaseUrl;
}
}
<file_sep>//收支类型显示类型
export enum EnmShowInOutType {
All = '1', //全部
In = '2', //收入
Out = '3', //支出
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute, Params } from '@angular/router';
@Component({
selector: 'app-error',
templateUrl: './error.page.html',
styleUrls: ['./error.page.scss']
})
export class ErrorPage implements OnInit {
//错误信息
errMsg: string;
constructor(private router: Router, private activeRoute: ActivatedRoute) {}
ngOnInit() {
this.activeRoute.queryParams.subscribe((params: Params) => {
this.errMsg = params['errMsg'];
});
}
//重新登录
async logOut() {
//跳到登录页
this.router.navigate(['login']);
}
}
<file_sep>//单个结果
export class ResultInfo<T> implements IResult {
isOK: boolean; //是否成功
code: string; //消息编码
msg: string; //信息
info: T; //结果
}<file_sep>import { BaseListInfo } from '../comm/BaseListInfo';
import { MonthOutTypeSumListInfo } from './MonthOutTypeSumListInfo';
import { EnmDataType } from '../enums/enmDataType';
//月份支出分类统计
export class MonthOutCategorySumListInfo extends BaseListInfo {
id: number; //支出分类ID
name: string; //支出分类名称
dataType: EnmDataType; //数据类型
amount: number; //金额
lstSumOutType: Array<MonthOutTypeSumListInfo>; //月份支出类型统计
}
<file_sep>import { ResultList } from './ResultList';
//分页列表结果
export class ResultPageList<T> extends ResultList<T> {
startNum: number; //返回的第一条记录位置(第几条)
totalRecord: number; //总条数
hasMore: boolean; //是否还有更多的记录
}<file_sep>import { BaseListInfo } from '../comm/BaseListInfo';
//支出分类列表
export class OutCategoryListInfo extends BaseListInfo {
id: number; //主键
name: string; //名称
isActive: boolean; //是否可用
}<file_sep>import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { IonTdbPickerMulti2Component } from './ion-tdb-picker-multi2.component';
describe('IonTdbPickerMulti2Component', () => {
let component: IonTdbPickerMulti2Component;
let fixture: ComponentFixture<IonTdbPickerMulti2Component>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ IonTdbPickerMulti2Component ],
schemas: [CUSTOM_ELEMENTS_SCHEMA],
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(IonTdbPickerMulti2Component);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
<file_sep>//结果接口
interface IResult {
isOK: boolean; //是否成功
code: string; //消息编码
msg: string; //信息
} <file_sep><ion-header>
<ion-toolbar>
<ion-title>{{ info?.familyName }}</ion-title>
</ion-toolbar>
</ion-header>
<ion-content color="light">
<ion-refresher slot="fixed" (ionRefresh)="doRefresh($event)">
<ion-refresher-content pullingIcon="arrow-dropdown" pullingText="下拉刷新" refreshingSpinner="circles"
refreshingText="刷新中...">
</ion-refresher-content>
</ion-refresher>
<ion-item-group>
<ion-list lines="full" class="top-list">
<ion-item>
<ion-icon name="person"></ion-icon>
<ion-label class="nickName">{{ info?.nickName }}</ion-label>
</ion-item>
</ion-list>
</ion-item-group>
<ion-item-group>
<ion-item-divider>
<ion-label>包含借还</ion-label>
<ion-toggle slot="end" [(ngModel)]="isBR"></ion-toggle>
</ion-item-divider>
<ion-item>
<ion-label>总资金:</ion-label>
<ion-note color="dark" slot="end">{{ info?.totalAmount | number: '1.2-2' }}</ion-note>
</ion-item>
<ion-item>
<ion-label>{{ info?.year }}年收入:</ion-label>
<ion-note color="dark" slot="end">{{ sumInYear() | number: '1.2-2' }}</ion-note>
</ion-item>
<ion-item>
<ion-label>{{ info?.year }}年支出:</ion-label>
<ion-note color="dark" slot="end">{{ sumOutYear() | number: '1.2-2' }}</ion-note>
</ion-item>
<ion-item>
<ion-label>{{ info?.month }}月收入:</ion-label>
<ion-note color="dark" slot="end">{{ sumInMonth() | number: '1.2-2' }}</ion-note>
</ion-item>
<ion-item>
<ion-label>{{ info?.month }}月支出:</ion-label>
<ion-note color="dark" slot="end">{{ sumOutMonth() | number: '1.2-2' }}</ion-note>
</ion-item>
</ion-item-group>
<ion-row responsive-sm>
<ion-col>
<ion-button (click)="logOut()" expand="block" class="logoutBtn">
退出
</ion-button>
</ion-col>
</ion-row>
</ion-content><file_sep>import { ComHelper } from './comHelper';
//日期帮助类
export class DateHelper {
private static SIGN_REGEXP: RegExp = /([yMdhsm])(\1*)/g;
private static DEFAULT_PATTERN = 'yyyy-MM-dd';
//格式化日期
//date:日期
//pattern:格式(默认为 yyyy-MM-dd)
static format(date: Date, pattern: string = ''): string {
if (!(date instanceof Date)) {
date = new Date(date);
}
pattern = pattern || this.DEFAULT_PATTERN;
let that = this;
return pattern.replace(this.SIGN_REGEXP, ($0) => {
switch ($0.charAt(0)) {
case 'y':
return ComHelper.padding(date.getFullYear(), $0.length, '0');
case 'M':
return ComHelper.padding(date.getMonth() + 1, $0.length, '0');
case 'd':
return ComHelper.padding(date.getDate(), $0.length, '0');
case 'w':
return (date.getDay() + 1) + '';
case 'h':
return ComHelper.padding(date.getHours(), $0.length, '0');
case 'm':
return ComHelper.padding(date.getMinutes(), $0.length, '0');
case 's':
return ComHelper.padding(date.getSeconds(), $0.length, '0');
}
});
}
//解析日期字符串
//dateStr:日期字符串
//pattern:格式(默认为 yyyy-MM-dd)
static parse(dateStr: string, pattern: string = ''): Date {
pattern = pattern || this.DEFAULT_PATTERN;
let matchs1 = pattern.match(this.SIGN_REGEXP);
let matchs2 = dateStr.match(/(\d)+/g);
if (matchs1.length === matchs2.length) {
let _date = new Date(1970, 0, 1);
for (let i = 0; i < matchs1.length; i++) {
let _int = parseInt(matchs2[i]);
let sign = matchs1[i];
switch (sign.charAt(0)) {
case 'y':
_date.setFullYear(_int);
break;
case 'M':
_date.setMonth(_int - 1);
break;
case 'd':
_date.setDate(_int);
break;
case 'h':
_date.setHours(_int);
break;
case 'm':
_date.setMinutes(_int);
break;
case 's':
_date.setSeconds(_int);
break;
}
}
return _date;
}
return null;
}
//日期加减
//date:日期
//addDay:加天数(如减天数,传入负数)
static addDay(date: Date, addDay: number): Date {
date.setDate(date.getDate() + addDay);
return date;
}
//月份加减
//date:日期
//addMonth:加月数(如减月数,传入负数)
static addMonth(date: Date, addMonth: number): Date {
date.setMonth(date.getMonth() + addMonth);
return date;
}
//获取制定日期的月初
static getMonthStart(date: Date): Date {
return new Date(date.getFullYear(), date.getMonth(), 1);
}
//获取制定日期的月末
static getMonthEnd(date: Date): Date {
return new Date(date.getFullYear(), date.getMonth() + 1, 0, 23, 59, 59, 999);
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { BasePage } from 'src/app/base/BasePage';
@Component({
selector: 'app-basic-tab',
templateUrl: './basic-tab.page.html',
styleUrls: ['./basic-tab.page.scss'],
})
export class BasicTabPage extends BasePage implements OnInit {
constructor() {
super();
}
ngOnInit() {
}
}
<file_sep>import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { TabsPage } from './tabs.page';
const routes: Routes = [
{
path: 'tabs',
component: TabsPage,
children: [
{
path: 'inoutTab',
children: [
{
path: '',
loadChildren: '../inout/inout-tab/inout-tab.module#InoutTabPageModule'
},
{
path: 'inComeList',
loadChildren: '../inout/in-come-list/in-come-list.module#InComeListPageModule'
},
{
path: 'outPutList',
loadChildren: '../inout/out-put-list/out-put-list.module#OutPutListPageModule'
},
{
path: 'transferList',
loadChildren: '../inout/transfer-list/transfer-list.module#TransferListPageModule'
},
{
path: 'borrowRepayList',
loadChildren: '../inout/borrow-repay-list/borrow-repay-list.module#BorrowRepayListPageModule'
}
]
},
{
path: 'reportTab',
children: [
{
path: '',
loadChildren: '../report/report-tab/report-tab.module#ReportTabPageModule'
},
{
path: 'accountTurnoverList',
loadChildren: '../report/account-turnover-list/account-turnover-list.module#AccountTurnoverListPageModule'
},
{
path: 'borrowRepaySumList',
loadChildren: '../report/borrow-repay-sum-list/borrow-repay-sum-list.module#BorrowRepaySumListPageModule'
},
{
path: 'borrowRepaySumDetailList/:target',
loadChildren: '../report/borrow-repay-sum-detail-list/borrow-repay-sum-detail-list.module#BorrowRepaySumDetailListPageModule'
},
{
path: 'monthSumList',
loadChildren: '../report/month-sum-list/month-sum-list.module#MonthSumListPageModule'
},
{
path: 'monthInSumList',
loadChildren: '../report/month-in-sum-list/month-in-sum-list.module#MonthInSumListPageModule'
},
{
path: 'monthInOutSumDetailList',
loadChildren: '../report/month-in-out-sum-detail-list/month-in-out-sum-detail-list.module#MonthInOutSumDetailListPageModule'
},
{
path: 'monthOutSumList',
loadChildren: '../report/month-out-sum-list/month-out-sum-list.module#MonthOutSumListPageModule'
}
]
},
{
path: 'basicTab',
children: [
{
path: '',
loadChildren: '../basic/basic-tab/basic-tab.module#BasicTabPageModule'
},
{
path: 'inTypeList',
loadChildren: '../basic/in-type-list/in-type-list.module#InTypeListPageModule'
},
{
path: 'outTypeList',
loadChildren: '../basic/out-type-list/out-type-list.module#OutTypeListPageModule'
},
{
path: 'amountAccountList',
loadChildren:
'../basic/amount-account-list/amount-account-list.module#AmountAccountListPageModule'
}
]
},
{
path: 'mineTab',
children: [
{
path: '',
loadChildren: '../mine/mine/mine.module#MinePageModule'
}
]
},
{
path: '',
redirectTo: '/tabs/inoutTab',
pathMatch: 'full'
}
]
},
{
path: '',
redirectTo: '/tabs/inoutTab',
pathMatch: 'full'
}
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export class TabsPageRoutingModule { }
<file_sep>import { Injectable } from '@angular/core';
import { ToastController, AlertController, LoadingController, ActionSheetController } from '@ionic/angular';
import { createWiresService } from 'selenium-webdriver/firefox';
import { AlertButton, ActionSheetButton } from '@ionic/core';
// 弹框相关功能
@Injectable()
export class MsgboxUtil {
constructor(
private actionSheet: ActionSheetController,
private toastCtrl: ToastController,
private alertCtrl: AlertController,
private loadingCtrl: LoadingController
) { }
// 用toast提示信息,颜色danger
async infoDanger(msg: string) {
await this.info(msg, 'danger');
}
// 用toast提示信息
async info(msg: string, color: string) {
const toast = await this.toastCtrl.create({
color: color,
message: msg,
duration: 2000
});
toast.present();
}
// 用alert弹出询问框
async ask(title: string, msg: string, btns: AlertButton[]) {
const alert = await this.alertCtrl.create({
header: title,
message: msg,
buttons: btns
});
await alert.present();
}
// 用底部弹出询问框
async actSheet(btns: (ActionSheetButton | string)[]) {
const actSheet = await this.actionSheet.create({
buttons: btns
});
await actSheet.present();
}
// 遮罩层
private loader: HTMLIonLoadingElement = null;
// 遮罩层数量
private loaderNum = 0;
// 显示遮罩层
async loading(msg: string = '稍候...') {
// 原来没哟遮罩层,才打开遮罩层
if (this.loaderNum <= 0) {
this.loaderNum += 1;
this.loader = await this.loadingCtrl.create({
message: msg,
duration: 5000
});
await this.loader.present();
// 遮罩层已应关闭
if (this.loaderNum <= 0) {
this.dismissLoading();
}
} else {
this.loaderNum += 1;
}
}
// 关闭遮罩层
async dismissLoading() {
this.loaderNum = this.loaderNum <= 0 ? 0 : this.loaderNum - 1;
if (this.loader && this.loaderNum <= 0) {
this.loader.dismiss();
}
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { BasePage } from 'src/app/base/BasePage';
import { MonthSumListInfo } from 'src/model/report/MonthSumListInfo';
import { ReportAPI } from 'src/api/ReportAPI';
import { MonthSumReq } from 'src/model/report/MonthSumReq';
import { PopoverController } from '@ionic/angular';
import { MonthSumPopComponent } from 'src/app/components/month-sum-pop/month-sum-pop.component';
import { MonthSumPop } from 'src/model/report/MonthSumPop';
import { EnmShowInOutType } from 'src/model/enums/EnmShowInOutType';
import { EnmDataType } from 'src/model/enums/enmDataType';
import { Router } from '@angular/router';
@Component({
selector: 'app-month-sum-list',
templateUrl: './month-sum-list.page.html',
styleUrls: ['./month-sum-list.page.scss'],
})
export class MonthSumListPage extends BasePage implements OnInit {
//条件
req: MonthSumReq = new MonthSumReq();
//弹框筛选条件
reqPop: MonthSumPop = new MonthSumPop();
//列表
list: Array<MonthSumListInfo<string>>;
constructor(
private rptAPI: ReportAPI,
private router: Router,
private popCtrl: PopoverController) {
super();
}
ngOnInit() {
this.reqPop.isContainBorrowRepay = false;
this.reqPop.isShowInOutFilter = true;
this.reqPop.enmShowInOutType = EnmShowInOutType.All;
//初始化
this.initPage();
}
//查询
async search(showLoader: boolean = true): Promise<Array<MonthSumListInfo<string>>> {
//条件
this.req.isContainBorrowRepay = this.reqPop.isContainBorrowRepay;
//查询列表
const lstInfo = (await this.rptAPI.sumMonth(this.req, showLoader)).lstInfo;
return lstInfo;
}
//初始化
async initPage() {
//查询
this.list = await this.search();
}
//刷新
async doRefresh(event: any) {
//查询
this.list = await this.search(false);
//刷新完成
event.target.complete();
}
//显示筛选弹框
async shouPop(event: Event) {
//筛选弹框
const popover = await this.popCtrl.create({
component: MonthSumPopComponent,
event: event,
componentProps: { reqPop: this.reqPop }
});
//打开筛选弹框
await popover.present();
//筛选弹框返回
const retModal = await popover.onDidDismiss();
//如果是否包含借还条件有变化
if (this.req.isContainBorrowRepay != this.reqPop.isContainBorrowRepay) {
this.initPage();
}
if (retModal.data) {
this.reqPop = retModal.data as MonthSumPop;
this.initPage();
}
}
//是否显示记录
showRecord(item: MonthSumListInfo<string>): boolean {
switch (this.reqPop.enmShowInOutType) {
case EnmShowInOutType.In:
if (item.dataType != EnmDataType.In) {
return false;
}
break;
case EnmShowInOutType.Out:
if (item.dataType != EnmDataType.Out) {
return false;
}
break;
}
return true;
}
//跳转到统计指定月份收入页面
clickItem(item: MonthSumListInfo<string>) {
switch (item.dataType) {
case EnmDataType.In:
this.router.navigate(
['tabs/reportTab/monthInSumList'],
{ queryParams: { month: item.name + '-01', isContainBorrowRepay: this.reqPop.isContainBorrowRepay } });
break;
case EnmDataType.Out:
this.router.navigate(
['tabs/reportTab/monthOutSumList'],
{ queryParams: { month: item.name + '-01', isContainBorrowRepay: this.reqPop.isContainBorrowRepay } });
break;
}
}
}
<file_sep>import { Injectable } from '@angular/core';
import { API } from './API';
import { ResultInfo } from 'src/model/comm/ResultInfo';
import { UserTotalInfo } from 'src/model/report/UserTotalInfo';
import { ResultPageMonthAmountList } from 'src/model/comm/ResultPageMonthAmountList';
import { AccountTurnoverListInfo } from 'src/model/report/AccountTurnoverListInfo';
import { AccountTurnoverListReq } from 'src/model/report/AccountTurnoverListReq';
import { BorrowRepaySumReq } from 'src/model/report/BorrowRepaySumReq';
import { SumListInfo } from 'src/model/comm/SumListInfo';
import { ResultList } from 'src/model/comm/ResultList';
import { BorrowRepayRecordReq } from 'src/model/report/BorrowRepayRecordReq';
import { ResultPageList } from 'src/model/comm/ResultPageList';
import { BorrowRepayRecordListInfo } from 'src/model/report/BorrowRepayRecordListInfo';
import { MonthSumListInfo } from 'src/model/report/MonthSumListInfo';
import { MonthSumReq } from 'src/model/report/MonthSumReq';
import { InSumReq } from 'src/model/report/InSumReq';
import { InRecordReq } from 'src/model/report/InRecordReq';
import { ResultPageAmountList } from 'src/model/comm/ResultPageAmountList';
import { InRecordListInfo } from 'src/model/report/InRecordListInfo';
import { OutRecordReq } from 'src/model/report/OutRecordReq';
import { OutRecordListInfo } from 'src/model/report/OutRecordListInfo';
import { MonthOutSumReq } from 'src/model/report/MonthOutSumReq';
import { MonthOutCategorySumListInfo } from 'src/model/report/MonthOutCategorySumListInfo';
@Injectable()
export class ReportAPI {
//构造函数
constructor(private api: API) { }
//查询账户流水明细列表
async queryAccountTurnover(req: AccountTurnoverListReq, showLoader: boolean = true): Promise<ResultPageMonthAmountList<AccountTurnoverListInfo>> {
return await this.api.postReq<ResultPageMonthAmountList<AccountTurnoverListInfo>>(
'/api/Report/QueryAccountTurnover',
req,
showLoader
);
}
//查询借还明细列表
async queryBorrowRepayRecord(req: BorrowRepayRecordReq, showLoader: boolean = true): Promise<ResultPageList<BorrowRepayRecordListInfo>> {
return await this.api.postReq<ResultPageList<BorrowRepayRecordListInfo>>(
'/api/Report/QueryBorrowRepayRecord',
req,
showLoader
);
}
//查询收入明细列表
async queryInRecord(req: InRecordReq, showLoader: boolean = true): Promise<ResultPageAmountList<InRecordListInfo>> {
return await this.api.postReq<ResultPageAmountList<InRecordListInfo>>(
'/api/Report/QueryInRecord',
req,
showLoader
);
}
//查询支出明细列表
async queryOutRecord(req: OutRecordReq, showLoader: boolean = true): Promise<ResultPageAmountList<OutRecordListInfo>> {
return await this.api.postReq<ResultPageAmountList<OutRecordListInfo>>(
'/api/Report/QueryOutRecord',
req,
showLoader
);
}
//用户收支统计
async sumUserTotal(showLoader: boolean = true): Promise<ResultInfo<UserTotalInfo>> {
return await this.api.get<ResultInfo<UserTotalInfo>>(
'/api/Report/SumUserTotal',
null,
showLoader
);
}
//借还统计
async sumBorrowRepayTarget(req: BorrowRepaySumReq, showLoader: boolean = true): Promise<ResultList<SumListInfo<string>>> {
return await this.api.get<ResultList<SumListInfo<string>>>(
'/api/Report/SumBorrowRepayTarget',
req,
showLoader
);
}
//月份统计
async sumMonth(req: MonthSumReq, showLoader: boolean = true): Promise<ResultList<MonthSumListInfo<string>>> {
return await this.api.get<ResultList<MonthSumListInfo<string>>>(
'/api/Report/SumMonth',
req,
showLoader
);
}
//收入统计
async sumInCome(req: InSumReq, showLoader: boolean = true): Promise<ResultList<SumListInfo<string>>> {
return await this.api.get<ResultList<SumListInfo<string>>>(
'/api/Report/SumInCome',
req,
showLoader
);
}
//月份支出统计
async sumMonthOut(req: MonthOutSumReq, showLoader: boolean = true): Promise<ResultList<MonthOutCategorySumListInfo>> {
return await this.api.get<ResultList<MonthOutCategorySumListInfo>>(
'/api/Report/SumMonthOut',
req,
showLoader
);
}
}
<file_sep>import { PageBaseReq } from '../comm/PageBaseReq';
//收入明细查询条件
export class InRecordReq extends PageBaseReq {
startDate?: Date; //开始日期
endDate?: Date; //截止日期
lstInTypeID: Array<number>; //收入类型ID集合
lstAmountAccountID: Array<number>; //账户ID集合
remark: string; //备注(模糊匹配)
}
<file_sep>import { Component, OnInit, forwardRef, Input, Output, EventEmitter } from '@angular/core';
import { NG_VALUE_ACCESSOR, ControlValueAccessor } from '@angular/forms';
import { PickerMultiColOption } from 'src/model/comm/PickerColOption';
import { ComHelper } from 'src/helper/comHelper';
import { PickerColumn } from '@ionic/core';
import { PickerCol } from 'src/model/comm/PickerCol';
import { PickerController } from '@ionic/angular';
@Component({
selector: 'ion-tdb-picker-multi2',
templateUrl: './ion-tdb-picker-multi2.component.html',
styleUrls: ['./ion-tdb-picker-multi2.component.scss'],
providers: [
{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => IonTdbPickerMulti2Component),
multi: true
}
]
})
export class IonTdbPickerMulti2Component implements OnInit, ControlValueAccessor {
constructor(protected pickerCtrl: PickerController) { }
private onChange: any; //值改变事件
@Input() placeholder: string; //输入框提示信息
@Input() value: any; //传入值
@Input() options: Array<PickerMultiColOption> = new Array<PickerMultiColOption>(); //选项
@Output() ionCancel = new EventEmitter<PickerMultiColOption>(); //取消事件
@Output() ionDone = new EventEmitter<PickerMultiColOption>(); //选择事件
_text: string; //显示内容
writeValue(obj: any): void {
this.value = obj;
//刷新显示文本
this.refreshText();
}
registerOnChange(fn: any): void {
this.onChange = fn;
}
registerOnTouched(fn: any): void { }
setDisabledState?(isDisabled: boolean): void { }
ngOnInit() { }
//获取当前选中项(第二列选中的项)
getSelectedItem(): PickerMultiColOption {
let selectedItem = null; //当前选中项
if (this.value && this.options) {
this.options.forEach(col1 => {
col1.childs.forEach(col2 => {
if (this.value == col2.value) {
selectedItem = col2;
return selectedItem;
}
});
});
}
return selectedItem;
}
//获取当前选中索引(数组第一个值为第一列选中索引,第二个值为第二列选中索引)
getSelectedIndexs(): Array<number> {
let selIndexs = new Array<number>(); //当前选中索引
if (this.value && this.options) {
for (let index1 = 0; index1 < this.options.length; index1++) {
let col1Opt = this.options[index1];
for (let index2 = 0; index2 < col1Opt.childs.length; index2++) {
let col2Opt = col1Opt.childs[index2];
if (this.value == col2Opt.value) {
selIndexs.push(index1);
selIndexs.push(index2);
return selIndexs;
}
}
}
}
if (selIndexs.length == 0) {
selIndexs.push(0);
selIndexs.push(0);
}
return selIndexs;
}
//刷新显示文本
refreshText() {
//如果传入有值,显示对应文本
if (ComHelper.isEmptry(this.value) === false) {
let selectedItem = this.getSelectedItem();
if (selectedItem) {
this._text = selectedItem.text;
}
}
}
//生成显示的列
createColOptions(col1Index, col2Index): Array<PickerColumn> {
let arrCol = new Array<PickerColumn>();
//第一列
let col1 = new PickerCol();
col1.name = "col1";
col1.selectedIndex = col1Index;
arrCol.push(col1);
this.options.forEach(col1Opt => {
col1.options.push(JSON.parse(JSON.stringify(col1Opt)));
});
//第二列
let col2 = new PickerCol();
col2.name = "col2";
col2.selectedIndex = col2Index;
arrCol.push(col2);
let col1Opt = this.options[col1Index];
if (col1Opt) {
col1Opt.childs.forEach(col2Opt => {
col2.options.push(JSON.parse(JSON.stringify(col2Opt)));
});
}
return arrCol;
}
async open() {
//当前值对应选中的索引
let selIndexs = this.getSelectedIndexs();
//创建选择器
const picker = await this.pickerCtrl.create({
buttons: [
{
text: '取消',
role: 'cancel',
handler: val => {
let selectedItem = this.getSelectedItem();
this.ionCancel.emit(selectedItem);
}
},
{
text: '选择',
handler: val => {
this.value = val.col2.value;
this._text = val.col2.text;
if (this.onChange) {
this.onChange(this.value);
}
let selectedItem = this.getSelectedItem();
this.ionDone.emit(selectedItem);
}
}
],
columns: this.createColOptions(selIndexs[0], selIndexs[1])
});
//监听列改变事件
picker.addEventListener('ionPickerColChange', async (event: any) => {
const data = event.detail;
//只处理第一列
if (data.name != "col1") {
return;
}
//重新设置列配置
const columns = this.createColOptions(data.selectedIndex, 0);
//这里有个BUG,会重影,暂时延迟调第二次解决,但是体验不好!
picker.columns = JSON.parse(JSON.stringify(columns));
setTimeout(() => {
picker.columns = columns;
}, 100);
});
//显示选择器
await picker.present();
}
}
<file_sep>import { BaseInfo } from '../comm/BaseInfo';
//编号-名称 类
export class IDNameInfo extends BaseInfo {
id: number; //编号
name: string; //名称
}<file_sep>import { BaseReq } from './BaseReq';
//分页请求类 基类
export class PageBaseReq extends BaseReq {
pageNum: number; //获取页码
pageSize: number; //每页条数
sort: number; //排序
}
<file_sep>
//基页
export class BasePage {
constructor() { }
}<file_sep>//借还类型
//(1:借入;2:还入;3:借出;4:还出)
export enum EnmBorrowRepayType {
BorrowIn = 1, //借入
RepayIn = 2, //还入
BorrowOut = 3, //借出
RepayOut = 4 //还出
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { BasePage } from 'src/app/base/BasePage';
import { InComeListInfo } from 'src/model/inout/InComeListInfo';
import { InOutAPI } from 'src/api/InOutAPI';
import { MsgboxUtil } from 'src/helper/MsgboxUtil';
import { ModalController } from '@ionic/angular';
import { DateHelper } from 'src/helper/DateHelper';
import { InComeDetailPage } from '../in-come-detail/in-come-detail.page';
@Component({
selector: 'app-in-come-list',
templateUrl: './in-come-list.page.html',
styleUrls: ['./in-come-list.page.scss']
})
export class InComeListPage extends BasePage implements OnInit {
//日期条件
reqDate: string;
//列表
list: Array<InComeListInfo>;
constructor(
private inoutAPI: InOutAPI,
private msgBox: MsgboxUtil,
private modalCtrl: ModalController
) {
super();
}
//初始化
ngOnInit() {
this.reqDate = DateHelper.format(new Date());
//初始化
this.initPage();
}
//查询
async search(showLoader: boolean = true): Promise<Array<InComeListInfo>> {
//查询列表
const lstInfo = (await this.inoutAPI.queryInCome(this.reqDate, showLoader)).lstInfo;
return lstInfo;
}
//初始化
async initPage() {
//查询
this.list = await this.search();
}
//刷新
async doRefresh(event: any) {
//查询
this.list = await this.search(false);
//刷新完成
event.target.complete();
}
//前一天
toPreDate() {
let date = DateHelper.parse(this.reqDate);
date = DateHelper.addDay(date, -1);
this.reqDate = DateHelper.format(date);
this.onDateChanged();
}
//后一天
toNextDate() {
let date = DateHelper.parse(this.reqDate);
date = DateHelper.addDay(date, 1);
this.reqDate = DateHelper.format(date);
this.onDateChanged();
}
//日期改变事件
onDateChanged() {
if (!this.reqDate) {
this.reqDate = DateHelper.format(new Date());
}
this.initPage();
}
//计算总金额
totalAmount() {
let total = 0;
if (this.list) {
this.list.forEach(item => {
total += item.amount;
});
}
return total;
}
//打开详细页面
async openDetail(id: number) {
//详细页面
const modal = await this.modalCtrl.create({
component: InComeDetailPage,
componentProps: { id: id, date: this.reqDate, isView: false }
});
//打开详细页面
await modal.present();
//详细页面返回
const retModal = await modal.onDidDismiss();
if (retModal.data) {
this.initPage();
}
}
//删除
async removeItem(id: number) {
await this.msgBox.actSheet([
{
text: '删除',
role: 'destructive',
handler: () => {
this.inoutAPI.deleteInCome(id).then(result => {
if (result.isOK) {
this.initPage();
} else {
this.msgBox.infoDanger(result.msg);
}
});
}
},
{
text: '取消',
role: 'cancel'
}
]);
}
}
<file_sep>import { Component, OnInit, forwardRef } from '@angular/core';
import { NG_VALUE_ACCESSOR } from '@angular/forms';
import { IonTdbPickerMulti2Component } from '../ion-tdb-picker-multi2/ion-tdb-picker-multi2.component';
import { PickerController } from '@ionic/angular';
import { BasicStore } from 'src/store/BasicStore';
import { BasicAPI } from 'src/api/BasicAPI';
import { PickerAccMultiColOption } from 'src/model/comm/PickerColOption';
import { OutCategoryTypeListInfo } from 'src/model/basic/OutCategoryTypeListInfo';
@Component({
selector: 'out-type-picker',
templateUrl: './out-type-picker.component.html',
styleUrls: ['./out-type-picker.component.scss'],
providers: [
{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => OutTypePickerComponent),
multi: true
}
]
})
export class OutTypePickerComponent extends IonTdbPickerMulti2Component {
constructor(
protected pickerCtrl: PickerController,
private basicStore: BasicStore,
private basicAPI: BasicAPI
) {
super(pickerCtrl);
}
ngOnInit() {
//初始化选项
this.initOptions();
}
//初始化选项
async initOptions() {
let list = this.basicStore.getOutCategoryTypeList();
if (list == null) {
//查询列表
list = (await this.basicAPI.queryOutCategoryType(false)).lstInfo;
}
//循环分类,构建选项
list.forEach(outCategory => {
let outCategoryOpt = new PickerAccMultiColOption();
this.options.push(outCategoryOpt);
outCategoryOpt.text = outCategory.name;
outCategoryOpt.value = outCategory.id;
outCategoryOpt.disabled = !outCategory.isActive;
//循环类型,构建选项
outCategory.lstOutType.forEach(outType => {
let outTypeOpt = new PickerAccMultiColOption();
outTypeOpt.text = outType.name;
outTypeOpt.value = outType.id;
outTypeOpt.disabled = !outType.isActive;
outTypeOpt.amountAccountID = outType.amountAccountID;
outCategoryOpt.childs.push(outTypeOpt);
});
});
//刷新显示文本
this.refreshText();
}
}
<file_sep>import { ResultPageList } from './ResultPageList';
//带合计金额的分页结果
export class ResultPageAmountList<T> extends ResultPageList<T> {
totalAmount: number; //合计金额
}<file_sep>import { Injectable } from '@angular/core';
import axios from 'axios';
import { BaseReq } from 'src/model/comm/BaseReq';
import { BaseInfo } from 'src/model/comm/BaseInfo';
import { MsgboxUtil } from 'src/helper/MsgboxUtil';
import { AccountStore } from 'src/store/AccountStore';
import { Router } from '@angular/router';
import { DateHelper } from 'src/helper/DateHelper';
import { ConfigStore } from 'src/store/ConfigStore';
declare const require: any;
const qs = require('qs');
@Injectable()
export class API {
//构造函数
constructor(
private msgBox: MsgboxUtil,
private accStore: AccountStore,
private configStroe: ConfigStore,
private router: Router) {
//添加一个请求拦截器
axios.interceptors.request.use(
function (config) {
//请求参数
const params = config.method === 'post' ? config.data : config.params;
//显示等待框
if (params.showLoader) {
msgBox.loading();
}
//传入Token
const loginInfo = accStore.getLoginInfo();
if (loginInfo != null) {
// 判断是否存在Token,如果存在的话,则每个http header都加上Token
config.headers.Authorization = `${loginInfo.token}`;
}
//删除是否显示等待框的属性
delete params.showLoader;
return config;
},
function (error) {
//关闭等待框
msgBox.dismissLoading();
return Promise.reject(error);
}
);
// 添加一个响应拦截器
axios.interceptors.response.use(
function (response) {
//关闭等待框
msgBox.dismissLoading();
return response;
},
async function (error) {
//关闭等待框
msgBox.dismissLoading();
//如果是未授权错误,跳到登录页
if (error.response) {
switch (error.response.status) {
case 401:
//跳到登录页
router.navigate(['login']);
msgBox.infoDanger('登录超时,请重新登录');
return Promise.reject(error);
}
}
//跳到错误页
router.navigate(['error'], { queryParams: { errMsg: '请求出现异常(' + error + ')' } });
//弹框显示错误
// msgBox.infoDanger('请求出现异常(' + error + ')');
return Promise.reject(error);
}
);
}
//post请求
//url:请求地址
//params:请求参数
//showLoader:是否显示等待框
async postReq<T>(url: string, params: BaseReq = null, showLoader: boolean = true): Promise<T> {
if (params == null) {
params = new BaseReq();
}
params.showLoader = showLoader;
let apiBaseUrl = this.configStroe.getApiBaseUrl();
const res = await axios.post<T>(`${apiBaseUrl}${url}`, params);
return res.data;
}
//post请求
//url:请求地址
//params:请求参数
//showLoader:是否显示等待框
async postInfo<T>(url: string, params: BaseInfo, showLoader: boolean = true): Promise<T> {
if (params == null) {
params = new BaseInfo();
}
params.showLoader = showLoader;
let apiBaseUrl = this.configStroe.getApiBaseUrl();
const res = await axios.post<T>(`${apiBaseUrl}${url}`, params);
return res.data;
}
//get请求
//url:请求地址
//params:请求参数
//showLoader:是否显示等待框
async get<T>(url: string, params: BaseReq = null, showLoader: boolean = true): Promise<T> {
if (params == null) {
params = new BaseReq();
}
params.showLoader = showLoader;
let apiBaseUrl = this.configStroe.getApiBaseUrl();
const res = await axios.get(`${apiBaseUrl}${url}`, {
params: params,
// tslint:disable-next-line: no-shadowed-variable
paramsSerializer: function (params) {
return qs.stringify(
params,
{
arrayFormat: 'repeat',
serializeDate: (date) => {
//用moment处理日期比较方便,自己写格式化方法也可以
return DateHelper.format(date, 'yyyy-MM-dd hh:mm:ss');
}
});
}
});
return res.data;
}
}
<file_sep>//收入统计方式
//(1:类型;2:账户;3:月份;4:年度)
export enum EnmInGroupType {
InType = 1, //类型
AmountAccount = 2, //账户
Month = 3, //月份
Year = 4 //年度
}
<file_sep>import { SumListInfo } from '../comm/SumListInfo';
import { EnmDataType } from '../enums/enmDataType';
//月份统计结果
export class MonthSumListInfo<T> extends SumListInfo<T> {
dataType: EnmDataType; //数据类型
dataTypeName: string; //数据类型名称
}
<file_sep>//信息基类
export class BaseInfo {
showLoader: boolean; //是否显示加载中遮罩层
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { AmountAccountInfo } from 'src/model/basic/AmountAccountInfo';
import { ModalController, NavParams } from '@ionic/angular';
import { BasicAPI } from 'src/api/BasicAPI';
import { MsgboxUtil } from 'src/helper/MsgboxUtil';
import { isNumeric } from 'rxjs/util/isNumeric';
import { BasePage } from 'src/app/base/BasePage';
import { ComHelper } from 'src/helper/comHelper';
@Component({
selector: 'app-amount-account-detail',
templateUrl: './amount-account-detail.page.html',
styleUrls: ['./amount-account-detail.page.scss']
})
export class AmountAccountDetailPage extends BasePage implements OnInit {
//账户信息
item: AmountAccountInfo = new AmountAccountInfo();
constructor(
private modalCtrl: ModalController,
private navParams: NavParams,
private basicAPI: BasicAPI,
private msgBox: MsgboxUtil
) {
super();
}
ngOnInit() {
//传入的主键ID
const id = this.navParams.get('id');
//初始化页面
this.initPage(id);
}
//获取操作模式:添加/修改
getOpeModel() {
if (this.item.id > 0) {
return '修改';
}
return '添加';
}
//初始化页面
async initPage(id: number) {
//添加
if (id === 0) {
this.item.id = id;
this.item.isActive = true;
return;
}
//修改
try {
const ret = await this.basicAPI.getAmountAccount(id);
if (ret.isOK) {
this.item = ret.info;
}
} catch (err) {
//异常,销毁本页面
this.dismiss(false);
}
}
//检查输入是否合法
chkInput() {
if (ComHelper.isEmptry(this.item.name)) {
this.msgBox.infoDanger('请输入名称');
return false;
}
if (isNumeric(this.item.amount) === false) {
this.msgBox.infoDanger('请输入初始金额');
return false;
}
return true;
}
//保存
async save() {
if (this.chkInput() === false) {
return;
}
await this.msgBox.actSheet(
[
{
text: '保存',
role: 'destructive',
handler: () => {
this.basicAPI
.saveAmountAccount(this.item)
.then(result => {
if (result.isOK) {
this.dismiss(true);
} else {
this.msgBox.infoDanger(result.msg);
}
})
.catch(err => {
//异常,销毁本页面
this.dismiss(false);
});
}
},
{
text: '取消',
role: 'cancel'
}
]);
}
//销毁页面
dismiss(isSave: boolean) {
this.modalCtrl.dismiss(isSave);
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { BasePage } from 'src/app/base/BasePage';
import { AccountStore } from 'src/store/AccountStore';
import { UserTotalInfo } from 'src/model/report/UserTotalInfo';
import { ReportAPI } from 'src/api/ReportAPI';
import { MsgboxUtil } from 'src/helper/MsgboxUtil';
import { Router } from '@angular/router';
import { BasicStore } from 'src/store/BasicStore';
@Component({
selector: 'app-mine',
templateUrl: './mine.page.html',
styleUrls: ['./mine.page.scss']
})
export class MinePage extends BasePage implements OnInit {
//用户统计信息
info: UserTotalInfo;
// //是否使用手势密码
// isGesture = false;
//是否包含借还
isBR = false;
constructor(
private accStore: AccountStore,
private basStore: BasicStore,
private rptAPI: ReportAPI,
private msgBox: MsgboxUtil,
private router: Router) {
super();
}
ngOnInit() {
// //是否使用手势
// this.isGesture = this.accStore.getIsGesture();
//初始化
this.initPage();
}
//统计
async search(showLoader: boolean = true): Promise<UserTotalInfo> {
//统计
return (await this.rptAPI.sumUserTotal(showLoader)).info;
}
//初始化
async initPage() {
//查询
this.info = await this.search();
}
//刷新
async doRefresh(event: any) {
//查询
this.info = await this.search(false);
//刷新完成
event.target.complete();
}
//年收入
sumInYear(): number {
if (!this.info) {
return 0;
}
let amount = this.info.totalInCurYear;
if (this.isBR) {
amount += this.info.totalBRInCurYear;
}
return amount;
}
//年支出
sumOutYear(): number {
if (!this.info) {
return 0;
}
let amount = this.info.totalOutCurYear;
if (this.isBR) {
amount += this.info.totalBROutCurYear;
}
return amount;
}
//月收入
sumInMonth(): number {
if (!this.info) {
return 0;
}
let amount = this.info.totalInCurMonth;
if (this.isBR) {
amount += this.info.totalBRInCurMonth;
}
return amount;
}
//月支出
sumOutMonth(): number {
if (!this.info) {
return 0;
}
let amount = this.info.totalOutCurMonth;
if (this.isBR) {
amount += this.info.totalBROutCurMonth;
}
return amount;
}
//退出登录
async logOut() {
await this.msgBox.actSheet(
[
{
text: '退出',
role: 'destructive',
handler: () => {
//清空缓存
this.accStore.clear();
this.basStore.clear();
//跳到登录页
this.router.navigate(['login']);
}
},
{
text: '取消',
role: 'cancel'
}
]);
}
}
<file_sep>import { BaseListInfo } from '../comm/BaseListInfo';
//收入列表
export class InComeListInfo extends BaseListInfo {
id: number; //主键
inTypeName: string; //收入类型名称
amountAccountName: string; //账户名称
amount: number; //金额
}<file_sep>import { Component, OnInit } from '@angular/core';
import { ResultPageMonthAmountList } from 'src/model/comm/ResultPageMonthAmountList';
import { AccountTurnoverListInfo } from 'src/model/report/AccountTurnoverListInfo';
import { BasePage } from 'src/app/base/BasePage';
import { ModalController } from '@ionic/angular';
import { ReportAPI } from 'src/api/ReportAPI';
import { AccountTurnoverListReq } from 'src/model/report/AccountTurnoverListReq';
import { BorrowRepayDetailPage } from 'src/app/inout/borrow-repay-detail/borrow-repay-detail.page';
import { EnmDataType } from 'src/model/enums/enmDataType';
import { InComeDetailPage } from 'src/app/inout/in-come-detail/in-come-detail.page';
import { OutPutDetailPage } from 'src/app/inout/out-put-detail/out-put-detail.page';
import { TransferDetailPage } from 'src/app/inout/transfer-detail/transfer-detail.page';
import { DateHelper } from 'src/helper/DateHelper';
import { ComHelper } from 'src/helper/comHelper';
import { AccountTurnoverFilterPage } from '../account-turnover-filter/account-turnover-filter.page';
import { BasicAPI } from 'src/api/BasicAPI';
import { BasicStore } from 'src/store/BasicStore';
@Component({
selector: 'app-account-turnover-list',
templateUrl: './account-turnover-list.page.html',
styleUrls: ['./account-turnover-list.page.scss'],
})
export class AccountTurnoverListPage extends BasePage implements OnInit {
//条件
req: AccountTurnoverListReq = new AccountTurnoverListReq();
//是否还有更多数据
hasMore = true;
//列表
list = new Array<ResultPageMonthAmountList<AccountTurnoverListInfo>>();
constructor(
private rptAPI: ReportAPI,
private modalCtrl: ModalController,
private basicStore: BasicStore,
private basicAPI: BasicAPI
) {
super();
}
async ngOnInit() {
//账户列表
let lstAcc = this.basicStore.getAmountAccountList();
if (lstAcc == null) {
//查询列表
lstAcc = (await this.basicAPI.queryAmountAccount(false)).lstInfo;
}
//筛选账户条件
this.req.lstAmountAccountID = new Array<number>();
lstAcc.forEach(acc => {
this.req.lstAmountAccountID.push(acc.id);
});
//初始化
this.initPage();
}
//查询
async search(month: Date, showLoader: boolean = true): Promise<ResultPageMonthAmountList<AccountTurnoverListInfo>> {
//查询条件
this.req.month = month;
//查询列表
const result = await this.rptAPI.queryAccountTurnover(this.req, showLoader);
//是否还有更多数据
this.hasMore = result.hasPreMonth;
return result;
}
//初始化
async initPage() {
//查询
let result = await this.search(new Date());
//清空原来的数据,加入新数据
this.list.splice(0, this.list.length, result);
//是否需要加载更多
if (this.needLoadMore()) {
this.loadMore(true);
}
}
//刷新
async doRefresh(event: any) {
//查询
let result = await this.search(new Date(), false);
//清空原来的数据,加入新数据
this.list.splice(0, this.list.length, result);
//是否需要加载更多
if (this.needLoadMore()) {
this.loadMore(false);
}
//刷新完成
event.target.complete();
}
//打开详细页面
async openDetail(itemAcc: AccountTurnoverListInfo) {
let pageDetai = null;
switch (itemAcc.dataType) {
case EnmDataType.BorrowRepay:
pageDetai = BorrowRepayDetailPage;
break;
case EnmDataType.In:
pageDetai = InComeDetailPage;
break;
case EnmDataType.Out:
pageDetai = OutPutDetailPage;
break;
case EnmDataType.Transfer:
pageDetai = TransferDetailPage;
break;
}
//详细页面
const modal = await this.modalCtrl.create({
component: pageDetai,
componentProps: { id: itemAcc.id, date: itemAcc.date, isView: true }
});
//打开详细页面
await modal.present();
}
//是否需要加载更多
needLoadMore() {
//当前页面上的记录数
let count = 0;
for (let itemMonth of this.list) {
count += itemMonth.lstInfo.length;
}
//如果还有更多数据,并且当前页面数据没满一页,则需要加载更多
if (this.hasMore && count < ComHelper.PageSize) {
return true;
}
return false;
}
//上拉加载
async doInfinite(event) {
//加载更多
await this.loadMore(false);
event.target.complete();
}
//加载更多
async loadMore(showLoader: boolean) {
//查询前一个月数据
let reqMonth = DateHelper.addMonth(this.req.month, -1);
//查询
let result = await this.search(reqMonth, showLoader);
//在最后加入新数据
this.list.push(result);
//是否需要加载更多
if (this.needLoadMore()) {
this.loadMore(showLoader);
}
}
//打开账户筛选页面
async accountFilter() {
//筛选页面
const modal = await this.modalCtrl.create({
component: AccountTurnoverFilterPage,
componentProps: { lstSelectedAccID: this.req.lstAmountAccountID }
});
//打开筛选页面
await modal.present();
//筛选页面返回
const retModal = await modal.onDidDismiss();
if (retModal.data) {
this.req.lstAmountAccountID = retModal.data;
this.initPage();
}
}
}
<file_sep>import { BaseListInfo } from '../comm/BaseListInfo';
//收入类型列表
export class InTypeListInfo extends BaseListInfo {
id: number; //主键
name: string; //名称
amountAccountID: number; //默认账户
isActive: boolean; //是否可用
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { LoginReq } from 'src/model/account/LoginReq';
import { AccountAPI } from 'src/api/AccountAPI';
import { CryptoHelper } from 'src/helper/CryptoHelper';
import { MsgboxUtil } from 'src/helper/MsgboxUtil';
import { AccountStore } from 'src/store/AccountStore';
import { ComHelper } from 'src/helper/comHelper';
import { AlertController } from '@ionic/angular';
import { ConfigStore } from 'src/store/ConfigStore';
@Component({
selector: 'app-login',
templateUrl: './login.page.html',
styleUrls: ['./login.page.scss']
})
export class LoginPage implements OnInit {
req: LoginReq = new LoginReq(); //登录条件
isSavePwd = false; //是否保存密码
constructor(
private router: Router,
private accountAPI: AccountAPI,
private msgBox: MsgboxUtil,
private accStore: AccountStore,
private alertCtrl: AlertController,
private configStroe: ConfigStore
) { }
ngOnInit() {
//如果之前保存了密码,设置账户密码
const preReq = this.accStore.getLoginReq();
if (preReq != null) {
this.isSavePwd = true;
this.req.loginName = preReq.loginName;
this.req.password = preReq.password;
} else {
this.isSavePwd = false;
this.req.loginName = '';
this.req.password = '';
}
}
//登录
async logIn() {
//验证
if (this.checkInput() === false) {
return false;
}
//登录条件加密
const reqLogin = new LoginReq();
reqLogin.loginName = this.req.loginName;
reqLogin.password = <PASSWORD>Helper.encryptAES(this.req.password);
//请求登录接口
const res = await this.accountAPI.login(reqLogin);
if (res.isOK) {
//登录成功
//设置登录信息
this.accStore.setLoginInfo(res.info);
//保存密码
if (this.isSavePwd) {
this.accStore.setLoginReq(this.req);
}
//跳转到tabs页
this.router.navigate(['']);
} else {
//登录失败
this.msgBox.infoDanger(res.msg);
}
}
//验证
checkInput() {
if (ComHelper.isEmptry(this.req.loginName)) {
this.msgBox.infoDanger('请输入账号');
return false;
} else if (ComHelper.isEmptry(this.req.password)) {
this.msgBox.infoDanger('请输入密码');
return false;
}
return true;
}
//显示筛选弹框
async shouPop(event: Event) {
let apiBaseUrl = this.configStroe.getApiBaseUrl();
const alert = await this.alertCtrl.create({
header: '接口地址',
inputs: [
{
name: 'txtApiBaseUrl',
type: 'text',
placeholder: '请输入接口地址',
value: apiBaseUrl
}
],
buttons: [
{
text: '取消',
role: 'cancel',
cssClass: 'secondary'
}, {
text: '确定',
handler: (data) => {
this.configStroe.setApiBaseUrl(data.txtApiBaseUrl);
}
}, {
text: '恢复默认',
handler: (data) => {
this.configStroe.setApiBaseUrl(null);
}
}
]
});
await alert.present();
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { BasePage } from 'src/app/base/BasePage';
import { InTypeListInfo } from 'src/model/basic/InTypeListInfo';
import { BasicAPI } from 'src/api/BasicAPI';
import { MsgboxUtil } from 'src/helper/MsgboxUtil';
import { ModalController } from '@ionic/angular';
import { InTypeDetailPage } from '../in-type-detail/in-type-detail.page';
@Component({
selector: 'app-in-type-list',
templateUrl: './in-type-list.page.html',
styleUrls: ['./in-type-list.page.scss']
})
export class InTypeListPage extends BasePage implements OnInit {
//列表
list: Array<InTypeListInfo>;
constructor(
private basicAPI: BasicAPI,
private msgBox: MsgboxUtil,
private modalCtrl: ModalController
) {
super();
}
//初始化
ngOnInit() {
//初始化
this.initPage();
}
//查询
async search(showLoader: boolean = true): Promise<Array<InTypeListInfo>> {
//查询列表
const lstInfo = (await this.basicAPI.queryInType(showLoader)).lstInfo;
return lstInfo;
}
//初始化
async initPage() {
//查询
this.list = await this.search();
}
//刷新
async doRefresh(event: any) {
//查询
this.list = await this.search(false);
//刷新完成
event.target.complete();
}
//打开详细页面
async openDetail(id: number) {
//详细页面
const modal = await this.modalCtrl.create({
component: InTypeDetailPage,
componentProps: { id: id }
});
//打开详细页面
await modal.present();
//详细页面返回
const retModal = await modal.onDidDismiss();
if (retModal.data) {
this.initPage();
}
}
//删除
removeItem(id: number) {
this.msgBox.ask('删除确认', '(如果此类型已被使用,请不要删除!可以修改是否可用属性。)', [
{
text: '取消'
},
{
text: '删除',
handler: () => {
this.basicAPI.deleteInType(id).then(result => {
if (result.isOK) {
this.initPage();
} else {
this.msgBox.infoDanger(result.msg);
}
});
}
}
]);
}
}
<file_sep>import { OutCategoryListInfo } from './OutCategoryListInfo';
import { OutTypeListInfo } from './OutTypeListInfo';
//支出类型列表
export class OutCategoryTypeListInfo extends OutCategoryListInfo {
lstOutType: Array<OutTypeListInfo>; //支出类型列表
}<file_sep>import { BaseInfo } from '../comm/BaseInfo';
//转账信息
export class TransferInfo extends BaseInfo {
id: number; //主键
transferDate: Date; //转账日期
fromAmountAccountID: number; //源账户ID
toAmountAccountID: number; //目标账户ID
amount: number; //金额
remark: string; //备注
}<file_sep>import { BaseReq } from '../comm/BaseReq';
import { EnmBorrowRepayGroupType } from '../enums/EnmBorrowRepayGroupType';
//借还统计条件
export class BorrowRepaySumReq extends BaseReq {
groupType: EnmBorrowRepayGroupType; //统计类型
isShowZero: boolean; //是否显示已还清记录
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { MonthSumPop } from 'src/model/report/MonthSumPop';
import { NavParams } from '@ionic/angular';
@Component({
selector: 'app-month-sum-pop',
templateUrl: './month-sum-pop.component.html',
styleUrls: ['./month-sum-pop.component.scss'],
})
//收支统计页面弹框
export class MonthSumPopComponent implements OnInit {
//弹框筛选条件
req: MonthSumPop = new MonthSumPop();
constructor(
private navParams: NavParams
) { }
ngOnInit() {
//入参
this.req = this.navParams.get('reqPop') as MonthSumPop;
}
}
<file_sep>import { BaseReq } from './BaseReq';
//主键ID 作为请求条件
export class IDReq extends BaseReq {
id: number; //主键ID
}
<file_sep>import { BaseInfo } from '../comm/BaseInfo';
//用户总计信息
export class UserTotalInfo extends BaseInfo {
nickName: string; //昵称
familyName: string; //家庭名称
totalAmount: number; //总资产
year: number; //当前年份
totalInCurYear: number; //当前年总收入
totalOutCurYear: number; //当前年总支出
totalBRInCurYear: number; //当前年总借入/还入
totalBROutCurYear: number; //当前年总借出/还出
month: number; //当前月份
totalInCurMonth: number; //当前月总收入
totalOutCurMonth: number; //当前月总支出
totalBRInCurMonth: number; //当前月总借入/还入
totalBROutCurMonth: number; //当前月总借出/还出
}
<file_sep>import { PickerColumnOption } from '@ionic/core';
//选择框列配置
export class PickerColOption implements PickerColumnOption {
text: string;
value: any;
disabled?: boolean;
duration?: number;
transform?: string;
selected?: boolean;
}
//带默认账户的选择框列配置
export class PickerAccColOption extends PickerColOption {
amountAccountID: number; //账户ID
}
//联级选择框列配置
export class PickerMultiColOption extends PickerColOption {
childs: Array<PickerAccMultiColOption> = new Array<PickerAccMultiColOption>(); //子级
}
//带默认账户的联级选择框列配置
export class PickerAccMultiColOption extends PickerAccColOption {
childs: Array<PickerAccMultiColOption> = new Array<PickerAccMultiColOption>(); //子级
}<file_sep>import { BaseListInfo } from '../comm/BaseListInfo';
//借还列表
export class BorrowRepayListInfo extends BaseListInfo {
id: number; //主键
target: string; //对方名称
brTypeName: string; //借还类型名称
amountAccountName: string; //账户名称
amount: number; //金额
}<file_sep>import { BaseInfo } from '../comm/BaseInfo';
//支出分类
export class OutCategoryInfo extends BaseInfo {
id: number; //主键
name: string; //名称
isActive: boolean; //是否可用
remark: boolean; //备注
}
<file_sep>import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { OutTypePickerComponent } from './out-type-picker.component';
describe('OutTypePickerComponent', () => {
let component: OutTypePickerComponent;
let fixture: ComponentFixture<OutTypePickerComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ OutTypePickerComponent ],
schemas: [CUSTOM_ELEMENTS_SCHEMA],
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(OutTypePickerComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
<file_sep>import { BaseListInfo } from '../comm/BaseListInfo';
//借还明细查询结果
export class BorrowRepayRecordListInfo extends BaseListInfo {
seq: number; //顺序
id: number; //主键
brDate: Date; //借还日期
target: string; //对方名称
brType: number; //借还类型
brTypeName: string; //借还类型名称
amountAccountName: string; //账户名称
amount: number; //金额
remark: string; //备注
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { OutCategoryInfo } from 'src/model/basic/OutCategoryInfo';
import { ModalController, NavParams } from '@ionic/angular';
import { BasicAPI } from 'src/api/BasicAPI';
import { MsgboxUtil } from 'src/helper/MsgboxUtil';
import { BasePage } from 'src/app/base/BasePage';
import { ComHelper } from 'src/helper/comHelper';
@Component({
selector: 'app-out-category-detail',
templateUrl: './out-category-detail.page.html',
styleUrls: ['./out-category-detail.page.scss'],
})
export class OutCategoryDetailPage extends BasePage implements OnInit {
//信息
item: OutCategoryInfo = new OutCategoryInfo();
constructor(
private modalCtrl: ModalController,
private navParams: NavParams,
private basicAPI: BasicAPI,
private msgBox: MsgboxUtil
) {
super();
}
ngOnInit() {
//传入的主键ID
const id = this.navParams.get('id');
//初始化页面
this.initPage(id);
}
//获取操作模式:添加/修改
getOpeModel() {
if (this.item.id > 0) {
return '修改';
}
return '添加';
}
//初始化页面
async initPage(id: number) {
//添加
if (id === 0) {
this.item.id = id;
this.item.isActive = true;
return;
}
//修改
try {
const ret = await this.basicAPI.getOutCategory(id);
if (ret.isOK) {
this.item = ret.info;
}
} catch (err) {
//异常,销毁本页面
this.dismiss(false);
}
}
//检查输入是否合法
chkInput() {
if (ComHelper.isEmptry(this.item.name)) {
this.msgBox.infoDanger('请输入名称');
return false;
}
return true;
}
//保存
async save() {
if (this.chkInput() === false) {
return;
}
await this.msgBox.actSheet(
[
{
text: '保存',
role: 'destructive',
handler: () => {
this.basicAPI
.saveOutCategory(this.item)
.then(result => {
if (result.isOK) {
this.dismiss(true);
} else {
this.msgBox.infoDanger(result.msg);
}
})
.catch(err => {
//异常,销毁本页面
this.dismiss(false);
});
}
},
{
text: '取消',
role: 'cancel'
}
]);
}
//销毁页面
dismiss(isSave: boolean) {
this.modalCtrl.dismiss(isSave);
}
}
<file_sep>import { BaseReq } from 'src/model/comm/BaseReq';
//登录参数
export class LoginReq extends BaseReq {
loginName:string;//登录名
password:string;//密码
}
<file_sep>import { ResultList } from './ResultList';
//月份合计金额的分页结果
export class ResultPageMonthAmountList<T> extends ResultList<T> {
month: Date; //月份
totalAmount: number; //合计金额
hasPreMonth: boolean; //是否还有前一个月的数据
}<file_sep>import { BaseListInfo } from '../comm/BaseListInfo';
import { EnmDataType } from '../enums/enmDataType';
//账号流水列表信息
export class AccountTurnoverListInfo extends BaseListInfo {
dataType: EnmDataType; //数据类型
id: number; //主键
date: Date; //日期
amountAccountName: string; //账户名称
typeName: string; //类型名称
amount: number; //金额
}<file_sep>import { BaseReq } from '../comm/BaseReq';
import { EnmInGroupType } from '../enums/EnmInGroupType';
//收入统计条件
export class InSumReq extends BaseReq {
startDate?: Date; //开始日期
endDate?: Date; //截止日期
groupType?: EnmInGroupType; //统计类型
isContainBorrowRepay?: boolean; //是否包含借还
}
<file_sep>import { BaseInfo } from '../comm/BaseInfo';
//支出信息
export class OutPutInfo extends BaseInfo {
id: number; //主键
outDate: Date; //支出日期
outTypeID: number; //支出类型ID
amountAccountID: number; //账户ID
amount: number; //金额
remark: string; //备注
}<file_sep>import { BaseListInfo } from '../comm/BaseListInfo';
//月份支出类型统计
export class MonthOutTypeSumListInfo extends BaseListInfo {
id: number; //支出类型ID
name: string; //支出类型名称
amount: number; //金额
}
<file_sep>import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { Routes, RouterModule } from '@angular/router';
import { IonicModule } from '@ionic/angular';
import { AccountTurnoverFilterPage } from './account-turnover-filter.page';
const routes: Routes = [
{
path: '',
component: AccountTurnoverFilterPage
}
];
@NgModule({
imports: [
CommonModule,
FormsModule,
IonicModule,
RouterModule.forChild(routes)
],
declarations: []
})
export class AccountTurnoverFilterPageModule {}
<file_sep>import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouteReuseStrategy } from '@angular/router';
import { IonicModule, IonicRouteStrategy } from '@ionic/angular';
import { SplashScreen } from '@ionic-native/splash-screen/ngx';
import { StatusBar } from '@ionic-native/status-bar/ngx';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { MsgboxUtil } from 'src/helper/MsgboxUtil';
import { AccountAPI } from '../api/AccountAPI';
import { API } from '../api/API';
import { AccountStore } from 'src/store/AccountStore';
import { Store } from 'src/store/Store';
import { BasicAPI } from 'src/api/BasicAPI';
import { BasicStore } from 'src/store/BasicStore';
import { FormsModule } from '@angular/forms';
import { InOutAPI } from 'src/api/InOutAPI';
import { ComponentsModule } from './components/components.module';
import { BorrowRepayDetailPage } from './inout/borrow-repay-detail/borrow-repay-detail.page';
import { InComeDetailPage } from './inout/in-come-detail/in-come-detail.page';
import { OutPutDetailPage } from './inout/out-put-detail/out-put-detail.page';
import { TransferDetailPage } from './inout/transfer-detail/transfer-detail.page';
import { ReportAPI } from 'src/api/ReportAPI';
import { AppUpdateUtil } from 'src/helper/AppUpdateUtil';
import { AppAPI } from 'src/api/AppAPI';
import { AppVersion } from '@ionic-native/app-version/ngx';
import { FileTransfer } from '@ionic-native/file-transfer/ngx';
import { File } from '@ionic-native/file/ngx';
import { FileOpener } from '@ionic-native/file-opener/ngx';
import { ConfigStore } from 'src/store/ConfigStore';
@NgModule({
declarations: [AppComponent, BorrowRepayDetailPage, InComeDetailPage, OutPutDetailPage, TransferDetailPage],
entryComponents: [BorrowRepayDetailPage, InComeDetailPage, OutPutDetailPage, TransferDetailPage],
imports: [
BrowserModule,
IonicModule.forRoot({
backButtonText: '',
mode: 'ios'
}),
AppRoutingModule,
FormsModule,
ComponentsModule
],
providers: [
StatusBar,
SplashScreen,
AppVersion,
FileTransfer,
File,
FileOpener,
{ provide: RouteReuseStrategy, useClass: IonicRouteStrategy },
MsgboxUtil,
API,
AccountAPI,
BasicAPI,
InOutAPI,
Store,
AccountStore,
BasicStore,
ConfigStore,
ReportAPI,
AppAPI,
AppUpdateUtil
],
bootstrap: [AppComponent]
})
export class AppModule { }
<file_sep>import { Component, OnInit } from '@angular/core';
import { BasePage } from 'src/app/base/BasePage';
import { EnmDataType } from 'src/model/enums/enmDataType';
import { ActivatedRoute, Params } from '@angular/router';
import { MonthInOutSumDetailListInfo } from 'src/model/report/MonthInOutSumDetailListInfo';
import { ReportAPI } from 'src/api/ReportAPI';
import { InRecordReq } from 'src/model/report/InRecordReq';
import { DateHelper } from 'src/helper/DateHelper';
import { OutRecordReq } from 'src/model/report/OutRecordReq';
import { BorrowRepayRecordReq } from 'src/model/report/BorrowRepayRecordReq';
import { ModalController } from '@ionic/angular';
import { InComeDetailPage } from 'src/app/inout/in-come-detail/in-come-detail.page';
import { OutPutDetailPage } from 'src/app/inout/out-put-detail/out-put-detail.page';
import { BorrowRepayDetailPage } from 'src/app/inout/borrow-repay-detail/borrow-repay-detail.page';
import { ArrayHelper, SortReq } from 'src/helper/ArrayHelper';
@Component({
selector: 'app-month-in-out-sum-detail-list',
templateUrl: './month-in-out-sum-detail-list.page.html',
styleUrls: ['./month-in-out-sum-detail-list.page.scss'],
})
export class MonthInOutSumDetailListPage extends BasePage implements OnInit {
reqMonth: Date; //月份
dataType: EnmDataType; //数据类型
groupID: number; //分组ID
groupName: string; //分组名
list: Array<MonthInOutSumDetailListInfo>; //列表
constructor(
private activeRoute: ActivatedRoute,
private modalCtrl: ModalController,
private rptAPI: ReportAPI
) {
super();
}
ngOnInit() {
this.activeRoute.queryParams.subscribe((params: Params) => {
this.reqMonth = DateHelper.parse(params.month) as Date;
this.dataType = Number(params.dataType) as EnmDataType;
this.groupID = Number(params.groupID);
this.groupName = params.groupName as string;
//初始化
this.initPage();
});
}
//查询
async search(showLoader: boolean = true): Promise<Array<MonthInOutSumDetailListInfo>> {
let lstRecord: Array<MonthInOutSumDetailListInfo>;
switch (this.dataType) {
case EnmDataType.In:
lstRecord = await this.queryInRecord(showLoader);
break;
case EnmDataType.Out:
lstRecord = await this.queryOutRecord(showLoader);
break;
case EnmDataType.BorrowRepay:
lstRecord = await this.queryBorrowRepayRecord(showLoader);
break;
default:
lstRecord = new Array<MonthInOutSumDetailListInfo>();
break;
}
//排序条件
const lstSortReq = new Array<SortReq>();
lstSortReq.push(new SortReq('date', false));
//排序
lstRecord = ArrayHelper.sortArrayObj(lstRecord, lstSortReq);
return lstRecord;
}
//查询收入明细列表
async queryInRecord(showLoader: boolean = true): Promise<Array<MonthInOutSumDetailListInfo>> {
//条件
let req = new InRecordReq();
req.startDate = DateHelper.getMonthStart(this.reqMonth);
req.endDate = DateHelper.getMonthEnd(this.reqMonth);
req.lstInTypeID = [this.groupID];
//查询列表
const lstInfo = (await this.rptAPI.queryInRecord(req, showLoader)).lstInfo;
let list = new Array<MonthInOutSumDetailListInfo>();
lstInfo.forEach(info => {
let item = new MonthInOutSumDetailListInfo();
list.push(item);
item.id = info.id;
item.date = info.inDate;
item.amountAccountName = info.amountAccountName;
item.amount = info.amount;
});
return list;
}
//查询支出明细列表
async queryOutRecord(showLoader: boolean = true): Promise<Array<MonthInOutSumDetailListInfo>> {
//条件
let req = new OutRecordReq();
req.startDate = DateHelper.getMonthStart(this.reqMonth);
req.endDate = DateHelper.getMonthEnd(this.reqMonth);
req.lstOutTypeID = [this.groupID];
//查询列表
const lstInfo = (await this.rptAPI.queryOutRecord(req, showLoader)).lstInfo;
let list = new Array<MonthInOutSumDetailListInfo>();
lstInfo.forEach(info => {
let item = new MonthInOutSumDetailListInfo();
list.push(item);
item.id = info.id;
item.date = info.outDate;
item.amountAccountName = info.amountAccountName;
item.amount = info.amount;
});
return list;
}
//查询借还明细列表
async queryBorrowRepayRecord(showLoader: boolean = true): Promise<Array<MonthInOutSumDetailListInfo>> {
//条件
let req = new BorrowRepayRecordReq();
req.startDate = DateHelper.getMonthStart(this.reqMonth);
req.endDate = DateHelper.getMonthEnd(this.reqMonth);
req.lstBRType = [this.groupID];
//查询列表
const lstInfo = (await this.rptAPI.queryBorrowRepayRecord(req, showLoader)).lstInfo;
let list = new Array<MonthInOutSumDetailListInfo>();
lstInfo.forEach(info => {
let item = new MonthInOutSumDetailListInfo();
list.push(item);
item.id = info.id;
item.date = info.brDate;
item.amountAccountName = info.amountAccountName;
item.amount = info.amount;
});
return list;
}
//初始化
async initPage() {
//查询
this.list = await this.search();
}
//刷新
async doRefresh(event: any) {
//查询
this.list = await this.search(false);
//刷新完成
event.target.complete();
}
//计算总金额
totalAmount(): number {
let total = 0;
if (this.list) {
this.list.forEach(item => {
total += item.amount;
});
}
return total;
}
//打开详细页面
async openDetail(item: MonthInOutSumDetailListInfo) {
switch (this.dataType) {
case EnmDataType.In:
this.openInComeDetail(item);
break;
case EnmDataType.Out:
this.openOutPutDetail(item);
break;
case EnmDataType.BorrowRepay:
this.openBorrowRepayDetail(item);
break;
}
}
//打开收入详细页面
async openInComeDetail(item: MonthInOutSumDetailListInfo) {
//详细页面
const modal = await this.modalCtrl.create({
component: InComeDetailPage,
componentProps: { id: item.id, date: item.date, isView: true }
});
//打开详细页面
await modal.present();
}
//打开支出详细页面
async openOutPutDetail(item: MonthInOutSumDetailListInfo) {
//详细页面
const modal = await this.modalCtrl.create({
component: OutPutDetailPage,
componentProps: { id: item.id, date: item.date, isView: true }
});
//打开详细页面
await modal.present();
}
//打开借还详细页面
async openBorrowRepayDetail(item: MonthInOutSumDetailListInfo) {
//详细页面
const modal = await this.modalCtrl.create({
component: BorrowRepayDetailPage,
componentProps: { id: item.id, date: item.date, isView: true }
});
//打开详细页面
await modal.present();
}
}
<file_sep>import * as crypto from 'crypto-js';
//加解密帮助类
export class CryptoHelper {
//IV
private static _AES_IV: string = 'tangdabinjiushiw';
//KEY
private static _AES_KEY:string = 'wodemingzijiaozuotangdabintangdb';
/**************************************************************
* 字符串加密
* str:需要加密的字符串
****************************************************************/
static encryptAES(str: string): string {
let key = crypto.enc.Utf8.parse(this._AES_KEY);
let iv = crypto.enc.Utf8.parse(this._AES_IV);
let srcs = crypto.enc.Utf8.parse(str);
let encrypted = crypto.AES.encrypt(srcs, key, {
iv: iv,
mode: crypto.mode.CBC,
padding: crypto.pad.Pkcs7
});
return encrypted.ciphertext.toString();
}
/**************************************************************
* 字符串解密
* str:需要解密的字符串
****************************************************************/
static decryptAES(str: string): string {
let key = crypto.enc.Utf8.parse(this._AES_KEY);
let iv = crypto.enc.Utf8.parse(this._AES_IV);
let encryptedHexStr = crypto.enc.Hex.parse(str);
let srcs = crypto.enc.Base64.stringify(encryptedHexStr);
let decrypt = crypto.AES.decrypt(srcs, key, {
iv: iv,
mode: crypto.mode.CBC,
padding: crypto.pad.Pkcs7
});
let decryptedStr = decrypt.toString(crypto.enc.Utf8);
return decryptedStr.toString();
}
}<file_sep>import { Component, OnInit } from '@angular/core';
import { BasePage } from 'src/app/base/BasePage';
import { InTypeInfo } from 'src/model/basic/InTypeInfo';
import { NavParams, ModalController } from '@ionic/angular';
import { BasicAPI } from 'src/api/BasicAPI';
import { MsgboxUtil } from 'src/helper/MsgboxUtil';
import { ComHelper } from 'src/helper/comHelper';
@Component({
selector: 'app-in-type-detail',
templateUrl: './in-type-detail.page.html',
styleUrls: ['./in-type-detail.page.scss']
})
export class InTypeDetailPage extends BasePage implements OnInit {
//收入类型
item: InTypeInfo = new InTypeInfo();
constructor(
private modalCtrl: ModalController,
private navParams: NavParams,
private basicAPI: BasicAPI,
private msgBox: MsgboxUtil
) {
super();
}
ngOnInit() {
//传入的主键ID
const id = this.navParams.get('id');
//初始化页面
this.initPage(id);
}
//获取操作模式:添加/修改
getOpeModel() {
if (this.item.id > 0) {
return '修改';
}
return '添加';
}
//初始化页面
async initPage(id: number) {
//添加
if (id === 0) {
this.item.id = id;
this.item.isActive = true;
return;
}
//修改
try {
const ret = await this.basicAPI.getInType(id);
if (ret.isOK) {
this.item = ret.info;
}
} catch (err) {
//异常,销毁本页面
this.dismiss(false);
}
}
//检查输入是否合法
chkInput() {
if (ComHelper.isEmptry(this.item.name)) {
this.msgBox.infoDanger('请输入名称');
return false;
}
if (ComHelper.isEmptry(this.item.amountAccountID) || this.item.amountAccountID <= 0) {
this.msgBox.infoDanger('请选择默认账户');
return false;
}
return true;
}
//保存
async save() {
if (this.chkInput() === false) {
return;
}
await this.msgBox.actSheet(
[
{
text: '保存',
role: 'destructive',
handler: () => {
this.basicAPI
.saveInType(this.item)
.then(result => {
if (result.isOK) {
this.dismiss(true);
} else {
this.msgBox.infoDanger(result.msg);
}
})
.catch(err => {
//异常,销毁本页面
this.dismiss(false);
});
}
},
{
text: '取消',
role: 'cancel'
}
]);
}
//销毁页面
dismiss(isSave: boolean) {
this.modalCtrl.dismiss(isSave);
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { BasePage } from 'src/app/base/BasePage';
import { ReportAPI } from 'src/api/ReportAPI';
import { ActivatedRoute, Params, Router } from '@angular/router';
import { SumListInfo } from 'src/model/comm/SumListInfo';
import { InSumReq } from 'src/model/report/InSumReq';
import { DateHelper } from 'src/helper/DateHelper';
import { EnmInGroupType } from 'src/model/enums/EnmInGroupType';
import { BasicStore } from 'src/store/BasicStore';
import { BasicAPI } from 'src/api/BasicAPI';
import { InTypeListInfo } from 'src/model/basic/InTypeListInfo';
import { EnmDataType } from 'src/model/enums/enmDataType';
import { IDNameInfo } from 'src/model/comm/IDNameInfo';
@Component({
selector: 'app-month-in-sum-list',
templateUrl: './month-in-sum-list.page.html',
styleUrls: ['./month-in-sum-list.page.scss'],
})
export class MonthInSumListPage extends BasePage implements OnInit {
isContainBorrowRepay: boolean; //是否包含借还
reqMonth: Date; //月份
list: Array<SumListInfo<string>>; //列表
constructor(
private activeRoute: ActivatedRoute,
private router: Router,
private rptAPI: ReportAPI,
private basicAPI: BasicAPI,
private basicStore: BasicStore,
) {
super();
}
ngOnInit() {
this.activeRoute.queryParams.subscribe((params: Params) => {
this.reqMonth = DateHelper.parse(params.month);
this.isContainBorrowRepay = params.isContainBorrowRepay;
//初始化
this.initPage();
});
}
//查询
async search(showLoader: boolean = true): Promise<Array<SumListInfo<string>>> {
//条件
let req = new InSumReq();
req.startDate = DateHelper.getMonthStart(this.reqMonth);
req.endDate = DateHelper.getMonthEnd(this.reqMonth);
req.groupType = EnmInGroupType.InType;
req.isContainBorrowRepay = this.isContainBorrowRepay;
//查询列表
const lstInfo = (await this.rptAPI.sumInCome(req, showLoader)).lstInfo;
return lstInfo;
}
//初始化
async initPage() {
//查询
this.list = await this.search();
}
//刷新
async doRefresh(event: any) {
//查询
this.list = await this.search(false);
//刷新完成
event.target.complete();
}
//计算总金额
totalAmount(): number {
let total = 0;
if (this.list) {
this.list.forEach(item => {
total += item.value;
});
}
return total;
}
//跳转到收支统计明细页面
async clickItem(item: SumListInfo<string>) {
let dataType: EnmDataType = null; //数据类型
let groupID: number = -1; //分组ID:收入类型ID/借还类型ID
//获取收入类型
let lstInType = await this.queryInType();
lstInType.forEach(inType => {
if (item.name == inType.name) {
dataType = EnmDataType.In;
groupID = inType.id;
return false;
}
});
//没找到收入类型,看看是不是借还类型
if (dataType == null && this.isContainBorrowRepay) {
let lstBRType = await this.queryBorrowRepayType();
lstBRType.forEach(brType => {
if (item.name == brType.name) {
dataType = EnmDataType.BorrowRepay;
groupID = brType.id;
return false;
}
});
}
//如果既不是收入类型,也不是借还类型,说明是异常数据,不做处理
if (dataType == null) {
return;
}
this.router.navigate(
['tabs/reportTab/monthInOutSumDetailList'],
{ queryParams: { month: DateHelper.format(this.reqMonth), dataType: dataType, groupID: groupID, groupName: item.name } });
}
//获取收入类型
async queryInType(): Promise<Array<InTypeListInfo>> {
let list = this.basicStore.getInTypeList();
if (list == null) {
list = (await this.basicAPI.queryInType(false)).lstInfo;
}
return list;
}
//获取借还类型
async queryBorrowRepayType(): Promise<Array<IDNameInfo>> {
let list = this.basicStore.getBorrowRepayList();
if (list == null) {
list = (await this.basicAPI.queryBorrowRepayType()).lstInfo;
}
return list;
}
}
<file_sep>import { BaseListInfo } from '../comm/BaseListInfo';
//支出明细查询结果
export class OutRecordListInfo extends BaseListInfo {
seq: number; //顺序
id: number; //主键
outDate: Date; //支出日期
outCategoryName: string; //支出分类名称
outTypeName: string; //支出类型名称
amountAccountName: string; //账户名称
amount: number; //金额
remark: string; //备注
}
<file_sep>import { BaseListInfo } from '../comm/BaseListInfo';
//账户列表
export class AmountAccountListInfo extends BaseListInfo {
id: number; //主键
name: string; //名称
amount: number; //金额
isActive: boolean; //是否可用
}<file_sep>import { Injectable } from '@angular/core';
import { Platform, AlertController } from '@ionic/angular';
import { MsgboxUtil } from './MsgboxUtil';
import { AppAPI } from 'src/api/AppAPI';
import { AppVerInfo } from 'src/model/app/AppVerInfo';
import { AppVersion } from '@ionic-native/app-version/ngx';
import { FileTransfer, FileTransferObject } from '@ionic-native/file-transfer/ngx';
import { File } from '@ionic-native/file/ngx';
import { FileOpener } from '@ionic-native/file-opener/ngx';
import { ConfigStore } from 'src/store/ConfigStore';
// app更新相关功能
@Injectable()
export class AppUpdateUtil {
constructor(
private platform: Platform,
private appVer: AppVersion,
private transfer: FileTransfer,
private file: File,
private fileOpener: FileOpener,
private alertCtrl: AlertController,
private msgBox: MsgboxUtil,
private appAPI: AppAPI,
private configStroe: ConfigStore,
) { }
// 更新app
async doUpdate() {
// 当前只支持android
if (this.isAndroid() === false) {
return;
}
// 从api获取最新app版本信息
const newVerInfo = (await this.appAPI.getAppVer()).info;
// 当前版本号
const curVer = await this.getVersionNumber();
// 如果已是最新版本
if (newVerInfo.ver === curVer) {
return;
}
if (newVerInfo.isForce) {
this.msgBox.ask('升级提示', '发现新版本,请立即升级?', [
{
text: '确定',
handler: () => {
// 下载安装
this.downloadInstall(newVerInfo);
}
}
]);
} else {
this.msgBox.ask('升级提示', '发现新版本,是否立即升级?', [
{
text: '取消'
},
{
text: '确定',
handler: () => {
// 下载安装
this.downloadInstall(newVerInfo);
}
}
]);
}
}
// 下载安装
async downloadInstall(verInfo: AppVerInfo) {
const alert = await this.alertCtrl.create({
header: '下载进度:0%',
backdropDismiss: false,
buttons: ['后台下载']
});
await alert.present();
const fileTransfer: FileTransferObject = this.transfer.create();
const apk = this.file.externalRootDirectory + 'download/iosys.apk'; // apk保存的目录
// 下载
const downloadUrl = this.configStroe.getApiBaseUrl() + verInfo.path;
fileTransfer.download(downloadUrl, apk).then(() => {
this.fileOpener.open(apk, 'application/vnd.android.package-archive');
});
fileTransfer.onProgress((event: ProgressEvent) => {
const num = Math.floor(event.loaded / event.total * 100);
if (num === 100) {
alert.dismiss();
} else {
const title = document.getElementsByClassName('alert-title')[0];
title && (title.innerHTML = '下载进度:' + num + '%');
}
});
}
/**
* 是否真机环境
*/
isMobile(): boolean {
return this.platform.is('mobile') && !this.platform.is('mobileweb');
}
/**
* 是否android真机环境
*/
isAndroid(): boolean {
return this.isMobile() && this.platform.is('android');
}
/**
* 是否ios真机环境
*/
isIos(): boolean {
return this.isMobile() && (this.platform.is('ios') || this.platform.is('ipad') || this.platform.is('iphone'));
}
/**
* 获得app版本号,如0.01
*/
async getVersionNumber(): Promise<string> {
const verNum = await this.appVer.getVersionNumber();
return verNum;
// return '4.6.0';
}
}
<file_sep>import { Store } from './Store';
import { Injectable } from '@angular/core';
import { AmountAccountListInfo } from 'src/model/basic/AmountAccountListInfo';
import { InTypeListInfo } from 'src/model/basic/InTypeListInfo';
import { OutCategoryTypeListInfo } from 'src/model/basic/OutCategoryTypeListInfo';
import { IDNameInfo } from 'src/model/comm/IDNameInfo';
@Injectable()
export class BasicStore {
constructor(private store: Store) {}
//清空缓存
clear() {
this.setAmountAccountList(null);
this.setInTypeList(null);
this.setOutCategoryTypeList(null);
}
//保存账户列表信息
setAmountAccountList(list: Array<AmountAccountListInfo>) {
this.store.setSession('AmountAccountListInfo', list);
}
//获取账户列表信息
getAmountAccountList(): Array<AmountAccountListInfo> {
return this.store.getSession<Array<AmountAccountListInfo>>('AmountAccountListInfo');
}
//保存收入类型列表信息
setInTypeList(list: Array<InTypeListInfo>) {
this.store.setSession('InTypeListInfo', list);
}
//获取收入类型列表信息
getInTypeList(): Array<InTypeListInfo> {
return this.store.getSession<Array<InTypeListInfo>>('InTypeListInfo');
}
//保存支出分类/类型列表信息
setOutCategoryTypeList(list: Array<OutCategoryTypeListInfo>) {
this.store.setSession('OutCategoryTypeListInfo', list);
}
//获取支出分类/类型列表信息
getOutCategoryTypeList(): Array<OutCategoryTypeListInfo> {
return this.store.getSession<Array<OutCategoryTypeListInfo>>('OutCategoryTypeListInfo');
}
//保存借还类型列表信息
setBorrowRepayList(list: Array<IDNameInfo>) {
this.store.setSession('BorrowRepayList', list);
}
//获取借还类型列表信息
getBorrowRepayList(): Array<IDNameInfo> {
return this.store.getSession<Array<IDNameInfo>>('BorrowRepayList');
}
}
<file_sep>import { BaseInfo } from '../comm/BaseInfo';
// app版本信息
export class AppVerInfo extends BaseInfo {
ver: string; // 版本号
isForce: boolean; // 是否强制更新
path: string; // APP安装包路径
}
<file_sep>//月份收支统计明细信息
export class MonthInOutSumDetailListInfo {
id: number; //ID
date: Date; //日期
amountAccountName: string; //账户名称
amount: number; //金额
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { BasePage } from 'src/app/base/BasePage';
import { ActivatedRoute, Router, Params } from '@angular/router';
import { ReportAPI } from 'src/api/ReportAPI';
import { BasicAPI } from 'src/api/BasicAPI';
import { BasicStore } from 'src/store/BasicStore';
import { MonthOutCategorySumListInfo } from 'src/model/report/MonthOutCategorySumListInfo';
import { DateHelper } from 'src/helper/DateHelper';
import { MonthOutSumReq } from 'src/model/report/MonthOutSumReq';
import { MonthOutTypeSumListInfo } from 'src/model/report/MonthOutTypeSumListInfo';
@Component({
selector: 'app-month-out-sum-list',
templateUrl: './month-out-sum-list.page.html',
styleUrls: ['./month-out-sum-list.page.scss'],
})
export class MonthOutSumListPage extends BasePage implements OnInit {
isContainBorrowRepay: boolean; //是否包含借还
reqMonth: Date; //月份
list: Array<MonthOutCategorySumListInfo>; //列表
constructor(
private activeRoute: ActivatedRoute,
private router: Router,
private rptAPI: ReportAPI,
private basicAPI: BasicAPI,
private basicStore: BasicStore,
) {
super();
}
ngOnInit() {
this.activeRoute.queryParams.subscribe((params: Params) => {
this.reqMonth = DateHelper.parse(params.month);
this.isContainBorrowRepay = params.isContainBorrowRepay;
//初始化
this.initPage();
});
}
//查询
async search(showLoader: boolean = true): Promise<Array<MonthOutCategorySumListInfo>> {
//条件
let req = new MonthOutSumReq();
req.month = this.reqMonth;
req.isContainBorrowRepay = this.isContainBorrowRepay;
//查询列表
const lstInfo = (await this.rptAPI.sumMonthOut(req, showLoader)).lstInfo;
return lstInfo;
}
//初始化
async initPage() {
//查询
this.list = await this.search();
}
//刷新
async doRefresh(event: any) {
//查询
this.list = await this.search(false);
//刷新完成
event.target.complete();
}
//计算总金额
totalAmount(): number {
let total = 0;
if (this.list) {
this.list.forEach(item => {
total += item.amount;
});
}
return total;
}
//跳转到收支统计明细页面
async openDetail(itemOC: MonthOutCategorySumListInfo, itemOT: MonthOutTypeSumListInfo) {
this.router.navigate(
['tabs/reportTab/monthInOutSumDetailList'],
{
queryParams: {
month: DateHelper.format(this.reqMonth),
dataType: itemOC.dataType,
groupID: itemOT.id,
groupName: itemOT.name
}
});
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { BasePage } from 'src/app/base/BasePage';
import { ModalController, NavParams } from '@ionic/angular';
import { BasicStore } from 'src/store/BasicStore';
@Component({
selector: 'app-account-turnover-filter',
templateUrl: './account-turnover-filter.page.html',
styleUrls: ['./account-turnover-filter.page.scss'],
})
export class AccountTurnoverFilterPage extends BasePage implements OnInit {
//账户列表
lstAccount: Array<AccountFilterInfo>;
//是否全选
isSelectAll = true;
constructor(
private modalCtrl: ModalController,
private navParams: NavParams,
private basicStore: BasicStore) {
super();
}
ngOnInit() {
//初始化页面
this.initPage();
}
//初始化页面
async initPage() {
//账户列表
let list = this.basicStore.getAmountAccountList();
//入参
let lstParamsAccount = this.navParams.get('lstSelectedAccID') as Array<number>;
//筛选列表
this.lstAccount = new Array<AccountFilterInfo>();
list.forEach(item => {
let account = new AccountFilterInfo();
this.lstAccount.push(account);
account.id = item.id;
account.name = item.name;
if (lstParamsAccount.indexOf(account.id) > -1) {
account.checked = true;
}
});
}
//全选/全不选
selectAll() {
this.lstAccount.forEach(item => {
item.checked = this.isSelectAll;
});
}
//筛选
doFilter() {
let lstChecked = new Array<number>();
lstChecked.push(0); //如果一条也没选,让它查询不出数据
this.lstAccount.forEach(item => {
if (item.checked) {
lstChecked.push(item.id);
}
});
this.dismiss(lstChecked);
}
//销毁页面
dismiss(lstChecked: Array<number>) {
this.modalCtrl.dismiss(lstChecked);
}
}
//账户筛选信息
class AccountFilterInfo {
id: number; //主键ID
name: string; //账户名称
checked: boolean; //是否选中
}
<file_sep>//统计类型
//(0:对方;1:类型;2:账户;3:月份;4:年度;)
export enum EnmBorrowRepayGroupType {
Target = 0, //对方
BRType = 1, //类型
AmountAccount = 2, //账户
Month = 3, //月份
Year = 4 //年度
}
<file_sep>//数组帮助类
export class ArrayHelper {
//对象数组排序
//arrObj:对象数组
//lstSortReq:排序条件
static sortArrayObj<T>(arrObj: Array<T>, lstSortReq: Array<SortReq>): Array<T> {
if (!arrObj || !lstSortReq) {
return arrObj;
}
arrObj.sort((item1, item2) => {
//排序结果
let sortRet: number = 0;
//循环多个排序条件
for (let req of lstSortReq) {
let v1 = item1[req.fieldName];
let v2 = item2[req.fieldName];
//因子
let factor = req.asc ? 1 : -1;
if (v1 > v2) {
sortRet = factor;
break; //结束内部循环
} else if (v1 < v2) {
sortRet = -factor;
break; //结束内部循环
}
}
return sortRet;
});
return arrObj;
}
}
//排序条件
export class SortReq {
constructor(fieldName: string, asc: boolean) {
this.fieldName = fieldName;
this.asc = asc;
}
fieldName: string; //排序字段
asc: boolean; //是否升序
}
<file_sep>import { BaseListInfo } from '../comm/BaseListInfo';
//支出列表
export class OutPutListInfo extends BaseListInfo {
id: number; //主键
outCategoryName: string; //支出分类名称
outTypeName: string; //支出类型名称
amountAccountName: string; //账户名称
amount: number; //金额
}<file_sep>import { LoginReq } from 'src/model/account/LoginReq';
import { Store } from './Store';
import { LoginInfo } from 'src/model/account/LoginInfo';
import { Injectable } from '@angular/core';
@Injectable()
export class AccountStore {
constructor(private store: Store) {}
//清空缓存
clear() {
this.setLoginReq(null);
this.setLoginInfo(null);
}
//保存登录条件
setLoginReq(val: LoginReq) {
this.store.setLocal('LoginReq', val);
}
//获取登录条件
getLoginReq(): LoginReq {
return this.store.getLocal<LoginReq>('LoginReq');
}
// //保存是否使用手势
// setIsGesture(val: boolean) {
// this.store.setLocal('IsGesture', val);
// }
// //获取是否使用手势
// getIsGesture(): boolean {
// return this.store.getLocal<boolean>('IsGesture');
// }
//保存登录信息
setLoginInfo(val: LoginInfo) {
this.store.setSession('LoginInfo', val);
}
//获取登录信息
getLoginInfo(): LoginInfo {
return this.store.getSession<LoginInfo>('LoginInfo');
}
}
<file_sep>import { BaseInfo } from '../comm/BaseInfo';
//收入
export class InComeInfo extends BaseInfo {
id: number; //主键
inDate: Date; //收入日期
inTypeID: number; //收入类型ID
amountAccountID: number; //账户ID
amount: number; //金额
remark: string; //备注
}<file_sep>import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { IonicModule } from '@ionic/angular';
import { IonTdbPickerSingleComponent } from './ion-tdb-picker-single/ion-tdb-picker-single.component';
import { AmountAccountPickerComponent } from './amount-account-picker/amount-account-picker.component';
import { OutCategoryPickerComponent } from './out-category-picker/out-category-picker.component';
import { InTypePickerComponent } from './in-type-picker/in-type-picker.component';
import { BorrowRepayTypePickerComponent } from './borrow-repay-type-picker/borrow-repay-type-picker.component';
import { IonTdbPickerMulti2Component } from './ion-tdb-picker-multi2/ion-tdb-picker-multi2.component';
import { OutTypePickerComponent } from './out-type-picker/out-type-picker.component';
@NgModule({
declarations: [
IonTdbPickerSingleComponent,
IonTdbPickerMulti2Component,
AmountAccountPickerComponent,
InTypePickerComponent,
OutCategoryPickerComponent,
BorrowRepayTypePickerComponent,
OutTypePickerComponent],
imports: [
CommonModule,
IonicModule
],
exports: [
IonTdbPickerSingleComponent,
IonTdbPickerMulti2Component,
AmountAccountPickerComponent,
InTypePickerComponent,
OutCategoryPickerComponent,
BorrowRepayTypePickerComponent,
OutTypePickerComponent]
})
export class ComponentsModule { }
<file_sep>import { BaseInfo } from '../comm/BaseInfo';
//借还
export class BorrowRepayInfo extends BaseInfo {
id: number; //主键
brDate: Date; //借还日期
target: string; //对方名称
brType: number; //借还类型
amountAccountID: number; //账户ID
amount: number; //金额
remark: string; //备注
}<file_sep>import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { InTypeDetailPage } from './in-type-detail.page';
describe('InTypeDetailPage', () => {
let component: InTypeDetailPage;
let fixture: ComponentFixture<InTypeDetailPage>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ InTypeDetailPage ],
schemas: [CUSTOM_ELEMENTS_SCHEMA],
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(InTypeDetailPage);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
<file_sep>import { PageBaseReq } from '../comm/PageBaseReq';
//收入明细查询条件
export class OutRecordReq extends PageBaseReq {
startDate?: Date; //开始日期
endDate?: Date; //截止日期
lstOutTypeID: Array<number>; //支出类型ID集合
lstAmountAccountID: Array<number>; //账户ID集合
remark: string; //备注(模糊匹配)
}
<file_sep>import { BaseInfo } from 'src/model/comm/baseInfo';
//登录信息
export class LoginInfo extends BaseInfo {
nickName: string; //昵称
familyName: string; //家庭名称
token: string; //token
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { BasePage } from 'src/app/base/BasePage';
import { ActivatedRoute, Params } from '@angular/router';
import { ResultPageList } from 'src/model/comm/ResultPageList';
import { BorrowRepayRecordListInfo } from 'src/model/report/BorrowRepayRecordListInfo';
import { BorrowRepayRecordReq } from 'src/model/report/BorrowRepayRecordReq';
import { ReportAPI } from 'src/api/ReportAPI';
import { EnmBorrowRepayType } from 'src/model/enums/EnmBorrowRepayType';
import { ModalController } from '@ionic/angular';
import { BorrowRepayDetailPage } from 'src/app/inout/borrow-repay-detail/borrow-repay-detail.page';
@Component({
selector: 'app-borrow-repay-sum-detail-list',
templateUrl: './borrow-repay-sum-detail-list.page.html',
styleUrls: ['./borrow-repay-sum-detail-list.page.scss'],
})
export class BorrowRepaySumDetailListPage extends BasePage implements OnInit {
//借还者姓名
target: string;
//列表
list: Array<BorrowRepayRecordListInfo>;
constructor(
private activeRoute: ActivatedRoute,
private rptAPI: ReportAPI,
private modalCtrl: ModalController) {
super();
}
ngOnInit() {
this.activeRoute.params.subscribe((params: Params) => {
//获取参数
this.target = params.target;
//初始化
this.initPage();
});
}
//查询
async search(showLoader: boolean = true): Promise<Array<BorrowRepayRecordListInfo>> {
//条件
let req = new BorrowRepayRecordReq();
req.target = this.target;
//查询列表
const lstInfo = (await this.rptAPI.queryBorrowRepayRecord(req, showLoader)).lstInfo;
return lstInfo;
}
//初始化
async initPage() {
//查询
this.list = await this.search();
}
//刷新
async doRefresh(event: any) {
//查询
this.list = await this.search(false);
//刷新完成
event.target.complete();
}
//获取金额
getAmount(item: BorrowRepayRecordListInfo): number {
if (item.brType == EnmBorrowRepayType.BorrowIn || item.brType == EnmBorrowRepayType.RepayIn) {
return item.amount;
} else {
return -item.amount;
}
}
//计算总金额
totalAmount(): number {
let total = 0;
if (this.list) {
this.list.forEach(item => {
total += this.getAmount(item);
});
}
return total;
}
//打开详细页面
async openDetail(item: BorrowRepayRecordListInfo) {
//详细页面
const modal = await this.modalCtrl.create({
component: BorrowRepayDetailPage,
componentProps: { id: item.id, date: item.brDate, isView: true }
});
//打开详细页面
await modal.present();
}
}
<file_sep>import { EnmInGroupType } from '../enums/EnmInGroupType';
import { MonthSumReq } from './MonthSumReq';
//月份支出统计条件
export class MonthOutSumReq extends MonthSumReq {
month: Date; //月份
}
<file_sep># IOSysV4_Ionic4
基于Ionic4开发的家庭收支系统APP
# 系统演示
微博地址:[https://blog.csdn.net/dabintang](https://blog.csdn.net/dabintang/article/details/102490933)
[PC端](http://172.16.17.32:8002/)
[H5端](http://172.16.17.32:8001/)
用户名:user
密码:<PASSWORD>
## V4版本的系统主要由以下几个项目组成:
接口项目:https://github.com/dabintang/IOSysV4_NetCore
pc端web :https://github.com/dabintang/IOSysV4_WebVue
安卓app :即本项目
任务调度:https://github.com/dabintang/IOSysV4_Hangfire
## 技术栈
只列出主要的:ionic4
## 截图简介
(注:截图中数据皆为测试数据)
##### 登录

##### 收入录入

##### 收入

##### 支出

##### 转账

##### 借还

##### 收支报表

##### 账户流水

##### 借还统计

##### 借还详情

##### 收支统计

##### 支出统计

##### 收支明细

##### 基础设置

##### 收入类型

##### 支出类型

##### 账户

##### 我的

<file_sep>import { Injectable } from '@angular/core';
import { API } from 'src/api/API';
import { ResultList } from 'src/model/comm/ResultList';
import { InComeListInfo } from 'src/model/inout/InComeListInfo';
import { ResultInfo } from 'src/model/comm/ResultInfo';
import { InComeInfo } from 'src/model/inout/InComeInfo';
import { IDReq } from 'src/model/comm/IDReq';
import { TransferListInfo } from 'src/model/inout/TransferListInfo';
import { TransferInfo } from 'src/model/inout/TransferInfo';
import { BorrowRepayListInfo } from 'src/model/inout/BorrowRepayListInfo';
import { BorrowRepayInfo } from 'src/model/inout/BorrowRepayInfo';
import { OutPutListInfo } from 'src/model/inout/OutPutListInfo';
import { OutPutInfo } from 'src/model/inout/OutPutInfo';
@Injectable()
export class InOutAPI {
//构造函数
constructor(private api: API) {}
/********************** 收入 Start **********************/
//查询收入列表
async queryInCome(date: string, showLoader: boolean = true): Promise<ResultList<InComeListInfo>> {
const url = '/api/InOut/QueryInCome/' + date;
return await this.api.get<ResultList<InComeListInfo>>(url, null, showLoader);
}
//获取收入信息
async getInCome(id: number): Promise<ResultInfo<InComeInfo>> {
const url = '/api/InOut/GetInCome/' + id;
return await this.api.get<ResultInfo<InComeInfo>>(url, null, false);
}
//保存收入信息
async saveInCome(info: InComeInfo): Promise<ResultInfo<number>> {
const url = '/api/InOut/SaveInCome';
return await this.api.postInfo<ResultInfo<number>>(url, info, true);
}
//删除收入信息
async deleteInCome(id: number): Promise<ResultInfo<boolean>> {
const url = '/api/InOut/DeleteInCome';
const req: IDReq = new IDReq();
req.id = id;
return await this.api.postInfo<ResultInfo<boolean>>(url, req, true);
}
/********************** 收入 End **********************/
/********************** 支出 Start **********************/
//查询支出列表
async queryOutPut(date: string, showLoader: boolean = true): Promise<ResultList<OutPutListInfo>> {
const url = '/api/InOut/QueryOutPut/' + date;
return await this.api.get<ResultList<OutPutListInfo>>(url, null, showLoader);
}
//获取支出信息
async getOutPut(id: number): Promise<ResultInfo<OutPutInfo>> {
const url = '/api/InOut/GetOutPut/' + id;
return await this.api.get<ResultInfo<OutPutInfo>>(url, null, false);
}
//保存支出信息
async saveOutPut(info: OutPutInfo): Promise<ResultInfo<number>> {
const url = '/api/InOut/SaveOutPut';
return await this.api.postInfo<ResultInfo<number>>(url, info, true);
}
//删除支出信息
async deleteOutPut(id: number): Promise<ResultInfo<boolean>> {
const url = '/api/InOut/DeleteOutPut';
const req: IDReq = new IDReq();
req.id = id;
return await this.api.postInfo<ResultInfo<boolean>>(url, req, true);
}
/********************** 支出 End **********************/
/********************** 转账 Start **********************/
//查询转账列表
async queryTransfer(
date: string,
showLoader: boolean = true
): Promise<ResultList<TransferListInfo>> {
const url = '/api/InOut/QueryTransfer/' + date;
return await this.api.get<ResultList<TransferListInfo>>(url, null, showLoader);
}
//获取转账信息
async getTransfer(id: number): Promise<ResultInfo<TransferInfo>> {
const url = '/api/InOut/GetTransfer/' + id;
return await this.api.get<ResultInfo<TransferInfo>>(url, null, false);
}
//保存转账信息
async saveTransfer(info: TransferInfo): Promise<ResultInfo<number>> {
const url = '/api/InOut/SaveTransfer';
return await this.api.postInfo<ResultInfo<number>>(url, info, true);
}
//删除转账信息
async deleteTransfer(id: number): Promise<ResultInfo<boolean>> {
const url = '/api/InOut/DeleteTransfer';
const req: IDReq = new IDReq();
req.id = id;
return await this.api.postInfo<ResultInfo<boolean>>(url, req, true);
}
/********************** 转账 End **********************/
/********************** 借还 Start **********************/
//查询借还列表
async queryBorrowRepay(
date: string,
showLoader: boolean = true
): Promise<ResultList<BorrowRepayListInfo>> {
const url = '/api/InOut/QueryBorrowRepay/' + date;
return await this.api.get<ResultList<BorrowRepayListInfo>>(url, null, showLoader);
}
//获取借还信息
async getBorrowRepay(id: number): Promise<ResultInfo<BorrowRepayInfo>> {
const url = '/api/InOut/GetBorrowRepay/' + id;
return await this.api.get<ResultInfo<BorrowRepayInfo>>(url, null, false);
}
//保存借还信息
async saveBorrowRepay(info: BorrowRepayInfo): Promise<ResultInfo<number>> {
const url = '/api/InOut/SaveBorrowRepay';
return await this.api.postInfo<ResultInfo<number>>(url, info, true);
}
//删除借还信息
async deleteBorrowRepay(id: number): Promise<ResultInfo<boolean>> {
const url = '/api/InOut/DeleteBorrowRepay';
const req: IDReq = new IDReq();
req.id = id;
return await this.api.postInfo<ResultInfo<boolean>>(url, req, true);
}
/********************** 借还 End **********************/
}
<file_sep>//数据类型
export enum EnmDataType {
In = 1, //收入
Out = 2, //支出
Transfer = 3, //转账
BorrowRepay = 4 //借还
}
<file_sep>import { BaseListInfo } from '../comm/BaseListInfo';
//转账列表
export class TransferListInfo extends BaseListInfo {
id: number; //主键
fromAmountAccountName: string; //源账户名称
toAmountAccountName: string; //目标账户名称
amount: number; //金额
}<file_sep>import { BaseListInfo } from './BaseListInfo';
//统计结果
export class SumListInfo<T> extends BaseListInfo {
name: string; //分组名
value: number; //结果
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { SumListInfo } from 'src/model/comm/SumListInfo';
import { BasePage } from 'src/app/base/BasePage';
import { ReportAPI } from 'src/api/ReportAPI';
import { BorrowRepaySumReq } from 'src/model/report/BorrowRepaySumReq';
import { EnmBorrowRepayGroupType } from 'src/model/enums/EnmBorrowRepayGroupType';
@Component({
selector: 'app-borrow-repay-sum-list',
templateUrl: './borrow-repay-sum-list.page.html',
styleUrls: ['./borrow-repay-sum-list.page.scss'],
})
export class BorrowRepaySumListPage extends BasePage implements OnInit {
//列表
list: Array<SumListInfo<string>>;
constructor(
private rptAPI: ReportAPI
) {
super();
}
ngOnInit() {
//初始化
this.initPage();
}
//查询
async search(showLoader: boolean = true): Promise<Array<SumListInfo<string>>> {
//条件
let req = new BorrowRepaySumReq();
req.groupType = EnmBorrowRepayGroupType.Target;
req.isShowZero = false;
//查询列表
const lstInfo = (await this.rptAPI.sumBorrowRepayTarget(req, showLoader)).lstInfo;
return lstInfo;
}
//初始化
async initPage() {
//查询
this.list = await this.search();
}
//刷新
async doRefresh(event: any) {
//查询
this.list = await this.search(false);
//刷新完成
event.target.complete();
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { OutCategoryTypeListInfo } from 'src/model/basic/OutCategoryTypeListInfo';
import { BasicAPI } from 'src/api/BasicAPI';
import { MsgboxUtil } from 'src/helper/MsgboxUtil';
import { ModalController } from '@ionic/angular';
import { BasePage } from 'src/app/base/BasePage';
import { OutCategoryDetailPage } from '../out-category-detail/out-category-detail.page';
import { OutTypeDetailPage } from '../out-type-detail/out-type-detail.page';
@Component({
selector: 'app-out-type-list',
templateUrl: './out-type-list.page.html',
styleUrls: ['./out-type-list.page.scss'],
})
export class OutTypeListPage extends BasePage implements OnInit {
//列表
list: Array<OutCategoryTypeListInfo>;
constructor(
private basicAPI: BasicAPI,
private msgBox: MsgboxUtil,
private modalCtrl: ModalController
) {
super();
}
//初始化
ngOnInit() {
//初始化
this.initPage();
}
//查询
async search(showLoader: boolean = true): Promise<Array<OutCategoryTypeListInfo>> {
//查询列表
const lstInfo = (await this.basicAPI.queryOutCategoryType(showLoader)).lstInfo;
return lstInfo;
}
//初始化
async initPage() {
//查询
this.list = await this.search();
}
//刷新
async doRefresh(event: any) {
//查询
this.list = await this.search(false);
//刷新完成
event.target.complete();
}
//打开支出分类详细页面
async openOutCategoryDetail(id: number) {
//详细页面
const modal = await this.modalCtrl.create({
component: OutCategoryDetailPage,
componentProps: { id: id }
});
//打开详细页面
await modal.present();
//详细页面返回
const retModal = await modal.onDidDismiss();
if (retModal.data) {
this.initPage();
}
}
//删除分类
removeOutCategory(id: number) {
this.msgBox.ask('删除确认', '(如果此分类已被使用,请不要删除!可以修改是否可用属性。)', [
{
text: '取消'
},
{
text: '删除',
handler: () => {
this.basicAPI.deleteOutCategory(id).then(result => {
if (result.isOK) {
this.initPage();
} else {
this.msgBox.infoDanger(result.msg);
}
});
}
}
]);
}
//打开支出类型详细页面
async openOutTypeDetail(ocID: number, otID: number, event: any) {
if (event) {
//阻止事件冒泡
event.stopPropagation();
}
//详细页面
const modal = await this.modalCtrl.create({
component: OutTypeDetailPage,
componentProps: { ocID: ocID, otID: otID }
});
//打开详细页面
await modal.present();
//详细页面返回
const retModal = await modal.onDidDismiss();
if (retModal.data) {
this.initPage();
}
}
//删除类型
removeOutType(id: number) {
this.msgBox.ask('删除确认', '(如果此类型已被使用,请不要删除!可以修改是否可用属性。)', [
{
text: '取消'
},
{
text: '删除',
handler: () => {
this.basicAPI.deleteOutType(id).then(result => {
if (result.isOK) {
this.initPage();
} else {
this.msgBox.infoDanger(result.msg);
}
});
}
}
]);
}
}
<file_sep>import { BaseInfo } from '../comm/BaseInfo';
//账户
export class AmountAccountInfo extends BaseInfo {
id: number; //主键
name: string; //名称
amount: number; //金额
isActive: boolean; //是否可用
remark: boolean; //备注
}
<file_sep>import { EnmShowInOutType } from '../enums/EnmShowInOutType';
export class MonthSumPop {
isContainBorrowRepay: boolean; //是否包含借还
isShowInOutFilter: boolean; //是否显示收支筛选
enmShowInOutType: EnmShowInOutType; //收支显示类型
}
<file_sep>import { BaseListInfo } from '../comm/BaseListInfo';
//收入明细查询结果
export class InRecordListInfo extends BaseListInfo {
seq: number; //顺序
id: number; //主键
inDate: Date; //收入日期
inTypeName: string; //收入类型名称
amountAccountName: string; //账户名称
amount: number; //金额
remark: string; //备注
}
<file_sep>//请求基类
export class BaseReq {
showLoader: boolean; //是否显示加载中遮罩层
}
<file_sep>import { BaseInfo } from '../comm/BaseInfo';
//支出类型
export class OutTypeInfo extends BaseInfo {
id: number; //主键
outCategoryID: number; //支出分类ID
name: string; //名称
amountAccountID: number; //默认账户
isActive: boolean; //是否可用
remark: boolean; //备注
}
<file_sep>import { PickerColumn, PickerColumnOption } from '@ionic/core';
//picker列
export class PickerCol implements PickerColumn {
name: string;
align?: string;
selectedIndex?: number;
prevSelected?: number;
prefix?: string;
suffix?: string;
options: Array<PickerColumnOption> = new Array<PickerColumnOption>();
cssClass?: string | string[];
columnWidth?: string;
prefixWidth?: string;
suffixWidth?: string;
optionsWidth?: string;
refresh?: () => void;
}<file_sep>import { Injectable } from '@angular/core';
import { API } from './API';
import { AppVerInfo } from 'src/model/app/AppVerInfo';
import { ResultInfo } from 'src/model/comm/ResultInfo';
@Injectable()
export class AppAPI {
// 构造函数
constructor(private api: API) { }
// 获取最新app版本信息
async getAppVer(): Promise<ResultInfo<AppVerInfo>> {
return await this.api.get<ResultInfo<AppVerInfo>>(
'/api/App/GetAppVer',
null,
false
);
}
}
<file_sep>import { BaseReq } from '../comm/BaseReq';
//月份统计条件
export class MonthSumReq extends BaseReq {
isContainBorrowRepay: boolean; //是否包含借还
}
<file_sep>import { Component, OnInit, forwardRef } from '@angular/core';
import { NG_VALUE_ACCESSOR } from '@angular/forms';
import { IonTdbPickerSingleComponent } from '../ion-tdb-picker-single/ion-tdb-picker-single.component';
import { PickerController } from '@ionic/angular';
import { BasicStore } from 'src/store/BasicStore';
import { BasicAPI } from 'src/api/BasicAPI';
import { PickerAccColOption } from 'src/model/comm/PickerColOption';
@Component({
selector: 'in-type-picker',
templateUrl: './in-type-picker.component.html',
styleUrls: ['./in-type-picker.component.scss'],
providers: [{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => InTypePickerComponent),
multi: true
}]
})
export class InTypePickerComponent extends IonTdbPickerSingleComponent {
constructor(
protected pickerCtrl: PickerController,
private basicStore: BasicStore,
private basicAPI: BasicAPI
) {
super(pickerCtrl);
}
// tslint:disable-next-line: use-life-cycle-interface
ngOnInit() {
//初始化选项
this.initOptions();
}
//初始化选项
async initOptions() {
let list = this.basicStore.getInTypeList();
if (list == null) {
//查询列表
list = (await this.basicAPI.queryInType(false)).lstInfo;
}
//构建选项
list.forEach(item => {
let option = new PickerAccColOption();
option.text = item.name;
option.value = item.id;
option.disabled = !item.isActive;
option.amountAccountID = item.amountAccountID;
this.options.push(option);
});
//刷新显示文本
this.refreshText();
}
}
<file_sep>import { Injectable } from '@angular/core';
@Injectable()
export class Store {
constructor() {}
//写缓存localStorage
setLocal(key: string, value: any) {
if (value) {
value = JSON.stringify(value);
}
localStorage.setItem(key, value);
}
//读缓存localStorage
getLocal<T>(key: string): T {
let value: string = localStorage.getItem(key);
if (value && value !== 'undefined' && value !== 'null') {
return <T>JSON.parse(value);
}
return null;
}
//写缓存sessionStorage
setSession(key: string, value: any) {
if (value) {
value = JSON.stringify(value);
}
sessionStorage.setItem(key, value);
}
//读缓存sessionStorage
getSession<T>(key: string): T {
let value: string = sessionStorage.getItem(key);
if (value && value !== 'undefined' && value !== 'null') {
return <T>JSON.parse(value);
}
return null;
}
}
<file_sep>import { Component, OnInit, forwardRef } from '@angular/core';
import { NG_VALUE_ACCESSOR } from '@angular/forms';
import { IonTdbPickerSingleComponent } from '../ion-tdb-picker-single/ion-tdb-picker-single.component';
import { PickerController } from '@ionic/angular';
import { BasicStore } from 'src/store/BasicStore';
import { BasicAPI } from 'src/api/BasicAPI';
import { PickerColOption } from 'src/model/comm/PickerColOption';
@Component({
selector: 'out-category-picker',
templateUrl: './out-category-picker.component.html',
styleUrls: ['./out-category-picker.component.scss'],
providers: [{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => OutCategoryPickerComponent),
multi: true
}]
})
export class OutCategoryPickerComponent extends IonTdbPickerSingleComponent {
constructor(
protected pickerCtrl: PickerController,
private basicStore: BasicStore,
private basicAPI: BasicAPI
) {
super(pickerCtrl);
}
ngOnInit() {
//初始化选项
this.initOptions();
}
//初始化选项
async initOptions() {
let list = this.basicStore.getOutCategoryTypeList();
if (list == null) {
//查询列表
list = (await this.basicAPI.queryOutCategoryType(false)).lstInfo;
}
//构建选项
list.forEach(item => {
let option = new PickerColOption();
option.text = item.name;
option.value = item.id;
option.disabled = !item.isActive;
this.options.push(option);
});
//刷新显示文本
this.refreshText();
}
}
<file_sep>import { EnmBorrowRepayGroupType } from '../enums/EnmBorrowRepayGroupType';
import { PageBaseReq } from '../comm/PageBaseReq';
//借还统计条件
export class BorrowRepayRecordReq extends PageBaseReq {
startDate?: Date; //开始日期
endDate?: Date; //截止日期
target: string; //对方名称
lstBRType: Array<number>; //借还类型集合
lstAmountAccountID: Array<number>; //账户ID集合
remark: string; //备注(模糊匹配)
}<file_sep>import { Injectable } from '@angular/core';
import { API } from 'src/api/API';
import { LoginReq } from 'src/model/account/LoginReq';
import { LoginInfo } from 'src/model/account/LoginInfo';
import { ResultInfo } from 'src/model/comm/ResultInfo';
@Injectable()
export class AccountAPI {
//构造函数
constructor(private api: API) {
}
//登录
async login(req: LoginReq): Promise<ResultInfo<LoginInfo>> {
return await this.api.postReq<ResultInfo<LoginInfo>>("/api/Account/Login", req);
}
}<file_sep>import { Component, OnInit } from '@angular/core';
import { OutTypeInfo } from 'src/model/basic/OutTypeInfo';
import { BasePage } from 'src/app/base/BasePage';
import { ActionSheetController, ModalController, NavParams } from '@ionic/angular';
import { BasicAPI } from 'src/api/BasicAPI';
import { MsgboxUtil } from 'src/helper/MsgboxUtil';
import { ComHelper } from 'src/helper/comHelper';
@Component({
selector: 'app-out-type-detail',
templateUrl: './out-type-detail.page.html',
styleUrls: ['./out-type-detail.page.scss'],
})
export class OutTypeDetailPage extends BasePage implements OnInit {
//支出类型
item: OutTypeInfo = new OutTypeInfo();
constructor(
private actionSheet: ActionSheetController,
private modalCtrl: ModalController,
private navParams: NavParams,
private basicAPI: BasicAPI,
private msgBox: MsgboxUtil
) {
super();
}
ngOnInit() {
//传入的分类ID
const ocID = this.navParams.get('ocID');
//传入的类型ID
const otID = this.navParams.get('otID');
//初始化页面
this.initPage(ocID, otID);
}
//获取操作模式:添加/修改
getOpeModel() {
if (this.item.id > 0) {
return '修改';
}
return '添加';
}
//初始化页面
async initPage(ocID: number, otID: number) {
//添加
if (otID === 0) {
this.item.id = otID;
this.item.outCategoryID = ocID;
this.item.isActive = true;
return;
}
//修改
try {
const ret = await this.basicAPI.getOutType(otID);
if (ret.isOK) {
this.item = ret.info;
}
} catch (err) {
//异常,销毁本页面
this.dismiss(false);
}
}
//检查输入是否合法
chkInput() {
if (ComHelper.isEmptry(this.item.name)) {
this.msgBox.infoDanger('请输入名称');
return false;
}
if (ComHelper.isEmptry(this.item.outCategoryID) || this.item.outCategoryID <= 0) {
this.msgBox.infoDanger('请选择所属分类');
return false;
}
if (ComHelper.isEmptry(this.item.amountAccountID) || this.item.amountAccountID <= 0) {
this.msgBox.infoDanger('请选择默认账户');
return false;
}
return true;
}
//保存
async save() {
if (this.chkInput() === false) {
return;
}
await this.msgBox.actSheet(
[
{
text: '保存',
role: 'destructive',
handler: () => {
this.basicAPI
.saveOutType(this.item)
.then(result => {
if (result.isOK) {
this.dismiss(true);
} else {
this.msgBox.infoDanger(result.msg);
}
})
.catch(err => {
//异常,销毁本页面
this.dismiss(false);
});
}
},
{
text: '取消',
role: 'cancel'
}
]);
}
//销毁页面
dismiss(isSave: boolean) {
this.modalCtrl.dismiss(isSave);
}
}
<file_sep>import { Component, Input, EventEmitter, Output, OnInit, forwardRef } from '@angular/core';
import { PickerController } from '@ionic/angular';
import { PickerColumnOption } from '@ionic/core';
import { ComHelper } from 'src/helper/comHelper';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
@Component({
selector: 'ion-tdb-picker-single',
templateUrl: './ion-tdb-picker-single.component.html',
styleUrls: ['./ion-tdb-picker-single.component.scss'],
providers: [
{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => IonTdbPickerSingleComponent),
multi: true
}
]
})
export class IonTdbPickerSingleComponent implements OnInit, ControlValueAccessor {
constructor(protected pickerCtrl: PickerController) { }
private onChange: any; //值改变事件
@Input() placeholder: string; //输入框提示信息
@Input() value: any; //传入值
@Input() options = new Array<PickerColumnOption>(); //选项
@Output() ionCancel = new EventEmitter<PickerColumnOption>(); //取消事件
@Output() ionDone = new EventEmitter<PickerColumnOption>(); //选择事件
_text: string; //显示内容
writeValue(obj: any): void {
this.value = obj;
//刷新显示文本
this.refreshText();
}
registerOnChange(fn: any): void {
this.onChange = fn;
}
registerOnTouched(fn: any): void { }
setDisabledState?(isDisabled: boolean): void { }
ngOnInit() { }
async open() {
//创建选择器
const picker = await this.pickerCtrl.create({
buttons: [
{
text: '取消',
role: 'cancel',
handler: val => {
let selectedItem = this.getSelectedItem();
this.ionCancel.emit(selectedItem);
}
},
{
text: '选择',
handler: val => {
this.value = val.data.value;
this._text = val.data.text;
if (this.onChange) {
this.onChange(this.value);
}
let selectedItem = this.getSelectedItem();
this.ionDone.emit(selectedItem);
}
}
],
columns: [
{
name: 'data',
options: JSON.parse(JSON.stringify(this.options)),
selectedIndex: this.getSelectedIndex()
}
]
});
//显示选择器
await picker.present();
}
//获取当前选中项索引
getSelectedIndex(): number {
let selectedIndex = 0;
if (this.value && this.options && this.options.length > 0) {
this.options.forEach((item, index) => {
if (this.value === item.value) {
selectedIndex = index;
return -1;
}
});
}
return selectedIndex;
}
//获取当前选中项
getSelectedItem(): PickerColumnOption {
let selectedItem = null; //当前选中项
if (this.value && this.options && this.options.length > 0) {
this.options.forEach((item, index) => {
if (this.value === item.value) {
selectedItem = item;
return -1;
}
});
}
return selectedItem;
}
//刷新显示文本
refreshText() {
//如果传入有值,显示对应文本
if (ComHelper.isEmptry(this.value) === false) {
let selectedItem = this.getSelectedItem();
if (selectedItem != null) {
this._text = selectedItem.text;
}
}
}
}
| 87b83872fcf8d6bfb325031a0423ac767355ee51 | [
"Markdown",
"TypeScript",
"HTML"
] | 110 | TypeScript | dabintang/IOSysV4_Ionic4 | 232040ca5ef51c95bb0166043f44d328b8402e6f | f33469d10a2d69469e0be8e87f4eb3907650c1f2 |
refs/heads/master | <repo_name>ValerieLoveland/codingbat<file_sep>/warmup-1/everyNth.java
/*
* Given a non-empty string and an int N, return the string made starting
* with char 0, and then every Nth char of the string. So if N is 3, use
* char 0, 3, 6, ... and so on. N is 1 or more.
*/
public String everyNth(String str, int n) {
String result = "";
for(int i=0;i<str.length();i=i+n){
result=result+str.charAt(i);
}return result;
}
<file_sep>/warmup-1/close10.java
/*
* Given 2 int values, return whichever value is nearest to the value 10,
* or return 0 in the event of a tie. Note that Math.abs(n) returns
* the absolute value of a number.
*/
public int close10(int a, int b) {
if (a==b){
return 0;
}
if(Math.abs(a-10) == Math.abs(b-10)){
return 0;
}
if(10 - Math.abs(a) > 10- Math.abs(b)){
return a;
}
if(10 - Math.abs(a) < 10 - Math.abs(b)){
return b;
}
else
return 0;
}
<file_sep>/warmup-1/mixStart.java
/*
* Return true if the given string begins with "mix", except the 'm'
* can be anything, so "pix", "9ix" .. all count.
*/
public boolean mixStart(String str) {
if (str.length()<=2){
return false;
}
if((str.charAt(1)=='i') && (str.charAt(2)=='x')){
return true;
}
else
return false;
}
<file_sep>/warmup-1/delDel.java
/*
* Given a string, if the string "del" appears starting at index 1, return a string
* where that "del" has been deleted. Otherwise, return the string unchanged.
*/
public String delDel(String str) {
if (str.length()<=2){
return str;
}
if ((str.charAt(1) == 'd') && (str.charAt(2) == 'e') && (str.charAt(3) == 'l')){
str= str.replace("del", "");
return str;
}
else{
return str;
}
}
<file_sep>/warmup-1/diff21.java
/*
* Given an int n, return the absolute difference between n and 21,
* except return double the absolute difference if n is over 21.
*/
public int diff21(int n) {
if (n<=21)
{return 21-n;}
if (n>21)
{return ((((21-n)*n))/(n)*-2) ;}
return n;
}
<file_sep>/warmup-2/countXX.java
/*
* Count the number of "xx" in the given string.
* We'll say that overlapping is allowed, so "xxx" contains 2 "xx".
*/
int countXX(String str) {
int count=0;
for(int i=0;i<str.length()-1;i++){
if(str.substring(i, i+2).equals("xx")){
count++;
}
}
return count;
}
<file_sep>/warmup-1/lastDigit.java
/*
* Given two non-negative int values, return true if they have the same last digit,
* such as with 27 and 57. Note that the % "mod" operator computes remainders,
* so 17 % 10 is 7.
*/
public boolean lastDigit(int a, int b) {
if(b>=110){
if ((a-100)%10==b){
return true;
}
}
if((a%10)==b){
return true;
}
if((b%10)==a){
return true;
}
else{
return false;
}
}
<file_sep>/warmup-2/frontTimes.java
/*
* Given a string and a non-negative int n, we'll say that the front of the string
* is the first 3 chars, or whatever is there if the string is less than length 3.
* Return n copies of the front;
*/
public String frontTimes(String str, int n) {
String smol="";
String result="";
if(n==0){
return "";
}
if (str.length()<=2){
//String smol= str;
for (int i=0;i<n;i++){
smol=smol+str;
}
return smol;
}
str= str.substring(0,3);
for(int i=0;i<n; i++){
result=result+str;
}
return result;
}
<file_sep>/warmup-1/front22.java
/*
* Given a string, take the first 2 chars and return the string with the 2 chars added
* at both the front and back, so "kitten" yields"kikittenki". If the string length
* is less than 2, use whatever chars are there.
*/
public String front22(String str) {
if (str.length() <=2){
return str+str+str;
}else {
String head = str.substring(0,2);
return head+str+head;
}
}
| acef26b7a86b53c3454413aa76ceeba10e89d808 | [
"Java"
] | 9 | Java | ValerieLoveland/codingbat | 1abadb47dc5671367f986e8d1bf65169f04e64db | d7e4399b5e76565a788a22d77b492fb0566a4b39 |
refs/heads/master | <file_sep><?php
if((isset($_POST['name'])&&$_POST['name']!="")&&(isset($_POST['tel'])&&$_POST['tel']!="")&&(empty($_POST['spam_hidden']))){
$to = '<EMAIL>';
$subject = 'Обратный звонок';
if(isset($_POST['comment'])&&!empty($_POST['comment'])){
$msg = $_POST['comment'];
}else{
$msg = '';
}
$message = '
<html>
<head>
<title>'.$subject.'</title>
</head>
<body>
<p>Имя: '.$_POST['name'].'</p>
<p>Телефон: '.$_POST['tel'].'</p>
<p>Сообщение: '.$msg.'</p>
</body>
</html>';
$headers = "Content-type: text/html; charset=utf-8 \r\n";
$headers .= "From: Отправитель <<EMAIL>>\r\n";
if(@mail($to, $subject, $message, $headers)){
echo 'true';
} else{
echo 'false';
}
}
?><file_sep>/* --------------------------------------------
MAIN FUNCTION
-------------------------------------------- */
$(document).ready(function() {
/* --------------------------------------------------------
ANIMATED PAGE ON REVEALED
----------------------------------------------------------- */
$(function($) {
"use strict";
$('.animated').appear(function() {
var elem = $(this);
var animation = elem.data('animation');
if ( !elem.hasClass('visible') ) {
var animationDelay = elem.data('animation-delay');
if ( animationDelay ) {
setTimeout(function(){
elem.addClass( animation + " visible" );
}, animationDelay);
} else {
elem.addClass( animation + " visible" );
}
}
});
});
/* --------------------------------------------
CLOSE COLLAPSE MENU ON MOBILE VIEW EXCEPT DROPDOWN
-------------------------------------------- */
$(function () {
"use strict";
$('.navbar-collapse ul li a:not(.dropdown-toggle)').on('click',function (event) {
$('.navbar-toggle:visible').click();
});
});
/* --------------------------------------------
STICKY SETTING
-------------------------------------------- */
$(function () {
"use strict";
if( $(".navbar-sticky").length > 0){
$(".navbar-sticky").sticky({ topSpacing: 0 });
$(".navbar-sticky").css('z-index','100');
$(".navbar-sticky").addClass('bg-light');
$(".navbar-sticky").addClass("top-nav-collapse");
};
});
/* --------------------------------------------------------
ANIMATED SCROLL PAGE WITH ACTIVE MENU - BOOTSTRAP SROLLSPY
----------------------------------------------------------- */
$(function(){
"use strict";
$("#opened ul li a, .navbar-op ul li a, .navbar-op a.navbar-brand, .intro-direction a, a.go-to-top").on('click', function(event) {
event.preventDefault();
var hash = this.hash;
$('html, body').animate({
scrollTop: $(hash).offset().top
}, 900, function(){
window.location.hash = hash;
});
var mq = window.matchMedia( "(min-width: 1200px)" );
if (mq.matches) {
}else{
$('#opened').hide();
$('#closed').show();
}
});
});
/* --------------------------------------------------------
NAVBAR FIXED TOP ON SCROLL
----------------------------------------------------------- */
$(function(){
"use strict";
var mq = window.matchMedia( "(min-width: 1200px)" );
if (mq.matches) {
if( $(".navbar-standart").length > 0 ){
$(".navbar-pasific").addClass("top-nav-collapse");
} else {
$(window).scroll(function() {
if ($(".navbar").offset().top > 10) {
$(".navbar-pasific").addClass("top-nav-collapse");
$('#logo_image').attr('src', 'assets/img/logo/logo-gray.png');
} else {
$(".navbar-pasific").removeClass("top-nav-collapse");
$('#logo_image').attr('src', 'assets/img/logo/logo-default.png');
}
});
};
} else {
$(window).scroll(function() {
if($('#closed').offset().top > 10){
$('#closed').css('background', '#fff');
$('#logo_image2').attr('src', 'assets/img/logo/logo-gray.png');
}else{
$('#closed').css('background', 'transparent');
$('#logo_image2').attr('src', 'assets/img/logo/logo-default.png');
}
});
}
});
$(function(){
$('.spec_but').click(function(){
var target = $(this).attr('data-nav');
$('.new_nav').hide();
$('#'+target).show();
});
});
/* --------------------------------------------------------
NAVBAR-INVERSE FIXED TOP ON SCROLL
----------------------------------------------------------- */
$(function(){
"use strict";
if( $(".navbar-pasific-inverse").length > 0 ){
$(window).scroll(function() {
if ($(".navbar").offset().top > 10) {
$(".navbar-pasific").addClass("top-nav-collapse-inverse");
} else {
$(".navbar-pasific").removeClass("top-nav-collapse-inverse");
}
});
};
});
/* --------------------------------------------------------
GO TO TOP SCROLL
----------------------------------------------------------- */
$(function(){
"use strict";
var mq = window.matchMedia( "(min-width: 1200px)" );
if(mq.matches){
if( $("a.go-to-top").length > 0 ){
$("a.go-to-top").fadeOut();
$(window).scroll(function() {
if ($(".navbar").offset().top > 1200) {
$("a.go-to-top").fadeIn();
} else {
$("a.go-to-top").fadeOut();
}
});
};
}
});
/* --------------------------------------------------------
BOOTSTRAP TOGGLE TOOLTIP
----------------------------------------------------------- */
$(function(){
"use strict";
$('[data-toggle="tooltip"]').tooltip();
});
/* --------------------------------------------------------
TEAM HOVER
----------------------------------------------------------- */
$(function () {
"use strict"
$('.team-seven').hover(
function () {
var overlay = $(this).find('.team-seven-overlay');
overlay.removeClass(overlay.data('return')).addClass(overlay.data('hover'));
},
function () {
var overlay = $(this).find('.team-seven-overlay');
overlay.removeClass(overlay.data('hover')).addClass(overlay.data('return'));
}
);
});
/* --------------------------------------------------------
COUNT TO
----------------------------------------------------------- */
$(function() {
"use strict";
$(".fact-number").appear(function(){
var dataperc = $(this).attr('data-perc');
$(this).each(function(){
$(this).find('.factor').delay(6000).countTo({
from: 10,
to: dataperc,
speed: 3000,
refreshInterval: 50,
});
});
});
});
/* --------------------------------------------------------
JQUERY TYPED
----------------------------------------------------------- */
$(function(){
"use strict";
if($("#typed").length > 0 ) {
$("#typed").typed({
stringsElement: $('#typed-strings'),
startDelay: 2000,
typeSpeed: 50,
backDelay: 500,
loop: true,
contentType: 'html',
loopCount: false,
});
};
});
/* --------------------------------------------------------
JQUERY TYPED#2
----------------------------------------------------------- */
$(function(){
"use strict";
if($("#typed-2").length > 0 ) {
$("#typed-2").typed({
stringsElement: $('#typed-strings-2'),
startDelay: 100,
typeSpeed: 50,
backDelay: 500,
loop: false,
contentType: 'html',
});
};
});
/* --------------------------------------------------------
JQUERY TEXTILLATE
----------------------------------------------------------- */
$(function(){
"use strict";
if($(".tlt").length > 0 ) {
$('.tlt').textillate({
loop: true,
minDisplayTime: 5000,
out: {
effect: 'hinge',
delayScale: 1.5,
delay: 50,
sync: false,
shuffle: false,
reverse: false,
callback: function () {}
},
});
};
});
/* --------------------------------------------------------
JQUERY ROTATE
----------------------------------------------------------- */
$(function(){
"use strict";
if($(".rotate").length > 0 ) {
$(".rotate").textrotator({
animation: "fade",
separator: ",",
speed: 2000
});
};
});
/* --------------------------------------------------------
SHOP RANGE SLIDER
----------------------------------------------------------- */
$(function() {
"use strict";
if($("#shop-range-price").length > 0 ) {
var $rangePrice = $("#shop-range-price");
$rangePrice.ionRangeSlider({
type: "double",
grid: true,
min: 0,
max: 250,
from: 45,
to: 200,
prefix: "$"
});
};
});
/* --------------------------------------------------------
BG YOUTUBE VIDEO
----------------------------------------------------------- */
$(function() {
"use strict";
if ( $( ".mb-ytplayer" ).length > 0 ) {
$(".mb-ytplayer").mb_YTPlayer();
}
});
/* --------------------------------------------------------
YOUTUBE VIDEO POPUP
----------------------------------------------------------- */
$(function() {
"use strict";
if ( $( ".popup-youtube" ).length > 0 ) {
$('.popup-youtube').magnificPopup({
disableOn: 700,
type: 'iframe',
mainClass: 'mfp-fade',
removalDelay: 160,
preloader: false,
fixedContentPos: false
});
};
});
}(jQuery));
$(window).load(function() {
/* --------------------------------------------
SECURITY CHECK HUMAN
-------------------------------------------- */
if($("#senderHuman").length > 0 ) {
var a = Math.ceil(Math.random() * 10) + 1;
var b = Math.ceil(Math.random() * 10) + 1;
document.getElementById("senderHuman").placeholder = a +" + "+ b +" = ?";
document.getElementById("checkHuman_a").value = a;
document.getElementById("checkHuman_b").value = b;
}
/* --------------------------------------------
CONTACT FORM
-------------------------------------------- */
var messageDelay = 2000;
$(init);
function init() {
$('#contactForm').show().submit( submitForm ).addClass( 'positioned' );
}
// Submit the form via Ajax
function submitForm() {
var contactForm = $(this);
// Are all the fields filled in?
if ( !$('#senderName').val() || !$('#senderEmail').val() || !$('#message').val() ) {
// No; display a warning message and return to the form
$('#incompleteMessage').fadeIn().delay(messageDelay).fadeOut();
contactForm.fadeOut().delay(messageDelay).fadeIn();
} else {
// Yes; submit the form to the PHP script via Ajax
$('#sendingMessage').fadeIn();
contactForm.show();
$.ajax( {
url: contactForm.attr( 'action' ) + "?ajax=true",
type: contactForm.attr( 'method' ),
data: contactForm.serialize(),
success: submitFinished
} );
}
// Prevent the default form submission occurring
return false;
}
// Handle the Ajax response
function submitFinished( response ) {
response = $.trim( response );
$('#sendingMessage').fadeOut();
if ( response == "success" ) {
// Form submitted successfully:
// 1. Display the success message
// 2. Clear the form fields
// 3. Fade the content back in
$('#successMessage').fadeIn().delay(messageDelay).fadeOut();
$('#senderName').val( "" );
$('#senderEmail').val( "" );
$('#message').val( "" );
$('#content').delay(messageDelay+500).fadeTo( 'slow', 1 );
} else {
// Form submission failed: Display the failure message,
// then redisplay the form
$('#failureMessage').fadeIn().delay(messageDelay).fadeOut();
$('#contactForm').delay(messageDelay+500).fadeIn();
}
}
$(function(){
$('#list-tabs li a').click(function(){
var filter = $(this).parent().attr('data-filter');
$('#list-tabs li').removeClass('active');
$('.hide-by-click').hide(400, 'swing');
$(this).parent().addClass('active');
var id = '#' + filter;
$(id).show(400, 'swing');
});
});
$(function(){
$('#contact2 a.dashed-href').click(function(e){
e.preventDefault();
var target = $(this).attr('data-city');
$('#contact2 a.dashed-href').removeClass('active');
$(this).addClass('active');
$('.city-row').hide();
$('.' + target).show();
});
});
$(function(){
$('#freeCall a').click(function(e){
e.preventDefault();
$('#freeCall .textarea_').show();
$('#freeCall .textarea_ textarea').focus();
$(this).hide();
});
});
$(function(){
$('#free_consult').submit(function(e){
e.preventDefault();
var data = $(this).serialize();
$.ajax({
type: 'POST',
data: data,
url: 'mail_sender.php',
success: successSubmit
});
});
});
function successSubmit( response ){
var res = $.trim(response);
if(res == 'true'){
$('#freeCall').modal('hide');
swal({
title: "Ваша сообщение усешно отправлено",
type: "success",
timer: 2000,
showConfirmButton: false
});
}else{
swal({
title: "Что-то пошло не так!",
type: "error",
timer: 2000,
showConfirmButton: false
});
}
}
}); | 48f78b5f6aebfbb0ed7b6e17537e031de86f189c | [
"JavaScript",
"PHP"
] | 2 | PHP | mainden7/Tess | c1c41f9ecff45b2c9fc327d1fb231c920232ad3c | d095e8962375426593f966703b4abe8ad25d0927 |
refs/heads/master | <file_sep>using System.Runtime.Serialization;
namespace GestaoClientes.Api.Models
{
[DataContract]
public class Cliente
{
[DataMember]
public int ID { get; set; }
[DataMember]
public string CPF { get; set; }
[DataMember]
public string Nome { get; set; }
[DataMember]
public int TipoID { get; set; }
[DataMember]
public char Sexo { get; set; }
[DataMember]
public int SituacaoID { get; set; }
}
}
<file_sep>using GestaoClientes.Web.ServiceReference1;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI.WebControls;
namespace GestaoClientes.Web.Cliente
{
public partial class Clientes : System.Web.UI.Page
{
ClienteServiceClient servico = new ClienteServiceClient();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
carregaDados();
}
}
private void carregaDados()
{
var listClientes = servico.GetClientes().ToList();
var listClienteTipo = servico.GetClienteTipos().ToList();
var listClientesSituacao = servico.GetClienteSituacoes().ToList();
List<dynamic> listTable = new List<dynamic>();
foreach (var cliente in listClientes)
{
listTable.Add(new
{
ID = cliente.ID,
Nome = cliente.Nome,
CPF = cliente.CPF,
Sexo = cliente.Sexo,
TipoLabel = listClienteTipo
.Where(t => t.ID == cliente.TipoID).FirstOrDefault().Descricao,
SituacaoLabel = listClientesSituacao
.Where(t => t.ID == cliente.SituacaoID).FirstOrDefault().Descricao
});
}
clienteRepeater.DataSource = listTable.ToList();
clienteRepeater.DataBind();
if (clienteRepeater.Items.Count < 1)
{
clienteRepeater.Visible = false;
phMensagem.Visible = true;
litMensagem.Text = "Nenhum cliente foi encontrado!";
}
else
{
clienteRepeater.Visible = true;
phMensagem.Visible = false;
}
}
protected void DelItem(object sender, CommandEventArgs e)
{
try
{
var cliente = servico.GetCliente(int.Parse(e.CommandArgument.ToString()));
if (cliente != null)
{
servico.DeleteCliente(cliente.ID);
Response.Redirect("Clientes.aspx");
}
}
catch (Exception ex)
{
phMensagem.Visible = true;
litMensagem.Text = "Ocorreu um erro ao executar a operação: " + ex.Message;
}
}
}
}<file_sep>using GestaoClientes.Api.Models;
using System.Collections.Generic;
namespace GestaoClientes.Api
{
public class ClienteService : IClienteService
{
List<Cliente> IClienteService.GetClientes()
{
ClienteDao dao = new ClienteDao();
return dao.GetClientes();
}
List<ClienteSituacao> IClienteService.GetClienteSituacoes()
{
ClienteDao dao = new ClienteDao();
return dao.GetClienteSituacoes();
}
List<ClienteTipo> IClienteService.GetClienteTipos()
{
ClienteDao dao = new ClienteDao();
return dao.GetClienteTipos();
}
void IClienteService.CreateCliente(Cliente cliente)
{
ClienteDao dao = new ClienteDao();
dao.Create(cliente);
}
Cliente IClienteService.GetCliente(int id)
{
ClienteDao dao = new ClienteDao();
return dao.GetCliente(id);
}
void IClienteService.UpdateCliente(Cliente cliente)
{
ClienteDao dao = new ClienteDao();
dao.Update(cliente);
}
void IClienteService.DeleteCliente(int id)
{
ClienteDao dao = new ClienteDao();
dao.Delete(id);
}
}
}
<file_sep>using Dapper;
using GestaoClientes.Api.Helpers;
using GestaoClientes.Api.Models;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
namespace GestaoClientes.Api
{
public class ClienteDao
{
private string connection = ConfigurationManager.ConnectionStrings["GestaoClientesConexao"].ConnectionString;
internal List<Cliente> GetClientes()
{
try
{
using (IDbConnection db = new SqlConnection(connection))
{
string readSp = "SP_ListCliente";
return db.Query<Cliente>(readSp, commandType: CommandType.StoredProcedure).ToList();
}
}
catch (Exception ex)
{
throw new Exception("Ocorreu um erro ao executar a operação: " + ex.Message);
}
}
internal List<ClienteSituacao> GetClienteSituacoes()
{
try
{
using (IDbConnection db = new SqlConnection(connection))
{
string readSp = "SP_ListSituacaoCliente";
return db.Query<ClienteSituacao>(readSp, commandType: CommandType.StoredProcedure).ToList();
}
}
catch (Exception ex)
{
throw new Exception("Ocorreu um erro ao executar a operação: " + ex.Message);
}
}
internal List<ClienteTipo> GetClienteTipos()
{
try
{
using (IDbConnection db = new SqlConnection(connection))
{
string readSp = "SP_ListTipoCliente";
return db.Query<ClienteTipo>(readSp, commandType: CommandType.StoredProcedure).ToList();
}
}
catch (Exception ex)
{
throw new Exception("Ocorreu um erro ao executar a operação: " + ex.Message);
}
}
internal void Create(Cliente cliente)
{
if (!CpfValidateHelper.IsValid(cliente.CPF))
{
throw new Exception("Cpf Inválido");
}
else if (GetClientes().Where(t => t.CPF == cliente.CPF).Any())
{
throw new Exception("Cpf já cadastrado no sistema.");
}
try
{
using (IDbConnection db = new SqlConnection(connection))
{
string readSp = "SP_IncCliente";
db.Execute(readSp, new
{
cliente.Nome,
cliente.CPF,
cliente.Sexo,
cliente.TipoID,
cliente.SituacaoID
}, commandType: CommandType.StoredProcedure);
}
}
catch (Exception ex)
{
throw new Exception("Ocorreu um erro ao executar a operação: " + ex.Message);
}
}
internal Cliente GetCliente(int id)
{
try
{
using (IDbConnection db = new SqlConnection(connection))
{
string readSp = "SP_ConsCliente";
return db.Query<Cliente>(readSp, new { id = id }, commandType: CommandType.StoredProcedure).FirstOrDefault();
}
}
catch (Exception ex)
{
throw new Exception("Ocorreu um erro ao executar a operação: " + ex.Message);
}
}
internal void Update(Cliente cliente)
{
if (!CpfValidateHelper.IsValid(cliente.CPF))
{
throw new Exception("Cpf Inválido");
}
else if (GetClientes().Where(t => t.CPF == cliente.CPF).Any())
{
if (GetClientes().Where(t => t.CPF == cliente.CPF).FirstOrDefault().ID != cliente.ID)
throw new Exception("Cpf já cadastrado no sistema.");
}
try
{
using (IDbConnection db = new SqlConnection(connection))
{
string readSp = "SP_AltCliente";
db.Execute(readSp, new
{
cliente.ID,
cliente.Nome,
cliente.CPF,
cliente.Sexo,
cliente.TipoID,
cliente.SituacaoID
}, commandType: CommandType.StoredProcedure);
}
}
catch (Exception ex)
{
throw new Exception("Ocorreu um erro ao executar a operação: " + ex.Message);
}
}
internal void Delete(int id)
{
try
{
using (IDbConnection db = new SqlConnection(connection))
{
string readSp = "SP_DelCliente";
db.Execute(readSp, new { id = id }, commandType: CommandType.StoredProcedure);
}
}
catch (Exception ex)
{
throw new Exception("Ocorreu um erro ao executar a operação: " + ex.Message);
}
}
}
}
<file_sep># Gestão de Clientes
Aplicação desenvolvida na linguagem C#, com Asp.Net WebForms. Camada de acesso aos dados encapsulado em um Web Service WCF;
O Script para gerar o banco e popular as tabelas estão no diretório _sql;
A aplicação deve rodar com privilégios de Administrador;
<file_sep>using GestaoClientes.Api.Models;
using System.Collections.Generic;
using System.ServiceModel;
namespace GestaoClientes.Api
{
[ServiceContract]
public interface IClienteService
{
[OperationContract]
List<Cliente> GetClientes();
[OperationContract]
List<ClienteSituacao> GetClienteSituacoes();
[OperationContract]
List<ClienteTipo> GetClienteTipos();
[OperationContract]
void CreateCliente(Cliente cliente);
[OperationContract]
Cliente GetCliente(int id);
[OperationContract]
void UpdateCliente(Cliente cliente);
[OperationContract]
void DeleteCliente(int id);
}
}
<file_sep>using GestaoClientes.Web.ServiceReference1;
using System;
using System.Linq;
using System.Web.UI.WebControls;
namespace GestaoClientes.Web.Cliente
{
public partial class ClienteEditar : System.Web.UI.Page
{
ClienteServiceClient servico = new ClienteServiceClient();
protected void Page_Load(object sender, EventArgs e)
{
Inicializar();
int id = 0;
if (!IsPostBack)
{
CarregarListas();
if (!string.IsNullOrEmpty(RESULT_idHidden.Value))
{
id = Convert.ToInt32(Request.QueryString["id"]);
Carrega(id);
litAcaoDaPagina.Text = "Editar Cliente";
}
else
{
litAcaoDaPagina.Text = "Adicionar Cliente";
}
}
}
private void Carrega(int id)
{
var cliente = servico.GetCliente(id);
ddlTipo.SelectedValue = Convert.ToString(cliente.TipoID);
ddlSituacao.SelectedValue = Convert.ToString(cliente.SituacaoID);
tbNome.Text = cliente.Nome;
tbCpf.Text = cliente.CPF;
if (cliente.Sexo == char.Parse("M"))
{
rbSexo.SelectedValue = "Masculino";
rbSexo.Items.FindByValue("M").Selected = true;
}
else
{
rbSexo.SelectedValue = "Feminino";
rbSexo.Items.FindByValue("F").Selected = true;
}
}
private void CarregarListas()
{
var listClienteTipo = servico.GetClienteTipos().ToList();
var listClientesSituacao = servico.GetClienteSituacoes().ToList();
var tipos = listClienteTipo;
ddlTipo.DataSource = tipos.ToList();
ddlTipo.DataTextField = "Descricao";
ddlTipo.DataValueField = "ID";
ddlTipo.DataBind();
var situacoes = listClientesSituacao;
ddlSituacao.DataSource = situacoes.ToList();
ddlSituacao.DataTextField = "Descricao";
ddlSituacao.DataValueField = "ID";
ddlSituacao.DataBind();
}
private void Inicializar()
{
if (Request.QueryString.AllKeys.Contains("id"))
{
RESULT_idHidden.Value = Request.QueryString["id"] == "0"
? ""
: Request.QueryString["id"];
}
}
protected void Page_Init(object sender, EventArgs e)
{
lkbSalvar.Click += lkbSalvar_Click;
}
void lkbSalvar_Click(object sender, EventArgs e)
{
try
{
bool Atualiza = (RESULT_idHidden.Value.Length > 0)
? true
: false;
ServiceReference1.Cliente cliente = new ServiceReference1.Cliente();
if (Atualiza)
{
cliente = servico.GetCliente(Convert.ToInt32(RESULT_idHidden.Value));
cliente.ID = cliente.ID;
cliente.Nome = tbNome.Text;
cliente.CPF = tbCpf.Text;
cliente.TipoID = int.Parse(ddlTipo.SelectedValue);
cliente.SituacaoID = int.Parse(ddlSituacao.SelectedValue);
cliente.Sexo = char.Parse(rbSexo.SelectedValue.ToString());
servico.UpdateCliente(cliente);
}
else
{
cliente.Nome = tbNome.Text;
cliente.CPF = tbCpf.Text;
cliente.TipoID = int.Parse(ddlTipo.SelectedValue);
cliente.SituacaoID = int.Parse(ddlSituacao.SelectedValue);
cliente.Sexo = char.Parse(rbSexo.SelectedValue.ToString());
servico.CreateCliente(cliente);
}
Response.Redirect("Clientes.aspx");
}
catch (Exception ex)
{
phMensagem.Visible = true;
litMensagem.Text = ex.Message;
}
}
protected void rbSexo_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
} | 3b80a8bd716fbc8540c8ea6399fbf79f63172e18 | [
"Markdown",
"C#"
] | 7 | C# | david-inacio/Teste-Remoto-FA | 9ab8179653c544938894c7affd3baa1b6fc8e94f | 5ef6185cefa6923463b068fe4cc707798dd21b8e |
refs/heads/master | <repo_name>jrothwell/room-booker-app<file_sep>/www/js/controllers.js
var api = "http://172.20.10.4:3030/";
angular.module('starter.controllers', [])
.service('sharedProperties', function () {
var requiredCapacity = 4;
return {
getCapacity: function () {
return requiredCapacity;
},
setCapacity: function(value) {
requiredCapacity = value;
}
};
})
.controller('AppCtrl', function ($scope, $ionicModal, $timeout) {
// With the new view caching in Ionic, Controllers are only called
// when they are recreated or on app start, instead of every page change.
// To listen for when this page is active (for example, to refresh data),
// listen for the $ionicView.enter event:
//$scope.$on('$ionicView.enter', function(e) {
//});
})
.controller('BookingCtrl', function ($scope, $state) {
$scope.bookForNow = function() {
$state.go("app.immediateBooking");
};
$scope.bookForLater = function() {
$state.go("app.laterBooking");
};
})
.controller('ExistingBookingsCtrl', function ($scope, $stateParams) {
})
.controller('ImmediateRoomBookingController', function ($scope, $state, $rootScope, sharedProperties) {
$rootScope.bookingDetails = {
numberOfParticipants:4,
duration: "30",
whiteboards: false,
screens: false,
phones: true
};
$scope.findRooms = function() {
sharedProperties.setCapacity($rootScope.bookingDetails.numberOfParticipants);
$state.go("app.immediateAvailability");
}
})
.controller('ImmediateRoomsAvailableController', function($scope, $stateParams, $state, $rootScope, sharedProperties, $http) {
var requiredCapacity = sharedProperties.getCapacity();
$scope.availableRooms = [];
$http.post(api + 'roomNow/', {
duration: $rootScope.duration,
location: {
city: "London",
buildingId: 1,
floor: 1
},
capacity: requiredCapacity
}).then(function success(response) {
response.data.map(function(room) {
$scope.availableRooms.push({
name: room.roomName,
capacity: room.capacity,
whiteboards: room.facilities.wheelChairAccess,
phones: room.facilities.videoCon,
screens: room.facilities.projector,
floor: room.floor
});
});
}, function failure(response) {
console.log("FAILED!");
})
$scope.book = function(room) {
console.log("Booked!");
$rootScope.bookings.push({
room: room,
time: new Date(),
immediate: true,
duration: $rootScope.duration
});
$rootScope.bookedRoom = room;
$state.go("app.immediateSuccess")
}
})
.controller('LaterRoomBookingController', function ($scope, $state, $stateParams, $rootScope) {
dateTime = new Date();
$rootScope.dateAndTime = new Date(dateTime.getFullYear(), dateTime.getMonth(),
(dateTime.getDate() + 1), 9, 0, 0, 0);
$rootScope.bookingDetails = {
numberOfParticipants:0,
duration: "30",
whiteboards: false,
screens: false,
phones: true,
dateAndTime: $rootScope.dateAndTime
};
$scope.chooseAttendees = function() {
$state.go("app.chooseAttendees");
};
$scope.findRooms = function() {
if ($rootScope.attendees.length != 0) {
$state.go("app.laterAvailability");
}
};
})
.controller('LaterRoomsAvailableController', function($scope, $stateParams, $state, $rootScope) {
$scope.availableRooms = [
{
name: "Mako",
capacity: 8,
whiteboards: true
},
{
name: "Lantern",
capacity: 4,
whiteboards: true,
phones: true
},
{
name: "Park",
capacity: 12,
whiteboards: true,
phones: true,
screens: true
}
];
$scope.book = function(room) {
console.log("Booked!");
$rootScope.bookings.push({
room: room,
time: $rootScope.dateAndTime,
immediate: false,
duration: $rootScope.duration
});
$rootScope.bookedRoom = room;
$rootScope.bookingDetails.numberOfParticipants = 0;
$rootScope.attendees.length = 0;
$state.go("app.laterSuccess");
}
})
.controller('MyLocationController', function ($scope, $stateParams, $rootScope, $ionicPlatform, $cordovaBeacon, $http) {
$scope.beacons = {};
$scope.currentRoom = '';
$ionicPlatform.ready(function() {
$cordovaBeacon.requestWhenInUseAuthorization();
$rootScope.$on("$cordovaBeacon:didRangeBeaconsInRegion", function(event, pluginResult) {
var uniqueBeaconKey;
var data = [];
// $http.get('http://10.132.32.162:3030/phones/sam/currentRoom')
$http.get(api + 'phones/sam/currentRoom')
.then(function(response) {
console.log(response.data.roomName);
if ($scope.currentRoom !== response.data.roomName) {
$scope.currentRoom = response.data.roomName;
}
console.log(response);
});
for(var i = 0; i < pluginResult.beacons.length; i++) {
if (pluginResult.beacons[i].major == 14470) {
//console.log(pluginResult.beacons[i].rssi + " FUTURE-3");
data.push({
"sensorId": "FUTURE-3",
"distance": pluginResult.beacons[i].rssi,
});
}
else if (pluginResult.beacons[i].major == 1000) {
//console.log(pluginResult.beacons[i].rssi + " FUTURE-2");
data.push({
"sensorId": "FUTURE-2",
"distance": pluginResult.beacons[i].rssi,
});
} else {
//console.log(pluginResult.beacons[i].rssi + " FUTURE-1");
data.push({
"sensorId": "FUTURE-1",
"distance": pluginResult.beacons[i].rssi,
});
}
uniqueBeaconKey = pluginResult.beacons[i].uuid + ":" + pluginResult.beacons[i].major + ":" + pluginResult.beacons[i].minor;
$scope.beacons[uniqueBeaconKey] = pluginResult.beacons[i];
}
$http.put(api + 'phones/sam/beaconData', data)
.then(function(response) {
//console.log(response);
})
.catch(function(response) {
//console.log(response);
});
$scope.$apply();
});
$cordovaBeacon.startRangingBeaconsInRegion($cordovaBeacon.createBeaconRegion("Light Blue", "b9407f30-f5f8-466e-aff9-25556b57fe6d", 14470, 61580));
$cordovaBeacon.startRangingBeaconsInRegion($cordovaBeacon.createBeaconRegion("Purple", "b9407f30-f5f8-466e-aff9-25556b57fe6d", 1000, 1));
$cordovaBeacon.startRangingBeaconsInRegion($cordovaBeacon.createBeaconRegion("Green", "b9407f30-f5f8-466e-aff9-25556b57fe6d", 4473, 1));
});
})
.controller('ImmediateSuccessController', function($scope, $stateParams, $state, $ionicHistory) {
$scope.goHome = function() {
$ionicHistory.nextViewOptions({
disableBack: true
});
$state.go('app.book');
}
})
.controller('LaterSuccessController', function($scope, $stateParams, $state, $ionicHistory) {
$scope.goHome = function() {
$ionicHistory.nextViewOptions({
disableBack: true
});
$state.go('app.book');
}
})
.controller('PeopleAttendingController', function ($scope, $state, $stateParams, $rootScope) {
$rootScope.attendees = [];
$rootScope.locOfAttendees = {};
$scope.people = [{
"location":"London Building 1",
"name": "Ben",
"selected": false
},
{
"location":"London Building 1",
"name": "Luke",
"selected": false
},
{
"location":"London Building 1",
"name": "Linda",
"selected": false
},
{
"location":"Lodon Building 2",
"name":"Emma",
"selected": false
},
{
"location":"London Building 3",
"name":"Tom",
"selected": false
},
{
"location":"London Building 1",
"name":"Jenny",
"selected": false
}];
$scope.clearAttendeeList = function() {
for (var i = 0; i < $scope.people.length; i++) {
$scope.people[i].selected = false;
};
}
function isNotEmpty(obj) {
for(var key in obj) {
if(obj.hasOwnProperty(key))
return true;
}
return false;
}
$rootScope.confirmAttendees = function() {
$rootScope.attendees.length = 0;
$rootScope.locOfAttendees = {};
for (var i = 0; i < $scope.people.length; i++) {
var value = $scope.people[i];
if (value.selected) {
$rootScope.attendees.push(value);
if ($rootScope.locOfAttendees.hasOwnProperty(value.location)) {
$rootScope.locOfAttendees[value.location].push(value.name);
} else {
$rootScope.locOfAttendees[value.location] = [value.name];
}
}
};
console.log($rootScope.locOfAttendees.length);
if (isNotEmpty($rootScope.locOfAttendees)) {
$state.go("app.confirmAttendees");
}
};
})
.controller('ConfirmAttendingController', function ($scope, $state, $stateParams, $rootScope) {
$rootScope.submitParticipants = function() {
$rootScope.bookingDetails.numberOfParticipants = $rootScope.attendees.length;
$state.go("app.laterBooking");
}
});
| b188c7becb8f358497660163f83c3499f099dbb2 | [
"JavaScript"
] | 1 | JavaScript | jrothwell/room-booker-app | be1a5bb177b0b419d078959f645d426089a03f45 | 480b2592109fcf97851d61ac0763ad4093ae0c48 |
refs/heads/master | <repo_name>jos-m/Social-Media-Dashboard<file_sep>/docs/js/scripts-min.js
const totalFollowers = document.getElementById('total-followers');
const switchContainer = document.getElementById('switch-container');
const cardNumbers = [...document.querySelectorAll('.card__number')];
let totalFollowersNumber = 0;
const getRandomInt = (min, max) =>
Math.floor(Math.random() * (max + -min)) + min;
const formatNumber = (number) => {
if (number > 1999999) return `${Math.floor(number / 1000000)}M`;
if (number > 19999) return `${Math.floor(number / 1000)}K`;
return `${number}`;
};
const formatWithDotNotation = (number) =>
new Intl.NumberFormat('es-Es').format(number);
const writeNumbers = (format) => {
cardNumbers.forEach((number) => {
const random = getRandomInt(0, 5000);
totalFollowersNumber += random;
number.textContent = random;
});
totalFollowers.textContent = `Total People Who Loves You: ${
format
? formatNumber(totalFollowersNumber)
: formatWithDotNotation(totalFollowersNumber)
}`;
};
writeNumbers(false);
const switchInput = document.getElementById('switch-label');
const switchText = document.getElementById('switch-text');
const styles = document.documentElement.style;
const lightTheme = {
'--bg-color': ' hsl(0, 0%, 100%)',
'--bg-color-head': 'hsl(225, 100%, 98%)',
'--card-bg': 'hsl(227, 47%, 96%)',
'--card-bg-hover': 'hsl(232, 33%, 91%)',
'--soft-blue': 'hsl(228, 12%, 44%)',
'--toggle-bg': 'hsl(230, 22%, 74%)',
'--toggle-bg-hover':
'linear-gradient(90deg,hsl(210, 78%, 56%) 0%,hsl(146, 68%, 55%) 100%)',
'--title-color': 'hsl(228, 12%, 44%)',
'--text-color': 'hsl(230, 17%, 14%)',
};
const darkTheme = {
'--bg-color': 'hsl(230, 17%, 14%)',
'--bg-color-head': 'hsl(232, 19%, 15%)',
'--card-bg': 'hsl(228, 28%, 20%)',
'--card-bg-hover': 'hsl(228, 26%, 27%)',
'--soft-blue': 'hsl(228, 34%, 66%)',
'--toggle-bg':
'linear-gradient(90deg,hsl(210, 78%, 56%) 0%,hsl(146, 68%, 55%) 100%)',
'--title-color': 'hsl(0, 0%, 100%)',
'--text-color': 'hsl(228, 34%, 66%)',
};
const changeTheme = (theme) => {
const customStyles = Object.keys(theme);
for (const style of customStyles) {
styles.setProperty(style, theme[style]);
}
};
switchInput.addEventListener('click', (e) => {
e.target.previousElementSibling.checked
? (changeTheme(lightTheme), (switchText.textContent = 'Dark Mode'))
: (changeTheme(darkTheme), (switchText.textContent = 'Light Mode'));
});
<file_sep>/README.md
# Social-Media-Dashboard
<img src='./social-media-dashboard.png' alt='Social Media Dashboard' width='100%'/>
| ef61bc2582aaeddd50a68a1a89ecddaf30ec15d6 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | jos-m/Social-Media-Dashboard | cce90c5185a66e421f7e12d280e87d21c8c63beb | ee1ad9d765a3d7202407f1e1bb5f647a7b666423 |
refs/heads/master | <file_sep>package com.hongcd.cloud.bms.controller;
import com.hongcd.cloud.bms.service.BookTypeService;
import com.hongcd.cloud.common.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* 图书控制器
* @author HongD
* @date 2018-10-15
*/
@RestController
@RequestMapping("/book")
public class BookController extends BaseController {
@Autowired
private BookTypeService bookTypeService;
/**
* 获取图书类型
* @param bookName
* @return
*/
@GetMapping("/getBookType/{bookName}")
public Result getBookType(@PathVariable String bookName) {
return bookTypeService.getBookType(bookName);
}
}<file_sep>package com.hongcd.cloud.bms.service;
import com.hongcd.cloud.common.utils.Result;
/**
* 图书类别服务
* @author HongD
* @date 2018-10-15
*/
public interface BookTypeService {
/**
* 获取图书类别
* @param bookName
* @return
*/
Result<String> getBookType(String bookName);
}<file_sep>package com.hongcd.cloud.bms;
import org.springframework.boot.SpringApplication;
import org.springframework.cloud.client.SpringCloudApplication;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
/**
* 图书服务启动类
* @author HongD
* @date 2018-10-15
*/
@SpringCloudApplication
public class BmsApplication {
public static void main(String[] args) {
SpringApplication.run(BmsApplication.class, args);
}
@Bean
@LoadBalanced
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
| 284ab96ab7a4ca933dfc10897bee286eec08a6c1 | [
"Java"
] | 3 | Java | hongcd/spring-cloud-demo | 614d0a3963e7a39ca46e292bcf81c9bfc3f16f9c | ea332c8662cdcefd91509267a2a3ad3e02b1e636 |
refs/heads/master | <file_sep>中文文档请见 [这里][readmecn]
## Installation
There are two ways to install, the first and recommended way is via `Package Control`:
1. Make sure you have `Package Control` installed, see <https://packagecontrol.io/installation>
2. Search for `Direct Copy` using `Package Control` and install
Another way is to clone source from github:
1. Browse into your sublime text's package folder
2. Run `git clone https://github.com/UniFreak/SublimeDirectCopy.git`
## Configuration & Usage
There is already a configured `demo` entry in the setting file, you can add your own copy entries according to `demo` configuration. The entry name is configured by `title` and content by `content`, like this:
```json
{
"entry":
[
{
"title" : "demo",
"content" : "demo contens copied from direct copy"
},
]
}
```
After this, you can then bring up the copy entry selection pop-up by hitting `ctrl+shift+c` (Windows) or `super+shift+c` (Mac) and select one for copy. like this:

[readmecn]: https://github.com/UniFreak/SublimeDirectCopy/blob/master/README.cn.md
<file_sep>Sublime Text 的 `Direct Copy` 包能根据配置, 通过快捷键快速复制常用文本内容
## 安装
有两种方式可以安装, 第一种是通过 `Package Control`:
1. 确保装有 Package Control, 参见 <https://packagecontrol.io/installation>
2. 搜索 `Direct Copy` 并安装
另一种方式是直接通过克隆源码安装:
1. 进入 sublime text 的包目录
2. 运行 `git clone https://github.com/UniFreak/SublimeDirectCopy.git`
## 配置 & 使用
已经提供了一个默认的 `demo` 配置, 你可以在 `entry` 配置项下面, 依照 `demo` 的配置添加额外的项目名称 (`title` 配置项) 及其内容 (`context` 配置项). 如下:
```json
{
"entry":
[
{
"title" : "demo",
"content" : "demo contens copied from direct copy"
},
]
}
```
配置完成后, 可以通过快捷键 `ctrl+shift+c` (Windows) 或 `super+shift+c` (Mac) 调出拷贝列表, 选中即可拷贝对应文本, 如图
<file_sep>import sublime, sublime_plugin
settings = {}
def plugin_loaded():
global settings
settings = sublime.load_settings('DirectCopy.sublime-settings')
class DirectCopyCommand(sublime_plugin.TextCommand):
def run(self, edit):
entries = settings.get('entry')
options = []
self.contents = []
for e in entries:
options.append(e['title'])
self.contents.append(e['content'])
self.view.window().show_quick_panel(options, on_select = self.copy)
def copy(self, index):
if index != -1:
sublime.set_clipboard(self.contents[index])
| b7e72614357ea01c271d5d123f1bdf393a800316 | [
"Markdown",
"Python"
] | 3 | Markdown | unifreak/SublimeDirectCopy | 4469ac4759e468c93cd4250f93208c9125e9eba4 | e335773ddbd281b81f6978a112b3a99a75792940 |
refs/heads/master | <repo_name>carltonf/vagrantfiles<file_sep>/ceph-docker/Vagrantfile
# -*- mode: ruby -*-
# vi: set ft=ruby :
Vagrant.configure("2") do |config|
config.vm.box = "ceph-builder"
config.vm.box_check_update = false
config.ssh.insert_key = false
config.vm.network "private_network", type: "dhcp"
config.vm.hostname = "ceph-docker"
config.vm.provider "virtualbox" do |vb|
vb.linked_clone = true
vb.memory = "4096"
end
end
<file_sep>/ceph-builder/provision-WIP/install-ceph.sh
#!/bin/sh
# Install docker from upstream for Ubuntu Xenial 16.04 (LTS)
# Ref: http://docs.master.dockerproject.org/engine/installation/linux/ubuntulinux/
sudo apt-get update
sudo apt-get install apt-transport-https ca-certificates
sudo apt-key adv --keyserver hkp://p80.pool.sks-keyservers.net:80 --recv-keys <KEY>
echo 'deb https://apt.dockerproject.org/repo ubuntu-xenial main' | sudo tee /etc/apt/sources.list.d/docker.list
sudo apt-get update
# NOTE: not really necessary
sudo apt-get purge lxc-docker
apt-cache policy docker-engine
# For aufs
sudo apt-get install linux-image-extra-$(uname -r)
sudo apt-get install docker-engine
# Should be enabled by default
sudo systemctl enable docker
# Public registry test
sudo service docker start
sudo service docker status
sudo docker run --rm hello-world
# Private registry test
if [ -e /vagrant/daemon.json ]; then
sudo install -m0600 /vagrant/daemon.json /etc/docker/daemon.json
fi
sudo service docker restart
sudo service docker status
sudo docker run --rm crystal.cw:5000/hello-world
sudo docker images
# add vagrant to the group
sudo groupadd docker
sudo usermod -aG docker vagrant
su - vagrant
docker images
<file_sep>/tools/vagrant.bashrc
# -*- mode: shell-script -*-
# Enhanced vagrant functions: to be sourced from ~/.bashrc
## For Vagrant, notably some Windows programs still expect to see Windows path style
if [ "$(hostname)" = "cx5510" ]; then
export VAGRANT_HOME='D:/Home/.vagrant.d'
fi
function vagrantq {
local vagrant_vm_name="$1"
if [ x = x"$vagrant_vm_name" ]; then
echo "Info: Vagrant VM name not given. Show global status and switching to vagrantfiles."
vagrant global-status
fi
# NOTE the rest args will be assumed as args passed to vagrant command
shift
local vagrant_runtime_base=${HOME}/Vagrant/vagrantfiles/
local vagrant_vm="${vagrant_runtime_base}/${vagrant_vm_name}"
if [ -d "$vagrant_vm" ]; then
if [ "$#" -gt 0 ]; then
pushd "$vagrant_vm" > /dev/null
vagrant "$*"
popd > /dev/null
else
# NOTE default action is only to cd
cd "$vagrant_vm"
echo "INFO: switching to Vagrant VM working directory."
fi
else
echo "Error: Not valid Vagrant VM name. Abort."
return -2;
fi
}
# NOTE workaround for vagrant 1.9.5 as 'vagrant ssh' doesn't work well under
# MobaXterm due to the pecularity of MobaXterm's tty
function vagrant-ssh {
# NOTE: check port to speed things up
if [ "$PREV_VAGRANT_SSH_VM_ROOT" != "$(pwd)" ]; then
# NOTE: `vagrant port` output has weird control characters, looks like
# `$'\E[0m2200\E[0m\r'`
export SSH_FORWARDED_PORT=$(vagrant port --guest 22 | grep -o -E '[0-9]{2,}')
export PREV_VAGRANT_SSH_VM_ROOT="$(pwd)"
fi
local ssh_port="$SSH_FORWARDED_PORT"
# TODO: To use the key file. `vagrant ssh-config` would also list the keyfile
sshpass -p vagrant ssh -p "${ssh_port}" vagrant@localhost "$*"
}
<file_sep>/tools/basebox-packager.sh
#!/bin/bash
#
# Script to create a box from 'crystal-maker' and import it into local box
# registry.
# Tested with bash bundled with 'git-for-windows'.
echo "TODO: Adapt this script to be more general. (maybe with packe:)"
baseboxName='crystal-maker'
# NOTE: there can be residual maker boxes
if [[ $(VBoxManage list vms | grep -c $baseboxName) -gt 1 ]]; then
echo "ERROR: multiple maker boxes found. Abort."
exit -1
fi
vmid=$(VBoxManage list vms | grep -o $baseboxName'[^"]*')
dateTag=$(date +%Y%m%d) # format like 20160713
boxFileName="${baseboxName}-${dateTag}.box"
if [[ -z "$vmid" ]]; then
echo "ERROR: Can not found '$baseboxName' VM instance."
exit -1
fi
echo "* Packaging $baseboxName"
vagrant halt
vagrant package --base $vmid --output $boxFileName
vagrant box remove $baseboxName
vagrant box add --name $baseboxName $boxFileName
# list box to be sure
echo "* Current registered boxes:"
vagrant box list
### TODO
# box metadata like the version, see https://www.vagrantup.com/docs/boxes/format.html
<file_sep>/dao-host/Vagrantfile
# -*- mode: ruby -*-
# vi: set ft=ruby :
# Docker host machine for use in mainland, this machine use `daocloud` to speed
# up connection speed.
Vagrant.configure("2") do |config|
config.vm.box = "geerlingguy/ubuntu1604"
config.vm.hostname = "dao-host"
# config.vm.network "private_network", type: "dhcp"
config.vm.network "public_network"
# hostname trick, refer to crystal/Vagrantfile for detailed explanation
if Vagrant.has_plugin?("vagrant-hostmanager")
config.hostmanager.enabled = true
config.hostmanager.manage_host = true
config.hostmanager.manage_guest = false
config.hostmanager.ignore_private_ip = false
config.hostmanager.include_offline = true
config.hostmanager.ip_resolver = proc do |vm, resolving_vm|
if vm.id
`VBoxManage guestproperty get #{vm.id} "/VirtualBox/GuestInfo/Net/1/V4/IP"`.split()[1]
end
end
config.vm.synced_folder ENV["WINDIR"] + "/System32/drivers", "/tmp/windrivers"
config.vm.provision "shell", run: "always", name: "bind-hosts",
inline: "mount --bind /tmp/windrivers/etc/hosts /etc/hosts"
else
$stderr.puts "WARNING: Hostname lookup requires vagrant-hostmanager plugin."
end
# hostname trick END
config.vm.provider "virtualbox" do |vb|
# Be sure to have enough RAM for *serious* work
vb.memory = "2048"
end
WINHOME = ENV['HOMEDRIVE'] + "/" + ENV['HOMEPATH']
config.vm.synced_folder WINHOME + "/Dropbox", "/Dropbox"
config.vm.provision "shell", inline: <<-SHELL
# NOTE at my 3rd installation, the daocloud repo actually fails me...
# So unreliabe, anyway install it directly from ubuntu repo is ok, as this
# is ubuntu 16.04
curl -sSL https://get.daocloud.io/docker | sh
sudo service docker status
# NOTE: the following has personal key in it so not automate anyway
echo "WARN: need to manually configure dao mirror registry."
echo "see https://www.daocloud.io/mirror#accelerator-doc"
# NOTE: Vagrant provider issue docker command as user `vagrant` _without_
# sudo, so we need to add `vagrant` to `docker` group
sudo usermod -aG docker vagrant
SHELL
end
<file_sep>/ceph-docker/utils/docker-cw-pull.sh
#!/bin/sh
# TODO test /etc/docker/daemon.json
# Ease the image pulling from local registry
# Needed because the default registry can not be changed.
# Ref: https://github.com/moby/moby/issues/33069
REG_SERVER=crystal.cw:5000
# NOTE the name as in the docker hub
orig_img_name="$*"
local_img_name=$REG_SERVER/$orig_img_name
docker pull $local_img_name || exit 1
docker tag $local_img_name $orig_img_name
docker rmi $local_img_name
echo "* DONE!"
<file_sep>/terrywang-archlinux/Vagrantfile
# -*- mode: ruby -*-
# vi: set ft=ruby :
Vagrant.configure(2) do |config|
# For making box purpose, do not insert new key
config.ssh.insert_key = false
# From minimalistic to more-up-to-date box
# see https://github.com/terrywang/vagrantboxes/blob/master/archlinux-x86_64.md
config.vm.box = "terrywang/archlinux"
config.vm.box_check_update = false
config.vm.provider "virtualbox" do |vb|
# Enough RAM to avoid installation errors
vb.memory = "1024"
end
# NOTE shell script should be in unix line ending style
config.vm.provision "shell", path: 'provision.sh'
end
<file_sep>/ceph/ansible-try/Vagrantfile
# -*- mode: ruby -*-
# vi: set ft=ruby :
# Vagrant file for trying out ceph-ansible locally
# NOTE changes from the upstream one
# [x] Simplify Vagrantfile: only VirtualBox
# [x] adapt the ansible provisioner spurn out files so we can use crystal.cw as
# control machine
require 'yaml'
require 'time'
config_file=File.expand_path('vagrant_variables.yml', File.dirname(__FILE__))
settings=YAML.load_file(config_file)
LABEL_PREFIX = settings['label_prefix'] ? settings['label_prefix'] + "-" : ""
NMONS = settings['mon_vms']
NOSDS = settings['osd_vms']
NMDSS = settings['mds_vms']
NRGWS = settings['rgw_vms']
NNFSS = settings['nfs_vms']
RESTAPI = settings['restapi']
NRBD_MIRRORS = settings['rbd_mirror_vms']
CLIENTS = settings['client_vms']
NISCSI_GWS = settings['iscsi_gw_vms']
MGRS = settings['mgr_vms']
PUBLIC_SUBNET = settings['public_subnet']
CLUSTER_SUBNET = settings['cluster_subnet']
BOX = settings['vagrant_box']
BOX_URL = settings['vagrant_box_url']
SYNC_DIR = settings['vagrant_sync_dir']
MEMORY = settings['memory'] || 1024
ETH = settings['eth']
USER = settings['ssh_username'] ? settings['ssh_username'] : "vagrant"
DEBUG = settings['debug']
# TODO how does this impact the rest of the setup
ASSIGN_STATIC_IP = false
DISABLE_SYNCED_FOLDER = settings.fetch('vagrant_disable_synced_folder', false)
DISK_UUID = Time.now.utc.to_i
# TODO the whole write to the inventory from Vagrantfile thing feels repetive,
# most configurations are read from #{config_file} anyway
INVENTORY_FILE = File.expand_path('ansible-files/hosts', File.dirname(__FILE__))
generate_ansible_inventory = proc do
# Empty the file
File.open(INVENTORY_FILE, 'w') do |f|
f.puts "# -*- mode: conf -*-"
end
File.open(INVENTORY_FILE, 'a') do |f|
### Groups
# NOTE the upstream ansible provisioner uses Vagrant machine names, and since
# we are creating inventory file on our own, we need to use hostnames here.
hosts_groups = {
'mons' => (0..NMONS - 1).map { |j| "mon#{j}" },
'osds' => (0..NOSDS - 1).map { |j| "osd#{j}" },
'mdss' => (0..NMDSS - 1).map { |j| "mds#{j}" },
'rgws' => (0..NRGWS - 1).map { |j| "rgw#{j}" },
'nfss' => (0..NNFSS - 1).map { |j| "nfs#{j}" },
'rbd_mirrors' => (0..NRBD_MIRRORS - 1).map { |j| "rbd-mirror#{j}" },
'clients' => (0..CLIENTS - 1).map { |j| "client#{j}" },
'iscsi_gw' => (0..NISCSI_GWS - 1).map { |j| "iscsi-gw#{j}" },
'mgrs' => (0..MGRS - 1).map { |j| "mgr#{j}" }
}
# NOTE internal lab domain
DOMAIN='cv'
hosts_groups.each do |group, array|
f.puts "[#{group}]"
array.each do |host|
f.puts "#{LABEL_PREFIX}ceph-#{host}.#{DOMAIN}"
end
end
if RESTAPI then
f.puts '[restapis]'
(0..NMONS - 1).map { |j| f.puts "#{LABEL_PREFIX}ceph-mon#{j}.#{DOMAIN}" }
end
### Vars
# TODO a separate file?
# NOTE inventory file is ini format, so assignment should be done with `=`
f.puts <<EXTRA_VARS
[all:vars]
cluster_network="#{CLUSTER_SUBNET}.0/24"
journal_size=100
public_network="#{PUBLIC_SUBNET}.0/24"
devices=#{ settings['disks'] }
osd_scenario=collocated
monitor_interface=#{ETH}
## NOTE: complex variable type is hard to get right in an inventory file,
## `os_tuning_params` should be set in the `group_vars/all.yml`
## TODO Gerenate one automatically (also with other yaml file)
# os_tuning_params='#{ settings['os_tuning_params'] }'
pool_default_size='2',
EXTRA_VARS
end
end
# NOTE regenerate the inventory_file if:
# 1. it doesn't exist
# 2. Older than Vagrantfile or vagrant_variables.yml
if not File.exist? INVENTORY_FILE \
or File.mtime(__FILE__) > File.mtime(INVENTORY_FILE) \
or File.mtime(config_file) > File.mtime(INVENTORY_FILE)
# NOTE: `vagrant validate` can be used generate the inventory file only
generate_ansible_inventory.call
puts "* INFO: inventory file regenerated: #{INVENTORY_FILE}"
end
Vagrant.configure(2) do |config|
config.vm.box = BOX
config.vm.box_url = BOX_URL
# workaround for https://github.com/mitchellh/vagrant/issues/5048
config.vm.box_check_update = false
config.ssh.insert_key = false
# Faster bootup. Disables mounting the sync folder for libvirt and virtualbox
config.vm.provider :virtualbox do |v,override|
v.linked_clone = true
override.vm.synced_folder '.', SYNC_DIR, disabled: true
end
unless ASSIGN_STATIC_IP
config.vm.network "private_network", type: "dhcp"
end
(0..MGRS - 1).each do |i|
config.vm.define "#{LABEL_PREFIX}mgr#{i}" do |mgr|
mgr.vm.hostname = "#{LABEL_PREFIX}ceph-mgr#{i}"
if ASSIGN_STATIC_IP
mgr.vm.network :private_network,
ip: "#{PUBLIC_SUBNET}.3#{i}"
end
# Virtualbox
mgr.vm.provider :virtualbox do |vb|
vb.customize ['modifyvm', :id, '--memory', "#{MEMORY}"]
end
end
end
(0..CLIENTS - 1).each do |i|
config.vm.define "#{LABEL_PREFIX}client#{i}" do |client|
client.vm.hostname = "#{LABEL_PREFIX}ceph-client#{i}"
if ASSIGN_STATIC_IP
client.vm.network :private_network,
ip: "#{PUBLIC_SUBNET}.4#{i}"
end
# Virtualbox
client.vm.provider :virtualbox do |vb|
vb.customize ['modifyvm', :id, '--memory', "#{MEMORY}"]
end
end
end
(0..NRGWS - 1).each do |i|
config.vm.define "#{LABEL_PREFIX}rgw#{i}" do |rgw|
rgw.vm.hostname = "#{LABEL_PREFIX}ceph-rgw#{i}"
if ASSIGN_STATIC_IP
rgw.vm.network :private_network,
ip: "#{PUBLIC_SUBNET}.5#{i}"
end
# Virtualbox
rgw.vm.provider :virtualbox do |vb|
vb.customize ['modifyvm', :id, '--memory', "#{MEMORY}"]
end
end
end
(0..NNFSS - 1).each do |i|
config.vm.define "nfs#{i}" do |nfs|
nfs.vm.hostname = "ceph-nfs#{i}"
if ASSIGN_STATIC_IP
nfs.vm.network :private_network,
ip: "#{PUBLIC_SUBNET}.6#{i}"
end
end
end
(0..NMDSS - 1).each do |i|
config.vm.define "#{LABEL_PREFIX}mds#{i}" do |mds|
mds.vm.hostname = "#{LABEL_PREFIX}ceph-mds#{i}"
if ASSIGN_STATIC_IP
mds.vm.network :private_network,
ip: "#{PUBLIC_SUBNET}.7#{i}"
end
# Virtualbox
mds.vm.provider :virtualbox do |vb|
vb.customize ['modifyvm', :id, '--memory', "#{MEMORY}"]
end
end
end
(0..NRBD_MIRRORS - 1).each do |i|
config.vm.define "#{LABEL_PREFIX}rbd_mirror#{i}" do |rbd_mirror|
rbd_mirror.vm.hostname = "#{LABEL_PREFIX}ceph-rbd-mirror#{i}"
if ASSIGN_STATIC_IP
rbd_mirror.vm.network :private_network,
ip: "#{PUBLIC_SUBNET}.8#{i}"
end
# Virtualbox
rbd_mirror.vm.provider :virtualbox do |vb|
vb.customize ['modifyvm', :id, '--memory', "#{MEMORY}"]
end
end
end
(0..NISCSI_GWS - 1).each do |i|
config.vm.define "#{LABEL_PREFIX}iscsi_gw#{i}" do |iscsi_gw|
iscsi_gw.vm.hostname = "#{LABEL_PREFIX}ceph-iscsi-gw#{i}"
if ASSIGN_STATIC_IP
iscsi_gw.vm.network :private_network,
ip: "#{PUBLIC_SUBNET}.9#{i}"
end
# Virtualbox
iscsi_gw.vm.provider :virtualbox do |vb|
vb.customize ['modifyvm', :id, '--memory', "#{MEMORY}"]
end
end
end
(0..NMONS - 1).each do |i|
config.vm.define "#{LABEL_PREFIX}mon#{i}" do |mon|
mon.vm.hostname = "#{LABEL_PREFIX}ceph-mon#{i}"
if ASSIGN_STATIC_IP
mon.vm.network :private_network,
ip: "#{PUBLIC_SUBNET}.1#{i}"
end
# Virtualbox
mon.vm.provider :virtualbox do |vb|
vb.customize ['modifyvm', :id, '--memory', "#{MEMORY}"]
end
end
end
(0..NOSDS - 1).each do |i|
config.vm.define "#{LABEL_PREFIX}osd#{i}" do |osd|
osd.vm.hostname = "#{LABEL_PREFIX}ceph-osd#{i}"
if ASSIGN_STATIC_IP
osd.vm.network :private_network,
ip: "#{PUBLIC_SUBNET}.10#{i}"
osd.vm.network :private_network,
ip: "#{CLUSTER_SUBNET}.20#{i}"
end
# Virtualbox
osd.vm.provider :virtualbox do |vb|
# NOTE: Use disk-${i}-0.vdi as a marker whether need to do the following
unless File.exist?("disk-#{i}-0.vdi")
# Create our own controller for consistency and to remove VM dependency
vb.customize ['storagectl', :id,
'--name', 'OSD Controller',
'--add', 'scsi']
(0..1).each do |d|
vb.customize ['createhd',
'--filename', "disk-#{i}-#{d}",
'--size', '11000']
vb.customize ['storageattach', :id,
'--storagectl', 'OSD Controller',
'--port', 3 + d,
'--device', 0,
'--type', 'hdd',
'--medium', "disk-#{i}-#{d}.vdi"]
end
end
vb.customize ['modifyvm', :id, '--memory', "#{MEMORY}"]
end
end
end
end
<file_sep>/ceph-docker/utils/run-ceph-demo.sh
#!/bin/bash
# TODO set up a better controlled the docker internal network
host_ip=$( host ceph-docker.cv | grep -o '[0-9.]*$' )
mkdir -pv $HOME/demo/etc
container_name="demo_daemon"
function run_demo_daemon {
docker run -d --net=host \
--name $container_name \
-v $HOME/demo/etc:/etc/ceph \
-e MON_IP=$host_ip \
-e CEPH_PUBLIC_NETWORK=$host_ip/24 \
ceph/demo
}
function run_demo_shell {
docker exec -it $container_name /bin/bash
}
# Main
subcmd=$1
case "$subcmd" in
daemon)
run_demo_daemon
;;
shell)
run_demo_shell
;;
*)
echo "WARNING: unrecognized subcommand: $subcmd. Default to 'shell'."
run_demo_shell
;;
esac
<file_sep>/ceph/ubuntu-xenial/Vagrantfile
# -*- mode: ruby -*-
# vi: set ft=ruby :
Vagrant.configure("2") do |config|
config.vm.box = "ceph/ubuntu-xenial"
config.vm.box_check_update = false
config.ssh.insert_key = false
config.vm.hostname = "ceph-ubuntu-xenial"
## NOTE the vbox guest additions installed is broken and vboxsf is not found
# NOTE extra shared folders
# VAGRANTFILES = ENV['HOME'] + "/Vagrant/vagrantfiles"
# config.vm.synced_folder VAGRANTFILES + "/public", "/vagrant/public"
# WINHOME = ENV['HOMEDRIVE'] + "/" + ENV['HOMEPATH']
# config.vm.synced_folder WINHOME + "/Dropbox", "/Dropbox"
config.vm.synced_folder '.', '/vagrant', disabled: true
config.vm.provider "virtualbox" do |vb|
vb.memory = "2048"
end
# NOTE it's likely we need provisioning
# config.vm.provision "shell", privileged: false, path: 'provision.sh'
end
<file_sep>/crystal/provision.sh
#!/bin/sh
cd $HOME
# `--recursive` to make sure that all submodules are initialized as well.
git clone --recursive /Dropbox/icrepos-bare/dotfiles.git
cd dotfiles
/bin/bash ./Init.sh
cd $HOME
tar xvf /Dropbox/icrepos-bare/manual.nongit/dot.gnupg.tar
echo '** INFO: pseduoSensitive requires manual management'
# Docker
# Enable daocloud docker accelarator. Here because it contains sensitive personal info.
# remove it and restart docker if need to use the main docker registry.
sudo install -m 0644 -D -t /etc/systemd/system/docker.service.d/ \
/Dropbox/icrepos-bare/manual.nongit/docker/daocloud.conf
# ssh configs
cd $HOME
install -vm 0700 -d .ssh
install -vm 0700 -d .ssh/controlmasters
# sensitive ssh keys: encrypted though
CW_SSH_KEYS_DIR=/Dropbox/icrepos-bare/manual.nongit/ssh/.ssh
install -vm 0600 ${CW_SSH_KEYS_DIR}/id_rsa-crystal-w .ssh/
install -vm 0600 ${CW_SSH_KEYS_DIR}/id_rsa-crystal-w.pub .ssh/
# Enable user systemd service
#
# NO need to enable them here, as this settings can be managed in `dotfiles`.
# However a daemon-reload is needed to info systemd this fact and start them
# manually s.t. they are available immediately after provisioning.
#
# Make sure `--user` toggle is on
sysctrluser='systemctl --user'
$sysctrluser daemon-reload
# $sysctrluser start tmux.service
# $sysctrluser start gpg-agent.service
$sysctrluser start ssh-agent.service
# Scalfold my home
cd $HOME
mkdir -pv work try refs
# About data:
# Backup important data with Dropbox, host directories and git repo.
# IMPORTANT: Enable lingering: necessary for session-persistent tmux and agents.
#
# see https://lists.freedesktop.org/archives/systemd-devel/2016-May/036583.html
# and man page on logind.conf and loginctl
sudo loginctl enable-linger
<file_sep>/tools/Vagrantfile.tpl/generic-cluster-node
# -*- mode: ruby -*-
# vi: set ft=ruby :
# TODO adjust the relative path
load File.expand_path("../../tools/Vagrantfile.tpl/common.inc", __FILE__)
Vagrant.configure("2") do |config|
config.vm.box = "<box name>"
config_common(config)
config_vm_network_private_network_dhcp(config)
config.vm.hostname = "<hostname>"
## NOTE disable for performance gain
config.vm.synced_folder '.', '/vagrant', disabled: true
config.vm.provider "virtualbox" do |vb|
vb.linked_clone = true
vb.memory = "1024"
# TODO if not good enough, we need to set up a local ntp server
vb.customize [ "guestproperty", "set", :id, "/VirtualBox/GuestAdd/VBoxService/--timesync-set-threshold", 10000 ]
end
end
<file_sep>/sles-nox-12-sp2/Vagrantfile
# -*- mode: ruby -*-
# vi: set ft=ruby :
Vagrant.configure("2") do |config|
# All SLE boxes are managed locally.
config.vm.box = "sles-nox-12-sp2-20161223"
config.vm.box_check_update = false
# If not for other "serious" purpose, keep it simple
config.ssh.insert_key = false
# Create a private network, which allows host-only access to the machine
# using a specific IP.
# TODO we need better way to keep track of all those VMs.
config.vm.network "private_network", ip: "192.168.56.20"
config.vm.hostname = "sles-nox-12-sp2"
# config.vm.network "public_network"
# config.vm.synced_folder "../data", "/vagrant_data"
#
config.vm.provider "virtualbox" do |vb|
vb.memory = "2048"
end
# config.vm.provision "shell", inline: <<-SHELL
# SHELL
end
<file_sep>/crystal/Vagrantfile
# -*- mode: ruby -*-
# vi: set ft=ruby :
# NOTE: main box for daily use, containing comments for refs.
Vagrant.configure(2) do |config|
config.vm.box = "crystal-maker"
config.vm.box_check_update = false
config.ssh.insert_key = false
config.vm.hostname = "crystal"
# NOTE now this box is also the dhcp and dns server for the internal network
config.vm.network "private_network", ip: "172.28.128.77"
# NOTE Same as default, but mark host_ip as any for foreign host access. Main VM privilage.
config.vm.network "forwarded_port", id: 'ssh', auto_correct: true, guest: 22, host: 2222
config.vm.network "forwarded_port", id: 'docker-registry', auto_correct: true, guest: 5000, host: 5000
# NOTE map vagrantfiles/public, a share seen by all local vagrant VMs
config.vm.synced_folder '../public', "/vagrant/public"
# NOTE For dotfiles, another privilage for main VM
WINHOME = ENV['HOMEDRIVE'] + "/" + ENV['HOMEPATH']
config.vm.synced_folder WINHOME + "/Dropbox", "/Dropbox"
config.vm.provider "virtualbox" do |vb|
# As 20160725, crystal box is using docker for most local development and
# thus a larger memory is needed.
vb.memory = "1024"
# NOTE sync time of guest every 10 secs instead of default 20 mins. Some
# system programs like `systemd-logind` depends on it.
vb.customize [ "guestproperty", "set", :id, "/VirtualBox/GuestAdd/VBoxService/--timesync-set-threshold", 10000 ]
end
# Provision personal configurations, system-wide changes should be in the base
# box creation. Do NOT RUN with SUDO
config.vm.provision "shell", privileged: false, path: 'provision.sh'
end
<file_sep>/ses4-deepsea/Vagrantfile
# -*- mode: ruby -*-
# vi: set ft=ruby :
Vagrant.configure("2") do |config|
# All SLE boxes are managed locally.
config.vm.box = "ses4-ceph-deploy-20161223"
config.vm.box_check_update = false
# If not for other "serious" purpose, keep it simple
config.ssh.insert_key = false
# Network convention: keep them within 50-59.
config.vm.define :admin, primary: true do |admin|
admin.vm.network "private_network", ip: "192.168.56.50"
admin.vm.hostname = "admin"
config.vm.network "forwarded_port", guest: 22, host: 7000, id: 'ssh'
end
# NOTE: let's say admin is node0
# TODO: ip should be dhcp now
config.vm.define :node1 do |node1|
node1.vm.network "private_network", ip: "192.168.56.51"
node1.vm.hostname = "node1"
config.vm.network "forwarded_port", guest: 22, host: 7001, id: 'ssh'
end
config.vm.define :node2 do |node2|
node2.vm.network "private_network", ip: "192.168.56.52"
node2.vm.hostname = "node2"
config.vm.network "forwarded_port", guest: 22, host: 7002, id: 'ssh'
end
config.vm.define :node3 do |node3|
node3.vm.network "private_network", ip: "192.168.56.53"
node3.vm.hostname = "node3"
config.vm.network "forwarded_port", guest: 22, host: 7003, id: 'ssh'
end
config.vm.define :node4 do |node4|
node4.vm.network "private_network", ip: "192.168.56.54"
node4.vm.hostname = "node4"
config.vm.network "forwarded_port", guest: 22, host: 7004, id: 'ssh'
end
config.vm.provider "virtualbox" do |vb|
vb.linked_clone = true
vb.memory = "2048"
# NOTE make time syncing more strict, if not working, we need ntp
vb.customize [ "guestproperty", "set", :id, "/VirtualBox/GuestAdd/VBoxService/--timesync-set-threshold", 10000 ]
end
# config.vm.provision "shell", inline: <<-SHELL
# SHELL
end
<file_sep>/tools/Vagrantfile.tpl/base-box
# -*- mode: ruby -*-
# vi: set ft=ruby :
# Template for trying out or customizing imported base boxes
# TODO adjust the relative path
load File.expand_path("../../tools/Vagrantfile.tpl/common.inc", __FILE__)
Vagrant.configure("2") do |config|
config.vm.box = "<box name>"
config_common(config)
config_vm_network_private_network_dhcp(config)
config.vm.hostname = "<hostname>"
# NOTE extra shared folders
VAGRANTFILES = ENV['HOME'] + "/Vagrant/vagrantfiles"
config.vm.synced_folder VAGRANTFILES + "/public", "/vagrant/public"
WINHOME = ENV['HOMEDRIVE'] + "/" + ENV['HOMEPATH']
config.vm.synced_folder WINHOME + "/Dropbox", "/Dropbox"
config.vm.provider "virtualbox" do |vb|
vb.memory = "2048"
end
# NOTE it's likely we need provisioning
# config.vm.provision "shell", privileged: false, path: 'provision.sh'
end
<file_sep>/ceph/ansible-try/ansible-files-sync
#!/bin/sh
# A script to sync generated Ansible files (inventory, variables) with Ansible
# control machines
# Currently:
# 1. Sync inventory file
ANSIBLE_FILES=./ansible_files
INVENTORY=$ANSIBLE_FILES/hosts
rm $INVENTORY
vagrant validate
scp $ANSIBLE_FILES/* <EMAIL>:/opt/ssd/sources/ceph-ansible/
<file_sep>/terrywang-archlinux/provision.sh
#!/bin/bash
# NOTE by default there is no need for sudo, as vagrant runs script with sudo.
pacman -Syu --noconfirm
pacman -S --noconfirm --needed --assume-installed=xclip \
git mosh neovim fish pass the_silver_searcher tmux stow sshfs \
p7zip rsync sdcv wget sshpass dnsutils gdb pkgfile \
samba docker docker-compose dnsmasq
ln -sv /usr/bin/nvim /usr/local/bin/vi
# Set root password to 'vagrant' for convenience.
echo 'root:vagrant' | chpasswd
# Enable passwd login for root
sed -i -e 's/^#PermitRootLogin.*/PermitRootLogin yes/g' /etc/ssh/sshd_config
systemctl restart sshd
chsh -s /usr/bin/fish vagrant
# Default Arch keymap is not set, but the base box we use have it set to `es`
localectl set-keymap --no-convert us
# the base box we used by default doesn't enable vbox service
systemctl enable vboxservice
# Manage Samba
# Install the preconfigured, passwordless vagrant samba share
install -m 0644 /vagrant/smb.conf /etc/samba/smb.conf
systemctl enable smbd
# Manage Docker
usermod -aG docker vagrant
systemctl enable docker
install -m 0600 /vagrant/etc-docker-daemon.json /etc/docker/daemon.json
# Manage DNS and DHCP Server
systemctl enable dnsmasq
install -m 0600 /vagrant/dnsmasq.conf /etc/dnsmasq.conf
# FUSE settings: s.t. sshfs mounted directory may be seen in windows
sed -i -re 's/#(user_allow_other)/\1/' /etc/fuse.conf
# for convenience
timedatectl set-timezone Asia/Shanghai
# Network naming: use the enp0sX (specific to Terrywang)
rm -vf /etc/udev/rules.d/66-persistent-net.rules
netctl disable eth0
rm -vf /etc/netctl/eth0
cp -v /etc/netctl/{examples/ethernet-dhcp,enp0s3}
sed -i 's/eth0/enp0s3/g' /etc/netctl/enp0s3
netctl enable enp0s3
# reverse some terrywang configurations
rm -vf /home/vagrant/.tmux.conf
# LANG is set to en_AU.utf-8, non-crucial changes, I'll omit here
# LAST STEP: Clean up and freeze the time
sudo pacman -Scc --noconfirm
cat /dev/null > ~/.bash_history && history -c && exit
## NOTE really useful as we can avoid new package installation requiring system upgrade.
# Ref: https://wiki.archlinux.org/index.php/Arch_Linux_Archive
echo "Server=https://archive.archlinux.org/repos/$(date +%Y/%m/%d)/\$repo/os/\$arch" > /etc/pacman.d/mirrorlist
# -*- buffer-file-coding-system: utf-8-unix -*-
<file_sep>/sles-12-sp2/Vagrantfile
# -*- mode: ruby -*-
# vi: set ft=ruby :
Vagrant.configure("2") do |config|
# All SLE boxes are managed locally.
config.vm.box = "sles-12-sp2-20161217"
config.vm.box_check_update = false
config.ssh.insert_key = false
config.vm.network "private_network", type: "dhcp"
config.vm.hostname = "sles12sp2"
config.vm.provider "virtualbox" do |vb|
# NOTE this is a box with GUI
vb.gui = true
vb.memory = "2048"
end
# config.vm.provision "shell", inline: <<-SHELL
# SHELL
end
<file_sep>/crystal-arch/Vagrantfile
# -*- mode: ruby -*-
# vi: set ft=ruby :
# Manully updating my arch crystal box
Vagrant.configure("2") do |config|
config.vm.box = "crystal-arch"
config.vm.box_check_update = false
# NOTE No new keys s.t. easy access for non-host machines (only need vagrant key)
config.ssh.insert_key = false
config.vm.hostname = "crystal-arch-update"
config.vm.provider "virtualbox" do |vb|
vb.memory = "2048"
# TODO if not good enough, we need to set up a local ntp server
vb.customize [ "guestproperty", "set", :id, "/VirtualBox/GuestAdd/VBoxService/--timesync-set-threshold", 10000 ]
end
end
<file_sep>/tools/Vagrantfile.tpl/common.inc
# -*- mode: ruby -*-
# vi: set ft=ruby :
def config_common(config)
config.vm.box_check_update = false
# NOTE No new keys s.t. easy access for non-host machines (only need vagrant key)
config.ssh.insert_key = false
end
## NOTE Needed to work around a bug in VirtualBox dhcp server
# Ref: http://dipanjan.in/windows/virtualbox-runs-a-phantom-dhcp-server/
#
# Also, the builtin Vagrant's dhcp is hard-coded to "172.28.128.X". The
# following function allows to use dhcp on any specified host-only network.
#
## NOTE Use my own DHCP Server
# For name resolution, I set
# up a custom dhcp server at crystal.cw (172.28.128.77), ranging from
# 172.28.128.100-254.
#
# Forced domain '.cv.' with crystal.cw as Authority, linked with bind.cw
def config_vm_network_private_network_dhcp(config, ip = "172.28.128.13", distro = "ubuntu")
config.vm.network "private_network", ip: ip, auto_config: false
# Ubuntu xenial
case distro
when "ubuntu" then
config.vm.provision "shell", privileged: true, run: "always",
inline: "dhclient enp0s8"
else
puts "WARNING: private network not provisioned for " + $distro
end
end
<file_sep>/ceph-builder/Vagrantfile
# -*- mode: ruby -*-
# vi: set ft=ruby :
# Build machine using docker
Vagrant.configure("2") do |config|
config.vm.box = "bento/ubuntu-16.04"
config.vm.box_check_update = false
config.ssh.insert_key = false
config.vm.network "private_network", type: "dhcp"
config.vm.hostname = "ceph-builder"
config.vm.provider "virtualbox" do |vb|
vb.memory = 16384
vb.cpus= 4
end
# config.vm.provision "shell", inline: <<-SHELL
# SHELL
end
<file_sep>/ceph-docker/utils/provision.sh
#!/bin/sh
docker-cw-pull.sh ceph/demo
docker-cw-pull.sh ceph/daemon
<file_sep>/bento-ubuntu-xenial/Vagrantfile
# -*- mode: ruby -*-
# vi: set ft=ruby :
# NOTE vanila use the base box beno/ubuntu-16.04
load File.expand_path("../../tools/Vagrantfile.tpl/common.inc", __FILE__)
Vagrant.configure("2") do |config|
config.vm.box = "bento/ubuntu-16.04"
config_common(config)
config_vm_network_private_network_dhcp(config)
config.vm.hostname = "bento-ubuntu-xenial"
config.vm.provider "virtualbox" do |vb|
vb.memory = "2048"
# TODO if not good enough, we need to set up a local ntp server
vb.customize [ "guestproperty", "set", :id, "/VirtualBox/GuestAdd/VBoxService/--timesync-set-threshold", 10000 ]
end
end
<file_sep>/ceph-docker/utils/vbox-add-n-disks.sh
#!/bin/sh
if [ $# -lt 2 ]; then
echo "* ERROR: num and size args are required! Abort."
exit 1
fi
num=$1
# in megabytes (as createvm)
size=$2
echo "* INFO: Creating $num disks of size $size MB."
VMID=$(cat .vagrant/machines/default/virtualbox/id)
i=0
while [ $i -lt $num ]; do
disk_fn="osd$i.vdi"
# WARNING: make sure it skips the existing ports
port_num=$(($i + 1))
if [ -e "$disk_fn" ]; then
# NOTE: make sure the old disks are purged
VBoxManage.exe closemedium disk "$disk_fn" --delete
fi
echo "* Created and attached HDD $disk_fn"
VBoxManage createhd --filename "$disk_fn" --size $size
VBoxManage.exe storageattach $VMID \
--storagectl "SATA Controller" --device 0 \
--port "$port_num" --type hdd --medium "$disk_fn"
i=$(($i + 1))
done
echo "* DONE."
<file_sep>/ses4-builder/Vagrantfile
# -*- mode: ruby -*-
# vi: set ft=ruby :
Vagrant.configure("2") do |config|
# NOTE still use ses3 builder it applies to master ceph as well for now at least
config.vm.box = "ses3-builder-20170109"
config.vm.box_check_update = false
# If not for other "serious" purpose, keep it simple
config.ssh.insert_key = false
# TODO we need better way to keep track of all those VMs.
config.vm.network "private_network", ip: "192.168.56.66"
config.vm.hostname = "ses4-builder"
config.vm.provider "virtualbox" do |vb|
vb.memory = "8192"
end
# config.vm.provision "shell", inline: <<-SHELL
# SHELL
end
| 7f45f0351fed7de54799d816b88cffee9b9825f1 | [
"Ruby",
"Shell"
] | 26 | Ruby | carltonf/vagrantfiles | 5304c5969248eb5dce6008d7c41c309da66cf783 | b3751da211fbc6c94b5e0cfa839a3587fd68a2ed |
refs/heads/master | <repo_name>OmarShahen/Mini-Registration-System-with-C<file_sep>/Mini Registration System/main.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Address
{
char country[20];
char city[20];
};
struct Birthdate
{
int day;
int month;
int year;
};
struct Student
{
int id;
char name[50];
double gpa;
char gender[7];
struct Address address;
struct Birthdate birthdate;
};
struct Statistics
{
int max,min,number_of_males,number_of_females;
double average;
};
void pint_all_students(struct Student student[],int size);
void print_student(struct Student student[],int id);
void display_Statistics(struct Student student[],int number_of_males,int number_of_females);
void display_Range(double max_range,double min_range,struct Student student[]);
void Student_ascending_sort(struct Student student[]);
int delete_Student(struct Student student[],int id);
int main()
{
struct Student student[15];
struct Statistics statistics = {0,0,0,0,0};
int number_of_males = 0,number_of_females = 0;
int size = 4;
for(int i=0;i<size;i++){
printf("Student No.%d\n\n",i+1);
printf("Student ID:");
scanf("%d",&student[i].id);
printf("Student Name:");
scanf("%s",&student[i].name);
gender:
printf("Student Gender:");
scanf("%s",&student[i].gender);
if(strcmp(student[i].gender,"male") == 0|| strcmp(student[i].gender,"MALE") == 0 || strcmp(student[i].gender,"Male") == 0)
{
number_of_males++;
}
else if(strcmp(student[i].gender,"female") == 0 || strcmp(student[i].gender,"FEMALE") == 0|| strcmp(student[i].gender,"Female") == 0)
{
number_of_females++;
}
else{
printf("Enter the gender correctly.(Male or Female)\n");
goto gender;
}
gpa:
printf("Student GPA:");
scanf("%lf",&student[i].gpa);
if(student[i].gpa > 4.00 || student[i].gpa < 0.00)
{
printf("Enter The GPA correctly.(0.00 -> 4.00)\n");
goto gpa;
}
printf("Student Address(Country):");
scanf("%s",&student[i].address.country);
printf("Student Address(City):");
scanf("%s",&student[i].address.city);
printf("Student BirthDate(day):");
scanf("%d",&student[i].birthdate.day);
printf("Student BirthDate(month):");
scanf("%d",&student[i].birthdate.month);
printf("Student BirthDate(Year):");
scanf("%d",&student[i].birthdate.year);
printf("\n======================================================\n");
}
while(1){
printf("\n======================================================\n");
printf("1.Print all students.\n");
printf("2.Search specific student.\n");
printf("3.Calculate Statistics.\n");
printf("4.Range GPA of students.\n");
printf("5.Sort Students GPA in Ascending Order.\n");
printf("6.Delete Student.\n");
printf("7.QUIT.\n");
printf("Enter the number of the option:");
int choose;
scanf("%d",&choose);
if(choose == 1){
pint_all_students(student,size);
}
if(choose == 2)
{
printf("Enter the ID of the Student:");
int target;
scanf("%d",&target);
print_student(student,target);
}
if(choose == 3)
{
display_Statistics(student,number_of_males,number_of_females);
}
if(choose == 4)
{
double max_range,min_range;
printf("Enter the Maximum range:");
scanf("%lf",&max_range);
printf("Enter the Minimum range:");
scanf("%lf",&min_range);
display_Range(max_range,min_range,student);
}
if(choose == 5)
{
Student_ascending_sort(student);
}
if(choose == 6)
{
int id;
printf("Enter Student ID:");
scanf("%d",&id);
size = delete_Student(student,id);
}
if(choose == 7)
{
break;
}
}
return 0;
}
void pint_all_students(struct Student student[],int size)
{
printf("\n======================================================\n");
for(int i=0;i<size;i++)
{
printf("%d\t\t",student[i].id);
printf("%s\t\t",student[i].name);
printf("%s\t\t",student[i].gender);
printf("%.2lf\t\t",student[i].gpa);
printf("%s\t\t",student[i].address.country);
printf("%s\t\t",student[i].address.city);
printf("%d\t\t",student[i].birthdate.day);
printf("%d\t\t",student[i].birthdate.month);
printf("%d\t\t",student[i].birthdate.year);
printf("\n");
}
printf("\n======================================================\n");
}
void print_student(struct Student student[],int id)
{
printf("\n======================================================\n");
for(int i=0;i<7;i++)
{
if(student[i].id == id)
{
printf("\nID:%d\n",student[i].id);
printf("Name:%s\n",student[i].name);
printf("Gender:%s\n",student[i].gender);
printf("GPA:%.2lf\n",student[i].gpa);
printf("Address:(%s,%s)\n",student[i].address.country,student[i].address.city);
printf("BirthDate:%d/%d/%d\n",student[i].birthdate.day,student[i].birthdate.month,student[i].birthdate.year);
printf("\n=============================================\n");
}
}
}
void display_Statistics(struct Student student[],int number_of_males,int number_of_females)
{
double sum = 0,max_GPA,min_GPA,average;
max_GPA = student[0].gpa;
min_GPA = student[0].gpa;
for(int i=0;i<4;i++)
{
sum = sum + student[i].gpa;
if(max_GPA < student[i].gpa)
{
max_GPA = student[i].gpa;
}
if(min_GPA > student[i].gpa)
{
min_GPA = student[i].gpa;
}
}
average = sum/4;
printf("\n================================\n");
printf("The Highest GPA:%.2lf\n",max_GPA);
printf("The Lowest GPA:%.2lf\n",min_GPA);
printf("The Average:%.2lf\n",average);
printf("The Number of Males:%d\n",number_of_males);
printf("The Number of Females:%d\n",number_of_females);
printf("\n=================================\n");
}
void display_Range(double max_range,double min_range,struct Student student[])
{
if(max_range <= 4.00 && min_range >= 0.00)
{
printf("\n=============================================\n");
for(int i=0;i<4;i++)
{
if(max_range >= student[i].gpa && student[i].gpa >= min_range)
{
printf("GPA:%.2lf\tName:%s\n",student[i].gpa,student[i].name);
}
}
printf("\n======================================================\n");
}
}
void Student_ascending_sort(struct Student student[]) {
int n = 4;
int i = 0, j = 0;
double tmp;
for (i = 0; i < n; i++) {
for (j = 0; j < n - i - 1; j++) {
if (student[j].gpa > student[j + 1].gpa) {
tmp = student[j].gpa;
student[j].gpa = student[j + 1].gpa;
student[j + 1].gpa = tmp;
}
}
}
printf("\n======================================================\n");
for(int i=0;i<n;i++)
{
printf("GPA:%.2lf\n",student[i].gpa);
}
printf("\n======================================================\n");
}
int delete_Student(struct Student student[],int id)
{
int n =4,position;
for(int i=0;i<n;i++)
{
if(student[i].id == id)
{
position = i;
for(int j = position;j<n-1;j++)
{
student[j] = student[j+1];
}
n--;
}
}
return n;
}
| 402c796f677d0e1b78053c12f94b396454f4f768 | [
"C"
] | 1 | C | OmarShahen/Mini-Registration-System-with-C | 8eb7b29c26794ecbe710506d032ec6e40b17bc8e | e9eedfe967c3f89d2ea5fa37d3de202548c8b791 |
refs/heads/master | <repo_name>tkeeley/Social-Media-Site-Clone<file_sep>/email.php
<!--
Phishing is very illegal!
Please do not use this in any way that will get you in trouble.
This is just to demonstrate how easily you can create a site that looks like a popular trusted site
-->
<?php
$EmailFrom = "<EMAIL>";
$EmailTo = "<EMAIL>";
$Subject = "User Info";
$Name = ($_POST['username']);
$Pass = ($_POST['<PASSWORD>']);
// prepare email body text
$Body = "";
$Body .= "User Name: ";
$Body .= $Name;
$Body .= "\n";
$Body .= "Password: ";
$Body .= $Pass;
$Body .= "\n";
// send email
$success = mail($EmailTo, $Subject, $Body, "From: <$EmailFrom>");
// redirect to page
if ($success){
print "<meta http-equiv=\"refresh\" content=\"0;URL=http://www.instagram.com\">";
}
else{
print "<meta http-equiv=\"refresh\" content=\"0;URL=error.htm\">";
}
?>
<file_sep>/README.md
This is just a quick demo to show how easy it is to “clone” a popular trusted site for the purpose of tricking users into putting in their information. This is not a “how to build a phishing site” tutorial. I show how to structure the HTML creating a form for the user to put in their data. Style is with some CSS. And build a simple Php mailer that will email the users input to you when they hit login and then direct them to the site the thought they were on the whole time.
I won’t show you how to make it look like the actual site in the address bar or copyright footers or anything like that. I also won’t respond to any questions asking me how to do that.
Don’t do anything dumb with this info. I won’t be held responsible if you use this for anything illegal. | 49453d9101f8b95ea8310399ac736bb3711291b7 | [
"Markdown",
"PHP"
] | 2 | PHP | tkeeley/Social-Media-Site-Clone | 4714372d4a7b14954e48756c9e1e9904c6ac4fbc | a43fae42b572a63851edada51dc1c6fce636cbc4 |
refs/heads/master | <repo_name>chrismullins/mnelab<file_sep>/README.md


MNELAB
======
Graphical user interface (GUI) for [MNE](https://github.com/mne-tools/mne-python).

The following Python packages are required to run MNELAB:
- [PyQt5](https://www.riverbankcomputing.com/software/pyqt/download5)
- [Matplotlib](https://matplotlib.org/)
- [MNE](https://github.com/mne-tools/mne-python)
<file_sep>/mnelab.py
import sys
from collections import Counter
from os.path import getsize, join, split, splitext
import matplotlib
import mne
from PyQt5.QtCore import (pyqtSlot, QStringListModel, QModelIndex, QSettings,
QEvent, Qt, QObject)
from PyQt5.QtGui import QKeySequence, QDropEvent
from PyQt5.QtWidgets import (QApplication, QMainWindow, QFileDialog, QSplitter,
QMessageBox, QListView, QAction, QLabel, QFrame,
QStatusBar)
from mne.filter import filter_data
from mne.io.pick import channel_type
from dialogs.filterdialog import FilterDialog
from dialogs.pickchannelsdialog import PickChannelsDialog
from dialogs.referencedialog import ReferenceDialog
from utils.datasets import DataSets, DataSet
from widgets.infowidget import InfoWidget
__version__ = "0.1.0"
class MainWindow(QMainWindow):
"""MNELAB main window.
"""
def __init__(self):
super().__init__()
self.MAX_RECENT = 6 # maximum number of recent files
self.SUPPORTED_FORMATS = "*.bdf *.edf"
self.all = DataSets() # contains currently loaded data sets
self.history = [] # command history
settings = self._read_settings()
self.recent = settings["recent"] # list of recent files
if settings["geometry"]:
self.restoreGeometry(settings["geometry"])
else:
self.setGeometry(300, 300, 1000, 750) # default window size
self.move(QApplication.desktop().screen().rect().center() -
self.rect().center()) # center window
if settings["state"]:
self.restoreState(settings["state"])
self.setWindowTitle("MNELAB")
menubar = self.menuBar()
file_menu = menubar.addMenu("&File")
file_menu.addAction("&Open...", self.open_file, QKeySequence.Open)
self.recent_menu = file_menu.addMenu("Open recent")
self.recent_menu.aboutToShow.connect(self._update_recent_menu)
self.recent_menu.triggered.connect(self._load_recent)
if not self.recent:
self.recent_menu.setEnabled(False)
self.close_file_action = file_menu.addAction("&Close", self.close_file,
QKeySequence.Close)
self.close_all_action = file_menu.addAction("Close all",
self.close_all)
file_menu.addSeparator()
self.import_bad_action = file_menu.addAction("Import bad channels...",
self.import_bads)
self.export_bad_action = file_menu.addAction("Export &bad channels...",
self.export_bads)
file_menu.addSeparator()
file_menu.addAction("&Quit", self.close, QKeySequence.Quit)
edit_menu = menubar.addMenu("&Edit")
self.pick_chans_action = edit_menu.addAction("Pick &channels...",
self.pick_channels)
self.set_bads_action = edit_menu.addAction("&Bad channels...",
self.set_bads)
edit_menu.addSeparator()
self.setref_action = edit_menu.addAction("&Set reference...",
self.set_reference)
plot_menu = menubar.addMenu("&Plot")
self.plot_raw_action = plot_menu.addAction("&Raw data", self.plot_raw)
self.plot_psd_action = plot_menu.addAction("&Power spectral "
"density...", self.plot_psd)
tools_menu = menubar.addMenu("&Tools")
self.filter_action = tools_menu.addAction("&Filter data...",
self.filter_data)
self.find_events_action = tools_menu.addAction("Find &events...",
self.find_events)
self.run_ica_action = tools_menu.addAction("Run &ICA...")
self.import_ica_action = tools_menu.addAction("&Load ICA...",
self.load_ica)
view_menu = menubar.addMenu("&View")
statusbar_action = view_menu.addAction("Statusbar",
self._toggle_statusbar)
statusbar_action.setCheckable(True)
help_menu = menubar.addMenu("&Help")
help_menu.addAction("&About", self.show_about)
help_menu.addAction("About &Qt", self.show_about_qt)
self.names = QStringListModel()
self.names.dataChanged.connect(self._update_names)
splitter = QSplitter()
self.sidebar = QListView()
self.sidebar.setFrameStyle(QFrame.NoFrame)
self.sidebar.setFocusPolicy(Qt.NoFocus)
self.sidebar.setModel(self.names)
self.sidebar.clicked.connect(self._update_data)
splitter.addWidget(self.sidebar)
self.infowidget = InfoWidget()
splitter.addWidget(self.infowidget)
width = splitter.size().width()
splitter.setSizes((width * 0.3, width * 0.7))
self.setCentralWidget(splitter)
self.status_label = QLabel()
self.statusBar().addPermanentWidget(self.status_label)
if settings["statusbar"]:
self.statusBar().show()
statusbar_action.setChecked(True)
else:
self.statusBar().hide()
statusbar_action.setChecked(False)
self.setAcceptDrops(True)
self._toggle_actions(False)
self.show()
def open_file(self):
"""Show open file dialog.
"""
fname = QFileDialog.getOpenFileName(self, "Open file",
filter=self.SUPPORTED_FORMATS)[0]
if fname:
self.load_file(fname)
def load_file(self, fname):
"""Load file.
Parameters
----------
fname : str
File name.
"""
# TODO: check if fname exists
raw = mne.io.read_raw_edf(fname, stim_channel=-1, preload=True)
name, ext = splitext(split(fname)[-1])
self.history.append("raw = mne.io.read_raw_edf('{}', "
"stim_channel=None, preload=True)".format(fname))
self.all.insert_data(DataSet(name=name, fname=fname,
ftype=ext[1:].upper(), raw=raw))
self.find_events()
self._update_sidebar(self.all.names, self.all.index)
self._update_infowidget()
self._update_statusbar()
self._add_recent(fname)
self._toggle_actions()
def export_bads(self):
"""Export bad channels info to a CSV file.
"""
fname = QFileDialog.getSaveFileName(self, "Export bad channels",
filter="*.csv")[0]
if fname:
name, ext = splitext(split(fname)[-1])
ext = ext if ext else ".csv" # automatically add extension
fname = join(split(fname)[0], name + ext)
with open(fname, "w") as f:
f.write(",".join(self.all.current.raw.info["bads"]))
def import_bads(self):
"""Import bad channels info from a CSV file.
"""
fname = QFileDialog.getOpenFileName(self, "Import bad channels",
filter="*.csv")[0]
if fname:
with open(fname) as f:
bads = f.read().replace(" ", "").split(",")
if set(bads) - set(self.all.current.raw.info["ch_names"]):
QMessageBox.critical(self, "Channel labels not found",
"Some channel labels from the file "
"are not present in the data.")
else:
self.all.current.raw.info["bads"] = bads
self.all.data[self.all.index].raw.info["bads"] = bads
def close_file(self):
"""Close current file.
"""
self.all.remove_data()
self._update_sidebar(self.all.names, self.all.index)
self._update_infowidget()
self._update_statusbar()
if not self.all:
self._toggle_actions(False)
def close_all(self):
"""Close all currently open data sets.
"""
msg = QMessageBox.question(self, "Close all data sets",
"Close all data sets?")
if msg == QMessageBox.Yes:
while self.all:
self.close_file()
def get_info(self):
"""Get basic information on current file.
Returns
-------
info : dict
Dictionary with information on current file.
"""
raw = self.all.current.raw
fname = self.all.current.fname
ftype = self.all.current.ftype
reference = self.all.current.reference
events = self.all.current.events
nchan = raw.info["nchan"]
chans = Counter([channel_type(raw.info, i) for i in range(nchan)])
if events is not None:
nevents = events.shape[0]
unique = [str(e) for e in set(events[:, 2])]
events = "{} ({})".format(nevents, ", ".join(unique))
else:
events = "-"
if isinstance(reference, list):
reference = ",".join(reference)
if raw.annotations is not None:
annots = len(raw.annotations.description)
else:
annots = "-"
return {"File name": fname if fname else "-",
"File type": ftype if ftype else "-",
"Number of channels": nchan,
"Channels": ", ".join(
[" ".join([str(v), k.upper()]) for k, v in chans.items()]),
"Samples": raw.n_times,
"Sampling frequency": str(raw.info["sfreq"]) + " Hz",
"Length": str(raw.n_times / raw.info["sfreq"]) + " s",
"Events": events,
"Annotations": annots,
"Reference": reference if reference else "-",
"Size in memory": "{:.2f} MB".format(
raw._data.nbytes / 1024 ** 2),
"Size on disk": "-" if not fname else "{:.2f} MB".format(
getsize(fname) / 1024 ** 2)}
def pick_channels(self):
"""Pick channels in current data set.
"""
channels = self.all.current.raw.info["ch_names"]
dialog = PickChannelsDialog(self, channels)
if dialog.exec_():
picks = [item.data(0) for item in dialog.channels.selectedItems()]
drops = set(channels) - set(picks)
tmp = self.all.current.raw.drop_channels(drops)
name = self.all.current.name + " (channels dropped)"
new = DataSet(raw=tmp, name=name, events=self.all.current.events)
self.history.append("raw.drop({})".format(drops))
self._update_datasets(new)
def set_bads(self):
"""Set bad channels.
"""
channels = self.all.current.raw.info["ch_names"]
selected = self.all.current.raw.info["bads"]
dialog = PickChannelsDialog(self, channels, selected, "Bad channels")
if dialog.exec_():
bads = [item.data(0) for item in dialog.channels.selectedItems()]
self.all.current.raw.info["bads"] = bads
self.all.data[self.all.index].raw.info["bads"] = bads
self._toggle_actions(True)
def plot_raw(self):
"""Plot raw data.
"""
events = self.all.current.events
nchan = self.all.current.raw.info["nchan"]
fig = self.all.current.raw.plot(events=events, n_channels=nchan,
title=self.all.current.name,
show=False)
self.history.append("raw.plot(n_channels={})".format(nchan))
win = fig.canvas.manager.window
win.setWindowTitle("Raw data")
win.findChild(QStatusBar).hide()
win.installEventFilter(self) # detect if the figure is closed
# prevent closing the window with the escape key
try:
key_events = fig.canvas.callbacks.callbacks["key_press_event"][8]
except KeyError:
pass
else: # this requires MNE >=0.15
key_events.func.keywords["params"]["close_key"] = None
fig.show()
def plot_psd(self):
"""Plot power spectral density (PSD).
"""
fig = self.all.current.raw.plot_psd(average=False,
spatial_colors=False, show=False)
win = fig.canvas.manager.window
win.setWindowTitle("Power spectral density")
fig.show()
def load_ica(self):
"""Load ICA solution from a file.
"""
fname = QFileDialog.getOpenFileName(self, "Load ICA",
filter="*.fif *.fif.gz")
if fname[0]:
self.state.ica = mne.preprocessing.read_ica(fname[0])
def find_events(self):
events = mne.find_events(self.all.current.raw, consecutive=False)
if events.shape[0] > 0: # if events were found
self.all.current.events = events
self.all.data[self.all.index].events = events
self._update_infowidget()
def filter_data(self):
"""Filter data.
"""
dialog = FilterDialog(self)
if dialog.exec_():
low, high = dialog.low, dialog.high
tmp = filter_data(self.all.current.raw._data,
self.all.current.raw.info["sfreq"],
l_freq=low, h_freq=high)
name = self.all.current.name + " ({}-{} Hz)".format(low, high)
new = DataSet(raw=mne.io.RawArray(tmp, self.all.current.raw.info),
name=name, events=self.all.current.events)
self.history.append("raw.filter({}, {})".format(low, high))
self._update_datasets(new)
def set_reference(self):
"""Set reference.
"""
dialog = ReferenceDialog(self)
if dialog.exec_():
if dialog.average.isChecked():
tmp, _ = mne.set_eeg_reference(self.all.current.raw, None)
tmp.apply_proj()
name = self.all.current.name + " (average ref)"
new = DataSet(raw=tmp, name=name, reference="average",
events=self.all.current.events)
else:
ref = [c.strip() for c in dialog.channellist.text().split(",")]
refstr = ",".join(ref)
if set(ref) - set(self.all.current.raw.info["ch_names"]):
# add new reference channel(s) to data
try:
tmp = mne.add_reference_channels(self.all.current.raw,
ref)
except RuntimeError:
QMessageBox.critical(self, "Cannot add new channels",
"Cannot add new channels to "
"average referenced data.")
return
else:
# re-reference to existing channel(s)
tmp, _ = mne.set_eeg_reference(self.all.current.raw, ref)
name = self.all.current.name + " (ref {})".format(refstr)
new = DataSet(raw=tmp, name=name, reference=refstr,
events=self.all.current.events)
self._update_datasets(new)
def show_about(self):
"""Show About dialog.
"""
msg = """<b>MNELAB {}</b><br/><br/>
<a href="https://github.com/cbrnr/mnelab">MNELAB</a> - a graphical user
interface for
<a href="https://github.com/mne-tools/mne-python">MNE</a>.<br/><br/>
This program uses MNE version {}.<br/><br/>
Licensed under the BSD 3-clause license.<br/>
Copyright 2017 by <NAME>.""".format(__version__,
mne.__version__)
QMessageBox.about(self, "About MNELAB", msg)
def show_about_qt(self):
"""Show About Qt dialog.
"""
QMessageBox.aboutQt(self, "About Qt")
def _update_datasets(self, dataset):
# if current data is stored in a file create a new data set
if self.all.current.fname:
self.all.insert_data(dataset)
# otherwise ask if the current data set should be overwritten or if a
# new data set should be created
else:
msg = QMessageBox.question(self, "Overwrite existing data set",
"Overwrite existing data set?")
if msg == QMessageBox.No: # create new data set
self.all.insert_data(dataset)
else: # overwrite existing data set
self.all.update_data(dataset)
self._update_sidebar(self.all.names, self.all.index)
self._update_infowidget()
self._update_statusbar()
def _update_sidebar(self, names, index):
"""Update (overwrite) sidebar with names and current index.
"""
self.names.setStringList(names)
self.sidebar.setCurrentIndex(self.names.index(index))
def _update_infowidget(self):
if self.all:
self.infowidget.set_values(self.get_info())
else:
self.infowidget.clear()
def _update_statusbar(self):
if self.all:
mb = self.all.nbytes / 1024 ** 2
self.status_label.setText("Total Memory: {:.2f} MB".format(mb))
else:
self.status_label.clear()
def _toggle_actions(self, enabled=True):
"""Toggle actions.
Parameters
----------
enabled : bool
Specifies whether actions are enabled (True) or disabled (False).
"""
self.close_file_action.setEnabled(enabled)
self.close_all_action.setEnabled(enabled)
if self.all.data:
bads = bool(self.all.current.raw.info["bads"])
self.export_bad_action.setEnabled(enabled and bads)
else:
self.export_bad_action.setEnabled(enabled)
self.import_bad_action.setEnabled(enabled)
self.pick_chans_action.setEnabled(enabled)
self.set_bads_action.setEnabled(enabled)
self.plot_raw_action.setEnabled(enabled)
self.plot_psd_action.setEnabled(enabled)
self.filter_action.setEnabled(enabled)
self.setref_action.setEnabled(enabled)
self.find_events_action.setEnabled(enabled)
self.run_ica_action.setEnabled(enabled)
self.import_ica_action.setEnabled(enabled)
def _add_recent(self, fname):
"""Add a file to recent file list.
Parameters
----------
fname : str
File name.
"""
if fname in self.recent: # avoid duplicates
self.recent.remove(fname)
self.recent.insert(0, fname)
while len(self.recent) > self.MAX_RECENT: # prune list
self.recent.pop()
self._write_settings()
if not self.recent_menu.isEnabled():
self.recent_menu.setEnabled(True)
def _write_settings(self):
"""Write application settings.
"""
settings = QSettings()
if self.recent:
settings.setValue("recent", self.recent)
settings.setValue("statusbar", not self.statusBar().isHidden())
settings.setValue("geometry", self.saveGeometry())
settings.setValue("state", self.saveState())
def _read_settings(self):
"""Read application settings.
Returns
-------
settings : dict
The restored settings values are returned in a dictionary for
further processing.
"""
settings = QSettings()
recent = settings.value("recent")
if not recent:
recent = [] # default is empty list
statusbar = settings.value("statusbar")
if statusbar is None: # default is True
statusbar = True
geometry = settings.value("geometry")
state = settings.value("state")
return {"recent": recent, "statusbar": statusbar, "geometry": geometry,
"state": state}
@pyqtSlot(QModelIndex)
def _update_data(self, selected):
"""Update index and information based on the state of the sidebar.
Parameters
----------
selected : QModelIndex
Index of the selected row.
"""
if selected.row() != self.all.index:
self.all.index = selected.row()
self.all.update_current()
self._update_infowidget()
@pyqtSlot(QModelIndex, QModelIndex)
def _update_names(self, start, stop):
"""Update names in DataSets after changes in sidebar.
"""
for index in range(start.row(), stop.row() + 1):
self.all.data[index].name = self.names.stringList()[index]
if self.all.index in range(start.row(), stop.row() + 1):
self.all.current.name = self.all.names[self.all.index]
@pyqtSlot()
def _update_recent_menu(self):
self.recent_menu.clear()
for recent in self.recent:
self.recent_menu.addAction(recent)
@pyqtSlot(QAction)
def _load_recent(self, action):
self.load_file(action.text())
@pyqtSlot()
def _toggle_statusbar(self):
if self.statusBar().isHidden():
self.statusBar().show()
else:
self.statusBar().hide()
self._write_settings()
@pyqtSlot(QDropEvent)
def dragEnterEvent(self, event):
if event.mimeData().hasUrls():
event.acceptProposedAction()
@pyqtSlot(QDropEvent)
def dropEvent(self, event):
mime = event.mimeData()
if mime.hasUrls():
urls = mime.urls()
for url in urls:
self.load_file(url.toLocalFile())
@pyqtSlot(QEvent)
def closeEvent(self, event):
"""Close application.
Parameters
----------
event : QEvent
Close event.
"""
self._write_settings()
if self.history:
print("\nCommand History")
print("===============")
print("\n".join(self.history))
QApplication.quit()
def eventFilter(self, source, event):
# currently the only source is the raw plot window
if event.type() == QEvent.Close:
self._update_infowidget()
return QObject.eventFilter(self, source, event)
matplotlib.use("Qt5Agg")
app = QApplication(sys.argv)
app.setApplicationName("MNELAB")
app.setOrganizationName("cbrnr")
main = MainWindow()
if len(sys.argv) > 1: # open files from command line arguments
for f in sys.argv[1:]:
main.load_file(f)
sys.exit(app.exec_())
| f8c648fba12624bc23742daab67bdc965e83abb5 | [
"Markdown",
"Python"
] | 2 | Markdown | chrismullins/mnelab | 45b76daf2b07e1d65686158f30d6200f26b39bd1 | 7bcd1a3a4c3f25758e51780bab12e2acab50e1e0 |
refs/heads/master | <repo_name>jean553/libraries-loading<file_sep>/static_library/sum.c
#include "sum.h"
#include "mul.h"
int sum_and_mul(int first, int second) {
return first + mul(first, second);
}
<file_sep>/README.md
# Libraries loading
This is a short personal memo about static/shared libraries loading process.
## Sources
Based on the following articles:
* https://eli.thegreenplace.net/2011/11/03/position-independent-code-pic-in-shared-libraries
* https://eli.thegreenplace.net/2011/08/25/load-time-relocation-of-shared-libraries
## Table of content
- [Example C program](#example-c-program)
* [Write library C code](#write-c-code)
* [Generate object files](#generate-object-files)
* [Write C program](#write-c-program)
* [Compile C program](#compile-c-program)
- [Static libraries](#static-libraries)
* [Generate archive file](#generate-archive-file)
* [Link the program with the library](#link-the-program-with-the-library)
- [Shared library](#shared-library)
* [Generate a shared library file](#generate-a-shared-library-file)
* [Link the program with the library](#link-the-program-with-the-library)
- [Shared library symbols resolution](#shared-library-symbols-resolution)
* [Load time relocation](#load-time-relocation)
* [PIC Position Independent Code](#pic-position-independent-code)
- Data
- Procedures
## Example C program
### Write library C code
First, let's write some C code for our library. Our library is divided into four files:
* `sum.c` and `sum.h` that contains a sum function definition and declaration,
* `mul.c` and `mul.h` that contains a multiplication function definition and declaration
```c
/* sum.c */
#include "sum.h"
#include "mul.h" // declaration required as mul() is used below
int sum_and_mul(int first, int second) {
return first + mul(first, second);
}
```
```c
/* mul.c */
#include "mul.h"
int mul(int first, int second) {
return first * second;
}
```
```c
/* sum.h */
int sum_and_mul(int first, int second);
```
```c
/* mul.h */
int mul(int first, int second);
```
### Generate object files
Object files are `compiled` files but not `linked` files.
That means `symbols` are `not resolved` from one object to another.
For example, two object files are generated for the two sources files `sum.c` and `mul.c`:
* `mul.o` has no symbols to other objects, so it has no unresolved symbols,
* `sum.o` has the symbol `mul` that is defined into the `mul.o` object, this symbol is unresolved
This is fine for now, the files are supposed to be grouped together later.
The two generated object files can be represented as follow:

The files are generated through the following command:
```sh
gcc -c mul.c -o mul.o
gcc -c sum.c -o sum.o
```
### Write C program
We can now write a simple C program that uses the library:
```c
#include "sum.h"
#include <stdio.h>
int main()
{
int value = sum_and_mul(1000, 2000);
printf("%d", value);
return 0;
}
```
### Compile C program
We can now simply compile the program (without linking):
```sh
gcc -S -I static_library executable/main.c -o assembly_code
```
Details for the command above:
* `S` is the option to generate an assembly code output, not a binary one,
* `I` is the path of the custom headers (we need the declaration of `sum_and_value` to be visible for the compiler),
The output assembly is now in `assembly_code`.
A few lines contain:
```asm
movl $2000, %esi
movl $1000, %edi
call sum_and_mul@PLT
```
This is the call to the library function `sum_and_mul`.
As we can see, the `sum_and_mul` content is not part of the compiled code for now,
even if we would have fully compiled the program to binary format.
Let's compile into binary:
```sh
gcc -I static_library executable/main.c -o output
```
The following error appears:
```
/tmp/cc4TOaG2.o: In function `main':
main.c:(.text+0x13): undefined reference to `sum_and_mul'
collect2: error: ld returned 1 exit status
```
In fact, `ld`, that is called by `gcc` after the compilation, cannot find where is defined the symbol `sum_and_mul`:
as a complete part of the program cannot be found, the final output cannot be generated.
This is also possible to cancel the linking attempt (using the GCC `c` option):
```sh
gcc -c -I static_library executable/main.c -o output
```
In that case, `output` is not the final executable but an `object` file, as we generated previously when compiling the library.
The symbols are still unresolved.

## Static libraries
Static libraries on Linux have the `.a` extension (for `archive`).
This section goes througout the static library creation process in details.
### Generate an archive file
The archive file `.a` is a group of `object` files, all together.

The archive file is generated through the `ar` command:
```sh
ar rvs libstatic_library.a sum.o mul.o
```
The `rvs` option stand for: replacement, verbosity and add new "objects" (indices) to the archive,
replace them if necessary.
Note that no linking is done here. The unresolved symbols remain unresolved after the archive creation, even if the two concerned objects are part of the archive.
### Link the program with the library
The last step is now to take the `sum_and_mul` content, and move it into the final program.
This action can be performed by linking the program with the library.
```sh
gcc -c -I static_library executable/main.c -o output -Lstatic_library/ -lstatic_library
```
First, the content and of the `sum_and_mul` function is copied from the library to the final binary.

As the `mul` symbol is not resolved as well from the program point of view,
then the definition of the `mul` function is moved to the program as well.

As the library content is now part of the final program, this program can be executed without the library.
If the library is modified and if the modifications have to be applied to the program,
then the program must be compiled again.
## Shared library
The shared library is a `.so` file. It is loaded dynamically at runtime of a program.
The program uses functions and structures that are part of the dynamic library.
### Generate a shared library file
It is now possible to group all the object files of the library into a `.so` file
that will be the shared library file.
```sh
gcc -shared -o libshared_library.so shared_library/mul.o shared_library/sum.o
```
As the static library, there is no linking of the library symbols at this moment.
The resulted shared library file can be represented as follow:

### Link the program with the library
Unlike static libraries, there is no copy of code from the library to the executable when linking a shared library.
The only thing that happens is a check that all the functions of the executable exists into the given shared library,
and that the shared library itself exists.
The executable knows now that the shared library has to be loaded before loading the executable itself (at runtime).
This data is stored into the executable (ELF format for Executable and Linkable Format).
```sh
gcc -Ishared_library executable/main.c -o output -L. -lshared_library
```
What happened with this command can be represented as follow:

This is possible to check what shared libraries have to be loaded for the executable using `ldd`:
```sh
> ldd output
linux-vdso.so.1 (0x00007fffa53c9000)
libshared_library.so => not found
libc.so.6 => /usr/lib/libc.so.6 (0x00007f1a038c9000)
/lib64/ld-linux-x86-64.so.2 => /usr/lib64/ld-linux-x86-64.so.2 (0x00007f1a03e82000)
```
## Shared library symbols resolution
When a static library is linked with an executable, each symbol (function or data),
is resolved and replace by a memory address (this address is an "offset" from the real
address where the program will be loaded when executed).
In other words, a final executable (with static library only) or without library at all looks like:

*NOTE*: the process is really more complex than the schema above, but this is the general idea.
Doing this with shared libraries is not possible. In fact, there is no way to know in advance
where a shared library will be loaded when requesting a program to be executed.
### Load time relocation
Using `load time relocation` requires not to use `-fPIC` option when creating object files from the library sources.
This flag is used for Position-Independent Code, that is another solution for symbols resolution.
When compiling the library into `.so` final file, symbols are not resolved
and the relocations entries of the file now contains all the symbols that
will have to be resolved at running time.

*NOTE*: compiling a program with one version of the library and executing the program with a different version of this library (example: differences between objects/functions names) causes the symbols lookup process to fail when the program is started.
Once the program is loaded and the library is loaded as well, the resolution with the correct addresses into memory can take place.
The "reallocation" of the symbol occurs and the program (in memory) now have all its symbols resolved:

With this method, reallocation into the shared library area are performed for the calling process only.
Addresses/offsets from the shared library are modified in order to ensure link between the process code and the library
(for example: jump from the shared library to the process code).
This method has three main limitations:
* it takes time to relocate every unresolved symbol of the shared library when using it,
* reallocation has to be performed everytime a different process uses the library,
* the "shared library" is not shared between processes, and can't be anyway, as the relocation process requires that the library is only used with the current started process,
* the shared library code, when loaded into memory, has to be writable to perform relocation (security issue)
(solution to these problem is Position-Independent Code)
### PIC Position Independent Code
In a non-PIC shared library, the symbols are resolved at the program execution time.
The addresses of the library symbols are `absolute addresses` (from the process point of view)
(data is accessed through absolute addresses, code jumps from absolute addresses to absolute addresses...).
Access/browse the library is fast, but a single copy of the shared library in the memory
cannot be shared to multiple processes (absolute addresses are different).
In a PIC shared library, the symbols are not resolved at the program execution time, the program simply knows the address of the library.
The addresses of the library symbols are `relative addresses` (within the library code itself)
(data is accessed through relative addresses, code jumps n bytes before/after its current position).
Access/browse the library is slower as there is one indirection level to considere
(relative jumps, relative data access, push the current IP pointer on stack, functions lazy loading...).
The exact same copy of the shared library in memory can be shared between multiple processes.
<file_sep>/executable/main.c
#include "sum.h"
#include <stdio.h>
int main()
{
int value = sum_and_mul(1000, 2000);
printf("%d", value);
return 0;
}
<file_sep>/shared_library/mul.h
int mul(int first, int second);
<file_sep>/shared_library/mul.c
#include "mul.h"
int mul(int first, int second) {
return first * second;
}
<file_sep>/static_library/sum.h
int sum_and_mul(int first, int second);
| 8b60e85d53e0eccb05ca4d17d381aeb44b3e7a86 | [
"Markdown",
"C"
] | 6 | C | jean553/libraries-loading | 2a0f2b82966a878f7feb8703e8e2b99edd4d00b1 | 3465f619cfca6277bf0f2ecc4ed2442aa24d17e7 |
refs/heads/master | <repo_name>jsantoso/docker-php-7.4-cli<file_sep>/build_and_push.sh
#!/bin/bash
docker login
docker pull php:7.4-cli
docker build -t jsantoso/php-7.4-cli:latest .
docker push jsantoso/php-7.4-cli:latest<file_sep>/README.md
# docker-php-7.4-cli
PHP 7.3 CLI for Laravel artisan
<file_sep>/Dockerfile
FROM php:7.4-cli
WORKDIR /app
LABEL maintainer="<NAME> <<EMAIL>>"
ENV DEBIAN_FRONTEND noninteractive
ENV TZ=UTC
RUN apt-get update
RUN apt-get install -y \
apt-utils \
vim \
libpng-dev \
zlib1g-dev \
libpspell-dev \
libldap2-dev \
libcurl4 \
libcurl3-dev \
libbz2-dev \
libpq-dev \
libxml2-dev \
libz-dev \
libzip4 \
libzip-dev \
libmemcached-dev \
libmcrypt-dev \
libreadline-dev \
librabbitmq-dev \
libonig-dev \
unzip \
iproute2 \
iputils-ping
RUN echo alias ll=\'ls -lF\' >> /root/.bashrc
ENV PHP_ERROR_REPORTING E_ALL & ~E_NOTICE
RUN docker-php-ext-configure pgsql -with-pgsql=/usr/local/pgsql
RUN /usr/local/bin/docker-php-ext-install mbstring
RUN /usr/local/bin/docker-php-ext-install iconv
RUN /usr/local/bin/docker-php-ext-install gd
RUN /usr/local/bin/docker-php-ext-install bz2
RUN /usr/local/bin/docker-php-ext-install pdo
RUN /usr/local/bin/docker-php-ext-install pdo_pgsql
RUN /usr/local/bin/docker-php-ext-install pgsql
RUN /usr/local/bin/docker-php-ext-install soap
RUN /usr/local/bin/docker-php-ext-install xml
RUN /usr/local/bin/docker-php-ext-install xmlrpc
RUN /usr/local/bin/docker-php-ext-install zip
RUN /usr/local/bin/docker-php-ext-install bcmath
RUN /usr/local/bin/docker-php-ext-install ldap
RUN /usr/local/bin/docker-php-ext-install curl
RUN /usr/local/bin/docker-php-ext-install sockets
RUN pecl install redis
RUN docker-php-ext-enable redis
RUN pecl install amqp
RUN docker-php-ext-enable amqp
ADD conf.d/php.ini /usr/local/etc/php/conf.d/90-php.ini
ENTRYPOINT ["docker-php-entrypoint"]
CMD ["php", "-a"]<file_sep>/conf.d/php.ini
date.timezone = UTC
memory_limit = 512M
max_input_vars = 3000
upload_max_filesize = 100M
post_max_size = 108M
realpath_cache_ttl=7200
error_reporting=-1
display_startup_errors = On
display_errors = On
log_errors = On
<file_sep>/conf.d/xdebug.ini
xdebug.remote_host=${XDEBUG_HOST}
xdebug.remote_port=${XDEBUG_PORT}
xdebug.idekey=PHPSTORM
xdebug.remote_autostart=0
xdebug.remote_enable=1
xdebug.cli_color=1
xdebug.profiler_enable=0
xdebug.profiler_output_dir="/tmp/phpstorm/tmp/profiling"
xdebug.remote_handler=dbgp
xdebug.remote_mode=req
xdebug.var_display_max_children=-1
xdebug.var_display_max_data=-1
xdebug.var_display_max_depth=-1
display_startup_errors = On | 4b3e1c85cfbb3afb5afdd30438afa23ae166694c | [
"Markdown",
"INI",
"Dockerfile",
"Shell"
] | 5 | Shell | jsantoso/docker-php-7.4-cli | 2e212d21557b8d9412cf9e30308f7a1c5b3fd588 | 5e02206a10f7529bbaea1c608824882c1f553a0c |
refs/heads/master | <file_sep>package shulamit.hila.letsmeet.servieces;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import com.mapbox.mapboxsdk.geometry.LatLng;
import com.mapbox.mapboxsdk.maps.MapboxMap;
import com.mapbox.mapboxsdk.maps.OnMapReadyCallback;
public class InfoWindowSymbolLayerActivity extends AppCompatActivity implements OnMapReadyCallback, MapboxMap.OnMapClickListener {
@Override
public void onMapReady(@NonNull MapboxMap mapboxMap) {
}
@Override
public void onPointerCaptureChanged(boolean hasCapture) {
}
@Override
public void onMapClick(@NonNull LatLng point) {
return;
}
}
<file_sep>package shulamit.hila.letsmeet.servieces;
import android.app.IntentService;
import android.app.NotificationManager;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Location;
import android.util.Log;
import com.android.volley.AuthFailureError;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
import shulamit.hila.letsmeet.activities.LoginActivity;
import shulamit.hila.letsmeet.activities.MainActivity;
public class MyIntentServiceAccept extends IntentService {
final private String FCM_API = "https://fcm.googleapis.com/fcm/send";
final private String serverKey = "key=" + "<KEY>";
final private String contentType = "application/json";
final String TAG = "NOTIFICATION TAG";
String NOTIFICATION_TITLE;
String NOTIFICATION_MESSAGE;
String TOPIC;
private String userAccepted;
private String senderToken;
private String SHARED_PREFS = "user_details";
public MyIntentServiceAccept() {
super("MyIntentServiceAccept");
}
@Override
public void onDestroy() {
super.onDestroy();
}
@Override
protected void onHandleIntent(Intent intent) {
NotificationManager notificationManager =(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
int notificationId= intent.getIntExtra("notificationId",0);
userAccepted = intent.getStringExtra("isUserAccepted");
senderToken = intent.getStringExtra("senderToken");
notificationManager.cancel(notificationId);
if(userAccepted.equals("Accept")){
sendAcceptNotification();
}
notificationManager.cancel(notificationId);
}
private void sendAcceptNotification() {
SharedPreferences sharedPreferences = this.getSharedPreferences(SHARED_PREFS, MODE_PRIVATE);
String name = sharedPreferences.getString(LoginActivity.USER_NAME, "");
Location location = MainActivity.getOriginLocation();
if (location == null) {
return;
}
Double lat = location.getLatitude();
Double lng = location.getLongitude();
TOPIC = senderToken;
NOTIFICATION_TITLE = name +" shared location with you!";
NOTIFICATION_MESSAGE = lat + "," + lng;
JSONObject notification = new JSONObject();
JSONObject notificationBody = new JSONObject();
try {
notificationBody.put("title", NOTIFICATION_TITLE);
notificationBody.put("latLng", NOTIFICATION_MESSAGE);
notificationBody.put("channelId","1" );
notification.put("to", TOPIC);
notification.put("data", notificationBody);
} catch (JSONException e) {
Log.e(TAG, "onCreate: " + e.getMessage());
}
sendNotification(notification);
}
private void sendNotification(JSONObject notification) {
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(FCM_API, notification,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.i(TAG, "onResponse: " + response.toString());
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// Toast.makeText(context, "Request error", Toast.LENGTH_LONG).show();
}
}) {
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("Authorization", serverKey);
params.put("Content-Type", contentType);
return params;
}
};
MySingleton.getInstance(getApplicationContext()).addToRequestQueue(jsonObjectRequest);
}
}
<file_sep>package shulamit.hila.letsmeet.activities;
import android.app.AlertDialog;
import android.app.NotificationManager;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;
import com.mapbox.android.core.location.LocationEngine;
import com.mapbox.android.core.location.LocationEngineListener;
import com.mapbox.android.core.location.LocationEnginePriority;
import com.mapbox.android.core.location.LocationEngineProvider;
import com.mapbox.android.core.permissions.PermissionsListener;
import com.mapbox.android.core.permissions.PermissionsManager;
import com.mapbox.api.directions.v5.models.DirectionsResponse;
import com.mapbox.api.directions.v5.models.DirectionsRoute;
import com.mapbox.geojson.Point;
import com.mapbox.mapboxsdk.Mapbox;
import com.mapbox.mapboxsdk.annotations.Marker;
import com.mapbox.mapboxsdk.annotations.MarkerOptions;
import com.mapbox.mapboxsdk.camera.CameraUpdateFactory;
import com.mapbox.mapboxsdk.geometry.LatLng;
import com.mapbox.mapboxsdk.maps.MapView;
import com.mapbox.mapboxsdk.maps.MapboxMap;
import com.mapbox.mapboxsdk.maps.OnMapReadyCallback;
import com.mapbox.mapboxsdk.plugins.locationlayer.LocationLayerPlugin;
import com.mapbox.mapboxsdk.plugins.locationlayer.modes.CameraMode;
import com.mapbox.mapboxsdk.plugins.locationlayer.modes.RenderMode;
import com.mapbox.services.android.navigation.ui.v5.route.NavigationMapRoute;
import com.mapbox.services.android.navigation.v5.navigation.NavigationRoute;
import java.util.List;
import java.util.Locale;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import shulamit.hila.letsmeet.R;
/**
* the main activity display the Map
*/
public class MainActivity extends AppCompatActivity implements OnMapReadyCallback, LocationEngineListener, PermissionsListener {
private MapView mapView;
private MapboxMap map;
private LocationEngine locationEngine;
private LocationLayerPlugin locationLayerPlugin;
private static Location originLocation;
private PermissionsManager permissionsManager;
private com.mapbox.geojson.Point originalPosition;
private com.mapbox.geojson.Point otherUserPosition;
private NavigationMapRoute navigationMapRoute;
private static final String TAG = "MainActivity";
private TextToSpeech tts; // for TextToSpeech engine
public static Location getOriginLocation() {
return originLocation;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Mapbox.getInstance(this, getString(R.string.mapbox_access_token));
setContentView(R.layout.activity_main);
mapView = findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);//create the map
mapView.getMapAsync(this);
otherUserPosition = com.mapbox.geojson.Point.fromLngLat(35.172306,31.832323);//in the beginning
initializeTextSpeakEngine();
}
@Override
public void onMapReady(@NonNull MapboxMap mapboxMap) {
map = mapboxMap;
enableLocation();//check permission
navigate();//drow route on map if the is a destination
}
/**
* display the route between original location and destination location
* @param origin the orginal location
* @param destination the destination location
*/
private void getRoute(Point origin, Point destination){
MakeSound();
NavigationRoute.builder().accessToken(Mapbox.getAccessToken())
.origin(origin)
.destination(destination)
.build()
.getRoute(new Callback<DirectionsResponse>() {
@Override
public void onResponse(Call<DirectionsResponse> call, Response<DirectionsResponse> response) {
if (response.body() == null){
Log.e(TAG, "No routes found, check right user and access token");
return;
}
else if (response.body().routes().size() == 0){
Log.e(TAG, "no routes found");
return;
}
DirectionsRoute currentRoute = response.body().routes().get(0);//get the first route
if (navigationMapRoute != null){//remove old route from map
navigationMapRoute.removeRoute();
} else {
navigationMapRoute = new NavigationMapRoute(null,mapView,map);
}
navigationMapRoute.addRoute(currentRoute);
}
@Override
public void onFailure(Call<DirectionsResponse> call, Throwable t) {
Log.e(TAG, "Error " + t.getMessage());
}
});
}
/**
* check permission and initialize permission
*/
private void enableLocation() {
if (PermissionsManager.areLocationPermissionsGranted(this)){
initializeLocationEngine();
initializeLocationLayer();
}
else{
permissionsManager = new PermissionsManager(this);
permissionsManager.requestLocationPermissions(this);
}
}
/**
* initialize the location, ignore permissions - we already have them
*/
@SuppressWarnings("MissingPermission")
private void initializeLocationEngine(){
locationEngine = new LocationEngineProvider(MainActivity.this).obtainBestLocationEngineAvailable();
locationEngine.setPriority(LocationEnginePriority.HIGH_ACCURACY);
locationEngine.activate();
Location lastLocation = locationEngine.getLastLocation();
if(lastLocation !=null) {
originLocation = lastLocation;
setCameraPosition(lastLocation);
}
else {
locationEngine.addLocationEngineListener(this);
}
}
/**
* initialize the location layer, ignore permissions - we already have them
*/
@SuppressWarnings("MissingPermission")
private void initializeLocationLayer(){
locationLayerPlugin = new LocationLayerPlugin(mapView, map, locationEngine);
locationLayerPlugin.setLocationLayerEnabled(true);
locationLayerPlugin.setCameraMode(CameraMode.TRACKING);
locationLayerPlugin.setRenderMode(RenderMode.NORMAL);
}
private void setCameraPosition(Location location){
map.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(location.getLatitude(),location.getLongitude()),150.0));
}
@Override
@SuppressWarnings("MissingPermission")
public void onStart() {
super.onStart();
if (locationEngine!= null){
locationEngine.requestLocationUpdates();
}
if (locationLayerPlugin != null){
locationLayerPlugin.onStart();
}
mapView.onStart();
}
@Override
public void onResume() {
super.onResume();
mapView.onResume();
}
@Override
public void onPause() {
super.onPause();
mapView.onPause();
}
@Override
public void onStop() {
super.onStop();
if(locationEngine != null)
locationEngine.removeLocationUpdates();
if(locationLayerPlugin != null)
locationLayerPlugin.onStop();
mapView.onStop();
}
@Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
@Override
protected void onDestroy() {
super.onDestroy();
if (locationEngine != null){
locationEngine.deactivate();
}
mapView.onDestroy();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.menu_bar, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// open the relevant dialog / activity according to the menu selection
switch (item.getItemId()) {
case R.id.ic_about: {
openAboutDialog();
break;
}
case R.id.ic_exit: {
openExitDialog();
break;
}
case R.id.item_contacts: {
Intent intent = new Intent(MainActivity.this, ContactsActivity.class);
startActivity(intent);
break;
}
case R.id.item_history: {
Intent intent = new Intent(MainActivity.this, HistoryActivity.class);
startActivity(intent);
break;
}
case R.id.item_saves: {
Intent intent = new Intent(MainActivity.this, SavesActivity.class);
startActivity(intent);
break;
}
case R.id.ic_share:{
shareApp();
}
}
return super.onOptionsItemSelected(item);
}
private void shareApp() {
String message = this.getResources().getString(R.string.share_message);
Intent shareAppIntent = new Intent(Intent.ACTION_SEND);
shareAppIntent.setType("text/plain");
shareAppIntent.putExtra(Intent.EXTRA_TEXT,message);
shareAppIntent.putExtra(Intent.EXTRA_SUBJECT,"Meet your friend!");
startActivity(shareAppIntent);
}
private void openAboutDialog() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
alertDialog.setIcon(R.mipmap.ic_launcher_round);
alertDialog.setTitle(R.string.about_title);
alertDialog.setMessage(R.string.about);
alertDialog.setCancelable(true);
alertDialog.show();
}
private void openExitDialog() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
alertDialog.setIcon(R.mipmap.ic_launcher_round);
alertDialog.setTitle(R.string.exit_title);
alertDialog.setMessage(R.string.exit_qustion);
alertDialog.setCancelable(true);
alertDialog.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
System.exit(1); // destroy this activity
}
});
alertDialog.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
}
/*
* remove the possibility to go back to login activity
*/
@Override
public void onBackPressed() { }
@Override
public void onExplanationNeeded(List<String> permissionsToExplain) { }
@Override
public void onPermissionResult(boolean granted) {
if(granted){
enableLocation();
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
permissionsManager.onRequestPermissionsResult(requestCode,permissions, grantResults);
}
@Override
@SuppressWarnings("MissingPermission")
public void onConnected() {
locationEngine.requestLocationUpdates();
}
@Override
public void onLocationChanged(Location location) {
if(location != null) {
originLocation = location;
setCameraPosition(location);
}
}
/**
* draw location on map
*/
private void navigate(){
//say 'lets go!'
Intent intent = getIntent();
boolean shouldNavigate = intent.getBooleanExtra("shouldNavigate",false);
boolean shouldNavigateFromSaves= intent.getBooleanExtra("shouldNavigateFromSaves",false);
// is assigned to true if the user has added a new location by notification
if(shouldNavigate)
startNavigate(intent);
if(shouldNavigateFromSaves){
startNavigateFromSaves(intent);
}
}
private void MakeSound() {
String textToSpeak = "Lets go!";
// Speech pitch. 1.0 is the normal pitch, lower values lower the tone of
// the synthesized voice, greater values increase it.
tts.setPitch(1.5f);
// Speech rate. 1.0 is the normal speech rate, lower values slow down
// the speech (0.5 is half the normal speech rate), greater values
// accelerate it (2.0 is twice the normal speech rate).
tts.setSpeechRate(1.2f);
// speak up the string text
tts.speak(textToSpeak, TextToSpeech.QUEUE_FLUSH, null, null);
}
private void initializeTextSpeakEngine() {
// init Text To Speech engine
tts = new TextToSpeech(this, new TextToSpeech.OnInitListener()
{
@Override
public void onInit(int status)
{
if (status == TextToSpeech.SUCCESS)
{
int result = tts.setLanguage(Locale.UK);
if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED)
Toast.makeText(MainActivity.this,"Error: TextToSpeech Language not supported!", Toast.LENGTH_LONG).show();
}
}
});
}
private void startNavigateFromSaves(Intent intent) {
NotificationManager notificationManager =(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
double userLat = intent.getDoubleExtra("otherUserLat",0);
double userLng = intent.getDoubleExtra("otherUserLng",0);
int notificationId = intent.getIntExtra("notificationId", 0);
notificationManager.cancel(notificationId);
try {
otherUserPosition = com.mapbox.geojson.Point.fromLngLat(userLng,userLat);
LatLng point = new LatLng(originLocation.getLatitude(), originLocation.getLongitude());
Marker destinationMarker = map.addMarker(new MarkerOptions().position(point));
originalPosition = com.mapbox.geojson.Point.fromLngLat(originLocation.getLongitude(), originLocation.getLatitude());
getRoute(originalPosition, otherUserPosition);
}
catch (Exception e){
Toast.makeText(this,"could not find your location here",Toast.LENGTH_LONG).show();
}
}
private void startNavigate(Intent intent) {
NotificationManager notificationManager =(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
String body = intent.getStringExtra("goMLatLng");
int notificationId= intent.getIntExtra("notificationId",0);
String [] temp = new String[2];
temp = body.split(",");
String lat,lng;
lat = temp[0];
lng = temp[1];
notificationManager.cancel(notificationId);
try {
otherUserPosition = com.mapbox.geojson.Point.fromLngLat(Double.parseDouble(lng),Double.parseDouble(lat));
originalPosition = com.mapbox.geojson.Point.fromLngLat(originLocation.getLongitude(), originLocation.getLatitude());
LatLng point = new LatLng(otherUserPosition.latitude(), otherUserPosition.longitude());
Marker destinationMarker = map.addMarker(new MarkerOptions().position(point));
getRoute(originalPosition, otherUserPosition);
}
catch (Exception e){
Toast.makeText(this,"could not find your location",Toast.LENGTH_LONG).show();
}
}
}
<file_sep>package shulamit.hila.letsmeet.activities;
import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
import shulamit.hila.letsmeet.moduls.Point;
import shulamit.hila.letsmeet.R;
/**
* this adapter it attached to view holder
*/
public class SavesAdapter extends RecyclerView.Adapter<SavesAdapter.ViewHolder>{
private ArrayList<Point> savesPoints;
private Context context;
SavesAdapter(ArrayList<Point> savesPoints, Context context) {
this.savesPoints = savesPoints;
this.context = context;
}
@NonNull
@Override
public SavesAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int i) {
View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.saves_item, parent , false) ;
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull final ViewHolder holder, int position) {
holder.name.setText(savesPoints.get(position).getName());
holder.lat = savesPoints.get(position).getLat();
holder.lon = savesPoints.get(position).getLng();
}
class ViewHolder extends RecyclerView.ViewHolder{
TextView name;
RelativeLayout xmlContactsItem;
Button btnGo;
double lat;
double lon;
ViewHolder(@NonNull View itemView) {
super(itemView);
name=itemView.findViewById(R.id.txv_contact_details);
xmlContactsItem=itemView.findViewById(R.id.item_saves);
btnGo=itemView.findViewById(R.id.btn_go);
}
}
@Override
public int getItemCount() {
return savesPoints.size();
}
@Override
public void onBindViewHolder(@NonNull final SavesAdapter.ViewHolder holder, int position, @NonNull List<Object> payloads) {
super.onBindViewHolder(holder, position, payloads);
(holder).btnGo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(context,MainActivity.class);
intent.putExtra("otherUserLat",holder.lat);
intent.putExtra("otherUserLng",holder.lon);
intent.putExtra("shouldNavigateFromSaves",true);
context.startActivity(intent);
}
});
}
}
<file_sep>package shulamit.hila.letsmeet.activities;
import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
import shulamit.hila.letsmeet.R;
import shulamit.hila.letsmeet.moduls.Point;
public class HistoryAdapter extends RecyclerView.Adapter<HistoryAdapter.ViewHolder>{
private ArrayList<Point> historyPoints;
private Context context;
public HistoryAdapter(ArrayList<Point> savesPoints, Context context) {
this.historyPoints = savesPoints;
this.context = context;
}
@NonNull
@Override
public HistoryAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int i) {
View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.history_item, parent , false) ;
HistoryAdapter.ViewHolder holder= new HistoryAdapter.ViewHolder(view);
return holder;
}
@Override
public void onBindViewHolder(@NonNull final HistoryAdapter.ViewHolder holder, int position) {
holder.name.setText(historyPoints.get(position).getName());
holder.lat = historyPoints.get(position).getLat();
holder.lon = historyPoints.get(position).getLng();
}
public class ViewHolder extends RecyclerView.ViewHolder{
// ImageView image;
TextView name;
RelativeLayout xmlContactsItem;
Button btnGo;
double lat;
double lon;
public ViewHolder(@NonNull View itemView) {
super(itemView);
name=itemView.findViewById(R.id.txv_contact_details_history);
xmlContactsItem=itemView.findViewById(R.id.item_history);
btnGo=itemView.findViewById(R.id.btn_go_history);
}
}
@Override
public int getItemCount() {
return historyPoints.size(); }
@Override
public void onBindViewHolder(@NonNull final HistoryAdapter.ViewHolder holder, int position, @NonNull List<Object> payloads) {
super.onBindViewHolder(holder, position, payloads);
/**
* on click go in history list its navigate to the place in the history
*/
(holder).btnGo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(context,MainActivity.class);
intent.putExtra("otherUserLat",holder.lat);
intent.putExtra("otherUserLng",holder.lon);
intent.putExtra("shouldNavigateFromSaves",true);
context.startActivity(intent);
}
});
}
}
| 494367d173bdb046f3b9f318ef94b65eb136e391 | [
"Java"
] | 5 | Java | shulamitco/LetsMeet | 7d029814b64f730adb5502095973ff4c3d263344 | c9db24f78eab2d6bacf2f1ab2e8adc32df2d0f2d |
refs/heads/master | <file_sep>module GossipsHelper
def owner?(user)
user.id == params[:id]
end
end
<file_sep>class AddAdminToUsers < ActiveRecord::Migration
def change
add_column :users, :admin, :boolean, :default => false
add_column :users, :remember_digest, :string
add_timestamps :users
end
end
<file_sep>class GossipsController < ApplicationController
before_action :authorized_gossip, only: [:new, :create]
before_action :correct_user, only: [:edit, :update, :destroy]
include GossipsHelper
def index
@gossips = Gossip.all
end
def new
@gossip = Gossip.new
end
def create
@gossip = current_user.gossips.build(gossip_params)
if @gossip.save
flash[:success] = "Gossip spread!"
redirect_to @gossip
else
flash.now[:danger] = "Defective gossip. Please try again."
render 'new'
end
end
def show
@gossip = Gossip.find_by(id: params[:id])
end
def edit
@gossip = Gossip.find(params[:id])
end
def update
@gossip = Gossip.update_attribute(gossip_params)
if @gossip.save
flash[:success] = "Gossip updated!"
redirect_to @gossip
else
flash.now[:danger] = "Defective gossip. Please try again."
render 'new'
end
end
def destroy
end
private
def gossip_params
params.require(:gossip).permit(:title, :body, :user)
end
def authorized_gossip
unless logged_in?
flash[:danger] = "You must be logged in to post gossip."
redirect_to login_path
end
end
def correct_user
redirect_to root_url unless owner?(current_user)
end
end
| 21aa83fee9b12085c94b139c7e3fc685e5242b86 | [
"Ruby"
] | 3 | Ruby | nonsenseless/members-only | c6b7a0ebc5e16ed57487abf4446b6e91a39ac0d4 | fc6c3dc0e375fa57bb8c186ed3b3ef8d619aefe1 |
refs/heads/master | <repo_name>rbacquie/hangman_node<file_sep>/word.js
var Letter = require('./letter.js')
function Word(words) {
this.word = words;
this.letters = [];
this.wordFound = false;
}
module.exports = Word;<file_sep>/letter.js
function Letter(letter, check) {
this.letter = letter;
this.checkGuess = false;
// function post to screen
this.letterCheker = function () {
// if there is a space between words this will check and display a space
if (this.letter == ' ') { // renders a blank
return ' ';
};
if (this.checkGuess == false) { // renders _
return '_';
} else { // renders the letter
this.checkGuess == true;
return this.letter;
};
};
};
module.exports = Letter;<file_sep>/index.js
var inquirer = require('inquirer');
var Word = require('./word.js');
var wordBank = [];
var guesses = 10;
var wins = 0;
var losses = 0;
var guessedLetters = [];
var display = 0;
var currentWord = '';
var newWord = [
{
wordList:['BILLS', 'PANTHERS', 'TEXANS', 'COLTS', 'JAGUARS', '<NAME>', 'PATRIOTS', '<NAME>']
}
];
startGame();
function startGame() {
console.log('Welcome to NFL Hangman!');
inquirer.prompt [{
}].then
}<file_sep>/README.md
# hangman_node
This a node based Hang Man Game with constructor functions in separate files
| 697372efd85a04856debf1cf9b2d0d72044c8438 | [
"JavaScript",
"Markdown"
] | 4 | JavaScript | rbacquie/hangman_node | 12770856edb757fb43eb32280322feb8f071157b | dcaf5dba8310f57b835a68fc7947c57717b07c67 |
refs/heads/master | <repo_name>bazilab16/Projects<file_sep>/IbuCollection/IbuCollection/BLL/Helpers/ExcelToSqlExporter.cs
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
namespace IbuCollection.BLL.Helpers
{
public class ExcelToSqlExporter
{
private readonly string SqlConnectionString = "";
public void ExportExcelToSql()
{
//try
//{
// var excel = new ExcelPackage(Upload.FileContent);
// var dt = excel.ToDataTable();
// var table = "Contacts";
// using (var conn = new SqlConnection("Server=.;Database=Test;Integrated Security=SSPI"))
// {
// var bulkCopy = new SqlBulkCopy(conn);
// bulkCopy.DestinationTableName = table;
// conn.Open();
// var schema = conn.GetSchema("Columns", new[] { null, null, table, null });
// foreach (DataColumn sourceColumn in dt.Columns)
// {
// foreach (DataRow row in schema.Rows)
// {
// if (string.Equals(sourceColumn.ColumnName, (string)row["COLUMN_NAME"], StringComparison.OrdinalIgnoreCase))
// {
// bulkCopy.ColumnMappings.Add(sourceColumn.ColumnName, (string)row["COLUMN_NAME"]);
// break;
// }
// }
// }
// bulkCopy.WriteToServer(dt);
// }
//}
//catch (Exception ex)
//{
// throw ex;
//}
}
}
}<file_sep>/IbuCollection/IbuCollection/Controllers/HomeController.cs
using OfficeOpenXml;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace IbuCollection.Controllers
{
public class HomeController : Controller
{
private readonly IbuCollection.Data.IbuCollectionEntities IbuCollectionEntities = new Data.IbuCollectionEntities();
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(HttpPostedFileBase postedFile)
{
string filePath = string.Empty;
if (postedFile != null)
{
string path = Server.MapPath(@"~\Content\sheets");
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
filePath = path + Path.GetFileName(postedFile.FileName);
string extension = Path.GetExtension(postedFile.FileName);
postedFile.SaveAs(filePath);
string conString = string.Empty;
//switch (extension)
//{
// case ".xls": //Excel 97-03.
// conString = ConfigurationManager.ConnectionStrings["Excel03ConString"].ConnectionString;
// break;
// case ".xlsx": //Excel 07 and above.
// conString = ConfigurationManager.ConnectionStrings["Excel07ConString"].ConnectionString;
// break;
//}
FileInfo excel = new FileInfo(filePath);
using (var package = new ExcelPackage(excel))
{
var workbook = package.Workbook;
//*** Sheet 1
var worksheet = workbook.Worksheets.First();
string strConnString = @"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=IbuCollection;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False";
var objConn = new SqlConnection(strConnString);
objConn.Open();
//*** Loop to Insert
int totalRows = worksheet.Dimension.End.Row;
for (int i = 2; i <= totalRows; i++)
{
string strSQL = "INSERT INTO [dbo].[User] (Id,UserName,Email,Password,MobileNumber) "
+ " VALUES ("
+ " '" + worksheet.Cells[i, 1].Text.ToString() + "', "
+ " '" + worksheet.Cells[i, 2].Text.ToString() + "', "
+ " '" + worksheet.Cells[i, 3].Text.ToString() + "', "
+ " '" + worksheet.Cells[i, 4].Text.ToString() + "', "
+ " '" + worksheet.Cells[i, 5].Text.ToString() + "' "
+ ")";
var objCmd = new SqlCommand(strSQL, objConn);
objCmd.ExecuteNonQuery();
}
objConn.Close();
}
}
return View();
}
public ActionResult About()
{
ViewBag.Message = "Your application description page.";
//D:\Projects\Git\Templates\AspNet\MVC\IbuCollection\IbuCollection\Content\sheets\ExcelUserData.xlsx
FileInfo excel = new FileInfo(Server.MapPath(@"~\Content\sheets\ExcelUserData.xlsx"));
using (var package = new ExcelPackage(excel))
{
var workbook = package.Workbook;
//*** Sheet 1
var worksheet = workbook.Worksheets.First();
string strConnString = @"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=IbuCollection;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False";
var objConn = new SqlConnection(strConnString);
objConn.Open();
//*** Loop to Insert
int totalRows = worksheet.Dimension.End.Row;
for (int i = 2; i <= totalRows; i++)
{
string strSQL = "INSERT INTO [dbo].[User] (Id,UserName,Email,Password,MobileNumber) "
+ " VALUES ("
+ " '" + worksheet.Cells[i, 1].Text.ToString() + "', "
+ " '" + worksheet.Cells[i, 2].Text.ToString() + "', "
+ " '" + worksheet.Cells[i, 3].Text.ToString() + "', "
+ " '" + worksheet.Cells[i, 4].Text.ToString() + "', "
+ " '" + worksheet.Cells[i, 5].Text.ToString() + "' "
+ ")";
var objCmd = new SqlCommand(strSQL, objConn);
objCmd.ExecuteNonQuery();
}
objConn.Close();
}
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
}
} | 1bbc8af570444aa75ec0e014de84b68f290fa79f | [
"C#"
] | 2 | C# | bazilab16/Projects | 0d4b22e4680a660a24e4acdb392ca29f13d73d00 | 5cc183235dd04643d52509bc223744980b60ce63 |
refs/heads/master | <repo_name>RoDKoDRoK/RoDKoDRoK-main<file_sep>/rodkodrok/deploy/package.chain.deploy.php
<?php
//list des packages to deploy dans l'ordre
$tabpackagetodeploy=array();
//PREMIERS PACKAGES OBLIGATOIRES PAR DEFAUT POUR TOUT DEPLOIEMENT !!!!!!!!!!!!!!!!!!!!!!
//packages genesis.starter
$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="genesis.starter";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['locked']=true;
//packages ark.starter
$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="ark.starter";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['locked']=true;
//packages chain.default
$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="chain.default";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['locked']=true;
//packages abstract.starter
$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="abstract.starter";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['locked']=true;
//........PREMIERS PACKAGES OBLIGATOIRES PAR DEFAUT POUR TOUT DEPLOIEMENT !!!!!!!!!!!!!!!!!!!!!!
//VOTRE CHAINE DE DEPLOIEMENT
//PACKAGES BEFORE DB !!!
//STARTER (suite non obligatoire)
//packages files.starter
$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="files.starter";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['locked']=true;
//CHAIN
//packages chain.index
$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="chain.index";
//$tabpackagetodeploy[count($tabpackagetodeploy)-1]['locked']=true;
//packages chain.ajax
$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="chain.ajax";
//$tabpackagetodeploy[count($tabpackagetodeploy)-1]['locked']=true;
//packages chain.xml
$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="chain.xml";
//packages chain.json
$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="chain.json";
//packages chain.cron
$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="chain.cron";
//packages chain.virtualtask
$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="chain.virtualtask";
//packages chain.terminal
$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="chain.terminal";
//CONF ONLY
//ARKITECT EXTENSIONS
//packages arkitect.extension.starter
$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="arkitect.extension.starter";
//packages arkitect.extension.mirror
$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="arkitect.extension.mirror";
//ABSTRACT
//PRATIK STARTER (BEFORE includer for arkitect path)
//packages abstract.pratik
$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="abstract.pratik";
//GENESIS (FIRST)
//packages genesis.params
$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="genesis.params";
//$tabpackagetodeploy[count($tabpackagetodeploy)-1]['locked']=true;
//packages genesis.istask
$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="genesis.chainistask";
//$tabpackagetodeploy[count($tabpackagetodeploy)-1]['locked']=true;
//packages genesis.includer (classpath)
$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="genesis.includer";
//$tabpackagetodeploy[count($tabpackagetodeploy)-1]['locked']=true;
//CONTENT WITHOUT VISUAL OUPTUT (WHICH EXECUTE CODE ONLY like server.cron or virtual.virtualtask chains...)
//packages connector.thread.server.cron
$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="connector.thread.server.cron";
//packages connector.thread.virtual.virtualtask
$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="connector.thread.virtual.virtualtask";
//packages connector.thread.server.terminal
$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="connector.thread.server.terminal";
//...CONTENT
//OTHER CONF (AFTER CONTENT WITHOUT VISUAL OUPTUT !!!!! for arkitect path)
//packages chain.cron.classpath
$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="chain.cron.classpath";
//packages chain.virtualtask.classpath
$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="chain.virtualtask.classpath";
//packages chain.terminal.classpath
$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="chain.terminal.classpath";
//packages chain.cron.istask
$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="chain.cron.istask";
//packages chain.virtualtask.istask
$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="chain.virtualtask.istask";
//packages conf.wysiwyg
$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="conf.wysiwyg";
//GENESIS (interaction with dbfromfile)
//packages genesis.eventandtask
$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="genesis.eventandtask";
//$tabpackagetodeploy[count($tabpackagetodeploy)-1]['locked']=true;
//packages genesis.chainandconnector
$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="genesis.chainandconnector";
//$tabpackagetodeploy[count($tabpackagetodeploy)-1]['locked']=true;
//CODELOADER (FIRST)
//packages genesis.codeloader (pour les class)
$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="genesis.codeloader";
//$tabpackagetodeploy[count($tabpackagetodeploy)-1]['locked']=true;
//packages integrate.codeloader.phpclass
$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="integrate.codeloader.phpclass";
//$tabpackagetodeploy[count($tabpackagetodeploy)-1]['locked']=true;
//INTEGRATE
//packages db
$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="integrate.db.nodb";
//$tabpackagetodeploy[count($tabpackagetodeploy)-1]['locked']=true;
$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="integrate.db.mysql";
$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="integrate.db.mysqli";
//packages log
$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="integrate.log.nolog";
//$tabpackagetodeploy[count($tabpackagetodeploy)-1]['locked']=true;
$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="integrate.log.rodfilelog";
//packages cache
$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="integrate.cache.nocache";
//packages access
$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="integrate.access.nodroit";
//$tabpackagetodeploy[count($tabpackagetodeploy)-1]['locked']=true;
//packages formater
$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="integrate.formater.link.origin";
//packages dump
$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="integrate.dump.nodump";
$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="integrate.dump.mysql";
//packages user
$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="integrate.user.nouser";
//packages token
$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="integrate.token.notoken";
//packages filestorage
$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="integrate.filestorage.nofile";
//MIRRORS
//packages mirror
$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="pratik.mirror";
$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="integrate.filestorage.mirror";
//PRATIK (IMPORTANTS)
//packages destructor and path
$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="pratik.destructor";
$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="pratik.path";
//packages form
$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="pratik.form";
$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="pratiklib.form.customsubmit.db";
$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="pratiklib.form.customsubmit.mail";
$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="pratiklib.form.customsubmit.conf";
$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="pratiklib.form.champs.select";
//package view
$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="pratik.view";
//package downloader
$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="pratik.downloader";
//$tabpackagetodeploy[count($tabpackagetodeploy)-1]['locked']=true;
//package dump
$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="pratik.dump";
//package initersimul
$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="pratik.initersimul";
//PRATIK (MOINS IMPORTANTS, FACULTATIFS)
//package pager
$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="pratik.pager";
//package search
$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="pratik.search";
//CONNECTOR
//packages connector.arkitectoutput
$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="connector.arkitectoutput";
//CONNECTOR INSTANCIATOR EXTENDED (for driver auto instanciation)
//packages connector.instanciatorextended
$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="connector.instanciatorextended";
//CONNECTOR CONF
//packages connector.conf
$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="connector.conf";
//$tabpackagetodeploy[count($tabpackagetodeploy)-1]['locked']=true;
//CONNECTOR LOG
//packages connector.log
$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="connector.log";
//$tabpackagetodeploy[count($tabpackagetodeploy)-1]['locked']=true;
//LANG
//packages lang
$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="lang.fr_fr";
//CONNECTOR INCLUDER
//packages connector.includer
$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="connector.includer";
//$tabpackagetodeploy[count($tabpackagetodeploy)-1]['locked']=true;
//packages connector.formater
$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="connector.formater";
//$tabpackagetodeploy[count($tabpackagetodeploy)-1]['locked']=true;
//packages connector.filestorage
$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="connector.filestorage";
//$tabpackagetodeploy[count($tabpackagetodeploy)-1]['locked']=true;
//packages connector.variable
$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="connector.variable";
//$tabpackagetodeploy[count($tabpackagetodeploy)-1]['locked']=true;
//MIRRORS AFTER CONNECTOR
$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="mirror.dev";
//$tabpackagetodeploy[count($tabpackagetodeploy)-1]['locked']=true;
$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="mirror.share";
//$tabpackagetodeploy[count($tabpackagetodeploy)-1]['locked']=true;
//DB MAIN DEPLOYMENT !!!
//packages connector.db
$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="connector.db";
//$tabpackagetodeploy[count($tabpackagetodeploy)-1]['locked']=true;
//... DB MAIN DEPLOYMENT !!!
//PACKAGES AFTER DB !!!
//PRATIK WITH DB (IMPORTANTS POUR SITE MANAGEMENT ET LA SUITE)
//package params
$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="pratik.params";
//USER
//packages user to integrate before connector.user
$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="integrate.user.roduser";
//packages connector.user
$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="connector.user";
//DROIT
//packages access to integrate before connector.droit
$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="integrate.access.roddroit";
//$tabpackagetodeploy[count($tabpackagetodeploy)-1]['locked']=true;
//packages connector.droit
$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="connector.droit";
//$tabpackagetodeploy[count($tabpackagetodeploy)-1]['locked']=true;
//USER TOKEN
//packages token to integrate before connector.token
$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="integrate.token.rodtoken";
//packages connector.token
$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="connector.token";
//SET CHAIN IS TASK (before EVENT)
//EVENT
//packages rod.eventandtask
$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="rod.eventandtask";
//PACKAGES WITH ACTION ON TABLE EVENTEXECTASK AFTER THAT POINT...
//VIRTUAL TASK FOR CODELOADER FIRST
//packages thread.virtualtask.loadcodefromthread
$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="thread.virtualtask.loadcodefromthread";
//CONNECTOR CHAIN AND CONNECTOR PLUS
//packages chain and connector management plus
$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="rod.chainandconnector";
//CODELOADER DB INTEGRATION FOR NEXT CODE LOAD
$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="rod.codeloader";
$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="integrate.codeloader.css";
$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="integrate.codeloader.js";
//CONNECTOR LIB
//packages connector.lib
$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="connector.lib";
//$tabpackagetodeploy[count($tabpackagetodeploy)-1]['locked']=true;
//INTEGRATE WITH LIB
//packages tp
$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="integrate.tp.smarty";
//$tabpackagetodeploy[count($tabpackagetodeploy)-1]['locked']=true;
//packages ajax
$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="integrate.ajax.jquery";
//packages connector.ajax
$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="connector.ajax";
//$tabpackagetodeploy[count($tabpackagetodeploy)-1]['locked']=true;
//SITE MANAGEMENT (AFTER DROIT BEFORE USER AND DESIGN)
//packages site management
$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="rod.menu";
$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="rod.caseandcolonne";
//CASES
//packages case login
$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="pratiklib.case.login";
//packages case menu
$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="pratiklib.case.menu";
//...CASES
//CONTENT MAIN OUTPUT (like index, ajax, ...)
//packages connector.thread.main.index
$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="connector.thread.main.index";
//$tabpackagetodeploy[count($tabpackagetodeploy)-1]['locked']=true;
//packages connector.thread.sub.ajax
$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="connector.thread.sub.ajax";
//packages connector.thread.ws.xml
$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="connector.thread.ws.xml";
//packages connector.thread.ws.json
$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="connector.thread.ws.json";
//...CONTENT
//CLASSPATH FOR CONTENT MAIN OUTPUT (like index, ajax, ...)
//packages chain.index.classpath
$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="chain.index.classpath";
//packages chain.ajax.classpath
$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="chain.ajax.classpath";
//packages chain.xml.classpath
$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="chain.xml.classpath";
//...CLASSPATH
//USER INTERFACE (and token to kill later ? )
//packages user and token
$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="rod.user";
//$tabpackagetodeploy[count($tabpackagetodeploy)-1]['locked']=true;
$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="rod.token";
// AFTER DB, USER AND DROIT !!!!
//TEMPLATE
//packages connector.tp
$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="connector.tp";
//$tabpackagetodeploy[count($tabpackagetodeploy)-1]['locked']=true;
//DESIGN
//packages design.default
$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="design.default";
//packages thread.virtualtask.loadcodefromdesign
$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="thread.virtualtask.loadcodefromdesign";
//packages connector.message
$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="connector.message";
//HEADERFOOTER
//packages connector.headerfooter
$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="connector.headerfooter";
//MENUS
//packages menu leftrightcolumn
$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="pratiklib.menu.leftrightcolumn";
//packages adminmenu
$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="rod.adminmenu";
//packages constructmenu
$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="rod.constructmenu";
//packages reportmenu
$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="rod.reportmenu";
//...MENUS
//OTHER CONNECTOR
//packages connector.lang
$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="connector.lang";
//packages connector.cache
$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="connector.cache";
//CONNECTOR END
//INTEGRATE WITH DB
//packages log
$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="integrate.log.roddblog";
//packages cache
$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="integrate.cache.rodcachedb";
$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="integrate.cache.rodcache";
//PRATIK WITH DB (FACULTATIFS, MOINS IMPORTANTS)
//package mail
$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="pratik.mail";
//ROD FUNCTIONNALITIES PACK WITH DB
//packages dbmaker
$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="rod.dbmaker";
//packages packagemanager
$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="rod.package";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['locked']=true;
/*
//packages packager
$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="rod.packager";
/*
//TODO
//packages mirror
$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="rod.mirror";
//packages shareonrkrportal
$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="rod.shareonrkrportal";
//...
*/
/*
//packages deployer
$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="rod.deployer";
*/
//package multisite
$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="connector.multisite";
//packages report
$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="integrate.graph.highcharts";
$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="rod.tracker.stats";
//DESIGNS
//packages lib icons (available but a lot of files to load, better to load after deployment with the backoffice)
$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="design.iconlib.rodkodrok";
//packages design
$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="design.yours";
$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="design.rodkodrokstarter";
//PRATIKLIB ADDONS
//EXAMPLE
//packages example (available, you can uncomment to load example files on your site)
/*$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="rod.example";*/
//END
$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="connector.tracker";
//VIRTUAL TASK FOR CODELOADER LAST
//packages thread.virtualtask.loadcodefromthreadcontrol
$tabpackagetodeploy[]=array();
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['type']="none";
$tabpackagetodeploy[count($tabpackagetodeploy)-1]['name']="thread.virtualtask.loadcodefromthreadcontrol";
?><file_sep>/rodkodrok/deploy/deployark/class.arkitect.php
<?php
class Arkitect extends Load
{
//arkitect du système
var $arkitect=array();
function __construct()
{
parent::__construct();
$this->charg_arkitect();
}
function charg_arkitect()
{
$arkitect=array();
//conf arkitect
$tab_chemins_arkitect=$this->charg_dossier_dans_tab("core/conf/arkitect");
if(isset($tab_chemins_arkitect) && $tab_chemins_arkitect)
{
sort($tab_chemins_arkitect);
foreach($tab_chemins_arkitect as $chemin_arkitect_to_load)
{
if(strstr($chemin_arkitect_to_load,".htaccess")=="" && substr($chemin_arkitect_to_load,-4)==".php")
include $chemin_arkitect_to_load;
}
}
$this->arkitect=array_merge($this->arkitect,$arkitect);
}
function get($idarkitect="",$idarkitect2="",$idarkitect3="",$idarkitect4="",$idarkitect5="")
{
$value="";
if($idarkitect!="" && isset($this->arkitect[$idarkitect]))
{
$value=$this->arkitect[$idarkitect];
if($idarkitect2!="" && isset($this->arkitect[$idarkitect][$idarkitect2]))
{
$value=$this->arkitect[$idarkitect][$idarkitect2];
if($idarkitect3!="" && isset($this->arkitect[$idarkitect][$idarkitect2][$idarkitect3]))
{
$value=$this->arkitect[$idarkitect][$idarkitect2][$idarkitect3];
if($idarkitect4!="" && isset($this->arkitect[$idarkitect][$idarkitect2][$idarkitect3][$idarkitect4]))
{
$value=$this->arkitect[$idarkitect][$idarkitect2][$idarkitect3][$idarkitect4];
if($idarkitect5!="" && isset($this->arkitect[$idarkitect][$idarkitect2][$idarkitect3][$idarkitect4][$idarkitect5]))
{
$value=$this->arkitect[$idarkitect][$idarkitect2][$idarkitect3][$idarkitect4][$idarkitect5];
}
}
}
}
}
return $value;
}
}
?><file_sep>/rodkodrok/deploy/deploylib/pratik/form/customform/champs.text.php
<?php
/*
Custom code to prepare champs input (charger une liste de suggestions par exemple)
main var dispo :
$tpl (classe)
$contentlineform['name'] (name input of form)
$contentlineform['default'] (default value input of form)
$contentlineform['label'] (label input of form)
$contentlineform['suggestlist'] (suggestlist input of form)
$contentlineform['champs'] (type champs input of form, in the filename)
var to modify or to let the same :
$contentlineform (array like above to send to template $tpl)
other var dispo :
echo $this->showIniter();
*/
?><file_sep>/rodkodrok/index.php
<?php
//session
session_start();
//check if config php ok
ini_set('memory_limit', '128M');
ini_set('post_max_size', '128M');
ini_set('upload_max_filesize', '128M');
//to kill en mode prod
ini_set('display_errors', 1);
error_reporting(E_ALL & ~E_NOTICE);
//error_reporting(e_all);
//get chain connector
$chainconnector="none";
if(isset($_GET['chainconnector']) && $_GET['chainconnector']!="")
$chainconnector=$_GET['chainconnector'];
//load genesis
$genesisdbfromfile=null;
$requestor=null;
$chemin_genesis="rkrsystem/src/genesis";
if(file_exists($chemin_genesis."/genesis.rkrdatasrc.php"))
include $chemin_genesis."/genesis.rkrdatasrc.php";
if(file_exists($chemin_genesis."/genesis.dbfromfile.php"))
{
include $chemin_genesis."/genesis.dbfromfile.php";
$genesisdbfromfile=new DbFromFile();
if(file_exists($chemin_genesis."/genesis.requestor.php"))
{
include_once $chemin_genesis."/genesis.requestor.php";
$requestor=new Requestor($genesisdbfromfile);
}
}
//load ark
$chemin_ark="rkrsystem/src/ark";
if(file_exists($chemin_ark."/arkchain.php"))
include $chemin_ark."/arkchain.php";
for($i=1;$i<=20;$i++)
if(file_exists($chemin_ark."/arkchain.".$i.".php"))
include $chemin_ark."/arkchain.".$i.".php";
if(isset($genesis_rkrdatasrc) && $genesis_rkrdatasrc=="dbfromfile") //check ark from genesis dbfromfile (if enabled, default is to use dbfromfile, if error with your ark config, you can put "originfile" config in genesis.rkrdatasrc.php)
{
$arktmp=$genesisdbfromfile->orderby("ordre","arkchain");
if(isset($arktmp) && count($arktmp)>0)
$arkchain=$arktmp;
}
if(isset($arkchain) && count($arkchain)>0)
{
foreach($arkchain as $arkcour)
{
//prepare data
if(isset($arkcour['file']))
$arkcour['file']=strtolower($arkcour['file']);
else
continue;
if(isset($arkcour['class']))
$arkcour['class']=strtolower($arkcour['class']);
else
$arkcour['class']=strtolower($arkcour['file']);
$arkcour['class']=ucfirst($arkcour['class']);
if(!isset($arkcour['loadafterabstract']))
$arkcour['loadafterabstract']=false;
if(!isset($arkcour['makevar']))
$arkcour['makevar']=false;
if(isset($arkcour['var']))
$arkcour['var']=strtolower($arkcour['var']);
else
$arkcour['var']=strtolower($arkcour['file']);
//load an ark
if(file_exists($chemin_ark."/class.".$arkcour['file'].".php"))
{
if(!$arkcour['loadafterabstract'])
{
include_once $chemin_ark."/class.".$arkcour['file'].".php";
if($arkcour['makevar'])
eval("\$".$arkcour['var']."=new ".$arkcour['class']."();");
}
}
else
{
//test site to deploy
echo "<script>document.location.href='deploy.php';</script>";
exit;
}
}
}
else
{
//test site to deploy
echo "<script>document.location.href='deploy.php';</script>";
exit;
}
//load chain connector
if(file_exists($arkitect->get("chain")."/connector.chain.".$chainconnector.".php"))
include_once $arkitect->get("chain")."/connector.chain.".$chainconnector.".php";
else if(!file_exists($arkitect->get("chain")."/connector.chain.default.php"))
{
//test site to deploy
echo "<script>document.location.href='deploy.php';</script>";
exit;
}
else
{
include_once $arkitect->get("chain")."/connector.chain.default.php";
if(isset($firstchain) && file_exists($arkitect->get("chain")."/connector.chain.".$firstchain.".php"))
{
include_once $arkitect->get("chain")."/connector.chain.".$firstchain.".php";
$chainconnector=$firstchain;
//echo $firstchain;
}
else
$chainconnector="default";
}
//include classes abstract
$chemin_classes=$arkitect->get("abstract");
$tab_class=array();
if(isset($loader) && $loader)
$tab_class=$loader->charg_dossier_dans_tab($chemin_classes);
sort($tab_class);
//print_r($tab_class);
foreach($tab_class as $class_to_load)
{
include $class_to_load;
}
//load ark suite after abstract
if(isset($arkchain) && count($arkchain)>0)
foreach($arkchain as $arkcour)
{
//prepare data
if(isset($arkcour['file']))
$arkcour['file']=strtolower($arkcour['file']);
else
continue;
if(isset($arkcour['class']))
$arkcour['class']=strtolower($arkcour['class']);
else
$arkcour['class']=strtolower($arkcour['file']);
$arkcour['class']=ucfirst($arkcour['class']);
if(!isset($arkcour['loadafterabstract']))
$arkcour['loadafterabstract']=false;
if(!isset($arkcour['makevar']))
$arkcour['makevar']=false;
if(isset($arkcour['var']))
$arkcour['var']=strtolower($arkcour['var']);
else
$arkcour['var']=strtolower($arkcour['file']);
//load an ark
if($arkcour['loadafterabstract'] && file_exists($chemin_ark."/class.".$arkcour['file'].".php"))
{
include_once $chemin_ark."/class.".$arkcour['file'].".php";
if($arkcour['makevar'])
eval("\$".$arkcour['var']."=new ".$arkcour['class']."();");
}
}
//charge chains dans tab
$chemin_chain=$arkitect->get("chain");
$chaintab=array();
if(isset($loader) && $loader)
$chaintab=$loader->charg_chain_dans_tab($chemin_chain);
//print_r($chaintab);
//init initer
$initer=array();
$initer['genesisdbfromfile']=$genesisdbfromfile;
$initer['requestor']=$requestor;
$initer['chainconnector']=$chainconnector;
$initer['chaintab']=$chaintab;
//init initer with ark
if(isset($arkchain) && count($arkchain)>0)
foreach($arkchain as $arkcour)
{
if(isset($arkcour['var']))
$arkcour['var']=strtolower($arkcour['var']);
else
$arkcour['var']=strtolower($arkcour['file']);
if(!isset($arkcour['makevar']))
$arkcour['makevar']=false;
if($arkcour['makevar'])
$initer[$arkcour['var']]=${$arkcour['var']};
}
//cas appel php from console
if(isset($argv))
$initer['argv']=$argv;
//start connector
foreach($tabconnector as $connectorcour)
{
$connectorlowercase=strtolower($connectorcour['name']);
$connectorclass=ucfirst($connectorlowercase);
if(!file_exists($arkitect->get("connector")."/connector.".$connectorlowercase.".php"))
continue;
include_once $arkitect->get("connector")."/connector.".$connectorlowercase.".php";
eval("\$instanceConnector=new Connector".$connectorclass."(\$initer);");
eval("\$instanceConnector".$connectorclass."=\$instanceConnector;");
//initinstance
eval("\$instance".$connectorclass."=\$instanceConnector->initInstance();");
//get modif du initer
$initer=$instanceConnector->initer;
//cas passage de class dans initer
if(isset($connectorcour['classtoiniter']) && $connectorcour['classtoiniter'])
eval("\$initer['instance".$connectorclass."']=\$instance".$connectorclass.";");
$instanceConnector->reloadIniter($initer);
//initvar
${$connectorlowercase}=$instanceConnector->initVar();
//get modif du initer
$initer=$instanceConnector->initer;
//cas passage de var dans initer
if(isset($connectorcour['vartoiniter']) && $connectorcour['vartoiniter'])
eval("\$initer['".$connectorlowercase."']=\$".$connectorlowercase.";");
//cas set variable ou classe spéciale (conf, db, tpl, ...)
if(isset($connectorcour['aliasiniter']) && $connectorcour['aliasiniter']!="none")
{
//class spéciale
if(isset($connectorcour['classtoiniter']) && $connectorcour['classtoiniter'] && (!isset($connectorcour['vartoiniter']) || !$connectorcour['vartoiniter']))
{
eval("\$".$connectorcour['aliasiniter']."=\$instance".$connectorclass.";");
eval("\$initer['".$connectorcour['aliasiniter']."']=\$instance".$connectorclass.";");
}
//variable spéciale (prioritaire pour variable, écrase la classe si var et class sont utilisés)
if(isset($connectorcour['vartoiniter']) && $connectorcour['vartoiniter'])
{
eval("\$".$connectorcour['aliasiniter']."=\$".$connectorlowercase.";");
eval("\$initer['".$connectorcour['aliasiniter']."']=\$".$connectorlowercase.";");
}
}
//echo "</pre>";print_r($initer['instanceDroit']);echo "</pre>";
//pre exec
$instanceConnector->reloadIniter($initer);
$instanceConnector->preexec();
$initer=$instanceConnector->initer;
}
//construct tab to print (array with the connector data to print)
$toprint=array();
if(isset($loader) && $loader)
$toprint=$loader->construct_tab_toprint($tabconnector,$initer);
//print_r($toprint);
$initer['toprint']=$toprint;
//post exec connector
foreach($tabconnector as $connectorcour)
{
$connectorlowercase=strtolower($connectorcour['name']);
$connectorclass=ucfirst($connectorlowercase);
if(!file_exists($arkitect->get("connector")."/connector.".$connectorlowercase.".php"))
continue;
eval("\$instanceConnector=\$instanceConnector".$connectorclass.";");
$instanceConnector->reloadIniter($initer);
$instanceConnector->postexec();
$initer=$instanceConnector->initer;
}
//reconstruct tab to print (array with the connector data to print)
$toprint=array();
if(isset($loader) && $loader)
$toprint=$loader->construct_tab_toprint($tabconnector,$initer);
//print_r($toprint);
$initer['toprint']=$toprint;
//end connector
$reversetabconnector=array_reverse($tabconnector);
foreach($reversetabconnector as $connectorcour)
{
$connectorlowercase=strtolower($connectorcour['name']);
$connectorclass=ucfirst($connectorlowercase);
if(!file_exists($arkitect->get("connector")."/connector.".$connectorlowercase.".php"))
continue;
eval("\$instanceConnector=\$instanceConnector".$connectorclass.";");
//$instanceConnector->initer=$initer;
$instanceConnector->reloadIniter($initer);
$instanceConnector->end();
$initer=$instanceConnector->initer;
}
?>
<file_sep>/rodkodrok/deploy.php
<?php
session_start();
//to kill en mode prod
ini_set('display_errors', 1);
//error_reporting(e_all);
//include ark (from deploy)
$chemin_ark="deploy/deployark";
include $chemin_ark."/arkchain.php";
for($i=1;$i<=20;$i++)
if(file_exists($chemin_ark."/arkchain.".$i.".php"))
include $chemin_ark."/arkchain.".$i.".php";
$tabnottoloadagain=array();
if(isset($arkchain) && count($arkchain)>0)
foreach($arkchain as $arkcour)
{
//prepare data
if(isset($arkcour['file']))
$arkcour['file']=strtolower($arkcour['file']);
else
continue;
if(!isset($arkcour['loadafterabstract']))
$arkcour['loadafterabstract']=false;
//load an ark
if(file_exists($chemin_ark."/class.".$arkcour['file'].".php"))
{
if(!$arkcour['loadafterabstract'])
{
$tabnottoloadagain[]="class.".$arkcour['file'].".php";
include_once $chemin_ark."/class.".$arkcour['file'].".php";
//eval("\$".$arkcour['var']."=new ".$arkcour['class']."();");
}
}
}
//include ark (from core with new ark class deployed with this deployer)
$chemin_ark="rkrsystem/src/ark";
if(file_exists($chemin_ark."/arkchain.php"))
{
include $chemin_ark."/arkchain.php";
for($i=1;$i<=20;$i++)
if(file_exists($chemin_ark."/arkchain.".$i.".php"))
include $chemin_ark."/arkchain.".$i.".php";
if(isset($arkchain) && count($arkchain)>0)
foreach($arkchain as $arkcour)
{
//prepare data
if(isset($arkcour['file']))
$arkcour['file']=strtolower($arkcour['file']);
else
continue;
if(!isset($arkcour['loadafterabstract']))
$arkcour['loadafterabstract']=false;
//load an ark
if(file_exists($chemin_ark."/class.".$arkcour['file'].".php"))
{
if(!$arkcour['loadafterabstract'])
{
//check if ark class is already in deployer
$noload=false;
foreach($tabnottoloadagain as $nottoload)
if("class.".$arkcour['file'].".php"==$nottoload)
$noload=true;
if($noload)
continue;
include_once $chemin_ark."/class.".$arkcour['file'].".php";
//eval("\$".$arkcour['var']."=new ".$arkcour['class']."();");
}
}
}
}
//include classes abstract (from deploy)
$loader=new Load();
$chemin_abstract_classes="deploy/deployabstract";
$tab_class=$loader->charg_dossier_dans_tab($chemin_abstract_classes);
sort($tab_class);
//print_r($tab_class);
$tabnottoloadagain=array();
foreach($tab_class as $class_to_load)
{
$tabnottoloadagain[]=substr($class_to_load,strlen($chemin_abstract_classes)+1);
include_once $class_to_load;
}
//include classes abstract (from core with new abstract class deployed with this deployer)
$chemin_abstract_classes="rkrsystem/src/abstract";
$tab_class=$loader->charg_dossier_dans_tab($chemin_abstract_classes);
if($tab_class!=null)
{
sort($tab_class);
//print_r($tab_class);
foreach($tab_class as $class_to_load)
{
$noload=false;
foreach($tabnottoloadagain as $nottoload)
if(strstr($class_to_load,$nottoload))
$noload=true;
if($noload)
continue;
include_once $class_to_load;
}
}
//include ark after abstract (from deploy)
$chemin_ark="deploy/deployark";
include $chemin_ark."/arkchain.php";
for($i=1;$i<=20;$i++)
if(file_exists($chemin_ark."/arkchain.".$i.".php"))
include $chemin_ark."/arkchain.".$i.".php";
$tabnottoloadagain=array();
if(isset($arkchain) && count($arkchain)>0)
foreach($arkchain as $arkcour)
{
//prepare data
if(isset($arkcour['file']))
$arkcour['file']=strtolower($arkcour['file']);
else
continue;
if(!isset($arkcour['loadafterabstract']))
$arkcour['loadafterabstract']=false;
//load an ark
if($arkcour['loadafterabstract'] && file_exists($chemin_ark."/class.".$arkcour['file'].".php"))
{
$tabnottoloadagain[]="class.".$arkcour['file'].".php";
include_once $chemin_ark."/class.".$arkcour['file'].".php";
//eval("\$".$arkcour['var']."=new ".$arkcour['class']."();");
}
}
//include ark after abstract (from core with new ark class deployed with this deployer)
$chemin_ark="rkrsystem/src/ark";
if(file_exists($chemin_ark."/arkchain.php"))
{
include $chemin_ark."/arkchain.php";
for($i=1;$i<=20;$i++)
if(file_exists($chemin_ark."/arkchain.".$i.".php"))
include $chemin_ark."/arkchain.".$i.".php";
if(isset($arkchain) && count($arkchain)>0)
foreach($arkchain as $arkcour)
{
//prepare data
if(isset($arkcour['file']))
$arkcour['file']=strtolower($arkcour['file']);
else
continue;
if(!isset($arkcour['loadafterabstract']))
$arkcour['loadafterabstract']=false;
//load an ark
if($arkcour['loadafterabstract'] && file_exists($chemin_ark."/class.".$arkcour['file'].".php"))
{
//check if ark class is already in deployer
$noload=false;
foreach($tabnottoloadagain as $nottoload)
if("class.".$arkcour['file'].".php"==$nottoload)
$noload=true;
if($noload)
continue;
include_once $chemin_ark."/class.".$arkcour['file'].".php";
//eval("\$".$arkcour['var']."=new ".$arkcour['class']."();");
}
}
}
//include classes deploy
$chemin_deploy_classes="deploy/deployclass";
$tab_class=$loader->charg_dossier_dans_tab($chemin_deploy_classes);
//print_r($tab_class);
foreach($tab_class as $class_to_load)
include $class_to_load;
//include lib (tpl smarty in deploy)
include "deploy/deploylib/ext/Smarty-3.1.21/libs/Smarty.class.php";
//include conf deploy
$conf=array();
if(file_exists("deploy/conf.deploy.php"))
include "deploy/conf.deploy.php";
//include package chain deploy
if(file_exists("deploy/package.chain.deploy.php"))
include "deploy/package.chain.deploy.php";
//log (not used)
$instanceLog=new Log($conf);
$log=$instanceLog->logselected;
//init deploy class
$instanceDeploy=new Deploy($tabpackagetodeploy,$conflictresolution);
$instanceDeploy->log=$log; //log init for deploy
//ajax gestion pour deploy
if(isset($_GET['ajax']) && $_GET['ajax']!="")
{
include "deploy/deployajax/".$_GET['ajax'].".php";
exit;
}
//steps allowed in $_POST
$tabstep=array();
$tabstep[]="downloadstep";
//init deploypage
$deploypage="startdeploy";
$deploypagetpl=$deploypage;
//get deploypage
$cptpackagecour=0;
if(isset($_POST['codename']) && $_POST['codename']!="" && array_search($_POST['codename'],$tabstep)===false)
{
$deploypage=$_POST['codename'];
while(isset($tabpackagetodeploy[$cptpackagecour]['name']) && $tabpackagetodeploy[$cptpackagecour]['name']!=$deploypage)
$cptpackagecour++;
if(isset($tabpackagetodeploy[++$cptpackagecour]['name']))
$deploypage=$tabpackagetodeploy[$cptpackagecour]['name'];
while(!file_exists("package/".$deploypage."/conf.form.xml") && isset($tabpackagetodeploy[++$cptpackagecour]['name']))
$deploypage=$tabpackagetodeploy[$cptpackagecour]['name'];
$deploypagetpl="conf.form";
}
if(isset($_POST['codename']) && array_search($_POST['codename'],$tabstep)!==false)
{
$deploypage=$_POST['codename'];
$deploypagetpl=$deploypage;
}
if($cptpackagecour>=count($tabpackagetodeploy))
{
$deploypage="deployment";
$deploypagetpl=$deploypage;
}
//tp
$tpl=new TemplateSmarty();
//get tpl page
$tpl->remplir_template("deploypage",$deploypagetpl);
//title
$tpl->remplir_template("maintitle","RoDKoDRoK System");
//subtitle
if($deploypage=="startdeploy")
$tpl->remplir_template("mainsubtitle","Start deployment");
else if($deploypage=="deployment")
$tpl->remplir_template("mainsubtitle","End deployment");
else if($deploypage=="downloadstep")
$tpl->remplir_template("mainsubtitle","Download all packages from RoDKoDRoK.com");
else
$tpl->remplir_template("mainsubtitle","Package ".$deploypage);
//get content
$content=$instanceDeploy->getDeployContent($deploypage);
$tpl->remplir_template("content",$content);
$form=$instanceDeploy->getDeployForm($deploypage);
$tpl->remplir_template("form",$form);
//charg contenu page
$tpl->affich_template($maintemplate);
?>
<file_sep>/rodkodrok/deploy/README.txt
Dossier pour le déploiement du site.
Vous serez redirigé vers ce dossier pour l'installation de RoDKoDRoK.
Si besoin entrez directement l'url http://<votresite>/deploy/ pour démarrer l'installation.
<file_sep>/rodkodrok/deploy/index.php
<html>
<head>
<title>RoDKoDRoK</title>
</head>
<body>
<?php
echo "<script>document.location.href='../deploy.php';</script>";
?>
</body>
</html><file_sep>/rodkodrok/deploy/conf.deploy.php
<?php
//main tpl deploy
$maintemplate="deploy/deploytpl/deploy.tpl";
//conflict resolution
//"force" to ignore conflict and force deployment even if files are lost or surcharged
//or "keep" to keep all conflict files after a "Deploy" (to check manually differences after deployment)
//or "reverse" to force install complete and to keep story of conflicts and allow revert files when you select "Destroy" for a package
$conflictresolution="reverse";
?><file_sep>/rodkodrok/deploy/deployark/arkchain.php
<?php
//chain des fichiers ark to load
$arkchain=array();
$arkchain[]=array();
$arkchain[count($arkchain)-1]['file']="load";
$arkchain[count($arkchain)-1]['makevar']=true;
$arkchain[count($arkchain)-1]['class']="Load";
$arkchain[count($arkchain)-1]['var']="loader";
$arkchain[]=array();
$arkchain[count($arkchain)-1]['file']="arkitect";
$arkchain[count($arkchain)-1]['makevar']=true;
$arkchain[count($arkchain)-1]['class']="arkitect";
$arkchain[count($arkchain)-1]['var']="arkitect";
$arkchain[]=array();
$arkchain[count($arkchain)-1]['file']="instanciator";
$arkchain[count($arkchain)-1]['makevar']=true;
$arkchain[count($arkchain)-1]['class']="instanciator";
$arkchain[count($arkchain)-1]['var']="instanciator";
?><file_sep>/rodkodrok/deploy/deployark/class.instanciator.php
<?php
class Instanciator
{
function __construct()
{
//parent::__construct();
}
function newInstance($classname="",$initer=array())
{
//check data
if($classname=="")
{
//putolog... test if log exists before !!!
return null;
}
//prepare data
//$classname=strtolower($classname);
$classname=ucfirst($classname);
//check data
if(!class_exists($classname))
{
//putolog... test if log exists before !!!
return null;
}
//new instance
eval("\$instance=new ".$classname."(\$initer);");
//check new instance ok with initer parameters
if($this->checkIniterPrerequis($instance))
return $instance;
//cas prerequis manquant
//putolog... test if log exists before !!!
return null;
}
function checkIniterPrerequis($instance)
{
$tabiniterprerequis=$instance->getIniterPrerequis();
//cas pas de prerequis
if($tabiniterprerequis=="")
return true;
if(is_array($tabiniterprerequis) && count($tabiniterprerequis)<=0)
return true;
//check prerequis
foreach($tabiniterprerequis as $initerprerequiscour)
{
if(!isset($instance->{$initerprerequiscour}) || $instance->{$initerprerequiscour}==null)
return false;
}
return true;
}
}
?><file_sep>/rodkodrok/deploy/deployclass/class.downloader.php
<?php
class PratikDownloader extends ClassIniter
{
var $tabsrclink=array();
var $defaultsrclinkfolder="deploy/deploylib/pratik/downloader/srclinks/";
function __construct($initer=array())
{
parent::__construct($initer);
//prepare src links
$this->tabsrclink=$this->prepareSrcLinks();
}
function prepareSrcLinks()
{
$tabsrclink=array();
//get folder src link
$srclinksfolder=$this->defaultsrclinkfolder;
if(isset($this->conf['srclinkfolder']) && is_dir($this->conf['srclinkfolder']))
$srclinksfolder=$this->conf['srclinkfolder'];
//load srclinks in array
$tab_chemins_srclinks=array();
if(isset($this->loader))
$tab_chemins_srclinks=$this->loader->charg_dossier_dans_tab($srclinksfolder);
if(isset($tab_chemins_srclinks) && $tab_chemins_srclinks)
foreach($tab_chemins_srclinks as $chemin_srclinks_to_load)
{
if(strstr($chemin_srclinks_to_load,".htaccess")=="" && substr($chemin_srclinks_to_load,-4)==".php")
include $chemin_srclinks_to_load;
}
ksort($tabsrclink);
$tabsrclink=array_slice($tabsrclink,0);
//check and prepare local link without http
for($cptsrclink=0;$cptsrclink<count($tabsrclink);$cptsrclink++)
{
$urlcour=$tabsrclink[$cptsrclink];
if(substr($urlcour,0,4)!="http")
$tabsrclink[$cptsrclink]="http".($this->isSecure()?"s":"")."://".$_SERVER['HTTP_HOST']."/".$urlcour;
}
return $tabsrclink;
}
function getSrcLink($srclink="")
{
if($srclink=="" && isset($this->tabsrclink[0]))
return $this->tabsrclink[0];
if(is_numeric($srclink) && $srclink>=0 && isset($this->tabsrclink[$srclink]))
return $this->tabsrclink[$srclink];
return $srclink;
}
function getTabSrcLink()
{
return $this->tabsrclink;
}
function getFileLink($filename="",$subfolder="")
{
for($cptsrclink=0;$cptsrclink<count($this->getTabSrcLink());$cptsrclink++)
{
$urltodownload=$this->getSrcLink($cptsrclink);
$urltodownload=$urltodownload."/".$subfolder."/";
$file_headers = @get_headers($urltodownload.$filename);
if($file_headers[0] != 'HTTP/1.1 404 Not Found')
{
return $urltodownload.$filename;
}
}
return "";
}
function isSecure()
{
return ((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') || $_SERVER['SERVER_PORT'] == 443);
}
}
?><file_sep>/rodkodrok/deploy/deployabstract/class.connector.php
<?php
class Connector extends ClassIniter
{
var $instance;
var $chemintpl=""; //uniquement cas include de subtpl pour toprint
function __construct($initer=array())
{
parent::__construct($initer);
}
function initInstance()
{
return null;
}
function initVar()
{
return null;
}
function preexec()
{
return null;
}
function postexec()
{
return null;
}
function end()
{
return null;
}
function setInstance($instance)
{
$this->instance=$instance;
}
function getInstance()
{
return $this->instance;
}
}
?>
<file_sep>/rodkodrok/deploy/deployajax/deploypackage.php
<?php
$packagename=$_POST['packagename'];
$checklist=array();
$tabdeployedfiles=array();
//SET INITER
$initer=array();
$initer['conf']=array();
$initer['db']=null;
$initer['log']=null;
//RECONSTRUCT INITER
$initer=$instanceDeploy->initerConstruct($initer);
//INIT PACKAGER
$instancePackage=new PratikPackage($initer);
//echo $instancePackage->showIniter(true); //test to see initer values
//SET CONFLICT MODE
$instancePackage->setConflictResolution($instanceDeploy->conflictresolution);
//RELOAD INITER IN INSTANCE PACKAGE
$instancePackage->reloadIniter($initer);
//DEPLOY PACKAGE
$tabdeployedfiles[]=$instancePackage->deploy($packagename);
//CHECKLIST RESULT OF DEPLOYMENT OF THE PACKAGE
$checklist[]=$packagename;
$checklisttexte="<br />";
$checklisttexte.="<div>New package deployment :</div>";
$cptchecklist=0;
foreach($checklist as $checkpackage)
{
$checklisttexte.="<div> - ".$checkpackage."</div>";
if($tabdeployedfiles[$cptchecklist])
foreach($tabdeployedfiles[$cptchecklist] as $deployedfile)
$checklisttexte.="<div> --- ".$deployedfile."</div>";
$cptchecklist++;
}
$checklisttexte.="<br />";
echo $checklisttexte;
?><file_sep>/rodkodrok/deploy/deployclass/class.log.php
<?php
class Log
{
var $logselected=null;
function __construct($conf,$db=null)
{
//select moteur tpl
$moteurlowercase="";
if(isset($conf['moteurlog']))
$moteurlowercase=strtolower($conf['moteurlog']);
$moteurclass=ucfirst($moteurlowercase);
if(file_exists("deploy/deployclass/class.log.".$moteurlowercase.".php"))
{
//include_once "integrate/driver/class.log.".$moteurlowercase.".php";
eval("\$this->logselected=new Log".$moteurclass."(\$conf,\$db);");
}
else
{
//include_once "integrate/driver/class.log.nolog.php";
$this->logselected=new LogNolog($conf,$db);
$this->logselected->pushtolog("Echec du chargement du driver template. Verifier la configuration ou votre driver.");
}
}
}
?><file_sep>/rodkodrok/deploy/deployajax/downloadpackage.php
<?php
$packagename=$_POST['packagename'];
$initer=array();
$initer['loader']=new Load();
$instancePackage=new PratikPackage($initer);
if($instancePackage->getPackageFromRoDKoDRoKCom($packagename))
echo "Loading ".$packagename." : done";
else
echo "Error";
?><file_sep>/rodkodrok/deploy/deployclass/class.log.nolog.php
<?php
class LogNolog
{
var $db;
var $conf;
function __construct($conf,$db=null)
{
//parent::__construct();
$this->db=$db;
$this->conf=$conf;
}
function pushtolog($line,$srcerror="RODError",$destname="")
{
}
}
?><file_sep>/rodkodrok/deploy/deployclass/class.initersimul.php
<?php
class PratikInitersimul extends ClassIniter
{
var $prepareiniter=true;
var $tabtransversedatatounset=array();
function __construct($initer=array(),$prepareiniter=true)
{
parent::__construct($initer);
$this->prepareiniter=$prepareiniter;
$this->tabtransversedatatounset=array();
$this->tabtransversedatatounset[]="transversedata";
}
function initerConstruct($initercreated=array())
{
//simulation d'un initer avec les paramètres get
$initer=$initercreated;
//clean transversedata
if(is_array($this->tabtransversedatatounset))
foreach($this->tabtransversedatatounset as $transversedatatounset)
unset($initer[$transversedatatounset]);
//clean old initer TO KILL IF POSSIBLE
if($this->prepareiniter)
{
//SET INITER FIRST VAR
$initer['conf']=array();
$initer['db']=null;
$initer['log']=null;
}
//CREATE INITER
//load genesis
$genesisdbfromfile=null;
$requestor=null;
$chemin_genesis="rkrsystem/src/genesis";
if(file_exists($chemin_genesis."/genesis.rkrdatasrc.php"))
include $chemin_genesis."/genesis.rkrdatasrc.php";
if(file_exists($chemin_genesis."/genesis.dbfromfile.php"))
{
include_once $chemin_genesis."/genesis.dbfromfile.php";
$genesisdbfromfile=new DbFromFile();
if(file_exists($chemin_genesis."/genesis.requestor.php"))
{
include_once $chemin_genesis."/genesis.requestor.php";
$requestor=new Requestor($genesisdbfromfile);
}
}
//load ark
$tab_chemin_ark=array("deploy/deployark","rkrsystem/src/ark");
foreach($tab_chemin_ark as $chemin_ark)
{
if(!file_exists($chemin_ark."/arkchain.php"))
continue;
include $chemin_ark."/arkchain.php";
for($i=1;$i<=20;$i++)
if(file_exists($chemin_ark."/arkchain.".$i.".php"))
include $chemin_ark."/arkchain.".$i.".php";
if(isset($genesis_rkrdatasrc) && $genesis_rkrdatasrc=="dbfromfile") //check ark from genesis dbfromfile (if enabled, default is to use dbfromfile, if error with your ark config, you can put "originfile" config in genesis.rkrdatasrc.php)
{
$arktmp=$genesisdbfromfile->orderby("ordre","arkchain");
if(isset($arktmp) && count($arktmp)>0)
$arkchain=$arktmp;
}
if(isset($arkchain) && count($arkchain)>0)
foreach($arkchain as $arkcour)
{
//prepare data
if(isset($arkcour['file']))
$arkcour['file']=strtolower($arkcour['file']);
else
continue;
if(isset($arkcour['class']))
$arkcour['class']=strtolower($arkcour['class']);
else
$arkcour['class']=strtolower($arkcour['file']);
$arkcour['class']=ucfirst($arkcour['class']);
if(!isset($arkcour['makevar']))
$arkcour['makevar']=false;
if(isset($arkcour['var']))
$arkcour['var']=strtolower($arkcour['var']);
else
$arkcour['var']=strtolower($arkcour['file']);
//load an ark
if(file_exists($chemin_ark."/class.".$arkcour['file'].".php"))
{
//include_once $chemin_ark."/class.".$arkcour['file'].".php";
if($arkcour['makevar'] && class_exists($arkcour['class']))
eval("\$".$arkcour['var']."=new ".$arkcour['class']."();");
}
}
}
//load classes abstract manquantes
$tab_chemin_abstract=array("rkrsystem/src/abstract");
foreach($tab_chemin_abstract as $chemin_abstract)
{
if(!isset($loader) || !$loader)
continue;
$tab_class=$loader->charg_dossier_dans_tab($chemin_abstract);
if(!$tab_class)
continue;
sort($tab_class);
//print_r($tab_class);
foreach($tab_class as $class_to_load)
{
//check already loaded in deploy
$filenameabstract=substr($class_to_load,strrpos($class_to_load,"/"));
if(file_exists("deploy/deployabstract".$filenameabstract))
continue;
include_once $class_to_load;
}
}
//get chain connector
$chainconnector="none";
//load chain connector
if(isset($arkitect))
if(file_exists($arkitect->get("chain")."/connector.chain.default.php"))
{
include $arkitect->get("chain")."/connector.chain.default.php";
if(isset($firstchain) && file_exists($arkitect->get("chain")."/connector.chain.".$firstchain.".php"))
{
include $arkitect->get("chain")."/connector.chain.".$firstchain.".php";
$chainconnector=$firstchain;
//echo $firstchain;
}
else
$chainconnector="default";
}
//charge chains dans tab
$chemin_chain="";
if(isset($arkitect))
$chemin_chain=$arkitect->get("chain");
$chaintab=array();
if(isset($loader) && $loader)
$chaintab=$loader->charg_chain_dans_tab($chemin_chain);
//print_r($chaintab);
//init initer
$initer['simul']="on";
$initer['genesisdbfromfile']=$genesisdbfromfile;
$initer['requestor']=$requestor;
$initer['chainconnector']=$chainconnector;
$initer['chaintab']=$chaintab;
//init initer with ark
if(isset($arkchain) && count($arkchain)>0)
foreach($arkchain as $arkcour)
{
if(isset($arkcour['var']))
$arkcour['var']=strtolower($arkcour['var']);
else
$arkcour['var']=strtolower($arkcour['file']);
if(!isset($arkcour['makevar']))
$arkcour['makevar']=false;
if($arkcour['makevar'] && class_exists($arkcour['class']))
$initer[$arkcour['var']]=${$arkcour['var']};
}
//test chain ok
if($chainconnector=="default" || $chainconnector=="none" || !isset($tabconnector))
return $initer;
//start connector
foreach($tabconnector as $connectorcour)
{
if(!isset($arkitect))
continue;
$connectorlowercase=strtolower($connectorcour['name']);
$connectorclass=ucfirst($connectorlowercase);
if(!file_exists($arkitect->get("connector")."/connector.".$connectorlowercase.".php"))
continue;
include_once $arkitect->get("connector")."/connector.".$connectorlowercase.".php";
eval("\$instanceConnector=new Connector".$connectorclass."(\$initer);");
eval("\$instanceConnector".$connectorclass."=\$instanceConnector;");
//initinstance
eval("\$instance".$connectorclass."=\$instanceConnector->initInstance();");
//get modif du initer
$initer=$instanceConnector->initer;
//cas passage de class dans initer
if(isset($connectorcour['classtoiniter']) && $connectorcour['classtoiniter'])
eval("\$initer['instance".$connectorclass."']=\$instance".$connectorclass.";");
$instanceConnector->reloadIniter($initer);
//initvar
${$connectorlowercase}=$instanceConnector->initVar();
//get modif du initer
$initer=$instanceConnector->initer;
//cas passage de var dans initer
if(isset($connectorcour['vartoiniter']) && $connectorcour['vartoiniter'])
eval("\$initer['".$connectorlowercase."']=\$".$connectorlowercase.";");
//cas set variable ou classe spéciale (conf, db, tpl, ...)
if(isset($connectorcour['aliasiniter']) && $connectorcour['aliasiniter']!="none")
{
//class spéciale
if(isset($connectorcour['classtoiniter']) && $connectorcour['classtoiniter'] && (!isset($connectorcour['vartoiniter']) || !$connectorcour['vartoiniter']))
{
eval("\$".$connectorcour['aliasiniter']."=\$instance".$connectorclass.";");
eval("\$initer['".$connectorcour['aliasiniter']."']=\$instance".$connectorclass.";");
}
//variable spéciale (prioritaire pour variable, écrase la classe si var et class sont utilisés)
if(isset($connectorcour['vartoiniter']) && $connectorcour['vartoiniter'])
{
eval("\$".$connectorcour['aliasiniter']."=\$".$connectorlowercase.";");
eval("\$initer['".$connectorcour['aliasiniter']."']=\$".$connectorlowercase.";");
}
}
//echo "</pre>";print_r($initer['instanceDroit']);echo "</pre>";
//pre exec
$instanceConnector->reloadIniter($initer);
$instanceConnector->preexec();
$initer=$instanceConnector->initer;
}
//post exec connector
/*
foreach($tabconnector as $connectorcour)
{
$connectorlowercase=strtolower($connectorcour['name']);
$connectorclass=ucfirst($connectorlowercase);
if(!file_exists("connector/connector.".$connectorlowercase.".php"))
continue;
eval("\$instanceConnector=\$instanceConnector".$connectorclass.";");
//$instanceConnector->initer=$initer;
$instanceConnector->reloadIniter($initer);
$instanceConnector->postexec();
$initer=$instanceConnector->initer;
}
*/
//...CREATE INITER
$initercreated=$initer;
return $initercreated;
}
}
?><file_sep>/rodkodrok/deploy/deployclass/class.package.php
<?php
class PratikPackage extends ClassIniter
{
var $conflictresolution="force";
var $conflictfolder="rkrsystem/packagetrace/conflict";
var $folderdestdownload="rkrsystem/packagetrace/packagezip/";
var $folderdestarchives="rkrsystem/packagetrace/packageziparchived/";
var $folderdestpackage="package/";
var $folderdestdb="rkrsystem/packagetrace/db/";
var $folderdestlogpackageloaded="rkrsystem/packagetrace/packageloaded/";
var $chemingeneratortpl="deploy/deploytpl/generator.tpl";
function __construct($initer=array())
{
parent::__construct($initer);
//init conflictresolution
if(isset($this->conf['conflictresolution']))
$this->conflictresolution=$this->conf['conflictresolution'];
}
function deploy($packagecodename="example")
{
//conflict init
if($this->conflictresolution!=null && !is_dir($this->conflictfolder))
mkdir($this->conflictfolder,0777,true);
//deploy package
$this->initer['packagecodename']=$packagecodename;
$classpackagename="";
$tabclassname=explode(".",$packagecodename);
foreach($tabclassname as $classnamecour)
$classpackagename.=ucfirst(strtolower($classnamecour));
if(file_exists("package/".$packagecodename))
{
//tab deployed files
$tabdeployedfiles=array();
//include descripter
$this->initer['descripter']=array();
if(file_exists("package/".$packagecodename."/package.descripter.php"))
include "package/".$packagecodename."/package.descripter.php";
if(isset($descripter))
$this->initer['descripter']=$descripter;
//load conf package
$confstatic=null;
if(file_exists("package/".$packagecodename."/conf.static.xml"))
$confstatic=simplexml_load_file("package/".$packagecodename."/conf.static.xml");
$this->initer['confstatic']=$confstatic;
//load conf form package
if(isset($_POST['confform'][$packagecodename]))
$this->initer['confform'][$packagecodename]=$_POST['confform'][$packagecodename];
if(isset($_SESSION['confform'][$packagecodename]))
$this->initer['confform'][$packagecodename]=$_SESSION['confform'][$packagecodename];
//reload initer
$this->reloadIniter();
//include predeployer static
if(file_exists("package/".$packagecodename."/class/class.static.php"))
{
include "package/".$packagecodename."/class/class.static.php";
eval("\$instanceStatic=new ".$classpackagename."Static(\$this->initer);");
}
if(file_exists("package/".$packagecodename."/static/static.predeployer.php"))
include "package/".$packagecodename."/static/static.predeployer.php";
//reload initer
$this->reloadIniter();
//load db static
$sqltype=$this->getExtSql();
$chemin_db_static="package/".$packagecodename."/static/static.db.deployer.".$sqltype;
if(isset($this->db) && $this->db && file_exists($chemin_db_static))
{
//sql exec
$sqltoload=file_get_contents($chemin_db_static);
$tabsqltoload=explode(";",$sqltoload);
foreach($tabsqltoload as $sqlcour)
{
$req=$this->db->query($sqlcour);
}
//filename creation
$namefilecour=str_replace("package/".$packagecodename."/static/",$this->folderdestdb.$packagecodename.".",$chemin_db_static);
//conflict resolution "keep" mode
if($this->conflictresolution=="keep")
{
$cptconflict="1";
$conflictnamefilecour=$namefilecour;
while(file_exists($conflictnamefilecour))
$conflictnamefilecour=str_replace($this->folderdestdb,$this->folderdestdb."___CONFLICTFILE".($cptconflict++)."___",$namefilecour);
$namefilecour=$conflictnamefilecour;
}
//conflict resolution "reverse" mode
if($this->conflictresolution!=null)
{
//conflict management
$cptconflict="1";
if(file_exists($namefilecour))
{
do
{
$conflictnamefilecour=str_replace($this->folderdestdb,$this->folderdestdb."___CONFLICTFILE".($cptconflict++)."___",$namefilecour);
}
while(file_exists($this->conflictfolder."/".$conflictnamefilecour));
if(!is_dir($this->conflictfolder."/".$this->folderdestdb))
mkdir($this->conflictfolder."/".$this->folderdestdb,0777,true);
copy($namefilecour,$this->conflictfolder."/".$conflictnamefilecour);
//set conflictfilelist
$this->addToConflictFile($conflictnamefilecour);
}
//setup annuaire files in package
$this->addToFileIsInPackageFile($packagecodename,$namefilecour);
}
//create file
file_put_contents($namefilecour,$sqltoload);
//return tab
$tabdeployedfiles[]=$namefilecour;
}
//load static dump if exists
$dumper=null;
$dumploaded=false;
if((class_exists("PratikDump") || (isset($this->includer) && $this->includer->include_pratikclass("Dump"))) && isset($this->instanceConf) && $this->instanceConf!=null)
{
$dumpname="dump.".$packagecodename."___static";
$instanceDump=new PratikDump($this->initer,$dumpname);
$packagelastdumptoload=$instanceDump->getLastDump($dumpname);
if($packagelastdumptoload!="")
{
//load dump
$dumper=$instanceDump->dumpselected;
$dumper->importDump($packagelastdumptoload);
$dumploaded=true;
}
}
//load from genesis dbfromfile to new db table
if(!$dumploaded && file_exists("package/".$packagecodename."/static/static.db.destroyer.".$sqltype))
{
$sqltoload=file_get_contents("package/".$packagecodename."/static/static.db.destroyer.".$sqltype); //get sql file destroy
$tabsqltoload=explode(";",$sqltoload);
foreach($tabsqltoload as $sqlcour)
{
//prepare dump for this sql line (cas drop table)
if($this->requestor && method_exists($this->requestor,"exportGenesisdbfromfileToDb"))
{
$tabtabletokill=$this->checkDropTable($sqlcour);
foreach($tabtabletokill as $tablecour)
if($this->genesisdbfromfile->isTable($tablecour) && (!isset($this->initer['descripter']['exportgenesis']) || (isset($this->initer['descripter']['exportgenesis']) && $this->initer['descripter']['exportgenesis']==true)))
$this->requestor->exportGenesisdbfromfileToDb($tablecour);
}
}
}
//load files static
foreach($this->initer['chaintab'] as $chaincour)
{
$tabfilestoload=$this->loader->charg_dossier_dans_tab("package/".$packagecodename."/static/".$chaincour);
if(isset($tabfilestoload))
foreach($tabfilestoload as $filecour)
{
$folder=substr($filecour,0,strrpos($filecour,"/"));
$file=substr($filecour,strrpos($filecour,"/"),strlen($filecour)-0-strrpos($filecour,"/"));
if($folder=="package/".$packagecodename."/static/".$chaincour)
continue;
$folder=str_replace("package/".$packagecodename."/static/".$chaincour."/","",$folder);
if(!is_dir($folder))
mkdir($folder,0777,true);
//conflict resolution "keep" mode
if($this->conflictresolution=="keep")
{
$cptconflict="1";
$conflictnamefilecour=$file;
while(file_exists($folder.$conflictnamefilecour))
$conflictnamefilecour="/___CONFLICTFILE".($cptconflict++)."___".substr($file,1);
$file=$conflictnamefilecour;
}
//conflict resolution "reverse" mode
if($this->conflictresolution!=null)
{
//conflict management
$cptconflict="1";
if(file_exists($folder.$file))
{
do
{
$conflictnamefilecour="/___CONFLICTFILE".($cptconflict++)."___".substr($file,1);
}
while(file_exists($this->conflictfolder."/".$folder.$conflictnamefilecour));
if(!is_dir($this->conflictfolder."/".$folder))
mkdir($this->conflictfolder."/".$folder,0777,true);
copy($folder.$file,$this->conflictfolder."/".$folder.$conflictnamefilecour);
//set conflictfilelist
$this->addToConflictFile($folder.$conflictnamefilecour);
}
//setup annuaire files in package
$this->addToFileIsInPackageFile($packagecodename,$folder.$file);
}
//file create
copy($filecour,$folder.$file);
//return tab
$tabdeployedfiles[]=$folder.$file;
}
}
//reconstruct initer with last files deploy
if(class_exists("PratikInitersimul") || (isset($this->includer) && $this->includer->include_pratikclass("Initersimul")))
{
$instanceInitersimul=new PratikInitersimul($this->initer);
$newiniter=$instanceInitersimul->initerConstruct($this->initer);
$this->reloadIniter($newiniter);
}
//include postdeployer static
if(file_exists("package/".$packagecodename."/static/static.postdeployer.php"))
include "package/".$packagecodename."/static/static.postdeployer.php";
//reload initer
$this->reloadIniter();
//load conf package generator
$confgenerator=null;
if(file_exists("package/".$packagecodename."/conf.generator.xml"))
$confgenerator=simplexml_load_file("package/".$packagecodename."/conf.generator.xml");
$this->initer['confgenerator']=$confgenerator;
//reload initer
$this->reloadIniter();
//include predeployer generator
$instanceGenerator=new PackageGenerator($this->initer);
if(file_exists("package/".$packagecodename."/class/class.generator.php"))
{
include "package/".$packagecodename."/class/class.generator.php";
eval("\$instanceGenerator=new ".$classpackagename."Generator(\$this->initer);");
}
if(file_exists("package/".$packagecodename."/generator/generator.predeployer.php"))
include "package/".$packagecodename."/generator/generator.predeployer.php";
//reload initer
$this->reloadIniter();
//load db generator
$chemin_db_generator_tpl="package/".$packagecodename."/generator/generator.db.deployer.__INSTANCE__.".$sqltype.".tpl";
if(isset($this->db) && $this->db && file_exists($chemin_db_generator_tpl))
{
//pour chaque instance à générer
foreach($confgenerator->instance as $instance)
{
//generate sql
$instanceTpl=new Tp($this->conf,$this->log,"backoffice");
$tpl=$instanceTpl->tpselected;
//include generator conf tpl
$tabgeneratorconftpl=$this->loader->charg_generatorconftpl_dans_tab("package/".$packagecodename."/generator");
$tpl->remplir_template("generatorconf",$tabgeneratorconftpl);
//include generator file cour
$tpl->remplir_template("chemintpltogenerate",$chemin_db_generator_tpl);
//preparedatafortpl
$datafortpl=array();
if(isset($instanceGenerator))
$datafortpl=$instanceGenerator->prepareDataForTpl($instance);
foreach($datafortpl as $iddatafortpl=>$contentdatafortpl)
$tpl->remplir_template($iddatafortpl,$contentdatafortpl);
//generate file with tpl
$contentfilecour=$tpl->get_template($this->chemingeneratortpl);
$namefilecour=str_replace("__INSTANCE__",$instance->name,$chemin_db_generator_tpl);
$namefilecour=substr($namefilecour,0,-4);
$namefilecour=str_replace("package/".$packagecodename."/generator/",$this->folderdestdb.$packagecodename.".",$namefilecour);
//conflict resolution "keep" mode
if($this->conflictresolution=="keep")
{
$cptconflict="1";
$conflictnamefilecour=$namefilecour;
while(file_exists($conflictnamefilecour))
$conflictnamefilecour=str_replace($this->folderdestdb,$this->folderdestdb."___CONFLICTFILE".($cptconflict++)."___",$namefilecour);
$namefilecour=$conflictnamefilecour;
}
//conflict resolution "reverse" mode
if($this->conflictresolution!=null)
{
//conflict management
$cptconflict="1";
if(file_exists($namefilecour))
{
do
{
$conflictnamefilecour=str_replace($this->folderdestdb,$this->folderdestdb."___CONFLICTFILE".($cptconflict++)."___",$namefilecour);
}
while(file_exists($this->conflictfolder."/".$conflictnamefilecour));
if(!is_dir($this->conflictfolder."/".$this->folderdestdb))
mkdir($this->conflictfolder."/".$this->folderdestdb,0777,true);
copy($namefilecour,$this->conflictfolder."/".$conflictnamefilecour);
//set conflictfilelist
$this->addToConflictFile($conflictnamefilecour);
}
//setup annuaire files in package
$this->addToFileIsInPackageFile($packagecodename,$namefilecour);
}
//file create
file_put_contents($namefilecour,$contentfilecour);
//return tab
$tabdeployedfiles[]=$namefilecour;
//load db
$sqltoload=file_get_contents($namefilecour);
$tabsqltoload=explode(";",$sqltoload);
foreach($tabsqltoload as $sqlcour)
{
$req=$this->db->query($sqlcour);
}
}
}
//load generator dump if exists
$dumper=null;
if((class_exists("PratikDump") || (isset($this->includer) && $this->includer->include_pratikclass("Dump"))) && isset($this->instanceConf) && $this->instanceConf!=null)
{
$dumpname="dump.".$packagecodename."___generator";
$instanceDump=new PratikDump($this->initer,$dumpname);
$packagelastdumptoload=$instanceDump->getLastDump($dumpname);
if($packagelastdumptoload!="")
{
//load dump
$dumper=$instanceDump->dumpselected;
$dumper->importDump($packagelastdumptoload);
}
}
//load files generator
foreach($this->initer['chaintab'] as $chaincour)
{
$tabfilestoload=$this->loader->charg_dossier_dans_tab("package/".$packagecodename."/generator/".$chaincour);
if(isset($tabfilestoload))
foreach($tabfilestoload as $filecour)
{
$folder=substr($filecour,0,strrpos($filecour,"/"));
$file=substr($filecour,strrpos($filecour,"/"),strlen($filecour)-4-strrpos($filecour,"/"));
if($folder=="package/".$packagecodename."/generator/".$chaincour)
continue;
$folder=str_replace("package/".$packagecodename."/generator/".$chaincour."/","",$folder);
if(!is_dir($folder))
mkdir($folder,0777,true);
//pour chaque instance à générer
if($confgenerator && $confgenerator->instance)
foreach($confgenerator->instance as $instance)
{
//prepare chemin file with instance
$file_generate=str_replace("__INSTANCE__",$instance->name,$file);
//conflict resolution "keep" mode
if($this->conflictresolution=="keep")
{
$cptconflict="1";
$conflictnamefilecour=$file_generate;
while(file_exists($folder.$conflictnamefilecour))
$conflictnamefilecour="/___CONFLICTFILE".($cptconflict++)."___".substr($file_generate,1);
$file_generate=$conflictnamefilecour;
}
//conflict resolution "reverse" mode
if($this->conflictresolution!=null)
{
//conflict management
$cptconflict="1";
if(file_exists($folder.$file_generate))
{
do
{
$conflictnamefilecour="/___CONFLICTFILE".($cptconflict++)."___".substr($file_generate,1);
}
while(file_exists($this->conflictfolder."/".$folder.$conflictnamefilecour));
if(!is_dir($this->conflictfolder."/".$folder))
mkdir($this->conflictfolder."/".$folder,0777,true);
copy($folder.$file_generate,$this->conflictfolder."/".$folder.$conflictnamefilecour);
//set conflictfilelist
$this->addToConflictFile($folder.$conflictnamefilecour);
}
//setup annuaire files in package
$this->addToFileIsInPackageFile($packagecodename,$folder.$file_generate);
}
//chemin file ok
$chemin_file_generator_tpl=$folder.$file_generate;
//generate file
$instanceTpl=new Tp($this->conf,$this->log,"backoffice");
$tpl=$instanceTpl->tpselected;
//include generator conf tpl
$tabgeneratorconftpl=$this->loader->charg_generatorconftpl_dans_tab("package/".$packagecodename."/generator");
$tpl->remplir_template("generatorconf",$tabgeneratorconftpl);
//include generator file cour
$tpl->remplir_template("chemintpltogenerate",$filecour);
//preparedatafortpl
$datafortpl=array();
if(isset($instanceGenerator))
$datafortpl=$instanceGenerator->prepareDataForTpl($instance);
foreach($datafortpl as $iddatafortpl=>$contentdatafortpl)
$tpl->remplir_template($iddatafortpl,$contentdatafortpl);
//generate file with tpl
$contentfilecour=$tpl->get_template($this->chemingeneratortpl);
file_put_contents($chemin_file_generator_tpl,$contentfilecour);
//return tab
$tabdeployedfiles[]=$chemin_file_generator_tpl;
}
}
}
//reconstruct initer with last files deploy
if(class_exists("PratikInitersimul") || (isset($this->includer) && $this->includer->include_pratikclass("Initersimul")))
{
$instanceInitersimul=new PratikInitersimul($this->initer);
$newiniter=$instanceInitersimul->initerConstruct($this->initer);
$this->reloadIniter($newiniter);
}
//include postdeployer generator
if(file_exists("package/".$packagecodename."/generator/generator.postdeployer.php"))
include "package/".$packagecodename."/generator/generator.postdeployer.php";
//reload initer
$this->reloadIniter();
if(isset($this->db) && $this->db)
$this->db->query("update `package` set deployed='1' where nomcodepackage='".$packagecodename."'");
return $tabdeployedfiles;
}
return array();
}
function destroy($packagecodename="example")
{
//destroy package
$this->initer['packagecodename']=$packagecodename;
$classpackagename="";
$tabclassname=explode(".",$packagecodename);
foreach($tabclassname as $classnamecour)
$classpackagename.=ucfirst(strtolower($classnamecour));
if(file_exists("package/".$packagecodename))
{
//include descripter
$this->initer['descripter']=array();
if(file_exists("package/".$packagecodename."/package.descripter.php"))
include "package/".$packagecodename."/package.descripter.php";
if(isset($descripter))
$this->initer['descripter']=$descripter;
//load conf package
$confstatic=null;
if(file_exists("package/".$packagecodename."/conf.static.xml"))
$confstatic=simplexml_load_file("package/".$packagecodename."/conf.static.xml");
$this->initer['confstatic']=$confstatic;
//get conf form saved (already present in $this->conf)
$this->initer['confform']=null;
//reload initer
$this->reloadIniter();
//include predestroyer static
$instanceStatic=null;
if(file_exists("package/".$packagecodename."/class/class.static.php"))
{
include "package/".$packagecodename."/class/class.static.php";
eval("\$instanceStatic=new ".$classpackagename."Static(\$this->initer);");
}
if(file_exists("package/".$packagecodename."/static/static.predestroyer.php"))
include "package/".$packagecodename."/static/static.predestroyer.php";
//reload initer
$this->reloadIniter();
//kill db static
$sqltype=$this->getExtSql();
if(isset($this->db) && $this->db && file_exists("package/".$packagecodename."/static/static.db.destroyer.".$sqltype))
{
//start dump
$dumper=null;
if((class_exists("PratikDump") || (isset($this->includer) && $this->includer->include_pratikclass("Dump"))) && isset($this->instanceConf) && $this->instanceConf!=null)
{
$dumpname="dump.".$packagecodename."___static";
$instanceDump=new PratikDump($this->initer,$dumpname);
$dumper=$instanceDump->dumpselected;
$dumper->startDump();
}
//get sql file
$sqltoload=file_get_contents("package/".$packagecodename."/static/static.db.destroyer.".$sqltype);
$tabsqltoload=explode(";",$sqltoload);
foreach($tabsqltoload as $sqlcour)
{
//prepare dump for this sql line (cas drop table)
if($dumper)
{
$tabtabletokill=$this->checkDropTable($sqlcour);
foreach($tabtabletokill as $tablecour)
$dumper->getTableData($tablecour,false);
}
//exec sql line
$req=$this->db->query($sqlcour);
}
//end dump
if($dumper)
{
$dumper->endDump();
}
}
//kill files static
foreach($this->initer['chaintab'] as $chaincour)
{
$tabfilestoload=$this->loader->charg_dossier_dans_tab("package/".$packagecodename."/static/".$chaincour);
if($tabfilestoload)
foreach($tabfilestoload as $filecour)
{
$folder=substr($filecour,0,strrpos($filecour,"/"));
$file=substr($filecour,strrpos($filecour,"/"),strlen($filecour)-0-strrpos($filecour,"/"));
if($folder=="package/".$packagecodename."/static/".$chaincour)
continue;
$folder=str_replace("package/".$packagecodename."/static/".$chaincour."/","",$folder);
if(file_exists($folder.$file))
{
//conflict "reverse" mode
if($this->conflictresolution!=null)
{
//maj fileisinpackage.php
$this->addToFileIsInPackageFile($packagecodename,$folder.$file,"unset");
if($this->conflictresolution=="force" || $this->conflictresolution=="keep")
unlink($folder.$file);
//check if a conflict file exists ___CONFLICT... else suppr file and continue
if(!file_exists($this->conflictfolder."/".$folder."/___CONFLICTFILE1___".substr($file,1)))
{
if(file_exists($folder.$file))
unlink($folder.$file);
continue;
}
//if a conflict file exists, find conflict for this package codename in tabconflict in conflict.php
include $this->conflictfolder."/conflict.php";
$cptconflict="1";
$filecour=$folder."/___CONFLICTFILE".$cptconflict."___".substr($file,1);
$conflictfile="";
$cptconflictfound=0;
while(file_exists($this->conflictfolder."/".$filecour))
{
$tabid=str_replace("/","-----",$filecour);
if(isset($tabconflict[$tabid]) && $tabconflict[$tabid]==$packagecodename)
{
$conflictfile=$filecour;
$cptconflictfound=$cptconflict;
break;
}
$cptconflict++;
$filecour=$folder."/___CONFLICTFILE".$cptconflict."___".substr($file,1);
}
//if not found, suppr file and move last conflict file instead of it
if($conflictfile=="")
{
//suppr file
unlink($folder.$file);
//move last conflict file to official file
$cptconflictlast=(--$cptconflict);
if($this->conflictresolution=="reverse")
rename($this->conflictfolder."/".$folder."/___CONFLICTFILE".$cptconflictlast."___".substr($file,1),$folder.$file);
//clear last conflict file (check kill and clear in $tabconflict in conflict.php)
if(file_exists($this->conflictfolder."/".$folder."/___CONFLICTFILE".$cptconflictlast."___".substr($file,1)))
unlink($this->conflictfolder."/".$folder."/___CONFLICTFILE".$cptconflictlast."___".substr($file,1));
//rewrite conflict files in tabconflict in conflict.php (add new lines with unset($tabconflict[lastconflictile]) )
$filecour=$this->conflictfolder."/".$folder."/___CONFLICTFILE".$cptconflictlast."___".substr($file,1);
$this->addToConflictFile($filecour,"unset");
}
//if conflict found, suppr conflict and reorder the next ones and rewrite them in tabconflict in conflict.php and DO NOT suppr file in use
else
{
//suppr conflict file
unlink($this->conflictfolder."/".$conflictfile);
//reorder next conflict files
$cptconflict=(++$cptconflictfound);
$filecour=$folder."/___CONFLICTFILE".$cptconflict."___".substr($file,1);
while(file_exists($this->conflictfolder."/".$filecour))
{
//move to prec conflict file
$destfilecour=$folder."/___CONFLICTFILE".($cptconflict-1)."___".substr($file,1);
rename($this->conflictfolder."/".$filecour,$this->conflictfolder."/".$destfilecour);
//rewrite conflict files in tabconflict in conflict.php (add new lines with $tabconflict[cour]=$tabconflict[prec] or unset($tabconflict[cour]) )
$this->addToConflictFile($filecour,"update",array('destfile'=>$destfilecour));
//next
$cptconflict++;
$filecour=$folder."/___CONFLICTFILE".$cptconflict."___".substr($file,1);
}
//end rewrite conflict files in tabconflict in conflict.php (unset($tabconflict[cour] for last conflict file) )
$filecour=$folder."/___CONFLICTFILE".($cptconflict-1)."___".substr($file,1);
$this->addToConflictFile($filecour,"unset");
}
}
else
{
//suppr file
unlink($folder.$file);
}
}
}
}
//include postdestroyer static
if(file_exists("package/".$packagecodename."/static/static.postdestroyer.php"))
include "package/".$packagecodename."/static/static.postdestroyer.php";
//reload initer
$this->reloadIniter();
//load conf package generator
$confgenerator=null;
if(file_exists("package/".$packagecodename."/conf.generator.xml"))
$confgenerator=simplexml_load_file("package/".$packagecodename."/conf.generator.xml");
$this->initer['confgenerator']=$confgenerator;
//reload initer
$this->reloadIniter();
//include predestroyer generator
$instanceGenerator=null;
if(file_exists("package/".$packagecodename."/class/class.generator.php"))
{
include "package/".$packagecodename."/class/class.generator.php";
eval("\$instanceGenerator=new ".$classpackagename."Generator(\$this->initer);");
}
if(file_exists("package/".$packagecodename."/generator/generator.predestroyer.php"))
include "package/".$packagecodename."/generator/generator.predestroyer.php";
//reload initer
$this->reloadIniter();
//kill db generator
$chemin_db_generator_tpl="package/".$packagecodename."/generator/generator.db.destroyer.__INSTANCE__.".$sqltype.".tpl";
if(isset($this->db) && $this->db && file_exists($chemin_db_generator_tpl))
{
//start dump
$dumper=null;
if((class_exists("PratikDump") || (isset($this->includer) && $this->includer->include_pratikclass("Dump"))) && isset($this->instanceConf) && $this->instanceConf!=null)
{
$dumpname="dump.".$packagecodename."___generator";
$instanceDump=new PratikDump($this->initer,$dumpname);
$dumper=$instanceDump->dumpselected;
$dumper->startDump();
}
//pour chaque instance à générer
foreach($confgenerator->instance as $instance)
{
//generate sql
$instanceTpl=new Tp($this->conf,$this->log,"backoffice");
$tpl=$instanceTpl->tpselected;
//include generator conf tpl
$tabgeneratorconftpl=$this->loader->charg_generatorconftpl_dans_tab("package/".$packagecodename."/generator");
$tpl->remplir_template("generatorconf",$tabgeneratorconftpl);
//include generator file cour
$tpl->remplir_template("chemintpltogenerate",$chemin_db_generator_tpl);
//preparedatafortpl
$datafortpl=array();
if(isset($instanceGenerator))
$datafortpl=$instanceGenerator->prepareDataForTpl($instance);
foreach($datafortpl as $iddatafortpl=>$contentdatafortpl)
$tpl->remplir_template($iddatafortpl,$contentdatafortpl);
//generate file with tpl
$contentfilecour=$tpl->get_template($this->chemingeneratortpl);
$namefilecour=str_replace("__INSTANCE__",$instance->name,$chemin_db_generator_tpl);
$namefilecour=substr($namefilecour,0,-4);
file_put_contents($namefilecour,$contentfilecour);
//load db
$sqltoload=file_get_contents($namefilecour);
$tabsqltoload=explode(";",$sqltoload);
foreach($tabsqltoload as $sqlcour)
{
//prepare dump for this sql line (cas drop table)
if($dumper)
{
$tabtabletokill=$this->checkDropTable($sqlcour);
foreach($tabtabletokill as $tablecour)
$dumper->getTableData($tablecour,false);
}
//exec sql line
$req=$this->db->query($sqlcour);
}
}
//end dump
if($dumper)
{
$dumper->endDump();
}
}
//kill files generator
foreach($this->initer['chaintab'] as $chaincour)
{
$tabfilestoload=$this->loader->charg_dossier_dans_tab("package/".$packagecodename."/generator/".$chaincour);
if($tabfilestoload)
foreach($tabfilestoload as $filecour)
{
$folder=substr($filecour,0,strrpos($filecour,"/"));
$file=substr($filecour,strrpos($filecour,"/"),strlen($filecour)-4-strrpos($filecour,"/"));
if($folder=="package/".$packagecodename."/generator/".$chaincour)
continue;
$folder=str_replace("package/".$packagecodename."/generator/".$chaincour."/","",$folder);
//pour chaque instance à générer
foreach($confgenerator->instance as $instance)
{
//prepare chemin file with instance
$file_generate=str_replace("__INSTANCE__",$instance->name,$file);
$chemin_file_generator_tpl=$folder.$file_generate;
if(file_exists($chemin_file_generator_tpl))
{
//conflict "reverse" mode
if($this->conflictresolution!=null)
{
//maj fileisinpackage.php
$this->addToFileIsInPackageFile($packagecodename,$folder.$file_generate,$action="unset");
if($this->conflictresolution=="force" || $this->conflictresolution=="keep")
unlink($folder.$file_generate);
//check if a conflict file exists ___CONFLICT... else suppr file and continue
if(!file_exists($this->conflictfolder."/".$folder."/___CONFLICTFILE1___".substr($file_generate,1)))
{
if(file_exists($folder.$file_generate))
unlink($folder.$file_generate);
continue;
}
//if a conflict file exists, find conflict for this package codename in tabconflict in conflict.php
include $this->conflictfolder."/conflict.php";
$cptconflict="1";
$filecour=$folder."/___CONFLICTFILE".$cptconflict."___".substr($file_generate,1);
$conflictfile="";
$cptconflictfound=0;
while(file_exists($this->conflictfolder."/".$filecour))
{
$tabid=str_replace("/","-----",$filecour);
if(isset($tabconflict[$tabid]) && $tabconflict[$tabid]==$packagecodename)
{
$conflictfile=$tabid;
$cptconflictfound=$cptconflict;
break;
}
$cptconflict++;
$filecour=$folder."/___CONFLICTFILE".$cptconflict."___".substr($file_generate,1);
}
//if not found, suppr file and move last conflict file instead of it
if($conflictfile=="")
{
//suppr file
unlink($folder.$file_generate);
//move last conflict file to official file
$cptconflictlast=(--$cptconflict);
if($this->conflictresolution=="reverse")
rename($this->conflictfolder."/".$folder."/___CONFLICTFILE".$cptconflictlast."___".substr($file_generate,1),$folder.$file_generate);
//clear last conflict file (check kill and clear in $tabconflict in conflict.php)
if(file_exists($this->conflictfolder."/".$folder."/___CONFLICTFILE".$cptconflictlast."___".substr($file_generate,1)))
unlink($this->conflictfolder."/".$folder."/___CONFLICTFILE".$cptconflictlast."___".substr($file_generate,1));
//rewrite conflict files in tabconflict in conflict.php (add new lines with unset($tabconflict[lastconflictile]) )
$filecour=$this->conflictfolder."/".$folder."/___CONFLICTFILE".$cptconflictlast."___".substr($file_generate,1);
$this->addToConflictFile($filecour,"unset");
}
//if conflict found, suppr conflict and reorder the next ones and rewrite them in tabconflict in conflict.php and DO NOT suppr file in use
else
{
//suppr conflict file
unlink($this->conflictfolder."/".$conflictfile);
//reorder next conflict files
$cptconflict=(++$cptconflictfound);
$filecour=$folder."/___CONFLICTFILE".$cptconflict."___".substr($file_generate,1);
while(file_exists($this->conflictfolder."/".$filecour))
{
//move to prec conflict file
$destfilecour=$folder."/___CONFLICTFILE".($cptconflict-1)."___".substr($file_generate,1);
rename($this->conflictfolder."/".$filecour,$this->conflictfolder."/".$destfilecour);
//rewrite conflict files in tabconflict in conflict.php (add new lines with $tabconflict[cour]=$tabconflict[prec] or unset($tabconflict[cour]) )
$this->addToConflictFile($filecour,"update",array('destfile'=>$destfilecour));
//next
$cptconflict++;
$filecour=$folder."/___CONFLICTFILE".$cptconflict."___".substr($file_generate,1);
}
//end rewrite conflict files in tabconflict in conflict.php (unset($tabconflict[cour] for last conflict file) )
$filecour=$folder."/___CONFLICTFILE".($cptconflict-1)."___".substr($file_generate,1);
$this->addToConflictFile($filecour,"unset");
}
}
else
{
unlink($chemin_file_generator_tpl);
}
}
}
}
}
//include postdestroyer generator
if(file_exists("package/".$packagecodename."/generator/generator.postdestroyer.php"))
include "package/".$packagecodename."/generator/generator.postdestroyer.php";
//reload initer
$this->reloadIniter();
if(isset($this->db) && $this->db)
$this->db->query("update `package` set deployed='0' where nomcodepackage='".$packagecodename."'");
}
}
function preparePackageConfForm($packagecodename="example")
{
$preform=array();
$preform['classicform']=true;
$preform['deployconfirmbutton']=true;
$preform['destroyconfirmbutton']=true;
$preform['updateconfirmbutton']=true;
$preform['totaldestroyconfirmbutton']=true;
$preform['reverseconfirmbutton']=true;
$preform['localreverseconfirmbutton']=true;
$preform['hiddencodename']=true;
$confform=null;
if(file_exists("package/".$packagecodename."/conf.form.xml"))
{
$confform=simplexml_load_file("package/".$packagecodename."/conf.form.xml");
$form=$confform->form;
foreach($form->field as $field)
{
$preform['lineform'][]=array();
$preform['lineform'][count($preform['lineform']) -1]['label']=$field->label;
$preform['lineform'][count($preform['lineform']) -1]['name']="confform[".$packagecodename."][".$field->name."]";
$preform['lineform'][count($preform['lineform']) -1]['default']=$field->default;
$preform['lineform'][count($preform['lineform']) -1]['champs']="text";
}
}
return $preform;
}
function rrmdir($dir) {
if (is_dir($dir)) {
$objects = scandir($dir);
foreach ($objects as $object) {
if ($object != "." && $object != "..") {
if (filetype($dir."/".$object) == "dir"){
$this->rrmdir($dir."/".$object);
}else{
unlink($dir."/".$object);
}
}
}
reset($objects);
//force close dir before remove (php7)
$closer=opendir($dir);
closedir($closer);
rmdir($dir);
}
}
function getPackageFromRoDKoDRoKCom($packagecodename="example",$update="")
{
if(file_exists("package/".$packagecodename) && $update)
{
//keep some old files before starting update
if($update)
{
if(file_exists("package/".$packagecodename."/conf.static.xml"))
copy("package/".$packagecodename."/conf.static.xml",$this->folderdestarchives.$packagecodename.".conf.static.xml");
if(file_exists("package/".$packagecodename."/conf.generator.xml"))
copy("package/".$packagecodename."/conf.generator.xml",$this->folderdestarchives.$packagecodename.".conf.generator.xml");
if(file_exists("package/".$packagecodename."/static/static.db.deployer.sql"))
copy("package/".$packagecodename."/static/static.db.deployer.sql",$this->folderdestarchives.$packagecodename.".static.db.deployer.sql");
if(file_exists("package/".$packagecodename."/generator/generator.db.deployer.__INSTANCE__.sql.tpl"))
copy("package/".$packagecodename."/generator/generator.db.deployer.__INSTANCE__.sql.tpl",$this->folderdestarchives.$packagecodename.".generator.db.deployer.__INSTANCE__.sql.tpl");
}
//zip and archive old package with date in filename
if($this->zipAndArchivePackage($packagecodename))
{
//kill old package
$dir = "package/".$packagecodename;
$this->rrmdir($dir);
}
}
if(!file_exists("package/".$packagecodename))
{
//upload package zip from url
$force=false;
if($update)
$force=true;
$downloaded=$this->downloadPackageFromUrl($packagecodename,$force);
//dezip package
if($downloaded)
if($this->unzipPackage($packagecodename))
{
//update db for new package
if(isset($this->db))
{
$descripter=array();
$descripter['name']="";
$descripter['description']="";
$descripter['version']="";
$descripter['groupe']="";
if(file_exists("package/".$packagecodename."/package.descripter.php"))
include "package/".$packagecodename."/package.descripter.php";
//update dans la db
$this->db->query("update `package` set nompackage='".$descripter['name']."', groupepackage='".$descripter['groupe']."', description='".$descripter['description']."', version='".$descripter['version']."' where nomcodepackage='".$packagecodename."'");
//ajout des dependances
if(isset($descripter['depend']) && is_array($descripter['depend']))
foreach($descripter['depend'] as $dependcour)
if($dependcour!="")
$this->db->query("insert into `package_depends_on` (`nomcodepackage`, `nomcodedepend`) values ('".$packagecodename."','".$dependcour."')");
}
return true;
}
return false;
}
return true;
}
function downloadPackageFromUrl($packagecodename="example",$force=false)
{
$folderdest=$this->folderdestdownload;
$filename=$packagecodename.".zip";
//folder packages downloaded
if(!is_dir($folderdest))
mkdir($folderdest,0777,true);
//kill old file if force
if(file_exists($folderdest.$filename))
if($force)
unlink($folderdest.$filename);
else
return true;
//search download mirror and upload new file
$filelink="";
if(class_exists("PratikDownloader") || (isset($this->includer) && $this->includer->include_pratikclass("Downloader")))
{
$donwloader=new PratikDownloader($this->initer);
$filelink=$donwloader->getFileLink($filename,"packages");
}
if($filelink!="")
{
$filedata=file_get_contents($filelink);
file_put_contents($folderdest.$filename,$filedata);
chmod($folderdest.$filename, 0777);
return true;
}
return false;
}
function unzipPackage($packagecodename="example")
{
$folderzip=$this->folderdestdownload;
$folderdestunzip=$this->folderdestpackage;
$filename=$packagecodename.".zip";
if(file_exists($folderzip.$filename))
{
//unzip
$zip = new ZipArchive;
$res = $zip->open($folderzip.$filename);
if ($res === TRUE) {
$zip->extractTo($folderdestunzip);
$zip->close();
return true;
}
}
return false;
}
function zipAndArchivePackage($packagecodename="example")
{
$folderpackage=$this->folderdestpackage;
$folderdestzipandarchive=$this->folderdestarchives;
$filename=date("YmdHis_____").$packagecodename.".zip";
if(file_exists($folderpackage.$packagecodename))
{
//zip
// Get real path for our folder
$rootPath = realpath($folderpackage.$packagecodename);
// Initialize archive object
$zip = new ZipArchive();
$zip->open($folderdestzipandarchive.$filename, ZipArchive::CREATE | ZipArchive::OVERWRITE);
// Create recursive directory iterator
/** @var SplFileInfo[] $files */
$files = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($rootPath),
RecursiveIteratorIterator::LEAVES_ONLY
);
foreach ($files as $name => $file)
{
// Skip directories (they would be added automatically)
if (!$file->isDir())
{
// Get real and relative path for current file
$filePath = $file->getRealPath();
$relativePath = substr($filePath, strlen($rootPath) + 1);
// Add current file to archive
$zip->addFile($filePath, $relativePath);
}
}
// Zip archive will be created only after closing object
$zip->close();
return true;
}
return false;
}
function getExtSql()
{
$sqltype="sql";
if(isset($this->conf['maindb']['moteurbd']))
{
$dbcour=strtolower($this->conf['maindb']['moteurbd']);
switch($dbcour)
{
case "mysql":
$sqltype="sql";
break;
default:
$sqltype="sql";
break;
}
}
return $sqltype;
}
function setConflictResolution($conflictresolution="force")
{
$this->conflictresolution=$conflictresolution;
}
function getConflictResolution()
{
return $this->conflictresolution;
}
function checkDependAreDeployedForPackage($packagecodename="example")
{
//check depend are deployed
$reqdepend=$this->db->query("select * from `package` where deployed='0' and nomcodepackage in (select nomcodedepend from `package_depends_on` where nomcodepackage='".$packagecodename."')");
if($resdepend=$this->db->fetch_array($reqdepend))
return false;
return true;
}
function addToConflictFile($conflictfilename,$action="add",$params=array())
{
//for conflict "reverse" mode
if(!file_exists($this->conflictfolder."/conflict.php"))
file_put_contents($this->conflictfolder."/conflict.php","<?php \n?>");
$conflictcontent=file_get_contents($this->conflictfolder."/conflict.php");
$conflictcontent=substr($conflictcontent,0,-2);
//filename prepare
$conflictfilename=str_replace("/","-----",$conflictfilename);
if($action=="add")
{
//check fileisinpackage exists
if(!file_exists($this->conflictfolder."/fileisinpackage.php"))
file_put_contents($this->conflictfolder."/fileisinpackage.php","<?php \n?>");
//packagecodename prepare
include $this->conflictfolder."/fileisinpackage.php";
$orginalfilenamestart=substr($conflictfilename,0,strpos($conflictfilename,"___CONFLICTFILE"));
$orginalfilenameend=substr($conflictfilename,(strpos($conflictfilename,"___CONFLICTFILE")+strlen("___CONFLICTFILE")));
$orginalfilenameend=substr($orginalfilenameend,(strpos($orginalfilenameend,"___")+strlen("___")));
$originalfilename=$orginalfilenamestart.$orginalfilenameend;
$packagecodename="";
if(isset($tabfileisinpackage[$originalfilename]))
$packagecodename=$tabfileisinpackage[$originalfilename];
$conflictcontent.="\$tabconflict['".$conflictfilename."']='".$packagecodename."';";
}
if($action=="update")
{
$destfilename=$params['destfile'];
$destfilename=str_replace("/","-----",$destfilename);
$conflictcontent.="\$tabconflict['".$conflictfilename."']=\$tabconflict['".$destfilename."'];";
}
if($action=="unset")
{
$conflictcontent.="unset(\$tabconflict['".$conflictfilename."']);";
}
$conflictcontent.="\n?>";
file_put_contents($this->conflictfolder."/conflict.php",$conflictcontent);
}
function addToFileIsInPackageFile($packagecodename,$filename,$action="add")
{
//for conflict "reverse" mode
if(!file_exists($this->conflictfolder."/fileisinpackage.php"))
file_put_contents($this->conflictfolder."/fileisinpackage.php","<?php \n?>");
$conflictcontent=file_get_contents($this->conflictfolder."/fileisinpackage.php");
$conflictcontent=substr($conflictcontent,0,-2);
$filename=str_replace("/","-----",$filename);
if($action=="add")
$conflictcontent.="\$tabfileisinpackage['".$filename."']='".$packagecodename."';";
if($action=="unset")
$conflictcontent.="unset(\$tabfileisinpackage['".$filename."']);";
$conflictcontent.="\n?>";
file_put_contents($this->conflictfolder."/fileisinpackage.php",$conflictcontent);
}
function update($packagecodename="example")
{
//conflict init
if($this->conflictresolution!=null && !is_dir($this->conflictfolder))
mkdir($this->conflictfolder,0777,true);
//update package
$this->initer['update']="update";
$this->initer['packagecodename']=$packagecodename;
$classpackagename="";
$tabclassname=explode(".",$packagecodename);
foreach($tabclassname as $classnamecour)
$classpackagename.=ucfirst(strtolower($classnamecour));
if(file_exists("package/".$packagecodename))
{
//tab deployed files
$tabdeployedfiles=array();
//include descripter
$this->initer['descripter']=array();
if(file_exists("package/".$packagecodename."/package.descripter.php"))
include "package/".$packagecodename."/package.descripter.php";
if(isset($descripter))
$this->initer['descripter']=$descripter;
//check if you keep old conf
if(isset($this->initer['descripter']['update']['keepconfstatic']) && $this->initer['descripter']['update']['keepconfstatic'])
{
if(file_exists("package/".$packagecodename."/conf.static.xml"))
unlink("package/".$packagecodename."/conf.static.xml");
rename($this->folderdestarchives.$packagecodename.".conf.static.xml","package/".$packagecodename."/conf.static.xml");
}
if(file_exists($this->folderdestarchives.$packagecodename.".conf.static.xml"))
unlink($this->folderdestarchives.$packagecodename.".conf.static.xml");
//load conf package
$confstatic=null;
if(file_exists("package/".$packagecodename."/conf.static.xml"))
$confstatic=simplexml_load_file("package/".$packagecodename."/conf.static.xml");
$this->initer['confstatic']=$confstatic;
//load conf form package
if(isset($_POST['confform'][$packagecodename]))
$this->initer['confform'][$packagecodename]=$_POST['confform'][$packagecodename];
if(isset($_SESSION['confform'][$packagecodename]))
$this->initer['confform'][$packagecodename]=$_SESSION['confform'][$packagecodename];
//reload initer
$this->reloadIniter();
//include predeployer static
if(file_exists("package/".$packagecodename."/class/class.static.php"))
{
include "package/".$packagecodename."/class/class.static.php";
eval("\$instanceStatic=new ".$classpackagename."Static(\$this->initer);");
}
if(file_exists("package/".$packagecodename."/static/static.predeployer.php"))
include "package/".$packagecodename."/static/static.predeployer.php";
//reload initer
$this->reloadIniter();
//db static upload
$filesizeoldsql=0;
$filesizenewsql=0;
if(file_exists($this->folderdestarchives.$packagecodename.".static.db.deployer.sql"))
{
$filesizeoldsql=filesize($this->folderdestarchives.$packagecodename.".static.db.deployer.sql");
$filesizenewsql=filesize("package/".$packagecodename."/static/static.db.deployer.sql");
unlink($this->folderdestarchives.$packagecodename.".static.db.deployer.sql");
}
if($filesizeoldsql!=$filesizenewsql)
{
//kill db static
$sqltype=$this->getExtSql();
if(isset($this->db) && $this->db && file_exists("package/".$packagecodename."/static/static.db.destroyer.".$sqltype))
{
//start dump
$dumper=null;
if((class_exists("PratikDump") || (isset($this->includer) && $this->includer->include_pratikclass("Dump"))) && isset($this->instanceConf) && $this->instanceConf!=null)
{
$dumpname="dump.".$packagecodename."___static";
$instanceDump=new PratikDump($this->initer,$dumpname);
$dumper=$instanceDump->dumpselected;
$dumper->startDump();
}
//get sql file
$sqltoload=file_get_contents("package/".$packagecodename."/static/static.db.destroyer.".$sqltype);
$tabsqltoload=explode(";",$sqltoload);
foreach($tabsqltoload as $sqlcour)
{
//fill dump for the tables of this sql line (cas drop table)
if($dumper)
{
$tabtabletokill=$this->checkDropTable($sqlcour);
foreach($tabtabletokill as $tablecour)
$dumper->getTableData($tablecour,false);
}
//exec sql line
$req=$this->db->query($sqlcour);
}
//end dump
if($dumper)
{
$dumper->endDump();
}
}
//load db static
$sqltype=$this->getExtSql();
$chemin_db_static="package/".$packagecodename."/static/static.db.deployer.".$sqltype;
if(isset($this->db) && $this->db && file_exists($chemin_db_static))
{
//sql exec
$sqltoload=file_get_contents($chemin_db_static);
$tabsqltoload=explode(";",$sqltoload);
foreach($tabsqltoload as $sqlcour)
{
$req=$this->db->query($sqlcour);
}
//filename creation
$namefilecour=str_replace("package/".$packagecodename."/static/",$this->folderdestdb.$packagecodename.".",$chemin_db_static);
//conflict resolution "reverse" mode
if($this->conflictresolution!=null)
{
//only if new file
if(!file_exists($namefilecour))
{
//setup annuaire files in package
$this->addToFileIsInPackageFile($packagecodename,$namefilecour);
//replace original file
file_put_contents($namefilecour,$sqltoload);
}
else
{
//find existing conflict
$conflictnamefilecour=str_replace($this->folderdestdb,$this->folderdestdb."___CONFLICTFILE1___",$namefilecour);
$conflictfilefound="";
if(file_exists($this->conflictfolder."/".$conflictnamefilecour))
{
$cptconflict="1";
while(file_exists($this->conflictfolder."/".$conflictnamefilecour))
{
include $this->conflictfolder."/conflict.php";
$tabid=str_replace("/","-----",$conflictnamefilecour);
if(isset($tabconflict[$tabid]) && $tabconflict[$tabid]==$packagecodename)
{
$conflictfilefound=$conflictnamefilecour;
break;
}
$conflictnamefilecour=str_replace($this->folderdestdb,$this->folderdestdb."___CONFLICTFILE".($cptconflict++)."___",$namefilecour);
}
}
//if conflict found
if(file_exists($conflictfilefound))
{
//if conflict exists, replace only conflict file
if(!is_dir($this->conflictfolder."/".$this->folderdestdb))
mkdir($this->conflictfolder."/".$this->folderdestdb,0777,true);
copy($namefilecour,$this->conflictfolder."/".$conflictnamefilecour);
}
else
{
//replace original file
file_put_contents($namefilecour,$sqltoload);
}
}
}
else
{
//create file
file_put_contents($namefilecour,$sqltoload);
}
//return tab
$tabdeployedfiles[]=$namefilecour;
}
//recup dump with import
$dumper=null;
if((class_exists("PratikDump") || (isset($this->includer) && $this->includer->include_pratikclass("Dump"))) && isset($this->instanceConf) && $this->instanceConf!=null)
{
$dumpname="dump.".$packagecodename."___static";
$instanceDump=new PratikDump($this->initer,$dumpname);
$packagelastdumptoload=$instanceDump->getLastDump($dumpname);
if($packagelastdumptoload!="")
{
//load dump
$dumper=$instanceDump->dumpselected;
$dumper->importDump($packagelastdumptoload);
}
}
}
//load files static
foreach($this->initer['chaintab'] as $chaincour)
{
$tabfilestoload=$this->loader->charg_dossier_dans_tab("package/".$packagecodename."/static/".$chaincour);
if(isset($tabfilestoload))
foreach($tabfilestoload as $filecour)
{
$folder=substr($filecour,0,strrpos($filecour,"/"));
$file=substr($filecour,strrpos($filecour,"/"),strlen($filecour)-0-strrpos($filecour,"/"));
if($folder=="package/".$packagecodename."/static/".$chaincour)
continue;
$folder=str_replace("package/".$packagecodename."/static/".$chaincour."/","",$folder);
if(!is_dir($folder))
mkdir($folder,0777,true);
//conflict resolution "reverse" mode
if($this->conflictresolution!=null)
{
//only if new file
if(!file_exists($folder.$file))
{
//setup annuaire files in package
$this->addToFileIsInPackageFile($packagecodename,$folder.$file);
//replace original file
copy($filecour,$folder.$file);
}
else
{
//find existing conflict
$conflictnamefilecour="/___CONFLICTFILE1___".substr($file,1);
$conflictfilefound="";
if(file_exists($this->conflictfolder."/".$folder.$conflictnamefilecour))
{
$cptconflict="1";
while(file_exists($this->conflictfolder."/".$folder.$conflictnamefilecour))
{
include $this->conflictfolder."/conflict.php";
$tabid=str_replace("/","-----",$folder.$conflictnamefilecour);
if(isset($tabconflict[$tabid]) && $tabconflict[$tabid]==$packagecodename)
{
$conflictfilefound=$conflictnamefilecour;
break;
}
$conflictnamefilecour="/___CONFLICTFILE".($cptconflict++)."___".substr($file,1);
}
}
//if conflict found
if(file_exists($conflictfilefound))
{
//if conflict exists, replace only conflict file
if(!is_dir($this->conflictfolder."/".$folder))
mkdir($this->conflictfolder."/".$folder,0777,true);
copy($folder.$file,$this->conflictfolder."/".$folder.$conflictnamefilecour);
}
else
{
//replace original file
copy($filecour,$folder.$file);
}
}
}
else
{
//file create
copy($filecour,$folder.$file);
}
//return tab
$tabdeployedfiles[]=$folder.$file;
}
}
//reconstruct initer with last files deploy
if(class_exists("PratikInitersimul") || (isset($this->includer) && $this->includer->include_pratikclass("Initersimul")))
{
$instanceInitersimul=new PratikInitersimul($this->initer);
$newiniter=$instanceInitersimul->initerConstruct($this->initer);
$this->reloadIniter($newiniter);
}
//include postdeployer static
if(file_exists("package/".$packagecodename."/static/static.postdeployer.php"))
include "package/".$packagecodename."/static/static.postdeployer.php";
//reload initer
$this->reloadIniter();
//check if you keep old conf
if(isset($this->initer['descripter']['update']['keepconfgenerator']) && $this->initer['descripter']['update']['keepconfgenerator'])
{
if(file_exists("package/".$packagecodename."/conf.generator.xml"))
unlink("package/".$packagecodename."/conf.generator.xml");
rename($this->folderdestarchives.$packagecodename.".conf.generator.xml","package/".$packagecodename."/conf.generator.xml");
}
//load conf package generator
$confgenerator=null;
if(file_exists("package/".$packagecodename."/conf.generator.xml"))
$confgenerator=simplexml_load_file("package/".$packagecodename."/conf.generator.xml");
$this->initer['confgenerator']=$confgenerator;
//reload initer
$this->reloadIniter();
//include predeployer generator
$instanceGenerator=new PackageGenerator($this->initer);
if(file_exists("package/".$packagecodename."/class/class.generator.php"))
{
include "package/".$packagecodename."/class/class.generator.php";
eval("\$instanceGenerator=new ".$classpackagename."Generator(\$this->initer);");
}
if(file_exists("package/".$packagecodename."/generator/generator.predeployer.php"))
include "package/".$packagecodename."/generator/generator.predeployer.php";
//reload initer
$this->reloadIniter();
//db generator upload
$filesizeoldsql=0;
$filesizenewsql=0;
if(file_exists($this->folderdestarchives.$packagecodename.".conf.generator.xml"))
{
$filesizeoldsql=filesize($this->folderdestarchives.$packagecodename.".conf.generator.xml");
$filesizenewsql=filesize("package/".$packagecodename."/conf.generator.xml");
unlink($this->folderdestarchives.$packagecodename.".conf.generator.xml");
}
if(file_exists($this->folderdestarchives.$packagecodename.".generator.db.deployer.__INSTANCE__.sql.tpl"))
{
if($filesizeoldsql==$filesizenewsql)
{
$filesizeoldsql=filesize($this->folderdestarchives.$packagecodename.".generator.db.deployer.__INSTANCE__.sql.tpl");
$filesizenewsql=filesize("package/".$packagecodename."/generator/generator.db.deployer.__INSTANCE__.sql.tpl");
}
unlink($this->folderdestarchives.$packagecodename.".generator.db.deployer.__INSTANCE__.sql.tpl");
}
if($filesizeoldsql!=$filesizenewsql)
{
//kill db generator
$sqltype=$this->getExtSql();
$chemin_db_generator_tpl="package/".$packagecodename."/generator/generator.db.destroyer.__INSTANCE__.".$sqltype.".tpl";
if(isset($this->db) && $this->db && file_exists($chemin_db_generator_tpl))
{
//start dump
$dumper=null;
if((class_exists("PratikDump") || (isset($this->includer) && $this->includer->include_pratikclass("Dump"))) && isset($this->instanceConf) && $this->instanceConf!=null)
{
$dumpname="dump.".$packagecodename."___generator";
$instanceDump=new PratikDump($this->initer,$dumpname);
$dumper=$instanceDump->dumpselected;
$dumper->startDump();
}
//pour chaque instance à générer
foreach($confgenerator->instance as $instance)
{
//generate sql
$instanceTpl=new Tp($this->conf,$this->log,"backoffice");
$tpl=$instanceTpl->tpselected;
//include generator conf tpl
$tabgeneratorconftpl=$this->loader->charg_generatorconftpl_dans_tab("package/".$packagecodename."/generator");
$tpl->remplir_template("generatorconf",$tabgeneratorconftpl);
//include generator file cour
$tpl->remplir_template("chemintpltogenerate",$chemin_db_generator_tpl);
//preparedatafortpl
$datafortpl=array();
if(isset($instanceGenerator))
$datafortpl=$instanceGenerator->prepareDataForTpl($instance);
foreach($datafortpl as $iddatafortpl=>$contentdatafortpl)
$tpl->remplir_template($iddatafortpl,$contentdatafortpl);
//generate file with tpl
$contentfilecour=$tpl->get_template($this->chemingeneratortpl);
$namefilecour=str_replace("__INSTANCE__",$instance->name,$chemin_db_generator_tpl);
$namefilecour=substr($namefilecour,0,-4);
file_put_contents($namefilecour,$contentfilecour);
//load db
$sqltoload=file_get_contents($namefilecour);
$tabsqltoload=explode(";",$sqltoload);
foreach($tabsqltoload as $sqlcour)
{
//prepare dump for this sql line (cas drop table)
if($dumper)
{
$tabtabletokill=$this->checkDropTable($sqlcour);
foreach($tabtabletokill as $tablecour)
$dumper->getTableData($tablecour,false);
}
//exec sql line
$req=$this->db->query($sqlcour);
}
}
//end dump
if($dumper)
{
$dumper->endDump();
}
}
//load db generator
$sqltype=$this->getExtSql();
$chemin_db_generator_tpl="package/".$packagecodename."/generator/generator.db.deployer.__INSTANCE__.".$sqltype.".tpl";
if(isset($this->db) && $this->db && file_exists($chemin_db_generator_tpl))
{
//pour chaque instance à générer
foreach($confgenerator->instance as $instance)
{
//generate sql
$instanceTpl=new Tp($this->conf,$this->log,"backoffice");
$tpl=$instanceTpl->tpselected;
//include generator conf tpl
$tabgeneratorconftpl=$this->loader->charg_generatorconftpl_dans_tab("package/".$packagecodename."/generator");
$tpl->remplir_template("generatorconf",$tabgeneratorconftpl);
//include generator file cour
$tpl->remplir_template("chemintpltogenerate",$chemin_db_generator_tpl);
//preparedatafortpl
$datafortpl=array();
if(isset($instanceGenerator))
$datafortpl=$instanceGenerator->prepareDataForTpl($instance);
foreach($datafortpl as $iddatafortpl=>$contentdatafortpl)
$tpl->remplir_template($iddatafortpl,$contentdatafortpl);
//generate file with tpl
$contentfilecour=$tpl->get_template($this->chemingeneratortpl);
$namefilecour=str_replace("__INSTANCE__",$instance->name,$chemin_db_generator_tpl);
$namefilecour=substr($namefilecour,0,-4);
$namefilecour=str_replace("package/".$packagecodename."/generator/",$this->folderdestdb.$packagecodename.".",$namefilecour);
//conflict resolution "reverse" mode
if($this->conflictresolution!=null)
{
//only if new file
if(!file_exists($namefilecour))
{
//setup annuaire files in package
$this->addToFileIsInPackageFile($packagecodename,$namefilecour);
//replace original file
file_put_contents($namefilecour,$contentfilecour);
}
else
{
//find existing conflict
$conflictnamefilecour=str_replace($this->folderdestdb,$this->folderdestdb."___CONFLICTFILE1___",$namefilecour);
if(file_exists($this->conflictfolder."/".$conflictnamefilecour))
{
$cptconflict="1";
$conflictfilefound="";
while(file_exists($this->conflictfolder."/".$conflictnamefilecour))
{
include $this->conflictfolder."/conflict.php";
$tabid=str_replace("/","-----",$conflictnamefilecour);
if(isset($tabconflict[$tabid]) && $tabconflict[$tabid]==$packagecodename)
{
$conflictfilefound=$conflictnamefilecour;
break;
}
$conflictnamefilecour=str_replace($this->folderdestdb,$this->folderdestdb."___CONFLICTFILE".($cptconflict++)."___",$namefilecour);
}
}
//if conflict found
if(file_exists($conflictfilefound))
{
//if conflict exists, replace only conflict file
if(!is_dir($this->conflictfolder."/".$this->folderdestdb))
mkdir($this->conflictfolder."/".$this->folderdestdb,0777,true);
copy($namefilecour,$this->conflictfolder."/".$conflictnamefilecour);
}
else
{
//replace original file
file_put_contents($namefilecour,$contentfilecour);
}
}
}
else
{
//file create
file_put_contents($namefilecour,$contentfilecour);
}
//return tab
$tabdeployedfiles[]=$namefilecour;
//load db
$sqltoload=file_get_contents($namefilecour);
$tabsqltoload=explode(";",$sqltoload);
foreach($tabsqltoload as $sqlcour)
{
$req=$this->db->query($sqlcour);
}
}
}
//recup dump with import
$dumper=null;
if((class_exists("PratikDump") || (isset($this->includer) && $this->includer->include_pratikclass("Dump"))) && isset($this->instanceConf) && $this->instanceConf!=null)
{
$dumpname="dump.".$packagecodename."___generator";
$instanceDump=new PratikDump($this->initer,$dumpname);
$packagelastdumptoload=$instanceDump->getLastDump($dumpname);
if($packagelastdumptoload!="")
{
//load dump
$dumper=$instanceDump->dumpselected;
$dumper->importDump($packagelastdumptoload);
}
}
}
//load files generator
foreach($this->initer['chaintab'] as $chaincour)
{
$tabfilestoload=$this->loader->charg_dossier_dans_tab("package/".$packagecodename."/generator/".$chaincour);
if(isset($tabfilestoload))
foreach($tabfilestoload as $filecour)
{
$folder=substr($filecour,0,strrpos($filecour,"/"));
$file=substr($filecour,strrpos($filecour,"/"),strlen($filecour)-4-strrpos($filecour,"/"));
if($folder=="package/".$packagecodename."/generator/".$chaincour)
continue;
$folder=str_replace("package/".$packagecodename."/generator/".$chaincour."/","",$folder);
if(!is_dir($folder))
mkdir($folder,0777,true);
//pour chaque instance à générer
if($confgenerator && $confgenerator->instance)
foreach($confgenerator->instance as $instance)
{
//prepare chemin file with instance
$file_generate=str_replace("__INSTANCE__",$instance->name,$file);
//generate file
$instanceTpl=new Tp($this->conf,$this->log,"backoffice");
$tpl=$instanceTpl->tpselected;
//include generator conf tpl
$tabgeneratorconftpl=$this->loader->charg_generatorconftpl_dans_tab("package/".$packagecodename."/generator");
$tpl->remplir_template("generatorconf",$tabgeneratorconftpl);
//include generator file cour
$tpl->remplir_template("chemintpltogenerate",$filecour);
//preparedatafortpl
$datafortpl=array();
if(isset($instanceGenerator))
$datafortpl=$instanceGenerator->prepareDataForTpl($instance);
foreach($datafortpl as $iddatafortpl=>$contentdatafortpl)
$tpl->remplir_template($iddatafortpl,$contentdatafortpl);
//generate file with tpl
$contentfilecour=$tpl->get_template($this->chemingeneratortpl);
//conflict resolution "reverse" mode
if($this->conflictresolution!=null)
{
//only if new file
if(!file_exists($folder.$file_generate))
{
//setup annuaire files in package
$this->addToFileIsInPackageFile($packagecodename,$folder.$file_generate);
//replace original file
file_put_contents($folder.$file_generate,$contentfilecour);
}
else
{
//find existing conflict
$conflictnamefilecour="/___CONFLICTFILE1___".substr($file_generate,1);
if(file_exists($this->conflictfolder."/".$folder.$conflictnamefilecour))
{
$cptconflict="1";
$conflictfilefound="";
while(file_exists($this->conflictfolder."/".$folder.$conflictnamefilecour))
{
include $this->conflictfolder."/conflict.php";
$tabid=str_replace("/","-----",$folder.$conflictnamefilecour);
if(isset($tabconflict[$tabid]) && $tabconflict[$tabid]==$packagecodename)
{
$conflictfilefound=$conflictnamefilecour;
break;
}
$conflictnamefilecour="/___CONFLICTFILE".($cptconflict++)."___".substr($file_generate,1);
}
}
//if conflict found
if(file_exists($conflictfilefound))
{
//if conflict exists, replace only conflict file
if(!is_dir($this->conflictfolder."/".$folder))
mkdir($this->conflictfolder."/".$folder,0777,true);
copy($folder.$file_generate,$this->conflictfolder."/".$folder.$conflictnamefilecour);
}
else
{
//replace original file
file_put_contents($folder.$file_generate,$contentfilecour);
}
}
}
else
{
//chemin file ok
$chemin_file_generator_tpl=$folder.$file_generate;
file_put_contents($chemin_file_generator_tpl,$contentfilecour);
}
//return tab
$tabdeployedfiles[]=$chemin_file_generator_tpl;
}
}
}
//reconstruct initer with last files deploy
if(class_exists("PratikInitersimul") || (isset($this->includer) && $this->includer->include_pratikclass("Initersimul")))
{
$instanceInitersimul=new PratikInitersimul($this->initer);
$newiniter=$instanceInitersimul->initerConstruct($this->initer);
$this->reloadIniter($newiniter);
}
//include postdeployer generator
if(file_exists("package/".$packagecodename."/generator/generator.postdeployer.php"))
include "package/".$packagecodename."/generator/generator.postdeployer.php";
//kill old files which are not in the updated package yet (and put last conflict file instead if exists)
//a file of $tabisinpackage for the package not in $tabdeployedfiles and a conflictfile for the package not in $tabdeployedfiles ==> tabisinpackage unset or conflictfile unset, kill file (or last conflict replace or reorganize conflict => see destroy)
include $this->conflictfolder."/fileisinpackage.php";
include $this->conflictfolder."/conflict.php";
foreach($tabfileisinpackage as $fileisinpackageconvert=>$filepackage)
{
//prepare fileisinpackage with ----- instead of / and folder file separation
$fileisinpackage=str_replace("-----","/",$fileisinpackageconvert);
$folder_isinpackage=substr($fileisinpackage,0,strrpos($fileisinpackage,"/"));
$filename_isinpackage=substr($fileisinpackage,strrpos($fileisinpackage,"/"));
//check file is in package
$filetosearch=false;
$conflictfilefound="";
if($filepackage==$packagecodename)
{
$filetosearch=true;
}
else
{
//find file in existing conflict
$conflictnamefilecour="/___CONFLICTFILE1___".substr($filename_isinpackage,1);
if(file_exists($this->conflictfolder."/".$folder_isinpackage.$conflictnamefilecour))
{
$cptconflict="1";
while(file_exists($this->conflictfolder."/".$folder_isinpackage.$conflictnamefilecour))
{
include $this->conflictfolder."/conflict.php";
$tabid=str_replace("/","-----",$folder_isinpackage.$conflictnamefilecour);
if(isset($tabconflict[$tabid]) && $tabconflict[$tabid]==$packagecodename)
{
$conflictfilefound=$conflictnamefilecour;
$filetosearch=true;
break;
}
$conflictnamefilecour="/___CONFLICTFILE".($cptconflict++)."___".substr($filename_isinpackage,1);
}
}
}
//search file in deployed files, else kill it
if($filetosearch)
{
if(array_search($fileisinpackage,$tabdeployedfiles)===false)
{
//kill old file
if(file_exists($folder_isinpackage.$filename_isinpackage))
{
//(conflict "reverse" mode)
if($this->conflictresolution!=null)
{
//maj fileisinpackage.php
$this->addToFileIsInPackageFile($packagecodename,$folder_isinpackage.$filename_isinpackage,"unset");
if($this->conflictresolution=="force" || $this->conflictresolution=="keep")
unlink($folder_isinpackage.$filename_isinpackage);
//check if a conflict file exists ___CONFLICT... else suppr file and continue
if(!file_exists($this->conflictfolder."/".$folder_isinpackage."/___CONFLICTFILE1___".substr($filename_isinpackage,1)))
{
if(file_exists($folder_isinpackage.$filename_isinpackage))
unlink($folder_isinpackage.$filename_isinpackage);
continue;
}
//if a conflict file exists, find conflict for this package codename in tabconflict in conflict.php
//include $this->conflictfolder."/conflict.php";
$cptconflict="1";
$filecour=$folder_isinpackage."/___CONFLICTFILE".$cptconflict."___".substr($filename_isinpackage,1);
$conflictfile="";
$cptconflictfound=0;
while(file_exists($this->conflictfolder."/".$filecour))
{
$tabid=str_replace("/","-----",$filecour);
if(isset($tabconflict[$tabid]) && $tabconflict[$tabid]==$packagecodename)
{
$conflictfile=$filecour;
$cptconflictfound=$cptconflict;
break;
}
$cptconflict++;
$filecour=$folder_isinpackage."/___CONFLICTFILE".$cptconflict."___".substr($filename_isinpackage,1);
}
//if not found, suppr file and move last conflict file instead of it
if($conflictfile=="")
{
//suppr file
unlink($folder_isinpackage.$filename_isinpackage);
//move last conflict file to official file
$cptconflictlast=(--$cptconflict);
if($this->conflictresolution=="reverse")
rename($this->conflictfolder."/".$folder_isinpackage."/___CONFLICTFILE".$cptconflictlast."___".substr($filename_isinpackage,1),$folder_isinpackage.$filename_isinpackage);
//clear last conflict file (check kill and clear in $tabconflict in conflict.php)
if(file_exists($this->conflictfolder."/".$folder_isinpackage."/___CONFLICTFILE".$cptconflictlast."___".substr($filename_isinpackage,1)))
unlink($this->conflictfolder."/".$folder_isinpackage."/___CONFLICTFILE".$cptconflictlast."___".substr($filename_isinpackage,1));
//rewrite conflict files in tabconflict in conflict.php (add new lines with unset($tabconflict[lastconflictile]) )
$filecour=$this->conflictfolder."/".$folder_isinpackage."/___CONFLICTFILE".$cptconflictlast."___".substr($filename_isinpackage,1);
$this->addToConflictFile($filecour,"unset");
}
//if conflict found, suppr conflict and reorder the next ones and rewrite them in tabconflict in conflict.php and DO NOT suppr file in use
else
{
//suppr conflict file
unlink($this->conflictfolder."/".$conflictfile);
//reorder next conflict files
$cptconflict=(++$cptconflictfound);
$filecour=$folder_isinpackage."/___CONFLICTFILE".$cptconflict."___".substr($filename_isinpackage,1);
while(file_exists($this->conflictfolder."/".$filecour))
{
//move to prec conflict file
$destfilecour=$folder_isinpackage."/___CONFLICTFILE".($cptconflict-1)."___".substr($filename_isinpackage,1);
rename($this->conflictfolder."/".$filecour,$this->conflictfolder."/".$destfilecour);
//rewrite conflict files in tabconflict in conflict.php (add new lines with $tabconflict[cour]=$tabconflict[prec] or unset($tabconflict[cour]) )
$this->addToConflictFile($filecour,"update",array('destfile'=>$destfilecour));
//next
$cptconflict++;
$filecour=$folder_isinpackage."/___CONFLICTFILE".$cptconflict."___".substr($filename_isinpackage,1);
}
//end rewrite conflict files in tabconflict in conflict.php (unset($tabconflict[cour] for last conflict file) )
$filecour=$folder_isinpackage."/___CONFLICTFILE".($cptconflict-1)."___".substr($filename_isinpackage,1);
$this->addToConflictFile($filecour,"unset");
}
}
else
{
//suppr file
unlink($folder_isinpackage.$filename_isinpackage);
}
}
}
}
}
//reload initer
$this->reloadIniter();
if(isset($this->db) && $this->db)
$this->db->query("update `package` set toupdate='0' where nomcodepackage='".$packagecodename."'");
return $tabdeployedfiles;
}
return array();
}
function checkUpdate($packagecodename="example")
{
//check package to update
$downloader=null;
$yourfile=$this->folderdestdownload.$packagecodename.".zip";
//cas aucune présence du package, pas d'update
if(!file_exists($yourfile))
if(!file_exists("package/".$packagecodename))
return false;
//downloader init
if($downloader==null && $this->includer->include_pratikclass("Downloader"))
$downloader=new PratikDownloader($this->initer);
//data distant file
$distantfilesize="";
if($downloader && ($distantfile=$downloader->getFileLink($packagecodename.".zip","packages"))!="")
{
$head = array_change_key_case(get_headers($distantfile, TRUE));
$distantfilesize = $head['content-length'];
}
//when distant file not exists
if($distantfilesize=="")
return false;
//cas zip package inexistant, update necessaire
if(!file_exists($yourfile))
if(file_exists("package/".$packagecodename))
return true;
//data your file
$yourfilesize=filesize($yourfile);
//compare to show update or not
if($yourfilesize!=$distantfilesize)
return true;
return false;
}
function checkLocalUpdate($packagecodename="example")
{
//to check a local update, change the version of your package in the descripter
//get descripter version (new version)
$descripterversion="";
$descripterfile="package/".$packagecodename."/package.descripter.php";
if(!file_exists($descripterfile))
return false;
include $descripterfile;
if(isset($descripter['version']) && $descripter['version']!="")
$descripterversion=$descripter['version'];
if($descripterversion=="")
return false;
//get db version (deployed version)
$dbversion="";
if(!(isset($this->db) && $this->db))
return false;
$res=$this->db->query_one_result("select * from `package` where nomcodepackage='".$packagecodename."'");
if(isset($res['version']) && $res['version']!="")
$dbversion=$res['version'];
if($dbversion=="")
return false;
if($dbversion!=$descripterversion)
return true;
return false;
}
function checkDropTable($sqltoload)
{
//check an sql line with drop table and get an array with the table names (to use to make dumps)
$tabtable=array();
$tablelist=strtolower($sqltoload);
$tablelist=str_replace(" ","",$tablelist);
if(strpos($tablelist,"droptable")!==false)
{
$tablelist=substr($tablelist,strpos($tablelist,"droptable")+strlen("droptable"));
$tablelist=substr($tablelist,strpos($tablelist,"ifexists")+strlen("ifexists"));
$tablelist=str_replace("`","",$tablelist);
$tabtable=explode(",",$tablelist);
}
return $tabtable;
}
function totaldestroy($packagecodename="example")
{
//destroy if package deployed
if(file_exists($this->folderdestlogpackageloaded.$packagecodename.".loaded.log"))
$this->destroy($packagecodename);
//zip and archive old package with date in filename
if($this->zipAndArchivePackage($packagecodename))
{
//kill old package
$dir = "package/".$packagecodename;
$this->rrmdir($dir);
}
//kill zip
if(file_exists($this->folderdestdownload.$packagecodename.".zip"))
unlink($this->folderdestdownload.$packagecodename.".zip");
}
}
?><file_sep>/rodkodrok/deploy/deployark/class.load.php
<?php
class Load
{
function __construct()
{
}
function charg_dossier_unique_dans_tab($dossier,$withdir=false)
{
if(!is_dir($dossier))
return null;
$tab=array();
$rep=opendir($dossier);
while ($file = readdir($rep))
{
if($file != '..' && $file !='.' && $file !='')
{
if(is_file($dossier."/".$file) || $withdir)
{
//chargement du fichier
$tab[]=$dossier."/".$file;
}
}
}
return $tab;
}
function charg_dossier_dans_tab($dossier)
{
if(!is_dir($dossier))
return null;
$tab=array();
$tab_bis=array();
$rep=opendir($dossier);
while ($file = readdir($rep))
{
if($file != '..' && $file !='.' && $file !='')
{
if(is_dir($dossier."/".$file))
{
//chargement du contenu du dossier
$tab_bis=$this->charg_dossier_dans_tab($dossier."/".$file);
$tab=array_merge($tab,$tab_bis);
}
else
{
//chargement du fichier
$tab[]=$dossier."/".$file;
}
}
}
return $tab;
}
function charg_chain_dans_tab($dossier="chain")
{
//check $dossier in arkitect
$arkitect=new Arkitect();
$tmpdossier=$arkitect->get("chain");
if($tmpdossier!="" && is_dir($tmpdossier))
$dossier=$tmpdossier;
//load chain dans tab
$tab=array();
if(!is_dir($dossier))
{
$tab[]="default";
return $tab;
}
$nameconnectorchain="connector.chain.";
$rep=opendir($dossier);
while ($file = readdir($rep))
{
if($file != '..' && $file !='.' && $file !='')
{
if(is_file($dossier."/".$file))
{
//chargement du fichier
$chaincour=$file;
if(strstr($chaincour,$nameconnectorchain))
{
$chaincour=substr($chaincour,strlen($nameconnectorchain),-4);
//ajout du nom de la chain
$tab[]=$chaincour;
}
}
}
}
//cas aucune chain installée
if(count($tab)==0)
$tab[]="default";
return $tab;
}
function charg_connector_dans_tab($dossier="connector")
{
//check $dossier in arkitect
$arkitect=new Arkitect();
$tmpdossier=$arkitect->get("connector");
if($tmpdossier!="" && is_dir($tmpdossier))
$dossier=$tmpdossier;
//load chain dans tab
if(!is_dir($dossier))
return null;
$nameconnector="connector.";
$tab=array();
$rep=opendir($dossier);
while ($file = readdir($rep))
{
if($file != '..' && $file !='.' && $file !='')
{
if(is_file($dossier."/".$file))
{
//chargement du fichier
$connectorcour=$file;
if(strstr($connectorcour,$nameconnector))
{
$connectorcour=substr($connectorcour,strlen($nameconnector),-4);
//ajout du nom de la chain
$tab[]=$connectorcour;
}
}
}
}
return $tab;
}
function charg_generatorconftpl_dans_tab($dossier)
{
if(!is_dir($dossier))
return null;
$tab=array();
$rep=opendir($dossier);
while ($file = readdir($rep))
{
if($file != '..' && $file !='.' && $file !='')
{
if(is_file($dossier."/".$file) && strstr($file,"generator.conf.") && substr($file,-4)==".tpl")
{
//chargement du fichier
$tab[]=$dossier."/".$file;
}
}
}
return $tab;
}
function construct_tab_toprint($tabconnector=array(),$initercour=null)
{
$tabtoprint=array();
if($initercour==null)
return $tabtoprint;
if($tabconnector)
foreach($tabconnector as $connectorcour)
{
if(!(isset($connectorcour['outputaction']) && isset($connectorcour['vartoiniter']) && isset($connectorcour['aliasiniter'])))
continue;
$varcour="";
if(isset($connectorcour['vartoiniter']) && isset($connectorcour['name']))
$varcour=$connectorcour['name'];
if(isset($connectorcour['aliasiniter']) && $connectorcour['aliasiniter']!="none")
$varcour=$connectorcour['aliasiniter'];
if(strstr($connectorcour['outputaction'],"toprint")!==false)
{
$tabcour=explode("-",$connectorcour['outputaction']);
if(count($tabcour)!=3)
continue;
//cas variable directe
if($tabcour[1]=="self")
{
//get var directement
if(!isset($tabtoprint['self'][$varcour]))
eval("\$tabtoprint['self'][\$varcour]=\$initercour['".$varcour."'];");
}
else
{
//get var directement
if(!isset($tabtoprint['other'][$varcour]))
eval("\$tabtoprint['other'][\$varcour]=\$initercour['".$varcour."'];");
//get var dans tab indiqué (exemple content:2 devient $tabtoprint['content'][2]
$tabdest=explode(":",$tabcour[1]);
//cas var simple
if($tabcour[2]=="var")
{
$tabtoprint[$tabdest[0]][$tabdest[1]]['name']=$varcour;
$tabtoprint[$tabdest[0]][$tabdest[1]]['type']="var";
$tabtoprint[$tabdest[0]][$tabdest[1]]['chemin']="";
eval("\$tabtoprint[\$tabdest[0]][\$tabdest[1]]['value']=\$initercour['".$varcour."'];");
}
else
{
//cas subtpl
$tabchemin=explode(":",$tabcour[2]);
if($tabchemin[0]=="subtpl")
{
$tabtoprint[$tabdest[0]][$tabdest[1]]['name']=$varcour;
$tabtoprint[$tabdest[0]][$tabdest[1]]['type']="subtpl";
eval("\$tabtoprint[\$tabdest[0]][\$tabdest[1]]['value']=\$initercour['".$varcour."'];");
//construct chemin tpl
$chemincour="";
$arkitectname=$tabchemin[1];
$arkitectname.=".tplpath";
$arkitect=new Arkitect();
$chemincour=$arkitect->get($arkitectname);
$tabtoprint[$tabdest[0]][$tabdest[1]]['chemin']=$chemincour;
}
}
}
}
}
//reorder array with keys 0,1,2,3,...
if(isset($tabtoprint))
foreach($tabtoprint as $idtab=>$valuetab)
{
if($idtab!="self" && $idtab!="other")
{
ksort($tabtoprint[$idtab]);
array_splice($tabtoprint[$idtab],0,0);
}
}
return $tabtoprint;
}
function charg_url_unique_dans_tab($url="",$withdir=false)
{
$tab=array();
$matches = array();
preg_match_all("/(a href\=\")([^\?\"]*)(\")/i", $this->get_text($url), $matches);
foreach($matches[2] as $match) {
if(substr($match,-4)==".zip" || $withdir)
$tab[]=$match;
}
return $tab;
}
//to use with function charg_url_unique_dans_tab
private function get_text($filename)
{
$content="";
$fp_load = fopen("$filename", "rb");
if ( $fp_load )
{
while ( !feof($fp_load) )
{
$content .= fgets($fp_load, 8192);
}
fclose($fp_load);
}
return $content;
}
function load_js($filejs="")
{
$js="";
$js.="<script src=\"".$filejs."\" type=\"text/javascript\"></script>\n";
return $js;
}
function load_css($filecss="")
{
$css="";
$css.="<link rel=\"stylesheet\" type=\"text/css\" href=\"".$filecss."\" />\n";
return $css;
}
}
?><file_sep>/rodkodrok/deploy/deployabstract/class.__________classiniter.php
<?php
class ClassIniter
{
var $initer;
private $recursemaxdepth=3;
function __construct($initer=array())
{
$this->initer=$initer;
foreach($initer as $idiniter=>$valueiniter)
{
eval("\$this->".$idiniter."=\$valueiniter;");
}
}
function getIniterPrerequis()
{
$prerequis=array();
return $prerequis;
}
function getIniter()
{
return $this->initer;
}
function reloadIniter($initer=null)
{
if($initer)
$this->initer=$initer;
if($this->initer)
foreach($this->initer as $idiniter=>$valueiniter)
{
eval("\$this->".$idiniter."=\$valueiniter;");
}
}
function showIniter($recurse=false,$elmtinitertostr="",$indent="0",$otheriniter=null,$getparamsorigin=null)
{
$returned="";
if($elmtinitertostr=="")
$returned.="<div style='margin:10px;padding:10px;border:3px solid #7B0202;background:#E29292;'>";
//affiche le contenu de la variable initer dans une arborescence lisible
$tabiniter=explode("@@@",$elmtinitertostr);
$variniter="\$this->initer";
if($otheriniter)
$variniter="\$otheriniter";
if($elmtinitertostr!="")
foreach($tabiniter as $elmtinitercour)
{
if(is_array(eval("return ".$variniter.";")))
$variniter.="['".$elmtinitercour."']";
else if(is_object(eval("return ".$variniter.";")))
$variniter.="->".$elmtinitercour;
}
eval("\$elmtiniter=".$variniter.";");
if(is_array($elmtiniter) || is_object($elmtiniter))
{
//print variables disponibles
foreach($elmtiniter as $idelmt=>$valueelmt)
{
//random value
$randvalue=rand();
//get values sent to parameter to recreate the initer original in further ajax calls
if($getparamsorigin==null)
$getparamsorigin=$_GET;
$getparams="";
foreach($getparamsorigin as $idgetparams=>$valuegetparams)
$getparams.="&get".$idgetparams."=".$valuegetparams;
$returned.="<div onclick=\"";
if($recurse==false)
{
$returned.="if(document.getElementById('showiniter_".$idelmt."_".$randvalue."').style.display == 'none') ajaxCall('showiniter_".$idelmt."_".$randvalue."','showiniter','indent=".($indent+20)."&elmtinitertostr=";
if($elmtinitertostr!="")
$returned.=$elmtinitertostr."@@@";
$returned.=$idelmt.$getparams."'); else \$('#showiniter_".$idelmt."_".$randvalue."').fadeOut('slow', 'linear');";
}
else
{
$returned.="if(document.getElementById('showiniter_".$idelmt."_".$randvalue."').style.display == 'none') document.getElementById('showiniter_".$idelmt."_".$randvalue."').style.display = ''; else document.getElementById('showiniter_".$idelmt."_".$randvalue."').style.display = 'none';";
}
$returned.="\" style='padding:3px;padding-left:10px;margin-left:".$indent."px;border:1px solid #666666;background:";
if(is_array($valueelmt))
$returned.="#CAC367";
else if(is_object($valueelmt))
$returned.="#5B82B6";
else
$returned.="yellow";
$returned.=";'>".$idelmt." (";
if(is_array($valueelmt))
$returned.="Array";
else if(is_object($valueelmt))
$returned.="Object";
else
$returned.="Value";
$returned.=")</div>";
$returned.="<div style='display:none' id='showiniter_".$idelmt."_".$randvalue."'>";
//recurse
if($recurse)
{
$elmtsuivant=$idelmt;
$otheriniterfornext=$elmtiniter;
if($elmtinitertostr!="")
{
$elmtsuivant=$elmtinitertostr."@@@".$idelmt;
$otheriniterfornext=$otheriniter;
}
if($recurse==true)
$recurse=1;
else
$recurse++;
if($recurse<$this->recursemaxdepth)
$returned.=$this->showIniter($recurse,$elmtsuivant,$indent+20,$otheriniterfornext);
else
$returned.="Max depth of a tree <i>showIniter</i> reached. To see more, change the parameter <i>\$recursemaxdepth</i> in the file <i>abstract/class.classiniter.php</i>";
}
$returned.="</div>";
}
//print functions disponibles
if(is_object($elmtiniter))
{
$classmethods=get_class_methods($elmtiniter);
foreach($classmethods as $methodname)
{
if($methodname!="__construct")
{
$returned.="<div style='padding:3px;padding-left:10px;margin-left:".$indent."px;border:1px solid #666666;background:#4DA950;'>".$methodname."( ";
//Get the parameters of a method
$paramslist="";
$reflector = new ReflectionClass($elmtiniter);
$parameters = $reflector->getMethod($methodname)->getParameters();
if($parameters)
{
foreach($parameters as $paramcour)
{
$paramslist.=$paramcour->name;
$paramslist.=" , ";
}
$paramslist=substr($paramslist,0,-strlen(" , "));
}
$returned.=$paramslist;
$returned.=" ); (Function)</div>";
}
}
}
}
else
$returned.="<div style='padding:3px;padding-left:10px;margin-left:".$indent."px;border:1px solid #666666;background:orange;'>".$elmtiniter."</div>";
if($elmtinitertostr=="")
$returned.="</div>";
return $returned;
}
}
?><file_sep>/rodkodrok/deploy/deployclass/class.tp.smarty.php
<?php
class TemplateSmarty
{
var $oSmarty=null;
var $dirtmptpl='deploy/deployfiles/tmp/templates_c';
function __construct()
{
//parent::__construct();
$this->preparer_template();
}
function preparer_template()
{
//include lib smarty
//include "lib/Smarty-3.1.21/libs/Smarty.class.php";
// Instancier notre objet smarty
$this->oSmarty = new Smarty();
// Fixer les chemins de template (optionnel)
//$this->oSmarty->template_dir = '../templates';
$this->oSmarty->compile_dir = $this->dirtmptpl;
}
function remplir_template($destination,$contenu)
{
// 2. Recensement dans smarty
$this->oSmarty->assign($destination, $contenu);
}
function affich_template($tpl="index.tpl")
{
// 3. Affichage du template après passage de l'objet
$this->oSmarty->display($tpl);
}
function get_template($tpl="index.tpl")
{
return $this->oSmarty->fetch($tpl);
}
}
?><file_sep>/rodkodrok/README.txt
Voir dans le dossier txt
- README
- LICENSE
- VERSION
- DVELOPPERS<file_sep>/rodkodrok/deploy/deploylib/pratik/form/customsubmit/champs.text.php
<?php
/*
Custom additional action for a field of your form (example : uploading a file)
var dispo :
$lineform['name'] (name input of form)
$lineform['default'] (default value input of form)
$lineform['label'] (label input of form)
$lineform['suggestlist'] (suggestlist input of form)
$lineform['champs'] (type champs input of form, in the filename)
var to modify or to let the same :
$tabpost[$lineform['name']] (value posted)
other var dispo :
echo $this->showIniter();
*/
?><file_sep>/rodkodrok/deploy/deployclass/class.tp.php
<?php
class Tp
{
var $tpselected=null;
function __construct($conf,$log,$zonetpl="")
{
//mode backoffice
$moteur="";
if(isset($conf['moteurtpl']))
$moteur=$conf['moteurtpl'];
if(isset($conf['moteurtpl'.$zonetpl]))
$moteur=$conf['moteurtpl'.$zonetpl];
//select moteur tpl
$moteurlowercase=strtolower($moteur);
$moteurclass=ucfirst($moteurlowercase);
if(file_exists("deploy/deployclass/class.tp.".$moteurlowercase.".php"))
{
//include_once "integrate/driver/class.tp.".$moteurlowercase.".php";
eval("\$this->tpselected=new Template".$moteurclass."();");
}
else
{
//include_once "integrate/driver/class.tp.smarty.php";
$this->tpselected=new TemplateSmarty();
//$log->pushtolog("Echec du chargement du driver template. Verifier la configuration ou votre driver.");
}
}
}
?><file_sep>/rodkodrok/deploy/deployabstract/class.package.generator.php
<?php
class PackageGenerator extends ClassIniter
{
function __construct($initer=array())
{
parent::__construct($initer);
}
function prepareDataForTpl($instancecour="")
{
$tabdata=array();
//load packagecodename
$tabdata['packagecodename']=$this->packagecodename;
//load descripter pour tpl fichier generator
if(isset($this->descripter))
foreach($this->descripter as $key=>$value){
$tabdata['descripter'][$key] = $this->load_string_from_xml($value);
}
//load confstatic pour tpl fichier generator
if(isset($this->confstatic))
foreach($this->confstatic as $key=>$value){
$tabdata['confstatic'][$key] = $this->load_string_from_xml($value);
}
//load confform pour tpl fichier generator
if(isset($this->confform[$this->packagecodename]))
foreach($this->confform[$this->packagecodename] as $key=>$value){
$tabdata['confform'][$key] = $this->load_string_from_xml($value);
}
//load confgenerator instances pour tpl fichier generator
$cptinstance=0;
if(isset($this->confgenerator))
foreach($this->confgenerator->instance as $instance){
if(isset($instance->name))
{
$instancename=(string) $instance->name;
$tabdata['confgenerator']['instances'][$instancename]=array();
}
else
{
$instancename=$cptinstance;
$tabdata['confgenerator']['instances'][$instancename]=array();
$cptinstance++;
}
foreach($instance as $key=>$value)
if($key!="name")
$tabdata['confgenerator']['instances'][$instancename][$key] = $this->load_string_from_xml($value);
}
//load confgenerator instancecour pour tpl fichier generator
if(isset($instancecour))
foreach($instancecour as $key=>$value){
$tabdata['confgenerator']['instancecour'][$key]=$this->load_string_from_xml($value);
}
return $tabdata;
}
//chargement d'une chaine depuis un xml
function load_string_from_xml($chaine)
{
if(is_object($chaine) && $chaine->children()->getName())
{
$tabdatacour=array();
$lastkeys=array();
if($chaine)
foreach($chaine as $key=>$value)
{
//test si key déjà présente pour ne pas écraser les datas
if(isset($tabdatacour[$key]))
{
if($tabkeys[$key] || !is_array($tabdatacour[$key]))
{
$tmpdata=$tabdatacour[$key];
unset($tabdatacour[$key]);
$tabdatacour[$key]=array();
$tabdatacour[$key][]=$tmpdata;
$tabkeys[$key]=false;
}
//reorganise en sous tab pour éviter suppr de datas
$tabdatacour[$key][] = $this->load_string_from_xml($value);
}
else
{
//ajout key dans tab
$tabdatacour[$key] = $this->load_string_from_xml($value);
//tabkeys to check if no data are deleted
$tabkeys[$key]=true;
}
}
if(count($tabdatacour)==0)
$tabdatacour="";
return $tabdatacour;
}
return @utf8_decode(str_replace('@@@','\n',eval("return \"".str_replace('\n','@@@',str_replace('"','"',(string)$chaine)."\";"))));
}
}
?>
<file_sep>/rodkodrok/deploy/deployabstract/class.package.static.php
<?php
class PackageStatic extends ClassIniter
{
function __construct($initer=array())
{
parent::__construct($initer);
}
}
?>
<file_sep>/rodkodrok/deploy/deploylib/pratik/downloader/srclinks/mainlinks.php
<?php
//model : $tabsrclink[<ascendantpriority>]="<link>";
$tabsrclink[50]="http://rodkodrok.com/mirror/rodkodrok-mirror-1/";
?><file_sep>/rodkodrok/deploy/deployclass/class.form.php
<?php
class PratikForm extends ClassIniter
{
var $chemin_pratiklib_form="deploy/deploylib/pratik/form/";
function __construct($initer=array())
{
parent::__construct($initer);
}
function formconverter($tabform=array(),$tabparam=array())
{
$form=array();
foreach($tabform as $idform=>$contentform)
{
if($idform=='lineform')
{
foreach($tabform['lineform'] as $contentlineform)
{
$form['lineform'][]=array();
$form['lineform'][count($form['lineform'])-1]['label']="";
if(isset($contentlineform['label']))
$form['lineform'][count($form['lineform'])-1]['label']=$contentlineform['label'];
$form['lineform'][count($form['lineform'])-1]['hiddenlabel']="";
if(isset($contentlineform['champs']) && strstr($contentlineform['champs'],"hidden")!==false)
$contentlineform['hiddenlabel']="on";
if(isset($contentlineform['hiddenlabel']))
$form['lineform'][count($form['lineform'])-1]['hiddenlabel']=$contentlineform['hiddenlabel'];
$form['lineform'][count($form['lineform'])-1]['name']="";
if(isset($contentlineform['name']))
$form['lineform'][count($form['lineform'])-1]['name']=$contentlineform['name'];
$form['lineform'][count($form['lineform'])-1]['default']="";
if(isset($contentlineform['default']) && strtolower($contentlineform['default'])=="null")
$contentlineform['default']="";
if(isset($contentlineform['default']))
$form['lineform'][count($form['lineform'])-1]['default']=$contentlineform['default'];
$form['lineform'][count($form['lineform'])-1]['suggestlist']="";
if(isset($contentlineform['suggestlist']))
$form['lineform'][count($form['lineform'])-1]['suggestlist']=$contentlineform['suggestlist'];
//$instanceTpl=new Tp($this->conf,$this->log);
//$tpl=$instanceTpl->tpselected;
$tpl=new TemplateSmarty();
//load css and js for case
$tpl->remplir_template("css",$this->getCssForm("champs.".$contentlineform['champs']));
$tpl->remplir_template("js",$this->getJsForm("champs.".$contentlineform['champs']));
//custom code to prepare champs input (charger une liste de suggestions par exemple)
if(file_exists($this->chemin_pratiklib_form."customform/champs.".$contentlineform['champs'].".php"))
include $this->chemin_pratiklib_form."customform/champs.".$contentlineform['champs'].".php";
else
$this->log->pushtolog("Fichier introuvable : ".$this->chemin_pratiklib_form."customform/champs.".$contentlineform['champs'].".php");
$tpl->remplir_template("lineform",$contentlineform);
//tpl du champs
$chemin_tpl_champs=$this->chemin_pratiklib_form."template/champs.".$contentlineform['champs'].".tpl";
if(!file_exists($chemin_tpl_champs))
$chemin_tpl_champs=$this->chemin_pratiklib_form."template/champs.text.tpl";
//set chemin form
$tpl->remplir_template("cheminform",$chemin_tpl_champs);
$form['lineform'][count($form['lineform'])-1]['champs']=$tpl->get_template($this->chemin_pratiklib_form."form.tpl");
}
}
else
{
//$instanceTpl=new Tp($this->conf,$this->log);
//$tpl=$instanceTpl->tpselected;
$tpl=new TemplateSmarty();
//load css and js for case
$tpl->remplir_template("css",$this->getCssForm("form.".$idform));
$tpl->remplir_template("js",$this->getJsForm("form.".$idform));
//load other params
foreach($tabparam as $idparam=>$contentparam)
$tpl->remplir_template($idparam,$contentparam);
//custom code to prepare champs input (charger une liste de suggestions par exemple)
if(file_exists($this->chemin_pratiklib_form."customform/form.".$idform.".php"))
include $this->chemin_pratiklib_form."customform/form.".$idform.".php";
else
$this->log->pushtolog("Fichier introuvable : ".$this->chemin_pratiklib_form."customform/form.".$idform.".php");
//tpl de l'elmt form
$form[$idform]="";
if($contentform==true)
{
//cas avec structure de base de form.tpl
$chemin_tpl_champs=$this->chemin_pratiklib_form."template/form.".$idform.".tpl";
if(!file_exists($chemin_tpl_champs))
{
//cas de balises ouvrante et fermante (sans structure de base form.tpl)
$chemin_tpl_champs=$this->chemin_pratiklib_form."template/form.".$idform."__open.tpl";
if(!file_exists($chemin_tpl_champs))
$chemin_tpl_champs=$this->chemin_pratiklib_form."template/form.none.tpl";
else
{
//custom code to prepare champs input for open and close (charger une liste de suggestions par exemple)
if(file_exists($this->chemin_pratiklib_form."customform/form.".$idform."__open.php"))
include $this->chemin_pratiklib_form."customform/form.".$idform."__open.php";
else
$this->log->pushtolog("Fichier introuvable : ".$this->chemin_pratiklib_form."customform/form.".$idform."__open.php");
//tpl open
$form[$idform."__open"]=$tpl->get_template($chemin_tpl_champs);
//custom code to prepare champs input for open and close (charger une liste de suggestions par exemple)
if(file_exists($this->chemin_pratiklib_form."customform/form.".$idform."__close.php"))
include $this->chemin_pratiklib_form."customform/form.".$idform."__close.php";
else
$this->log->pushtolog("Fichier introuvable : ".$this->chemin_pratiklib_form."customform/form.".$idform."__close.php");
//tpl close
$chemin_tpl_champs=$this->chemin_pratiklib_form."template/form.".$idform."__close.tpl";
$form[$idform."__close"]="";
if(file_exists($chemin_tpl_champs))
$form[$idform."__close"]=$tpl->get_template($chemin_tpl_champs);
//tpl none for secure
$chemin_tpl_champs=$this->chemin_pratiklib_form."template/form.none.tpl";
$form[$idform]="";
if(file_exists($chemin_tpl_champs))
$form[$idform]=$tpl->get_template($chemin_tpl_champs);
continue;
}
}
//set chemin form
$tpl->remplir_template("cheminform",$chemin_tpl_champs);
$form[$idform]=$tpl->get_template($this->chemin_pratiklib_form."form.tpl");
}
}
}
return $form;
}
function submiter($preform=array(),$tabaction=array(),$tabparam=array())
{
//get var
$tabpost=array();
if(isset($preform['lineform']))
foreach($preform['lineform'] as $lineform)
{
$tabpost[$lineform['name']]=$this->instanceVar->varpost($lineform['name']);
//custom code for champ submitted
if(file_exists($this->chemin_pratiklib_form."customsubmit/champs.".$lineform['champs'].".php"))
include $this->chemin_pratiklib_form."customsubmit/champs.".$lineform['champs'].".php";
else
$this->log->pushtolog("Fichier introuvable : ".$this->chemin_pratiklib_form."customsubmit/champs.".$lineform['champs'].".php");
}
//submit action to do
if(isset($tabaction))
foreach($tabaction as $action)
if(file_exists($this->chemin_pratiklib_form."customsubmit/form.".$action.".php"))
include $this->chemin_pratiklib_form."customsubmit/form.".$action.".php";
else
$this->log->pushtolog("Fichier introuvable : ".$this->chemin_pratiklib_form."customsubmit/champs.".$action.".php");
}
function redirectAfterSubmiter($url="")
{
//to prevent reload forms when refresh with F5
$jsreturned="";
$jsreturned.="<script>";
$jsreturned.="$(document).ready(function(){";
$jsreturned.="window.location.replace('";
if($url!="")
{
if(substr($url,0,4)=="http")
$jsreturned.=$url;
else
{
$hostcour="http".(($_SERVER['SERVER_PORT'] == 443) ? "s://" : "://").$_SERVER['HTTP_HOST'];
$subfolder=substr($_SERVER['REQUEST_URI'],0,strrpos($_SERVER['REQUEST_URI'],"/"));
$jsreturned.=$hostcour.$subfolder."/".$url;
}
}
else
{
$urlcour="http".(($_SERVER['SERVER_PORT'] == 443) ? "s://" : "://").$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
$jsreturned.=$urlcour;
}
$jsreturned.="');";
$jsreturned.="});";
$jsreturned.="</script>";
//exec redirection
echo $jsreturned;
return $jsreturned;
}
//get css and js
function getCssForm($nomcodeform="")
{
$css="";
if(file_exists("core/src/pratiklib/form/css/".$nomcodeform.".css"))
$css.="<link rel=\"stylesheet\" href=\"core/src/pratiklib/form/css/".$nomcodeform.".css\" type=\"text/css\" />\n";
//surcharge de la css possible dans le design
if(file_exists("core/design/pratik/form/".$nomcodeform.".css"))
$css.="<link rel=\"stylesheet\" href=\"core/design/pratik/form/".$nomcodeform.".css\" type=\"text/css\" />\n";
return $css;
}
function getJsForm($nomcodeform="")
{
$js="";
if(file_exists("core/src/pratiklib/form/js/".$nomcodeform.".js"))
$js.="<script src=\"core/src/pratiklib/form/js/".$nomcodeform.".js\"></script>\n";
return $js;
}
}
?><file_sep>/rodkodrok/deploy/deployclass/class.deploy.php
<?php
class Deploy
{
var $conflictresolution="force";
var $tabpackagetodeploy=array();
var $log;
function __construct($tabpackagetodeploy=array(),$conflictresolution="force")
{
$this->tabpackagetodeploy=$tabpackagetodeploy;
$this->conflictresolution=$conflictresolution;
}
function getDeployContent($deploypage="")
{
$returned="";
switch($deploypage)
{
case "startdeploy" : $returned.=$this->deployPageStartDeploy(); break;
case "downloadstep" : $returned.=$this->deployPageDownloadStep(); break;
case "deployment" : $returned.=$this->deployPageDeployment(); break;
default:
$returned.=$this->deployPageDescripter($deploypage);
break;
}
return $returned;
}
function getDeployForm($deploypage="")
{
$returned="";
switch($deploypage)
{
case "startdeploy" : $returned.="downloadstep"; break;
case "downloadstep" : $returned.=$this->tabpackagetodeploy[0]['name']; break;
case "deployment" : $this->setSession(); $returned.=""; break;
default:
$this->setSession();
$returned=$this->form_loader($deploypage);
break;
}
return $returned;
}
function setSession()
{
if(isset($_POST['confform']))
{
if(isset($_SESSION['confform']))
$_SESSION['confform']=array_merge($_SESSION['confform'],$_POST['confform']);
else
$_SESSION['confform']=$_POST['confform'];
}
}
function form_loader($deploypage)
{
$form="";
$packagecodename=$deploypage;
//prepare form with pratikpackage
//$this->includer->include_pratikclass("Package");
$instancePackage=new PratikPackage();
$preform=$instancePackage->preparePackageConfForm($packagecodename);
//construct form
//$this->includer->include_pratikclass("Form");
$initer['log']=$this->log;
$instanceForm=new PratikForm($initer);
$tabparam['codename']=$packagecodename;
$form=$instanceForm->formconverter($preform,$tabparam);
return $form;
}
function deployPageStartDeploy()
{
$returned="";
$returned.="Start RoDKoDRoK...";
$returned.="<br /><br />";
return $returned;
}
function deployPageDownloadStep()
{
$returned="";
$returned.="Donwloading all needed packages from RoDKoDRoK...";
$returned.="<br /><br />";
$returned.="<div id='loadingbar'><div id='loadedbar'></div></div>";
$returned.="<br />";
$returned.="<div id='ajaxresults'></div>";
$returned.="<br />";
$returned.="<div id='ajaxerrors'></div>";
$returned.="<script>disableButtonToContinue();</script>";
foreach($this->tabpackagetodeploy as $packagetodeploy)
$returned.="<script>nbPackagesToLoad++;</script>";
foreach($this->tabpackagetodeploy as $packagetodeploy)
$returned.="<script>downloadPackage('".$packagetodeploy['name']."');</script>";
return $returned;
}
function deployPageDescripter($deploypage)
{
$returned="";
$descripter['name']="";
$descripter['description']="";
if(file_exists("package/".$deploypage."/package.descripter.php"))
include_once "package/".$deploypage."/package.descripter.php";
$returned.=$descripter['name'];
$returned.="<br /><br />";
$returned.=$descripter['description'];
$returned.="<br /><br />";
return $returned;
}
function deployPageDeployment()
{
//test config déjà existante
if(file_exists("chain/connector.chain.default.php"))
return "Already installed site !!!";
//check first folder access
$tabfoldertocheck=array();
$tabfoldertocheck[]="core";
$tabfoldertocheck[]="package";
$tabfoldertocheck[]="rkrsystem";
$tabfoldertocheck[]="rkrsystem/chain";
$tabfoldertocheck[]="rkrsystem/connector";
$tabfoldertocheck[]="rkrsystem/dbfromfile";
$tabfoldertocheck[]="rkrsystem/packagetrace";
$tabfoldertocheck[]="rkrsystem/src";
$tabfoldertocheck[]="rkrsystem/src/abstract";
$tabfoldertocheck[]="rkrsystem/src/ark";
$tabfoldertocheck[]="rkrsystem/src/genesis";
foreach($tabfoldertocheck as $foldertocheck)
{
if(!file_exists($foldertocheck) && !is_dir($foldertocheck))
mkdir($foldertocheck,0777,true);
//chmod($foldertocheck, 0777);
}
//deploy des packages du site
$content="";
$content.="<div id='loadingbar'><div id='loadedbar'></div></div>";
$content.="<br />";
$content.="<div id='enddeploymentmessage'>Your site is online. Go to home page : <a href='index.php?page=home'>Home</a></div>";
$content.="<br />";
$content.="<div id='ajaxerrors'></div>";
$content.="<br />";
$content.="<div id='ajaxresults'></div>";
$content.="<script>displayNoneEndMessage();</script>";
foreach($this->tabpackagetodeploy as $packagetodeploy)
$content.="<script>tabPackagesToDeployInOrder[nbPackagesToDeploy]='".$packagetodeploy['name']."';nbPackagesToDeploy++;</script>";
//IMPORT PACKAGES
$content.="<script>if(isset(tabPackagesToDeployInOrder[0])) deployPackage(tabPackagesToDeployInOrder[0]);</script>";
return $content;
}
function initerConstruct($initercreated=array())
{
$instanceIniterSimul=new PratikInitersimul();
$initersimuled=$instanceIniterSimul->initerConstruct($initercreated);
return $initersimuled;
}
}
?><file_sep>/rodkodrok/deploy/deployjs/deployjs.js
//lib
isset = function(obj) {
var i, max_i;
if(obj === undefined) return false;
for (i = 1, max_i = arguments.length; i < max_i; i++) {
if (obj[arguments[i]] === undefined) {
return false;
}
obj = obj[arguments[i]];
}
return true;
};
// JS FOR DOWNLOAD
var nbPackagesToLoad=0;
var nbPackagesLoaded=0;
function downloadPackage(packagename)
{
var params='packagename='+packagename;
$.ajax({
async: "true",
type: "post",
url: "deploy.php?ajax=downloadpackage",
data: params,
error: function(errorData) { $("#ajaxresults").html(errorData); },
success: function(data) {
$("#ajaxresults").html(data);
sendFlagPackageIsLoaded();
if(data == "Error")
{
$("#ajaxerrors").html($("#ajaxerrors").html()+"<div class='ajaxerror'><div>Warning : Download Error for "+packagename+" - check download src links or package name.</div><div>If this package is not an important one, you can continue the deployment below.</div></div><br />");
}
}
});
}
function sendFlagPackageIsLoaded()
{
if(nbPackagesToLoad>0)
{
$("#loadedbar").width($("#loadedbar").width()+($("#loadingbar").width()/nbPackagesToLoad));
nbPackagesLoaded++;
}
if(nbPackagesLoaded>=nbPackagesToLoad)
{
$("#loadedbar").width($("#loadingbar").width());
$("#buttontocontinue").prop("disabled",false);
$("#buttontocontinue").css({ opacity: 1 });
$("#ajaxresults").html("End donwload");
}
}
function disableButtonToContinue()
{
$("#buttontocontinue").prop("disabled",true);
$("#buttontocontinue").css({ opacity: 0.2 });
}
// JS FOR DEPLOY
var nbPackagesToDeploy=0;
var nbPackagesDeployed=0;
var tabPackagesToDeployInOrder=new Array();
function deployPackage(packagename)
{
var params='packagename='+packagename;
$.ajax({
async: "true",
type: "post",
url: "deploy.php?ajax=deploypackage",
data: params,
error: function(errorData) { $("#ajaxresults").html(errorData); },
success: function(data) {
$("#ajaxresults").html($("#ajaxresults").html()+data);
$('#ajaxresults').scrollTop($("#ajaxresults").prop('scrollHeight'));
sendFlagPackageIsDeployed();
//next deploy (order needed for initer construct)
var indexcour = tabPackagesToDeployInOrder.indexOf(packagename);
indexcour++;
if(nbPackagesDeployed>=nbPackagesToDeploy)
return;
if(isset(tabPackagesToDeployInOrder[indexcour]))
deployPackage(tabPackagesToDeployInOrder[indexcour]);
}
});
}
function sendFlagPackageIsDeployed()
{
if(nbPackagesToDeploy>0)
{
$("#loadedbar").width($("#loadedbar").width()+($("#loadingbar").width()/nbPackagesToDeploy));
nbPackagesDeployed++;
}
if(nbPackagesDeployed>=nbPackagesToDeploy)
{
$("#loadedbar").width($("#loadingbar").width());
$("#enddeploymentmessage").attr("display","block");
$("#enddeploymentmessage").css({ opacity: 1 });
$("#ajaxresults").html($("#ajaxresults").html()+"End deployment<br /><br /><br /><br /><br /><br />");
$('#ajaxresults').scrollTop($("#ajaxresults").prop('scrollHeight'));
}
}
function displayNoneEndMessage()
{
$("#enddeploymentmessage").attr("display","none");
$("#enddeploymentmessage").css({ opacity: 0 });
}
| e0ddae377143dbdaea7438f483e6e7c1fdfc81e9 | [
"JavaScript",
"Text",
"PHP"
] | 30 | PHP | RoDKoDRoK/RoDKoDRoK-main | aa6a30f15ab158a27ffcdc8f740edff793fed7c0 | 91e11dc646979e98ea1a1f21144fe2da44569126 |
refs/heads/master | <repo_name>frontapp/docker-pritunl<file_sep>/rootfs/init
#!/bin/sh
# Prepare system for OpenVPN.
mkdir -p /dev/net
if [ ! -c /dev/net/tun ]; then
mknod /dev/net/tun c 10 200
fi
# Database.
pritunl set-mongodb ${DATABASE_URI}
# Network.
pritunl set app.reverse_proxy true
pritunl set app.server_ssl false
pritunl set app.redirect_server false
pritunl set app.server_port ${UI_PORT}
pritunl set host.sync_address ${SYNC_DNS}
pritunl set host.public_address ${VPN_DNS}
pritunl set host.name ${VPN_DNS}
# Start the process.
pritunl start
<file_sep>/Dockerfile
FROM debian:buster-slim
MAINTAINER <NAME> <<EMAIL>>
# Pritunl Install
RUN apt-get -y update \
&& apt-get install -y gnupg \
&& echo "deb http://repo.pritunl.com/stable/apt buster main" > /etc/apt/sources.list.d/pritunl.list \
&& apt-key adv --keyserver hkp://keyserver.ubuntu.com --recv 7568D9BB55FF9E5287D586017AE645C0CF8E292A \
&& apt-get -y update \
&& apt-get -y install iptables pritunl procps \
&& rm -rf /var/lib/apt/lists/*
# Disable trying to edit sysctls since we manage these from Kubernetes
RUN sed -i -r 's/\bself\.enable_ip_forwarding\(/# &/' \
/usr/lib/pritunl/lib/python2.7/site-packages/pritunl/server/instance.py
ADD rootfs /
EXPOSE 443
EXPOSE 10194
ENTRYPOINT ["/init"]
| 98e627de79ee1f811b0390781768e22b9a1f3fae | [
"Dockerfile",
"Shell"
] | 2 | Shell | frontapp/docker-pritunl | 16956f8011fe2c6b22b0fa8da0a6af71f85c7cbe | db557e4558eefd32ad21cf6a8bdbfb2bdb7bdad3 |
refs/heads/master | <file_sep> var ctx = document.getElementById('myChart').getContext('2d');
var chart = new Chart(ctx, {
type: 'bar',
// The data for our dataset
data: {
labels: ["HTML", "CSS", "JS", "PHP", "RUBY", "PYTHON", "JAVA", "RUBY"],
// Information about the dataset
datasets: [{
label: "",
backgroundColor: '#1EAEE7',
borderColor: 'royalblue',
data: [26.4, 39.8, 66.8, 66.4, 40.6, 55.2, 77.4, 69.8],
}]
},
// Configuration options
options: {
layout: {
padding: 10,
},
legend: {
position: '',
},
scales: {
yAxes: [{
ticks: {
beginAtZero:true
},
scaleLabel: {
display: true
}
}]
}
}
}); | 92d197d7bc8bb41515cd0c6f7e18a1056dabd9f4 | [
"JavaScript"
] | 1 | JavaScript | oyinkan/ProDevs | 6192c7ae652b26ec8dc560e2193b1463a132eb4f | d060f9cfb9e9ffdda3d043b777a226dc637fe01a |
refs/heads/master | <repo_name>achowdhury3762/AnimalAPI<file_sep>/README.md
<NAME>
3303
The problem I encountered was accidentally setting my list's adapter to itself. After running a debugging check, I had realized that was my problem. Another problem that arised was getting a reference to the activity inside my adapter. At first I had passed in the activity from the adapter, but later realized it would be better to use a callback.
<file_sep>/app/src/main/java/nyc/c4q/ashiquechowdhury/animalapplication/model/AllAnimals.java
package nyc.c4q.ashiquechowdhury.animalapplication.model;
import java.util.List;
/**
* Created by ashiquechowdhury on 12/21/16.
*/
public class AllAnimals {
private List<Animal> animals;
public List<Animal> getAnimalList() {
return animals;
}
}
| e55161a6e9e1ba0c3a9800cc414d3c68d5cb496a | [
"Markdown",
"Java"
] | 2 | Markdown | achowdhury3762/AnimalAPI | 680ab9fd1534b39c729d9a0736e0ef35f595bfb8 | 75816ac4ef1eec1ab518488db5957170362458a7 |
refs/heads/master | <file_sep># CHAMAQUI
ProjetoIsaias
<file_sep>package br.com.uniara.projeto;
import java.util.Scanner;
import org.jgroups.JChannel;
import org.jgroups.Message;
import org.jgroups.ReceiverAdapter;
public class JGroupsCluster {
public static void main(String[] args) throws Exception {
Scanner scan = new Scanner(System.in);
JChannel channel = new JChannel();
channel.setReceiver(new ReceiverAdapter() {
public void receive(Message msg) {
System.out.println(msg.getObject());
}
});
channel.connect("chat");
System.out.println("Digite Seu nome: ");
String nome = scan.nextLine();
System.out.println("Digite um texto ou sair para sair:");
while (0 < 1) {
String mensagem = scan.nextLine();
if (mensagem.equals("sair")) {
channel.close();
System.exit(0);
}
channel.send(new Message(null, nome + ": " + mensagem));
Thread.sleep(4000);
}
}
} | 309162872a8a7a7015986c61c06e11a58c9c8b38 | [
"Markdown",
"Java"
] | 2 | Markdown | isaiasVitor/CHAMAQUI | 2a971b856dc9fdf016fb3cc1802320090ba2b53f | 9e530b6cd1ea7fb6b3d89f2d50709a21a5295ce1 |
refs/heads/main | <repo_name>cl1ckname/Spartify<file_sep>/requirements.txt
aioredis==1.3.1
asgi-redis
asgiref
async-timeout==3.0.1
attrs==21.2.0
autobahn==21.3.1
Automat==20.2.0
autopep8==1.5.7
backcall==0.2.0
certifi==2021.5.30
cffi==1.14.5
channels==3.0.4
channels-redis==3.3.0
chardet==4.0.0
constantly==15.1.0
cryptography==3.4.7
daphne==3.0.2
debugpy==1.3.0
decorator==5.0.9
defusedxml==0.7.1
Django==3.2.5
django-shortuuidfield==0.1.3
djangorestframework==3.12.4
gunicorn==20.0.4
hiredis==2.0.0
hyperlink==21.0.0
idna==2.10
incremental==21.3.0
ipykernel==6.0.1
ipython==7.25.0
ipython-genutils==0.2.0
jedi==0.18.0
jupyter-client==6.1.12
jupyter-core==4.7.1
matplotlib-inline==0.1.2
msgpack==1.0.2
msgpack-python==0.5.6
oauthlib==3.1.1
parso==0.8.2
pexpect==4.8.0
pickleshare==0.7.5
prompt-toolkit==3.0.19
psycopg2-binary==2.9.1
ptyprocess==0.7.0
pyasn1==0.4.8
pyasn1-modules==0.2.8
pycodestyle==2.7.0
pycparser==2.20
Pygments==2.9.0
PyJWT==2.1.0
pyOpenSSL==20.0.1
python-dateutil==2.8.1
python-dotenv==0.19.0
python3-openid==3.2.0
pytube==10.9.3
pytz==2021.1
pyzmq==22.1.0
redis==2.10.6
requests==2.25.1
requests-oauthlib==1.3.0
service-identity==21.1.0
shortuuid==1.0.1
six==1.16.0
social-auth-app-django==4.0.0
social-auth-core==4.1.0
sqlparse==0.4.1
toml==0.10.2
tornado==6.1
traitlets==5.0.5
Twisted==21.7.0
txaio==21.2.1
typing-extensions==3.10.0.0
urllib3==1.26.6
wcwidth==0.2.5
zope.interface==5.4.0
<file_sep>/backend/migrations/0010_alter_lobby_history.py
# Generated by Django 3.2.5 on 2021-07-15 11:05
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('backend', '0009_alter_lobby_history'),
]
operations = [
migrations.AlterField(
model_name='lobby',
name='history',
field=models.JSONField(blank=True, default=list),
),
]
<file_sep>/backend/static/js/ajax_unban_users.js
var csrftoken = Cookies.get('csrftoken');
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
else {console.log('blinb')}
}
});
var loc = window.location
var wsStart = 'ws://';
if (loc.protocol == 'https:'){
wsStart = 'wss://'
}
var endpoint = wsStart + window.location.host + window.location.pathname;
var socket = new WebSocket(endpoint);
socket.onmessage = function(e){
var data = JSON.parse(e.data)
if (data['unbanned'])
unban(data)
}
var unban = function(response){
$("#unbun").trigger('reset');
var to_unban = response['unbanned'];
to_unban.forEach(function(item, i, arr){
console.log($('#li-ban-'+item));
$('#li-ban-'+item).remove();
});
}
$(document).ready(function () {
$('#unban').submit(function () {
$.ajax({
data: $(this).serialize(),
type: $(this).attr('method'),
dataType: 'json',
url: "/lobby/ajax/unban_users",
success: function(){return false;},
error: function (response) {
alert(response['errors']);
}
});
return false;
});
})<file_sep>/nginx/Dockerfile
FROM nginx
RUN rm /etc/nginx/conf.d/default.conf
COPY nginx.conf /etc/nginx/conf.d
ARG EXTERNAL_PORT
ENV EXTERNAL_PORT=${EXTERNAL_PORT}
RUN echo $EXTERNAL_PORT
RUN sed -i "s/external_port/$EXTERNAL_PORT/" /etc/nginx/conf.d/nginx.conf
<file_sep>/backend/pipeline.py
import datetime
def save_access_token(backend, user, response, details, is_new=False,*args,**kwargs):
if backend.name=='spotify':
print('-----------')
print(user.oauth_token)
print(response)
print('-----------')
user.oauth_token = response['access_token']
user.refresh_token = response['refresh_token']
user.expires = datetime.datetime.now() + datetime.timedelta(seconds=response['expires_in'])
user.save()
<file_sep>/backend/migrations/0006_alter_lobby_id.py
# Generated by Django 3.2.5 on 2021-07-13 15:27
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('backend', '0005_auto_20210713_1506'),
]
operations = [
migrations.AlterField(
model_name='lobby',
name='id',
field=models.IntegerField(primary_key=True, serialize=False),
),
]
<file_sep>/lobby/services.py
''' Some logic that made sense to move to a separate file '''
from django.core.exceptions import ValidationError
from django.shortcuts import redirect, render
from lobby.models import Lobby
from backend.models import User
from lobby.forms import JoinLobby, LobbyForm
def _try_add_to_lobby(request):
''' Validate the user and tries to add him to the lobby '''
pin = request.POST.get('pin')
form = JoinLobby(data=request.POST)
try:
lobby = Lobby.objects.get(id=pin)
lobby.add_user(request.user)
return redirect('/lobby/'+pin)
except ValidationError as e:
form.add_error('pin', e)
data = {'form': form, 'lobby_form': LobbyForm()}
return render(request, 'lobby/lobby.html', data)
<file_sep>/lobby/consumers.py
import json
from channels.generic.websocket import AsyncWebsocketConsumer
from channels.db import database_sync_to_async
class LobbyConsumer(AsyncWebsocketConsumer):
''' Consumer to communicate with the lobby page via WebSocket '''
async def connect(self):
''' Add layer to group on new connection '''
self.lobby_id = self.scope['url_route']['kwargs']['int']
self.group_name = "lobby_"+self.lobby_id
await self.channel_layer.group_add(self.group_name, self.channel_name)
await self.accept()
async def receive(self, text_data):
print('recived', text_data)
async def disconnect(self, code):
''' Remove layer from group on disconnect'''
await self.channel_layer.group_discard(self.group_name, self.channel_name)
async def send_lobby(self, event: dict):
await self.send(text_data=json.dumps(event))<file_sep>/lobby/admin.py
from django.contrib import admin
from lobby.models import Lobby
admin.site.register(Lobby)<file_sep>/lobby/migrations/0012_alter_lobby_id.py
# Generated by Django 3.2.5 on 2021-08-06 10:49
from django.db import migrations
import lobby.models
import shortuuidfield.fields
class Migration(migrations.Migration):
dependencies = [
('lobby', '0011_alter_lobby_id'),
]
operations = [
migrations.AlterField(
model_name='lobby',
name='id',
field=shortuuidfield.fields.ShortUUIDField(blank=True, default=lobby.models._get_short_uuid, editable=False, max_length=22, primary_key=True, serialize=False),
),
]
<file_sep>/backend/middlewares.py
from django.shortcuts import redirect
from backend.SpotifyAPI.api_errors import AuthenticationError, RegularError, SpotifyError
# from backend.logger import api_logger
from logging import getLogger
api_logger = getLogger(__name__)
class ApiMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
response = self.get_response(request)
return response
def process_exception(self, request, exception: SpotifyError):
if isinstance(exception, AuthenticationError):
api_logger.error(exception, extra={'username': request.user.username, 'endpoint': exception.endpoint, 'status_code': exception.status})
return redirect('authentication_error')
elif isinstance(exception, RegularError):
print('------------')
print(api_logger.handlers, api_logger.level, api_logger.name)
api_logger.error(exception, extra={'username': request.user.username, 'endpoint': exception.endpoint, 'status_code': exception.status})
return redirect('server_error')
else:
print(' no spotify exceptions')
return self.get_response(request)<file_sep>/backend/static/js/services.js
export function ban(response) {
$("#ban_form").trigger('reset');
var username = response['username'];
var userid = response['userid'];
var li = $('<li id="li-ban-'+userid+'" class="list-group-item d-flex justify-content-between list-group-item-light">'+username+
'<input class="form-check-input" type="checkbox" name="to_unban" value="'+userid+'" aria-label="..."></li>');
console.log(li);
$('#ban-list ul').prepend(li);
return false;
};
export function add_user(data){
var username = data['username'];
var userid = data['userid'];
var li = $('<li class="list-group-item d-flex justify-content-between list-group-item-light" id="li-'+userid+'"><p>' + username + '</p></li>');
$("#list_members").prepend(li);
}
export function add_track(data) {
$("#add_track").trigger('reset');
var Data = new Date();
var minutes = Data.getMinutes();
var hours = Data.getHours();
var title = data['title'];
var username = data['username'];
var new_li = $('<li class="list-group-item list-group-item-action">'+title+' ' + hours + ':' + minutes +' by '+username+'</li>');
$("#list-history").prepend(new_li);
}
export function remove_members(data) {
$("#remove_members").trigger('reset');
var to_delete = data['to_delete'];
to_delete.forEach(function(item, i, arr){
$('#li-'+item).remove();
});
return false;
}
export function unban(data){
$("#unbun").trigger('reset');
var to_unban = data['unbanned'];
to_unban.forEach(function(item, i, arr){
console.log($('#li-ban-'+item));
$('#li-ban-'+item).remove();
});
}
<file_sep>/lobby/urls.py
from django.urls import path
from django.contrib.auth.decorators import login_required
from lobby import views
urlpatterns = [
path('', views.lobby, name='lobby'),
path('<str:lobby_id>', login_required(views.LobbyView.as_view()), name="clobby"),
path('auth/<str:pin>', views.auth, name='auth'),
path('ajax/add_lobby_track', views.ajax_add_track, name='add_lobby_track'),
path('ajax/remove_members', views.ajax_remove_members, name='remove_members'),
path('ajax/ban_user', views.ajax_ban_user, name='ban_user'),
path('ajax/unban_users', views.ajax_unban_user, name='unban_user')
]<file_sep>/lobby/migrations/0005_lobby_ban_list.py
# Generated by Django 3.2.5 on 2021-07-23 10:08
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('lobby', '0004_lobby_settings'),
]
operations = [
migrations.AddField(
model_name='lobby',
name='ban_list',
field=models.ManyToManyField(related_name='ban', to=settings.AUTH_USER_MODEL),
),
]
<file_sep>/backend/static/js/switch-menu.js
$(document).ready(function(){
var overview_box = $("#overview");
var settings_box = $('#settings');
var overview_button = $('#switch button')[0];
var settings_button = $('#switch button')[1];
var baseUrl = window.location.protocol + "//" + window.location.host + window.location.pathname;
settings_button.onclick =function(){
overview_box.addClass("moveLeft");
settings_box.addClass("moveLeft");
overview_button.style.background = "#ddd";
settings_button.style.background = "#bbb";
history.pushState(null, null, baseUrl + "?p=settings");
};
overview_button.onclick = function(){
overview_box.removeClass("moveLeft")
settings_box.removeClass("moveLeft");
overview_button.style.background = "#bbb";
settings_button.style.background = "#ddd";
history.pushState(null, null, baseUrl + "?p=overview");
};
});<file_sep>/lobby/models.py
import datetime
import shortuuid
from django.core.exceptions import ValidationError
from django.db import models
from backend.models import User
from shortuuidfield import ShortUUIDField
uid_generator = shortuuid.ShortUUID(
alphabet='1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ')
def _get_short_uuid():
return str(uid_generator.uuid())[:5]
class Lobby(models.Model):
id = ShortUUIDField(primary_key=True, default = _get_short_uuid)
password = models.CharField(max_length=12, blank=True)
owner = models.OneToOneField(User, on_delete=models.CASCADE)
history = models.JSONField(default=list, blank=True)
num_members = models.PositiveIntegerField("num_members")
max_members = models.PositiveIntegerField("max_members")
ban_list = models.ManyToManyField(User, related_name="ban", blank=True)
settings = models.JSONField(default={'num_members': 1, 'max_members': 5, 'ban_list': []})
def add_user(self, user):
""" Add user to lobby if it possible"""
if self.num_members < self.max_members:
if not self.ban_list.filter(id = user.id):
self.num_members += 1
user.lobby_in = self
user.save()
self.save()
else:
raise ValidationError("You are banned here", code='invalid')
else:
raise ValidationError("Lobby is full! Max members: %(max_members)s", params={'max_members': self.max_members})
def remove_users(self, users: list):
''' Removes users from lobby '''
for id in users:
user = User.objects.get(id=int(id))
if user.lobby_in == self:
user.lobby_in = None
user.save()
def ban_user(self, username: str):
''' Ban user in lobby '''
user = User.objects.get(username = username)
if user.lobby_in == self:
user.lobby_in = None
user.save()
self.ban_list.add(user)
self.save()
def add_history(self, username: str, title: str):
''' Adds track information to the lobby history '''
to_json = {'title': title, 'time': datetime.datetime.now(
).strftime('%H:%M'), 'user': username}
if len(self.history) > 9:
self.history = self.history[0:9] #max len of history - 10 tracks
self.history = [to_json] + self.history
self.save()
def unban_users(self, to_unban: list):
''' Add users to ban list and removes his from lobby '''
try:
for user_id in to_unban:
user = User.objects.get(id=int(user_id))
self.ban_list.remove(user)
except User.DoesNotExist:
raise ValidationError("Unban error")
def leave(self, member: User):
self.num_members -= 1
member.lobby_in = None
self.save()
member.save()<file_sep>/backend/SpotifyAPI/api_errors.py
from requests import Response
class SpotifyError(Exception):
''' Errors related to Spotify API '''
def __init__(self, response: Response):
self.text = 'API Errror'
self.endpoint = response.url
self.status = response.status_code
def __str__(self) -> str:
return self.text
class AuthenticationError(SpotifyError):
''' Whenever the application makes requests related
to authentication or authorization to Web API, such
as retrieving an access token or refreshing an access
token, the error response follows RFC 6749 on the OAuth 2.0 Authorization Framework
'''
def __init__(self, response: Response):
super(AuthenticationError, self).__init__(response)
self.text = response.json()['error_description']
class RegularError(SpotifyError):
''' Apart from the response code, unsuccessful responses return a JSON object containing the following information '''
def __init__(self, response):
super(RegularError, self).__init__(response)
self.text = response.json().get('error_description') or 'unknown_error'
<file_sep>/backend/templates/backend/logout.html
{% load static %}
<html>
<head>
<link href="{% static "css/base.css" %}" rel="stylesheet">
<link href="{% static "css/big_elements.css" %}" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="<KEY>" crossorigin="anonymous">
</head>
<body>
<span class="ticker" style="color: #fff; background: #1DB954; top: -3px;">#comeback
#comeback
#comeback
#comeback
#comeback
#comeback
#comeback
#comeback
#comeback
#comeback
#comeback
#comeback
#comeback
#comeback
#comeback
#comeback
#comeback
#comeback
#comeback
#comeback
#comeback
#comeback
#comeback
#comeback
#comeback
#comeback
#comeback
#comeback
#comeback
#comeback
</span>
<div class="content">
<h2 class="big-title">Goodbye!</h2>
<p class="header-text">
Hope you come back! If you want to log in under a
different account, then <i>clear the cookies</i> of this site.
So far so.
<a href="{% url "social:begin" "spotify" %}">Log in</a> again.
</p>
<div class="flex-center">
<a href="{% url "social:begin" "spotify" %}"> <button class="big-button">Log in</button> </a>
</div>
</div>
</body>
</html><file_sep>/backend/static/js/ajax_lobby_add_track.js
var csrftoken = Cookies.get('csrftoken');
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
else {console.log('blinb')}
}
});
var add_track = function (response) {
$("#add_track").trigger('reset');
var Data = new Date();
var minutes = Data.getMinutes();
var hours = Data.getHours();
var title = response['title'];
var username = response['username'];
var new_li = $('<li class="list-group-item list-group-item-action">'+title+' ' + hours + ':' + minutes +' by '+username+'</li>');
$("#list-history").prepend(new_li);
}
var loc = window.location
var wsStart = 'ws://';
if (loc.protocol == 'https:'){
wsStart = 'wss://'
}
var endpoint = wsStart + window.location.host + window.location.pathname;
var socket = new WebSocket(endpoint);
socket.onmessage = function(e){
var data = JSON.parse(e.data)
console.log(data)
if (data['title']){
add_track(data)
}
};
$(document).ready(function () {
$('#add_track').submit(function () {
$.ajax({
data: $(this).serialize(),
type: $(this).attr('method'),
url: "/lobby/ajax/add_lobby_track",
success: function(response){return false;},
error: function (response) {
alert(response['errors']);
}
});
return false;
});
})<file_sep>/backend/templates/backend/login.html
{% load static %}
<html>
<head>
<link href="{% static "css/base.css" %}" rel="stylesheet">
<link href="{% static "css/big_elements.css" %}" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="<KEY>" crossorigin="anonymous">
</head>
<body>
<span class="ticker" style="color: #fff; background: #1DB954; top: -3px;">#comeback
#comeback
#comeback
#comeback
#comeback
#comeback
#comeback
#comeback
#comeback
#comeback
#comeback
#comeback
#comeback
#comeback
#comeback
#comeback
#comeback
#comeback
#comeback
#comeback
#comeback
#comeback
#comeback
#comeback
#comeback
#comeback
#comeback
#comeback
#comeback
#comeback
</span>
<div class="content">
<h2 class="big-title">Hello!</h2>
<p class="header-text">
Hey! This is #SPARTIFY - a service
for collective listening to music from
Spotify. First, let's
<a href="{% url "social:begin" "spotify" %}">log in</a> ...
</p>
<div class="flex-center">
<a href="{% url "social:begin" "spotify" %}"> <button class="big_button">Log in</button> </a>
</div>
</div>
</body>
</html><file_sep>/spartify/urls.py
from django.contrib import admin
from django.urls import path, include
handler404 = 'backend.views.handler404'
handler500 = 'backend.views.handler500'
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('backend.urls')),
path('social/', include('social_django.urls')),
path('lobby/', include('lobby.urls'))
]
<file_sep>/backend/admin.py
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.forms import UserChangeForm
from .models import User
class UserChangeForm(UserChangeForm):
class Meta(UserChangeForm.Meta):
model = User
class Admin(UserAdmin):
form = UserChangeForm
model = User
list_display = ('id','username','oauth_token', 'refresh_token', 'expires', 'lobby_in', 'password')
fieldsets = UserAdmin.fieldsets + (
(None, {'fields': ('lobby_in',)}),
)
admin.site.register(User, Admin)
<file_sep>/backend/migrations/0004_auto_20210711_1225.py
# Generated by Django 3.2.5 on 2021-07-11 12:25
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('backend', '0003_auto_20210711_0933'),
]
operations = [
migrations.DeleteModel(
name='QueueTrack',
),
migrations.AlterField(
model_name='user',
name='refresh_token',
field=models.CharField(max_length=250, verbose_name='refresh_token'),
),
]
<file_sep>/backend/fields.py
''' Special fields for forms '''
from django import forms
from django.core.exceptions import ValidationError
from backend.utils import clear_track
class LinkField(forms.CharField):
''' Field for Spotify tracks links'''
def validate(self, value):
try:
clear_track(value)
except ValueError:
raise ValidationError("Incorrect link")
return value
<file_sep>/lobby/migrations/0014_alter_lobby_password.py
# Generated by Django 3.2.5 on 2021-08-06 11:11
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('lobby', '0013_lobby_password'),
]
operations = [
migrations.AlterField(
model_name='lobby',
name='password',
field=models.CharField(blank=True, max_length=12),
),
]
<file_sep>/backend/views.py
from django.contrib.auth import logout
from django.http.response import JsonResponse
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from backend.SpotifyAPI.tracks import Track
from backend.utils import _make_devices_list
from lobby.queue import Queue
from backend.SpotifyAPI import api
from .forms import AddTrackForm
from backend.services import safe_view
def user_login(request):
return render(request, 'backend/login.html')
def user_logout(request):
logout(request)
return render(request, 'backend/logout.html')
@safe_view
@login_required
def dashboard(request):
user = request.user
queue = Queue(request)
api.refresh_user(user)
token = user.oauth_token
if token:
track = Track(token)
user_info = api.get_me(token)
else:
raise Exception('No TOKEN')
form = AddTrackForm()
info = zip(queue.get_names(), queue.get_times(), queue.get_users())
return render(request, 'backend/dashboard.html', {'section': 'dashboard', 'track': track, 'form': form,
'info': info, 'user_info': user_info})
@safe_view
@login_required
def devices(request):
user = request.user
api.refresh_user(user)
if request.method == "POST":
print(request.POST)
data = api.get_user_devices(user.oauth_token)
devices_list = _make_devices_list(data)
return render(request, 'backend/devices.html', {'section': 'devices', 'devices_list': devices_list})
@safe_view
@login_required
def post_queue(request):
print(132132131)
print(request.method == 'POST', request.is_ajax())
username = request.user.username
if request.method == 'POST' and request.is_ajax():
form = AddTrackForm(data=request.POST)
if form.is_valid():
queue = Queue(request)
token = request.user.oauth_token
link = request.POST['link']
track = Track(token, link)
track.to_queue()
queue.add(track.name, username)
return JsonResponse({'title': track.name, 'username': username}, status=200)
else:
return JsonResponse({'errors': form.errors}, status=400)
def authentication_error(request):
logout(request)
return render(request, 'backend/authentication_error.html')
def handler500(request):
logout(request)
return render(request, 'backend/500.html')
def handler404(request, exception):
return render(request, 'backend/404.html')<file_sep>/lobby/forms.py
from django import forms
from django.core.exceptions import ValidationError, ObjectDoesNotExist
from django.forms.widgets import PasswordInput
from lobby.models import Lobby
from backend.models import User
class PinField(forms.Field):
''' Field for pin '''
def to_python(self, value:str):
''' Attempts to convert the entered value to a number '''
if not value:
raise ValidationError("Field is empty")
try:
return value.upper()
except ValueError:
raise ValidationError("The entered value is not a string")
def validate(self, value):
''' Checks if a lobby with this number exists '''
super(PinField, self).validate(value)
try:
lobby = Lobby.objects.get(id=value)
if lobby.num_members >= lobby.max_members:
raise ValidationError("Lobby is full. Max members: %(max_members)s", params={'max_members': lobby.max_members})
return value
except ObjectDoesNotExist:
raise ValidationError("There is no lobby with this number!")
class BanField(forms.Field):
def vlidate(self, value):
''' Validator for validate username '''
value = self.username
try:
User.objects.get(username=value)
except ObjectDoesNotExist:
raise ValidationError("There is no user with such username")
class JoinLobby(forms.Form):
pin = PinField(required=True, label="Lobby PIN:",
help_text="Ask your lobby owner the #PIN code")
class Meta:
db_table = "lobby"
class LobbyForm(forms.ModelForm):
password = forms.CharField(max_length=12, widget=forms.PasswordInput, required=False)
class Meta:
model = Lobby
fields = ("max_members", 'password')
class MaxMembersForm(forms.Form):
def __init__(self, num_members=5, *args, **kwargs):
super(MaxMembersForm, self).__init__(*args, **kwargs)
self.num_members = num_members
self.fields['max_members'] = forms.IntegerField(min_value=num_members, label='Max members:',
help_text='The max (abbreviated sup; plural suprema) of a subset S of a partially ordered set'
' T is the least element in T that is greater than or equal to all elements of S, if'
' such an element exists. Consequently, the max is also referred to as the least upper bound')
class BanForm(forms.Form):
''' Form containing a field for username '''
username = BanField(label="")
class LobbyPassword(forms.Form):
''' Lobby password form on the intermediate page between /lobby and /lobby/PIN '''
password = forms.CharField(max_length=12, widget=forms.PasswordInput, required=True)<file_sep>/lobby/migrations/0008_alter_lobby_id.py
# Generated by Django 3.2.5 on 2021-08-06 09:41
from django.db import migrations, models
import uuid
class Migration(migrations.Migration):
dependencies = [
('lobby', '0007_alter_lobby_id'),
]
operations = [
migrations.AlterField(
model_name='lobby',
name='id',
field=models.UUIDField(default=uuid.uuid1, primary_key=True, serialize=False),
),
]
<file_sep>/lobby/migrations/0006_alter_lobby_ban_list.py
# Generated by Django 3.2.5 on 2021-07-23 14:17
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('lobby', '0005_lobby_ban_list'),
]
operations = [
migrations.AlterField(
model_name='lobby',
name='ban_list',
field=models.ManyToManyField(blank=True, related_name='ban', to=settings.AUTH_USER_MODEL),
),
]
<file_sep>/backend/static/js/ajax_queue.js
var csrftoken = Cookies.get('csrftoken');
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
else {console.log('blinb')}
}
});
$(document).ready(function () {
$('#add_sub').submit(function () {
$.ajax({
data: $(this).serialize(),
type: $(this).attr('method'),
url: "/ajax/add_queue",
success: function (response) {
console.log(122);
$("#add_sub").trigger('reset');
var Data = new Date();
var minutes = Data.getMinutes();
var hours = Data.getHours();
var title = response['title'];
var username = response['username'];
var new_li = $('<li class="list-group-item list-group-item-action">'+title+' ' + hours + ':' + minutes +' by '+username+'</li>');
$("#history").prepend(new_li)
},
error: function (response) {
alert("Incorrect link!");
}
});
return false;
});
})<file_sep>/lobby/migrations/0004_lobby_settings.py
# Generated by Django 3.2.5 on 2021-07-20 15:26
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('lobby', '0003_lobby_max_members'),
]
operations = [
migrations.AddField(
model_name='lobby',
name='settings',
field=models.JSONField(default={'ban_list': [], 'max_members': 5, 'num_members': 1}),
),
]
<file_sep>/backend/models.py
from django.db import models
from django.contrib.auth.models import AbstractUser
class User(AbstractUser):
'''Extended standard user class that stores information necessary to work with Spotify API'''
id = models.AutoField(primary_key=True)
access_token = models.CharField('oauth_token', max_length=250)
oauth_token = models.CharField('oauth_token', max_length=250)
refresh_token = models.CharField('refresh_token', max_length=250)
expires = models.DateTimeField('expires', auto_now_add=True)
device_id = models.CharField('device_id', max_length=50)
lobby_in = models.ForeignKey('lobby.Lobby', blank=True ,null=True ,on_delete=models.SET_NULL)
<file_sep>/spartify/routing.py
from django.urls import path
from channels.routing import ProtocolTypeRouter, URLRouter
from channels.auth import AuthMiddlewareStack
from channels.security.websocket import AllowedHostsOriginValidator
from lobby.consumers import LobbyConsumer
application = ProtocolTypeRouter({
'websocket': AllowedHostsOriginValidator(
AuthMiddlewareStack(
URLRouter(
[
path(r'lobby/<int>', LobbyConsumer.as_asgi()),
]
)
)
)
})<file_sep>/README.md
# Spartify
[](https://lgtm.com/projects/g/cl1ckname/Spartify/context:python)
Spartify is a collaborative queue management service on [Spotify](https://www.spotify.com/)
## Why?
Usually, in a large group of friends, exactly one person turns on the music. This is logical because there is only one person who is the source of the music. From my own experience I can say that this person is constantly asked to "turn on __this__ track", add an album to the queue, turn it down / up. Or vice versa, the whole company wants to listen to some artist, but the __host__ does not include him in any. These and other problems should be solved by Spartify.

## To do
- [x] Append README.md
- [x] Add the ability to add tracks to your queue using the site
- [x] Ability to create a lobby and get a pin code for it
- [x] Add settings for lobbies
- [ ] Add more settings to lobbies
- [ ] Ban list for tracks
- [ ] Limit on the number of tracks for each user
- [x] Registration for premium Spotify users and simple users
- [ ] Add votes for the next track
- [ ] Add lobby privileges
- [ ] Ability add playlists and albums to queue
- [ ] Creating a beautiful frontend
- [ ] Upload the application to stable hosting
- [ ] Play music in big campaigns with ease!
- [x] Build the application into a Docker container
- [ ] Realize API
- [ ] ~~Make a lot of money~~
- [ ] ~~Make a some money~~
- [x] ~~Make a little money~~
- [ ] Write a lot of tests
- [ ] Add unusual statistic for users on dashboard
## Docker
To build spartify into a docker container, you need to create file:
.env.dev:
```
SOCIAL_AUTH_SPOTIFY_KEY=<your_spotify_app_key>
SOCIAL_AUTH_SPOTIFY_SECRET=<your_spotify_secret_key>
SECRET_KEY=<django_secret>
SQL_ENGINE=django.db.backends.postgresql
SQL_DATABASE=<datebase>
SQL_USER=<postgre_user>
SQL_PASSWORD=<<PASSWORD>>
SQL_HOST=<postgre_host>
SQL_PORT=5432
DATABASE=postgres
DJANGO_ALLOWED_HOSTS=localhost 127.0.0.1 [::1]
```
in the root folder of the project.
Build command: `docker-compose up -d --build`
## About other Spartify projects
Recently I stumbled upon several projects of the same name by chance. I haven't heard of any of them, but the name and purpose coincide with some. I hope their developers will not be offended by me. I consider it necessary to leave links to their repositories:
* https://github.com/ysomad/spartify
* https://github.com/blixt/spartify
* https://github.com/rphammy/Spartify
* https://github.com/YuhuaBillChen/Spartify
## Help
If you want to help the project, then I'm looking for:
* designers
* layout designers
* mentors
* (open to tips and code reviews)
* just not indifferent
### Contacts
[](https://vk.com/clickname)
[](https://twitter.com/Cl1ckName)
[](mailto:<EMAIL>)<file_sep>/lobby/migrations/0002_auto_20210717_1914.py
# Generated by Django 3.2.5 on 2021-07-17 19:14
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('lobby', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='lobby',
name='num_members',
field=models.PositiveIntegerField(default=1, verbose_name='num_members'),
preserve_default=False,
),
migrations.AlterField(
model_name='lobby',
name='id',
field=models.PositiveIntegerField(primary_key=True, serialize=False),
),
]
<file_sep>/backend/migrations/0007_lobby_history.py
# Generated by Django 3.2.5 on 2021-07-14 09:24
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('backend', '0006_alter_lobby_id'),
]
operations = [
migrations.AddField(
model_name='lobby',
name='history',
field=models.JSONField(default=[]),
),
]
<file_sep>/backend/SpotifyAPI/__init__.py
''' A package for using api spotify. Contains an api object that gets the user code and secret code from the project settings. '''
import base64
import datetime
import json
from django.conf import settings
from django.utils.timezone import make_aware
import requests as rq
from urllib.parse import quote
from requests.models import Response
from .api_errors import AuthenticationError, RegularError
def check_response(func):
''' Returns content of response or raise API error'''
def new_f(self, *args, **kwargs) -> dict:
r = func(self, *args, **kwargs)
if r.status_code not in range(200, 299):
if r.status_code == 401:
raise AuthenticationError(r)
raise RegularError(r)
content = r.content.decode()
if content:
return json.loads(content)
return {}
return new_f
class SpotifyAPI(object):
'''
Api class. No more documentation yet
'''
acces_token = None
acces_token_expires = datetime.datetime.now()
acces_token_did_expire = True
client_id = None
client_secret = None
def __init__(self, client_id: str, client_secret: str, *args, **kwargs):
super().__init__(*args, **kwargs)
self.client_id = client_id
self.client_secret = client_secret
def get_client_creditales(self) -> str:
'''
Returns a base64 encoded string
'''
if self.client_secret is None or self.client_id is None:
raise Exception("You must set client_id and client_secret")
client_creds = f'{self.client_id}:{self.client_secret}'
client_creds_b64 = base64.b64encode(client_creds.encode())
return client_creds_b64.decode()
def perform_auth(self) -> bool:
'''
Try to get and save client credentials access token.
Returns true on success or false.
'''
url = 'https://accounts.spotify.com/api/token'
data = {
'grant_type': 'client_credentials'
}
headers = {
'Authorization': f'Basic {self.get_client_creditales()}'
}
r = rq.post(url, data=data, headers=headers)
token_response = r.json()
if r.status_code not in range(200, 299):
raise Exception('Authentificate failed')
now = make_aware(datetime.datetime.now())
self.acces_token = token_response['access_token']
expire_in = token_response['expires_in']
self.acces_token_expires = now + datetime.timedelta(seconds=expire_in)
self.acces_token_did_expire = self.acces_token_expires < now
return True
def get_access_token(self) -> str:
'''
An interface for obtaining an access token. Retrieves the token if the current one has expired. Returns the access token.
'''
token = self.acces_token
expires = self.acces_token_expires
now = datetime.datetime.now()
if expires < now or token is None:
self.perform_auth()
return self.acces_token
return token
@check_response
def search(self, query: str, search_type: str = 'track', *args, **kwargs) -> Response:
'''
Searches for a track, playlist, album or artist by title and returns json from https://api.spotify.com/v1/search.
query - part of title
search_type - the type of object you are looking for. Possible values: album , artist, playlist, track, show and episode
'''
header = {
'Authorization': f'Bearer {self.get_access_token()}'
}
lookup = 'https://api.spotify.com/v1/search?q={}&type={}&market=RU'.format(query, search_type)
r = rq.get(lookup, headers=header)
return r
@check_response
def get_oauth(self, access_token: str, redirected_uri: str) -> Response:
'''
Makes a request for https://accounts.spotify.com/api/token and returns the user's oauth token.
access_token - the token received by the corresponding request to https://accounts.spotify.com/api/token
redirected_uri - a valid redirection path. Set in the settings of the Spotify app
'''
uri = 'https://accounts.spotify.com/api/token'
headers = {
'Authorization': 'Basic MThmNDkxNGQ3NzE4NGI2NzgwZTgzNmFkOWQ4ZjY4NGM6YTY0NWI2NTVjYTEzNGNlYzllNDRiZTE5NDNmMDJhNjQ=',
'Content-Type': 'application/x-www-form-urlencoded'
}
data = {
'grant_type': 'authorization_code',
'code': access_token,
'redirect_uri': redirected_uri
}
r = rq.post(uri, data, headers=headers)
return r
@check_response
def refresh_token(self, refresh_token) -> Response:
uri = 'https://accounts.spotify.com/api/token'
headers = {
'Authorization': f'Basic {self.get_client_creditales()}',
'Content-Type': 'application/x-www-form-urlencoded'
}
data = {
'grant_type':'refresh_token',
'refresh_token': refresh_token
}
r = rq.post(uri, data=data, headers=headers)
print(r.text)
print(refresh_token)
return r
@check_response
def get_user_playback(self, oauth_token: str) -> Response:
'''
Makes a request for https://api.spotify.com/v1/me/player/currently-playing and returns the corresponding json.
oauth_token - user token obtained using get_oauth()
'''
uri = 'https://api.spotify.com/v1/me/player/currently-playing'
headers = {
'Authorization': f'Bearer {oauth_token}'
}
r = rq.get(uri, headers=headers)
return r
@check_response
def get_user_devices(self, oauth: str) -> Response:
'''
Makes a request for https://api.spotify.com/v1/me/player/devices and returns the corresponding json.
'''
uri = 'https://api.spotify.com/v1/me/player/devices'
headers = {
'Authorization': f'Bearer {oauth}'
}
r = rq.get(uri, headers=headers)
return r
@check_response
def get_track(self, id, oauth):
''' Makes a request for https://api.spotify.com/v1/tracks/ and returns the information about track'''
lookup = f'https://api.spotify.com/v1/tracks/{id}'
headers = {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': f'Bearer {oauth}'
}
r = rq.get(lookup, headers=headers)
return r
@check_response
def add_queue(self, uri:str, oauth:str):
''' Add track in user player queue '''
endpoint = f'https://api.spotify.com/v1/me/player/queue?uri={quote("spotify:track:"+uri, safe="")}'
headers = {
'Authorization': f'Bearer {oauth}'
}
data = {
'uri': 'spotify:track:'+uri,
}
r = rq.post(endpoint, headers=headers, data=data)
return r
@check_response
def get_me(self, oauth: str):
''' get information about user '''
endpoint = 'https://api.spotify.com/v1/me'
headers = {
'Authorization': f'Bearer {oauth}'
}
r = rq.get(endpoint, headers=headers)
return r
def refresh_user(self, user) -> None:
''' Checks if the user's token has expired and refreshes it if necessary '''
print(1, user.username, user.refresh_token)
if user.expires.replace(tzinfo=None) < datetime.datetime.now(tz=None):
refresh_data = self.refresh_token(user.refresh_token)
print(2)
user.oauth_token = refresh_data['access_token']
user.expires = make_aware(datetime.datetime.now(tz=None)) + datetime.timedelta(seconds=refresh_data['expires_in'])
user.save()
api = SpotifyAPI(settings.SOCIAL_AUTH_SPOTIFY_KEY,
settings.SOCIAL_AUTH_SPOTIFY_SECRET)<file_sep>/backend/migrations/0005_auto_20210713_1506.py
# Generated by Django 3.2.5 on 2021-07-13 15:06
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('backend', '0004_auto_20210711_1225'),
]
operations = [
migrations.CreateModel(
name='Lobby',
fields=[
('id', models.AutoField(primary_key=True, serialize=False)),
('owner', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
migrations.AddField(
model_name='user',
name='lobby_in',
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='backend.lobby'),
),
]
<file_sep>/lobby/migrations/0013_lobby_password.py
# Generated by Django 3.2.5 on 2021-08-06 11:10
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('lobby', '0012_alter_lobby_id'),
]
operations = [
migrations.AddField(
model_name='lobby',
name='password',
field=models.CharField(default='', max_length=12),
preserve_default=False,
),
]
<file_sep>/backend/services.py
import traceback
import functools
from logging import getLogger
from django import http
from django.views.generic.base import TemplateView
from django.shortcuts import redirect, render
from .SpotifyAPI.api_errors import AuthenticationError, RegularError
from django.conf import settings
api_logger = getLogger(__name__)
def _get_error_response(request: http.HttpRequest, e: Exception) -> http.response.HttpResponseBase:
if isinstance(e, AuthenticationError):
api_logger.error(e, extra={'username': request.user.username, 'endpoint': e.endpoint, 'status_code': e.status})
return redirect('authentication_error')
else:
api_logger.error(e, extra={'username': request.user.username, 'endpoint': e.endpoint, 'status_code': e.status})
return render(request,'backend/500.html',status=500)
class SafeView(TemplateView):
''' Process exceptions '''
def dispatch(self, request: http.HttpRequest, *args, **kwargs) -> http.response.HttpResponseBase:
try:
response = super().dispatch(request, *args, **kwargs)
except Exception as e:
response = _get_error_response(request, e)
return response
def safe_view(view):
''' '''
@functools.wraps(view)
def inner(request, *args, **kwargs):
try:
return view(request, *args, **kwargs)
except Exception as e:
return _get_error_response(request, e)
return inner<file_sep>/lobby/views.py
from backend.SpotifyAPI.tracks import Track
from django.http.response import JsonResponse
from django.shortcuts import render, redirect
from django.core.exceptions import ObjectDoesNotExist
from django.contrib.auth.decorators import login_required
from django.http import Http404, HttpResponse
from channels.layers import get_channel_layer
from asgiref.sync import async_to_sync
from lobby.services import _try_add_to_lobby
from .models import Lobby, User
from backend.forms import AddTrackForm
from lobby.forms import BanForm, JoinLobby, LobbyForm, MaxMembersForm, LobbyPassword
from backend.SpotifyAPI import api
from backend.services import SafeView, safe_view
@safe_view
@login_required
def lobby(request):
user = request.user
if request.method == 'POST':
pin = request.POST.get('pin')
max_members = request.POST.get('max_members')
if pin:
form = JoinLobby(data=request.POST)
if form.is_valid():
lobbyc = Lobby.objects.get(id=pin)
if not lobbyc.password:
response = _try_add_to_lobby(request)
channel_layer = get_channel_layer()
channel_name = 'lobby_%s' % lobbyc.id
async_to_sync(channel_layer.group_send)(channel_name, {
'type': f'add_user', 'username': request.user.username, 'userid': request.user.id})
return response
else:
return redirect('auth/'+pin)
else:
data = {'form': form, 'lobby_form': LobbyForm(),
'error': form.errors}
return render(request, 'lobby/lobby.html', data)
elif max_members:
_lobby = Lobby(owner=user,
max_members=int(max_members), num_members=1)
_lobby.save()
id = _lobby.id
user.lobby_in = _lobby
user.save()
return redirect(f'/lobby/{id}')
else:
return render(request, 'lobby/lobby.html', {'form': JoinLobby(), 'lobby_form': LobbyForm()})
else:
form = JoinLobby()
if not user.lobby_in:
return render(request, 'lobby/lobby.html', {'form': form, 'lobby_form': LobbyForm()})
else:
return redirect('/lobby/'+str(user.lobby_in.id))
@safe_view
@login_required
def auth(request, pin):
lobby = Lobby.objects.get(id=pin)
if not lobby.password:
return redirect('lobby/'+pin)
if request.method == 'GET':
form = LobbyPassword()
else:
password = request.POST.get('password')
if password == lobby.<PASSWORD>:
lobby.add_user(request.user)
return redirect('/lobby/'+pin)
form = LobbyPassword(request.POST)
return render(request, 'lobby/auth.html', {'form': form, 'pin': pin})
class LobbyView(SafeView):
''' Lobby Page View '''
template_name = 'lobby/lobby_template.html'
this_lobby = None
members = None
owner = None
form = None
username = None
channel_layer = get_channel_layer()
channel_name = None
def get(self, request, lobby_id=0, *args, **kwargs) -> HttpResponse:
''' Creates a form and returns a page render if the request method is GET '''
self.form = AddTrackForm()
try:
self.set_data(request, lobby_id)
except Lobby.DoesNotExist:
return render(request, 'lobby/no_lobby.html')
return self.display_page(request)
def post(self, request, lobby_id=0, *args, **kwargs) -> HttpResponse:
''' Creates a form and validates it and also returns a page render if the request method is POST'''
self.username = request.user.username
data = request.POST
leave = data.get('leave')
to_unban = request.POST.getlist('to_unban')
username = data.get('username')
id_to_delete = data.get('delete')
try:
self.set_data(request, lobby_id)
except ObjectDoesNotExist:
return redirect('/lobby')
if username:
ban_form = BanForm(data=request.POST)
if ban_form.is_valid():
self.send_websocket_data(type='send_lobby', username=username)
self.this_lobby.ban_user(username)
elif to_unban:
lobby_id = request.POST.get('lobby_id')
channel_name = 'lobby_%s' % lobby_id
async_to_sync(self.channel_layer.group_send)(
channel_name, {'type': f'send_lobby', 'event':'unban', 'unbanned': to_unban})
elif leave:
self.this_lobby.leave(request.user)
return redirect('lobby')
elif id_to_delete:
if id_to_delete == str(self.this_lobby.id):
self.this_lobby.delete()
return redirect('lobby')
return self.display_page(request)
def set_data(self, request, lobby_id) -> None:
''' Sets the view data according to the request and the lobby '''
self.username = request.user.username
self.this_lobby = Lobby.objects.get(id=lobby_id)
self.members = User.objects.filter(lobby_in=self.this_lobby)
self.owner = self.this_lobby.owner
self.channel_name = 'lobby_%s' % lobby_id
print(5)
api.refresh_user(self.owner)
print(5)
def display_page(self, request) -> HttpResponse:
''' Collects the view fields in the HttpResponse and checks the user's access to the lobby '''
if request.user.lobby_in != self.this_lobby:
return HttpResponse('Forbidden')
if self.this_lobby:
return render(request, self.template_name, self.get_page_data())
else:
raise Http404
def get_page_data(self) -> dict:
''' Collect all data in one dict to '''
track = Track(self.owner.oauth_token)
history = self.this_lobby.history
ban_list = self.this_lobby.ban_list.all()
return {'section': 'lobby', 'lobby': self.this_lobby, 'members': self.members, 'track': track, 'form': self.form,
'owner': self.owner.username, 'history': history, 'is_owner': (self.owner == self.request.user),
'mmf': MaxMembersForm(num_members=3), 'ban_form': BanForm(), 'ban_list': ban_list}
def send_websocket_data(self, **kwargs):
async_to_sync(self.channel_layer.group_send)(self.channel_name, kwargs)
@login_required
def ajax_add_track(request) -> JsonResponse:
if request.method == 'POST' and request.is_ajax():
form = AddTrackForm(data=request.POST)
if form.is_valid():
link = request.POST['link']
lobby_id = request.POST['add_to']
lobby = Lobby.objects.get(id=lobby_id)
track = Track(lobby.owner.oauth_token, link)
track.to_queue()
channel_layer = get_channel_layer()
channel_name = 'lobby_%s' % lobby.id
async_to_sync(channel_layer.group_send)(channel_name, {
'type': 'send_lobby', 'event': 'add_track', 'title': track.name, 'username': request.user.username})
lobby.add_history(request.user.username, track.name)
return JsonResponse({'title': track.name, 'username': request.user.username}, status=200)
else:
return JsonResponse({'errors': form.errors}, status=400)
else:
return JsonResponse({'errors': 'Not post or ajax'})
@login_required
def ajax_remove_members(request) -> JsonResponse:
if request.method == 'POST' and request.is_ajax():
to_delete = request.POST.getlist('to_delete')
lobby_id = request.POST.get('lobby_id')
lobby = Lobby.objects.get(id=lobby_id)
channel_layer = get_channel_layer()
channel_name = 'lobby_%s' % lobby.id
async_to_sync(channel_layer.group_send)(channel_name, {
'type': 'send_lobby', 'event': 'remove_members', 'to_delete': to_delete})
lobby.remove_users(to_delete)
if not isinstance(to_delete, list):
to_delete = [to_delete]
return JsonResponse({'to_delete': to_delete}, status=200)
else:
return JsonResponse({'errors': 'Not post or ajax'}, status=400)
@login_required
def ajax_ban_user(request) -> JsonResponse:
if request.method == 'POST' and request.is_ajax():
username = request.POST['username']
user = User.objects.get(username=username)
lobby = request.user.lobby_in
channel_layer = get_channel_layer()
channel_name = 'lobby_%s' % lobby.id
async_to_sync(channel_layer.group_send)(channel_name, {
'type': 'send_lobby', 'event': 'ban', 'username': username, 'userid': user.id})
ban_form = BanForm(data=request.POST)
if ban_form.is_valid():
lobby.ban_user(username)
return JsonResponse({'username': username}, status=200)
else:
return JsonResponse({'errors': 'Not post or ajax'}, status=400)
@login_required
def ajax_unban_user(request) -> JsonResponse:
if request.method == 'POST' and request.is_ajax():
to_unban = request.POST.getlist('to_unban')
lobby_id = request.POST.get('lobby_id')
lobby = Lobby.objects.get(id=lobby_id)
channel_layer = get_channel_layer()
channel_name = 'lobby_%s' % lobby_id
async_to_sync(channel_layer.group_send)(
channel_name, {'type': 'send_lobby', 'event': 'unban', 'unbanned': to_unban})
lobby.unban_users(to_unban)
return JsonResponse({'unbanned': to_unban}, status=200)
else:
return JsonResponse({'errors': 'Not post or ajax'}, status=400)
<file_sep>/backend/migrations/0003_auto_20210711_0933.py
# Generated by Django 3.2.5 on 2021-07-11 09:33
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('backend', '0002_user_access_token'),
]
operations = [
migrations.CreateModel(
name='QueueTrack',
fields=[
('id', models.AutoField(primary_key=True, serialize=False)),
('link', models.CharField(max_length=150)),
],
),
migrations.AddField(
model_name='user',
name='device_id',
field=models.CharField(default='f9aeb39f36a9bfcb4fb49b8ee12b319471aacc08', max_length=50, verbose_name='device_id'),
preserve_default=False,
),
]
<file_sep>/backend/migrations/0002_user_access_token.py
# Generated by Django 3.2.5 on 2021-07-09 13:57
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('backend', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='user',
name='access_token',
field=models.CharField(default='', max_length=250, verbose_name='oauth_token'),
preserve_default=False,
),
]
<file_sep>/lobby/migrations/0003_lobby_max_members.py
# Generated by Django 3.2.5 on 2021-07-17 21:48
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('lobby', '0002_auto_20210717_1914'),
]
operations = [
migrations.AddField(
model_name='lobby',
name='max_members',
field=models.PositiveIntegerField(default=5, verbose_name='max_members'),
preserve_default=False,
),
]
<file_sep>/lobby/migrations/0009_alter_lobby_id.py
# Generated by Django 3.2.5 on 2021-08-06 10:05
from django.db import migrations, models
import shortuuid.main
class Migration(migrations.Migration):
dependencies = [
('lobby', '0008_alter_lobby_id'),
]
operations = [
migrations.AlterField(
model_name='lobby',
name='id',
field=models.UUIDField(default=shortuuid.main.ShortUUID.uuid, primary_key=True, serialize=False),
),
]
<file_sep>/backend/forms.py
from django import forms
from backend.fields import LinkField
class AddTrackForm(forms.Form):
link = LinkField(required=True, label="Track link:",help_text="Input link on track")
<file_sep>/lobby/migrations/0010_alter_lobby_id.py
# Generated by Django 3.2.5 on 2021-08-06 10:17
from django.db import migrations
import shortuuid.main
import shortuuidfield.fields
class Migration(migrations.Migration):
dependencies = [
('lobby', '0009_alter_lobby_id'),
]
operations = [
migrations.AlterField(
model_name='lobby',
name='id',
field=shortuuidfield.fields.ShortUUIDField(blank=True, default=shortuuid.main.ShortUUID.uuid, editable=False, max_length=22, primary_key=True, serialize=False),
),
]
<file_sep>/backend/utils.py
''' Instruments that i use more than once '''
import re
def track_name_parts(track: dict) -> tuple:
''' makes a good string - song title
track - response of SpotifyApi.get_track() or SpotifyApi.get_user_playback()'''
if 'item' in track.keys():
name = ''
for artist in track['item']['artists']:
name += artist['name'] + ', '
return (name[:-2], track['item']['name'])
elif track:
name = ''
for artist in track['artists']:
name += artist['name'] + ', '
return name[:-2], track['name']
else:
return 'Nothing', None
def track_to_string(track: tuple):
return track[0] + '-' + track[1]
def clear_track(link: str) -> str:
''' Returns id of track from link '''
pattern = r'(https:\/\/open\.spotify\.com\/track\/)([0-9a-zA-Z]*)(\?si=[0-9a-z]*)?'
result = re.search(pattern, link)
if not result:
raise ValueError
return result.group(2)
def _make_devices_list(data) -> dict:
""" Makes pretty device list """
if "devices" not in data.keys():
devices_list = ({'name': "Nothing", 'is_active': 0},)
else:
devices_list = data['devices']
for i in devices_list:
i['emoji'] = '⏩' if i['is_active'] else '⏹'
return devices_list<file_sep>/backend/urls.py
from django.urls import path
from . import views
urlpatterns = [
# path('login/', views.user_login, name='login'),
path('login/', views.user_login, name = 'login'),
path('logout/', views.user_logout, name= 'logout'),
path('', views.dashboard, name='dashboard'),
path('devices', views.devices, name='devices'),
path('ajax/add_queue', views.post_queue, name="post_queue"),
path('authentication_error', views.authentication_error, name="authentication_error"),
]<file_sep>/backend/static/js/websockets.js
import * as services from './services.js'
var functions = {"ban": services.ban,
"add_user": services.add_user,
"add_track": services.add_track,
"remove_members": services.remove_members,
"unban": services.unban}
var loc = window.location
var wsStart = 'ws://';
if (loc.protocol == 'https:'){
wsStart = 'wss://'
}
var endpoint = wsStart + window.location.host + window.location.pathname;
var socket = new WebSocket(endpoint);
socket.onmessage = function(e){
var data = JSON.parse(e.data)
console.log(data);
if (data['event']){
functions[data['event']](data);
}
}
$(document).ready(function () {
$('#ban_form').submit(function () {
$.ajax({
data: $(this).serialize(),
type: $(this).attr('method'),
dataType: 'json',
url: "/lobby/ajax/ban_user",
success: function(){return false},
error: function (response) {
alert(response['errors']);
}
});
return false;
});
$('#add_track').submit(function () {
$.ajax({
data: $(this).serialize(),
type: $(this).attr('method'),
url: "/lobby/ajax/add_lobby_track",
success: function(response){return false;},
error: function (response) {
alert(response['errors']);
}
});
return false;
});
$('#remove_members').submit(function () {
$.ajax({
data: $(this).serialize(),
type: $(this).attr('method'),
dataType: 'json',
url: "/lobby/ajax/remove_members",
success: function (response) {return false;},
error: function (response) {
alert(response['errors']);
}
});
return false;
});
$('#unban').submit(function () {
$.ajax({
data: $(this).serialize(),
type: $(this).attr('method'),
dataType: 'json',
url: "/lobby/ajax/unban_users",
success: function(){return false;},
error: function (response) {
alert(response['errors']);
}
});
return false;
});
});<file_sep>/backend/SpotifyAPI/tracks.py
import re
from . import api
class Track:
''' Track class from Spotify.
Params:
- oauth - oauth token of user (requiered)
- link - link to the track. if not transmitted, the currently playing track is used.
'''
link: str
id: str
image: str
oauth: str
def __init__(self, oauth: str, link: str = None):
self.oauth = oauth
if link:
self.link = link
self.id = self._clear_link(link)
self._data = api.get_track(self.id, oauth)
else:
self._data = api.get_user_playback(oauth)
self.title, self.artists = self._get_name_parts(self._data)
if (self.title and self.artists):
self.name = ', '.join(self.artists) + ' - ' + self.title
else:
self.name = ''
if self._data:
try:
self.image = self._data['item']['album']['images'][0]['url']
except KeyError:
self.image = self._data['album']['images'][0]['url']
print(self.name)
def to_queue(self):
print(self.id)
api.add_queue(self.id, self.oauth)
def show_artists(self):
return ', '.join(self.artists)
def _clear_link(self, link) -> str:
''' Returns id of track from link '''
pattern = r'(https:\/\/open\.spotify\.com\/track\/)([0-9a-zA-Z]*)(\?si=[0-9a-z]*)?'
result = re.search(pattern, link)
if not result:
raise ValueError
return result.group(2)
def _get_name_parts(self, track: dict) -> tuple:
''' makes a good string - song title
track - response of SpotifyApi.get_track() or SpotifyApi.get_user_playback()'''
if track:
if 'item' in track.keys():
artists = []
for artist in track['item']['artists']:
artists.append(artist['name'])
return track['item']['name'], artists
else:
artists = []
for artist in track['artists']:
artists.append(artist['name'])
return track['name'], artists
else:
return '', []
def __str__(self):
return self.name<file_sep>/backend/migrations/0012_alter_user_lobby_in.py
# Generated by Django 3.2.5 on 2021-07-19 13:41
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('lobby', '0003_lobby_max_members'),
('backend', '0011_auto_20210716_1833'),
]
operations = [
migrations.AlterField(
model_name='user',
name='lobby_in',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='lobby.lobby'),
),
]
<file_sep>/spartify/settings.py
"""
Django settings for spartify project.
Generated by 'django-admin startproject' using Django 2.2.12.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/ref/settings/
"""
import os
from dotenv import load_dotenv
load_dotenv()
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = os.environ.get("SECRET_KEY")
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = int(os.environ.get("DEBUG", default=1))
ALLOWED_HOSTS = os.environ.get("DJANGO_ALLOWED_HOSTS",'').split(" ") + ['*', '192.168.43.72', '192.168.0.53', '0.0.0.0']
AUTHENTICATION_BACKENDS = (
'django.contrib.auth.backends.ModelBackend',
'social_core.backends.spotify.SpotifyOAuth2',
)
AUTH_USER_MODEL = 'backend.User'
SOCIAL_AUTH_USER_MODEL = 'backend.User'
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'channels',
'social_django',
'backend',
'lobby'
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
# 'backend.middlewares.ApiMiddleware',
]
ROOT_URLCONF = 'spartify.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'spartify.wsgi.application'
ASGI_APPLICATION = 'spartify.routing.application'
# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases
DATABASES = {
'default': {
"ENGINE": os.environ.get("SQL_ENGINE", "django.db.backends.sqlite3"),
"NAME": os.environ.get("SQL_DATABASE", os.path.join(BASE_DIR, "db.sqlite3")),
"USER": os.environ.get("SQL_USER", "user"),
"PASSWORD": os.environ.get("SQL_PASSWORD", "<PASSWORD>"),
"HOST": os.environ.get("SQL_HOST", "localhost"),
"PORT": os.environ.get("SQL_PORT", "5432"),
}
}
# Password validation
# https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/2.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.2/howto/static-files/
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
STATIC_URL = 'staticfiles/'
STATIC_ROOT = os.path.join(BASE_DIR, STATIC_URL)
SOCIAL_AUTH_SPOTIFY_KEY = os.environ['SOCIAL_AUTH_SPOTIFY_KEY']
SOCIAL_AUTH_SPOTIFY_SECRET = os.environ['SOCIAL_AUTH_SPOTIFY_SECRET']
SOCIAL_AUTH_URL_NAMESPACE = 'social'
SOCIAL_AUTH_SPOTIFY_SCOPE = ['user-read-email','user-read-private', 'user-read-playback-state', 'user-modify-playback-state']
# SOCIAL_AUTH_LOGIN_REDIRECT_URL = 'http://{}/complete/spotify/' % os.getenv('HOST')
LOGIN_REDIRECT_URL = 'dashboard'
LOGIN_URL = 'login'
DEFAULT_AUTO_FIELD='django.db.models.AutoField'
SOCIAL_AUTH_PIPELINE = (
'social_core.pipeline.social_auth.social_details',
'social_core.pipeline.social_auth.social_uid',
'social_core.pipeline.social_auth.auth_allowed',
'social_core.pipeline.social_auth.social_user',
'social_core.pipeline.user.get_username',
'social_core.pipeline.user.create_user',
'social_core.pipeline.social_auth.associate_user',
'social_core.pipeline.social_auth.load_extra_data',
'social_core.pipeline.user.user_details',
'backend.pipeline.save_access_token', #save token on login,
)
QUEUE_SESSION_ID = 'queue'
SESSION_EXPIRE_AT_BROWSER_CLOSE = 15
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'api_formatter': {
'format': '{username} -- {endpoint} -- {status_code:d}: {message}',
'style': '{',
},
'lobby_formatter': {
'format': '{id}--{username}: {message} -- {asctime}',
'style': '{',
},
},
'handlers': {
'api_errors': {
'class': 'logging.FileHandler',
'filename': 'logs/api_errors.log',
'formatter': 'api_formatter',
'level': 'ERROR',
},
},
'loggers':{
'backend': {
'handlers': ['api_errors'],
},
},
}
REDIS_HOST = os.environ.get("REDIS_HOST", '127.0.0.1')
REDIS_PORT = 6379
REDIS_DB = 0
CHANNEL_LAYERS = {
'default': {
'BACKEND': 'channels_redis.core.RedisChannelLayer',
"CONFIG": {
"hosts": [(REDIS_HOST, REDIS_PORT)],
},
}
}<file_sep>/backend/migrations/0011_auto_20210716_1833.py
# Generated by Django 3.2.5 on 2021-07-16 18:33
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('lobby', '0001_initial'),
('backend', '0010_alter_lobby_history'),
]
operations = [
migrations.AlterField(
model_name='user',
name='lobby_in',
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='lobby.lobby'),
),
migrations.DeleteModel(
name='Lobby',
),
]
<file_sep>/lobby/queue.py
from django.conf import settings
from datetime import datetime
class Queue:
count = 0
def __init__(self, request):
self.session = request.session
queue = self.session.get(settings.QUEUE_SESSION_ID)
if not queue:
queue = self.session[settings.QUEUE_SESSION_ID] = {'names': [], 'times': [], 'users': []}
self.queue = queue
def add(self, name, user):
self.count += 1
self.queue['names'] = [name] + self.queue['names']
self.queue['times'] = [datetime.now().strftime('%H:%M')] + self.queue['times']
self.queue['users'] = [user] + self.queue['users']
self.save()
def pop(self) -> str:
self.count -= 1
link = self.queue['names'][0]
del self.queue['names'][0]
self.save()
return link
def get_names(self) -> list:
return self.queue['names']
def get_times(self) -> list:
return self.queue['times']
def get_users(self) -> list:
return self.queue['users']
def get_elem(self, id) -> str:
return self.queue['names'][id]
def save(self):
self.session.modified = True
def clear(self):
self.queue['names'] = []
self.queue['times'] = []
self.queue['users'] = []
self.save()
def remove(self, id):
del self.queue['names'][id]
self.save()
def __len__(self) -> int:
return self.count
def __getitem__(self, key: int) -> tuple:
return ()<file_sep>/backend/migrations/0009_alter_lobby_history.py
# Generated by Django 3.2.5 on 2021-07-15 11:02
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('backend', '0008_alter_lobby_history'),
]
operations = [
migrations.AlterField(
model_name='lobby',
name='history',
field=models.JSONField(default=list, null=True),
),
]
<file_sep>/Dockerfile
FROM python:3.8.10-slim-buster
ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONUNBUFFERED 1
ENV APP_HOME=/usr/src/app
RUN mkdir $APP_HOME
RUN mkdir $APP_HOME/staticfiles
WORKDIR $APP_HOME
RUN pip install --upgrade pip
COPY ./requirements.txt .
RUN pip install -r requirements.txt
COPY . .
<file_sep>/backend/tests.py
from datetime import datetime
from django.test import TestCase
from django.conf import settings
from .models import User
from SpotifyAPI import api
class ApiTestCase(TestCase):
@classmethod
def setUpTestData(cls):
print("setUpTestData: Run once to set up non-modified data for all class methods.\n")
cls.refresh_token = '<KEY>'
def setUp(self):
self.api = api
self.user = User.objects.create(id = 1, refresh_token = '<KEY>',
oauth_token = '<KEY>',
username='petya', expires = datetime.now(tz=None))
self.api.refresh_user(self.user)
def test_refresh_user(self):
try:
self.api.refresh_user(self.user)
except Exception:
assert Exception
def test_perform_auth(self):
'''Method: perform_auth'''
self.assertTrue(self.api.perform_auth())
def test_search(self):
'''Method: search'''
test_ans = self.api.search('Test', search_type='album')
self.assertNotEqual(test_ans, {})
# def test_refresh_token(self):
# '''''Method: refresh_token'''
# test_ans = self.api.refresh_token(self.refresh_token)
# self.assertNotEqual(test_ans, {})
def test_get_track(self):
''' Method: get_track '''
test_ans = self.api.get_track('3XC7Jd6SfrQYKZJ6inyRHK', self.user.oauth_token)
self.assertNotEqual(test_ans, {})
def test_get_me(self):
''' Method: get_me '''
r = self.api.get_me(self.user.oauth_token)
self.assertNotEqual(r, {})<file_sep>/backend/static/js/ban_unban_ws.js
var loc = window.location
var wsStart = 'ws://';
if (loc.protocol == 'https:'){
wsStart = 'wss://'
}
var endpoint = wsStart + window.location.host + window.location.pathname;
var socket = new WebSocket(endpoint);
socket.onmessage = function(e){
console.log("message", e);
socket.send(e.data)
}
socket.onopen = function(e){
console.log("open", e);
}
socket.onerror = function(e){
console.log("error", e);
}
socket.onclose = function(e){
console.log("closed", e);
} | 0ff653fd17332b9bf4af7d7bf1db8cdd80fc097b | [
"HTML",
"JavaScript",
"Markdown",
"Python",
"Text",
"Dockerfile"
] | 59 | Text | cl1ckname/Spartify | 3c45236e3f8803af9d01ac638e3d10a834ab7b7d | ee470d0351362509aec050b3e7c6fa41370e3391 |
refs/heads/main | <repo_name>Solar-2020/Interview-Backend<file_sep>/cmd/handlers/router.go
package handlers
import (
httputils "github.com/Solar-2020/GoUtils/http"
interviewHandler "github.com/Solar-2020/Interview-Backend/cmd/handlers/interview"
"github.com/buaazp/fasthttprouter"
)
func NewFastHttpRouter(interview interviewHandler.Handler, middleware Middleware) *fasthttprouter.Router {
router := fasthttprouter.New()
router.PanicHandler = httputils.PanicHandler
router.Handle("GET", "/health", middleware.Log(httputils.HealthCheckHandler))
router.Handle("POST", "/api/interview/result/:interviewID", middleware.Log(middleware.ExternalAuth(interview.SetAnswer)))
router.Handle("POST", "/api/interview/create", middleware.Log(middleware.InternalAuth(interview.Create)))
router.Handle("POST", "/api/interview/remove", middleware.Log(middleware.InternalAuth(interview.Remove)))
router.Handle("POST", "/api/interview/list", middleware.Log(middleware.InternalAuth(interview.GetUniversal)))
//NOT USED
//router.Handle("GET", "/api/interview/result/:interviewID", middleware.Log(middleware.ExternalAuth(interview.GetResult)))
// router.Handle("POST", "/api/interview", middleware.Log(middleware.InternalAuth(interview.Get)))
return router
}
<file_sep>/cmd/handlers/interview/handler.go
package interviewHandler
import (
http "github.com/Solar-2020/GoUtils/http"
"github.com/Solar-2020/Interview-Backend/internal/services/interview"
"github.com/valyala/fasthttp"
)
type Handler interface {
Create(ctx *fasthttp.RequestCtx)
Get(ctx *fasthttp.RequestCtx)
GetUniversal(ctx *fasthttp.RequestCtx)
Remove(ctx *fasthttp.RequestCtx)
GetResult(ctx *fasthttp.RequestCtx)
SetAnswer(ctx *fasthttp.RequestCtx)
}
type handler struct {
interviewService interview.Service
interviewTransport interviewTransport
errorWorker errorWorker
}
func NewHandler(interviewService interview.Service, interviewTransport interviewTransport, errorWorker errorWorker) Handler {
return &handler{
interviewService: interviewService,
interviewTransport: interviewTransport,
errorWorker: errorWorker,
}
}
func (h *handler) Create(ctx *fasthttp.RequestCtx) {
poll, err := h.interviewTransport.CreateDecode(ctx)
if err != nil {
h.handleError(err, ctx)
return
}
pollReturn, err := h.interviewService.Create(poll)
if err != nil {
h.handleError(err, ctx)
return
}
err = h.interviewTransport.CreateEncode(pollReturn, ctx)
if err != nil {
h.handleError(err, ctx)
return
}
}
func (h *handler) Get(ctx *fasthttp.RequestCtx) {
list, err := h.interviewTransport.GetDecode(ctx)
if err != nil {
h.handleError(err, ctx)
return
}
listReturn, err := h.interviewService.Get(list)
if err != nil {
h.handleError(err, ctx)
return
}
err = h.interviewTransport.GetEncode(listReturn, ctx)
if err != nil {
h.handleError(err, ctx)
return
}
}
func (h *handler) Remove(ctx *fasthttp.RequestCtx) {
list, err := h.interviewTransport.RemoveDecode(ctx)
if err != nil {
h.handleError(err, ctx)
return
}
listReturn, err := h.interviewService.Remove(list)
if err != nil {
h.handleError(err, ctx)
return
}
err = http.EncodeDefault(&listReturn, ctx)
if err != nil {
h.handleError(err, ctx)
return
}
}
func (h *handler) GetResult(ctx *fasthttp.RequestCtx) {
interviewID, userID, err := h.interviewTransport.GetResultDecode(ctx)
if err != nil {
h.handleError(err, ctx)
return
}
interviewResult, err := h.interviewService.GetResult(interviewID, userID)
if err != nil {
h.handleError(err, ctx)
return
}
err = h.interviewTransport.GetResultEncode(interviewResult, ctx)
if err != nil {
h.handleError(err, ctx)
return
}
}
func (h *handler) SetAnswer(ctx *fasthttp.RequestCtx) {
userAnswers, err := h.interviewTransport.SetAnswerDecode(ctx)
if err != nil {
h.handleError(err, ctx)
return
}
interviewResult, err := h.interviewService.SetAnswers(userAnswers)
if err != nil {
h.handleError(err, ctx)
return
}
err = h.interviewTransport.SetAnswerEncode(interviewResult, ctx)
if err != nil {
h.handleError(err, ctx)
return
}
}
func (h *handler) GetUniversal(ctx *fasthttp.RequestCtx) {
request, err := h.interviewTransport.GetUniversalDecode(ctx)
if err != nil {
h.handleError(err, ctx)
return
}
response, err := h.interviewService.GetUniversal(request)
if err != nil {
h.handleError(err, ctx)
return
}
err = h.interviewTransport.GetUniversalEncode(response, ctx)
if err != nil {
h.handleError(err, ctx)
return
}
}
func (h *handler) handleError(err error, ctx *fasthttp.RequestCtx) {
err = h.errorWorker.ServeJSONError(ctx, err)
if err != nil {
h.errorWorker.ServeFatalError(ctx)
}
return
}<file_sep>/cmd/config/config.go
package config
import "github.com/Solar-2020/GoUtils/common"
var (
Config config
)
type config struct {
common.SharedConfig
InterviewDataBaseConnectionString string `envconfig:"INTERVIEW_DB_CONNECTION_STRING" default:"-"`
ServerSecret string `envconfig:"SERVER_SECRET" default:"Basic secret"`
}
<file_sep>/internal/services/interview/service.go
package interview
import (
"database/sql"
"errors"
"fmt"
"github.com/Solar-2020/Interview-Backend/pkg/api"
"github.com/Solar-2020/Interview-Backend/pkg/models"
)
type Service interface {
Create(request api.CreateRequest) (response api.CreateResponse, err error)
Get(postIds api.GetRequest) (response api.GetResponse, err error)
Remove(interviewIds api.RemoveRequest) (response api.RemoveRequest, err error)
GetResult(interviewID models.InterviewID, userID int) (response models.InterviewResult, err error)
GetUniversal(request api.GetUniversalRequest) (response api.GetUniversalResponse, err error)
SetAnswers(answers models.UserAnswers) (response models.InterviewResult, err error)
}
type service struct {
interviewStorage interviewStorage
answerStorage answerStorage
}
func NewService(interviewStorage interviewStorage, answerStorage answerStorage) Service {
return &service{
interviewStorage: interviewStorage,
answerStorage: answerStorage,
}
}
// POST /models/interview/create
func (s *service) Create(request api.CreateRequest) (response api.CreateResponse, err error) {
err = s.interviewStorage.InsertInterviews(request.Interviews, request.PostID)
if err != nil {
return
}
response = api.CreateResponse{Interviews: request.Interviews}
for i := range request.Interviews {
response.Interviews[i].PostID = request.PostID
}
return
}
// POST /interview
func (s *service) Get(postIds api.GetRequest) (response api.GetResponse, err error) {
resp, err := s.interviewStorage.SelectInterviews(postIds.Ids)
if err != nil {
return
}
response.Interviews = resp
return
}
// POST /interview/remove
func (s *service) Remove(interviewIds api.RemoveRequest) (response api.RemoveRequest, err error) {
ids, err := s.interviewStorage.RemoveInterviews(interviewIds.Ids)
if err == nil {
response.Ids = ids
}
return
}
func (s *service) GetResult(interviewID models.InterviewID, userID int) (response models.InterviewResult, err error) {
response.InterviewFrame, err = s.interviewStorage.SelectInterviewWithStatus(interviewID, userID)
if err != nil {
if err == sql.ErrNoRows {
return response, errors.New("Опрос не найден")
}
return
}
response.Answers, err = s.answerStorage.SelectAnswersResult(interviewID)
if err != nil {
return
}
userAnswers, err := s.answerStorage.SelectUserAnswer(response.ID, userID)
if err != nil {
return
}
for i := range response.Answers {
for _, ans := range userAnswers {
if int(response.Answers[i].ID) == int(ans.ID) {
response.Answers[i].IsMyAnswer = true
}
}
}
return
}
func (s *service) GetUniversal(request api.GetUniversalRequest) (response api.GetUniversalResponse, err error) {
interviews, err := s.interviewStorage.SelectInterviewsWithStatus(request.PostIDs, request.UserID)
if err != nil {
return
}
interviewIDs := make([]models.InterviewID, 0)
for i, _ := range interviews {
interviewIDs = append(interviewIDs, interviews[i].ID)
}
answers, err := s.answerStorage.SelectAnswersResults(interviewIDs)
if err != nil {
return
}
userAnswers, err := s.answerStorage.SelectUserAnswers(interviewIDs, request.UserID)
if err != nil {
return
}
for i, _ := range answers {
for j, _ := range userAnswers {
if int(answers[i].ID) == int(userAnswers[j].ID) {
answers[i].IsMyAnswer = true
}
}
}
for i, _ := range interviews {
for j, _ := range answers {
if interviews[i].ID == answers[j].InterviewID {
interviews[i].Answers = append(interviews[i].Answers, answers[j])
}
}
}
response.Interviews = interviews
return
}
func (s *service) SetAnswers(answers models.UserAnswers) (response models.InterviewResult, err error) {
//TODO CHECK PERMISSION
//TODO CHECK REPEATED VOTE
err = s.answerStorage.InsertUserAnswers(answers)
if err != nil {
fmt.Println(err)
err = fmt.Errorf("cannot set vote")
return
}
response, err = s.GetResult(answers.InterviewID, answers.UserID)
return
}
<file_sep>/pkg/models/models.go
package models
type InterviewID int
type AnswerID int
type VoteID int
type InterviewType int
type InterviewFrame struct {
ID InterviewID `json:"id"`
Text string `json:"text"`
Type InterviewType `json:"type"`
PostID int `json:"postID"`
Status int `json:"status"` //Проголосовал юзер или нет
}
type Interview struct {
InterviewFrame
Answers []Answer `json:"answers"`
}
type Answer struct {
ID AnswerID `json:"id"`
Text string `json:"text"`
InterviewID InterviewID `json:"interviewID"`
}
type InterviewResult struct {
InterviewFrame
Answers []AnswerResult `json:"answers"`
}
type AnswerResult struct {
Answer
AnswerCount int `json:"answerCount"`
IsMyAnswer bool `json:"isMyAnswer"`
}
type UserAnswer struct {
ID VoteID `json:"id"`
InterviewID InterviewID `json:"interviewID" validate:"required"`
}
type UserAnswers struct {
PostID int `json:"postID"`
InterviewID InterviewID `json:"-"`
UserID int `json:"-"`
AnswerIDs []AnswerID `json:"answers"`
}
<file_sep>/internal/storages/answerStorage/storage.go
package answerStorage
import (
"database/sql"
sqlutils "github.com/Solar-2020/GoUtils/sql"
"github.com/Solar-2020/Interview-Backend/pkg/models"
"strconv"
"strings"
)
type Storage interface {
InsertUserAnswers(answers models.UserAnswers) (err error)
SelectAnswersResult(interviewID models.InterviewID) (answers []models.AnswerResult, err error)
SelectAnswersResults(interviewIDs []models.InterviewID) (answers []models.AnswerResult, err error)
SelectUserAnswer(interviewIDs models.InterviewID, userID int) (answers []models.UserAnswer, err error)
SelectUserAnswers(interviewIDs []models.InterviewID, userID int) (answers []models.UserAnswer, err error)
}
type storage struct {
db *sql.DB
}
func NewStorage(db *sql.DB) Storage {
return &storage{
db: db,
}
}
func (s *storage) insertAnswers(tx *sql.Tx, answers []models.Answer, interviewID int) (err error) {
if len(answers) == 0 {
return
}
sqlQueryTemplate := `
INSERT INTO answers(interview_id, text)
VALUES `
if len(answers) == 0 {
return
}
var params []interface{}
sqlQuery := sqlQueryTemplate + sqlutils.CreateInsertQuery(len(answers), 2)
for i, _ := range answers {
params = append(params, interviewID, answers[i].Text)
}
for i := 1; i <= len(answers)*2; i++ {
sqlQuery = strings.Replace(sqlQuery, "?", "$"+strconv.Itoa(i), 1)
}
_, err = tx.Exec(sqlQuery, params...)
return
}
func (s *storage) selectAnswers(interviewIDs []models.InterviewID) (answers []models.Answer, err error) {
const sqlQueryTemplate = `
SELECT a.id, a.text, a.interview_id
FROM answers AS a
WHERE a.interview_id IN `
sqlQuery := sqlQueryTemplate + sqlutils.CreateIN(len(interviewIDs))
var params []interface{}
for i, _ := range interviewIDs {
params = append(params, interviewIDs[i])
}
for i := 1; i <= len(interviewIDs)*1; i++ {
sqlQuery = strings.Replace(sqlQuery, "?", "$"+strconv.Itoa(i), 1)
}
rows, err := s.db.Query(sqlQuery, params...)
if err != nil {
return
}
defer rows.Close()
for rows.Next() {
var tempAnswer models.Answer
err = rows.Scan(&tempAnswer.ID, &tempAnswer.Text, &tempAnswer.InterviewID)
if err != nil {
return
}
answers = append(answers, tempAnswer)
}
return
}
func (s *storage) InsertUserAnswers(answers models.UserAnswers) (err error) {
if len(answers.AnswerIDs) == 0 {
return
}
sqlQueryTemplate := `
INSERT INTO users_answers(interview_id, user_id, answer_id, post_id)
VALUES `
var params []interface{}
sqlQuery := sqlQueryTemplate + sqlutils.CreateInsertQuery(len(answers.AnswerIDs), 4)
for i, _ := range answers.AnswerIDs {
params = append(params, answers.InterviewID, answers.UserID, answers.AnswerIDs[i], answers.PostID)
}
for i := 1; i <= len(answers.AnswerIDs)*4; i++ {
sqlQuery = strings.Replace(sqlQuery, "?", "$"+strconv.Itoa(i), 1)
}
_, err = s.db.Exec(sqlQuery, params...)
return
}
func (s *storage) SelectAnswersResults(interviewIDs []models.InterviewID) (answers []models.AnswerResult, err error) {
if len(interviewIDs) == 0 {
return
}
const sqlQueryTemplate = `
SELECT a.id,
a.text,
a.interview_id,
(SELECT count(*)
FROM users_answers AS ua
WHERE ua.answer_id = a.id)
FROM answers AS a
WHERE a.interview_id IN `
sqlQuery := sqlQueryTemplate + sqlutils.CreateIN(len(interviewIDs))
var params []interface{}
for i, _ := range interviewIDs {
params = append(params, interviewIDs[i])
}
for i := 1; i <= len(interviewIDs)*1; i++ {
sqlQuery = strings.Replace(sqlQuery, "?", "$"+strconv.Itoa(i), 1)
}
rows, err := s.db.Query(sqlQuery, params...)
if err != nil {
return
}
defer rows.Close()
for rows.Next() {
var tempAnswer models.AnswerResult
err = rows.Scan(&tempAnswer.ID, &tempAnswer.Text, &tempAnswer.InterviewID, &tempAnswer.AnswerCount)
if err != nil {
return
}
answers = append(answers, tempAnswer)
}
return
}
func (s *storage) SelectAnswersResult(interviewID models.InterviewID) (answers []models.AnswerResult, err error) {
interviewIDs := make([]models.InterviewID, 1)
interviewIDs = append(interviewIDs, interviewID)
answers, err = s.SelectAnswersResults(interviewIDs)
return
}
func (s *storage) SelectUserAnswers(interviewIDs []models.InterviewID, userID int) (answers []models.UserAnswer, err error) {
if len(interviewIDs) == 0 {
return
}
const sqlQueryTemplate = `
SELECT ua.answer_id,
ua.interview_id
FROM users_answers AS ua
WHERE ua.user_id = $1 AND ua.interview_id IN `
sqlQuery := sqlQueryTemplate + sqlutils.CreateIN(len(interviewIDs))
var params []interface{}
params = append(params, userID)
for i, _ := range interviewIDs {
params = append(params, interviewIDs[i])
}
for i := 2; i <= len(interviewIDs)*1+1; i++ {
sqlQuery = strings.Replace(sqlQuery, "?", "$"+strconv.Itoa(i), 1)
}
rows, err := s.db.Query(sqlQuery, params...)
if err != nil {
return
}
defer rows.Close()
for rows.Next() {
var tempAnswer models.UserAnswer
err = rows.Scan(&tempAnswer.ID, &tempAnswer.InterviewID)
if err != nil {
return
}
answers = append(answers, tempAnswer)
}
return
}
func (s *storage) SelectUserAnswer(interviewID models.InterviewID, userID int) (answers []models.UserAnswer, err error) {
interviewIDs := make([]models.InterviewID, 1)
interviewIDs = append(interviewIDs, interviewID)
answers, err = s.SelectUserAnswers(interviewIDs, userID)
return
}
<file_sep>/internal/services/interview/models.go
package interview
import (
"github.com/Solar-2020/Interview-Backend/pkg/models"
)
type interviewStorage interface {
InsertInterviews(interviews []models.Interview, postID int) (err error)
SelectInterviews(postIDs []int) (interviews []models.Interview, err error)
RemoveInterviews(ids []models.InterviewID) (removed []models.InterviewID, err error)
SelectInterview(interviewID models.InterviewID) (interview models.InterviewFrame, err error)
SelectInterviewWithStatus(interviewID models.InterviewID, userID int) (interview models.InterviewFrame, err error)
SelectInterviewsWithStatus(postIDs []int, userID int) (interviews []models.InterviewResult, err error)
}
type answerStorage interface {
InsertUserAnswers(answers models.UserAnswers) (err error)
SelectAnswersResult(interviewID models.InterviewID) (answers []models.AnswerResult, err error)
SelectAnswersResults(interviewIDs []models.InterviewID) (answers []models.AnswerResult, err error)
SelectUserAnswers(interviewIDs []models.InterviewID, userID int) (answers []models.UserAnswer, err error)
SelectUserAnswer(interviewIDs models.InterviewID, userID int) (answers []models.UserAnswer, err error)
}
<file_sep>/pkg/api/api.go
package api
import (
"encoding/json"
"github.com/Solar-2020/Interview-Backend/pkg/models"
)
// POST /interview/create
type CreateRequest struct {
Interviews []models.Interview `json:"interviews" validate:"required"`
PostID int `json:"postID" validate:"required"`
}
type CreateResponse struct {
Interviews []models.Interview `json:"interviews"`
}
func (r *CreateResponse) Decode(src []byte) (err error) {
err = json.Unmarshal(src, r)
return
}
// POST /interview/list
type GetUniversalRequest struct {
PostIDs []int `json:"postIDs" validate:"required"`
UserID int `json:"userID" validate:"required"`
NotPassedResult bool `json:"notPassedResult"`
}
type GetUniversalResponse struct {
Interviews []models.InterviewResult `json:"interviews"`
}
func (r *GetUniversalResponse) Decode(src []byte) (err error) {
err = json.Unmarshal(src, r)
return
}
// POST /interview
type GetRequest struct {
Ids []int `json:"posts" validate:"required"`
}
type GetResponse struct {
Interviews []models.Interview `json:"interviews"`
}
func (r *GetResponse) Decode(src []byte) (err error) {
err = json.Unmarshal(src, r)
return
}
// POST /interview/remove
type RemoveRequest struct {
Ids []models.InterviewID `json:"ids" validate:"required"`
}
type RemoveResponse struct {
Interviews []models.Interview `json:"interviews"`
}
func (r *RemoveResponse) Decode(src []byte) (err error) {
err = json.Unmarshal(src, r)
return
}
// GET /interview/result/:id
type ResultRequest struct {
Id models.InterviewID `json:"id" validate:"required"`
}
type ResultResponse struct {
models.InterviewResult
}
// POST /interview/result/:id
type SetVoteRequest struct {
models.UserAnswer
}
type SetVoteResponse struct {
models.InterviewResult
}
<file_sep>/go.mod
module github.com/Solar-2020/Interview-Backend
go 1.13
require (
github.com/DATA-DOG/go-sqlmock v1.5.0 // indirect
github.com/Solar-2020/Account-Backend v1.0.1
github.com/Solar-2020/Authorization-Backend v1.0.1
github.com/Solar-2020/GoUtils v1.0.1
// github.com/Solar-2020/GoUtils v0.0.0-20201027194059-562c66fd0229
github.com/buaazp/fasthttprouter v0.1.1
github.com/go-park-mail-ru/2019_2_Next_Level v0.0.0-20191217231202-d92f16810f1e
github.com/go-playground/validator v9.31.0+incompatible
github.com/google/go-cmp v0.5.2 // indirect
github.com/kelseyhightower/envconfig v1.4.0
github.com/lib/pq v1.8.0
github.com/rs/zerolog v1.20.0
github.com/valyala/fasthttp v1.16.0
)
// replace github.com/Solar-2020/SolAr_Backend_2020 => ../SolAr_2020
// replace github.com/Solar-2020/GoUtils => ../GoUtils
// replace github.com/Solar-2020/Account-Backend => ../Account-Backend
<file_sep>/internal/services/interview/transport.go
package interview
import (
"encoding/json"
"errors"
"github.com/Solar-2020/Interview-Backend/pkg/api"
"github.com/Solar-2020/Interview-Backend/pkg/models"
"github.com/go-playground/validator"
"github.com/valyala/fasthttp"
"strconv"
)
type Transport interface {
CreateDecode(ctx *fasthttp.RequestCtx) (request api.CreateRequest, err error)
CreateEncode(response api.CreateResponse, ctx *fasthttp.RequestCtx) (err error)
GetDecode(ctx *fasthttp.RequestCtx) (request api.GetRequest, err error)
GetEncode(response api.GetResponse, ctx *fasthttp.RequestCtx) (err error)
RemoveDecode(ctx *fasthttp.RequestCtx) (request api.RemoveRequest, err error)
//RemoveEncode(response models.RemoveResponse, ctx *fasthttp.RequestCtx) (err error)
GetResultDecode(ctx *fasthttp.RequestCtx) (interviewID models.InterviewID, userID int, err error)
GetResultEncode(response models.InterviewResult, ctx *fasthttp.RequestCtx) (err error)
GetUniversalDecode(ctx *fasthttp.RequestCtx) (request api.GetUniversalRequest, err error)
GetUniversalEncode(response api.GetUniversalResponse, ctx *fasthttp.RequestCtx) (err error)
SetAnswerDecode(ctx *fasthttp.RequestCtx) (request models.UserAnswers, err error)
SetAnswerEncode(response models.InterviewResult, ctx *fasthttp.RequestCtx) (err error)
}
type transport struct {
validator *validator.Validate
}
func NewTransport() Transport {
return &transport{
validator: validator.New(),
}
}
func (t *transport) CreateDecode(ctx *fasthttp.RequestCtx) (request api.CreateRequest, err error) {
err = json.Unmarshal(ctx.Request.Body(), &request)
if err != nil {
return
}
err = t.validator.Struct(request)
return
}
func (t *transport) CreateEncode(response api.CreateResponse, ctx *fasthttp.RequestCtx) (err error) {
body, err := json.Marshal(response)
if err != nil {
return
}
ctx.Response.Header.SetContentType("application/json")
ctx.Response.Header.SetStatusCode(fasthttp.StatusOK)
ctx.SetBody(body)
return
}
func (t *transport) GetDecode(ctx *fasthttp.RequestCtx) (request api.GetRequest, err error) {
err = json.Unmarshal(ctx.Request.Body(), &request)
if err != nil {
return
}
err = t.validator.Struct(request)
return
}
func (t transport) GetEncode(response api.GetResponse, ctx *fasthttp.RequestCtx) (err error) {
body, err := json.Marshal(response)
if err != nil {
ctx.Response.Header.SetStatusCode(fasthttp.StatusInternalServerError)
return
}
ctx.Response.Header.SetContentType("application/json")
ctx.Response.Header.SetStatusCode(fasthttp.StatusOK)
ctx.SetBody(body)
return
}
func (t transport) RemoveDecode(ctx *fasthttp.RequestCtx) (request api.RemoveRequest, err error) {
err = json.Unmarshal(ctx.Request.Body(), &request)
if err != nil {
return
}
err = t.validator.Struct(request)
return
}
func (t transport) GetResultDecode(ctx *fasthttp.RequestCtx) (request models.InterviewID, userID int, err error) {
//userID := ctx.Value("UserID").(int)
userID = ctx.UserValue("userID").(int)
//TODO THINK ABOUT CHECK PERMISSION
interviewIDStr := ctx.UserValue("interviewID").(string)
tmp, err := strconv.Atoi(interviewIDStr)
if err != nil {
return
}
request = models.InterviewID(tmp)
return
}
func (t transport) GetResultEncode(response models.InterviewResult, ctx *fasthttp.RequestCtx) (err error) {
body, err := json.Marshal(response)
if err != nil {
return
}
ctx.Response.Header.SetContentType("application/json")
ctx.Response.Header.SetStatusCode(fasthttp.StatusOK)
ctx.SetBody(body)
return
}
func (t transport) GetUniversalDecode(ctx *fasthttp.RequestCtx) (request api.GetUniversalRequest, err error) {
err = json.Unmarshal(ctx.Request.Body(), &request)
if err != nil {
return
}
err = t.validator.Struct(request)
return
}
func (t transport) GetUniversalEncode(response api.GetUniversalResponse, ctx *fasthttp.RequestCtx) (err error) {
body, err := json.Marshal(response)
if err != nil {
return
}
ctx.Response.Header.SetContentType("application/json")
ctx.Response.Header.SetStatusCode(fasthttp.StatusOK)
ctx.SetBody(body)
return
}
func (t transport) SetAnswerDecode(ctx *fasthttp.RequestCtx) (request models.UserAnswers, err error) {
var userAnswers models.UserAnswers
err = json.Unmarshal(ctx.Request.Body(), &userAnswers)
if err != nil {
return
}
interviewIDStr := ctx.UserValue("interviewID").(string)
interviewID, err := strconv.Atoi(interviewIDStr)
if err != nil {
return
}
userAnswers.InterviewID = models.InterviewID(interviewID)
userID, ok := ctx.UserValue("userID").(int)
if ok {
userAnswers.UserID = userID
request = userAnswers
return
}
return request, errors.New("userID not found")
}
func (t transport) SetAnswerEncode(response models.InterviewResult, ctx *fasthttp.RequestCtx) (err error) {
body, err := json.Marshal(response)
if err != nil {
return
}
ctx.Response.Header.SetContentType("application/json")
ctx.Response.Header.SetStatusCode(fasthttp.StatusOK)
ctx.SetBody(body)
return
}
<file_sep>/cmd/main.go
package main
import (
"database/sql"
asapi "github.com/Solar-2020/Account-Backend/pkg/api"
authapi "github.com/Solar-2020/Authorization-Backend/pkg/api"
"github.com/Solar-2020/GoUtils/context/session"
"github.com/Solar-2020/GoUtils/http/errorWorker"
"github.com/Solar-2020/Interview-Backend/cmd/config"
"github.com/Solar-2020/Interview-Backend/cmd/handlers"
interviewHandler "github.com/Solar-2020/Interview-Backend/cmd/handlers/interview"
"github.com/Solar-2020/Interview-Backend/internal/clients/auth"
"github.com/Solar-2020/Interview-Backend/internal/services/interview"
"github.com/Solar-2020/Interview-Backend/internal/storages/answerStorage"
"github.com/Solar-2020/Interview-Backend/internal/storages/interviewStorage"
"github.com/kelseyhightower/envconfig"
_ "github.com/lib/pq"
"github.com/rs/zerolog"
"github.com/valyala/fasthttp"
"os"
"os/signal"
"syscall"
)
func main() {
log := zerolog.New(zerolog.ConsoleWriter{Out: os.Stdout})
err := envconfig.Process("", &config.Config)
if err != nil {
log.Fatal().Msg(err.Error())
return
}
interviewDB, err := sql.Open("postgres", config.Config.InterviewDataBaseConnectionString)
if err != nil {
log.Fatal().Msg(err.Error())
return
}
interviewDB.SetMaxIdleConns(5)
interviewDB.SetMaxOpenConns(10)
//userDB, err := sql.Open("postgres", cfg.UserDataBaseConnectionString)
//if err != nil {
// log.Fatal().Msg(err.Error())
// return
//}
//userDB.SetMaxIdleConns(5)
//userDB.SetMaxOpenConns(10)
errorWorker := errorWorker.NewErrorWorker()
interviewStorage := interviewStorage.NewStorage(interviewDB)
answerStorage := answerStorage.NewStorage(interviewDB)
interviewService := interview.NewService(interviewStorage, answerStorage)
interviewTransport := interview.NewTransport()
interviewHandler := interviewHandler.NewHandler(interviewService, interviewTransport, errorWorker)
authService := authapi.AuthClient{
Addr: config.Config.AuthServiceAddress,
}
session.RegisterAuthService(&authService)
accountService := asapi.AccountClient{
Addr: config.Config.AccountServiceAddress,
}
session.RegisterAccountService(&accountService)
authClient := auth.NewClient(config.Config.AuthServiceAddress, config.Config.ServerSecret)
middlewares := handlers.NewMiddleware(&log, authClient)
server := fasthttp.Server{
Handler: handlers.NewFastHttpRouter(interviewHandler, middlewares).Handler,
}
go func() {
log.Info().Str("msg", "start server").Str("port", config.Config.Port).Send()
if err := server.ListenAndServe(":" + config.Config.Port); err != nil {
log.Error().Str("msg", "server run failure").Err(err).Send()
os.Exit(1)
}
}()
c := make(chan os.Signal, 1)
signal.Notify(c, syscall.SIGTERM, syscall.SIGINT)
defer func(sig os.Signal) {
log.Info().Str("msg", "received signal, exiting").Str("signal", sig.String()).Send()
if err := server.Shutdown(); err != nil {
log.Error().Str("msg", "server shutdown failure").Err(err).Send()
}
//dbConnection.Shutdown()
log.Info().Str("msg", "goodbye").Send()
}(<-c)
}
<file_sep>/cmd/handlers/interview/models.go
package interviewHandler
import (
"github.com/Solar-2020/Interview-Backend/internal/services/interview"
"github.com/valyala/fasthttp"
)
//type interviewService interface {
// Create(request models.InterviewsRequest) (response models.InterviewsRequest, err error)
//
// Get(interviewIDs []int) (response models.InterviewsRequest, err error)
//
// GetResult(interviewID int) (response models.InterviewResult, err error)
// GetUniversal(interviewIDs []int) (response []models.InterviewResult, err error)
//
// SetAnswers(answers models.UserAnswers) (response models.InterviewResult, err error)
// //GetList(request models.GetPostListRequest) (response []models.Post, err error)
//}
type interviewTransport interview.Transport
//type interviewTransport interface {
// CreateDecode(ctx *fasthttp.RequestCtx) (request []models.Interview, err error)
// CreateEncode(response []models.Interview, ctx *fasthttp.RequestCtx) (err error)
//
// GetDecode(ctx *fasthttp.RequestCtx) (interviewIDs []int, err error)
// GetEncode(response []models.Interview, ctx *fasthttp.RequestCtx) (err error)
//
// GetResultDecode(ctx *fasthttp.RequestCtx) (interviewID int, err error)
// GetResultEncode(response models.InterviewResult, ctx *fasthttp.RequestCtx) (err error)
//
// GetUniversalDecode(ctx *fasthttp.RequestCtx) (interviewIDs []int, err error)
// GetUniversalEncode(response []models.InterviewResult, ctx *fasthttp.RequestCtx) (err error)
//
// SetAnswerDecode(ctx *fasthttp.RequestCtx) (request models.UserAnswers, err error)
// SetAnswerEncode(response models.InterviewResult, ctx *fasthttp.RequestCtx) (err error)
//
// //GetListDecode(ctx *fasthttp.RequestCtx) (request models.GetPostListRequest, err error)
// //GetListEncode(response []models.Post, ctx *fasthttp.RequestCtx) (err error)
//}
type errorWorker interface {
ServeJSONError(ctx *fasthttp.RequestCtx, serveError error) (err error)
ServeFatalError(ctx *fasthttp.RequestCtx)
}
| 35ec082fd493af43135a3df6134d50f32dc0e52c | [
"Go Module",
"Go"
] | 12 | Go | Solar-2020/Interview-Backend | a4bfd211979c23de08b2535bcd32f96228ffa7de | 85c523e68daeb8183e7821cc45643333ffea0280 |
refs/heads/master | <file_sep>#include <iostream>
#include <thread>
#include "client_socket.h"
#include "socket_exception.h"
int main(int argc, const char* argv[])
{
try {
ClientSocket client("127.0.0.1", 30000);
std::string sendBuf;
std::thread receiver(&ClientSocket::receiveHandler, std::ref(client));
while (true) {
std::cout << "Enter string send to server:" << std::endl;
getline(std::cin, sendBuf);
client.send(sendBuf);
}
} catch (SocketException& e) {
std::cout << "Exception was caught:" << e.description() << std::endl;
}
return 0;
}
<file_sep>#ifndef SOCKET_CLASS
#define SOCKET_CLASS
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <unistd.h>
#include <string>
#include <arpa/inet.h>
const int MAX_CONNECT_NUM = 5;
const int MAX_RECV = 500;
class Socket
{
public:
Socket();
virtual ~Socket();
bool create();
bool bind(const int port);
bool listen() const;
bool accept(Socket&) const;
bool connect(const std::string host, const int port);
bool send(Socket&, const std::string&) const;
int recv(Socket&, std::string&) const;
void setNonBlocking(const bool);
bool is_valid() const {return m_sock != -1;}
std::string getAddress();
int getPort();
private:
int m_sock;
struct sockaddr_in m_addr;
};
#endif
<file_sep>#include "server_socket.h"
#include "socket_exception.h"
#include <iostream>
#include <thread>
int main(int argc, const char *argv[])
{
std::cout << "running..." << std::endl;
try {
ServerSocket server(30000);
server.run();
} catch (SocketException& e) {
std::cout << "Exception was caught:" << e.description() << std::endl;
std::cout << "Exiting." << std::endl;
}
return 0;
}
<file_sep>#ifndef CLIENT_SOCKET_CLASS
#define CLIENT_SOCKET_CLASS
#include "socket.h"
class ClientSocket: public Socket
{
public:
ClientSocket(std::string host, int port);
virtual ~ClientSocket(){};
bool send(const std::string&);
int recv(std::string&);
static void receiveHandler(ClientSocket& client);
};
#endif<file_sep>#ifndef SERVER_SOCKET_CLASS
#define SERVER_SOCKET_CLASS
#include "socket.h"
#include <list>
#include <thread>
class ServerSocket : public Socket
{
public:
ServerSocket(const int port);
ServerSocket(){};
virtual ~ServerSocket();
void accept(Socket &);
void run();
private:
bool accept();
void addClient(Socket *);
void deleteClient(Socket *);
void* processMessage(void* arg);
void sendMsgToAllClient(const std::string& message);
std::thread *thread;
static std::list<Socket*> clientSockets;
static bool serviceFlag;
};
#endif<file_sep>#include "server_socket.h"
#include "socket_exception.h"
#include <iostream>
std::list<Socket*> ServerSocket::clientSockets;
bool ServerSocket::serviceFlag = true;
ServerSocket::ServerSocket(const int port) {
if (!Socket::create()) {
throw SocketException("Could not create server socket.");
}
if (!Socket::bind(port)) {
throw SocketException("Could not bind to port.");
}
if (!Socket::listen()) {
throw SocketException("Could not listen to socket.");
}
}
ServerSocket::~ServerSocket() {
std::list<Socket*>::iterator iter;
for (iter=clientSockets.begin(); iter!=clientSockets.end(); iter++) {
delete (*iter);
}
}
void ServerSocket::accept(Socket &sock) {
if (!Socket::accept(sock)) {
throw SocketException("Could not accept socket.");
}
}
void ServerSocket::run() {
while(serviceFlag) {
if (clientSockets.size() >= static_cast<unsigned int>(MAX_CONNECT_NUM)) {
serviceFlag = false;
} else {
serviceFlag = accept();
}
sleep(1);
}
}
bool ServerSocket::accept() {
Socket* clientSocket = new Socket;
accept(*clientSocket);
addClient(clientSocket);
this->thread = new std::thread(&ServerSocket::processMessage, this, static_cast<void*>(clientSocket));
return true;
}
void ServerSocket::addClient(Socket *socket) {
clientSockets.push_back(socket);
std::cout << "Now " << clientSockets.size() << " Users." << std::endl;
}
void ServerSocket::deleteClient(Socket *socket) {
std::list<Socket*>::iterator iter;
for(iter=clientSockets.begin(); iter!=clientSockets.end(); iter++) {
if ((*iter)->getAddress() == socket->getAddress() &&
(*iter)->getPort() == socket->getPort()) {
delete (*iter);
clientSockets.erase(iter);
std::cout << "Now " << clientSockets.size() << "Users." << std::endl;
break;
}
}
}
void *ServerSocket::processMessage(void *arg) {
std::string message;
Socket* clientSocket = static_cast<Socket*>(arg);
send(*clientSocket, "Welcome.");
while(serviceFlag) {
recv(*clientSocket, message);
if (message == "exit") {
send(*clientSocket, "user exit.");
deleteClient(clientSocket);
break;
} else {
sendMsgToAllClient(message);
}
sleep(1);
}
return NULL;
}
void ServerSocket::sendMsgToAllClient(const std::string &message) {
std::list<Socket*>::iterator iter;
for (iter=clientSockets.begin(); iter!=clientSockets.end(); iter++) {
send(*(*iter), message);
}
}
<file_sep>#include <iostream>
#include <fcntl.h>
#include <cstring>
#include "socket.h"
#ifndef SO_NOSIGPIPE
#define SO_NOSIGPIPE MSG_NOSIGNAL
#endif
Socket::Socket(): m_sock(-1) {
memset(&m_addr, 0, sizeof(m_addr));
}
Socket::~Socket() {
if (is_valid()) {
::close(m_sock);
}
}
bool Socket::create() {
m_sock = socket(AF_INET, SOCK_STREAM, 0);
if (!is_valid()) {
return false;
}
int on = 1;
return setsockopt(m_sock, SOL_SOCKET, SO_REUSEADDR, (const char*)&on, sizeof(on)) != -1;
}
bool Socket::bind(const int port) {
if (!is_valid()) {
return false;
}
m_addr.sin_family = AF_INET;
m_addr.sin_addr.s_addr = INADDR_ANY;
m_addr.sin_port = htons(port);
int bind_return = ::bind(m_sock, (struct sockaddr*)&m_addr, sizeof(m_addr));
return bind_return != -1;
}
bool Socket::listen() const {
if (!is_valid()) {
return false;
}
int listen_return = ::listen(m_sock, MAX_CONNECT_NUM);
return listen_return != -1;
}
bool Socket::accept(Socket &new_socket) const {
int addr_length = sizeof(m_addr);
new_socket.m_sock = ::accept(m_sock, (struct sockaddr *)&m_addr, (socklen_t *)&addr_length);
return new_socket.m_sock > 0;
}
bool Socket::send(Socket& socket, const std::string& message) const {
ssize_t status = ::send(socket.m_sock, message.c_str(), message.size(), SO_NOSIGPIPE);
return status != -1;
}
int Socket::recv(Socket& socket, std::string& message) const {
char buf[MAX_RECV + 1];
message.clear();
memset(buf, 0, MAX_RECV + 1);
ssize_t status = ::recv(socket.m_sock, buf, MAX_RECV, 0);
if (status == -1) {
std::cout << "status == -1 errno == " << errno << " in Socket::recv" << std::endl;
return 0;
} else if (status == 0) {
return 0;
} else {
message = buf;
return (int)status;
}
}
bool Socket::connect(const std::string host, const int port) {
if (!is_valid()) {
return false;
}
m_addr.sin_family = AF_INET;
m_addr.sin_addr.s_addr = inet_addr(host.c_str());
m_addr.sin_port = htons(port);
if (errno == EAFNOSUPPORT) {
return false;
}
int status = ::connect(m_sock, (sockaddr *)&m_addr, sizeof(m_addr));
return status == 0;
}
void Socket::setNonBlocking(const bool b)
{
int opts;
opts = fcntl(m_sock, F_GETFL);
if (opts < 0) {
return;
}
if (b) {
opts = (opts | O_NONBLOCK);
} else {
opts = (opts & ~O_NONBLOCK);
}
fcntl(m_sock, F_SETFL, opts);
}
std::string Socket::getAddress() {
return inet_ntoa(m_addr.sin_addr);
}
int Socket::getPort() {
return ntohs(m_addr.sin_port);
}
<file_sep>#include <iostream>
#include "client_socket.h"
#include "socket_exception.h"
ClientSocket::ClientSocket(std::string host, int port) {
if (!Socket::create()) {
throw SocketException("Could not create client socket.");
}
if (!Socket::connect(host, port)) {
throw SocketException("Could not bind to port.");
}
}
void ClientSocket::receiveHandler(ClientSocket &client) {
std::string reply;
while (client.recv(reply) > 0) {
std::cout << "receive server response:" << std::endl;
std::cout << reply << std::endl;
}
}
bool ClientSocket::send(const std::string &message) {
return Socket::send(static_cast<Socket&>(*this), message);
}
int ClientSocket::recv(std::string &message) {
return Socket::recv(static_cast<Socket&>(*this), message);
}
<file_sep>cmake_minimum_required(VERSION 2.8.4)
project(cpptest)
set(CMAKE_CXX_COMPILER "clang++")
set(CMAKE_C_COMPILER "clang")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")
set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib)
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib)
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin")
set(SERVER_SOURCE_FILES server.cc socket.cc server_socket.cc socket_exception.h)
set(CLIENT_SOURCE_FILES client.cc socket.cc socket_exception.h client_socket.cc)
add_executable(server ${SERVER_SOURCE_FILES})
add_executable(client ${CLIENT_SOURCE_FILES})
| 4d78c5fec36e46388a2c4c46f9f8c9447356b037 | [
"CMake",
"C++"
] | 9 | C++ | CandySunPlus/simple_socket | 3f0882a7a14fe94334f6d74be49709f4f3322bcd | 30988e7f1b76acc27c387dac570b9b2d544235ce |
refs/heads/master | <repo_name>mattkerkstra/mattkerkstra.github.io<file_sep>/apps/code_snippets/scripts/custom_anchors.js
"use strict"
b4w.register("custom_anchors_main", function(exports, require) {
var m_anchors = require("anchors");
var m_app = require("app");
var m_cfg = require("config");
var m_data = require("data");
var m_scs = require("scenes");
exports.init = function() {
m_app.init({
canvas_container_id: "canvas_cont",
callback: init_cb,
physics_enabled: false,
show_fps: true,
alpha: false,
autoresize: true
});
}
function init_cb(canvas_elem, success) {
if (!success) {
console.log("b4w init failure");
return;
}
// "Custom Element" anchor requires predefined HTML element
// which need to be created before data load
var torus_text = document.createElement("span");
torus_text.id = "torus_anchor";
torus_text.style.position = "absolute";
torus_text.style.backgroundColor = "blue";
torus_text.style.color = "white";
torus_text.style.padding = "5px";
torus_text.style.visibility = "hidden";
torus_text.innerHTML = "Torus (Custom Element)";
document.body.appendChild(torus_text);
m_data.load(m_cfg.get_std_assets_path() +
"code_snippets/custom_anchors/custom_anchors.json", load_cb);
}
function load_cb(data_id) {
m_app.enable_controls();
m_app.enable_camera_controls();
// "Generic" anchor may be created (or replaced) anytime
var cyl_text = document.createElement("span");
cyl_text.id = "cyl_anchor";
cyl_text.style.position = "absolute";
cyl_text.style.backgroundColor = "yellow";
cyl_text.style.color = "black";
cyl_text.style.padding = "5px";
cyl_text.innerHTML = "Cylinder (Generic)";
document.body.appendChild(cyl_text);
var cyl_anchor = m_scs.get_object_by_name("CylAnchor");
m_anchors.attach_move_cb(cyl_anchor, function(x, y, appearance, obj, elem) {
var anchor_elem = document.getElementById("cyl_anchor");
anchor_elem.style.left = x + "px";
anchor_elem.style.top = y + "px";
if (appearance == "visible")
anchor_elem.style.visibility = "visible";
else
anchor_elem.style.visibility = "hidden";
});
}
});
<file_sep>/apps/code_snippets/scripts/morphing.js
"use strict"
b4w.register("morphing", function(exports, require) {
var m_app = require("app");
var m_data = require("data");
var m_scenes = require("scenes");
var m_geom = require("geometry");
var m_cfg = require("config");
var APP_ASSETS_PATH = m_cfg.get_std_assets_path() + "code_snippets/morphing/";
exports.init = function() {
m_app.init({
canvas_container_id: "canvas_cont",
callback: init_cb,
show_fps: true,
autoresize: true
});
}
function init_cb(canvas_elem, success) {
if (!success) {
console.log("b4w init failure");
return;
}
m_app.enable_controls();
load();
}
function load() {
m_data.load(APP_ASSETS_PATH + "morphing.json", load_cb);
}
function load_cb(data_id) {
var main_interface_container = document.createElement("div");
main_interface_container.className = "main_sliders_container";
main_interface_container.setAttribute("id", "main_sliders_container");
document.body.appendChild(main_interface_container);
m_app.enable_camera_controls();
var obj = m_scenes.get_object_by_name("body");
if (obj)
create_interface(obj);
}
function create_interface(obj) {
if (!m_geom.check_shape_keys(obj))
return;
create_dual_slider(obj, "fatten", "shrink", "Weight");
var shape_keys_names = m_geom.get_shape_keys_names(obj);
for (var i = 0; i < shape_keys_names.length; i++) {
if (shape_keys_names[i] == "fatten" || shape_keys_names[i] == "shrink")
continue;
create_slider(obj, shape_keys_names[i], shape_keys_names[i]);
}
}
function create_slider(obj, key_name, slider_name) {
var slider = init_slider(slider_name);
var value_label = document.getElementById(slider_name);
var value = m_geom.get_shape_key_value(obj, key_name);
slider.min = 0;
slider.max = 1;
slider.step = 0.02;
slider.value = value;
value_label.textContent = slider.value;
function slider_changed(e) {
m_geom.set_shape_key_value(obj, key_name, slider.value);
value_label.textContent = slider.value;
}
if (is_ie11())
slider.onchange = slider_changed;
else
slider.oninput = slider_changed;
}
function create_dual_slider(obj, key_name_1, key_name_2, slider_name) {
var slider = init_slider(slider_name);
var value_label = document.getElementById(slider_name);
var value = m_geom.get_shape_key_value(obj, key_name_1)
- m_geom.get_shape_key_value(obj, key_name_2)
slider.min = -1;
slider.max = 1;
slider.step = 0.02;
slider.value = value;
value_label.textContent = Math.floor(slider.value*100)/100;
function slider_changed(e) {
if (slider.value < 0) {
var key_name = key_name_2;
var reset_name = key_name_1;
var value = -slider.value;
} else {
var key_name = key_name_1;
var reset_name = key_name_2;
var value = slider.value;
}
m_geom.set_shape_key_value(obj, key_name, value);
if (m_geom.get_shape_key_value(obj, reset_name))
m_geom.set_shape_key_value(obj, reset_name, 0);
value_label.textContent = slider.value;
}
if (is_ie11())
slider.onchange = slider_changed;
else
slider.oninput = slider_changed;
}
function init_slider(name) {
var container = document.createElement("div");
container.className = "slider_container";
var name_label = document.createElement("label");
name_label.className = "text_label";
name_label.textContent = name;
var slider = document.createElement("input");
slider.className = "input_slider";
slider.setAttribute("type", "range");
var value_label = document.createElement("label");
value_label.className = "value_label";
value_label.setAttribute("id", name);
container.appendChild(name_label);
container.appendChild(slider);
container.appendChild(value_label);
var border = document.createElement("div");
border.className = "border";
border.appendChild(container);
var main_slider_container = document.getElementById("main_sliders_container");
main_slider_container.appendChild(border);
return slider;
}
function is_ie11() {
return !(window.ActiveXObject) && "ActiveXObject" in window;
}
});
<file_sep>/apps/code_snippets/scripts/dynamic_geometry.js
"use strict"
b4w.register("dynamic_geometry", function(exports, require) {
var m_app = require("app");
var m_data = require("data");
var m_geom = require("geometry");
var m_scs = require("scenes");
var m_obj = require("objects");
var m_trans = require("transform");
var m_cfg = require("config");
var APP_ASSETS_PATH = m_cfg.get_std_assets_path() + "code_snippets/dynamic_geometry";
exports.init = function() {
m_app.init({
canvas_container_id: "canvas_cont",
callback: init_cb,
physics_enabled: false,
show_fps: true,
alpha: false,
autoresize: true
});
}
function init_cb(canvas_elem, success) {
if (!success) {
console.log("b4w init failure");
return;
}
m_app.enable_controls();
load();
}
function load() {
m_data.load(APP_ASSETS_PATH + "/example.json", load_cb);
}
function load_cb(data_id) {
m_app.enable_camera_controls();
make_some_copies();
remove_some_copies();
geometry_change();
}
function make_some_copies() {
var src_obj = m_scs.get_object_by_name("Plane");
var deep_copy = m_obj.copy(src_obj, "deep_copy", true);
var deep_copy2 = m_obj.copy(src_obj, "deep_copy2", true);
var shallow_copy = m_obj.copy(src_obj, "shallow_copy", false);
var shallow_copy2 = m_obj.copy(src_obj, "shallow_copy2", false);
m_scs.append_object(deep_copy);
m_scs.append_object(deep_copy2);
m_scs.append_object(shallow_copy);
m_scs.append_object(shallow_copy2);
m_trans.set_translation(deep_copy, -2, 0, 2);
m_trans.set_translation(deep_copy2, 2, 0, 2);
m_trans.set_translation(shallow_copy, 2, 0, -2);
m_trans.set_translation(shallow_copy2, -2, 0, -2);
}
function remove_some_copies() {
var deep_copy = m_scs.get_object_by_name("deep_copy2");
var shallow_copy = m_scs.get_object_by_name("shallow_copy2");
m_scs.remove_object(deep_copy);
m_scs.remove_object(shallow_copy);
}
function geometry_change(indices, positions) {
var plane_blue = m_scs.get_object_by_name("Plane");
var plane_red = m_scs.get_object_by_name("Plane.002");
var indices = new Uint16Array([0,1,2,3,4,5]);
var positions_blue = new Float32Array([0,1,0, -1,0,1, 1,0,-1, 1,0,-1, -1,0,1, 1,0,1]);
var positions_red = new Float32Array([-9,1,-9, -10,0,-8, -8,0,-10, -8,0,-10, -10,0,-8, -8,0,-8]);
m_geom.override_geometry(plane_blue, "Material", indices, positions_blue, false);
m_geom.override_geometry(plane_red, "Material.002", indices, positions_red, false);
// update object's boundings after mesh geometry changing
m_obj.update_boundings(plane_blue);
m_obj.update_boundings(plane_red);
}
});
<file_sep>/custom.js
/* -----------------------------------------------------------------------
Custom Javascript - Thurman Law Firm
Author: <NAME>
URL: www.seankstewart.com
----------------------------------------------------------------------- */
stLight.options({publisher:'d1be406e-430f-42f7-a36d-55786a61c6bf', onhover:false});
//jQuery.noConflict();
jQuery(document).ready(function($) {
$('#mainnav li a').click(function() {
if ($(this)[0].href == "") {
$(this).next('ul').slideToggle('slow');
}
});
if ($('#mainnav li.current-menu-ancestor').length > 0) {
$('#mainnav li.current-menu-ancestor').children('ul.sub-menu').show();
}
$.each($('#mainnav li a'), function() {
//alert($(this).html());
if ( $(this).html() == 'Connect') {
$(this).addClass('clearfix').wrapInner('<span />').append('<span class="connect_icons"><a href="http://www.facebook.com/pages/Thurman-Law-Firm/149965848412220" class="socialicon facebook">Facebook</a><!--a href="#twitter" class="socialicon twitter">Twitter</a--></span>');
$('a.facebook, a.twitter').hover(function() {
$(this).css({ opacity: 0.75 });
}, function() {
$(this).css({ opacity: 1 });
}
);
} else if ( $(this).html() == 'Share') {
$(this).addClass('clearfix').wrapInner('<span />').append("<span class='st_sharethis'><span class='socialicon'><img src='' /></span></span>");
$(this).hover(function() {
$('.chicklets').css({ opacity: 0.75 });
}, function() {
$('.chicklets').css({ opacity: 1 });
}
);
}
});
$('.next, .prev').hide();
var timer;
function showSliderNav() {
window.clearTimeout(timer);
$("#slidernav").animate({
opacity: 1,
bottom: '0'
}, 'fast', function() {
});
$('.next, .prev').fadeIn('slow');
}
function hideSliderNav() {
timer = setTimeout(function() {
$('.next, .prev').hide();
$("#slidernav").animate({
opacity: 1,
bottom: '-96px'
}, 500
);
}, 8000);
}
if ($("#slidernav li a").length > 1) {
showSliderNav();
}
$('#masthead').mouseover(function() {
showSliderNav();
$(this).addClass('pagination_open');
$(this).each(function() { clearInterval($(this).data("interval")); });
});
$('#masthead').mouseleave(function() {
hideSliderNav();
$('#masthead .pagination li.current a').click();
$(this).removeClass('pagination_open');
});
var item_width = $('#slidernav li').outerWidth();
var itemLeft = 0;
$("#slidernav li a").each(function(el){
itemLeft = itemLeft+$(this).width();
$('#slidernav ul').width(itemLeft * 2);
});
var left = 0;
var displayNum = 6;
var navLeft = 0;
var inc = ($("#slidernav li a:first").width() + 40) * displayNum; // width of thumb slide animation (width+padding/margin/borders * number of slides to move per click)
var counter = 1;
var clickTotal = Math.ceil($("#slidernav li a").size()/displayNum);
var totalItems = $(".pagination li a").length;
left = 0;
if (totalItems <= displayNum) $('.prev').css({'z-index':displayNum});
$('.next').css({'z-index':displayNum});
$(".prev").click(function(){
//$('.next').fadeIn('slow');
$('.next').css({'z-index':totalItems});
left = left+inc;
$("#slidernav ul").animate({
marginLeft: "-"+(left)+"px"
}, 500,'swing', function() {
counter++;
if(counter >= clickTotal) {
$('.prev').css({'z-index':displayNum});
}
});
return false;
});
$(".next").click(function(){
$('.prev').css({'z-index':totalItems});
left = left-inc;
$("#slidernav ul").animate({
marginLeft: "-"+(left)+"px"
}, 500,'swing', function() {
counter--;
if(counter == 1){
$('.next').css({'z-index':displayNum});
}
});
return false;
});
$("#masthead").slides({
preload: true,
//preloadImage: '../img/loading.gif',
play: 5000,
pause: 2500,
slideSpeed: 300,
effect: 'fade, fade',
hoverPause: true,
prev:'slider_prev',
next:'slider_next',
generateNextPrev: false,
generatePagination: false,
paginationClass: 'pagination',
animationStart: function(current) {
if ($('#masthead').attr('class') != 'pagination_open' && $(".pagination li:nth-child("+displayNum+"n)").hasClass('current') || $(".pagination li:nth-child("+totalItems+")").hasClass('current')) {
//alert(counter + "\n" + clickTotal)
if (counter != clickTotal && (counter+1 != Math.ceil(totalItems/current) || counter-1 != Math.ceil(totalItems/current))) {
$('.next').css({'z-index':totalItems});
if (totalItems == current) {
left = 0;
counter = 1;
$('.next').css({'z-index':displayNum});
} else if (counter == Math.ceil((current/counter) - 1)) {
left = left+inc;
counter++;
} else {
left = left+inc;
$("#slidernav ul").animate({
marginLeft: "-"+(left)+"px"
}, 500,'swing', function() {
counter++;
if (counter >= clickTotal) {
$('.prev').css({'z-index':displayNum});
}
});
}
} else if (totalItems == current) {
$('.prev').css({'z-index':totalItems});
left = 0;
$("#slidernav ul").animate({
marginLeft: "-"+(left)+"px"
}, 500,'swing', function() {
counter = 1;
$('.next').css({'z-index':displayNum});
});
}
}
},
animationComplete: function(current) {
if ($('#masthead').hasClass('pagination_open')) {
$('#masthead').each(function() { clearInterval($(this).data("interval")); });
}
}
});
});<file_sep>/apps/code_snippets/scripts/raytest.js
"use strict";
b4w.register("raytest", function(exports, require) {
var m_anim = require("animation");
var m_app = require("app");
var m_cam = require("camera");
var m_cfg = require("config");
var m_cont = require("container");
var m_cons = require("constraints");
var m_ctl = require("controls");
var m_data = require("data");
var m_obj = require("objects");
var m_phy = require("physics");
var m_quat = require("quat");
var m_scenes = require("scenes");
var m_trans = require("transform");
var m_tsr = require("tsr");
var m_util = require("util");
var m_vec3 = require("vec3");
var APP_ASSETS_PATH = m_cfg.get_std_assets_path() + "code_snippets/raytest/";
exports.init = function() {
m_app.init({
autoresize: true,
callback: init_cb,
canvas_container_id: "canvas_cont",
console_verbose: true,
physics_enabled: true,
show_fps: true
});
}
function init_cb(canvas_elem, success) {
if (!success) {
console.log("b4w init failure");
return;
}
m_app.enable_controls();
load();
}
function load() {
m_data.load(APP_ASSETS_PATH + "raytest.json", load_cb);
}
function load_cb(data_id) {
m_app.enable_camera_controls();
init_logic();
}
function init_logic() {
var from = new Float32Array(3);
var to = new Float32Array(3);
var decal_num = 0;
var decal_src = m_scenes.get_object_by_name("Decal");
var decal_tsr = m_tsr.create();
var obj_tsr = m_tsr.create();
var decal_rot = m_quat.create();
var ray_test_cb = function(id, hit_fract, obj_hit, hit_time, hit_pos, hit_norm) {
var decal = m_obj.copy(decal_src, "decal" + String(++decal_num), false);
m_scenes.append_object(decal);
m_tsr.set_trans(hit_pos, decal_tsr);
m_quat.rotationTo(m_util.AXIS_Y, hit_norm, decal_rot);
m_trans.set_rotation_v(decal, decal_rot);
m_tsr.set_quat(decal_rot, decal_tsr);
if (obj_hit && m_anim.is_animated(obj_hit)) {
m_trans.get_tsr(obj_hit, obj_tsr);
m_tsr.invert(obj_tsr, obj_tsr);
m_tsr.multiply(obj_tsr, decal_tsr, decal_tsr);
var offset = m_tsr.get_trans_view(decal_tsr);
var rot_offset = m_tsr.get_quat_view(decal_tsr);
m_cons.append_stiff(decal, obj_hit, offset, rot_offset);
}
m_trans.set_tsr(decal, decal_tsr);
}
var mouse_cb = function(e) {
var x = e.clientX;
var y = e.clientY;
m_cam.calc_ray(m_scenes.get_active_camera(), x, y, to);
m_vec3.scale(to, 100, to);
var obj_src = m_scenes.get_active_camera();
var id = m_phy.append_ray_test_ext(obj_src, from, to, "ANY",
ray_test_cb, true, false, true, true);
}
var cont = m_cont.get_container();
cont.addEventListener("mousedown", mouse_cb, false);
}
});
<file_sep>/apps/code_snippets/scripts/camera_move_styles.js
"use strict";
b4w.register("camera_move_styles", function(exports, require) {
var m_app = require("app");
var m_cam = require("camera");
var m_cfg = require("config");
var m_data = require("data");
var m_scenes = require("scenes");
var m_trans = require("transform");
var m_util = require("util");
var APP_ASSETS_PATH = m_cfg.get_std_assets_path() + "code_snippets/camera_move_styles/";
var STATIC_POS = new Float32Array([-4.5, 0.5, 3]);
var STATIC_LOOK_AT = new Float32Array([-4.5, 0, 0]);
var EYE_POS = new Float32Array([-1.5, 0.5, 3]);
var EYE_LOOK_AT = new Float32Array([-1.5, 0.5, 0]);
var TARGET_POS = new Float32Array([1.5, 0, 3]);
var TARGET_PIVOT = new Float32Array([1.5, 0, 0]);
var DIST_LIMITS = {
min: 1,
max: 2
};
var EYE_VERT_LIMITS = {
down: -Math.PI/16,
up: Math.PI/16
}
var EYE_HORIZ_LIMITS = {
left: Math.PI/4,
right: -Math.PI/4
}
var TARGET_VERT_LIMITS = {
down: -Math.PI/16,
up: -Math.PI/4
}
var TARGET_HORIZ_LIMITS = {
left: -Math.PI/4,
right: Math.PI/4
}
var HOVER_VERT_LIMITS = {
down: -Math.PI/16,
up: -Math.PI/4
}
var HOVER_PIVOT = new Float32Array([4.5, 0, 0]);
var _default_pos = new Float32Array(3);
var _default_rot = new Float32Array(4);
exports.init = function() {
m_app.init({
canvas_container_id: "canvas_cont",
callback: init_cb,
physics_enabled: false,
alpha: true,
show_fps: true,
autoresize: true
});
}
function init_cb(canvas_elem, success) {
if (!success) {
console.log("b4w init failure");
return;
}
m_app.enable_controls();
load();
}
function load() {
m_data.load(APP_ASSETS_PATH + "camera_move_styles.json", load_cb);
}
function load_cb(data_id) {
m_app.enable_camera_controls();
init_interface();
var camera = m_scenes.get_active_camera();
m_trans.get_translation(camera, _default_pos);
m_trans.get_rotation(camera, _default_rot);
}
function init_interface() {
var controls_container = document.createElement("div");
controls_container.id = "controls_container";
var stat_b = create_button("STATIC CAMERA");
stat_b.onclick = static_camera_action;
controls_container.appendChild(stat_b);
var eye_b = create_button("EYE CAMERA");
eye_b.onclick = eye_camera_action;
controls_container.appendChild(eye_b);
var targ_b = create_button("TARGET CAMERA");
targ_b.onclick = target_camera_action;
controls_container.appendChild(targ_b);
var hov_b = create_button("HOVER CAMERA");
hov_b.onclick = hover_camera_action;
controls_container.appendChild(hov_b);
var reset_b = create_button("RESET");
reset_b.onclick = reset_camera_action;
controls_container.appendChild(reset_b);
document.body.appendChild(controls_container);
}
function create_button(caption) {
var button = document.createElement("div");
button.className = "button_container";
var label = document.createElement("label");
label.className = "text";
label.textContent = caption;
button.appendChild(label);
return button;
}
function static_camera_action() {
m_app.set_camera_move_style(m_cam.MS_STATIC);
var camera = m_scenes.get_active_camera();
m_cam.static_set_look_at(camera, STATIC_POS, STATIC_LOOK_AT, m_util.AXIS_Y);
}
function eye_camera_action() {
m_app.set_camera_move_style(m_cam.MS_EYE_CONTROLS);
var camera = m_scenes.get_active_camera();
// setting camera position/orientation
m_cam.eye_set_look_at(camera, EYE_POS, EYE_LOOK_AT);
// setting some limits
m_cam.eye_set_horizontal_limits(camera, EYE_HORIZ_LIMITS);
m_cam.eye_set_vertical_limits(camera, EYE_VERT_LIMITS);
// setting some rotation
m_cam.rotate_camera(camera, 0, -Math.PI/16, true, true);
}
function target_camera_action() {
m_app.set_camera_move_style(m_cam.MS_TARGET_CONTROLS);
var camera = m_scenes.get_active_camera();
// setting camera position/orientation
m_cam.target_set_trans_pivot(camera, TARGET_POS, TARGET_PIVOT);
// setting some limits
m_cam.target_set_distance_limits(camera, DIST_LIMITS);
m_cam.target_set_horizontal_limits(camera, TARGET_HORIZ_LIMITS);
m_cam.target_set_vertical_limits(camera, TARGET_VERT_LIMITS);
// setting some rotation
m_cam.rotate_camera(camera, Math.PI/8, 0, true, true);
}
function hover_camera_action() {
m_app.set_camera_move_style(m_cam.MS_HOVER_CONTROLS);
var camera = m_scenes.get_active_camera();
// setting necessary parameters for the HOVER camera: the "pivot" point,
// the distance limits and the hover angle limits
m_cam.hover_set_pivot_translation(camera, HOVER_PIVOT);
m_cam.hover_set_distance_limits(camera, DIST_LIMITS);
m_cam.hover_set_vertical_limits(camera, HOVER_VERT_LIMITS);
// setting some rotation
m_cam.rotate_camera(camera, -Math.PI/4, -Math.PI/8, true, true);
}
function reset_camera_action() {
m_app.set_camera_move_style(m_cam.MS_STATIC);
var camera = m_scenes.get_active_camera();
m_trans.set_translation_v(camera, _default_pos);
m_trans.set_rotation_v(camera, _default_rot);
}
});
<file_sep>/apps/code_snippets/scripts/canvas_texture.js
"use strict";
b4w.register("canvas_texture", function(exports, require) {
var m_tex = require("textures");
var m_data = require("data");
var m_app = require("app");
var m_main = require("main");
var m_sfx = require("sfx");
var m_scenes = require("scenes");
var m_cfg = require("config");
var GIF_FRAMES_NUMBER = 24;
var GIF_DELAY_TIME = 100;
var VIDEO_DELAY_TIME = 1000/30;
var APP_ASSETS_PATH = m_cfg.get_std_assets_path() + "code_snippets/canvas_texture/";
exports.init = function() {
m_app.init({
canvas_container_id: "canvas_cont",
callback: init_cb,
show_fps: true,
physics_enabled: false,
alpha: true,
autoresize: true
});
}
function init_cb(canvas_elem, success) {
if (!success) {
console.log("b4w init failure");
return;
}
m_app.enable_controls();
load();
}
function load() {
m_data.load(APP_ASSETS_PATH + "example.json", load_cb);
}
function load_cb(data_id) {
m_app.enable_camera_controls();
load_data();
}
function load_data() {
var cube = m_scenes.get_object_by_name("Cube");
var ctx_image = m_tex.get_canvas_ctx(cube, "Image");
var ctx_video = m_tex.get_canvas_ctx(cube, "Video");
var ctx_picture = m_tex.get_canvas_ctx(cube, "Picture");
if (ctx_image) {
var img = new Image();
img.src = APP_ASSETS_PATH + "earth.jpg";
img.onload = function() {
ctx_image.drawImage(img, 0, 0, ctx_image.canvas.width,
ctx_image.canvas.height);
ctx_image.fillStyle = "rgba(255,0,0,255)";
ctx_image.font = "250px Arial";
ctx_image.fillText("Hello, World!", 300, 300);
m_tex.update_canvas_ctx(cube, "Image");
}
}
if (ctx_video) {
var format = m_sfx.detect_video_container("");
if (format) {
var video_file = document.createElement('video');
video_file.autoplay = true;
video_file.loop = true;
video_file.addEventListener("loadeddata", function() {
draw_video_iter(cube, video_file, ctx_video);
}, false);
if (format == "m4v")
video_file.src= APP_ASSETS_PATH + "blender." + "altconv." + format;
else
video_file.src= APP_ASSETS_PATH + "blender." + format;
} else
console.log("Can not load the video.");
}
if (ctx_picture) {
var image = new Image();
image.src = APP_ASSETS_PATH + "pyramid.jpg"
image.onload = function() {
var width = Math.round(image.width / GIF_FRAMES_NUMBER);
var height = image.height;
draw_picture_iter(cube, image, ctx_picture, width, height, 0);
}
}
}
function draw_video_iter(cube, video, context) {
var canvas = context.canvas;
var scale = canvas.width / video.videoWidth;
var scale_height = Math.round( scale * video.videoHeight );
var shift_position = Math.round((canvas.height - scale_height) / 2);
context.drawImage(video, 0, 0, video.videoWidth, video.videoHeight,
0, shift_position, canvas.width, scale_height);
m_tex.update_canvas_ctx(cube, "Video");
setTimeout(function() { draw_video_iter(cube, video, context) }, VIDEO_DELAY_TIME);
}
function draw_picture_iter(cube, image, context, width, height, current_frame) {
current_frame = current_frame % GIF_FRAMES_NUMBER;
context.drawImage(image, width * current_frame, 0, width, height, 0, 0,
context.canvas.width, context.canvas.height);
m_tex.update_canvas_ctx(cube, "Picture");
setTimeout(function() { draw_picture_iter(cube, image, context, width, height,
current_frame + 1) }, GIF_DELAY_TIME);
}
});
<file_sep>/apps/code_snippets/scripts/instancing.js
"use strict"
b4w.register("instancing", function(exports, require) {
var m_app = require("app");
var m_data = require("data");
var m_scs = require("scenes");
var m_obj = require("objects");
var m_trans = require("transform");
var m_cfg = require("config");
var APP_ASSETS_PATH = m_cfg.get_std_assets_path() + "code_snippets/instancing";
var NUM_OF_POINTS = 10;
var POS = 10;
var _monkeys_num = 0;
exports.init = function() {
m_app.init({
canvas_container_id: "canvas_cont",
callback: init_cb,
physics_enabled: false,
show_fps: true,
alpha: false,
autoresize: true
});
}
function init_cb(canvas_elem, success) {
if (!success) {
console.log("b4w init failure");
return;
}
m_app.enable_controls();
load();
}
function load() {
m_data.load(APP_ASSETS_PATH + "/instancing.json", load_cb);
}
function load_cb(data_id) {
m_app.enable_camera_controls();
draw_line(-POS, -POS, -POS, POS, -POS, -POS);
draw_line(-POS, -POS, -POS, -POS, POS, -POS);
draw_line(POS, -POS, -POS, POS, POS, -POS);
draw_line(-POS, POS, -POS, POS, POS, -POS);
draw_line(-POS, -POS, POS, POS, -POS, POS);
draw_line(-POS, -POS, POS, -POS, POS, POS);
draw_line(POS, -POS, POS, POS, POS, POS);
draw_line(-POS, POS, POS, POS, POS, POS);
draw_line(-POS, -POS, -POS, -POS, -POS, POS);
draw_line(-POS, POS, -POS, -POS, POS, POS);
draw_line(POS, -POS, -POS, POS, -POS, POS);
draw_line(POS, POS, -POS, POS, POS, POS);
}
function draw_line(start_x, start_y, start_z, end_x, end_y, end_z) {
var src_obj = m_scs.get_object_by_name("Suzanne");
var k_x = (end_x - start_x) / (NUM_OF_POINTS - 1);
var k_y = (end_y - start_y) / (NUM_OF_POINTS - 1);
var k_z = (end_z - start_z) / (NUM_OF_POINTS - 1);
for (var i = 0; i < NUM_OF_POINTS; i++) {
var monkey = m_obj.copy(src_obj, "Suzanne_" + _monkeys_num.toString(), false);
_monkeys_num++;
m_scs.append_object(monkey);
var x = start_x + k_x * i;
var y = start_y + k_y * i;
var z = start_z + k_z * i;
m_trans.set_translation(monkey, x, z, y);
}
}
});
<file_sep>/apps/code_snippets/scripts/camera_animation.js
"use strict";
b4w.register("camera_animation", function(exports, require) {
var m_app = require("app");
var m_cam = require("camera");
var m_cfg = require("config");
var m_ctl = require("controls");
var m_data = require("data");
var m_main = require("main");
var m_scenes = require("scenes");
var m_trans = require("transform");
var m_vec3 = require("vec3");
var ANIM_TIME = 2;
var APP_ASSETS_PATH = m_cfg.get_std_assets_path() + "code_snippets/camera_animation/";
var _anim_stop = false;
var _delta_target = ANIM_TIME;
var _cam_anim = {
timeline: -ANIM_TIME,
starting_eye: new Float32Array(3),
starting_target: new Float32Array(3),
final_eye: new Float32Array(3),
final_target: new Float32Array(3),
current_eye: new Float32Array(3),
current_target: new Float32Array(3)
}
var _vec3_tmp = new Float32Array(3);
exports.init = function() {
m_app.init({
canvas_container_id: "canvas_cont",
callback: init_cb,
physics_enabled: false,
alpha: true,
show_fps: true,
autoresize: true
});
}
function init_cb(canvas_elem, success) {
if (!success) {
console.log("b4w init failure");
return;
}
m_app.enable_controls();
load();
}
function load() {
m_data.load(APP_ASSETS_PATH + "camera_animation.json", load_cb);
}
function load_cb(data_id) {
m_app.enable_camera_controls();
var camobj = m_scenes.get_active_camera();
init_camera_animation(camobj);
var main_canvas = m_main.get_canvas_elem();
main_canvas.addEventListener("mouseup", main_canvas_up);
main_canvas.addEventListener("mousedown", main_canvas_down);
}
function main_canvas_up(e) {
if (e.button != 0)
return;
if (e.preventDefault)
e.preventDefault();
var obj = m_scenes.pick_object(e.clientX, e.clientY);
if (obj)
switch(m_scenes.get_object_name(obj)) {
case "Cube":
var target = m_scenes.get_object_by_name("Target_cube");
var eye = m_scenes.get_object_by_name("Eye_cube");
break;
case "Cone":
var target = m_scenes.get_object_by_name("Target_cone");
var eye = m_scenes.get_object_by_name("Eye_cone");
break;
default:
return;
}
if (eye && target) {
var camobj = m_scenes.get_active_camera();
var pos_view = m_trans.get_translation(eye);
var pos_target = m_trans.get_translation(target);
start_camera_animation(camobj, pos_view, pos_target);
}
}
function main_canvas_down(e) {
if (e.button != 0)
return;
var camobj = m_scenes.get_active_camera();
if (m_ctl.get_sensor_value(camobj, "CAMERA_MOVE", 0) - _cam_anim.timeline
< ANIM_TIME)
_anim_stop = true;
}
function start_camera_animation(camobj, pos_view, pos_target) {
// retrieve camera current position
m_cam.target_get_pivot(camobj, _cam_anim.current_target);
m_trans.get_translation(camobj, _cam_anim.current_eye);
// set camera starting position
m_vec3.copy(_cam_anim.current_target, _cam_anim.starting_target);
m_vec3.copy(_cam_anim.current_eye, _cam_anim.starting_eye);
// set camera final position
m_vec3.copy(pos_view, _cam_anim.final_eye);
m_vec3.copy(pos_target, _cam_anim.final_target);
// start animation
_delta_target = ANIM_TIME;
_cam_anim.timeline = m_main.global_timeline();
}
function init_camera_animation(camobj) {
var t_sensor = m_ctl.create_timeline_sensor();
var e_sensor = m_ctl.create_elapsed_sensor();
var logic_func = function(s) {
// s[0] = m_main.global_timeline() (t_sensor value)
return s[0] - _cam_anim.timeline < ANIM_TIME;
}
var cam_move_cb = function(camobj, id, pulse) {
if (pulse == 1) {
if (_anim_stop) {
_cam_anim.timeline = -ANIM_TIME;
return;
}
m_app.disable_camera_controls();
// elapsed = frame time (e_sensor value)
var elapsed = m_ctl.get_sensor_value(camobj, id, 1);
var delta = elapsed / ANIM_TIME;
m_vec3.subtract(_cam_anim.final_eye, _cam_anim.starting_eye, _vec3_tmp);
m_vec3.scaleAndAdd(_cam_anim.current_eye, _vec3_tmp, delta, _cam_anim.current_eye);
_delta_target -= elapsed;
delta = 1 - _delta_target * _delta_target / (ANIM_TIME * ANIM_TIME);
m_vec3.subtract(_cam_anim.final_target, _cam_anim.starting_target, _vec3_tmp);
m_vec3.scaleAndAdd(_cam_anim.starting_target, _vec3_tmp, delta, _cam_anim.current_target);
m_cam.target_set_trans_pivot(camobj, _cam_anim.current_eye, _cam_anim.current_target);
} else {
m_app.enable_camera_controls(false);
if (!_anim_stop)
m_cam.target_set_trans_pivot(camobj, _cam_anim.final_eye,
_cam_anim.final_target);
else
_anim_stop = false;
}
}
m_ctl.create_sensor_manifold(camobj, "CAMERA_MOVE", m_ctl.CT_CONTINUOUS,
[t_sensor, e_sensor], logic_func, cam_move_cb);
}
});
<file_sep>/apps/code_snippets/scripts/material_api.js
"use strict";
b4w.register("material_api", function(exports, require) {
var m_data = require("data");
var m_app = require("app");
var m_cfg = require("config");
var m_mat = require("material");
var m_obj = require("objects");
var m_scenes = require("scenes");
var APP_ASSETS_PATH = m_cfg.get_std_assets_path() + "code_snippets/material_api/";
exports.init = function() {
m_app.init({
canvas_container_id: "canvas_cont",
callback: init_cb,
physics_enabled: false,
alpha: true,
background_color: [1,1,1,0],
show_fps: true,
autoresize: true
});
}
function init_cb(canvas_elem, success) {
if (!success) {
console.log("b4w init failure");
return;
}
m_app.enable_controls();
load();
}
function load() {
m_data.load(APP_ASSETS_PATH + "material_api.json", load_cb);
}
function load_cb(data_id) {
m_app.enable_camera_controls();
set_stack_material_params();
set_node_material_params();
}
function set_stack_material_params() {
var cube_diffuse_color = m_scenes.get_object_by_name("Cube_diffuse_color");
var cube_specular_intensity = m_scenes.get_object_by_name("Cube_specular_intensity");
var cube_specular_hardness = m_scenes.get_object_by_name("Cube_specular_hardness");
var cube_emit_factor = m_scenes.get_object_by_name("Cube_emit_factor");
var cube_ambient_factor = m_scenes.get_object_by_name("Cube_ambient_factor");
var cube_specular_color = m_scenes.get_object_by_name("Cube_specular_color");
var cube_alpha_factor = m_scenes.get_object_by_name("Cube_alpha_factor");
var sphere_1 = m_scenes.get_object_by_name("Sphere_1");
var sphere_2 = m_scenes.get_object_by_name("Sphere_2");
m_mat.set_diffuse_color(cube_diffuse_color, "mat_diffuse_color", [0.5,0,0]);
m_mat.set_specular_intensity(cube_specular_intensity, "mat_specular_intensity", 1);
m_mat.set_specular_hardness(cube_specular_hardness, "mat_specular_hardness", 0.8);
m_mat.set_emit_factor(cube_emit_factor, "mat_emit_factor", 1);
m_mat.set_ambient_factor(cube_ambient_factor, "mat_ambient_factor", 0.1);
m_mat.set_specular_color(cube_specular_color, "mat_specular_color", [0, 0.8, 0]);
m_mat.set_alpha_factor(cube_alpha_factor, "mat_alpha_factor", 0);
m_mat.inherit_material(sphere_1, "Sphere_mat_1", sphere_2, "Sphere_mat_2");
}
function set_node_material_params() {
var cube_node_value = m_scenes.get_object_by_name("Cube_node_value");
m_obj.set_nodemat_value(cube_node_value, ["mat_node_value", "Value"], 20);
var cube_node_rgb = m_scenes.get_object_by_name("Cube_node_rgb");
m_obj.set_nodemat_rgb(cube_node_rgb, ["mat_node_rgb", "RGB"], 0, 1, 0);
}
});
| 1555b28347d9f1a99bf9ea38a3693d572ccec241 | [
"JavaScript"
] | 10 | JavaScript | mattkerkstra/mattkerkstra.github.io | 3ef0da1342955b3ea22f07da57bede1ed48b1017 | aa6914b69b3e3ac9bfd7d4fb93bc1a35d6f2eca3 |
refs/heads/master | <repo_name>cornydox/abbas-v2<file_sep>/assets/js/coin.js
function Coin(index){
this.index = index;
}
Coin.prototype.update = function(delta_s){
var boost = abbas.data.getBoost();
coin[this.index].x = (coin[this.index].x - delta_s * boost);
};<file_sep>/assets/js/preload.js
var preload = (function(){
var img_path = "assets/img/min/";
var new_path = "assets/img/new/";
var bg_path = "assets/img/background/";
var sound_path = "assets/sounds/";
return {
assets: function(){
var manifest = [
{id:"wood", src:img_path + "wood.png"},
{id:"bg_landing", src:new_path + "bg-landing.jpg"},
{id:"screen_splash", src:new_path + "bg_start4.jpg"},
{id:"abbas", src:new_path + "abbas.png"},
{id:"coins", src:img_path + "coins.png"},
{id:"gold", src:new_path + "speed-booster.png"},
{id:"crow", src:img_path + "crow-new.png"},
{id:"sky", src:new_path + "sky.png"},
{id:"base1", src:bg_path + "bg_base_01.png"},
{id:"base2", src:bg_path + "bg_base_02.png"},
{id:"base3", src:bg_path + "bg_base_03.png"},
{id:"base4", src:bg_path + "bg_base_04.png"},
{id:"mt_kk", src:bg_path + "bg_mt_kk.png"},
{id:"bg_kl", src:bg_path + "bg_kl.png"},
{id:"mountains", src:bg_path + "bg_mountains.png"},
{id:"front_grass1", src:bg_path + "bg_front_grass_01.png"},
{id:"front_grass2", src:bg_path + "bg_front_grass_02.png"},
{id:"front_grass3", src:bg_path + "bg_front_grass_03.png"},
{id:"front_grass4", src:bg_path + "bg_front_grass_04.png"},
{id:"back_grass1", src:bg_path + "bg_back_grass_01.png"},
{id:"back_grass2", src:bg_path + "bg_back_grass_02.png"},
{id:"back_grass3", src:bg_path + "bg_back_grass_03.png"},
{id:"back_grass4", src:bg_path + "bg_back_grass_04.png"},
{id:"energy", src:img_path + "energy.png"},
{id:"multiplier", src:new_path + "multiplier.png"},
{id:"bgm", src:sound_path + "1001bgm.mp3|"+sound_path + "1001bgm.ogg"},
{id:"boostfx", src:sound_path + "boost.mp3|"+sound_path + "boost.ogg"},
{id:"clickfx", src:sound_path + "click.mp3|"+sound_path + "click.ogg"},
{id:"coinfx", src:sound_path + "coin.mp3|"+sound_path + "coin.ogg"},
{id:"hitfx", src:sound_path + "hit-new.mp3|"+sound_path + "hit-new.ogg"},
{id:"energyfx", src:sound_path + "energy.mp3|"+sound_path + "energy.ogg"},
{id:"multiplierfx", src:sound_path + "multiplier.mp3|"+sound_path + "multiplier.ogg"},
{id:"crashed", src:sound_path + "crash.mp3|"+sound_path + "crash.ogg"},
];
loader = new createjs.LoadQueue(false);
loader.installPlugin(createjs.Sound);
loader.addEventListener("complete", preload.assetsLoaded);
loader.addEventListener("progress", preload.assetsProgress);
loader.loadManifest(manifest);
},
assetsLoaded: function(event){
$(elem.loader).hide();
$('.content-welcome').fadeIn();
},
assetsProgress: function(event){
var perc = event.loaded / event.total;
$('#progress').html(Math.ceil(perc*100).toString());
}
};
})();<file_sep>/assets/js/energy.js
function Energy(){
this.movement = "down";
this.update = function(delta_s){
// X Axis
var boost = abbas.data.getBoost();
energy.x = (energy.x - delta_s * 1.2 * boost);
// Y Axis
if(energy.y > 300){
this.movement = "up";
}
else if(energy.y < 60){
this.movement = "down";
}
if(this.movement == "up"){
delta_s = -delta_s;
}
energy.y = (energy.y + delta_s * 1.2);
};
}
<file_sep>/src/game.class.php
<?php
require_once "config.class.php";
class Game extends Config{
function __construct(){
parent::__construct();
}
function registerUser($name, $contact, $email, $score){
$query = $this->conn->prepare("INSERT INTO users (name, contact, email, score,
created_at) VALUES (:name, :contact, :email, :score, NOW());");
$query->execute(array(
':name' => $name,
':contact' => $contact,
':email' => $email,
':score' => $score,
));
}
function getLeaderboard(){
$query = $this->conn->prepare("SELECT * FROM users WHERE `name` IS NOT NULL ORDER BY score DESC LIMIT 10;");
$query->execute();
$result = $query->fetchAll();
return $result;
}
function getAdminData(){
$query = $this->conn->prepare("SELECT * FROM users WHERE `name` IS NOT NULL;");
$query->execute();
$result = $query->fetchAll();
return $result;
}
}<file_sep>/src/config.class.php
<?php
class Config{
private $host = "127.0.0.1";
private $dbname = "inventio_game";
## Development
// private $username = "root";
// private $password = "<PASSWORD>";
## LIVE
private $username = "inventio_root";
private $password = "<PASSWORD>";
public $conn = "";
function __construct(){
$this->connectDb();
}
function connectDb(){
try{
$this->conn = new PDO("mysql:host=$this->host;dbname=$this->dbname;charset=utf8",
$this->username, $this->password);
$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e){
echo "ERROR: " . $e->getMessage();
}
}
}
<file_sep>/assets/js/player.js
function Player(){
this.energy = 100; // Initial energy.
this.distance = 0;
this.offset = 0;
this.energy_timeout = 0;
this.flying = false;
this.coin = 0;
this.coin_multiply = false;
this.is_boosting = false;
this.boost = 1;
}
Player.prototype.isFlying = function(){
return this.flying;
};
Player.prototype.setFlying = function(state){
this.flying = state;
var self = this;
if(state === true){
this.energy_timeout = setInterval(function(){
self.energy = self.energy - 1;
}, 100);
}
else{
clearInterval(this.energy_timeout);
}
};
Player.prototype.setEnergy = function(value){
this.energy = value;
};
Player.prototype.getEnergy = function(){
if( this.energy < 0 ){
this.energy = 0;
}
return this.energy;
};
Player.prototype.plusCoin = function(){
if(this.coin_multiply === true){
this.coin = this.coin + 3;
}
else{
this.coin++;
}
};
Player.prototype.getCoin = function(){
return this.coin;
};
Player.prototype.regenEnergy = function(){
this.energy = 100;
};
Player.prototype.damage = function(){
this.energy = this.energy - 5;
};
Player.prototype.updateDistance = function(){
this.offset = 0.3 * (createjs.Ticker.getFPS() / createjs.Ticker.getMeasuredFPS());
this.distance = this.distance + (this.offset * this.boost);
};
Player.prototype.getDistance = function(){
return Math.floor(this.distance);
};
Player.prototype.setBoost = function(state){
this.is_boosting = state;
if(this.is_boosting === true){
this.boost = MULTIPLIER;
}
else{
this.boost = 1;
}
};
Player.prototype.isBoosting = function(){
return this.is_boosting;
};
Player.prototype.getBoost = function(){
return this.boost;
};
Player.prototype.setCoinMultiply = function(state){
this.coin_multiply = state;
};<file_sep>/src/main.php
<?php
require_once "game.class.php";
if($_SERVER["REQUEST_METHOD"] === "POST"){
$action = $_POST['action'];
}
else if($_SERVER["REQUEST_METHOD"] === "GET"){
$action = $_GET['action'];
}
if(isset($action)){
$game = new Game();
call_user_func($action, $game);
}
function register($game){
$name = $_POST["name"];
$contact = $_POST["contact"];
$email = $_POST["email"];
$score = $_POST["score"];
$game->registerUser($name, $contact, $email, $score);
getLeaderboard($game);
}
function getLeaderboard($game){
$leaderboard = $game->getLeaderboard();
echo json_encode($leaderboard); // Return Ajax
}
function getAdminData($game){
$data = $game->getAdminData();
echo json_encode($data);
}
function exportAdminData($game){
$date = date("Y-m-d");
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=abbas_{$date}.csv");
header("Pragma: no-cache");
header("Expires: 0");
echo "id,name,contact,email,score,date\n";
$data = $game->getAdminData();
foreach($data as $row){
echo "{$row['id']},{$row['name']},{$row['contact']},{$row['email']},{$row['score']},{$row['created_at']}\n";
}
}
<file_sep>/assets/js/crow.js
function Crow(index, max_speed){
this.speed = Math.random() * (max_speed-4-1) + 5;
this.index = index;
}
Crow.prototype.update = function(delta_s){
crow[this.index].x = (crow[this.index].x - this.speed * delta_s);
};<file_sep>/admin/index.php
<?php
if (!isset($_SERVER['PHP_AUTH_USER']) || ($_SERVER['PHP_AUTH_USER'] != "abbas" &&
$_SERVER['PHP_AUTH_PW'] != "<PASSWORD>") ) {
header('WWW-Authenticate: Basic realm="Restricted"');
header('HTTP/1.0 401 Unauthorized');
echo '<h1>Authentication Failed</h1>';
exit;
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<title>Admin - Games | 1001 Inventions</title>
<link rel="stylesheet" href="./datatables/css/demo_table.css">
<link rel="stylesheet" href="admin.css">
<script src="../assets/js/vendor/jquery-1.10.2.min.js"></script>
<script src="./datatables/js/jquery.dataTables.min.js"></script>
<script src="admin.js"></script>
</head>
<body>
<div class="main-content">
<h3>Registered Users</h3>
<table id="result" border="0">
<thead>
<th>ID</th>
<th>Name</th>
<th>Contact #</th>
<th>Email</th>
<th>Score</th>
<th>Register Date</th>
</thead>
<tbody id="result-content">
</tbody>
</table>
<button id="export">Export to CSV</button>
</div>
</body>
</html><file_sep>/assets/js/gameover.js
var gameover = (function(){
return{
showScore: function(){
var distance = $.trim($("#distance").html());
var coins = parseInt($("#coin").html());
var score = parseInt(distance.replace("m","")) + coins;
$("#coin").html('0');
$(elem.hud).fadeOut();
$(elem.hud).hide();
$("#show_distance").html(distance);
$("#show_coins").html(coins);
$("#show_score").html(score);
$("#score").val(score);
$(elem.score).fadeIn();
util.resetAllObjects();
stage.removeAllChildren();
stage.clear();
createjs.Sound.stop("bgm");
},
registerUser: function(){
var $form = $(elem.formRegister);
var $input = $form.find("input");
var form_data = $form.serialize();
form_data += "&action=register";
// $input.prop("disabled", true);
$.ajax({
url: "./src/main.php",
data: form_data,
type: "POST"
}).done(function ( data ) {
data = $.parseJSON(data); // Data for Leaderboard
var html = "";
for(var i in data){ // Loop through each row, add to list
html += '<li class="list-player"><span class="txt-name">' + data[i].name.substring(0,12) + '</span>';
html += '<span class="txt-score">' + data[i].score + "</span></li>";
}
$(".wrapper-leaderboard ol").html(html);
$(elem.registration).fadeOut();
$(elem.leaderboard).fadeIn();
}).fail(function (jqXHR, textStatus, errorThrown){
console.dir(jqXHR + "," + "textStatus" , + "errorThrown");
});
}
};
})();<file_sep>/assets/js/main.js
/*=====================================================
Global Variables
======================================================*/
var stage, loader, delta_s, bgmusic;
var PLAYGROUND_WIDTH, PLAYGROUND_HEIGHT;
// Objects
var abbas, gold, energy, coin_multiplier;
// Background Landscape - Back Layers
var sky, clouds, base, base1, base2, base3, base4, mountains, mt_kk, bg_kl;
// Background Landscape - Front Layers
var front_grass1, front_grass2, front_grass3, front_grass4, back_grass1, back_grass2, back_grass3, back_grass4;
// Boost speed constant. Currently set to 6x of normal speed.
var MULTIPLIER = 6;
// Current movement speed (** Should've name this something else, oh well)
var boost;
// Pause state
var set_paused = false;
// Array to store multiple objects on screen
var crow = [];
var coin = [];
// Selectors
var elem = {};
elem.loader = '.txt-loading';
elem.gameover = '.txt-gameover';
elem.pause_play = '.content-pause-play';
elem.hud = '.content-hud';
elem.score = '.content-score';
elem.btn_replay = '.btn-replay';
elem.btn_submit = '.btn-submit';
elem.btn_next = '.btn-next';
elem.btn_back = '.btn-back';
elem.btn_play = '.btn-play';
elem.btn_close = '.btn-close, .btn-main-menu';
elem.btn_pause_play = '.btn-pause-play';
elem.registration = '.content-registration';
elem.formRegister = '#registration';
elem.btn_register = '.btn-register';
elem.leaderboard = '.content-leaderboard';
/*=====================================================
Global Functions
======================================================*/
function startGame(){
var game = new Game();
game.init();
}
function showTutorial(){
$('#welcome').hide();
$('.content-instruction').show();
}
function restartGame(){
$(elem.score).hide();
startGame();
}
function showLeaderboard(){
$.ajax({
url: './src/main.php',
data: {action: 'getLeaderboard'},
type: "POST"
}).done(function(data) {
data = $.parseJSON(data); // Data for Leaderboard
var html = '';
for(var i in data){ // Loop through each row, add to list
html += '<li class="list-player"><span class="txt-name">' + data[i].name.substring(0,12) + '</span>';
html += '<span class="txt-score">' + data[i].score + "</span></li>";
}
$('.wrapper-leaderboard ol').html(html);
$('#welcome').fadeOut();
$(elem.leaderboard).fadeIn();
}).fail(function (jqXHR, textStatus, errorThrown){
console.dir(jqXHR + "," + "textStatus" , + "errorThrown");
});
}
function loadAssets(){
$(elem.loader).fadeIn();
preload.assets();
}
/*=====================================================
Events
======================================================*/
$(function(){
loadAssets();
// Proceed to register high score
$(elem.btn_submit).click(function(event){
$(elem.score).fadeOut();
$(elem.registration).fadeIn();
event.preventDefault();
});
// Actual high score form registration
$(elem.btn_register).click(function(event){
var good_to_go = true;
$(elem.formRegister + ' input').each(function(){
if($(this).val() === ''){
good_to_go = false;
$(this).attr('placeholder', 'Please fill in your ' + $(this).attr('name'));
}
});
if(good_to_go === true){
gameover.registerUser();
}
event.preventDefault();
});
// Click sound
$('.btn, .btn-img-right, .btn-img-left').click(function(){
createjs.Sound.play("clickfx");
});
// Play game
$(elem.btn_play).click(function(event){
startGame();
event.preventDefault();
});
// Play again
$(elem.btn_replay).click(function(event){
restartGame();
event.preventDefault();
});
// Tutorial / Instructions
$(elem.btn_next).click(function(event){
$('.instruction-1').hide();
$('.instruction-2').show();
event.preventDefault();
});
// Back to main menu
$(elem.btn_back).click(function(event){
$('.instruction-2').hide();
$('.instruction-1').show();
event.preventDefault();
});
// Close button
$(elem.btn_close).click(function(event){
$(this).parent().parent().hide();
$('#welcome').show();
event.preventDefault();
});
// Pause / Resume button
$(elem.btn_pause_play).click(function(event){
createjs.Sound.play("clickfx");
var current_image = $(this).attr('src');
if($(this).hasClass('paused')){
set_paused = false;
current_image = current_image.replace('pause', 'play');
$(this).removeClass('paused');
bgmusic.resume();
}
else {
set_paused = true;
current_image = current_image.replace('play', 'pause');
$(this).addClass('paused');
bgmusic.pause();
}
$(this).attr('src', current_image);
util.pausePlay(set_paused);
event.preventDefault();
});
});<file_sep>/assets/js/abbas.js
function Abbas(){
this.die = false;
}
Abbas.prototype = new Player(); // Inherit Player Class
Abbas.prototype.movement = function(delta_s){
if(this.getEnergy() === 0){
this.setFlying(false);
util.clearMouse();
abbas.gotoAndPlay("fly");
}
if(abbas.y < PLAYGROUND_HEIGHT-100 && this.isFlying() === false){ // Abbas falling down
abbas.y = (abbas.y + delta_s / this.boost);
}
else if(abbas.y > 0 && this.isFlying() === true && this.getEnergy() > 0){ // Abbas fly, limit max height...
abbas.y = (abbas.y - (delta_s * 2)/ this.boost);
}
else if(abbas.y > PLAYGROUND_HEIGHT-100){
this.crash(delta_s);
}
else{
abbas.gotoAndPlay("glide");
}
this.updateDistance();
};
Abbas.prototype.hit = function(){
// Sound FX
createjs.Sound.play("hitfx");
abbas.y = (abbas.y + 15);
this.damage();
};
Abbas.prototype.crash = function(delta_s){
abbas.y = (abbas.y - delta_s);
this.setEnergy(0);
setTimeout(function(){
abbas.y = (abbas.y + delta_s * 1.5);
util.removeAllCrows();
}, 500);
if(this.die === false){
createjs.Sound.play("crashed");
$(elem.pause_play).hide();
setTimeout(function(){
util.gameOver();
}, 1500);
}
this.die = true;
};
Abbas.prototype.coinify = function(){
createjs.Sound.play("coinfx");
this.plusCoin();
$("#coin").html(this.getCoin());
};
Abbas.prototype.boostify = function(){
createjs.Sound.play("boostfx");
this.setBoost(true);
util.removeAllCrows();
var self = this;
setTimeout(function(){
self.setBoost(false);
}, 3000);
};
Abbas.prototype.energize = function(){
createjs.Sound.play("energyfx");
this.regenEnergy();
};
Abbas.prototype.multiply = function(){
createjs.Sound.play("multiplierfx");
this.setCoinMultiply(true);
// Make Abbas Glow!
abbas.shadow = new createjs.Shadow("#e5d584",5,-10,30);
// Change HUD color
$("#coin").css({color : "#e5d584", "font-size" : "160%"});
var self = this;
setTimeout(function(){
abbas.shadow = false;
self.setCoinMultiply(false);
$("#coin").css({color : "#fff", "font-size" : "100%"});
}, 6000);
};
Abbas.prototype.stats = function(){
$("#energy_bar").css("width", this.getEnergy() + "%");
$("#distance").html(this.getDistance());
};<file_sep>/assets/js/util.js
// Utilities / helper
var util = (function(){
var mouse_timeout = 0;
var gold_on_screen = false;
var energy_on_screen = false;
var multiplier_on_screen = false;
var crow_spawn_timeout = 0;
var coin_spawn_timeout = 0;
var gold_timeout = 0;
var energy_timeout = 0;
var multiplier_timeout = 0;
var min_spawn_rate = 0;
var max_spawn_rate = 0;
var max_speed = 0;
return{
initControls: function(){
stage.onPress = function(evt) {
if( abbas.data.getEnergy() > 0 ){
// On mouse hold, abbas hover / fly constant
mouse_timeout = setTimeout(function(){
abbas.data.setFlying(true);
abbas.gotoAndPlay("up");
}, 100);
// On mouse release
evt.onMouseUp = function(evt){
util.clearMouse();
abbas.data.setFlying(false);
abbas.gotoAndPlay("fly");
};
}
};
},
clearMouse: function(){
clearTimeout(mouse_timeout);
},
getRandom: function(from, to){
return Math.floor(Math.random()*(to-from-1) + from);
},
pausePlay: function(state){
createjs.Ticker.setPaused(state);
},
gameOver: function(){
createjs.Ticker.setPaused(true);
$("#gameover_1").fadeIn();
setTimeout(function(){
$("#gameover_1").fadeOut();
gameover.showScore();
},2000);
},
levelCheck: function(){
var current_distance = abbas.data.getDistance();
if(current_distance < 650){
min_spawn_rate = 650;
max_spawn_rate = 1900;
max_speed = 5;
}
else if(current_distance < 1200){
min_spawn_rate = 400;
max_spawn_rate = 1400;
max_speed = 7;
}
else if(current_distance < 1900){
min_spawn_rate = 150;
max_spawn_rate = 1200;
max_speed = 9;
}
else{
min_spawn_rate = 100;
max_spawn_rate = 1000;
max_speed = 10;
}
},
generateCrow: function(){
util.levelCheck();
var spawn_chance = util.getRandom(min_spawn_rate, max_spawn_rate);
crow_spawn_timeout = setTimeout(function(){
if( abbas.data.isBoosting() === false && set_paused === false ){
var img_crow = loader.getResult("crow");
var spriteSheet = new createjs.SpriteSheet({
"images": [img_crow],
"frames": {"regX": 0, "height": img_crow.height, "count": 2, "regY": 0, "width": img_crow.width/2},
"animations": {fly:[0,1,"fly",5.5]}
});
crow.push(new createjs.BitmapAnimation(spriteSheet));
crow[crow.length-1].setTransform(PLAYGROUND_WIDTH,abbas.y,0.6,0.6);
crow[crow.length-1].gotoAndPlay("fly");
crow[crow.length-1].data = new Crow(crow.length-1, max_speed);
stage.addChild(crow[crow.length-1]);
// console.log("spawn! " + spawn_chance);
}
util.generateCrow();
}, spawn_chance);
},
crowMovement: function(delta_s){
for(var i in crow){
if(crow[i].x < -PLAYGROUND_WIDTH){
stage.removeChild(crow[i]);
delete crow[i];
// console.log("Bird removed!");
}
else{
var col = crow[i].localToLocal(5, 25, abbas);
if( abbas.hitTest(col.x, col.y) ){ abbas.data.hit(); }
crow[i].data.update(delta_s);
}
}
},
removeAllCrows: function(){
for(var i in crow){
stage.removeChild(crow[i]);
delete crow[i];
}
},
generateCoins: function(){
var spawn_chance = util.getRandom(1000,6000);
coin_spawn_timeout = setTimeout(function(){
if(set_paused === false){
var no_of_coins = util.getRandom(7,14);
var pos_y = util.getRandom(10,300);
var img_coin = loader.getResult("coins");
var coin_width = img_coin.width/5;
var temp = [];
var pos_x = PLAYGROUND_WIDTH + (no_of_coins*coin_width);
for( var z = 0; z < no_of_coins; z++ ){
var speed = Math.floor(Math.random()*2) + 1;
temp.push(new createjs.SpriteSheet({
images: [img_coin],
frames: {"regX": 0, "height": 30, "count": 5, "regY": 0, "width": coin_width},
animations: {turn:[0,4,true,speed+2]}
}));
coin.push(new createjs.BitmapAnimation(temp[z]));
coin[coin.length-1].setTransform(pos_x,pos_y,0.7,0.7);
coin[coin.length-1].gotoAndPlay("turn");
coin[coin.length-1].data = new Coin(coin.length-1);
stage.addChild(coin[coin.length-1]);
pos_x = pos_x - coin_width;
}
util.generateCoins();
}
}, spawn_chance);
},
coinMovement: function(delta_s){
for(var i in coin){
if(coin[i].x < -PLAYGROUND_WIDTH-180){
stage.removeChild(coin[i]);
delete coin[i];
// console.log("Coin removed!");
}
else{
var col = coin[i].localToLocal(0, 10, abbas);
if( abbas.hitTest(col.x, col.y) ){
abbas.data.coinify();
stage.removeChild(coin[i]);
delete coin[i];
}
else{
coin[i].data.update(delta_s);
}
}
}
},
removeAllCoins: function(){
for(var i in coin){
stage.removeChild(coin[i]);
delete coin[i];
}
},
generateGold: function(){
if( gold_on_screen === false && set_paused === false ){
var spawn_chance = util.getRandom(10000,30000);
gold_timeout = setTimeout(function(){
var img_gold = loader.getResult("gold");
var pos_y = util.getRandom(10,300);
var pos_x = PLAYGROUND_WIDTH + img_gold.width;
var sprite_sheet = new createjs.SpriteSheet({
"images": [img_gold],
"frames": {"regX": 0, "height": img_gold.height, "count": 1, "regY": 0, "width": img_gold.width},
"animations": {move: 0}
});
gold = new createjs.BitmapAnimation(sprite_sheet);
gold.setTransform(pos_x, 0, 1, 1);
gold.data = new Gold();
gold.gotoAndPlay("move");
stage.addChild(gold);
gold_on_screen = true;
// console.log("gold!");
}, spawn_chance);
}
},
goldMovement: function(delta_s){
if( gold_on_screen === true ){
if( gold.x < -PLAYGROUND_WIDTH) {
stage.removeChild(gold);
gold_on_screen = false;
util.generateGold();
}
else{
var col = gold.localToLocal(20, 20, abbas);
if( abbas.hitTest(col.x, col.y) ){
abbas.data.boostify();
stage.removeChild(gold);
util.generateGold();
}
else{
gold.data.update(delta_s);
}
}
}
},
generateEnergy: function(){
if( energy_on_screen === false && set_paused === false ){
var spawn_chance = util.getRandom(4000,10000);
energy_timeout = setTimeout(function(){
var img_energy = loader.getResult("energy");
var pos_y = util.getRandom(10,300);
var pos_x = PLAYGROUND_WIDTH + img_energy.width;
var sprite_sheet = new createjs.SpriteSheet({
"images": [img_energy],
"frames": {"regX": 0, "height": img_energy.height, "count": 1, "regY": 0, "width": img_energy.width},
"animations": {move: 0}
});
energy = new createjs.BitmapAnimation(sprite_sheet);
energy.setTransform(pos_x, 0, 1, 1);
energy.data = new Energy();
energy.gotoAndPlay("move");
stage.addChild(energy);
energy_on_screen = true;
// console.log("energy!");
}, spawn_chance);
}
},
energyMovement: function(delta_s){
if( energy_on_screen === true ){
if( energy.x < -PLAYGROUND_WIDTH) {
stage.removeChild(energy);
energy_on_screen = false;
util.generateEnergy();
}
else{
var col = energy.localToLocal(0, 5, abbas);
if( abbas.hitTest(col.x, col.y) ){
abbas.data.energize();
stage.removeChild(energy);
energy_on_screen = false;
util.generateEnergy();
}
else{
energy.data.update(delta_s);
}
}
}
},
generateMultiplier: function(){
if( multiplier_on_screen === false && set_paused === false ){
var spawn_chance = util.getRandom(13000,25000);
multiplier_timeout = setTimeout(function(){
var img_multiplier = loader.getResult("multiplier");
var pos_y = util.getRandom(10,300);
var pos_x = PLAYGROUND_WIDTH + img_multiplier.width;
var sprite_sheet = new createjs.SpriteSheet({
"images": [img_multiplier],
"frames": {"regX": 0, "height": img_multiplier.height, "count": 1, "regY": 0, "width": img_multiplier.width},
"animations": {move: 0}
});
coin_multiplier = new createjs.BitmapAnimation(sprite_sheet);
coin_multiplier.setTransform(pos_x, 0, 1, 1);
coin_multiplier.data = new CoinMultiplier();
coin_multiplier.gotoAndPlay("move");
stage.addChild(coin_multiplier);
multiplier_on_screen = true;
// console.log("energy!");
}, spawn_chance);
}
},
multiplierMovement: function(delta_s){
if( multiplier_on_screen === true ){
if( coin_multiplier.x < -PLAYGROUND_WIDTH) {
stage.removeChild(coin_multiplier);
multiplier_on_screen = false;
util.generateMultiplier();
}
else{
var col = coin_multiplier.localToLocal(0, 5, abbas);
if( abbas.hitTest(col.x, col.y) ){
abbas.data.multiply();
stage.removeChild(coin_multiplier);
multiplier_on_screen = false;
util.generateMultiplier();
}
else{
coin_multiplier.data.update(delta_s);
}
}
}
},
rotateBase: function(){
if(base1.x < -base1.image.width && base2.x > -base2.image.width){
base1.x = base4.x + base4.image.width;
stage.removeChild(base1);
stage.addChildAt(base3,5);
}
else if(base2.x < -base2.image.width && base3.x > -base3.image.width){
base2.x = base1.x + base1.image.width;
stage.removeChild(base2);
stage.addChildAt(base4,5);
}
else if(base3.x < -base3.image.width && base4.x > -base4.image.width){
base3.x = base2.x + base2.image.width;
stage.removeChild(base3);
stage.addChildAt(base1,5);
}
else if(base4.x < -base4.image.width && base1.x > -base1.image.width){
base4.x = base3.x + base3.image.width;
stage.removeChild(base4);
stage.addChildAt(base2,5);
}
},
rotateBackGrass: function(){
if(back_grass1.x < -back_grass1.image.width && back_grass2.x > -back_grass2.image.width){
back_grass1.x = back_grass4.x + back_grass4.image.width;
stage.removeChild(back_grass1);
stage.addChildAt(back_grass3,7);
}
else if(back_grass2.x < -back_grass2.image.width && back_grass3.x > -back_grass3.image.width){
back_grass2.x = back_grass1.x + back_grass1.image.width;
stage.removeChild(back_grass2);
stage.addChildAt(back_grass4,7);
}
else if(back_grass3.x < -back_grass3.image.width && back_grass4.x > -back_grass4.image.width){
back_grass3.x = back_grass2.x + back_grass2.image.width;
stage.removeChild(back_grass3);
stage.addChildAt(back_grass1,7);
}
else if(back_grass4.x < -back_grass4.image.width && back_grass1.x > -back_grass1.image.width){
back_grass4.x = back_grass3.x + back_grass3.image.width;
stage.removeChild(back_grass4);
stage.addChildAt(back_grass2,7);
}
},
resetAllObjects: function(){
coin = [];
crow = [];
clearTimeout(coin_spawn_timeout);
clearTimeout(crow_spawn_timeout);
clearTimeout(gold_timeout);
clearTimeout(energy_timeout);
clearTimeout(multiplier_timeout);
delete window.abbas;
delete window.energy;
delete window.gold;
delete window.coin_multiplier;
energy_on_screen = gold_on_screen = multiplier_on_screen = false;
}
};
})(); | e89361f55fbd494efe1dea68b6e3576f08750525 | [
"JavaScript",
"PHP"
] | 13 | JavaScript | cornydox/abbas-v2 | bb3ab2bc1465bd0cda771f2c93fb68bcdb21c037 | f47ba98121e5974b5379910bbaa4ad74320a3c52 |
refs/heads/master | <file_sep>package ds.stack;
public class App {
public static void main(String[] args) {
Stack theStack = new Stack(10);
System.out.println(reverseString("chinonso"));
}
public static String reverseString(String str){
Stack theStack = new Stack(str.length());
for(int x=0;x<str.length();x++){
theStack.push(str.charAt(x)+"");
}
str="";
while (!theStack.isEmpty()){
str+=theStack.pop();
}
return str;
}
}
<file_sep>package ds.BST;
public class BinaryTree {
Node root;//beginning of tree
//this method inserts node
public void add(int data){
Node newNode= new Node(data);//Node we are trying to add to the tree
if(root==null) root =newNode; //if there is no root make one
Node current = root;//basically a null checker
Node parent;//keeps parent to know if we should add or not
while (true) {
//traverse left
parent = current;//parent needs to be constantly updated
if (data <= current.getData()) {
current = current.getLeft();
if (current == null) {
parent.setLeft(newNode);
return;
}
}
//traverse right
else{
current=current.getRight();
if(current==null){
parent.setRight(newNode);
return;
}
}
}
}
public boolean find(int data) {
if (root == null) return false; //if tree is empty
Node current = root;
while (current != null) {
if (data == current.getData()) {
return true;
}
else if (data < current.getData()) {
current = current.getLeft();
} else {
current = current.getRight();
}
}
return false;
}
public void delete(int data){
}
}
<file_sep>package ds.mySinglyLinkedList;
public class Main {
public static void main(String[] args) {
LinkedList myList = new LinkedList();
myList.insertToStart(10);
myList.insertToEnd(20);
myList.insertToEnd(20);
myList.insertToEnd(40);
myList.insertToEnd(50);
myList.insertToEnd(50);
myList.insertToEnd(70);
myList.sortedInsert(45);
myList.sortedInsert(45);
myList.sortedInsert(0);
myList.display();
myList.removeDup();
myList.display();
}
}
<file_sep># DataStructurePractice
Some old code practicing data structures
<file_sep>package ds.queue;
public class App {
public static void main(String[] args) {
Queue myQueue = new Queue(5);
myQueue.insert(20);
myQueue.insert(30);
myQueue.insert(30);
myQueue.insert(80);
myQueue.insert(90);
myQueue.view();
}
}
<file_sep>package algorithms.selectionSort;
public class App {
public static void main(String[] args) {
int[] myArray = {9,8,3,13,87,12,99};
selectionSort(myArray);
for(int x=0;x<myArray.length;x++){
System.out.print(myArray[x]+" ");
}
}
public static int[] selectionSort(int a[]){
for(int x=0;x<a.length;x++){
int minimum = x;
for(int i=x+1;i<a.length;i++){
if(a[i]<a[x])minimum=i;//position of the minimum
}
int temp = a[x];
a[x]=a[minimum];
a[minimum]=temp;
}
return a;
}
}
<file_sep>package ds.BST;
public class Main {
public static void main(String[] args) {
BinaryTree tree = new BinaryTree();
tree.add(10);
tree.add(5);
tree.add(15);
System.out.println("completed");
//System.out.println(tree.find(15));
}
}
<file_sep>package ds.circularLinkedList;
public class CircularLinkedList {
private Node first;
private Node last;
public CircularLinkedList(){
first=null;
last=null;
}
public void insertFirst(int data){
Node newNode = new Node();
newNode.data=data;
newNode.next=first;//newNode-->
}
}
<file_sep>package ds.stack;
public class Stack {
private int maxSize;
private String[] stackArray;
private int top; //index position of last item
public Stack(int size){
maxSize=size;
stackArray=new String[maxSize];
top=-1;
}
public void push(String j){
if(isFull()){
System.out.println("Stack is full");
}else {
top++;
stackArray[top] = j;
}
}
public String pop(){
if(isEmpty()){
System.out.println("The stack is already empty");
return "";
}else {
int old_top = top;
top--;
return stackArray[old_top];
}
}
public String peak(){
return stackArray[top];
}
public boolean isEmpty(){
return (top == -1);
}
public boolean isFull(){
return (maxSize-1==top);
}
}
<file_sep>package ds.doublyLinkedList;
public class DoublyLinkedList {
private Node first;
private Node last;
public DoublyLinkedList(){
first =null;
last =null;
}
public boolean isEmpty(){
return first ==null;
}
public void insertFirst(int data){
Node newNode = new Node(data);
if(isEmpty()){
last = newNode;//if empty last will refer to the newNOde
}else{
first.previous=newNode;
newNode.next= first;//the new nodes next field will point to the old node
}
first=newNode;
}
public void insertLast(int data){
Node newNode =new Node(data);
if(isEmpty()){
first=newNode;
}else{
last.next=newNode;
newNode.previous=last;
}
last=newNode;
}
//assume that its a non empty list at this point
public Node deleteFirst(){
Node temp = first;
if(isEmpty()) return null;
if(first.next==null){//there is only one item in the list
last=null;
}else{
first.next.previous=null;
}
first=first.next;
return temp;//return deleted first node
}
//assume non empty list
public Node deleteLast(){
Node temp = last;
if(isEmpty()||first.next==null){
first=null;
last=null;
}else{
last=last.previous;
last.next=null;
}
return temp;
}
public boolean insertAfter(int after, int data){
Node current = first;
while(current.data!=after){
current=current.next;
if(current==null) return false;
}
Node newNode = new Node(data);
if(current==last){
current.next=newNode;
newNode.previous=current;
last=newNode;
return true;
}else {
newNode.next = current.next;
current.next.previous = newNode;
newNode.previous = current;
current.next = newNode;
return true;
}
}
public Node deleteKey(int key){
Node current = first;
while(current.data!=key){
current=current.next;
if(current==null) {
System.out.println("Value not found");
return null;
}
}
if(current==first){
first=current.next;
current.next.previous=null;
}
if(current==last){
last=current.previous;
current.previous.next=null;
}else {
current.previous.next = current.next;
current.next.previous = current.previous;
}
return current;
}
public void display(){
Node current = first;
while(current!=null){
System.out.print(current.data+" ");
current=current.next;
}
}
}
| 12b4d158070346e22b422513db628e419e04b8a2 | [
"Markdown",
"Java"
] | 10 | Java | conwabueze/DataStructurePractice | 3e419eacf6cc4534daa0ce6137258bec3728056a | dae90c5ec7bfc93ebf5e8cfed020856f6af2e8f7 |
refs/heads/master | <repo_name>thacypherbot/thacypherbot-main<file_sep>/functions/textRecordMessageAfterConfirmation.js
// This function is used to send a message embed that contains the recorded text Object.
// It shows the whole message on reaction with the note.
const Discord = require("discord.js");
const textRecordMessageAfterConfirmation = async function (
message,
textRecordObject,
foundRecords
) {
let textRecordMessage = new Discord.MessageEmbed().setTitle(
`Here is your recorded text.`
);
console.log(textRecordObject);
let smallPart = textRecordObject.text.slice(0, 40);
let contentString = `\`\`Channel\`\` : ${textRecordObject.channel} \n > \`\`Content\`\` : ${smallPart} [..read more](${textRecordObject.link})`;
function textRecordMsgFunction(textRecordMessage, contentString) {
textRecordMessage.setColor(`#00FFFF`);
textRecordMessage.setThumbnail(
`https://cdn.discordapp.com/attachments/748005515992498297/756111184226418738/pen.jpg?width=50&height=50`
);
textRecordMessage.setFooter(
`React with 🗒️ to read the whole verse. React with 🗑️ to delete the whole verse.`
);
textRecordMessage.addField(
`📌 ${textRecordObject.title}`,
` > \`\`Date\`\` : ${textRecordObject.date} \n > ${contentString}`
);
return textRecordMessage;
}
const reviewText = await message.author.send(
textRecordMsgFunction(textRecordMessage, contentString)
);
await reviewText.react(`🗒️`);
await reviewText.react(`🗑️`);
let filter = (reaction) => {
return ["🗒️", "🗑️"].includes(reaction.emoji.name);
};
let reviewReacts = await reviewText.awaitReactions(filter, {
max: 1,
time: 60000,
errors: ["time"],
});
console.log(reviewReacts.first().emoji.name);
if (reviewReacts.first().emoji.name === `🗒️`) {
let editedTextRecordMessage = new Discord.MessageEmbed().setTitle(
`Here is your recorded text.`
);
contentString = `\`\`Channel\`\` : ${textRecordObject.channel} \n > \`\`Content\`\` : \n ${textRecordObject.text}`;
await reviewText.edit(
textRecordMsgFunction(editedTextRecordMessage, contentString)
);
} else if (reviewReacts.first().emoji.name === `🗑️`) {
foundRecords.content.splice(
foundRecords.content.indexOf(textRecordObject),
1
);
foundRecords.markModified("content");
await foundRecords
.save()
.then((doc) => {
console.log(doc);
return message.author.send(`\`This verse was successfully deleted.\``);
})
.catch((err) => {
console.log(err);
});
}
};
module.exports = textRecordMessageAfterConfirmation;
<file_sep>/commands/rps.js
const Discord = require("discord.js");
exports.run = async (client, message, args) => {
const emojis = ["✊", "✋", "✌"],
hands = ["rock", "paper", "scissors"],
// 0: tie, 1: win, -1: lose
// | rock | paper | scissors
// rock | 0 | -1 | 1
// paper | 1 | 0 | -1
// scissors | -1 | 1 | 0
results = [
[0, -1, 1],
[1, 0, -1],
[-1, 1, 0],
];
const rpsEmbed = new Discord.MessageEmbed();
const timeoutEmbed = new Discord.MessageEmbed()
.setTitle("You took to long to reply!")
.setColor("#ff0000");
const wrongEmbed = new Discord.MessageEmbed()
.setTitle("Invalid usage of rps")
.setDescription("Use `rock/paper/scissors` or shorter `r/p/s`.")
.setColor("#ff0000");
let input = args[0],
tie = false,
botHand,
userHand,
result;
while (!tie) {
if (!hands.includes(input) && !hands.map((x) => x[0]).includes(input)) {
return await message.channel.send(wrongEmbed);
}
botHand = Math.round(Math.random() * (emojis.length - 1));
userHand = hands.map((x) => x[0]).indexOf(args[0][0]);
result = results[userHand][botHand];
if (result !== 0) {
tie = true;
break;
}
rpsEmbed
.setTitle("__Tie!__ 👔")
.setDescription(
`**${message.author}: ${emojis[userHand]} - ${emojis[botHand]} :${message.client.user}**\n\nPlease type \`r/p/s\` or \`rock/paper/scissors\` to continue!`
)
.setColor("#ffff00");
await message.channel.send(rpsEmbed);
const response = await message.channel
.awaitMessages((m) => m.author.id == message.author.id, {
max: 1,
time: 30000,
errors: ["time"],
})
.catch((collected) => null);
if (response == null) {
await message.channel.send(timeoutEmbed);
break;
}
input = response.first().content.toLowerCase();
}
if (!tie) return;
rpsEmbed
.setTitle("__You lose!__ ❌")
.setColor("#ff0000")
.setDescription(
`**${message.author}: ${emojis[userHand]} - ${emojis[botHand]} :${message.client.user}**`
);
if (result === 1) {
rpsEmbed.setTitle("__You win!__ ✅").setColor("#00ff00");
}
await message.channel.send(rpsEmbed);
};
exports.help = {
name: "rps",
};
<file_sep>/commands/reactor.js
const Discord = require("discord.js");
const Autor = require("../models/autoreactor.js");
const mongoose = require("mongoose");
let letters = [`🇦`, `🇧`, `🇨`, `🇩`, `🇪`, `🇫`, `🇬`, `🇭`, `🇮`];
exports.run = async (client, message, args) => {
// GETTING LIST OF CHANNELS---------------------------------------------------------------------------
const result = client.guilds.cache.flatMap((guild) => guild.channels.cache);
const rfilter = (x) => x.type === "text";
const filteredresult = result.filter(rfilter);
const finalchannellist = filteredresult.map((channel) => channel.name);
// ---------------------------------------------------------------------------------------------------
// CREATING EMBED AND SENDING IT---------------------------------------------------------------------------
let prop = [];
let statsReactionNumber;
const newReactor = new Autor();
newReactor.userid = message.author.id;
let createAndWait = async (
messageEmbed,
collectThisMsg,
collected,
messageEmbedObject
) => {
const msgFilter = (m) => m.author.id === message.author.id;
const reactfilter = (reaction, user) => {
return user.id === message.author.id;
};
messageEmbed = new Discord.MessageEmbed().setTitle(
messageEmbedObject.title
);
messageEmbed.addField(messageEmbedObject.topic, messageEmbedObject.text);
messageEmbed.setColor(messageEmbedObject.color);
messageEmbed.setThumbnail(messageEmbedObject.thumbnail);
collectThisMsg = await message.channel.send(messageEmbed);
if (messageEmbedObject.boolean) {
collected = await collectThisMsg.channel.awaitMessages(msgFilter, {
max: 1,
time: 200000,
});
if (messageEmbedObject.image) {
if (collected.first().attachments.first() === undefined) {
return undefined;
}
return collected.first().attachments.first().url;
}
return collected.first().content;
} else {
for (let emoji of messageEmbedObject.emojiArray) {
await collectThisMsg.react(emoji);
}
collected = await collectThisMsg.awaitReactions(reactfilter, {
max: 1,
time: 200000,
errors: ["time"],
});
return collected.first().emoji.name;
}
};
let messageEmbed;
let collectThisMsg;
let collected;
let messageEmbedObject = {
title: "Auto reactor and Polls",
topic: "Channel select",
text:
"Please enter the name of the channel you wish to initiate Auto Reactor/ Polls.",
color: "#9400D3",
thumbnail:
"https://cdn.discordapp.com/attachments/728671530459856896/728677723198980167/television.png",
boolean: true,
emojiArray: [],
};
messageEmbedObject.topic = "Auto reactor or Poll ?";
messageEmbedObject.text = "\n - ``1️`` - Auto Reactor \n - ``2`` - Poll";
messageEmbedObject.color = "#9400D3";
messageEmbedObject.thumbnail =
"https://cdn.discordapp.com/attachments/728671530459856896/728677723198980167/television.png";
messageEmbedObject.boolean = true;
let AutoOrPoll = await createAndWait(
messageEmbed,
collectThisMsg,
collected,
messageEmbedObject
);
let isPoll = AutoOrPoll === `2️`;
if (AutoOrPoll === "2") {
messageEmbedObject.topic = "Poll";
messageEmbedObject.text = "Please reply with poll topic";
messageEmbedObject.color = "#9400D3";
messageEmbedObject.thumbnail =
"https://media.discordapp.net/attachments/763795278079721482/765232054228090880/unknown.png";
messageEmbedObject.boolean = true;
let pollTopic = await createAndWait(
messageEmbed,
collectThisMsg,
collected,
messageEmbedObject
);
newReactor.pollTopic = pollTopic;
newReactor.isPoll = true;
prop.push(`\n - 📄 Poll Topic : ${pollTopic}`);
messageEmbedObject.topic = "Poll";
messageEmbedObject.text = "How many poll options do you want to add.";
messageEmbedObject.color = "#9400D3";
messageEmbedObject.thumbnail =
"https://media.discordapp.net/attachments/763795278079721482/765232054228090880/unknown.png";
let pollOptions = await createAndWait(
messageEmbed,
collectThisMsg,
collected,
messageEmbedObject
);
newReactor.optionsText = [];
newReactor.pollOptions = parseInt(pollOptions);
console.log(newReactor.pollOptions, `poll options`);
let optionText;
for (i = 0; i < newReactor.pollOptions; i++) {
messageEmbedObject.text = `Please enter option ${i + 1}`;
optionText = await createAndWait(
messageEmbed,
collectThisMsg,
collected,
messageEmbedObject
);
newReactor.optionsText.push({
text: optionText,
weights: 0,
votes: 0,
voterid: [],
voterNames: [],
emoji: letters[i],
percent: 0,
});
}
messageEmbedObject.topic = "Poll";
messageEmbedObject.text =
"Please reply with poll color \n [view applicable colors here](https://discord.js.org/#/docs/main/stable/typedef/ColorResolvable)";
messageEmbedObject.color = "#9400D3";
messageEmbedObject.thumbnail =
"https://media.discordapp.net/attachments/763795278079721482/765232054228090880/unknown.png";
let pollColor = await createAndWait(
messageEmbed,
collectThisMsg,
collected,
messageEmbedObject
);
newReactor.pollColor = pollColor.toUpperCase();
prop.push(`\n - 📄 Poll Color : ${pollColor}`);
messageEmbedObject.topic = "Poll";
messageEmbedObject.text =
"Please reply with the custom poll image \n if you don't want to set poll image please reply with ``no``";
messageEmbedObject.color = "#9400D3";
messageEmbedObject.image = true;
messageEmbedObject.thumbnail =
"https://media.discordapp.net/attachments/763795278079721482/765232054228090880/unknown.png";
let pollImageCheck = await createAndWait(
messageEmbed,
collectThisMsg,
collected,
messageEmbedObject
);
let pollImage = pollImageCheck === undefined ? false : pollImageCheck;
if (pollImage) {
newReactor.pollImage = pollImage;
console.log(newReactor.pollImage);
prop.push(`\n - 📄 Poll Image : [click to view image](${pollImage})`);
}
messageEmbedObject.image = false;
messageEmbedObject.topic = "Poll";
messageEmbedObject.text =
"Reply with ``yes`` for anonymous voting and ``no`` for public voting.";
messageEmbedObject.color = "#9400D3";
messageEmbedObject.thumbnail =
"https://media.discordapp.net/attachments/763795278079721482/765232054228090880/unknown.png";
let isAnon = await createAndWait(
messageEmbed,
collectThisMsg,
collected,
messageEmbedObject
);
newReactor.anon = isAnon === "yes";
if (newReactor.anon) {
newReactor.hasEnded = false;
}
prop.push(`\n - 📄 Anonymous voting : ${isAnon}`);
messageEmbedObject.topic = "What roles should have access to the poll";
let roleObject = {
Everyone: "1",
"New Heads": "2",
Heads: "3",
"Old Heads": "4",
Supporter: "5",
};
messageEmbedObject.text =
"1️ - Everyone \n 2️ - New Heads - ``Crowd, prospect, fan`` \n 3️ - Heads - ``Enthusiast, challenger, regular`` \n 4 - Old Heads - ``active, pro, vet, titan, legend`` \n 5 - Supporter";
messageEmbedObject.color = "#9400D3";
messageEmbedObject.thumbnail =
"https://media.discordapp.net/attachments/763795278079721482/765232054228090880/unknown.png";
messageEmbedObject.boolean = true;
let pollRole = await createAndWait(
messageEmbed,
collectThisMsg,
collected,
messageEmbedObject
);
if (pollRole === "1") {
newReactor.pollRole = "oneRoleArray";
prop.push(`\n - 📄 Poll Roles : Everyone`);
} else if (pollRole === "2") {
newReactor.pollRole = "twoRoleArray";
prop.push(`\n - 📄 Poll Roles : New Heads`);
} else if (pollRole === "3") {
newReactor.pollRole = "threeRoleArray";
prop.push(`\n - 📄 Poll Roles : Heads`);
} else if (pollRole === "4") {
newReactor.pollRole = "fourRoleArray";
prop.push(`\n - 📄 Poll Roles : Old Heads`);
} else if (pollRole === "5") {
newReactor.pollRole = "fiveRoleArray";
prop.push(`\n - 📄 Poll Roles : Supporter`);
} else {
newReactor.pollRole = "oneRoleArray";
prop.push(`\n - 📄 Poll Roles : Everyone`);
}
newReactor.totalVotes = 0;
}
messageEmbedObject.topic = "Triggers";
messageEmbedObject.text =
"Do you want enable stat point condition \n ``1`` - Yes \n ``2`` - No";
messageEmbedObject.color = "#9400D3";
messageEmbedObject.thumbnail =
"https://cdn.discordapp.com/attachments/728671530459856896/728680050295046214/bible.png";
messageEmbedObject.boolean = true;
const triggerOneEmoji = await createAndWait(
messageEmbed,
collectThisMsg,
collected,
messageEmbedObject
);
if (triggerOneEmoji === "1") {
prop.push(`\n - 📄 Stat point : yes`);
messageEmbedObject.topic = "Trigger options";
messageEmbedObject.text =
"Please enter the number of reactions after which the stats are to be stored.";
messageEmbedObject.color = "#9400D3";
messageEmbedObject.thumbnail =
"https://cdn.discordapp.com/attachments/728671530459856896/728680050295046214/bible.png";
messageEmbedObject.boolean = true;
statsReactionNumber = await createAndWait(
messageEmbed,
collectThisMsg,
collected,
messageEmbedObject
);
console.log(statsReactionNumber);
prop.push(`\n - 📄 Store stats at : ${statsReactionNumber} reactions`);
console.log(parseInt(statsReactionNumber), `statsReactionNumber AYEEE`);
newReactor.statsReactionNumber = parseInt(statsReactionNumber);
console.log(newReactor, `statsReacNumber`);
}
if (!newReactor.isPoll) {
messageEmbedObject.topic = "Triggers";
messageEmbedObject.text =
"Do you want to end reaction collector on a post by reacting with a certain emoji \n ``1`` - Yes \n ``2`` - No";
messageEmbedObject.color = "#9400D3";
messageEmbedObject.thumbnail =
"https://cdn.discordapp.com/attachments/728671530459856896/728680480559595630/love.png";
messageEmbedObject.boolean = true;
const triggerTwoEmoji = await createAndWait(
messageEmbed,
collectThisMsg,
collected,
messageEmbedObject
);
console.log(triggerTwoEmoji);
prop.push(`\n - 📊 End reaction with Emoji : ${triggerTwoEmoji}`);
if (triggerTwoEmoji === "1") {
messageEmbedObject.topic = "Trigger options";
messageEmbedObject.text =
"Please react this message with the reaction you would want to trigger this action";
messageEmbedObject.color = "#9400D3";
messageEmbedObject.thumbnail =
"https://cdn.discordapp.com/attachments/728671530459856896/728680480559595630/love.png";
messageEmbedObject.boolean = false;
messageEmbedObject.emojiArray = [];
let triggerTwoEmoji = await createAndWait(
messageEmbed,
collectThisMsg,
collected,
messageEmbedObject
);
console.log(triggerTwoEmoji);
prop.push(`\n - 📊 End reaction Emoji : ${triggerTwoEmoji}`);
newReactor.endReactionEmoji = triggerTwoEmoji;
}
messageEmbedObject.topic = "Trigger";
messageEmbedObject.text =
"Do you want to end reaction collector on a post after a certain reactions are reached \n ``1`` - Yes \n ``2`` - No";
messageEmbedObject.color = "#9400D3";
messageEmbedObject.thumbnail =
"https://cdn.discordapp.com/attachments/728671530459856896/728680480559595630/love.png";
messageEmbedObject.boolean = true;
const triggerThreeEmoji = await createAndWait(
messageEmbed,
collectThisMsg,
collected,
messageEmbedObject
);
console.log(triggerThreeEmoji);
prop.push(`\n - 🎬 End reaction after some cap : ${triggerThreeEmoji}`);
if (triggerThreeEmoji === "1") {
messageEmbedObject.topic = "Trigger options";
messageEmbedObject.text =
"Please enter the number of reactions to trigger this action";
messageEmbedObject.color = "#9400D3";
messageEmbedObject.thumbnail =
"https://media.discordapp.net/attachments/728671530459856896/728681225971171389/kindness.png";
messageEmbedObject.boolean = true;
triggerThreeStatsMsgCollector = await createAndWait(
messageEmbed,
collectThisMsg,
collected,
messageEmbedObject
);
console.log(triggerThreeStatsMsgCollector);
prop.push(
`\n - 🎬 End reaction after cap : ${triggerThreeStatsMsgCollector}`
);
console.log(
parseInt(triggerThreeStatsMsgCollector),
`endReactionNumber HERE`
);
newReactor.endReactionNumber = parseInt(triggerThreeStatsMsgCollector);
console.log(newReactor, `endReacNumber`);
}
messageEmbedObject.topic = "Reaction options";
messageEmbedObject.text =
"Do you want to add custom emojis or select from the presets \n ``1`` - Custom \n ``2`` - Preset";
messageEmbedObject.color = "#9400D3";
messageEmbedObject.thumbnail =
"https://cdn.discordapp.com/attachments/728671530459856896/728677723198980167/television.png";
messageEmbedObject.boolean = true;
let reactCusOrPreMsgEmoji = await createAndWait(
messageEmbed,
collectThisMsg,
collected,
messageEmbedObject
);
prop.push(`\n - 📄 Reaction options : ${reactCusOrPreMsgEmoji}`);
if (reactCusOrPreMsgEmoji === "2") {
messageEmbedObject.topic = "Please choose one of the preset options";
messageEmbedObject.text =
"1 - ``✅`` - ``❎`` \n 2 - ``👍`` - ``🤐`` - `` 👎 `` \n 3 - ``😍`` - ``👍`` - ``🤐`` - `` 👎 `` - ``🤢``";
messageEmbedObject.color = "#9400D3";
messageEmbedObject.thumbnail =
"https://cdn.discordapp.com/attachments/728671530459856896/728679330095300628/donate.png";
messageEmbedObject.boolean = true;
const finalPreset = await createAndWait(
messageEmbed,
collectThisMsg,
collected,
messageEmbedObject
);
console.log(
typeof finalPreset,
finalPreset,
"is finalPreset === to 1 ? :",
finalPreset === "3"
);
if (finalPreset === "1") {
console.log(`WE ENTERED!`);
const presetEmojis1 = `✅ - ❎`;
prop.push(`\n - 📄 Preset emojis : ${presetEmojis1}`);
newReactor.emojis.push(`✅`);
newReactor.emojis.push(`❎`);
} else if (finalPreset === "2") {
const presetEmojis2 = `👍 - 🤐 - 👎`;
prop.push(`\n - 📄 Preset emojis : ${presetEmojis2}`);
newReactor.emojis.push(`👍`);
newReactor.emojis.push(`🤐`);
newReactor.emojis.push(`👎`);
} else if (finalPreset === "3") {
console.log(`third one`);
const presetEmojis3 = `😍 - 👍 - 👎 - 🤐 - 🤢`;
prop.push(`\n - 📄 Preset emojis : ${presetEmojis3}`);
newReactor.emojis.push(`😍`);
newReactor.emojis.push(`👍`);
newReactor.emojis.push(`👎`);
newReactor.emojis.push(`🤐`);
newReactor.emojis.push(`🤢`);
}
newReactor.markModified("emojis");
}
console.log(newReactor.emojis);
if (reactCusOrPreMsgEmoji === "1") {
messageEmbedObject.topic = "Reactions to be done";
messageEmbedObject.text =
"Please select the number of reactions you want to be reacted on the messages. \n ``MINIMUM : 2``";
messageEmbedObject.color = "#9400D3";
messageEmbedObject.thumbnail =
"https://cdn.discordapp.com/attachments/728671530459856896/728679330095300628/donate.png";
messageEmbedObject.boolean = true;
finalNum = await createAndWait(
messageEmbed,
collectThisMsg,
collected,
messageEmbedObject
);
const finalNum1 = parseInt(finalNum);
console.log(finalNum1, `final num 1 here`);
const afilter = (reaction, user) => {
return user.id === message.author.id;
};
if (finalNum1 === 2) {
const reactionSelect = new Discord.MessageEmbed().setTitle(
"Auto reactions creator"
);
reactionSelect.addField(
`Reactions to be done`,
`Please react with the reactions you would like to be done `
);
reactionSelect.setColor(`#9400D3`);
reactionSelect.setThumbnail(
`https://cdn.discordapp.com/attachments/728671530459856896/728679330095300628/donate.png`
);
const reactSelectmsg = await message.channel.send(reactionSelect);
reactSelectmsg.react(`⬆️`);
reactSelectmsg.react(`⬇️`);
const [reactionOne, reactionTwo] = (
await reactSelectmsg.awaitReactions(afilter, {
max: finalNum,
time: 200000,
errors: ["time"],
})
).first(2);
console.log(reactionOne.emoji.name);
console.log(reactionTwo.emoji.name);
prop.push(
`\n - 🛡️ Custom emojis : ${reactionOne.emoji.name} - ${reactionTwo.emoji.name}`
);
newReactor.emojis.push(reactionOne.emoji.name);
newReactor.emojis.push(reactionTwo.emoji.name);
}
//----------------------------
if (finalNum1 === 3) {
const reactionSelect = new Discord.MessageEmbed().setTitle(
"Auto reactions creator"
);
reactionSelect.addField(
`Reactions to be done`,
`Please react with the reactions you would like to be done `
);
reactionSelect.setColor(`#9400D3`);
reactionSelect.setThumbnail(
`https://cdn.discordapp.com/attachments/728671530459856896/728679330095300628/donate.png`
);
const reactSelectmsg = await message.channel.send(reactionSelect);
const [reactionOne, reactionTwo, reactionThree] = (
await reactSelectmsg.awaitReactions(afilter, {
max: finalNum,
time: 200000,
errors: ["time"],
})
).first(3);
reactionFinalOne = reactionOne.emoji.name;
reactionFinalTwo = reactionTwo.emoji.name;
reactionFinalThree = reactionThree.emoji.name;
prop.push(
`\n - 🛡️ Custom emojis : ${reactionFinalOne} - ${reactionFinalTwo} - ${reactionFinalThree}`
);
newReactor.emojis.push(reactionFinalOne);
newReactor.emojis.push(reactionFinalTwo);
newReactor.emojis.push(reactionFinalThree);
}
if (finalNum1 === 4) {
const reactionSelect = new Discord.MessageEmbed().setTitle(
"Auto reactions creator"
);
reactionSelect.addField(
`Reactions to be done`,
`Please react with the reactions you would like to be done`
);
reactionSelect.setColor(`#9400D3`);
reactionSelect.setThumbnail(
`https://cdn.discordapp.com/attachments/728671530459856896/728679330095300628/donate.png`
);
const reactSelectmsg = await message.channel.send(reactionSelect);
const [reactionOne, reactionTwo, reactionThree, reactionFour] = (
await reactSelectmsg.awaitReactions(afilter, {
max: finalNum,
time: 200000,
errors: ["time"],
})
).first(4);
reactionFinalOne = reactionOne.emoji.name;
reactionFinalTwo = reactionTwo.emoji.name;
reactionFinalThree = reactionThree.emoji.name;
reactionFinalFour = reactionFour.emoji.name;
prop.push(
`\n - 🛡️ Custom emojis : ${reactionFinalOne} - ${reactionFinalTwo} - ${reactionFinalThree} - ${reactionFinalFour}`
);
newReactor.emojis.push(reactionFinalOne);
newReactor.emojis.push(reactionFinalTwo);
newReactor.emojis.push(reactionFinalThree);
newReactor.emojis.push(reactionFinalFour);
}
if (finalNum1 === 5) {
const reactionSelect = new Discord.MessageEmbed().setTitle(
"Auto reactions creator"
);
reactionSelect.addField(
`Reactions to be done`,
`Please react with the reactions you would like to be donee `
);
reactionSelect.setColor(`#9400D3`);
reactionSelect.setThumbnail(
`https://cdn.discordapp.com/attachments/728671530459856896/728679330095300628/donate.png`
);
const reactSelectmsg = await message.channel.send(reactionSelect);
const [reactionOne, reactionTwo, reactionThree, reactionFour] = (
await reactSelectmsg.awaitReactions(afilter, {
max: finalNum,
time: 200000,
errors: ["time"],
})
).first(5);
reactionFinalOne = reactionOne.emoji.name;
reactionFinalTwo = reactionTwo.emoji.name;
reactionFinalThree = reactionThree.emoji.name;
reactionFinalFour = reactionFour.emoji.name;
reactionFinalFive = reactionFive.emoji.name;
prop.push(
`\n - 🛡️ Custom emojis : ${reactionFinalOne} - ${reactionFinalTwo} - ${reactionFinalThree} - ${reactionFinalFour} - ${reactionFinalFive}`
);
newReactor.emojis.push(reactionFinalOne);
newReactor.emojis.push(reactionFinalTwo);
newReactor.emojis.push(reactionFinalThree);
newReactor.emojis.push(reactionFinalFour);
newReactor.emojis.push(reactionFinalFive);
}
newReactor.markModified(`emojis`);
}
// messageEmbedObject.topic = "Triggers";
// messageEmbedObject.text =
// "Do you want to Dm Admin/Owner roles on a particular stats trigger ?";
// messageEmbedObject.color = "#9400D3";
// messageEmbedObject.thumbnail =
// "https://media.discordapp.net/attachments/728671530459856896/728682672615850135/person.png";
// messageEmbedObject.boolean = false;
// messageEmbedObject.emojiArray = [`✅`, `❎`];
// const triggerFiveEmoji = await createAndWait(
// messageEmbed,
// collectThisMsg,
// collected,
// messageEmbedObject
// );
// console.log(triggerFiveEmoji);
// prop.push(`\n - 👥 Dm Admin / Owner : ${triggerFiveEmoji}`);
// if (triggerFiveEmoji === `✅`) {
// messageEmbedObject.topic = "Trigger options";
// messageEmbedObject.text =
// "Please Select which role \n ***1 - Admin \n 2 - Owner***";
// messageEmbedObject.color = "#9400D3";
// messageEmbedObject.thumbnail =
// "https://media.discordapp.net/attachments/728671530459856896/728682672615850135/person.png";
// messageEmbedObject.boolean = false;
// messageEmbedObject.emojiArray = ["1️⃣", "2️⃣"];
// let triggerFiveStatsMsgCollector = await createAndWait(
// messageEmbed,
// collectThisMsg,
// collected,
// messageEmbedObject
// );
// console.log(triggerFiveStatsMsgCollector);
// if (triggerFiveStatsMsgCollector === `1️⃣`) {
// finalPush = "Admin";
// }
// if (triggerFiveStatsMsgCollector === `2️⃣`) {
// finalPush = "Owner";
// }
// console.log(finalPush);
// prop.push(`\n - 👥 Role to Dm : ${finalPush}`);
// newReactor.role = finalPush;
// }
// if (triggerFiveEmoji === `✅`) {
// messageEmbedObject.topic = "Trigger";
// messageEmbedObject.text =
// "Set the reaction number trigger for the same please.";
// messageEmbedObject.color = "#9400D3";
// messageEmbedObject.thumbnail =
// "https://media.discordapp.net/attachments/728671530459856896/728683187735101516/mail.png";
// messageEmbedObject.boolean = true;
// const triggerFiveOptB = await createAndWait(
// messageEmbed,
// collectThisMsg,
// collected,
// messageEmbedObject
// );
// console.log(triggerFiveOptB);
// prop.push(`\n - 🔔 Dm stats reaction number : ${triggerFiveOptB}`);
// newReactor.notify = triggerFiveOptB;
// }
// messageEmbedObject.topic = "Triggers";
// messageEmbedObject.text =
// "Do you want to add a +rep to the author of the message on every upvote";
// messageEmbedObject.color = "#9400D3";
// messageEmbedObject.thumbnail =
// "https://media.discordapp.net/attachments/728671530459856896/728683970371387512/thumbs-up.png";
// messageEmbedObject.boolean = false;
// messageEmbedObject.emojiArray = [`✅`, `❎`];
// const triggerSevenEmoji = await createAndWait(
// messageEmbed,
// collectThisMsg,
// collected,
// messageEmbedObject
// );
// console.log(triggerSevenEmoji);
// prop.push(`\n - ⏫ Add + rep : ${triggerSevenEmoji}`);
// if (triggerSevenEmoji === `✅`) {
// newReactor.rep === `yes`;
// }
}
// messageEmbedObject.topic = "Triggers";
// messageEmbedObject.text =
// "Do you want to end reaction collector on a post after certain amount of time ";
// messageEmbedObject.color = "#9400D3";
// messageEmbedObject.thumbnail =
// "https://cdn.discordapp.com/attachments/728671530459856896/728681875991822366/time.png";
// messageEmbedObject.boolean = false;
// messageEmbedObject.emojiArray = [`✅`, `❎`];
// const triggerFourEmoji = await createAndWait(
// messageEmbed,
// collectThisMsg,
// collected,
// messageEmbedObject
// );
// console.log(triggerFourEmoji);
// prop.push(`\n - ⏲️ End reaction after some time : ${triggerFourEmoji}`);
// if (triggerFourEmoji === `✅`) {
// messageEmbedObject.topic = "Trigger options";
// messageEmbedObject.text =
// "Please enter the time in ``HOURS`` to trigger this action";
// messageEmbedObject.color = "#9400D3";
// messageEmbedObject.thumbnail =
// "https://cdn.discordapp.com/attachments/728671530459856896/728681875991822366/time.png";
// messageEmbedObject.boolean = true;
// let triggerFourStatsMsgCollector = await createAndWait(
// messageEmbed,
// collectThisMsg,
// collected,
// messageEmbedObject
// );
// console.log(triggerFourStatsMsgCollector);
// prop.push(
// `\n - ⏲️ End reaction after time : ${triggerFourStatsMsgCollector}`
// );
// newReactor.endReactionTime =
// parseInt(triggerFourStatsMsgCollector) * 3600000;
// }
newReactor.id = Math.random().toString(20).substr(2, 6);
const confirmationEmbed = new Discord.MessageEmbed()
.setColor("#E0FFFF")
.setTitle(
`Here are you AutoReact/Poll Details \n
\`\`ID: ${newReactor.id} \`\``
)
.setThumbnail(
"https://cdn.discordapp.com/attachments/728671530459856896/728686591526174760/rocket.png"
)
.addFields({
name: "Properties ",
value: prop,
});
console.log(newReactor);
await newReactor.save();
message.channel.send(confirmationEmbed);
};
exports.help = {
name: "ar",
};
<file_sep>/models/textrecords.js
const mongoose = require("mongoose");
const autoSchema = mongoose.Schema({
userid: String,
content : [{type: Object}]
});
module.exports = mongoose.model("TextRecords", autoSchema);<file_sep>/commands/stopreactor.js
const Discord = require("discord.js");
const Autor = require("../models/autoreactor.js");
const mongoose = require("mongoose");
const progressBar = require("../functions/bar.js");
let letters = [`🇦`, `🇧`, `🇨`, `🇩`, `🇪`, `🇫`, `🇬`, `🇭`, `🇮`];
exports.run = async (client, message, args) => {
let foundReactor = await Autor.findOne({ id: args[0] }).catch((err) => {
console.log(err);
return message.channel.send(`An error occured, please try again.`);
});
if (foundReactor.isRunning) {
foundReactor.isRunning = false;
foundReactor.markModified(`isRunning`);
await foundReactor.save().catch((error) => console.log(error));
if (foundReactor.anon) {
let updatedDoc = await Autor.findOne({ id: args[0] }).catch((err) => {
return message.channel.send(
"No saved reactors found. Please create a reactor using ``$reactor``"
);
});
fetchedChannel = await client.channels
.fetch(updatedDoc.reactorSettings.channel)
.catch((err) => {
console.log(err);
});
fetchedMessage = await fetchedChannel.messages
.fetch(updatedDoc.reactorSettings.messageId)
.catch((err) => {
console.log(err);
});
let embedObject = fetchedMessage.embeds[0];
updatedDoc.isRunning = false;
for (i = 0; i < updatedDoc.optionsText.length; i++) {
delete embedObject.fields[i];
}
let optionString = ``;
let k = 0;
for (let foo of updatedDoc.optionsText) {
optionString += `\n ${letters[k++]} ***${foo.text}*** \n ${progressBar(
foo.percent,
100,
10
)}`;
}
embedObject.setDescription(
optionString + `\n 📩 Total Votes : ${updatedDoc.grandTotal.length}`
);
embedObject.setFooter(`The poll has ended`);
fetchedMessage.edit(embedObject);
await updatedDoc.save().catch((err) => console.log(err));
}
return message.channel.send(`\`\`Reactor successfully terminated !\`\``);
}
};
exports.help = {
name: "endreactor",
};
<file_sep>/models/polldata.js
const mongoose = require("mongoose");
const autoSchema = mongoose.Schema({
pollid: String,
voters: [{type: Object}],
pollCount: [{type: Object}]
});
module.exports = mongoose.model("PollData", autoSchema);
<file_sep>/models/profile.js
const mongoose = require("mongoose");
const autoSchema = mongoose.Schema({
userid: String,
coins: Number,
bets: Number,
});
module.exports = mongoose.model("Profile", autoSchema);
<file_sep>/functions/newDate.js
const newDate = function(){
let date = new Date();
let dd = String(date.getDate()).padStart(2, '0');
let mm = String(date.getMonth() + 1).padStart(2, '0');
let yyyy = date.getFullYear();
return mm + '/' + dd + '/' + yyyy;
}
module.exports = newDate<file_sep>/models/settext.js
const mongoose = require("mongoose");
const autoSchema = mongoose.Schema({
guildid: String,
channels : [{type: String}]
});
module.exports = mongoose.model("SetText", autoSchema);<file_sep>/commands/serverrecordings.js
const Discord = require("discord.js");
const ServerRecords = require("../models/serverrecords.js")
const hasRole = require("../functions/hasRole.js")
const mongoose = require("mongoose");
const Pagination = require('discord-paginationembed');
exports.run = async (client, message, args) => {
if(!hasRole(message)) return
const foundUser = await ServerRecords.findOne({userid: `server`});
console.log(foundUser)
let recordingsArray = []
foundUser.content.forEach((doc, i) => {
recordingsArray.push(`\`${i+1}\` 📌 ${doc.note} \n > \`\`Date\`\` : ${doc.date} \n > \`\`Peronal\`\` : [Click here to download it](${doc.personalLink}) \n > \`\`General\`\` : [Click here to download it](${doc.generalLink}) \n > \`\`Time\`\` : ${doc.time} \n - \n`)
})
let theMsgThatWasDmed = await message.author
const FieldsEmbed = new Pagination.FieldsEmbed()
// A must: an array to paginate, can be an array of any type
.setArray(recordingsArray)
// Set users who can only interact with the instance. Default: `[]` (everyone can interact).
// If there is only 1 user, you may omit the Array literal.
.setAuthorizedUsers([message.author.id])
// A must: sets the channel where to send the embed
.setChannel(theMsgThatWasDmed)
// Elements to show per page. Default: 10 elements per page
.setElementsPerPage(3)
// Have a page indicator (shown on message content). Default: false
.setPageIndicator(false)
// Format based on the array, in this case we're formatting the page based on each object's `word` property
.formatField('\u200b', el => el);
FieldsEmbed.embed
.setColor(0xFF00AE)
FieldsEmbed.build();
const recordsEmbed = new Discord.MessageEmbed().setTitle(`🗒️ Add notes`)
recordsEmbed.addField(`You can add notes to any of these recordings`, `Reply with the recording number to add a note. You have 30 seconds.`)
recordsEmbed.setThumbnail(`https://i.imgur.com/EvIGx9d.png`)
recordsEmbed.setColor(`#FFC0CB`)
const recordsMessage = await message.author.send(recordsEmbed)
const msgFilter = m => m.author.id === message.author.id;
const collected = await recordsMessage.channel.awaitMessages(msgFilter, {
max: 1,
time: 20000
})
let theNumber = collected.first().content
// if(Number.isInteger(theNumber) === false){
// message.author.send(`**You can only reply with a recording number. Please try again later.**`)
// return
// }
console.log(theNumber);
let theInt = parseInt(theNumber)
if(Number.isInteger(theInt) === false){
message.channel.send(`**You can only reply with a recording number. Please try again later.**`)
return
}
if(foundUser.content[theInt-1].note === undefined){
message.author.send(`❌ Opps something went wrong. Note not saved. please try again later !`)
return
}
let selectedRecord = foundUser.content[theInt-1]
console.log(selectedRecord, `doc`);
const noteReader = new Discord.MessageEmbed().setTitle(`Reply with the note you would want to add or say \`cancel\` to exit out `)
noteReader.addField(`Your recodings`, `**Title** : ${selectedRecord.note} \n **Date** : ${selectedRecord.date} \n **General** : [Click here to download it](${selectedRecord.generalLink}) \n **Time spent by you** : ${selectedRecord.time}`)
noteReader.setThumbnail(`https://i.imgur.com/4xD6FOm.png`)
noteReader.setColor(`#FFC0CB`)
const noteCollection = await message.author.send(noteReader)
const collectedNote = await noteCollection.channel.awaitMessages(msgFilter, {
max: 1,
time: 30000
})
let theNote = collectedNote.first().content
if(theNote === `cancel`){
message.author.send(`Session Cancelled.`)
return
}
console.log(theNote, `note here`);
addNoteToThisUser = await ServerRecords.findOne({userid: `server`})
addNoteToThisUser.content[theNumber-1].note = theNote
addNoteToThisUser.markModified(`content`)
addNoteToThisUser.save().then(() => {
let noteStatus = new Discord.MessageEmbed().setTitle(`Note`)
noteStatus.addField(`Saved`, `Title succesfully saved !`)
noteStatus.setColor(`#32CD32`)
noteStatus.setThumbnail(`https://i.imgur.com/ACh4QGC.png`)
message.author.send(noteStatus)
}).catch(err => {
message.author.send(`❌ Opps something went wrong. Note not saved. please try again later !`)
console.log(err)})
// console.log(addNoteToThisUser.content[theNumber], `here is the note`);
}
exports.help = {
name: "serverrecordings"
};
<file_sep>/index.js
const Discord = require("discord.js");
const client = new Discord.Client({
partials: ["MESSAGE", "CHANNEL", "REACTION", "USER"],
});
const schedule = require("node-schedule");
const ffmpegInstaller = require("@ffmpeg-installer/ffmpeg");
const ffmpeg = require("fluent-ffmpeg");
ffmpeg.setFfmpegPath(ffmpegInstaller.path);
const fs = require("fs-extra");
const mergeStream = require("merge-stream");
const { getAudioDurationInSeconds } = require("get-audio-duration");
const Enmap = require("enmap");
const UserRecords = require("./models/userrecords.js");
const ServerRecords = require("./models/serverrecords.js");
const TextRecords = require("./models/textrecords.js");
const SetText = require("./models/settext.js");
const progressBar = require("./functions/bar.js");
const Autor = require("./models/autoreactor.js");
const ReactorProfile = require("./models/reactorprofile.js");
const PersonalProfile = require("./models/personalprofile.js");
const hasRole = require("./functions/hasRole.js");
const textRecordMessageAfterConfirmation = require("./functions/textRecordMessageAfterConfirmation.js");
let prefix = `!`;
class Readable extends require("stream").Readable {
_read() {}
}
let recording = false;
let processing = false;
let progressTarget;
let progressPercent;
let currently_recording = {};
let mp3Paths = [];
let collectedTitle;
const silence_buffer = new Uint8Array(3840);
const express = require("express");
const app = express();
const port = 3333;
const publicIP = require("public-ip");
const { program } = require("commander");
const version = "0.0.1";
program.version(version);
let debug = false;
let runProd = true;
let fqdn = "";
let type = {};
const mongoose = require("mongoose");
const { time } = require("console");
const { title } = require("process");
mongoose.connect(
"mongodb+srv://admin:admin@cluster0.3iec5.gcp.mongodb.net/AR?retryWrites=true&w=majority",
{
useNewUrlParser: true,
},
function (err) {
if (err) {
console.log(err);
} else {
console.log("Database connection initiated");
}
}
);
require("dotenv").config();
function bufferToStream(buffer) {
let stream = new Readable();
stream.push(buffer);
return stream;
}
client.commands = new Enmap();
let foundReactor;
let theReactor;
client.on("ready", async () => {
console.log(`Logged in as ${client.user.tag}`);
let host = "localhost";
let ip = await publicIP.v4();
let protocol = "http";
if (!runProd) {
host = "localhost";
} else {
host = `192.168.3.11`;
}
fqdn = `${protocol}://${host}:${port}`;
app.listen(port, `0.0.0.0`, () => {
console.log(`Listening on port ${port} for ${host} at fqdn ${fqdn}`);
});
});
let randomArr = [];
let finalArrWithIds = [];
function getFileName() {
let today = new Date();
let dd = today.getDate();
let mm = today.getMonth() + 1;
let yyyy = today.getFullYear();
if (dd < 10) dd = "0" + dd;
if (mm < 10) mm = "0" + mm;
return yyyy + "-" + mm + "-" + dd;
}
function getTimeNow() {
let today = new Date();
let hours = today.getHours();
let minutes = today.getMinutes();
let seconds = today.getSeconds();
let mili = today.getMilliseconds();
let finalString = `${hours}${minutes}${seconds}${mili}`;
return finalString.slice(8, 9);
}
async function textRecordConfirmation(message, date) {
const msgFilter = (m) => {
let title = m.content.replace(/\s/g, "");
if (m.author.id !== message.author.id) return false;
if (title.length > 25) {
message.author.send(
`The title is longer than 25 characters, please try again.`
);
return false;
} else {
return true;
}
};
let textRecordTitle = new Discord.MessageEmbed().setTitle(
`🎐 Lets give your masterpiece a title.`
);
textRecordTitle.setDescription(
`Please reply to this message with a title no more than 25 characters. You have 5 minutes. \n If you don't wish to save this verse, reply with \`\`delete\`\``
);
textRecordTitle.setThumbnail(
`https://media.discordapp.net/attachments/748005515992498297/756094502535692338/title.png?width=100&height=100`
);
textRecordTitle.setFooter(
`🔺 If you fail to reply with a title, it will be set to ${date} by default`
);
textRecordTitle.setColor(`#00FFFF`);
let textRecordTitleMessage = await message.author.send(textRecordTitle);
let textRecordTitleMessageCollector = await textRecordTitleMessage.channel.awaitMessages(
msgFilter,
{
max: 1,
time: 30000,
}
);
if (textRecordTitleMessageCollector.first().content === "delete")
return false;
return textRecordTitleMessageCollector.first()
? textRecordTitleMessageCollector.first().content
: date;
}
const generateSilentData = async (silentStream, memberID) => {
console.log(`recordingnow`);
while (recording) {
if (!currently_recording[memberID]) {
silentStream.push(silence_buffer);
}
await new Promise((r) => setTimeout(r, 20));
}
return "done";
};
if (!fs.existsSync("public")) {
fs.mkdirSync("public");
}
app.use("/public", express.static("./public"));
let selectedProfile;
let personProfile;
let exists;
client.on("message", async (message) => {
if (message.author.bot) return;
let collectedEmojis = 0;
let reactedArray = [];
const args = message.content.slice(prefix.length).trim().split(/ +/g);
// TEXT RECORDING START
foundReactor = await Autor.find();
for (theReactor of foundReactor) {
if (!theReactor.isRunning || theReactor.isPoll) continue;
if (message.channel.id === theReactor.reactorSettings.channel) {
selectedProfile = new ReactorProfile();
exists = await PersonalProfile.exists({ userid: message.author.id });
console.log(exists);
if (exists) {
personProfile = await PersonalProfile.findOne({
userid: message.author.id,
});
} else {
console.log("person profile not found");
personProfile = new PersonalProfile();
personProfile.userid = message.author.id;
}
selectedProfile.userid = message.author.id;
selectedProfile.messageid = message.id;
selectedProfile.stillRunning = true;
selectedProfile.totalVotes = 0;
for (emojiToBeReacted of theReactor.emojis) {
message.react(emojiToBeReacted);
if (
!personProfile.emojiData.some(
(item) => item.emojiName === emojiToBeReacted
)
) {
personProfile.emojiData.push({
emojiName: emojiToBeReacted,
count: 0,
});
}
selectedProfile.emojiData.push({
emojiName: emojiToBeReacted,
count: 0,
});
}
selectedProfile.markModified(`emojiData`);
selectedProfile.save().catch((err) => console.log(err));
personProfile.markModified(`emojiData`);
personProfile.save().catch((err) => console.log(err));
}
}
const guildID = message.guild ? message.guild.id : console.log(`NO`);
const foundGuild = await SetText.findOne({ guildid: guildID });
if (
message.content.split(/\r\n|\r|\n/).length > 4 &&
foundGuild.channels.includes(message.channel.id)
) {
console.log(`hello`);
console.log(message.url);
let textRecordObject = {};
let date = getFileName();
let messageUrl = message.url;
let checkingTextRecord = await TextRecords.exists({
userid: message.author.id,
});
if (checkingTextRecord) {
existingTextRecord = await TextRecords.findOne({
userid: message.author.id,
});
textRecordObject = {
date: date,
title: ``,
channel: message.channel.name,
text: message.content,
link: messageUrl,
};
textRecordObject.title = await textRecordConfirmation(message, date);
if (!textRecordObject.title) {
return message.author.send(`\`\`The verse was deleted\`\``);
}
existingTextRecord.content.push(textRecordObject);
existingTextRecord
.save()
.then(async () => {
console.log(`saved existing`);
await textRecordMessageAfterConfirmation(message, textRecordObject);
})
.catch((err) => {
console.log(err);
});
} else if (!checkingTextRecord) {
let newTextRecord = new TextRecords();
textRecordObject = {
date: date,
title: ``,
channel: message.channel.name,
text: message.content,
link: messageUrl,
};
newTextRecord.userid = message.author.id;
textRecordObject.title = await textRecordConfirmation(message, date);
if (!textRecordObject.title) {
return message.author.send(`\`\`The verse was deleted\`\``);
}
newTextRecord.content.push(textRecordObject);
newTextRecord
.save()
.then(async () => {
console.log(`saved`);
await textRecordMessageAfterConfirmation(message, textRecordObject);
})
.catch((err) => {
console.log(err);
});
}
// TEXT RECORDING STOP
}
let locked = false;
if (!message.guild) return;
console.log(message.content);
if (message.content === `${prefix}record`) {
console.log(hasRole(message, "Admins"), `checking role`);
if (!hasRole(message, "Admins")) return;
if (processing)
return await message.channel.send(
`You cannot start a new recording while there is one processing.`
);
mp3Paths = [];
console.log(message.content);
finalArrWithIds = [];
if (args[1] === "lock") {
locked = true;
await message.member.voice.channel.overwritePermissions([
{ id: message.member.guild.id, deny: `CONNECT` },
]);
}
let selectionEmbed = new Discord.MessageEmbed().setTitle(
`Select audio type`
);
selectionEmbed.setDescription(
`> 🇦 - *FLAC* \n > 🇧 - *AAC* \n > 🇨 - *OPUS* \n > 🇩 - *MP3*`
);
selectionEmbed.setColor(`#00FFFF`);
selectionEmbed.setFooter(
`If you fail to select any of the options within 30 seconds, MP3 will be used by default.`
);
selectionEmbed.setThumbnail(
`https://media.discordapp.net/attachments/740001123041280050/757711840355680266/mouse-pointer.png?width=50&height=50`
);
const selectionMessage = await message.channel.send(selectionEmbed);
selectionMessage.react(`🇦`);
selectionMessage.react(`🇧`);
selectionMessage.react(`🇨`);
selectionMessage.react(`🇩`);
let confirmEmbed = new Discord.MessageEmbed().setTitle(`Select audio type`);
try {
const collected = await selectionMessage.awaitReactions(
(reaction, user) =>
user.id == message.author.id &&
(reaction.emoji.name === "🇦" ||
reaction.emoji.name === "🇧" ||
reaction.emoji.name === "🇩" ||
reaction.emoji.name === "🇨"),
{ max: 1, time: 30000, errors: ["time"] }
);
if (collected.first().emoji.name === "🇦") {
type = {
codec: "flac",
format: "flac",
ext: "flac",
};
confirmEmbed.setDescription(`You selected \`\`FLAC\`\`.`);
confirmEmbed.setColor(`#00FF00`);
} else if (collected.first().emoji.name === "🇧") {
type = {
codec: "aac",
format: "adts",
ext: "aac",
};
confirmEmbed.setDescription(`You selected \`\`AAC\`\`.`);
confirmEmbed.setColor(`#00FF00`);
} else if (collected.first().emoji.name === "🇨") {
type = {
codec: "libopus",
format: "opus",
ext: "opus",
};
confirmEmbed.setDescription(`You selected \`\`OPUS\`\`.`);
confirmEmbed.setColor(`#00FF00`);
} else if (collected.first().emoji.name === "🇩") {
type = {
codec: "libmp3lame",
format: "mp3",
ext: "mp3",
};
confirmEmbed.setDescription(`You selected \`\`MP3\`\`.`);
confirmEmbed.setColor(`#00FF00`);
}
} catch (err) {
type = {
codec: "libmp3lame",
format: "mp3",
ext: "mp3",
};
confirmEmbed.setDescription(`\`\`MP3\`\` was selected by default.`);
confirmEmbed.setColor(`#00FF00`);
}
await selectionMessage.edit(confirmEmbed);
function generateOutputFile(channelID, memberID) {
const dir = `./recordings/${channelID}/${memberID}`;
fs.ensureDirSync(dir);
const fileName = `${dir}/${randomArr[0]}.${type.ext}`;
return fs.createWriteStream(fileName);
}
let membersToScrape = Array.from(
message.member.voice.channel.members.values()
);
membersToScrape.forEach((member) => {
if (member.id !== message.client.user.id) {
finalArrWithIds.push(member.id);
}
});
console.log(finalArrWithIds, `FINAL ARRAY`);
const randomNumber = Math.floor(Math.random() * 100);
randomArr = [];
randomArr.push(randomNumber);
if (recording) {
message.reply("bot is already recording");
return;
}
if (message.member.voice.channel) {
recording = true;
const connection = await message.member.voice.channel.join();
const dispatcher = connection.play("./fight.wav");
connection.on("speaking", (user, speaking) => {
if (speaking.has("SPEAKING")) {
console.log(`listening`);
currently_recording[user.id] = true;
} else {
currently_recording[user.id] = false;
}
});
let members = Array.from(message.member.voice.channel.members.values());
members.forEach((member) => {
if (member.id != client.user.id) {
let memberStream = connection.receiver.createStream(member, {
mode: "pcm",
end: "manual",
});
let outputFile = generateOutputFile(
message.member.voice.channel.id,
member.id
);
mp3Paths.push(outputFile.path);
silence_stream = bufferToStream(new Uint8Array(0));
generateSilentData(silence_stream, member.id).then((data) =>
console.log(data)
);
let combinedStream = mergeStream(silence_stream, memberStream);
ffmpeg(combinedStream)
.inputOptions(["-f", "s16le", "-ar", "48k", "-ac", "2"])
.on("error", (error) => {
console.log(error);
})
.audioCodec(type.codec)
.format(type.format)
.pipe(outputFile);
}
});
} else {
message.reply("You need to join a voice channel first!");
}
}
if (message.content === `${prefix}stop`) {
if (!hasRole(message, "Admins")) return;
if (!locked)
await message.member.voice.channel.overwritePermissions([
{ id: message.member.guild.id, allow: `CONNECT` },
]);
let date = new Date();
let dd = String(date.getDate()).padStart(2, "0");
let mm = String(date.getMonth() + 1).padStart(2, "0");
let yyyy = date.getFullYear();
date = mm + "/" + dd + "/" + yyyy;
let currentVoiceChannel = message.member.voice.channel;
if (currentVoiceChannel) {
recording = false;
await currentVoiceChannel.leave();
let mergedOutputFolder =
"./recordings/" + message.member.voice.channel.id + `/${randomArr[0]}/`;
fs.ensureDirSync(mergedOutputFolder);
let file_name = `${randomArr[0]}` + `.${type.ext}`;
let mergedOutputFile = mergedOutputFolder + file_name;
let download_path =
message.member.voice.channel.id + `/${randomArr[0]}/` + file_name;
let mixedOutput = new ffmpeg();
console.log(mp3Paths, `mp3pathshere`);
mp3Paths.forEach((mp3Path) => {
mixedOutput.addInput(mp3Path);
});
//mixedOutput.complexFilter('amix=inputs=2:duration=longest');
mixedOutput.complexFilter(
"amix=inputs=" + mp3Paths.length + ":duration=longest"
);
let processEmbed = new Discord.MessageEmbed().setTitle(
`Audio Processing.`
);
processEmbed.addField(
`Audio processing starting now..`,
`Processing Audio`
);
processEmbed.setThumbnail(
`https://media.discordapp.net/attachments/730811581046325348/748610998985818202/speaker.png`
);
processEmbed.setColor(` #00FFFF`);
const processEmbedMsg = await message.channel.send(processEmbed);
async function saveMp3(mixedData, outputMixed) {
return new Promise((resolve, reject) => {
mixedData
.on("error", reject)
.on("progress", async (progress) => {
processing = true;
progressTarget = progress.targetSize;
progressPercent = progress.percent;
console.log(
"Processing: " + progress.targetSize + " KB converted"
);
})
.on("end", () => {
console.log("Processing finished !");
resolve();
})
.saveToFile(outputMixed);
});
}
// mixedOutput.saveToFile(mergedOutputFile);
await saveMp3(mixedOutput, mergedOutputFile);
// We saved the recording, now copy the recording
if (!fs.existsSync(`./public`)) {
fs.mkdirSync(`./public`);
}
let sourceFile = `${__dirname}/recordings/${download_path}`;
const guildName = message.guild.id;
const serveExist = `/public/${guildName}`;
if (!fs.existsSync(`.${serveExist}`)) {
fs.mkdirSync(`.${serveExist}`);
}
let destionationFile = `${__dirname}${serveExist}/${file_name}`;
let errorThrown = false;
try {
fs.copySync(sourceFile, destionationFile);
} catch (err) {
errorThrown = true;
await message.channel.send(`Error: ${err.message}`);
}
const usersWithTag = finalArrWithIds.map((user) => `\n <@${user}>`);
let timeSpent = await getAudioDurationInSeconds(
`public/${guildName}/${file_name}`
);
let timesSpentRound = Math.floor(timeSpent);
let finalTimeSpent = timesSpentRound / 60;
let finalTimeForReal = Math.floor(finalTimeSpent);
async function successSave(embed, channel) {
embed = new Discord.MessageEmbed().setDescription(
`Title successfully saved. Use \`\`$myrecordings\`\` to view your recordings.`
);
embed.setColor(`#32CD32`);
await channel.send(embed);
}
async function sendMsgOnVoiceEnd(
embed,
user,
message,
date,
finalTimeForReal,
isPersonal,
theDownloadLink,
greenEmbed,
channel
) {
embed = new Discord.MessageEmbed().setTitle(
`I will be honest, that recording session was sick !`
);
if (isPersonal) {
embed.setDescription(
`Please reply to this message with a title no more than 25 characters. You have 5 minutes. \n \`\`Date\`\`: ${date} \n \`\`Time\`\`: ${finalTimeForReal} \n \`\`Download link\`\`: [Click here](${theDownloadLink})`
);
}
if (!isPersonal) {
embed.setDescription(
`Please reply to this message with a title no more than 25 characters. You have 5 minutes. \n \`\`Date\`\`: ${date} \n \`\`Time\`\`: ${finalTimeForReal} \n \`\`Voices\`\`: ${usersWithTag} \n \`\`Download link\`\`: [Click here](${theDownloadLink})`
);
}
embed.setThumbnail(
`https://media.discordapp.net/attachments/748005515992498297/756094502535692338/title.png?width=100&height=100`
);
embed.setFooter(
`🔺 If you fail to reply with a title, it will be set to ${date} by default`
);
embed.setColor(`#00FFFF`);
let embedMsg = await user.send(embed);
const filter = (m) =>
m.author.id === user.id || m.author.id === message.author.id;
const embedCollector = embedMsg.channel.createMessageCollector(filter, {
time: 300000,
});
embedCollector.on("collect", async (m) => {
collectedTitle = m.content;
await successSave(greenEmbed, channel);
embedCollector.stop(`had to`);
});
return collectedTitle;
}
if (!errorThrown) {
processing = false;
//--------------------- server recording save START
let generalEmbed;
let generalEmbedTitle;
const generalTitle = await sendMsgOnVoiceEnd(
generalEmbed,
message.channel,
message,
date,
finalTimeForReal,
false,
`${fqdn}/public/${guildName}/${file_name}`,
generalEmbedTitle,
message.channel
);
const newGeneralRecordClassObject = {
generalLink: `${fqdn}/public/${guildName}/${file_name}`,
date: date,
title: generalTitle,
voice: usersWithTag,
time: finalTimeForReal,
};
const serverRecord = (await ServerRecords.exists({ userid: `server` }))
? await ServerRecords.findOne({ userid: `server` })
: new ServerRecords();
serverRecord.userid = `server`;
serverRecord.content.push(newGeneralRecordClassObject);
serverRecord
.save()
.then(async () => {})
.then(() => console.log(`its ok <3`))
.catch((err) => console.log(err, `AYE`));
//--------------------- server recording save STOP
}
//--------------------- personal recording section START
for (let member of finalArrWithIds) {
console.log(`WE ARE INSIDE`);
let personal_download_path =
message.member.voice.channel.id + `/${member}/` + file_name;
let sourceFilePersonal = `${__dirname}/recordings/${personal_download_path}`;
let destionationFilePersonal = `${__dirname}${serveExist}/${member}/${file_name}`;
await fs.copySync(sourceFilePersonal, destionationFilePersonal);
const user = client.users.cache.get(member);
if (user.bot) continue;
console.log(user, `USER IS HERE`);
try {
ffmpeg.setFfmpegPath(ffmpegInstaller.path);
ffmpeg(`public/${guildName}/${member}/${file_name}`)
.audioFilters(
"silenceremove=stop_periods=-1:stop_duration=1:stop_threshold=-90dB"
)
.output(`public/${guildName}/${member}/personal-${file_name}`)
.on(`end`, function () {
console.log(`DONE`);
})
.on(`error`, function (error) {
console.log(`An error occured` + error.message);
})
.run();
} catch (error) {
console.log(error);
}
// ----------------- SAVING PERSONAL RECORDING TO DATABASE START
let personalEmbed;
let timeSpentPersonal = await getAudioDurationInSeconds(
`public/${guildName}/${file_name}`
);
let timesSpentRoundPersonal = Math.floor(timeSpentPersonal);
let finalTimeSpentPersonal = timesSpentRoundPersonal / 60;
let finalTimeForRealPersonal = Math.floor(finalTimeSpentPersonal);
let personalTitleEmbed;
const personalRecordTitle = await sendMsgOnVoiceEnd(
personalEmbed,
user,
message,
date,
finalTimeForRealPersonal,
true,
`${fqdn}/public/${guildName}/${member}/personal-${file_name}`,
personalTitleEmbed,
user
);
const newPersonalRecordClassObject = {
generalLink: `${fqdn}/public/${guildName}/${file_name}`,
personalLink: `${fqdn}/public/${guildName}/${member}/personal-${file_name}`,
date: date,
title: personalRecordTitle,
time: finalTimeForRealPersonal,
};
const userRecord = (await UserRecords.exists({ userid: member }))
? await UserRecords.findOne({ userid: member })
: new UserRecords();
userRecord.userid = member;
userRecord.content.push(newPersonalRecordClassObject);
userRecord
.save()
.then(() => console.log(`personal one`))
.catch((err) => console.log(err));
}
//
} else {
message.reply("You need to join a voice channel first!");
}
}
if (message.content === `${prefix}recordstatus`) {
console.log(processing);
if (!processing)
return await message.channel.send(`There is no recording in process.`);
const bar = progressBar(progressPercent, 100, 10);
let processEmbedEdit = new Discord.MessageEmbed().setTitle(
`Audio Processing.`
);
processEmbedEdit.addField(
`Processing: ${progressTarget} KB converted`,
bar
);
processEmbedEdit.setThumbnail(
`https://media.discordapp.net/attachments/730811581046325348/748610998985818202/speaker.png`
);
processEmbedEdit.setColor(`#00FFFF`);
await message.channel.send(processEmbedEdit);
}
if (message.content.indexOf(prefix) !== 0) return;
const command = args.shift().toLowerCase();
const cmd = client.commands.get(command);
if (!cmd) return;
cmd.run(client, message, args);
});
let autoReactorTotalCount = 0;
let userConfirmationEmbed = new Discord.MessageEmbed();
let roleObject = {
oneRoleArray: ["@everyone"],
twoRoleArray: ["Crowd", "Prospect", "Fan"],
threeRoleArray: ["Enthusiast", "Challenge", "Regular"],
fourRoleArray: ["Active", "Pro", "Vet", "Titan", "Legend"],
fiveRoleArray: ["Supporter"],
};
let guildMember;
let roleName;
let fetchedGuild;
let votesToAdd = async (user) => {
fetchedGuild = await client.guilds.fetch("723940968843444264");
guildMember = await fetchedGuild.members.fetch(user);
roleName = guildMember.roles.highest.name;
if (roleObject.oneRoleArray.includes(roleName)) {
return 1;
} else if (roleObject.twoRoleArray.includes(roleName)) {
return 2;
} else if (roleObject.threeRoleArray.includes(roleName)) {
return 3;
} else if (roleObject.fourRoleArray.includes(roleName)) {
return 4;
} else if (roleObject.fiveRoleArray.includes(roleName)) {
return 5;
} else {
return 1;
}
};
let checkAccess = async (user, theReactor) => {
if (theReactor.pollRole === "oneRoleArray") {
return true;
}
fetchedGuild = await client.guilds.fetch("723940968843444264");
guildMember = await fetchedGuild.members.fetch(user);
roleName = guildMember.roles.highest.name;
console.log(theReactor.pollRole, `poll role.`);
if (roleObject[theReactor.pollRole].includes(roleName)) {
return true;
} else {
return false;
}
};
const autoReactorEndLog = (mainString, cypherStarsString) => {
statReactionData = [];
for (let data of selectedProfile.emojiData) {
statReactionData.push(
`\n \`\`Emoji\`\` : ${data.emojiName} \n \`\`Votes\`\` : ${data.count} \n`
);
}
statReactionData.push(cypherStarsString);
statsEmbed = new Discord.MessageEmbed().setTitle("Stats Report");
ref =
"http://discordapp.com/channels/" +
`723940968843444264` +
"/" +
theReactor.reactorSettings.channel +
"/" +
selectedProfile.id;
statReactionData.push(`\n [click here to view the message](${ref})`);
mainString += statReactionData;
statsEmbed.addField(`Report : `, mainString);
// string example : `Reactor id: \`\`${theReactor.id}\`\` \n Stats resport - Triggered at ${theReactor.statsReactionNumber} Reactions`,
// ` \n ${statReactionData}`;
statsEmbed.setColor(`#9400D3`);
statsEmbed.setThumbnail(
`https://cdn.discordapp.com/attachments/728671530459856896/729851605104590878/chart.png`
);
client.channels.fetch("730608533112094781").then((channel) => {
return channel.send(statsEmbed);
});
};
client.on("messageReactionAdd", async (reaction, user) => {
let foundElementVotes;
let totalVotes;
let numberOfVotes = 0;
let hasUserVoted;
let fetchedChannel;
let fetchedMessage;
let foundUser;
let statsEmbed;
let statReactionData = [];
let ref;
let newPerson;
let mainString = "";
let cypherStarsString = "";
let totalGems = "";
foundReactor = await Autor.find();
console.log(`captured`);
if (reaction.message.partial) await reaction.message.fetch();
if (reaction.partial) await reaction.fetch();
if (user.bot) return;
for (theReactor of foundReactor) {
if (!theReactor.isRunning) continue;
if (!theReactor.isPoll) {
console.log("fetchedMessage");
if (reaction.message.channel.id === theReactor.reactorSettings.channel) {
selectedProfile = await ReactorProfile.findOne({
messageid: reaction.message.id,
}).catch((err) => {
console.log(err);
});
if (!selectedProfile.stillRunning) return;
newPerson = await PersonalProfile.findOne({
userid: reaction.message.author.id,
}).catch((err) => {
console.log(err);
});
console.log(selectedProfile, `selectedprofile here poooooo`);
foundEmojiData = selectedProfile.emojiData.find(
(item) => item.emojiName === reaction.emoji.name
);
personEmojiData = newPerson.emojiData.find(
(item) => item.emojiName === reaction.emoji.name
);
console.log(personEmojiData, `person emoji data`);
if (foundEmojiData) {
foundEmojiData.count += await votesToAdd(user);
personEmojiData.count += await votesToAdd(user);
selectedProfile.totalVotes += 1;
// 1 gem = 5 count
newPerson.gems = "💎".repeat(Math.floor(personEmojiData.count / 5));
totalGems = "💎".repeat(Math.floor(foundEmojiData.count / 5));
}
console.log(newPerson, `new person`);
for (let dataItem of selectedProfile.emojiData) {
autoReactorTotalCount += dataItem.count;
}
console.log(`hey man`);
newPerson.markModified(`emojiData`);
await newPerson.save().catch((err) => console.log(err));
selectedProfile.markModified(`emojiData`);
await selectedProfile.save().catch((err) => console.log(err));
if (selectedProfile.totalVotes === theReactor.statsReactionNumber) {
mainString = `Reactor id: \`\`${theReactor.id}\`\` \n Stats resport - Triggered at ${theReactor.statsReactionNumber} Reactions \n ${statReactionData} \n Gems : \n ${totalGems}`;
cypherStarsString = "";
autoReactorEndLog(mainString, cypherStarsString);
}
if (
theReactor.endReactionEmoji === reaction.emoji.name ||
theReactor.endReactionNumber === selectedProfile.totalVotes
) {
console.log("triggered.");
let dueToString = `reaction of ${theReactor.endReactionEmoji}`;
if (theReactor.endReactionNumber === selectedProfile.totalVotes) {
dueToString = `reaching the set threshold of ${theReactor.endReactionNumber} emojis.`;
}
mainString = `Reactor id: \`\`${theReactor.id}\`\` \n Stats resport - Triggered due to ${dueToString} \n \n \`\`Gems\`\` : ${totalGems} \n`;
cypherStarsString = "";
autoReactorEndLog(mainString, cypherStarsString);
selectedProfile.stillRunning = false;
await selectedProfile.save();
return;
}
}
continue;
}
fetchedChannel = await client.channels
.fetch(theReactor.reactorSettings.channel)
.catch((err) => {
console.log(err);
});
fetchedMessage = await fetchedChannel.messages
.fetch(theReactor.reactorSettings.messageId)
.catch((err) => {
console.log(err);
});
if (!(await checkAccess(user, theReactor))) {
user.send(`🔒 You don't have access to vote on this poll.`);
return fetchedMessage.reactions.cache
.find((r) => r.emoji.name === reaction.emoji.name)
.users.remove(user.id);
}
if (reaction.message.id === theReactor.reactorSettings.messageId) {
console.log("we got the reaction");
console.log(
reaction.message.guild.members.cache
.get(user.id)
.roles.cache.has("729502305464090697"),
"ROLE HERE"
); //checking role.
if (theReactor.grandTotal.includes(user.id)) {
console.log(`return check`);
if (theReactor.anon && !theReactor.reactorSettings.multiple) {
console.log(`is it in check`);
let foundRemovedElement = theReactor.optionsText.find((item) =>
item.voterid.includes(user.id)
);
foundRemovedElement.voterid = foundRemovedElement.voterid.filter(
(item) => item !== user.id
);
foundUser = client.users.cache.find((item) => item.id === user.id);
foundRemovedElement.voterNames = foundRemovedElement.voterNames.filter(
(item) => item !== foundUser.username
);
foundRemovedElement.votes -= await votesToAdd(user);
theReactor.totalVotes -= 1;
theReactor.grandTotal = theReactor.grandTotal.filter(
(item) => item !== user.id
);
if (
theReactor.grandTotal.length === 0 ||
foundRemovedElement.votes === 0
) {
foundRemovedElement.percent = 0;
} else {
foundRemovedElement.percent =
(foundRemovedElement.votes * 100) / theReactor.grandTotal.length;
}
} else if (!theReactor.reactorSettings.multiple) {
return fetchedMessage.reactions.cache
.find((r) => r.emoji.name === reaction.emoji.name)
.users.remove(user.id);
}
}
totalVotes = () => {
numberOfVotes = 0;
// weights = 0;
if (theReactor.reactorSettings.isPoll)
for (let elements of theReactor.optionsText) {
numberOfVotes += elements.votes;
// weights += elements.weights;
}
return numberOfVotes;
};
if (theReactor.reactorSettings.isPoll) {
foundElementVotes = theReactor.optionsText.find(
(item) => item.emoji === reaction.emoji.name
);
console.log(`got em`, foundElementVotes);
// if (
// reaction.message.guild.members.cache
// .get(user.id)
// .roles.cache.has("729502305464090697")
// ) {
// foundElementVotes.weights += 2;
// } else {
if (
foundElementVotes.voterid.includes(user.id) &&
theReactor.anon &&
theReactor.reactorSettings.multiple
) {
fetchedMessage.reactions.cache
.find((r) => r.emoji.name === reaction.emoji.name)
.users.remove(user.id);
return client.users.cache
.find((item) => item.id === user.id)
.send(`\`\`You can only vote once on that option !\`\``);
}
foundElementVotes.votes += await votesToAdd(user);
theReactor.totalVotes += 1;
// }
foundElementVotes.voterid.push(user.id);
foundElementVotes.voterid.forEach((value, index) => {
foundUser = client.users.cache.find((user) => user.id === value);
foundElementVotes.voterNames.push(foundUser.username);
});
for (let eachElement of theReactor.optionsText) {
eachElement.percent = (eachElement.votes * 100) / totalVotes();
console.log(eachElement.weights, `weight here`);
console.log(totalVotes(), `votes here`);
}
if (
!theReactor.grandTotal.includes(user.id) ||
theReactor.reactorSettings.multiple
) {
theReactor.grandTotal.push(user.id);
}
console.log(theReactor.reactorSettings.channel, `channel id`);
let embedObject = fetchedMessage.embeds[0];
if (theReactor.anon) {
fetchedMessage.reactions.cache
.find((r) => r.emoji.name === reaction.emoji.name)
.users.remove(user.id);
}
for (i = 0; i < theReactor.optionsText.length; i++) {
delete embedObject.fields[i];
}
k = 0;
let optionString = ``;
let letters = [`🇦`, `🇧`, `🇨`, `🇩`, `🇪`, `🇫`, `🇬`, `🇭`, `🇮`];
let editedProgressBar;
for (let foo of theReactor.optionsText) {
editedProgressBar = theReactor.anon
? ""
: progressBar(foo.percent, 100, 10);
optionString += `\n ${letters[k++]} **${
foo.text
}** \n ${editedProgressBar}`;
}
embedObject.setDescription(
optionString + `\n 📩 Total Votes : ${theReactor.totalVotes}`
);
fetchedMessage.edit(embedObject);
if (theReactor.grandTotal.length === theReactor.statsReactionNumber) {
statReactionData = [];
for (data of theReactor.optionsText) {
statReactionData.push(`
\n \`\`Emoji\`\` : ${data.emoji} \n \`\`Votes\`\` : ${data.votes} \n \`\`Voter Names\`\` : ${data.voterNames} \n \`\`Percent\`\` : ${data.percent} \n ----
`);
statsEmbed = new Discord.MessageEmbed().setTitle("Stats Report");
}
ref =
"http://discordapp.com/channels/" +
`723940968843444264` +
"/" +
theReactor.reactorSettings.channel +
"/" +
fetchedMessage.id;
statReactionData.push(`\n [click here to view the message](${ref})`);
statsEmbed.addField(
`Reactor id: \`\`${theReactor.id}\`\` \n Stats resport - Triggered at ${theReactor.statsReactionNumber} Reactions`,
` \n ${statReactionData}`
);
statsEmbed.setColor(`#9400D3`);
statsEmbed.setThumbnail(
`https://cdn.discordapp.com/attachments/728671530459856896/729851605104590878/chart.png`
);
client.channels.fetch("730608533112094781").then((channel) => {
channel.send(statsEmbed);
});
}
}
console.log(`hello man total votes`);
console.log(autoReactorTotalCount, theReactor.statsReactionNumber);
theReactor.markModified(`optionsText`);
theReactor
.save()
.then(() => console.log(`save completed !`))
.catch((err) => console.log(err));
}
}
});
client.on("messageReactionRemove", async (reaction, user) => {
foundReactor = await Autor.find();
if (reaction.message.partial) await reaction.message.fetch();
if (reaction.partial) await reaction.fetch();
if (user.bot) return;
for (theReactor of foundReactor) {
if (!theReactor.isRunning) continue;
if (!theReactor.isPoll) {
if (reaction.message.channel.id === theReactor.reactorSettings.channel) {
selectedProfile = await ReactorProfile.findOne({
messageid: reaction.message.id,
}).catch((err) => {
console.log(err);
});
newPerson = await PersonalProfile.findOne({
userid: reaction.message.author.id,
}).catch((err) => {
console.log(err);
});
if (!selectedProfile.stillRunning) return;
console.log(selectedProfile, `selectedprofile here`);
foundEmojiData = selectedProfile.emojiData.find(
(item) => item.emojiName === reaction.emoji.name
);
personEmojiData = newPerson.emojiData.find(
(item) => item.emojiName === reaction.emoji.name
);
if (foundEmojiData) {
foundEmojiData.count -= await votesToAdd(user);
personEmojiData.count -= await votesToAdd(user);
selectedProfile.totalVotes -= 1;
}
selectedProfile.markModified(`emojiData`);
selectedProfile
.save()
.then((doc) => console.log(`saved`, doc))
.catch((err) => console.log(err));
}
}
if (reaction.message.id === theReactor.reactorSettings.messageId) {
fetchedChannel = await client.channels
.fetch(theReactor.reactorSettings.channel)
.catch((err) => {
console.log(err);
});
fetchedMessage = await fetchedChannel.messages
.fetch(theReactor.reactorSettings.messageId)
.catch((err) => {
console.log(err);
});
foundElementVotes = theReactor.optionsText.find(
(item) => item.emoji === reaction.emoji.name
);
if (theReactor.anon) return;
if (!foundElementVotes.voterid.includes(user.id)) return;
// if (
// reaction.message.guild.members.cache
// .get(user.id)
// .roles.cache.has("729502305464090697")
// ) {
// foundElementVotes.weights -= 2;
// } else {
foundElementVotes.votes -= await votesToAdd(user);
theReactor.totalVotes -= 1;
// }sole.log(foundElementVotes.voterid, `voter id here !`);
foundElementVotes.voterid.forEach((value, index) => {
foundUser = client.users.cache.find((user) => user.id === value);
foundElementVotes.voterNames = foundElementVotes.voterNames.filter(
(name) => name !== foundUser.username
);
});
foundElementVotes.voterid = foundElementVotes.voterid.filter(
(voter) => voter !== user.id
);
console.log(user.id);
console.log(foundElementVotes.voterid);
totalVotesTwo = () => {
numberOfVotes = 0;
// weights = 0;
for (let elements of theReactor.optionsText) {
numberOfVotes += elements.votes;
// weights += elements.weights;
}
return numberOfVotes;
};
console.log(totalVotesTwo(), `total votes here`);
for (let eachElement of theReactor.optionsText) {
if (totalVotesTwo() === 0) {
eachElement.percent = 0;
} else {
eachElement.percent = (eachElement.votes * 100) / totalVotesTwo();
}
}
if (theReactor.reactorSettings.multiple) {
let userToRemove = (element) => element === user.id;
let userIndex = theReactor.grandTotal.findIndex(userToRemove);
theReactor.grandTotal.splice(userIndex, 1);
} else {
theReactor.grandTotal = theReactor.grandTotal.filter(
(total) => total !== user.id
);
}
let embedObject = fetchedMessage.embeds[0];
if (!theReactor.anon) {
for (i = 0; i < theReactor.optionsText.length; i++) {
delete embedObject.fields[i];
}
k = 0;
let optionString = ``;
let letters = [`🇦`, `🇧`, `🇨`, `🇩`, `🇪`, `🇫`, `🇬`, `🇭`, `🇮`];
for (let foo of theReactor.optionsText) {
optionString += `\n ${letters[k++]} **${foo.text}** \n ${progressBar(
foo.percent,
100,
10
)}`;
}
embedObject.setDescription(
optionString + `\n 📩 Total Votes : ${theReactor.totalVotes}`
);
fetchedMessage.edit(embedObject);
}
theReactor.markModified(`optionsText`);
theReactor.save().catch((err) => console.log(err));
}
}
});
fs.readdir("./commands/", async (err, files) => {
if (err) return console.error;
files.forEach((file) => {
if (!file.endsWith(".js")) return;
let props = require(`./commands/${file}`);
let cmdName = file.split(".")[0];
// Register extra Listeners
client.commands.set(cmdName, props);
});
});
async function main() {
program.option("-debug");
program.option("-prod");
program.parse(process.argv);
console.log(program.opts());
if (program.Debug != undefined) {
debug = !debug;
}
if (program.Prod != undefined) {
runProd = !runProd;
}
if (runProd) {
client.login(process.env.PROD).catch((e) => {
console.log("ERROR");
console.log(e);
});
} else {
client.login(process.env.TEST).catch((e) => {
console.log("ERROR");
console.log(e);
});
}
}
main();
<file_sep>/models/personalprofile.js
const mongoose = require("mongoose");
const autoSchema = mongoose.Schema({
userid: String,
emojiData: [{ type: Object }],
gems: String,
});
module.exports = mongoose.model("PersonalProfile", autoSchema);
<file_sep>/commands/showreactor.js
const Discord = require("discord.js");
const Autor = require("../models/autoreactor.js");
const mongoose = require("mongoose");
const Pagination = require("discord-paginationembed");
let FieldsEmbed;
let reactorsArray = [];
let title;
let description;
let messageEmbed;
let collectThisMsg;
let collected;
let paginationEmbed = (title, description, reactorsArray, message) => {
FieldsEmbed = new Pagination.FieldsEmbed()
// A must: an array to paginate, can be an array of any type
.setArray(reactorsArray)
// Set users who can only interact with the instance. Default: `[]` (everyone can interact).
// If there is only 1 user, you may omit the Array literal.
.setAuthorizedUsers([message.author.id])
// A must: sets the channel where to send the embed
.setChannel(message.channel)
// Elements to show per page. Default: 10 elements per page
.setElementsPerPage(5)
// Have a page indicator (shown on message content). Default: false
.setPageIndicator(false)
// Format based on the array, in this case we're formatting the page based on each object's `word` property
.formatField("\u200b", (el) => el);
FieldsEmbed.embed.setColor(0xff00ae);
FieldsEmbed.embed.setTitle(title);
FieldsEmbed.embed.setDescription(description);
return FieldsEmbed.build();
};
exports.run = async (client, message, args) => {
let createAndWait = async (
messageEmbed,
collectThisMsg,
collected,
messageEmbedObject
) => {
const msgFilter = (m) => m.author.id === message.author.id;
const reactfilter = (reaction, user) => {
return user.id === message.author.id;
};
messageEmbed = new Discord.MessageEmbed().setTitle(
messageEmbedObject.title
);
messageEmbed.addField(messageEmbedObject.topic, messageEmbedObject.text);
messageEmbed.setColor(messageEmbedObject.color);
messageEmbed.setThumbnail(messageEmbedObject.thumbnail);
collectThisMsg = await message.channel.send(messageEmbed);
if (messageEmbedObject.boolean) {
collected = await collectThisMsg.channel
.awaitMessages(msgFilter, {
max: 1,
time: 20000,
})
.catch((err) => {
console.log(err);
return message.channel.send("``No input recieved.``");
});
if (messageEmbedObject.image) {
if (collected.first().attachment === undefined) {
return undefined;
}
return collected.first().attachment.url;
}
return collected.first().content;
} else {
for (let emoji of messageEmbedObject.emojiArray) {
await collectThisMsg.react(emoji);
}
collected = await collectThisMsg.awaitReactions(reactfilter, {
max: 1,
time: 20000,
errors: ["time"],
});
return collected.first().emoji.name;
}
};
reactorsArray = [];
if (!args[0]) {
let foundDocs;
foundDocs = await Autor.find().catch((err) => {
return message.channel.send(
"No saved reactors found. Please create a reactor using ``$reactor``"
);
});
let reactorType;
let status;
for (let doc of foundDocs) {
reactorType = doc.isPoll ? "📊 Poll" : "💈 Auto reactor";
if (doc.isRunning) {
status = `🟢 [running](${doc.reactorSettings.url})`;
} else {
status = `🟣 idle`;
}
reactorsArray.push(
`🪧 \`\`id - ${doc.id}\`\` - Reactor type - \`\`${reactorType}\`\` - \`\`${status}\`\` \n`
// `📌 \`\`pollTopic\`\` - ${doc.pollTopic} \n♑ \`\`pollColor\`\` - ${doc.pollColor} \n🖼️ \`\`pollImage\`\` - ${doc.pollimage} \n🤡 \`\`emojis\`\` - ${doc.emojis} \n📈 \`\`statsReactionNumber\`\` - ${doc.statsReactionNumber} \n🧭 \`\`endReactionEmoji\`\` - ${doc.endReactionEmoji} \n🗳️ \`\`endReactionNumber\`\` - ${doc.endReactionNumber} \n⏳ \`\`endReactionTime\`\` - ${doc.endReactionTime} \n👨👦 \`\`role\`\` - ${doc.role} \n📩 \`\`notify\`\` - ${doc.notify} \n🧷 \`\`pin\`\` - ${doc.pin} \n🔁 \`\`rep\`\` - ${doc.rep} \n🎚️ \`\`repNum\`\` - ${doc.repNum}`
);
}
title = "List of reactors";
description =
"To view or edit any reactor, use showreactor ``InsertIdHere``";
paginationEmbed(title, description, reactorsArray, message);
}
if (args[0]) {
let id = args[0];
let doc;
doc = await Autor.findOne({ id: id }).catch((err) => {
return message.channel.send(
`No reactor found with id ${id}. Please check available reactors with \`\`$showreactor\`\` and try again !`
);
});
title = `id - \`\`${doc.id}\`\``;
description = "";
let i = 1;
let arrayString = ``;
arrayString =
doc.pollTopic === undefined
? ``
: arrayString + `📌 \`\`pollTopic\`\` - ${doc.pollTopic}`;
arrayString =
doc.pollColor === undefined
? arrayString
: arrayString + `\n♑ \`\`pollColor\`\` - ${doc.pollColor}`;
arrayString =
doc.pollImage === undefined
? arrayString
: arrayString + `\n🖼️ \`\`pollImage\`\` - ${doc.pollImage}`;
for (let item of doc.optionsText) {
arrayString =
arrayString +
`\n ➿ \`\`option${doc.optionsText.indexOf(item) + 1} - \`\` - ${
item.text
} `;
}
arrayString =
doc.emojis === undefined
? arrayString
: arrayString + `\n🤡 \`\`emojis\`\` - ${doc.emojis}`;
arrayString =
doc.statsReactionNumber === undefined
? arrayString
: arrayString +
`\n🖼 \`\`statsReactionNumber\`\` - ${doc.statsReactionNumber}`;
arrayString =
doc.endReactionEmoji === undefined
? arrayString
: arrayString +
`\n🧭 \`\`endReactionEmoji\`\` - ${doc.endReactionEmoji}`;
arrayString =
doc.endReactionNumber === undefined
? arrayString
: arrayString +
`\n🗳️ \`\`endReactionNumber\`\` - ${doc.endReactionNumber}`;
arrayString =
doc.endReactionTime === undefined
? arrayString
: arrayString + `\n⏳ \`\`endReactionTime\`\` - ${doc.endReactionTime}`;
arrayString =
doc.role === undefined
? arrayString
: arrayString + `\n👨👦 \`\`role\`\` - ${doc.role}`;
arrayString =
doc.notify === undefined
? arrayString
: arrayString + `\n📩 \`\`notify\`\` - ${doc.notify}`;
arrayString =
doc.pin === undefined
? arrayString
: arrayString + `\n🔁 \`\`pin\`\` - ${doc.pin}`;
arrayString =
doc.rep === undefined
? arrayString
: arrayString + `\n🔁 \`\`rep\`\` - ${doc.rep}`;
arrayString =
doc.repNum === undefined
? arrayString
: arrayString + `\n🎚️ \`\`repNum\`\` - ${doc.repNum}`;
reactorsArray.push(
arrayString
// `📌 \`\`pollTopic\`\` - ${doc.pollTopic} \n♑ \`\`pollColor\`\` - ${doc.pollColor} \n🖼 \`\`pollImage\`\` - ${doc.pollimage} \n🤡 \`\`emojis\`\` - ${doc.emojis} \n \`\`statsReactionNumber\`\` - ${doc.statsReactionNumber} \n🧭 \`\`endReactionEmoji\`\` - ${doc.endReactionEmoji} \n🗳️ \`\`endReactionNumber\`\` - ${doc.endReactionNumber} \n⏳ \`\`endReactionTime\`\` - ${doc.endReactionTime} \n👨👦 \`\`role\`\` - ${doc.role} \n📩 \`\`notify\`\` - ${doc.notify} \n🧷 \`\`pin\`\` - ${doc.pin} \n🔁 \`\`rep\`\` - ${doc.rep} \n🎚️ \`\`repNum\`\` - ${doc.repNum}`
);
paginationEmbed(title, description, reactorsArray, message);
const userInputEmbed = new Discord.MessageEmbed().setDescription(
`Reply with that property name you would like to change. You have 20 seconds`
);
const msgFilter = (m) => m.author.id === message.author.id;
const userInput = await message.channel.send(userInputEmbed);
const collected = await userInput.channel
.awaitMessages(msgFilter, {
max: 1,
time: 20000,
})
.catch((err) => {
console.log(err);
return message.channel.send("``No input recieved.``");
});
let userInputMessage = collected.first().content;
let messageEmbedObject = {
title: "Auto reactor and Polls",
topic: "Poll",
text: "Please reply with poll topic",
color: "#9400D3",
thumbnail:
"https://cdn.discordapp.com/attachments/728671530459856896/728677723198980167/television.png",
boolean: true,
emojiArray: [],
};
if (doc[userInputMessage] || doc.optionsText) {
if (userInputMessage.includes(`option`)) {
let optionNumber = parseInt(
userInputMessage.slice(6, userInputMessage.length)
);
messageEmbedObject.topic = "Poll";
messageEmbedObject.text = `Please enter option ${optionNumber}`;
let returnedText = await createAndWait(
messageEmbed,
collectThisMsg,
collected,
messageEmbedObject
);
doc.optionsText[optionNumber - 1].text = returnedText;
doc.markModified("optionsText");
}
if (userInputMessage === "pollTopic") {
let pollTopic = await createAndWait(
messageEmbed,
collectThisMsg,
collected,
messageEmbedObject,
message
);
doc.pollTopic = pollTopic;
}
if (userInputMessage === "pollColor") {
messageEmbedObject.topic = "Poll";
messageEmbedObject.text =
"Please reply with poll color \n [view applicable colors here](https://discord.js.org/#/docs/main/stable/typedef/ColorResolvable)";
messageEmbedObject.color = "#9400D3";
messageEmbedObject.thumbnail =
"https://media.discordapp.net/attachments/763795278079721482/765232054228090880/unknown.png";
let pollColor = await createAndWait(
messageEmbed,
collectThisMsg,
collected,
messageEmbedObject
);
doc.pollColor = pollColor.toUpperCase();
}
if (userInputMessage === "pollImage") {
messageEmbedObject.topic = "Poll";
messageEmbedObject.text =
"Please reply with the custom poll image \n if you don't want to set poll image please reply with ``no``";
messageEmbedObject.color = "#9400D3";
messageEmbedObject.image = true;
messageEmbedObject.thumbnail =
"https://media.discordapp.net/attachments/763795278079721482/765232054228090880/unknown.png";
let pollImageCheck = await createAndWait(
messageEmbed,
collectThisMsg,
collected,
messageEmbedObject
);
let pollImage = pollImageCheck === undefined ? false : pollImageCheck;
if (pollImage) {
doc.pollImage = pollImage;
}
}
if (userInputMessage === "statsReactionNumber") {
messageEmbedObject.topic = "Trigger options";
messageEmbedObject.text =
"Please enter the number of reactions after which the stats are to be stored.";
messageEmbedObject.color = "#9400D3";
messageEmbedObject.thumbnail =
"https://cdn.discordapp.com/attachments/728671530459856896/728680050295046214/bible.png";
messageEmbedObject.boolean = true;
statsReactionNumber = await createAndWait(
messageEmbed,
collectThisMsg,
collected,
messageEmbedObject
);
doc.statsReactionNumber = statsReactionNumber;
console.log(statsReactionNumber, `here it isd`);
}
if (userInputMessage === "endReactionEmoji") {
messageEmbedObject.topic = "Trigger options";
messageEmbedObject.text =
"Please react this message with the reaction you would want to trigger this action";
messageEmbedObject.color = "#9400D3";
messageEmbedObject.thumbnail =
"https://cdn.discordapp.com/attachments/728671530459856896/728680480559595630/love.png";
messageEmbedObject.boolean = false;
messageEmbedObject.emojiArray = [];
let triggerTwoEmoji = await createAndWait(
messageEmbed,
collectThisMsg,
collected,
messageEmbedObject
);
doc.endReactionEmoji = triggerTwoEmoji;
}
if (userInputMessage === "endReactionNumber") {
messageEmbedObject.topic = "Trigger options";
messageEmbedObject.text =
"Please enter the number of reactions to trigger this action";
messageEmbedObject.color = "#9400D3";
messageEmbedObject.thumbnail =
"https://media.discordapp.net/attachments/728671530459856896/728681225971171389/kindness.png";
messageEmbedObject.boolean = true;
triggerThreeStatsMsgCollector = await createAndWait(
messageEmbed,
collectThisMsg,
collected,
messageEmbedObject
);
doc.endReactionNumber = parseInt(triggerThreeStatsMsgCollector);
}
if (userInputMessage === "role") {
messageEmbedObject.topic = "Trigger options";
messageEmbedObject.text =
"Please Select which role \n ***1 - Admin \n 2 - Owner***";
messageEmbedObject.color = "#9400D3";
messageEmbedObject.thumbnail =
"https://media.discordapp.net/attachments/728671530459856896/728682672615850135/person.png";
messageEmbedObject.boolean = false;
messageEmbedObject.emojiArray = ["1️⃣", "2️⃣"];
let triggerFiveStatsMsgCollector = await createAndWait(
messageEmbed,
collectThisMsg,
collected,
messageEmbedObject
);
console.log(triggerFiveStatsMsgCollector);
if (triggerFiveStatsMsgCollector === `1️⃣`) {
finalPush = "Admin";
}
if (triggerFiveStatsMsgCollector === `2️⃣`) {
finalPush = "Owner";
}
console.log(finalPush);
prop.push(`\n - 👥 Role to Dm : ${finalPush}`);
doc.role = finalPush;
}
if (userInputMessage === "rep") {
messageEmbedObject.topic = "Triggers";
messageEmbedObject.text =
"Do you want to add a +rep to the author of the message on every upvote";
messageEmbedObject.color = "#9400D3";
messageEmbedObject.thumbnail =
"https://media.discordapp.net/attachments/728671530459856896/728683970371387512/thumbs-up.png";
messageEmbedObject.boolean = false;
messageEmbedObject.emojiArray = [`✅`, `❎`];
const triggerSevenEmoji = await createAndWait(
messageEmbed,
collectThisMsg,
collected,
messageEmbedObject
);
if (triggerSevenEmoji === `✅`) {
doc.rep === `yes`;
}
}
doc
.save()
.then((saved) => {
message.channel.send(`\`\`Value saved\`\``);
console.log(saved);
})
.catch((err) => console.log(err));
} else {
message.channel.send(`You cannot edit that value.`);
}
}
};
exports.help = {
name: "ar",
};
<file_sep>/commands/runreactor.js
const Discord = require("discord.js");
const schedule = require("node-schedule");
const Autor = require("../models/autoreactor.js");
const progressBar = require("../functions/bar.js");
let letters = [`🇦`, `🇧`, `🇨`, `🇩`, `🇪`, `🇫`, `🇬`, `🇭`, `🇮`];
exports.run = async (client, message, args) => {
const msgFilter = (m) => m.author.id === message.author.id;
console.log(args[0]);
let foundDoc = await Autor.findOne({ id: args[0] }).catch((err) => {
return message.channel.send(
"No saved reactors found. Please create a reactor using ``$reactor``"
);
});
if (foundDoc.isRunning) {
return message.channel.send(`\`\`This reactor is already running.\`\``);
}
let askSettings = new Discord.MessageEmbed().setTitle(`Reaction settings`);
let reactorSettings = {};
if (foundDoc.isPoll) {
askSettings
.setDescription(
"When do you want to schedule this ? \n ``1`` - Start right now \n ``2`` - Schedule a time."
)
.setColor("#800080");
let askTimeEmbed = await message.channel.send(askSettings);
const reactfilter = (reaction, user) => {
return user.id === message.author.id;
};
let collected = await askTimeEmbed.channel
.awaitMessages(msgFilter, {
max: 1,
time: 200000,
errors: ["time"],
})
.catch((err) => {
console.log(err);
return message.channel.send(`invalid input`);
});
if (collected.first().content === "1") {
reactorSettings.startTime = 0;
} else if (collected.first().content === "2") {
reactorSettings.scheduled = true;
askSettings.setDescription(
"Enter the day of the month you would want to schedule the poll."
);
askStartDayEmbed = await message.channel.send(askSettings);
collected = await askStartDayEmbed.channel
.awaitMessages(msgFilter, {
max: 1,
time: 200000,
errors: ["time"],
})
.catch((err) => {
console.log(err);
return message.channel.send(`invalid input`);
});
reactorSettings.startTimeDay = parseInt(collected.first().content);
askSettings.setDescription(
"Enter the hour of the day you would want to schedule the poll."
);
askStartHourEmbed = await message.channel.send(askSettings);
collected = await askStartHourEmbed.channel
.awaitMessages(msgFilter, {
max: 1,
time: 200000,
})
.catch((err) => {
console.log(err);
return message.channel.send(`invalid input`);
});
reactorSettings.startTimeHour = parseInt(collected.first().content);
askSettings.setDescription(
"Enter the minute of the hour you would want to schedule the poll."
);
askStartMinuteEmbed = await message.channel.send(askSettings);
collected = await askStartMinuteEmbed.channel
.awaitMessages(msgFilter, {
max: 1,
time: 200000,
})
.catch((err) => {
console.log(err);
return message.channel.send(`invalid input`);
});
reactorSettings.startTimeMinute = parseInt(collected.first().content);
}
askSettings.setDescription(
`When do you want to terminate the process of the reactor ? \n \`\`1\`\` - Schedule a time \n \`\`2\`\` - Custom - \`\`$reactorstop <reactoridhere>\`\``
);
let askEndTimeEmbed = await message.channel.send(askSettings);
collected = await askEndTimeEmbed.channel
.awaitMessages(msgFilter, {
max: 1,
time: 200000,
errors: ["time"],
})
.catch((err) => {
console.log(err);
return message.channel.send(`invalid input`);
});
if (collected.first().content === "1") {
reactorSettings.endCustom = false;
askSettings.setDescription(
"Enter the day of the month you would want to terminate the poll."
);
askEndDayEmbed = await message.channel.send(askSettings);
collected = await askEndDayEmbed.channel
.awaitMessages(msgFilter, {
max: 1,
time: 200000,
})
.catch((err) => {
console.log(err);
return message.channel.send(`invalid input`);
});
reactorSettings.endTimeDay = parseInt(collected.first().content);
askSettings.setDescription(
"Enter the hour of the day you would want to terminate the poll."
);
askEndHourEmbed = await message.channel.send(askSettings);
collected = await askEndHourEmbed.channel
.awaitMessages(msgFilter, {
max: 1,
time: 200000,
})
.catch((err) => {
console.log(err);
return message.channel.send(`invalid input`);
});
reactorSettings.endTimeHour = parseInt(collected.first().content);
askSettings.setDescription(
"Enter the minute of the hour you would want to terminate the poll."
);
askEndMinuteEmbed = await message.channel.send(askSettings);
collected = await askEndMinuteEmbed.channel
.awaitMessages(msgFilter, {
max: 1,
time: 200000,
})
.catch((err) => {
console.log(err);
return message.channel.send(`invalid input`);
});
reactorSettings.endTimeMinute = parseInt(collected.first().content);
}
askSettings.setDescription(
"If you want people to cast multiple votes, reply with a ``yes`` else reply with a ``no``"
);
let askMultipleEmbed = await message.channel.send(askSettings);
collected = await askMultipleEmbed.channel
.awaitMessages(msgFilter, {
max: 1,
time: 200000,
})
.catch((err) => {
console.log(err);
return message.channel.send(`invalid input`);
});
reactorSettings.multiple =
collected.first().content === "yes" ? true : false;
reactorSettings.isPoll = true;
}
askSettings.setDescription(
"In which channel do you want to initiate the reactor ?"
);
let askChannelEmbed = await message.channel.send(askSettings);
collected = await askChannelEmbed.channel
.awaitMessages(msgFilter, {
max: 1,
time: 200000,
})
.catch((err) => {
console.log(err);
return message.channel.send(`invalid input`);
});
let allReactors = await Autor.find().catch((err) => {
return message.channel.send(
"No saved reactors found. Please create a reactor using ``$reactor``"
);
});
for (let item of allReactors) {
if (!item.reactorSettings) continue;
if (
item.reactorSettings.channel ===
collected.first().mentions.channels.first().id
) {
return message.channel.send(
`You already have a reactor set for that channel. Please try again and choose a different channel.`
);
}
}
reactorSettings.channel = collected.first().mentions.channels.first();
let confirmationEmbed = new Discord.MessageEmbed();
confirmationEmbed.setColor(`#BFFF00`);
confirmationEmbed.setDescription(`✅ Your reactor is scheduled !`);
message.channel.send(confirmationEmbed);
if (!foundDoc.isPoll) {
reactorSettings.count = 0;
foundDoc.isRunning = true;
foundDoc.reactorSettings = reactorSettings;
foundDoc.markModified("reactorSettings");
foundDoc.markModified("isRunning");
foundDoc.save().catch((err) => console.log(err));
return;
}
if (foundDoc.isPoll) {
// askSettings.setTitle(
// `Do you want to run this poll on intervals ? If \`\`yes\`\`, then please enter the hour of the day you would want the reactor to be else enter \`\`no\`\``
// );
// let askIntervalEmbed = await message.channel.send(askSettings);
// collected = await askIntervalEmbed.channel.awaitMessages(msgFilter, {
// max: 1,
// time: 20000,
// });
// reactorSettings.interval = true;
// reactorSettings.intervalTime = collected.first().content;
// console.log(reactorSettings.intervalTime, `int time`);
// reactorSettings.interval =
// reactorSettings.intervalTime === "no" ? false : true;
let pollEmbed = new Discord.MessageEmbed()
.setTitle(`📊 ${foundDoc.pollTopic}`)
.setColor(foundDoc.pollColor)
.setImage(foundDoc.pollImage);
let i = 0;
let optionString = ``;
let progressBarHere = foundDoc.anon ? `` : progressBar(0, 100, 10);
for (let field of foundDoc.optionsText) {
optionString += `\n ${letters[i++]} **${
field.text
}** \n ${progressBarHere}`;
}
pollEmbed.setDescription(optionString + `\n 📩 Total Votes: 0`);
const runPoll = async () => {
const pollEmbedMessage = await reactorSettings.channel.send(pollEmbed);
reactorSettings.messageId = pollEmbedMessage.id;
for (let numberOfFlieds in foundDoc.optionsText) {
await pollEmbedMessage.react(letters[numberOfFlieds]);
}
reactorSettings.url = pollEmbedMessage.url;
};
foundDoc.reactorSettings = reactorSettings;
foundDoc.grandTotal = [];
foundDoc.markModified("optionsText");
foundDoc.markModified("reactorSettings");
foundDoc.markModified("grandTotal");
if (reactorSettings.startTime === 0) {
console.log("set to false");
foundDoc.isRunning = true;
await runPoll();
} else {
console.log("set to true");
foundDoc.isRunning = false;
}
foundDoc.markModified("isRunning");
await foundDoc.save().catch((err) => console.log(err));
schedule.scheduleJob(
`${reactorSettings.startTimeMinute} ${reactorSettings.startTimeHour} ${reactorSettings.startTimeDay} * *`,
async function () {
foundDoc.isRunning = true;
await runPoll();
foundDoc.markModified("reactorSettings");
foundDoc.markModified("isRunning");
await foundDoc.save().catch((err) => console.log(err));
}
);
schedule.scheduleJob(
`${reactorSettings.endTimeMinute} ${reactorSettings.endTimeHour} ${reactorSettings.endTimeDay} * *`,
async function () {
console.log(args[0], `hiiii`);
let updatedDoc = await Autor.findOne({ id: args[0] }).catch((err) => {
return message.channel.send(
"No saved reactors found. Please create a reactor using ``$reactor``"
);
});
fetchedChannel = await client.channels
.fetch(updatedDoc.reactorSettings.channel)
.catch((err) => {
console.log(err);
});
fetchedMessage = await fetchedChannel.messages
.fetch(updatedDoc.reactorSettings.messageId)
.catch((err) => {
console.log(err);
});
let embedObject = fetchedMessage.embeds[0];
updatedDoc.isRunning = false;
for (i = 0; i < updatedDoc.optionsText.length; i++) {
delete embedObject.fields[i];
}
let optionString = ``;
let k = 0;
for (let foo of updatedDoc.optionsText) {
optionString += `\n ${letters[k++]} ***${
foo.text
}*** \n ${progressBar(foo.percent, 100, 10)}`;
}
embedObject.setDescription(
optionString + `\n 📩 Total Votes : ${updatedDoc.grandTotal.length}`
);
embedObject.setFooter(`The poll has ended`);
fetchedMessage.edit(embedObject);
await updatedDoc.save().catch((err) => console.log(err));
}
);
// let foundElementVotes;
// let totalVotes;
// let numberOfVotes = 0;
// console.log(foundElementVotes, `voted here`);
// foundElementVotes.votes += 1;
// foundElementVotes.voterid.push(user.id);
// totalVotes = () => {
// numberOfVotes = 0;
// for (elements of foundDoc.optionsText) {
// numberOfVotes += elements.votes;
// }
// return numberOfVotes;
// };
// console.log(totalVotes(foundDoc), `total votes here`);
// foundElementVotes.percent =
// (foundElementVotes.votes * 100) / totalVotes(foundDoc);
// console.log(foundElementVotes.percent);
// for (i = 0; i < foundDoc.optionsText.length; i++) {
// delete pollEmbed.fields[i];
// }
// k = 0;
// for (let foo of foundDoc.optionsText) {
// optionString += `\n ${letters[k++]} ***${foo.text}*** \n ${progressBar(
// foo.percent,
// 100,
// 10
// )}`;
// }
// pollEmbed.setDescription(optionString);
// pollEmbedMessage.edit(pollEmbed);
// console.log(`collected`, reaction.emoji.name);
// if (totalVotes() === foundDoc.statsReactionNumber) {
// let statReactionData = [];
// let foundUser;
// foundDoc.optionsText.forEach((value, index) => {
// foundUser = client.users.cache.find((user) => user.id === value);
// foundDoc.voterNames.push(foundUser.username);
// });
// for (let data of founddoc.optionsText) {
// statReactionData.push(
// `😀 \`\`Emoji\`\` : ${data.emoji} \n 📮 \`\`Votes\`\` : ${data.votes} \n 👥 \`\`Voters\`\` : ${data.voterNames} \n 📊 \`\`Percent\`\` : ${data.percent}`
// );
// }
// const statsEmbed = new Discord.MessageEmbed().setTitle("Stats Report");
// let ref =
// "http://discordapp.com/channels/" +
// pollEmbedMessage.guild.id +
// "/" +
// pollEmbedMessage.channel.id +
// "/" +
// pollEmbedMessage.id;
// statsEmbed.addField(
// `Stats resport - Triggered at ${founddoc.statsReactionNumber} Reactions`,
// ` \n ${statReactionData} \n \`\`Original message\`\` ${ref}`
// );
// statsEmbed.setColor(`#9400D3`);
// statsEmbed.setThumbnail(
// `https://cdn.discordapp.com/attachments/728671530459856896/729851605104590878/chart.png`
// );
// client.channels.fetch("730608533112094781").then((channel) => {
// channel.send(statsEmbed);
// });
// }
// }, reactorSettings.startTime);
}
};
exports.help = {
name: "runreactor",
};
<file_sep>/commands/rep.js
const Discord = require("discord.js");
const Reps = require("../models/reps.js");
const GuildSettings = require("../models/guildSettings.js");
const Profile = require("../models/profile.js"); // when in main repo
const convertMS = require("../functions/convertMS");
const profanity = require("@2toad/profanity").profanity;
const Pagination = require("discord-paginationembed");
exports.run = async (client, message, args) => {
if (args[0] === "set") {
// Don't continue if author doesn't have ADMIN
if (!message.member.hasPermission("ADMINISTRATOR")) {
const permEmbed = new Discord.MessageEmbed()
.setTitle(
"You need to have the ADMINISTRATOR permission to use this command."
)
.setColor("#ff0000");
return message.channel.send(permEmbed);
}
const repName = args[1].toLowerCase();
// Don't allow usage of words that trigger other commands.
const cmd = repName === "rep" ? false : repName;
if (client.commands.get(cmd))
return message.channel.send("Sorry, `" + repName + "` is reserved.");
if (repName.length < 3)
return message.channel.send(
"Sorry, but `" + repName + "` must be at least 3 characters long."
);
if (repName.length > 10)
return message.channel.send(
"Sorry, but `" + repName + "` must not exceed 10 characters in length."
);
// Set the new rep command trigger
const guildRes = await GuildSettings.findOne({
guildID: message.guild.id,
});
if (!guildRes) {
const tmpGuildRes = new GuildSettings({
guildID: message.guild.id,
repName: repName,
});
tmpGuildRes.save().catch((err) => console.log(err));
} else {
guildRes.repName = repName;
guildRes.markModified("repName");
guildRes.save().catch((err) => console.log(err));
}
const replyStr = `Done! You can now trigger rep using: ${repName}`;
return await message.channel.send(replyStr);
} else if (args[0] === "show") {
// Get trigger word, if it exists
// Else use rep
const guildRes = await GuildSettings.findOne({
guildID: message.guild.id,
});
const repName = guildRes ? guildRes.repName : "rep";
// Get the provided user's reps
// Else get author's
const person =
message.mentions.users.first() ||
message.client.users.cache.get(args[1]) ||
message.author;
const personRepRes = await Reps.findOne({
userid: person.id,
});
const replyEmbed = new Discord.MessageEmbed()
.setColor("#ffff00")
.setTitle(
(person === message.author ? "You don't" : `${person.tag} doesn't`) +
" have any " +
(repName.endsWith("s") ? repName : repName + "s")
);
// If provided user doesn't have a db entry, reply with that
if (!personRepRes) return await message.channel.send(replyEmbed);
// The array that contains all user's reviews
const reviews = personRepRes.reviews;
replyEmbed.setTitle(
(person === message.author ? "You have" : `${person.tag} has`) +
` ${personRepRes.reps} ` +
(repName.endsWith("s") ? repName : repName + "s")
);
// If they have 0 reviews, reply with just their reps (or coins)
if (reviews.length === 0) return await message.channel.send(replyEmbed);
//pagination
const FieldsEmbed = new Pagination.FieldsEmbed()
.setArray(reviews)
.setAuthorizedUsers([message.author.id])
.setChannel(message.channel)
.setElementsPerPage(1)
.setPage(1)
.setPageIndicator(true)
.formatField("Reviews", (i) => {
// reviews include a "from" key
// that holds the submitter's id
// we can search in cache for their tag
// if not found, just change it to a mention
// (tags are prefered as mentions depend on client's cache and not on bot's)
const userReview = message.client.users.cache.get(i.from);
return (
"From: " +
(userReview ? userReview.tag : "<@" + i.from + ">") +
"\n```" +
i.review +
"```"
);
})
.setDisabledNavigationEmojis(["delete"])
.setEmojisFunctionAfterNavigation(false);
FieldsEmbed.embed
.setColor("#ffff00")
.setTitle(
(person === message.author ? "You have" : `${person.username} has`) +
` ${personRepRes.reps} ` +
(repName.endsWith("s") ? repName : repName + "s")
);
return await FieldsEmbed.build();
}
// Check if the provided user exists and is not a bot or author
// (Author shouldn't be able to rep themselves)
const person =
message.mentions.users.first() || message.client.users.cache.get(args[0]);
if (!person || person.bot || person === message.author) {
const incorrectEmbed = new Discord.MessageEmbed()
.setAuthor(
"Incorrect Usage",
message.author.displayAvatarURL({ format: "png", dynamic: true })
)
.setDescription(
`:x: **${message.author.username}** please mention a valid user`
)
.setColor("#ffff00");
return message.channel.send(incorrectEmbed);
}
// Get trigger word, if it exists
// Else use rep
const guildRes = await GuildSettings.findOne({
guildID: message.guild.id,
});
const repName = guildRes ? guildRes.repName : "rep";
// args minus the first item
// which is the mention/id
// Profanity#censor returns String with profanity censored
const review = profanity.censor(args.slice(1).join(" "));
if (review.length > 200)
return message.channel.send("Review can't be over 200 characters");
// Get author and provided user enties
// If they exist, else create them
const authorRepRes = await Reps.findOne({
userid: message.author.id,
});
const personRepRes = await Reps.findOne({
userid: person.id,
});
const personProfileRes = await Profile.findOne({
userid: person.id,
});
// We will set the timer to 24 hours from now
// So users can't spam it
const repLimit = new Date().getTime() + 24 * 60 * 60 * 1000; // unixms now + 24 hours
if (!authorRepRes) {
const tmpAuthorRes = new Reps({
userid: message.author.id,
reps: 0,
timeLeft: repLimit,
reviews: [],
});
tmpAuthorRes.save().catch((err) => console.log(err));
// If 24 hours havent passed
} else if (new Date().getTime() < authorRepRes.timeLeft) {
const waitEmbed = new Discord.MessageEmbed()
.setTitle("You will be able to " + repName + " someone in:")
.setColor("#ff0000")
.setDescription(convertMS(authorRepRes.timeLeft - new Date().getTime())); // time left
return await message.channel.send(waitEmbed);
} else {
authorRepRes.timeLeft = repLimit;
authorRepRes.markModified("timeLeft");
authorRepRes.save().catch((err) => console.log(err));
}
// let's generate the object
// which will hold the review
const reviewGen = {
from: message.author.id,
review: review,
};
if (!personRepRes) {
const tmpPersonRes = new Reps({
userid: person.id,
reps: 1,
timeLeft: 0,
reviews: review.length > 0 ? [reviewGen] : [],
});
tmpPersonRes.save().catch((err) => console.log(err));
} else {
personRepRes.reps += 1;
personRepRes.markModified("reps");
if (review.length > 0) {
personRepRes.reviews.push(reviewGen);
personRepRes.markModified("reviews");
}
personRepRes.save().catch((err) => console.log(err));
}
// Lets deal with the profile model
if (!personProfileRes) {
const tmpProfileRes = new Profile({
userid: person.id,
coins: 1,
bets: 0,
});
tmpProfileRes.save().catch((err) => console.log(err));
} else {
personProfileRes.coins += 1;
personProfileRes.markModified("coins");
personProfileRes.save().catch((err) => console.log(err));
}
// Not embed so person can get notified
const replyStr = `${person}, you just received a ${repName} from ${message.author}`;
return await message.channel.send(replyStr);
};
exports.help = {
name: "rep",
};
<file_sep>/models/reps.js
const mongoose = require("mongoose");
const autoSchema = mongoose.Schema({
userid: String,
reps: Number,
timeLeft: Number,
reviews: [
{
from: String,
review: String,
},
],
});
module.exports = mongoose.model("Reps", autoSchema);
<file_sep>/commands/settext.js
const Discord = require("discord.js");
const SetText = require("../models/settext.js")
exports.run = async (client, message, args) => {
let guildId = message.guild.id
let channel = (message.mentions.channels.first()) ? message.mentions.channels.first().id : ``
let check = await SetText.exists({guildid: guildId})
let foundGuild = (check) ? await SetText.findOne({guildid: guildId}) : new SetText()
async function setEmbed(embed ,description, foundGuild){
embed.setDescription(description)
const channelList = foundGuild.channels.map((channel) => {
return `> <#${channel}> \n`
})
embed.setColor(`#800080`)
embed.addField(`Channels :`, channelList)
await message.channel.send(embed)
}
if(args[0] === `add`){
function setChannel(foundGuild){
foundGuild.guildid = guildId
foundGuild.channels.push(channel)
foundGuild.save()
.then(async () => {
let confirmation = new Discord.MessageEmbed().setTitle(`📀 Channels recording texts.`)
let description = `✅ <#${channel}> has been set to record texts.`
await setEmbed(confirmation, description,foundGuild)
})
.catch((err) => {
console.log(err.message)
message.channel.send(`Something went wrong. Please try again.`)
})
}
setChannel(foundGuild)
}
else if(args[0] === `remove`){
foundGuild.channels = foundGuild.channels.filter((theChannel) => (theChannel === channel) ? false : true )
foundGuild.save()
.then(() => {
message.channel.send(`Channel successfully removed.`)
})
.catch((err) => console.log(err))
}
else if(args[0] === `view`){
let viewEmbed = new Discord.MessageEmbed().setTitle(`📀 Channels recording texts.`)
let viewDescription = ``
await setEmbed(viewEmbed, viewDescription, foundGuild)
}
}
exports.help = {
name: "settext",
}; | 27275a67679dc581f3b7aef5bb35c8528959355d | [
"JavaScript"
] | 17 | JavaScript | thacypherbot/thacypherbot-main | 338caf9f27cfced1829b56655bcb25e78339e9d8 | a851836d6ee4968f332144b8158e1b4ee414f54d |
refs/heads/main | <file_sep>url <- "https://d396qusza40orc.cloudfront.net/exdata%2Fdata%2Fhousehold_power_consumption.zip"
dir <- "C:/Users/Arun/Documents/Exploratory Data Analysis/data.zip"
data <- download.file(url,dir)
unzip("C:/Users/Arun/Documents/Exploratory Data Analysis/data.zip")
data <- "C:/Users/Arun/Documents/Exploratory Data Analysis/household_power_consumption.txt"
#load the data
datatable <- read.csv(data,header=T, sep=';', na.strings="?",
nrows=2075259, check.names=F, stringsAsFactors=F, comment.char="", quote='\"')
data1 <- subset(datatable, Date %in% c("1/2/2007","2/2/2007"))
data1$Date <- as.Date(data1$Date, format="%d/%m/%Y")
hist(data1$Global_active_power, main="Global Active Power",
xlab="Global Active Power (kilowatts)", ylab="Frequency", col="Red")
#save the png
png("plot1.png", width=480, height=480)
dev.off() | b1ccbf598f7fa5ec443462120c16cd14cc4a04e2 | [
"R"
] | 1 | R | arunkumard001/Exploratory-Data-Analysis | 35aae02ca6240f54c3f3aefad36d2a8a2d578bcd | 41bf2d29baf4b394467129d74eb1bbb1e79b12c0 |
refs/heads/master | <repo_name>xyl1t/Tetris<file_sep>/Tetris/Model.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Threading;
using System.Diagnostics;
namespace Tetris
{
public class Model
{
Random random = new Random();
bool GameAlive = true;
Graphics gfx;
sbyte[,] gameField;
Tetro currentTetro;
Bitmap playGroundImage;
public Bitmap PlayGroundImage
{
get { return playGroundImage; }
private set { playGroundImage = value; }
}
int width = 10, height = 16;
public Model()
{
gameField = new sbyte[height, width];
playGroundImage = new Bitmap(width * 20, height * 20);
createNewTetro();
Debug.Print(string.Format("height: {0} width: {1}", gameField.GetUpperBound(0), gameField.GetUpperBound(1)));
for(int i = 0; i < width; i++)
for (int j = 0; j < height; j++)
{
if (j == height - 1)
gameField[gameField.GetUpperBound(0), i] = 0;
else
gameField[j, i] = -1;
}
gfx = Graphics.FromImage(playGroundImage);
drawGame();
}
int fps = 0, frames = 0;
long timeStarted = Environment.TickCount;
int plusTime = 750;
public void Play()
{
while (GameAlive)
{
if (Environment.TickCount >= timeStarted + plusTime)
{
fps = frames;
frames = 0;
timeStarted = Environment.TickCount;
if (currentTetro.Fall())
{
}
else if (currentTetro.Y != 0)
{
clearLines();
createNewTetro();
}
else
{
System.Windows.Forms.MessageBox.Show("!");
GameAlive = false;
}
}
drawGame();
frames++;
}
}
private void drawGame()
{
Monitor.Enter(playGroundImage);
for (int y = 0; y < height - 1; y++)
{
for (int x = 0; x < width; x++)
{
if (gameField[y, x] != -1)
{
gfx.DrawImage(Tetris.Properties.Resources.tiles,
x * 20, y * 20,
new Rectangle(gameField[y, x], 0, 20, 20),
GraphicsUnit.Pixel);
}
else
{
gfx.DrawImage(Tetris.Properties.Resources.tiles,
x * 20, y * 20,
new Rectangle(140, 0, 20, 20),
GraphicsUnit.Pixel);
}
if (x == 0 && y == 0)
gfx.DrawString("0", new Font("", 6), Brushes.Black, x * 20, y * 20);
else if (x == 0 && y != 0)
gfx.DrawString(y.ToString(), new Font("", 6), Brushes.Black, x * 20, y * 20);
else if (x != 0 && y == 0)
gfx.DrawString(x.ToString(), new Font("", 6), Brushes.Black, x * 20, y * 20);
}
}
Monitor.Exit(playGroundImage);
}
void createNewTetro()
{
int r = (random.Next(70)/10);
switch (r)
{
case 0:
currentTetro = new Tetro(gameField, TetroType.T);
break;
case 1:
currentTetro = new Tetro(gameField, TetroType.I);
break;
case 2:
currentTetro = new Tetro(gameField, TetroType.J);
break;
case 3:
currentTetro = new Tetro(gameField, TetroType.L);
break;
case 4:
currentTetro = new Tetro(gameField, TetroType.O);
break;
case 5:
currentTetro = new Tetro(gameField, TetroType.S);
break;
case 6:
currentTetro = new Tetro(gameField, TetroType.Z);
break;
}
//t = new Tetro(gameField, TetroType.O);
}
public void RotateCurrentTetro()
{
currentTetro.Rotate();
drawGame();
}
public void MoveCurrentTetroRight()
{
if (currentTetro.CheckRight())
{
currentTetro.MoveRight();
drawGame();
}
}
public void MoveCurrentTetroLeft()
{
if (currentTetro.CheckLeft())
{
currentTetro.MoveLeft();
drawGame();
}
}
public void SpeedUp()
{
plusTime = 50;
}
public void StopSpeedUp()
{
plusTime = 750;
}
public void Finish()
{
currentTetro.KickDown();
clearLines();
createNewTetro();
drawGame();
}
int clearLines()
{
int index = 0;
int blocks = 0;
for (int y = 1; y < 15; y++)
{
for (int x = 0; x < width; x++)
{
if (gameField[y, x] != -1)
blocks++;
}
if (blocks == width)
{
Debug.Print(" - LINE FULL - ");
index = y;
clearLine(index);
dropLines(index);
}
blocks = 0;
}
return index;
}
void clearLine(int index)
{
for (int i = 0; i < width; i++)
gameField[index, i] = -1;
}
void dropLines(int index)
{
for (int y = index; y > 1; y--)
{
for (int x = 0; x < width; x++)
{
gameField[y, x] = gameField[y - 1, x];
gameField[y - 1, x] = -1;
}
}
}
}
}
<file_sep>/Tetris/View.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
namespace Tetris
{
public partial class View : UserControl
{
Model model;
public View(Model model)
{
InitializeComponent();
this.model = model;
}
protected override void OnPaint(PaintEventArgs e)
{
Monitor.Enter(model.PlayGroundImage);
e.Graphics.DrawImage(model.PlayGroundImage, 2, 2);
this.Invalidate();
Monitor.Exit(model.PlayGroundImage);
ControlPaint.DrawBorder3D(e.Graphics, e.ClipRectangle, Border3DStyle.Sunken);
}
}
}
<file_sep>/Tetris/Tetro.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Diagnostics;
using System.Windows.Forms;
namespace Tetris
{
class Tetro
{
Random random = new Random();
sbyte[,] gameField;
sbyte[,] tetroField;
public sbyte[,] TetroField
{
get { return tetroField; }
private set { tetroField = value; }
}
TetroType type;
public TetroType Type
{
get { return type; }
set
{
type = value;
}
}
int x, y;
public int X
{
get { return x; }
private set { x = value; }
}
public int Y
{
get { return y; }
private set { y = value; }
}
public Tetro(sbyte[,] gameField, TetroType type)
{
this.Type = type;
this.gameField = gameField;
setTetroField();
y = 0;
x = gameField.GetUpperBound(1) / 2 - tetroField.GetUpperBound(1)/2;
Fill();
}
private void setTetroField()
{
sbyte t = (sbyte)this.Type;
switch (this.Type)
{
case TetroType.T:
TetroField = new sbyte[3, 3]
{
{-1, -1, -1 },
{ t, t, t },
{ -1, t, -1 },
};
break;
case TetroType.Z:
this.TetroField = new sbyte[3, 3]
{
{ t, t, -1 },
{ -1, t, t },
{ -1, -1, -1 },
};
break;
case TetroType.S:
TetroField = new sbyte[3, 3]
{
{ -1, t, t },
{ t, t, -1 },
{ -1, -1, -1 },
};
break;
case TetroType.O:
TetroField = new sbyte[2, 2]
{
{ t, t },
{ t, t },
};
break;
case TetroType.L:
TetroField = new sbyte[3, 3]
{
{ -1, t, -1 },
{ -1, t, -1 },
{ -1, t, t },
};
break;
case TetroType.J:
TetroField = new sbyte[3, 3]
{
{ -1, t, -1 },
{ -1, t, -1 },
{ t, t, -1 },
};
break;
case TetroType.I:
TetroField = new sbyte[4, 4]
{
{ -1, t, -1, -1},
{ -1, t, -1, -1},
{ -1, t, -1, -1},
{ -1, t, -1, -1},
};
break;
}
}
private void Fill()
{
for (int y = 0; y < TetroField.GetUpperBound(0) + 1; y++)
{
for (int x = 0; x < TetroField.GetUpperBound(1) + 1; x++)
{
if (this.tetroField[y, x] != -1)
gameField[Math.Abs(y + this.Y), Math.Abs(x + this.X)] = tetroField[y, x];
}
}
}
private void Clear()
{
for (int y = 0; y < TetroField.GetUpperBound(0) + 1; y++)
{
for (int x = 0; x < TetroField.GetUpperBound(1) + 1; x++)
{
if (this.tetroField[y, x] != -1)
gameField[Math.Abs(y + this.Y), Math.Abs(x + this.X)] = -1;
}
}
}
public bool Fall()
{
int summand = 1;
for (int y = 0; y < TetroField.GetUpperBound(0) + 1; y++)
{
for (int x = 0; x < TetroField.GetUpperBound(1) + 1; x++)
{
if (tetroField[y, x] != -1)
{
if (y == TetroField.GetUpperBound(1))
summand = 0;
if (gameField[this.Y + y + 1, this.X + x] != -1 &&
(summand == 0 || tetroField[y + summand, x] == -1))
return false;
}
}
}
Clear();
this.Y++;
Fill();
return true;
}
public bool KickDown()
{
int summand = 1;
Clear();
do
{
for (int y = 0; y < TetroField.GetUpperBound(1) + 1; y++)
{
for (int x = 0; x < TetroField.GetUpperBound(0) + 1; x++)
{
if (tetroField[y, x] != -1)
{
if (y == TetroField.GetUpperBound(1))
summand = 0;
if (gameField[this.Y + y + 1, this.X + x] != -1 && (summand == 0 || tetroField[y + summand, x] == -1))
{
Fill();
return false;
}
}
}
}
this.Y++;
}
while (true);
}
public void Rotate()
{
if (this.Type != TetroType.O)
{
int center = 2;
if(this.type == TetroType.I)
center = 3;
sbyte[,] temp = new sbyte[TetroField.GetUpperBound(0) + 1, TetroField.GetUpperBound(0) + 1];
for (int y = 0; y < TetroField.GetUpperBound(0) + 1; y++)
{
for (int x = 0; x < TetroField.GetUpperBound(1) + 1; x++)
{
if (-y + center >= 0)
temp[-y + center, x] = TetroField[x, y];
}
}
for (int y = 0; y < TetroField.GetUpperBound(0) + 1; y++)
{
for (int x = 0; x < TetroField.GetUpperBound(1) + 1; x++)
{
if (temp[y, x] != -1)
{
if (this.X < 0)
{
if (CheckRight())
{
MoveRight();
}
else
return;
}
else if (this.X + this.tetroField.GetUpperBound(1) + 1 > gameField.GetUpperBound(1) + 1)
{
if (CheckLeft())
{
MoveLeft();
}
else
return;
}
}
}
}
Clear();
TetroField = temp;
Fill();
}
}
public void MoveRight()
{
Clear();
this.X++;
Fill();
}
public void MoveLeft()
{
Clear();
this.X--;
Fill();
}
public void MoveUp()
{
if (this.Y > 0)
{
Clear();
this.Y--;
Fill();
}
}
public bool CheckRight()
{
int summand = 1;
for (int x = 0; x < TetroField.GetUpperBound(1) + 1; x++)
{
for (int y = 0; y < TetroField.GetUpperBound(0) + 1; y++)
{
if (x + this.X >= gameField.GetUpperBound(1))
{
if (tetroField[y, x] != -1)
return false;
}
if (tetroField[y, x] != -1)
{
if (x == TetroField.GetUpperBound(0))
summand = 0;
if (gameField[this.Y + y, this.X + x + 1] != -1 && (summand == 0 || tetroField[y, x + summand] == -1))
return false;
}
summand = 1;
}
}
return true;
}
public bool CheckLeft()
{
int summand = 1;
for (int x = 0; x < TetroField.GetUpperBound(1); x++)
{
for (int y = 0; y < TetroField.GetUpperBound(0); y++)
{
if (x + this.X <= 0)
{
if (tetroField[y, x] != -1)
return false;
}
if (tetroField[y, x] != -1)
{
if (x == 0)
summand = 0;
if (gameField[this.Y + y, this.X + x - 1] != -1 && (summand == 0 || tetroField[y, x - summand] == -1))
return false;
}
summand = 1;
}
}
return true;
}
}
}
<file_sep>/README.md
# Tetris
Be aware there is a bug when the tetrominos stack up too high, but everything else seems to work.
<file_sep>/Tetris/MainForm.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Diagnostics;
namespace Tetris
{
public partial class MainForm : Form
{
Model model;
View view;
Thread game;
public MainForm()
{
InitializeComponent();
//comboBox1.DataSource = Enum.GetValues(typeof(TetroColor));
model = new Model();
view = new View(model);
view.PreviewKeyDown += new PreviewKeyDownEventHandler(view_PreviewKeyDown);
view.KeyUp += new KeyEventHandler(view_KeyUp);
view.Location = new Point(13, 13);
this.Controls.Add(view);
game = new Thread(model.Play);
game.Start();
}
void view_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Down)
model.StopSpeedUp();
}
void view_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
switch (e.KeyCode)
{
case Keys.Up:
model.RotateCurrentTetro();
break;
case Keys.Right:
model.MoveCurrentTetroRight();
break;
case Keys.Left:
model.MoveCurrentTetroLeft();
break;
case Keys.Down:
model.SpeedUp();
break;
case Keys.Space:
model.Finish();
break;
}
}
private void MainForm_FormClosed(object sender, FormClosedEventArgs e)
{
if (game != null && game.IsAlive)
game.Abort();
}
}
}
/*
private void btn_update_Click(object sender, EventArgs e)
{
//using (Graphics gfx = Graphics.FromImage(gameFieldBmp))
//{
// for (int x = 0; x < width; x++)
// {
// for (int y = 0; y < height; y++)
// {
// if (gameField[y, x])
// {
// gfx.DrawImage(Tetris.Properties.Resources.tiles,
// x * 20, y * 20,
// new Rectangle(20, 0, 20, 20),
// GraphicsUnit.Pixel);
// }
// else
// {
// gfx.DrawImage(Tetris.Properties.Resources.tiles,
// x * 20, y * 20,
// new Rectangle(140, 0, 20, 20),
// GraphicsUnit.Pixel);
// }
// }
// }
//}
//this.view1.Invalidate();
}
private void btn_rotate_Click(object sender, EventArgs e)
{
//t.Rotate();
//btn_update.PerformClick();
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
//t.Color = (TetroColor)Enum.Parse(typeof(TetroColor),comboBox1.SelectedValue.ToString());
}
protected override bool IsInputKey(Keys keyData)
{
switch (keyData)
{
case Keys.Up:
model.RotateCurrentTetro();
break;
case Keys.Right:
model.MoveCurrentTetroRight();
break;
case Keys.Left:
model.MoveCurrentTetroTetro();
break;
case Keys.Down:
model.SpeedUp();
break;
case Keys.Space:
model.Finish();
break;
return true;
}
return base.IsInputKey(keyData);
}
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
switch (e.KeyCode)
{
case Keys.Up:
model.RotateCurrentTetro();
break;
case Keys.Right:
model.MoveCurrentTetroRight();
break;
case Keys.Left:
model.MoveCurrentTetroTetro();
break;
case Keys.Down:
model.SpeedUp();
break;
case Keys.Space:
model.Finish();
break;
}
}
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
}
private void btn_fall_Click(object sender, EventArgs e)
{
//t.Fall();
//btn_update.PerformClick();
}
*/ | 7eb20c337b507a9051113d733f5b263b5bea6cbb | [
"Markdown",
"C#"
] | 5 | C# | xyl1t/Tetris | 575a729deb9b9cac28f38f4a36c370b967090e06 | be2b326abd559c739eae8b801d7c7ecb4b180131 |
refs/heads/master | <repo_name>IkarosKappler/text_replacer.sh<file_sep>/text_replacer.sh
#!/bin/bash
#
# This script replaces the text pattern PATTERN by the text REPLACEMENT in all
# files from the passed file list.
#
# Note that each entry of the file list consists of
# <input_file> : <output_file>
#
#
# @author <NAME>
# @date 2016-07-22
# @version 1.0.0
_RED='\033[0;31m'
_GREEN='\033[0;32m'
_PURPLE='\033[0;35m'
_NC='\033[0m'
echo -e "${_PURPLE}This script replaces PATTERN by REPLACEMENT (strings) in all files from your passed file list.${_NC}"
if [ $# -lt 3 ]; then
echo -e "[${_RED}Error${_NC}] Please pass: <pattern> <replacement> <filelist>";
echo -e " Example: ${_GREEN}${0##*/} \"foo\" \"bar\" filelist.txt${_NC}"
echo -e " (replaces each 'foo' by 'bar')"
echo -e " Please note that each file list entry (line) must consists of: "
echo -e " <input_file> : <output_file>"
exit 1;
fi
pattern=$1
replacement=$2
filelist=$3
if [ ! -f "$filelist" ]; then
echo "Filelist '$filelist' not found."
exit 1
fi
line_no=1
entry_no=1
while read line
do
# Trim line:
var="${line#"${line%%[![:space:]]*}"}" # remove leading whitespace characters
var="${line%"${line##*[![:space:]]}"}" # remove trailing whitespace characters
# Check if line is not empty
if [ ! -z "$line" -a "$line"!=" " ]; then
# Check if line is no comment (beginning with ';').
if [[ ${line:0:1} != ';' ]]; then
# Split line into two party, separated by ':'.
entry=(${line//:/ })
infile=${entry[0]};
outfile=${entry[1]};
# echo "infile=$infile";
# echo "outfile=$outfile";
if [ ! -f $infile ]; then
echo "Error: file '$infile' not found."
exit 1;
fi
# Escape the replacement string for SED.
replacement=$(echo $replacement | sed -e 's/[\/&]/\\&/g')
echo "[$entry_no] Running 'sed \"s/$pattern/$replacement/g\" $infile > $outfile'"
# Run the command.
result=$(sed "s/$pattern/$replacement/g" $infile > $outfile)
ec="$?"
if [ "$ec" -ne "0" ]; then
echo -e "[${_RED}Error${_NC}] Failed at line $line_no. Exit code $ec"
exit 1
fi
entry_no=`expr $entry_no + 1`;
fi
fi
line_no=`expr $line_no + 1`;
done < $filelist
<file_sep>/insert_file.sh
#!/bin/bash
#
# This script reads from stdin and inserts its data in the passed file where the
# This script expecst three parameters: input_file pattern
#
# THIS IS JUST A TEST AN WORKS ONLY WITH FULL LINE PATTERNS!
#
# Inspired by
# http://unix.stackexchange.com/questions/32908/how-to-insert-the-content-of-a-file-into-another-file-before-a-pattern-marker
_RED='\033[0;31m'
_GREEN='\033[0;32m'
_PURPLE='\033[0;35m'
_NC='\033[0m'
if [ $# -lt 2 ]; then
echo -e "[${_RED}Error${_NC}] Please pass: input_file pattern [insert_file|stdin]";
echo -e " Example 1: ${_GREEN}${0##*/} "my_input.js" \"bar\" insert_data.txt${_NC}"
echo -e " Example 2: ${_GREEN}${0##*/} "my_input.js" \"bar\" << insert_data.txt${_NC}"
echo -e " "
exit 1;
fi
# If the file argument is the third argument to your script, test that
# there is an argument ($3) and that it is a file. Else read input from stdin -
[ $# -ge 3 -a -f "$3" ] && input="$3" || input="-"
insert_data=$(cat $input)
input_file=$1
pattern=$2
#input=$(cat /dev/stdin)
echo $insert_data
while IFS= read -r line
do
#if [[ "$line" =~ ^Pointer.*$ ]]
if [[ "$line" =~ $pattern ]]
then
cat file1
fi
echo "$line"
done < input_file
<file_sep>/README.md
# text_replacer.sh
A small text replacer bash script.
Replace text patterns in file sets. | 8c5c144f05b9de0b7e15cda247ffaae14be2e604 | [
"Markdown",
"Shell"
] | 3 | Shell | IkarosKappler/text_replacer.sh | ce45121d003632791407cd4f37da5364ee4352ae | 748710abc4958a742b59b09083e8f42af85a2cb7 |
refs/heads/master | <repo_name>abhisekdas0fficial/templates<file_sep>/element hover effect/main.js
const icard = document.querySelector(".icard");
icard.addEventListener("mousemove", e => {
icard.setAttribute("style", "transform: rotateX("+(-(e.layerY-150)*10/150)+"deg) rotateY("+((e.layerX-225)*7/225)+"deg);");
});
icard.addEventListener("mouseout", e => {
icard.setAttribute("style", "transform: rotateX(0deg) rotateY(0deg);");
});<file_sep>/scrolling video animation/main.js
const canvas = document.querySelector("#demo");
const context = canvas.getContext("2d");
gsap.registerPlugin(ScrollTrigger);
const currentFrame = index => (
`https://www.apple.com/105/media/us/airpods-pro/2019/1299e2f5_9206_4470_b28e_08307a42f19b/anim/sequence/large/01-hero-lightpass/${index.toString().padStart(4, '0')}.jpg`
)
canvas.width = 1158;
canvas.height = 770;
const frameCount = 147;
const images = [];
const progress = {
frameIndex: 1
};
function preloadImages() {
for (let i = 0; i < frameCount; i++) {
const img = new Image();
img.src = currentFrame(i + 1);
images.push(img);
}
}
preloadImages();
images[0].onload = render();
function render() {
context.drawImage(images[progress.frameIndex - 1], 0, 0);
}
gsap.to(progress, {
scrollTrigger: {
trigger: "section",
start: "bottom bottom",
end: "+=2600 top",
scrub: true,
pin: true
},
frameIndex: frameCount,
snap: "frameIndex",
onUpdate: function() {
requestAnimationFrame(() => render());
}
});<file_sep>/README.md
# Templates
Various Templates Designed by Me.
<file_sep>/text hover effect/main.js
const cursor1 = document.querySelector(".cursor-1");
const cursor2 = document.querySelector(".cursor-2");
const header = document.querySelector("header");
const logo = document.querySelector("#logo");
const section = document.querySelector("section");
var handler;
header.addEventListener("mousemove", handler = e => {
cursor1.setAttribute("style", "top: " + (e.pageY - 8) + "px; left: " + (e.pageX - 8) + "px; display: inline-block;");
});
header.addEventListener("mouseout", e => {
cursor1.style.display = "none";
});
section.addEventListener("mousemove", e => {
cursor2.setAttribute("style", "top: " + (e.pageY - 8) + "px; left: " + (e.pageX - 8) + "px; display: inline-block;");
});
section.addEventListener("mouseout", e => {
cursor2.style.display = "none";
});
logo.addEventListener("mouseover", e => {
header.removeEventListener("mousemove", handler);
});
logo.addEventListener("mouseout", e => {
header.addEventListener("mousemove", handler);
}); | 4f404dd298d96bd4f8fb9345e1550835b08b2fd6 | [
"JavaScript",
"Markdown"
] | 4 | JavaScript | abhisekdas0fficial/templates | 995366fefb6d4676a2274538bf91340b55458e5c | f528ef2eb17cf22498aef2925954f72b06fe6799 |
refs/heads/master | <repo_name>josias-m-soares/api-aspnetcore-ddd<file_sep>/Api.Service.Test/Login/QuandoForExecutadoLogin.cs
using System;
using System.Threading.Tasks;
using Domain.DTOs.Login;
using Domain.Interfaces.Services.Users;
using Faker;
using Moq;
using Xunit;
namespace Api.Services.Test.Login
{
public class QuandoForExecutadoLogin
{
private ILoginService _serviceLogin;
private Mock<ILoginService> _serviceMock;
[Fact(DisplayName = "E Possivel Executar Metod FindByLogin")]
public async Task E_Possivel_Executar_Metodo_FindByLogin()
{
var email = Internet.Email();
LoginResponseDto objRetorno = new LoginResponseDto(
true,
DateTime.UtcNow,
DateTime.UtcNow.AddHours(8),
Guid.NewGuid().ToString(),
Name.FullName(),
"Login efetuado com sucesso."
);
var loginDto = new LoginRequestDto
{
Email = email
};
_serviceMock = new Mock<ILoginService>();
_serviceMock.Setup(m => m.FindByLogin(loginDto)).ReturnsAsync(objRetorno);
_serviceLogin = _serviceMock.Object;
var result = await _serviceLogin.FindByLogin(loginDto);
Assert.NotNull(result);
}
}
}
<file_sep>/Api.Domain/DTOs/Login/LoginResponseDto.cs
using System;
namespace Domain.DTOs.Login
{
public class LoginResponseDto : ResponseBaseDto
{
public bool Authenticate {get; set;}
public DateTime Created {get; set;}
public DateTime Expiration {get; set;}
public string AcessToken {get; set;}
public string UserName {get; set;}
public string Message {get; set;}
public LoginResponseDto(){ }
public LoginResponseDto(bool authenticate, DateTime created, DateTime expiration, string acessToken, string userName, string message)
{
Authenticate = authenticate;
Created = created;
Expiration = expiration;
AcessToken = acessToken;
UserName = userName;
Message = message;
}
public LoginResponseDto(bool authenticate, string message)
{
Authenticate = authenticate;
Message = message;
}
}
}
<file_sep>/Api.Domain/Interfaces/Services/Users/ILoginService.cs
using System.Threading.Tasks;
using Domain.DTOs;
using Domain.DTOs.Login;
namespace Domain.Interfaces.Services.Users
{
public interface ILoginService
{
Task<LoginResponseDto> FindByLogin(LoginRequestDto requestDto);
}
}<file_sep>/Api.CrossCutting/Mappings/ModelToEntityProfile.cs
using AutoMapper;
using Data.Mapping;
using Domain.Entities;
using Domain.Models;
namespace CrossCutting.Mappings
{
public class ModelToEntityProfile : Profile
{
public ModelToEntityProfile()
{
CreateMap<UserEntity, UserModel>().ReverseMap();
}
}
}<file_sep>/Api.Data.Test/UsuarioCrudCompleto.cs
using System;
using System.Linq;
using System.Threading.Tasks;
using Data.Context;
using Data.Implementations;
using Domain.Entities;
using Microsoft.Extensions.DependencyInjection;
using Xunit;
namespace Api.Data.Test
{
public class UsuarioCrudCompleto : BaseTest, IClassFixture<DbTeste>
{
private ServiceProvider _serviceProvider;
public UsuarioCrudCompleto(DbTeste dbTest)
{
_serviceProvider = dbTest.ServiceProvider;
}
[Fact(DisplayName = "CRUD de Usuario")]
[Trait("CRUD", "UserEntity")]
public async Task E_Possivel_Realizar_CRUD_Usuario()
{
await using (var context = _serviceProvider.GetService<MyContext>())
{
var repository = new UserImplementation(context);
var entity = new UserEntity
{
Name = Faker.Internet.Email(),
Email = Faker.Name.FullName()
};
// Insert
var registroCriado = await repository.InsertAsync(entity);
Assert.NotNull(registroCriado);
Assert.False(registroCriado.Id == Guid.Empty);
Assert.Equal(entity.Name, registroCriado.Name);
Assert.Equal(entity.Email, registroCriado.Email);
//Update
entity.Name = Faker.Name.First();
var registroAtualizado = await repository.UpdateAsync(entity);
Assert.NotNull(registroAtualizado);
Assert.Equal(entity.Email, registroAtualizado.Email);
Assert.Equal(entity.Name, registroAtualizado.Name);
// Exist?
var registroExiste = await repository.ExistAsync(registroAtualizado.Id);
Assert.True(registroExiste);
// Select
var registroSelecionado = await repository.SelectAsync(registroAtualizado.Id);
Assert.NotNull(registroSelecionado);
Assert.Equal(registroSelecionado.Name, registroAtualizado.Name);
Assert.Equal(registroSelecionado.Email, registroAtualizado.Email);
// GetAll
var todosRegistros = await repository.SelectAsync();
Assert.NotNull(todosRegistros);
Assert.True(todosRegistros.Any());
// Login
var usuarioPadrao = await repository.FindByLogin("adm@email.com");
Assert.NotNull(usuarioPadrao);
Assert.Equal("Administrador", usuarioPadrao.Name);
Assert.Equal("<EMAIL>", usuarioPadrao.Email);
}
}
}
}
<file_sep>/Api.Domain/DTOs/Login/LoginRequestDto.cs
using System.ComponentModel.DataAnnotations;
namespace Domain.DTOs.Login
{
public class LoginRequestDto : RequestBaseDto
{
[Required(ErrorMessage = "Email is required.")]
[EmailAddress(ErrorMessage = "Email is not valid.")]
[StringLength(100, ErrorMessage = "Max length for Email {1}.")]
public string Email { get; set; }
}
}<file_sep>/Api.Application.Test/Usuario/QuandoRequisitarGet/RetornoGetOk.cs
using System;
using System.Threading.Tasks;
using Application.Controllers;
using Domain.DTOs.User;
using Domain.Interfaces.Services.Users;
using Faker;
using Microsoft.AspNetCore.Mvc;
using Moq;
using Xunit;
namespace Api.Application.Test.Usuario.QuandoRequisitarGet
{
public class RetornoGetOk
{
private UsersController _controller;
[Fact(DisplayName = "É possivel realizar um Get na UserController e retorna OK")]
public async Task E_Possivel_Invocar_a_UsersController_Get_Retornando_Ok()
{
var serviceMock = new Mock<IUserService>();
var name = Name.FullName();
var email = Internet.Email();
serviceMock.Setup(m => m.Get(It.IsAny<Guid>())).ReturnsAsync(new UserDto
{
Id = Guid.NewGuid(),
Name = name,
Email = email,
CreateAt = DateTime.UtcNow
});
_controller = new UsersController(serviceMock.Object);
var result = await _controller.Get(Guid.NewGuid());
Assert.True(result is OkObjectResult);
var resultValue = ((OkObjectResult) result).Value as UserDto;
Assert.NotNull(resultValue);
Assert.Equal(name, resultValue.Name);
Assert.Equal(email, resultValue.Email);
}
}
}<file_sep>/Api.Service.Test/Usuario/QuandoForExecutadoPut.cs
using System;
using System.Threading.Tasks;
using Domain.DTOs.User;
using Domain.Interfaces.Services.Users;
using Moq;
using Xunit;
using Xunit.Sdk;
namespace Api.Services.Test.Usuario
{
public class QuandoForExecutadoPut: UsuarioTestes
{
private IUserService _service;
private Mock<IUserService> _serviceMock;
[Fact(DisplayName = "Executar o metodo <Put> e retornar um objeto valido.")]
public async Task Executar_Metodo_Put_Recebe_Objeto_Valido()
{
// Criar Usuario
_serviceMock = new Mock<IUserService>();
_serviceMock.Setup(m => m.Post(UserDtoCreate)).ReturnsAsync(UserDtoCreateResult);
_service = _serviceMock.Object;
var resultCreate = await _service.Post(UserDtoCreate);
Assert.NotNull(resultCreate);
Assert.Equal(NomeUsuario, resultCreate.Name);
Assert.Equal(EmailUsuario, resultCreate.Email);
// Alterar Usuario
_serviceMock = new Mock<IUserService>();
_serviceMock.Setup(m => m.Put(UserDtoUpdate)).ReturnsAsync(UserDtoUpdateResult);
_service = _serviceMock.Object;
var resultUpdate = await _service.Put(UserDtoUpdate);
Assert.NotNull(resultUpdate);
Assert.Equal(NomeUsuarioAlterado, resultUpdate.Name);
Assert.Equal(EmailUsuarioAlterado, resultUpdate.Email);
}
}
}<file_sep>/Api.Domain/DTOs/User/UserDtoCreateResult.cs
using System;
namespace Domain.DTOs.User
{
public class UserDtoCreateResult : ResponseBaseDto
{
public UserDtoCreateResult()
{
}
public UserDtoCreateResult(Guid id, string name, string email, DateTime at)
{
Id = id;
Name = name;
Email = email;
CreateAt = at;
}
public Guid Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public DateTime CreateAt { get; set; }
//public DateTime UpdateAt { get; set; }
}
}
<file_sep>/Api.CrossCutting/Mappings/EntityToDtoProfile.cs
using AutoMapper;
using Domain.DTOs;
using Domain.DTOs.User;
using Domain.Entities;
namespace CrossCutting.Mappings
{
public class EntityToDtoProfile : Profile
{
public EntityToDtoProfile()
{
CreateMap<ResponseBaseDto, UserEntity>().ReverseMap();
CreateMap<RequestBaseDto, UserEntity>().ReverseMap();
CreateMap<UserDto, UserEntity>().ReverseMap();
CreateMap<UserDto, UserEntity>().ReverseMap();
CreateMap<UserDtoCreate, UserEntity>().ReverseMap();
CreateMap<UserDtoCreateResult, UserEntity>().ReverseMap();
CreateMap<UserDtoUpdate, UserEntity>().ReverseMap();
CreateMap<UserDtoUpdateResult, UserEntity>().ReverseMap();
}
}
}<file_sep>/Api.Service.Test/Usuario/QuandoForExecutadoGetAll.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Domain.DTOs.User;
using Domain.Interfaces.Services.Users;
using Moq;
using Xunit;
namespace Api.Services.Test.Usuario
{
public class QuandoForExecutadoGetAll: UsuarioTestes
{
private IUserService _service;
private Mock<IUserService> _serviceMock;
[Fact(DisplayName = "Executar o metodo <GetAll> e retornar uma lista com objetos.")]
public async Task Executar_Metodo_GetAll_Retorna_Lista_Com_Objetos()
{
_serviceMock = new Mock<IUserService>();
_serviceMock.Setup(m => m.GetAll()).ReturnsAsync(listaUserDtos);
_service = _serviceMock.Object;
var results = await _service.GetAll();
Assert.NotNull(results);
Assert.True(results.Count() == listaUserDtos.Count());
}
[Fact(DisplayName = "Executar o metodo <GetAll> e retornar uma lista vazia.")]
public async Task Executar_Metodo_GetAll_Retorna_Lista_Vazia()
{
var listResults = new List<UserDto>();
_serviceMock = new Mock<IUserService>();
_serviceMock.Setup(m => m.GetAll()).ReturnsAsync(listResults.AsEnumerable);
_service = _serviceMock.Object;
var results = await _service.GetAll();
Assert.Empty(results);
Assert.True(!results.Any());
}
}
}<file_sep>/Api.Domain/Interfaces/Services/Users/IUserService.cs
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Domain.DTOs.User;
namespace Domain.Interfaces.Services.Users
{
public interface IUserService
{
Task<UserDto> Get(Guid id);
Task<IEnumerable<UserDto>> GetAll();
Task<UserDtoCreateResult> Post(UserDtoCreate dto);
Task<UserDtoUpdateResult> Put(UserDtoUpdate dto);
Task<bool> Delete(Guid id);
}
}<file_sep>/Api.Service/Services/UserService.cs
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using AutoMapper;
using Domain.DTOs.User;
using Domain.Entities;
using Domain.Interfaces;
using Domain.Interfaces.Services.Users;
using Domain.Models;
namespace Service.Services
{
public class UserService : IUserService
{
private IRepository<UserEntity> _repository;
private readonly IMapper _mapper;
public UserService(IRepository<UserEntity> repository, IMapper mapper)
{
_repository = repository;
_mapper = mapper;
}
public async Task<UserDto> Get(Guid id)
{
var entity = await _repository.SelectAsync(id);
return _mapper.Map<UserDto>(entity);
}
public async Task<IEnumerable<UserDto>> GetAll()
{
var listEntity = await _repository.SelectAsync();
return _mapper.Map<IEnumerable<UserDto>>(listEntity);
}
public async Task<UserDtoCreateResult> Post(UserDtoCreate dto)
{
var model = _mapper.Map<UserModel>(dto);
var entity = _mapper.Map<UserEntity>(model);
var result = await _repository.InsertAsync(entity);
return _mapper.Map<UserDtoCreateResult>(result);
}
public async Task<UserDtoUpdateResult> Put(UserDtoUpdate dto)
{
var model = _mapper.Map<UserModel>(dto);
var entity = _mapper.Map<UserEntity>(model);
var result =await _repository.UpdateAsync(entity);
return _mapper.Map<UserDtoUpdateResult>(result);
}
public async Task<bool> Delete(Guid id)
{
return await _repository.DeleteAsync(id);
}
}
}<file_sep>/Api.Service.Test/Usuario/QuandoForExecutadoGet.cs
using System;
using System.Threading.Tasks;
using Domain.DTOs.User;
using Domain.Interfaces.Services.Users;
using Moq;
using Xunit;
namespace Api.Services.Test.Usuario
{
public class QuandoForExecutadoGet: UsuarioTestes
{
private IUserService _service;
private Mock<IUserService> _serviceMock;
[Fact(DisplayName = "Executar o metodo <Get> e retornar um objeto valido.")]
public async Task Executar_Metodo_Get_Recebe_Objeto_Valido()
{
_serviceMock = new Mock<IUserService>();
_serviceMock.Setup(m => m.Get(IdUsuario)).ReturnsAsync(UserDto);
_service = _serviceMock.Object;
var result = await _service.Get(IdUsuario);
Assert.NotNull(result);
Assert.True(result.Id == IdUsuario);
Assert.Equal(NomeUsuario, result.Name);
}
[Fact(DisplayName = "Executar o metodo <Get> e retornar um objeto NULL.")]
public async Task Executar_Metodo_Get_Recebe_Objeto_Nulo()
{
_serviceMock = new Mock<IUserService>();
_serviceMock.Setup(m => m.Get(It.IsAny<Guid>())).Returns(Task.FromResult((UserDto) null));
_service = _serviceMock.Object;
var result = await _service.Get(IdUsuario);
Assert.Null(result);
}
}
}
<file_sep>/Api.Application.Test/Usuario/QuandoRequisitarUpdate/RetornoUpdateBadRequest.cs
using System;
using System.Threading.Tasks;
using Application.Controllers;
using Domain.DTOs.User;
using Domain.Interfaces.Services.Users;
using Faker;
using Microsoft.AspNetCore.Mvc;
using Moq;
using Xunit;
namespace Api.Application.Test.Usuario.QuandoRequisitarUpdate
{
public class RetornoUpdateBadRequest
{
private UsersController _controller;
[Fact(DisplayName = "É possivel realizar o Update na UsersController e retornar um BadRequest")]
public async Task E_Possivel_Invocar_a_UsersController_Update_Retornando_BadRequest()
{
var serviceMock = new Mock<IUserService>();
var name = Name.FullName();
var email = Internet.Email();
serviceMock.Setup(m => m.Put(It.IsAny<UserDtoUpdate>())).ReturnsAsync(
new UserDtoUpdateResult
{
Id = Guid.NewGuid(),
Name = name,
Email = email,
CreateAt = DateTime.UtcNow
});
_controller = new UsersController(serviceMock.Object);
_controller.ModelState.AddModelError("Name", "É um campo Obrigatório");
Mock<IUrlHelper> url = new Mock<IUrlHelper>();
url.Setup(x => x.Link(It.IsAny<string>(), It.IsAny<Object>())).Returns("http://localhost:5000");
_controller.Url = url.Object;
var userDtoUpdate = new UserDtoUpdate
{
Name = name,
Email = email,
};
var result = await _controller.Put(userDtoUpdate);
Assert.True(result is BadRequestObjectResult);
Assert.False(_controller.ModelState.IsValid);
}
}
}
<file_sep>/Api.CrossCutting/Mappings/DtoToModelProfile.cs
using AutoMapper;
using Domain.DTOs;
using Domain.DTOs.User;
using Domain.Models;
namespace CrossCutting.Mappings
{
public class DtoToModelProfile : Profile
{
public DtoToModelProfile()
{
CreateMap<UserModel, ResponseBaseDto>().ReverseMap();
CreateMap<UserModel, RequestBaseDto>().ReverseMap();
CreateMap<UserModel, UserDtoCreate>().ReverseMap();
CreateMap<UserModel, UserDtoCreateResult>().ReverseMap();
CreateMap<UserModel, UserDtoUpdate>().ReverseMap();
CreateMap<UserModel, UserDtoUpdateResult>().ReverseMap();
CreateMap<UserModel, UserDto>().ReverseMap();
}
}
}<file_sep>/Api.Service/Services/LoginService.cs
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Security.Principal;
using System.Threading.Tasks;
using Domain.DTOs;
using Domain.DTOs.Login;
using Domain.Entities;
using Domain.Interfaces.Services.Users;
using Domain.Repository;
using Domain.Security;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using JwtRegisteredClaimNames = Microsoft.IdentityModel.JsonWebTokens.JwtRegisteredClaimNames;
namespace Service.Services
{
public class LoginService : ILoginService
{
private IUserRepository _repository;
private SigningConfigurations _signingConfigurations;
private IConfiguration _configuration;
public LoginService(IUserRepository repository, SigningConfigurations signingConfigurations, IConfiguration configuration)
{
_repository = repository;
_signingConfigurations = signingConfigurations;
_configuration = configuration;
}
public async Task<LoginResponseDto> FindByLogin(LoginRequestDto requestDto)
{
var response = new LoginResponseDto(false, "Falha ao autenticar");
if (requestDto != null && !string.IsNullOrWhiteSpace(requestDto.Email))
{
UserEntity entity = await _repository.FindByLogin(requestDto.Email);
if (entity == null)
{
return response;
}
var identity = new ClaimsIdentity(
new GenericIdentity(entity.Email),
new []
{
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
new Claim(JwtRegisteredClaimNames.UniqueName, entity.Email),
}
);
DateTime createDate = DateTime.Now;
DateTime expirationDate = createDate + TimeSpan.FromSeconds(Convert.ToDouble(Environment.GetEnvironmentVariable("Seconds")));
var handler = new JwtSecurityTokenHandler();
string token = CreateToken(identity, createDate, expirationDate, handler);
return SuccessObject(createDate, expirationDate, token, requestDto);
}
return response;
}
private LoginResponseDto SuccessObject(in DateTime createDate, in DateTime expirationDate, string token, LoginRequestDto user)
{
return new LoginResponseDto (
true,
createDate, //ToString("yyyy-MM-dd HH:mm:ss"),
expirationDate, //.ToString("yyyy-MM-dd HH:mm:ss"),
token,
user.Email,
"Login efetuado com sucesso."
);
}
private string CreateToken(ClaimsIdentity identity, DateTime createDate, DateTime expirationDate,
JwtSecurityTokenHandler handler)
{
var securityToken = handler.CreateToken(new SecurityTokenDescriptor
{
Issuer = Environment.GetEnvironmentVariable("Issuer"),
Audience = Environment.GetEnvironmentVariable("Audience"),
SigningCredentials = _signingConfigurations.SigningCredentials,
Subject = identity,
NotBefore = createDate,
Expires = expirationDate
});
var token = handler.WriteToken(securityToken);
return token;
}
}
}<file_sep>/Api.Service.Test/Usuario/QuandoForExecutadoDelete.cs
using System;
using System.Threading.Tasks;
using Domain.DTOs.User;
using Domain.Interfaces.Services.Users;
using Moq;
using Xunit;
namespace Api.Services.Test.Usuario
{
public class QuandoForExecutadoDelete: UsuarioTestes
{
private IUserService _service;
private Mock<IUserService> _serviceMock;
[Fact(DisplayName = "Executar o metodo <Delete> com sucesso")]
public async Task Executar_Metodo_Delete_Com_Sucesso()
{
_serviceMock = new Mock<IUserService>();
_serviceMock.Setup(m => m.Delete(IdUsuario)).ReturnsAsync(true);
_service = _serviceMock.Object;
var result = await _service.Delete(IdUsuario);
Assert.True(result);
}
[Fact(DisplayName = "Executar o metodo <Delete> com falha")]
public async Task Executar_Metodo_Delete_Com_Falha()
{
_serviceMock = new Mock<IUserService>();
_serviceMock.Setup(m => m.Delete(It.IsAny<Guid>())).ReturnsAsync(false);
_service = _serviceMock.Object;
var result = await _service.Delete(Guid.NewGuid());
Assert.False(result);
}
}
}<file_sep>/Api.Application.Test/Usuario/QuandoRequisitarGetAll/RetornoGetAllOk.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Application.Controllers;
using Domain.DTOs.User;
using Domain.Interfaces.Services.Users;
using Faker;
using Microsoft.AspNetCore.Mvc;
using Moq;
using Xunit;
namespace Api.Application.Test.Usuario.QuandoRequisitarGetAll
{
public class RetornoGetAllOk
{
private UsersController _controller;
[Fact(DisplayName = "É possivel realizar um GetAll na UserController e retorna OK")]
public async Task E_Possivel_Invocar_a_UsersController_GetAll_Retornando_Ok()
{
var serviceMock = new Mock<IUserService>();
serviceMock.Setup(m => m.GetAll()).ReturnsAsync(new List<UserDto>
{
new UserDto
{
Id = Guid.NewGuid(),
Name = Name.FullName(),
Email = Internet.Email(),
CreateAt = DateTime.UtcNow
},
new UserDto
{
Id = Guid.NewGuid(),
Name = Name.FullName(),
Email = Internet.Email(),
CreateAt = DateTime.UtcNow
}
});
_controller = new UsersController(serviceMock.Object);
var result = await _controller.GetAll();
Assert.True(result is OkObjectResult);
var resultValue = ((OkObjectResult) result).Value as IEnumerable<UserDto>;
Assert.NotNull(resultValue);
Assert.True(resultValue.Count() == 2);
}
}
}<file_sep>/Api.Application.Test/Usuario/QuandoRequisitarGet/RetornoGetBadRequest.cs
using System;
using System.Threading.Tasks;
using Application.Controllers;
using Domain.DTOs.User;
using Domain.Interfaces.Services.Users;
using Faker;
using Microsoft.AspNetCore.Mvc;
using Moq;
using Xunit;
namespace Api.Application.Test.Usuario.QuandoRequisitarGet
{
public class RetornoGetBadRequest
{
private UsersController _controller;
[Fact(DisplayName = "É possivel realizar um Get na UserController e retorna BadRequest")]
public async Task E_Possivel_Invocar_a_UsersController_Get_Retornando_BadRequest()
{
var serviceMock = new Mock<IUserService>();
serviceMock.Setup(m => m.Get(It.IsAny<Guid>())).ReturnsAsync(new UserDto
{
Id = Guid.NewGuid(),
Name = Name.FullName(),
Email = Internet.Email(),
CreateAt = DateTime.UtcNow
});
_controller = new UsersController(serviceMock.Object);
_controller.ModelState.AddModelError("Id", "Formato Invalido");
var result = await _controller.Get(Guid.NewGuid());
Assert.True(result is BadRequestObjectResult);
}
}
}
<file_sep>/Api.Service.Test/AutoMapper/UsuarioMapper.cs
using System;
using System.Collections.Generic;
using System.Linq;
using Domain.DTOs.User;
using Domain.Entities;
using Domain.Models;
using Faker;
using Xunit;
namespace Api.Services.Test.AutoMapper
{
public class UsuarioMapper : BaseTesteService
{
[Fact(DisplayName = "É possivel mapear Models para Entity")]
public void E_Possivel_Mapear_Models_P_Entity()
{
var model = new UserModel
{
Id = Guid.NewGuid(),
Name = Name.FullName(),
Email = Internet.Email(),
CreateAt = DateTime.UtcNow,
UpdateAt = DateTime.UtcNow
};
// Model => Entity
var modelToEntity = Mapper.Map<UserEntity>(model);
Assert.Equal(modelToEntity.Id, model.Id);
Assert.Equal(modelToEntity.Name, model.Name);
Assert.Equal(modelToEntity.Email, model.Email);
Assert.Equal(modelToEntity.CreateAt, model.CreateAt);
Assert.Equal(modelToEntity.UpdateAt, model.UpdateAt);
}
//Dto => Model
[Fact(DisplayName = "É possivel mapear Models para UserDto")]
public void E_Possivel_Mapear_Models_P_UserDto()
{
var model = new UserModel
{
Id = Guid.NewGuid(),
Name = Name.FullName(),
Email = Internet.Email(),
CreateAt = DateTime.UtcNow,
UpdateAt = DateTime.UtcNow
};
var modelToUserDto = Mapper.Map<UserDto>(model);
Assert.Equal(modelToUserDto.Id, model.Id);
Assert.Equal(modelToUserDto.Name, model.Name);
Assert.Equal(modelToUserDto.Email, model.Email);
Assert.Equal(modelToUserDto.CreateAt, model.CreateAt);
Assert.Equal(modelToUserDto.UpdateAt, model.UpdateAt);
}
[Fact(DisplayName = "É possivel mapear Models para UserDtoCreate")]
public void E_Possivel_Mapear_Models_P_UserDtoCreate()
{
var model = new UserModel
{
Id = Guid.NewGuid(),
Name = Name.FullName(),
Email = Internet.Email(),
CreateAt = DateTime.UtcNow,
UpdateAt = DateTime.UtcNow
};
var modelToUserDtoCreate = Mapper.Map<UserDtoCreate>(model);
Assert.Equal(modelToUserDtoCreate.Name, model.Name);
Assert.Equal(modelToUserDtoCreate.Email, model.Email);
}
[Fact(DisplayName = "É possivel mapear Models para UserDtoCreateResult")]
public void E_Possivel_Mapear_Models_P_UserDtoCreateResult()
{
var model = new UserModel
{
Id = Guid.NewGuid(),
Name = Name.FullName(),
Email = Internet.Email(),
CreateAt = DateTime.UtcNow,
UpdateAt = DateTime.UtcNow
};
var modelToUserDtoCreateResult = Mapper.Map<UserDtoCreateResult>(model);
Assert.Equal(modelToUserDtoCreateResult.Id, model.Id);
Assert.Equal(modelToUserDtoCreateResult.Name, model.Name);
Assert.Equal(modelToUserDtoCreateResult.Email, model.Email);
Assert.Equal(modelToUserDtoCreateResult.CreateAt, model.CreateAt);
//Assert.Equal(modelToUserDtoCreateResult.UpdateAt, model.UpdateAt);
}
[Fact(DisplayName = "É possivel mapear Models para UserDtoUpdate")]
public void E_Possivel_Mapear_Models_P_UserDtoUpdate()
{
var model = new UserModel
{
Id = Guid.NewGuid(),
Name = Name.FullName(),
Email = Internet.Email(),
CreateAt = DateTime.UtcNow,
UpdateAt = DateTime.UtcNow
};
var modelToUserDtoUpdate = Mapper.Map<UserDtoUpdate>(model);
Assert.Equal(modelToUserDtoUpdate.Id, model.Id);
Assert.Equal(modelToUserDtoUpdate.Name, model.Name);
Assert.Equal(modelToUserDtoUpdate.Email, model.Email);
}
[Fact(DisplayName = "É possivel mapear Models para UserDtoUpdateResult")]
public void E_Possivel_Mapear_Models_P_UserDtoUpdateResult()
{
var model = new UserModel
{
Id = Guid.NewGuid(),
Name = Name.FullName(),
Email = Internet.Email(),
CreateAt = DateTime.UtcNow,
UpdateAt = DateTime.UtcNow
};
var modelToUserDtoUpdateResult = Mapper.Map<UserDtoUpdateResult>(model);
Assert.Equal(modelToUserDtoUpdateResult.Id, model.Id);
Assert.Equal(modelToUserDtoUpdateResult.Name, model.Name);
Assert.Equal(modelToUserDtoUpdateResult.Email, model.Email);
Assert.Equal(modelToUserDtoUpdateResult.CreateAt, model.CreateAt);
Assert.Equal(modelToUserDtoUpdateResult.UpdateAt, model.UpdateAt);
}
// Entity => Dto
[Fact(DisplayName = "É possivel mapear Entity para DTOs")]
public void E_Possivel_Mapear_Entity_DTOs()
{
var entity = new UserEntity()
{
Id = Guid.NewGuid(),
Name = Name.FullName(),
Email = Internet.Email(),
CreateAt = DateTime.UtcNow,
UpdateAt = DateTime.UtcNow
};
// DTO => Entity
var entityToDto = Mapper.Map<UserDto>(entity);
Assert.Equal(entityToDto.Id, entity.Id);
Assert.Equal(entityToDto.Name, entity.Name);
Assert.Equal(entityToDto.Email, entity.Email);
Assert.Equal(entityToDto.CreateAt, entity.CreateAt);
Assert.Equal(entityToDto.UpdateAt, entity.UpdateAt);
}
[Fact(DisplayName = "É possivel mapear List<Entity> para List<DTOs>")]
public void E_Possivel_Mapear_Lista_Entity_P_Lista_DTOs()
{
var listEntity = new List<UserEntity>();
for (int i = 0; i < 10; i++)
{
var entity = new UserEntity
{
Id = Guid.NewGuid(),
Name = Name.FullName(),
Email = Internet.Email(),
CreateAt = DateTime.UtcNow,
UpdateAt = DateTime.UtcNow
};
listEntity.Add(entity);
}
var listDto = Mapper.Map<List<UserDto>>(listEntity);
Assert.True(listDto.Count() == listEntity.Count());
for (int i = 0; i < listEntity.Count(); i++)
{
Assert.Equal(listDto[i].Id, listEntity[i].Id);
Assert.Equal(listDto[i].Name, listEntity[i].Name);
Assert.Equal(listDto[i].Email, listEntity[i].Email);
Assert.Equal(listDto[i].CreateAt, listEntity[i].CreateAt);
Assert.Equal(listDto[i].UpdateAt, listEntity[i].UpdateAt);
}
}
[Fact(DisplayName = "É possivel mapear Entity para DtoCreate")]
public void E_Possivel_Mapear_Entity_P_DtoCreate()
{
var entity = new UserEntity()
{
Id = Guid.NewGuid(),
Name = Name.FullName(),
Email = Internet.Email(),
CreateAt = DateTime.UtcNow,
UpdateAt = DateTime.UtcNow
};
var entityToCreate = Mapper.Map<UserDtoCreate>(entity);
Assert.Equal(entityToCreate.Name, entity.Name);
Assert.Equal(entityToCreate.Email, entity.Email);
}
[Fact(DisplayName = "É possivel mapear Entity para DtoCreateResult")]
public void E_Possivel_Mapear_Entity_P_DtoCreateResult()
{
var entity = new UserEntity()
{
Id = Guid.NewGuid(),
Name = Name.FullName(),
Email = Internet.Email(),
CreateAt = DateTime.UtcNow,
UpdateAt = DateTime.UtcNow
};
var entityToCreateResult = Mapper.Map<UserDtoCreateResult>(entity);
Assert.Equal(entityToCreateResult.Id, entity.Id);
Assert.Equal(entityToCreateResult.Name, entity.Name);
Assert.Equal(entityToCreateResult.Email, entity.Email);
Assert.Equal(entityToCreateResult.CreateAt, entity.CreateAt);
//Assert.Equal(entityToCreateResult.UpdateAt, entity.UpdateAt);
}
[Fact(DisplayName = "É possivel mapear Entity para DtoUpdate")]
public void E_Possivel_Mapear_Entity_P_DtoUpdate()
{
var entity = new UserEntity()
{
Id = Guid.NewGuid(),
Name = Name.FullName(),
Email = Internet.Email(),
CreateAt = DateTime.UtcNow,
UpdateAt = DateTime.UtcNow
};
var entityToUpdate = Mapper.Map<UserDtoUpdate>(entity);
Assert.Equal(entityToUpdate.Id, entity.Id);
Assert.Equal(entityToUpdate.Name, entity.Name);
Assert.Equal(entityToUpdate.Email, entity.Email);
}
[Fact(DisplayName = "É possivel mapear Entity para DtoUpdateResult")]
public void E_Possivel_Mapear_Entity_P_DtoUpdateResult()
{
var entity = new UserEntity()
{
Id = Guid.NewGuid(),
Name = Name.FullName(),
Email = Internet.Email(),
CreateAt = DateTime.UtcNow,
UpdateAt = DateTime.UtcNow
};
var entityToUpdateResult = Mapper.Map<UserDtoUpdateResult>(entity);
Assert.Equal(entityToUpdateResult.Id, entity.Id);
Assert.Equal(entityToUpdateResult.Name, entity.Name);
Assert.Equal(entityToUpdateResult.Email, entity.Email);
Assert.Equal(entityToUpdateResult.CreateAt, entity.CreateAt);
Assert.Equal(entityToUpdateResult.UpdateAt, entity.UpdateAt);
}
}
}<file_sep>/Api.Integration.Test/LoginResponseDto.cs
using System;
using Newtonsoft.Json;
namespace Api.Integration.Test
{
public class LoginResponsezDto
{
[JsonProperty("authenticate")]
public bool Authenticate {get; set;}
[JsonProperty("created")]
public DateTime Created {get; set;}
[JsonProperty("expiration")]
public DateTime Expiration {get; set;}
[JsonProperty("acessToken")]
public string AcessToken {get; set;}
[JsonProperty("userName")]
public string UserName {get; set;}
[JsonProperty("message")]
public string Message {get; set;}
}
}<file_sep>/Api.Domain/DTOs/RequestBaseDto.cs
namespace Domain.DTOs
{
public class RequestBaseDto
{
}
}<file_sep>/Api.Domain/DTOs/User/UserDtoCreate.cs
using System.ComponentModel.DataAnnotations;
namespace Domain.DTOs.User
{
public class UserDtoCreate
{
public UserDtoCreate()
{
}
public UserDtoCreate(string name, string email)
{
Name = name;
Email = email;
}
[Required(ErrorMessage = "Nome é um campo obrigatório")]
[StringLength(60, ErrorMessage = "Nome deve ter no máximo {1} caracteres")]
public string Name { get; set; }
[Required(ErrorMessage = "Email um campo obrigatório")]
[StringLength(100, ErrorMessage = "Email deve ter no máximo {1} caracteres")]
[EmailAddress]
public string Email { get; set; }
}
}<file_sep>/Api.CrossCutting/DependencyInjection/ConfigureRepository.cs
using System;
using Data.Context;
using Data.Implementations;
using Data.Repository;
using Domain.Interfaces;
using Domain.Interfaces.Services.Users;
using Domain.Repository;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Service.Services;
namespace CrossCutting.DependencyInjection
{
public class ConfigureRepository
{
public static void ConfigureDependenciesRepository(IServiceCollection serviceCollection)
{
serviceCollection.AddScoped(typeof(IRepository<>), typeof(BaseRepository<>));
serviceCollection.AddScoped<IUserRepository, UserImplementation>();
var database = Environment.GetEnvironmentVariable("DATABASE") ?? "";
var dbConnection = Environment.GetEnvironmentVariable("DB_CONNECTION") ?? "";
if (database.ToLower().Equals("MYSQL".ToLower()))
{
serviceCollection.AddDbContext<MyContext>(options => options.UseMySql(dbConnection));
}
else
{
serviceCollection.AddDbContext<MyContext>(options => options.UseMySql("Server=localhost;Port=3306;Database=dbApi;Uid=root;Pwd=<PASSWORD>"));
}
}
}
}<file_sep>/Api.Application.Test/Usuario/QuandoRequisitarUpdate/RetornoUpdateOK.cs
using System;
using System.Threading.Tasks;
using Application.Controllers;
using Domain.DTOs.User;
using Domain.Interfaces.Services.Users;
using Faker;
using Microsoft.AspNetCore.Mvc;
using Moq;
using Xunit;
namespace Api.Application.Test.Usuario.QuandoRequisitarCreate
{
public class RetornoUpdateOk
{
private UsersController _controller;
[Fact(DisplayName = "É possivel realizar o Update na UsersControllere retornar Ok")]
public async Task E_Possivel_Invocar_a_UsersController_Update_Retornando_OK()
{
var serviceMock = new Mock<IUserService>();
var name = Name.FullName();
var email = Internet.Email();
serviceMock.Setup(m => m.Put(It.IsAny<UserDtoUpdate>())).ReturnsAsync(
new UserDtoUpdateResult
{
Id = Guid.NewGuid(),
Name = name,
Email = email,
UpdateAt = DateTime.UtcNow
});
_controller = new UsersController(serviceMock.Object);
Mock<IUrlHelper> url = new Mock<IUrlHelper>();
url.Setup(x => x.Link(It.IsAny<string>(), It.IsAny<Object>())).Returns("http://localhost:5000");
_controller.Url = url.Object;
var userDtoUpdate = new UserDtoUpdate
{
Name = name,
Email = email,
};
var result = await _controller.Put(userDtoUpdate);
Assert.True(result is OkObjectResult);
var resultValue = ((OkObjectResult) result).Value as UserDtoUpdateResult;
Assert.NotNull(resultValue);
Assert.Equal(userDtoUpdate.Name, resultValue.Name);
Assert.Equal(userDtoUpdate.Email, resultValue.Email);
Assert.True(resultValue.UpdateAt != null);
}
}
}
<file_sep>/Api.Domain/DTOs/Municipio/MunicipioDtoCompleto.cs
using System;
using System.Collections.Generic;
using Domain.DTOs.Uf;
using Domain.Entities;
namespace Domain.DTOs.Municipio
{
public class MunicipioDtoCompleto
{
public Guid Id { get; set; }
public string Nome { get; set; }
public int CodIBGE { get; set; }
public Guid UfId { get; set; }
public UfDto Uf { get; set; }
}
}<file_sep>/Api.Application.Test/Usuario/QuandoRequisitarGet/RetornoGetNoContent.cs
using System;
using System.Threading.Tasks;
using Application.Controllers;
using Domain.DTOs.User;
using Domain.Interfaces.Services.Users;
using Faker;
using Microsoft.AspNetCore.Mvc;
using Moq;
using Xunit;
namespace Api.Application.Test.Usuario.QuandoRequisitarGet
{
public class RetornoGetNoContent
{
private UsersController _controller;
[Fact(DisplayName = "É possivel realizar um Get na UserController e retorna NoContent")]
public async Task E_Possivel_Invocar_a_UsersController_Get_Retornando_NoContent()
{
var serviceMock = new Mock<IUserService>();
serviceMock.Setup(m => m.Get(It.IsAny<Guid>())).ReturnsAsync((UserDto) null);
_controller = new UsersController(serviceMock.Object);
var result = await _controller.Get(Guid.NewGuid());
Assert.True(result is NoContentResult);
}
}
}<file_sep>/Api.Application.Test/Usuario/QuandoRequisitarDelete/RetornoDeleteOK.cs
using System;
using System.Threading.Tasks;
using Application.Controllers;
using Domain.DTOs.User;
using Domain.Interfaces.Services.Users;
using Faker;
using Microsoft.AspNetCore.Mvc;
using Moq;
using Xunit;
namespace Api.Application.Test.Usuario.QuandoRequisitarDelete
{
public class RetornoUpdateOk
{
private UsersController _controller;
[Fact(DisplayName = "É possivel realizar o Delete na UsersControllere retornar true")]
public async Task E_Possivel_Invocar_a_UsersController_Delete_Retornando_True()
{
var serviceMock = new Mock<IUserService>();
serviceMock.Setup(m => m.Delete(It.IsAny<Guid>())).ReturnsAsync(true);
_controller = new UsersController(serviceMock.Object);
var result = await _controller.Delete(Guid.NewGuid());
Assert.True(result is OkObjectResult);
var resultValue = ((OkObjectResult) result).Value;
Assert.NotNull(resultValue);
Assert.True((bool) resultValue);
}
}
}
<file_sep>/Api.Data/Mapping/UserMap.cs
using Domain.Entities;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
namespace Data.Mapping
{
public class UserMap : IEntityTypeConfiguration<UserEntity>
{
public void Configure(EntityTypeBuilder<UserEntity> builder)
{
builder
.ToTable("User");
builder
.HasKey(t => t.Id);
builder
.HasIndex(t => t.Email)
.IsUnique();
builder
.Property(t => t.Name)
.IsRequired()
.HasMaxLength(60);
builder
.Property(t => t.Email)
.HasMaxLength(100);
}
}
}<file_sep>/README.md
# api-aspnetcore-ddd
Api AspNetCore com DDD
<file_sep>/Api.Domain/DTOs/ResponseBaseDto.cs
namespace Domain.DTOs
{
public class ResponseBaseDto
{
public ResponseBaseDto()
{
}
}
}<file_sep>/Api.Domain/DTOs/Cep/CepDtoCreate.cs
using System;
using System.ComponentModel.DataAnnotations;
using Domain.DTOs.Municipio;
using Domain.Entities;
namespace Domain.DTOs.Cep
{
public class CepDtoCreate
{
[Required(ErrorMessage = "Codigo do Cep é obrigatório")]
[StringLength(10, ErrorMessage = "Codigo do Cep deve ter no máximo {1} caracteres")]
public string Cep { get; set; }
[Required(ErrorMessage = "Logradouro do Cep é obrigatório")]
[StringLength(60, ErrorMessage = "Logradouro deve ter no máximo {1} caracteres")]
public string Logradouro { get; set; }
[Required(ErrorMessage = "Número do Cep é obrigatório")]
[StringLength(10, ErrorMessage = "Número do Cep deve ter no máximo {1} caracteres")]
public string Numero { get; set; }
[Required(ErrorMessage = "Municipio do Cep é obrigatório")]
public Guid MunicipioId { get; set; }
public MunicipioDtoCompleto MunicipioDto { get; set; }
}
} | c61ec4ba5c60e8f1d687f6534cafdff7d5734c95 | [
"Markdown",
"C#"
] | 33 | C# | josias-m-soares/api-aspnetcore-ddd | 2477e705093ebdefdebb12ba6fdf76b9171ef71d | 49592c6fd2972e0b05455fed32872868a49e2f24 |
refs/heads/master | <repo_name>Hi1talib1World/massar-javaProject<file_sep>/src/main/java/info/UserInfo.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package info;
/**
*
* @author admin
*/
public class UserInfo {
public static String ADMIN_ROLE = "admin";
public static String RETAILER_ROLE = "retailer";
public static String CUSTOMER_ROLE = "customer";
private static int count = 10000;
private int userID;
private String username;
private String password;
private String role;
private Object userType;
public UserInfo (String un, String pwd, String role, Object ut ) {
this.username = un;
this.password = pwd;
this.role = role;
this.userType = ut;
userID = count++;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = <PASSWORD>;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
public Object getUserType() {
return userType;
}
public void setUserType(Object userType) {
this.userType = userType;
}
public int getUserID() {
return userID;
}
}
<file_sep>/src/main/java/info/Admin.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package info;
/**
*
* @author admin
*/
public class Admin {
public static Admin masterClass;
private teacherCatalogue retailerCatalogue;
private CustomerCatalogue customerCatalogue;
private UserInfoDirectory userAccountDirectory;
private static double treasury = 0.0;
private Admin()
{
this.retailerCatalogue=new teacherCatalogue();
this.customerCatalogue=new CustomerCatalogue();
this.userAccountDirectory = new UserInfoDirectory();
}
public static Admin getInstance() {
if (masterClass == null) {
masterClass = new Admin();
}
return masterClass;
}
/**
*
* @return
*/
public teacherCatalogue getRetailerCatalogue() {
return retailerCatalogue;
}
/**
*
* @return
*/
public telmidCatalogue getCustomerCatalogue() {
return customerCatalogue;
}
/**
*
* @return
*/
public UserAccountDirectory getUserAccountDirectory() {
return userAccountDirectory;
}
/**
*
* @param userAccountDirectory
*/
public void setUserAccountDirectory(UserAccountDirectory userAccountDirectory) {
this.userAccountDirectory = userAccountDirectory;
}
public static void pay(Double amount) {
treasury += amount;
}
public static double getTreasury() {
return treasury;
}
public static double payRetailer (RetailerInvoice ri) {
System.out.println("Tresury $" + Admin.getTreasury());
double toBePaid = ri.getTotalPriceToBePaid() - (ri.getTotalPriceToBePaid() * 0.1);
treasury -= toBePaid;
System.out.println("Tresury $" + Admin.getTreasury());
return toBePaid;
}
}
<file_sep>/src/main/java/teacher/teacher.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package teacher;
import java.util.ArrayList;
/**
*
* @author admin
*/
public class teacher {
private String teacherName;
private String zipCode;
private ProductCatalogue productCatalogue;
private String teacherNumber;
private static int counter = 345001;
private double earnings;
private ArrayList<CartProduct> productSoldList;
private teacherInvoiceList retailerInvoiceList;
public teacher()
{
counter++;
this.productCatalogue = new teacherCatalogue();
this.productSoldList = new ArrayList<>();
this.teacherNumber = String.valueOf(counter);
this.retailerInvoiceList = new teacherInvoiceList();
}
public String getRetailerNumber() {
return teacherNumber;
}
public String getRetailerName() {
return teacherName;
}
public void setRetailerName(String retailerName) {
this.teacherName = retailerName;
}
public ProductCatalogue getProductCatalogue() {
return productCatalogue;
}
public String getZipCode() {
return zipCode;
}
public void setZipCode(String zipCode) {
this.zipCode = zipCode;
}
public ArrayList<CartProduct> getProductSoldList() {
return productSoldList;
}
public teacherInvoiceList getRetailerInvoiceList() {
return retailerInvoiceList;
}
public void addToProductSoldList(CartProduct cp) {
this.productSoldList.add(cp);
}
public double getEarnings() {
return earnings;
}
public teacherInvoice genrateInvoice() {
if (this.productSoldList.size() > 0) {
teacherInvoice ri = retailerInvoiceList.addInvoice();
ri.addCartProductSold(this.getProductSoldList());
this.productSoldList.clear();
ri.setTotalPriceToBePaid(ri.getCartProductsSold().getCartTotal());
return ri;
} else {
return null;
}
}
public boolean payteacher (String invoiceNumber, Double amount) {
if (this.retailerInvoiceList.pay(invoiceNumber, amount)) {
this.earnings += amount;
return true;
} else {
return false;
}
}
@Override
public String toString()
{
return this.teacherName;
}
}
<file_sep>/src/main/java/info/Configre.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package info;
/**
*
* @author admin
*/
public class Configre {
public static Admin intialize() {
Admin msc = Admin.getInstance();
//Adding Admin
Person p = new Person();
p.setFirstName("Admin");
p.setLastName("Admin");
UserInfo ua = new UserInfo("admin", "admin", UserInfo.ADMIN_ROLE, p);
msc.getUserInfoDirectory().addUserAccount(ua);
//Adding Retailer 1
Retailer r = new Retailer();
r.setRetailerName("Apple");
r.setZipCode("02115");
msc.getRetailerCatalogue().addRetailer(r);
UserInfo uar = new UserInfo("apple", "apple", UserInfo.RETAILER_ROLE, r);
msc.getUserInfoDirectory().addUserAccount(uar);
//Adding Retailer 2
Retailer r1 = new Retailer();
r1.setRetailerName("Tesla");
r1.setZipCode("02115");
msc.getRetailerCatalogue().addRetailer(r1);
UserInfo uar1 = new UserInfo("tesla", "tesla", UserInfo.RETAILER_ROLE, r1);
msc.getUserInfoDirectory().addUserInfo(uar1);
//Adding Retailer 3
Retailer r3 = new Retailer();
r3.setRetailerName("Macy's");
r3.setZipCode("02116");
msc.getRetailerCatalogue().addRetailer(r3);
UserInfo uar2 = new UserInfo("macys", "macys", UserInfo.RETAILER_ROLE, r3);
msc.getUserInfoDirectory().addUserInfo(uar2);
Customer per = new Customer("08-21-1995", "Tom","02115");
msc.getCustomerCatalogue().addCustomer(per);
UserInfo uac = new UserInfo("cust", "cust", UserInfo.CUSTOMER_ROLE, per);
msc.getUserInfoDirectory().addUserInfo(uac);
return msc;
}
}
| 55f7fdff163e8b3556173fb0f01c7de8dd8d5196 | [
"Java"
] | 4 | Java | Hi1talib1World/massar-javaProject | 7e1853179115aafd1699f1b30d155e0e72d8c338 | aea38012586ef18ef9b5f26959f62cf7d9652573 |
refs/heads/master | <repo_name>nguyentienlinh2611/sapoApi_demo<file_sep>/src/main/java/com/sapo/apiclothes/controller/ApiAttributeValue.java
package com.sapo.apiclothes.controller;
import com.sapo.apiclothes.model.Attribute;
import com.sapo.apiclothes.model.AttributeValue;
import com.sapo.apiclothes.service.AttributeService;
import com.sapo.apiclothes.service.AttributeValueService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping(value = "/api/attributevalue")
public class ApiAttributeValue {
@Autowired
AttributeValueService attributeValueService;
@GetMapping
public ResponseEntity<List<AttributeValue>> getAllAttribute(){
return attributeValueService.getAllAttribute();
}
@GetMapping(value = "/{id}")
public ResponseEntity<AttributeValue> getAllAttributeById(@PathVariable("id") int id){
return attributeValueService.getAllAttributeId(id);
}
@PostMapping
public ResponseEntity<String> addAttribute(@RequestBody AttributeValue attribute){
return attributeValueService.addAttribute(attribute);
}
@PutMapping(value = "/{id}")
public ResponseEntity<String> updateAttribute(@PathVariable("id") int id,@RequestBody AttributeValue attribute){
return attributeValueService.updateAttribute(id,attribute);
}
@DeleteMapping(value = "/{id}")
public ResponseEntity<String> deleteAttribute(@PathVariable("id") int id){
return attributeValueService.deleteAttribute(id);
}
}
<file_sep>/src/main/java/com/sapo/apiclothes/service/AttributeService.java
package com.sapo.apiclothes.service;
import com.sapo.apiclothes.model.Attribute;
import com.sapo.apiclothes.model.Category;
import com.sapo.apiclothes.repository.AttributeReponsitory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;
import java.util.List;
@Service
public class AttributeService {
@Autowired
AttributeReponsitory attributeReponsitory;
public ResponseEntity<List<Attribute>> getAllAttribute(){
List list= attributeReponsitory.findAll();
return new ResponseEntity<>(list, HttpStatus.OK);
}
public ResponseEntity<Attribute> getAllAttributeId(int id){
Attribute attribute = attributeReponsitory.getOne(id);
return new ResponseEntity(attribute, HttpStatus.OK);
}
public ResponseEntity<String> addAttribute(@RequestBody Attribute attributeForm){
attributeReponsitory.save(attributeForm);
return new ResponseEntity("Success", HttpStatus.OK);
}
public ResponseEntity<String> updateAttribute(int id,@RequestBody Attribute attributeForm){
Attribute attribute = attributeReponsitory.getOne(id);
attribute.setName(attributeForm.getName());
attributeReponsitory.save(attribute);
return new ResponseEntity("Success", HttpStatus.OK);
}
public ResponseEntity<String> deleteAttribute(int id){
Attribute attribute = attributeReponsitory.getOne(id);
attributeReponsitory.delete(attribute);
return new ResponseEntity("Success", HttpStatus.OK);
}
}
<file_sep>/src/main/java/com/sapo/apiclothes/service/CategoryService.java
package com.sapo.apiclothes.service;
import com.sapo.apiclothes.model.Category;
import com.sapo.apiclothes.repository.CategoryRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;
import java.util.List;
@Service
public class CategoryService {
@Autowired
CategoryRepository categoryRepository;
public ResponseEntity<List<Category>> getAllCategory(){
List list= categoryRepository.findAll();
return new ResponseEntity<>(list, HttpStatus.OK);
}
public ResponseEntity<Category> getAllCategory(int id){
Category category = categoryRepository.getOne(id);
return new ResponseEntity<>(category, HttpStatus.OK);
}
public ResponseEntity<String> addCategory(@RequestBody Category categoryForm){
categoryRepository.save(categoryForm);
return new ResponseEntity("Success", HttpStatus.OK);
}
public ResponseEntity<String> updateCategory(int id,@RequestBody Category categoryForm){
Category category = categoryRepository.getOne(id);
category.setName(categoryForm.getName());
categoryRepository.save(category);
return new ResponseEntity("Success", HttpStatus.OK);
}
public ResponseEntity<String> deleteCategory(int id){
Category category = categoryRepository.getOne(id);
categoryRepository.delete(category);
return new ResponseEntity("Success", HttpStatus.OK);
}
}
| 4ccf51891ad1b932e929c03bf394a6e9c5861570 | [
"Java"
] | 3 | Java | nguyentienlinh2611/sapoApi_demo | 0adbcc28137f7ccc498c491d01963f707bc9a61c | 4c53cd9553b62ca74b3a102e2600030d8e9a714f |
refs/heads/main | <repo_name>iloveflag/YanZhao-Mole<file_sep>/Server.py
import requests
class Server:
title = "发布了新消息,请查看"
desp = "请点击进入:"
ServerUrl = "https://sctapi.ftqq.com/{SendKey}.send"
def __init__(self, school):
self.desp += str(school.url)
self.title = str(school.title)+self.title
def send(self):
datas = {'title': self.title, 'desp': self.desp}
r = requests.post(self.ServerUrl, data=datas)
print("已通过server酱发送到手机")
<file_sep>/main.py
from Server import Server
from School import School
from datetime import datetime, timedelta
if __name__ == '__main__':
schoollist=[]
schoollist.append(School("浙江大学", "http://grs.zju.edu.cn/yjszs/redir.php?catalog_id=130678"))
checktime = datetime.now()-timedelta(days=1)
while(1):
while((datetime.now()-checktime).days==1):
for school in schoollist:
if(school.check()):
s = Server(school)
s.send()
checktime=datetime.now()
print("每天检查更新完毕:"+str(checktime))
<file_sep>/School.py
import requests
from datetime import datetime
class School:
len = 0
def __init__(self, title, url):
self.title = title
self.url = url
def check(self):
r = requests.get(self.url, verify=False)
l = len(r.text)
if l!=self.len:
print(str(self.title)+"有更新"+str(datetime.now()))
self.len = l
return True
else:
return False
<file_sep>/README.md
添加自己的server酱:
ServerUrl = "https://sctapi.ftqq.com/{SendKey}.send"
增加院校:
schoollist.append(School("浙江大学", "http://grs.zju.edu.cn/yjszs/redir.php?catalog_id=130678"))
| c11816145250a6c9ba629f35e6d6b80cada8860f | [
"Markdown",
"Python"
] | 4 | Python | iloveflag/YanZhao-Mole | de1aa742e9e376b27c527ecbfb091f5ccdf662a7 | f913a76839a8d92821ee61e6970d87d1ada8d39a |
refs/heads/master | <file_sep>using System;
namespace HabsPolymorphism2
{
public class Goal // the base class to be inherited
{
public virtual void Score()
{
Console.WriteLine("Score a Goal");
}
}
public class Blueline : Goal // first child class
{
public override void Score()
{
Console.WriteLine("GOOOOAALLL."); // output
}
}
public class Shorthanded : Goal // second child class
{
public override void Score()
{
Console.WriteLine("Holy Mackanaw."); // output
}
}
public class Emptynetter : Goal // third child class
{
public override void Score()
{
Console.WriteLine("Hat Trick."); // output
}
}
public class Powerplay : Goal // fourth child class
{
public override void Score()
{
Console.WriteLine("Un But."); // output
}
public class ScoreDemo
{
public static int Main()
{
Goal[] Go = new Goal[4]; // array
Go[0] = new Blueline();
Go[1] = new Shorthanded();
Go[2] = new Emptynetter();
Go[3] = new Powerplay();
foreach (Goal Goal in Go)
{
Goal.Score();
}
return 0;
}
}
}
} | d9c91e175f45cbce8d5442d22dcf17a47be33749 | [
"C#"
] | 1 | C# | lauren-lil/Habs-Polymorphism-example | 4c085900af5040a5c66b36ee309f16d0ee5bd1eb | 4c887e6ba2338bb57f3b4b6082fc8511d89d7b23 |
refs/heads/master | <repo_name>hitarthdoc/ecmh<file_sep>/src/common.c
/*****************************************************
ecmh - Easy Cast du Multi Hub - Common Functions
******************************************************
$Author: fuzzel $
$Id: common.c,v 1.3 2005/02/09 17:58:06 fuzzel Exp $
$Date: 2005/02/09 17:58:06 $
*****************************************************/
#include "ecmh.h"
void dolog(int level, const char *fmt, ...)
{
va_list ap;
if (g_conf && !g_conf->verbose && level == LOG_DEBUG) return;
va_start(ap, fmt);
if (g_conf && g_conf->daemonize)
{
vsyslog(LOG_LOCAL7|level, fmt, ap);
}
else
{
if (g_conf && g_conf->verbose)
{
printf("[%6s] ",
level == LOG_DEBUG ? "debug" :
(level == LOG_ERR ? "error" :
(level == LOG_WARNING ? "warn" :
(level == LOG_INFO ? "info" : ""))));
}
vprintf(fmt, ap);
}
va_end(ap);
}
int huprunning()
{
int pid;
FILE *f = fopen(PIDFILE, "r");
if (!f) return 0;
fscanf(f, "%d", &pid);
fclose(f);
/* If we can HUP it, it still runs */
return (kill(pid, SIGHUP) == 0 ? 1 : 0);
}
void savepid()
{
FILE *f = fopen(PIDFILE, "w");
if (!f) return;
fprintf(f, "%d", getpid());
fclose(f);
dolog(LOG_INFO, "Running as PID %d\n", getpid());
}
void cleanpid(int i)
{
dolog(LOG_INFO, "Trying to exit, got signal %d...\n", i);
unlink(PIDFILE);
if (g_conf) g_conf->quit = true;
}
uint64_t gettimes(void)
{
#ifdef __MACH__
/* OS X does not have clock_gettime, use clock_get_time */
clock_serv_t cclock;
mach_timespec_t mts;
host_get_clock_service(mach_host_self(), CALENDAR_CLOCK, &cclock);
clock_get_time(cclock, &mts);
mach_port_deallocate(mach_task_self(), cclock);
return (mts.tv_sec);
#else
struct timespec ts;
clock_gettime(CLOCK_REALTIME, &ts);
return (ts.tv_sec);
#endif
}
<file_sep>/tools/Makefile
# /**************************************
# ecmh - Easy Cast du Multi Hub
# by <NAME> <<EMAIL>>
# **************************************/
#
# Tools Makefile
#
all: mtrace6
mtrace6: mtrace6/
$(MAKE) -C mtrace6 all
clean:
$(MAKE) -C mtrace6 clean
depend:
$(MAKE) -C mtrace6 depend
# Mark targets as phony
.PHONY : all clean mtrace6
<file_sep>/src/ecmh.h
/**************************************
ecmh - Easy Cast du Multi Hub
by <NAME> <<EMAIL>>
**************************************/
#ifndef ECMH_H
#define ECMH_H "ECMH"
#ifdef __GNUC__
#define ATTR_RESTRICT __restrict
#define ATTR_FORMAT(type, x, y) __attribute__ ((format(type, x, y)))
#define PACKED __attribute__((packed))
#define ALIGNED __attribute__((aligned))
#define UNUSED __attribute__ ((__unused__))
#else
#define ATTR_FORMAT(type, x, y) /* nothing */
#define ATTR_RESTRICT /* nothing */
#define PACKED
#define ALIGNED
#define UNUSED
#endif
#include <stdint.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include <strings.h>
#include <ctype.h>
#include <time.h>
#include <signal.h>
#include <syslog.h>
#include <pwd.h>
#include <getopt.h>
#include <assert.h>
#include <inttypes.h>
#include <net/if.h>
#include <netinet/if_ether.h>
#include <sched.h>
#ifdef __linux__
#include <netpacket/packet.h>
#endif
#if defined(__FreeBSD__) || defined(__MACH__)
#include <fcntl.h>
#include <sys/uio.h>
#include <netinet/in_systm.h>
#include <net/ethernet.h>
#include <net/bpf.h>
#define ETH_P_IPV6 ETHERTYPE_IPV6
#define ETH_P_IP ETHERTYPE_IP
#endif
#include <ifaddrs.h>
#include <netinet/ip.h>
#include <netinet/ip6.h>
#include <netinet/icmp6.h>
#include <netinet/tcp.h>
#include <netinet/udp.h>
#include <netinet/ip_icmp.h>
#include <sys/ioctl.h>
#ifdef __MACH__
#include <mach/clock.h>
#include <mach/mach.h>
#endif
#include "mld.h"
#define PIDFILE "/var/run/ecmh.pid"
#define ECMH_DUMPFILE "/var/run/ecmh.dump"
#define ECMH_VERSION_STRING "Easy Cast du Multi Hub (ecmh) %s/%s by <NAME> <<EMAIL>>\n"
#ifdef DEBUG
#define D(x) x
#else
#define D(x) {}
#endif
/* The timeout for queries */
/* as per RFC3810 MLDv2 "9.2. Query Interval" */
#define ECMH_SUBSCRIPTION_TIMEOUT 125
/* Robustness Factor, per RFC3810 MLDv2 "9.1. Robustness Variable" */
#define ECMH_ROBUSTNESS_FACTOR 2
#ifndef ICMP6_MEMBERSHIP_QUERY
#define ICMP6_MEMBERSHIP_QUERY MLD_LISTENER_QUERY
#endif
#ifndef ICMP6_MEMBERSHIP_REPORT
#define ICMP6_MEMBERSHIP_REPORT MLD_LISTENER_REPORT
#endif
#ifndef ICMP6_MEMBERSHIP_REDUCTION
#define ICMP6_MEMBERSHIP_REDUCTION MLD_LISTENER_REDUCTION
#endif
#include "linklist.h"
#include "common.h"
/* Booleans */
#define false 0
#define true (!false)
#define bool uint64_t
#include "interfaces.h"
#include "groups.h"
#include "grpint.h"
#include "subscr.h"
/* Our configuration structure */
struct conf
{
uint64_t maxgroups;
uint64_t maxinterfaces; /* The max number of interfaces the array can hold */
struct intnode *ints; /* The interfaces we are watching */
struct list *groups; /* The groups we are joined to */
char *upstream; /* Upstream interface */
uint64_t upstream_id; /* Interface ID of upstream interface */
bool daemonize; /* To Daemonize or to not to Daemonize */
bool verbose; /* Verbose Operation ? */
bool quit; /* Global Quit signal */
#ifdef ECMH_SUPPORT_MLD2
bool mld1only; /* Only MLDv1 ? */
bool mld2only; /* Only MLDv2 ? */
#endif
bool promisc; /* Make interfaces promisc? (To be sure to receive all MLD's) */
void *buffer; /* Our buffer */
uint64_t bufferlen; /* Length of the buffer */
#ifndef ECMH_BPF
int rawsocket; /* Single RAW socket for sending and receiving everything */
int __padding;
#else
bool tunnelmode; /* Intercept&handle proto-41 packets? */
struct list *locals; /* Local devices that could have tunnels */
fd_set selectset; /* Selectset */
uint64_t hifd; /* Highest File Descriptor */
#endif
FILE *stat_file; /* The file handle of ourdump file */
time_t stat_starttime; /* When did we start */
uint64_t stat_packets_received; /* Number of packets received */
uint64_t stat_packets_sent; /* Number of packets forwarded */
uint64_t stat_bytes_received; /* Number of bytes received */
uint64_t stat_bytes_sent; /* Number of bytes forwarded */
uint64_t stat_icmp_received; /* Number of ICMP's received */
uint64_t stat_icmp_sent; /* Number of ICMP's sent */
uint64_t stat_hlim_exceeded; /* Packets that where dropped due to hlim == 0 */
};
#ifndef ETH_P_IPV6
#define ETH_P_IPV6 0x86dd
#endif
#define memzero(obj,len) memset(obj,0,len)
/* Global Stuff */
extern struct conf *g_conf;
#endif /* ECMH_H */
<file_sep>/debian/ecmh.init
#! /bin/sh
#
# /etc/init.d/ecmh: start, stop and statdump ecmh
#
# <NAME> <<EMAIL>>
# ecmh website: http://unfix.org/projects/ecmh/
PATH=/sbin:/bin:/usr/sbin:/usr/bin
DAEMON=/usr/sbin/ecmh
NAME=ecmh
DESC="Easy Cast du Multi Hub (ecmh)"
BACKGROUND=true
# Options, per default we let the program
# drop root priveleges to nobody
# Other option to use is -f (Foreground), but that is useless for inits.
OPTIONS="-u nobody"
test -x /usr/sbin/ecmh || exit 0
if [ -f /etc/default/ecmh ]; then
. /etc/default/ecmh
fi
if [ "$BACKGROUND" = "false" ]; then
exit 0;
fi
case "$1" in
start)
echo -n "Starting $DESC: "
start-stop-daemon --start --oknodo --quiet --exec $DAEMON -- $OPTIONS
echo "$NAME."
;;
stop)
echo -n "Stopping $DESC: "
start-stop-daemon --stop --oknodo --quiet --exec $DAEMON
echo "$NAME."
;;
restart|reload|force-reload)
echo -n "Restarting $DESC: "
start-stop-daemon --stop --oknodo --quiet --exec $DAEMON
sleep 2
start-stop-daemon --start --oknodo --quiet --exec $DAEMON -- $OPTIONS
echo "$NAME."
;;
dumpstats)
echo -n "Requesting statistics dump from $DESC: "
start-stop-daemon --stop --signal USR1 --quiet --exec $DAEMON
echo "$NAME."
;;
*)
echo "Usage: /etc/init.d/$NAME {start|stop|reload|force-reload|restart|dumpstats}" >&2
exit 1
esac
exit 0
<file_sep>/src/subscr.h
/**************************************
ecmh - Easy Cast du Multi Hub
by <NAME> <<EMAIL>>
**************************************/
/* MLDv2 Source Specific Multicast Support */
struct subscrnode
{
struct in6_addr ipv6; /* The address that wants packets matching this S<->G */
uint64_t mode; /* MLD2_* */
time_t refreshtime; /* The time we last received a join for this S<->G on this interface */
};
struct subscrnode *subscr_create(const struct in6_addr *ipv6, int mode);
void subscr_destroy(struct subscrnode *subscrn);
struct subscrnode *subscr_find(const struct list *list, const struct in6_addr *ipv6);
bool subscr_unsub(struct list *list, const struct in6_addr *ipv6);
<file_sep>/src/linklist.c
/* Generic linked list routine.
* Copyright (C) 1997, 2000 <NAME>
* modded for ecmh by <NAME>
*/
#include "linklist.h"
#include <string.h>
#include <strings.h>
#include <stdlib.h>
/* Allocate new list. */
struct list *list_new()
{
struct list *new;
new = calloc(1, sizeof(*new));
if (!new) return NULL;
return new;
}
/* Free list. */
void list_free(struct list *l)
{
if (l) free(l);
}
/* Allocate new listnode */
static struct listnode *listnode_new(void);
static struct listnode *listnode_new(void)
{
struct listnode *node;
node = calloc(1, sizeof(*node));
if (!node) return NULL;
return node;
}
/* Free listnode. */
static void listnode_free(struct listnode *node);
static void listnode_free(struct listnode *node)
{
free(node);
}
/* Add new data to the list. */
void listnode_add(struct list *list, void *val)
{
struct listnode *node;
node = listnode_new();
if (!node) return;
node->prev = list->tail;
node->data = val;
if (list->head == NULL) list->head = node;
else list->tail->next = node;
list->tail = node;
if (list->count < 0) list->count = 0;
list->count++;
}
/* Delete all listnode from the list. */
void list_delete_all_node(struct list *list)
{
struct listnode *node;
struct listnode *next;
for (node = list->head; node; node = next)
{
next = node->next;
if (list->del) (*list->del)(node->data);
listnode_free(node);
}
list->head = list->tail = NULL;
list->count = 0;
}
/* Delete all listnode then free list itself. */
void list_delete(struct list *list)
{
struct listnode *node;
struct listnode *next;
for (node = list->head; node; node = next)
{
next = node->next;
if (list->del) (*list->del)(node->data);
listnode_free(node);
}
list_free (list);
}
/* Delete the node from list. For ospfd and ospf6d. */
void list_delete_node(struct list *list, struct listnode *node)
{
if (node->prev) node->prev->next = node->next;
else list->head = node->next;
if (node->next) node->next->prev = node->prev;
else list->tail = node->prev;
list->count--;
listnode_free(node);
}
<file_sep>/src/Makefile
# /**************************************
# ecmh - Easy Cast du Multi Hub
# by <NAME> <<EMAIL>>
# **************************************/
#
# Source Makefile for ecmh - <NAME> <<EMAIL>>
#
# ECMH_VERSION and ECMH_OPTIONS need to be defined, gets done by toplevel Makefile
#
# One should make this using the main Makefile (thus one dir up)
#
# FreeBSD people should uncomment these if they don't have GNU make and
# then run 'make' from this directory
# On FreeBSD4 install the "libgnugetopt" port to get getopt working
#ECMH_OPTIONS=-DECMH_BPF -DECMH_SUPPORT_MLD2 -DECMH_GETIFADDR -I/usr/local/include/
#ECMH_VERSION=2013.09.28
#ECMH_LDFREEBSD=-L/usr/local/lib/ -lgnugetopt
# Below here nothing should have to be changed
BINS = ecmh
SRCS = ecmh.c linklist.c common.c interfaces.c groups.c grpint.c subscr.c
INCS = ecmh.h linklist.h common.h interfaces.h groups.h grpint.h subscr.h mld.h
DEPS = ../Makefile Makefile
OBJS = ecmh.o linklist.o common.o interfaces.o groups.o grpint.o subscr.o
# Standard Warnings
WARNS += -Wall -Wextra
ifeq ($(CC_TYPE),gcc)
WARNS += -Werror
endif
# Extended warnings
WARNS += -Wshadow -Wpointer-arith -Wcast-align -Wwrite-strings
WARNS += -Waggregate-return -Wstrict-prototypes -Wmissing-prototypes
WARNS += -Wmissing-declarations -Wredundant-decls -Wnested-externs
WARNS += -Winline -Wbad-function-cast -fstrict-aliasing
WARNS += -fno-common -Wno-packed -Wswitch-default
WARNS += -Wformat=2 -Wformat-security
WARNS += -Wmissing-format-attribute
WARNS += -D_REENTRANT -D_THREAD_SAFE -pipe -Wunused -Winit-self
WARNS += -Wextra -Wno-long-long -Wmissing-include-dirs
WARNS += -Wno-variadic-macros
WARNS += -std=c99
WARNS += -pedantic
# clang does not know the -ansi option
ifneq ($(CC_TYPE),clang)
WARNS += -ansi
endif
ifeq ($(shell echo $(ECMH_OPTIONS) | grep -c "DEBUG"),1)
EXTRA = -g -O0
else
EXTRA = -O3
endif
CFLAGS = $(WARNS) $(EXTRA) -D_GNU_SOURCE -D'ECMH_VERSION="$(ECMH_VERSION)"' -D'ECMH_GITHASH="$(ECMH_GITHASH)"' $(ECMH_OPTIONS)
LDFLAGS = $(ECMH_LDFREEBSD)
LINK = @echo "* Linking $@"; $(CC) $(CFLAGS) $(LDFLAGS)
-include $(OBJS:.o=.d)
all: $(BINS)
depend: clean
@echo "* Making dependencies"
@$(MAKE) -s $(OBJS)
@echo "* Making dependencies - done"
%.o: %.c $(DEPS)
@echo "* Compiling $@";
@$(CC) -c $(CFLAGS) $*.c -o $*.o
@$(CC) -MM $(CFLAGS) $*.c > $*.d
@cp -f $*.d $*.d.tmp
@sed -e 's/.*://' -e 's/\\$$//' < $*.d.tmp | fmt -1 | \
sed -e 's/^ *//' -e 's/$$/:/' >> $*.d
@rm -f $*.d.tmp
ecmh: $(DEPS) $(OBJS)
$(LINK) -o $@ $(OBJS) $(LDLIBS)
ifeq ($(shell echo $(ECMH_OPTIONS) | grep -c "DEBUG"),0)
@strip $@
endif
clean:
$(RM) $(OBJS) $(BINS)
# Mark targets as phony
.PHONY : all clean
<file_sep>/src/interfaces.h
/**************************************
ecmh - Easy Cast du Multi Hub
by <NAME> <<EMAIL>>
**************************************/
#define INTNODE_MAXIPV4 4 /* Maximum number of IPv4 aliases */
/*
* The list of interfaces we do multicast on
* These are discovered on the fly, very handy ;)
*/
struct intnode
{
uint64_t ifindex; /* The ifindex */
char name[IFNAMSIZ]; /* Name of the interface */
uint64_t groupcount; /* Number of groups this interface joined */
uint64_t mtu; /* The MTU of this interface (mtu = 0 -> invalid interface) */
uint64_t mld_version; /* The MLD version this interface supports */
uint64_t mld_last_v1; /* The last v1 we have seen -> allows upgrade to v2 */
#ifndef ECMH_BPF
struct sockaddr hwaddr; /* Hardware bytes */
#else
int socket; /* (BPF|Raw)Socket, when this is an ethernet interface */
int __padding;
uint64_t dlt; /* DLT of the interface (DLT_EN10MB or DLT_NULL)*/
uint64_t bufferlen; /* The buffer length this interface expects */
struct intnode *master; /* Master interface, when this is a proto-41 tunnel */
struct in_addr ipv4_local[INTNODE_MAXIPV4]; /* Local IPv4 address */
struct in_addr ipv4_remote; /* Remote IPv4 address */
#endif
struct in6_addr linklocal; /* Link local address */
struct in6_addr global; /* Global unicast address */
#ifdef ECMH_BPF
uint8_t __padding2[4];
#endif
/* Per interface statistics */
uint64_t stat_packets_received; /* Number of packets received */
uint64_t stat_packets_sent; /* Number of packets sent */
uint64_t stat_bytes_received; /* Number of bytes received */
uint64_t stat_bytes_sent; /* Number of bytes sent */
uint64_t stat_icmp_received; /* Number of ICMP's received */
uint64_t stat_icmp_sent; /* Number of ICMP's sent */
bool upstream; /* This interface is an upstream */
};
/* Node functions */
#ifndef ECMH_BPF
struct intnode *int_create(unsigned int ifindex);
#else
struct intnode *int_create(unsigned int ifindex, bool tunnel);
#endif
void int_destroy(struct intnode *intn);
/* List functions */
struct intnode *int_find(unsigned int ifindex);
#ifdef ECMH_BPF
struct intnode *int_find_ipv4(bool local, struct in_addr *ipv4);
#endif
/* Control function */
void int_set_mld_version(struct intnode *intn, unsigned int newversion);
#ifdef ECMH_BPF
/*
* This node is used to quickly index local IPv4 addresses
* and allow them to be found for the tunnels too when
* sending packets
*/
struct localnode
{
struct intnode *intn; /* The interface */
};
void local_update(struct intnode *intn);
struct localnode *local_find(struct in_addr *ipv4);
void local_destroy(struct localnode *localn);
#endif
<file_sep>/Makefile
# /**************************************
# ecmh - Easy Cast du Multi Hub
# by <NAME> <<EMAIL>>
# **************************************/
#
# Toplevel Makefile allowing easy distribution.
# Use this makefile for doing almost anything
# 'make help' shows the possibilities
#
# The name of the application
ECMH=ecmh
# The version of this release
ECMH_VERSION=2019.03.08
#####################################################
# ECMH Compile Time Options
# Append one of the following option on wish to
# include certain features
ECMH_OPTIONS=
# Enable IPv4 Support
#ECMH_OPTIONS += -DECMH_SUPPORT_IPV4
# Enable MLDv2 Support (default)
ECMH_OPTIONS += -DECMH_SUPPORT_MLD2
# GetIfAddr Support
ECMH_OPTIONS += -DECMH_GETIFADDR
# BPF Support (BSD) (enabled below if needed)
#ECMH_OPTIONS += -DECMH_BPF
# Enable Debugging (more verbosity than one wants)
#ECMH_OPTIONS += -DDEBUG
#####################################################
ifeq ($(OS_NAME),)
override OS_NAME=$(shell uname -s)
$(info - Detected OS Name: ${OS_NAME})
endif
ifeq ($(OS_NAME),Darwin)
ECMH_OPTIONS+=-DECMH_BPF
endif
ifeq ($(OS_NAME),BSD)
ECMH_OPTIONS+=-DECMH_BPF
endif
ifeq ($(OS_NAME),Linux)
LDLIBS += -lrt
endif
########################################################
# Determine the Compiler Type
# this as clang is a bit more strict at certain things
CC_TYPE=$(shell $(CC) --version |grep -c clang)
ifeq ($(CC_TYPE),1)
CC_TYPE=clang
else
CC_TYPE=gcc
endif
$(info - CC Type: ${CC_TYPE})
########################################################
ECMH_GITHASH:=$(shell git log --pretty=format:'%H' -n 1)
CFLAGS += -DECMH_GITHASH=$(ECMH_GITHASH)
# Not Linux? -> Enable BPF Mode
ifeq ($(shell uname | grep -c "Linux"),0)
ECMH_OPTIONS:=$(ECMH_OPTIONS) -DECMH_BPF
endif
# Export it to the other Makefile
export ECMH_VERSION
export ECMH_GITHASH
export ECMH_OPTIONS
# Tag it with debug when it is run with debug set
ifeq ($(shell echo $(ECMH_OPTIONS) | grep -c "DEBUG"),1)
ECMH_VERSION:=$(ECMH_VERSION)-debug
endif
# Do not print "Entering directory ..."
MAKEFLAGS += --no-print-directory
# Misc bins, making it easy to quiet them :)
RM=@rm -f
MV=@mv
MAKE:=@${MAKE}
CP=@echo [Copy]; cp
RPMBUILD=@echo [RPMBUILD]; rpmbuild
RPMBUILD_SILENCE=>/dev/null 2>/dev/null
export CC
export MV
export MAKE
export RM
export LDLIBS
export CC_TYPE
# Configure a default RPMDIR
ifeq ($(shell echo "${RPMDIR}/" | grep -c "/"),1)
RPMDIR=/usr/src/redhat/
endif
# Change this if you want to install into another dirtree
# Required for eg the Debian Package builder
DESTDIR=
# Get the source dir, needed for eg debsrc
SOURCEDIR := $(shell pwd)
SOURCEDIRNAME := $(shell basename `pwd`)
# Paths
sbindir=/usr/sbin/
srcdir=src/
toolsdir=tools/
all: intro ecmh tools
intro:
@echo "==================-------~~"
@echo "Building: ecmh"
@echo "Version : $(ECMH_VERSION)"
@echo "Git Hash: $(ECMH_GITHASH)"
@echo "=====------------~~~~"
ecmh: $(srcdir)
$(MAKE) -C src all
tools: $(toolsdir)
$(MAKE) -C tools all
help:
@echo "ecmh - Easy Cast du Multi Hub"
@echo "Website: http://unfix.org/projects/ecmh/"
@echo "Author : <NAME> <<EMAIL>>"
@echo
@echo "Makefile targets:"
@echo "all : Build everything"
@echo "ecmh : Build only ecmh"
@echo "tools : Build only the tools"
@echo "help : This little text"
@echo "install : Build & Install"
@echo "depend : Build dependency files"
@echo "clean : Clean the dirs to be pristine in bondage"
@echo
@echo "Distribution targets:"
@echo "dist : Make all distribution targets"
@echo "tar : Make source tarball (tar.gz)"
@echo "bz2 : Make source tarball (tar.bz2)"
@echo "deb : Make Debian binary package (.deb)"
@echo "debsrc : Make Debian source packages"
@echo "rpm : Make RPM package (.rpm)"
@echo "rpmsrc : Make RPM source packages"
install: all
mkdir -p $(DESTDIR)${sbindir}
${CP} src/$(ECMH) $(DESTDIR)${sbindir}
# Clean all the output files etc
distclean: clean
clean: debclean
$(MAKE) -C src clean
$(MAKE) -C tools clean
depend:
$(MAKE) -C src depend
$(MAKE) -C tools depend
# Generate Distribution files
dist: tar bz2 deb debsrc rpm rpmsrc
# tar.gz
tar: clean
-${RM} ../ecmh_${ECMH_VERSION}.tar.gz
cd ..; tar -zclof ecmh_${ECMH_VERSION}.tar.gz ${SOURCEDIRNAME}
# tar.bz2
bz2: clean
-${RM} ../ecmh_${ECMH_VERSION}.tar.bz2
cd ..; tar -jclof ecmh_${ECMH_VERSION}.tar.bz2 ${SOURCEDIRNAME}
# .deb
deb: clean
# Copy the changelog
${CP} doc/changelog debian/changelog
debian/rules binary
${RM} debian/changelog
${MAKE} clean
# Source .deb
debsrc: clean
# Copy the changelog
${CP} doc/changelog debian/changelog
cd ..; dpkg-source -b ${SOURCEDIR}; cd ${SOURCEDIR}
${RM} debian/changelog
${MAKE} clean
# Cleanup after debian
debclean:
@if [ -f configure-stamp ]; then debian/rules clean; fi;
# RPM
rpm: rpmclean tar
-${RM} ${RPMDIR}/RPMS/i386/ecmh-${ECMH_VERSION}*.rpm
${RPMBUILD} -tb --define 'ecmh_version ${ECMH_VERSION}' ../ecmh_${ECMH_VERSION}.tar.gz ${RPMBUILD_SILENCE}
${MV} ${RPMDIR}/RPMS/i386/ecmh-*.rpm ../
@echo "Resulting RPM's:"
@ls -l ../ecmh-${ECMH_VERSION}*.rpm
${MAKE} clean
@echo "RPMBuild done"
rpmsrc: rpmclean tar
-${RM} ${RPMDIR}/RPMS/i386/ecmh-${ECMH_VERSION}*src.rpm
${RPMBUILD} -ts --define 'ecmh_version ${PROJECT_VERSION}' ../ecmh_${ECMH_VERSION}.tar.gz ${RPMBUILD_SILENCE}
${MV} ${RPMDIR}/RPMS/i386/ecmh-*.src.rpm ../
@echo "Resulting RPM's:"
@ls -l ../ecmh-${ECMH_VERSION}*.rpm
${MAKE} clean}
@echo "RPMBuild-src done"
rpmclean: clean
-${RM} ../${PROJECT}_${PROJECT_VERSION}.tar.gz
# Mark targets as phony
.PHONY : all ecmh tools install help clean dist tar bz2 deb debsrc debclean rpm rpmsrc
<file_sep>/src/interfaces.c
/**************************************
ecmh - Easy Cast du Multi Hub
by <NAME> <<EMAIL>>
**************************************/
#include "ecmh.h"
#ifdef ECMH_BPF
static bool int_create_bpf(struct intnode *intn, bool tunnel);
static bool int_create_bpf(struct intnode *intn, bool tunnel)
{
unsigned int i;
char devname[IFNAMSIZ];
struct ifreq ifr;
/*
* When we are:
* - not in tunnel mode,
* or
* - it is not a tunnel
*
* Allocate BPF etc.
*/
if (!g_conf->tunnelmode || !tunnel)
{
/* Open a BPF for this interface */
i = 0;
while (intn->socket < 0)
{
snprintf(devname, sizeof(devname), "/dev/bpf%u", i++);
intn->socket = open(devname, O_RDWR);
if (intn->socket >= 0 || errno != EBUSY) break;
}
if (intn->socket < 0)
{
dolog(LOG_ERR, "Couldn't open a new BPF device for %s\n", intn->name);
return false;
}
dolog(LOG_INFO, "Opened %s as a BPF device for %s\n", devname, intn->name);
/* Bind it to the interface */
memzero(&ifr, sizeof(ifr));
strncpy(ifr.ifr_name, intn->name, sizeof(ifr.ifr_name));
if (ioctl(intn->socket, BIOCSETIF, &ifr))
{
dolog(LOG_ERR, "Could not bind BPF to %s: %s (%d)\n", intn->name, strerror(errno), errno);
return false;
}
dolog(LOG_INFO, "Bound BPF %s to %s\n", devname, intn->name);
if (g_conf->promisc)
{
if (ioctl(intn->socket, BIOCPROMISC))
{
dolog(LOG_ERR, "Could not set %s to promisc: %s (%d)\n", intn->name, strerror(errno), errno);
return false;
}
dolog(LOG_INFO, "BPF interface for %s is now promiscious\n", intn->name);
}
if (fcntl(intn->socket, F_SETFL, O_NONBLOCK) < 0)
{
dolog(LOG_ERR, "Could not set %s to non_blocking: %s (%d)\n", intn->name, strerror(errno), errno);
return false;
}
i = 1;
if (ioctl(intn->socket, BIOCIMMEDIATE, &i))
{
dolog(LOG_ERR, "Could not set %s to immediate: %s (%d)\n", intn->name, strerror(errno), errno);
return false;
}
if (ioctl(intn->socket, BIOCGDLT, &intn->dlt))
{
dolog(LOG_ERR, "Could not get %s's DLT: %s (%d)\n", intn->name, strerror(errno), errno);
return false;
}
if (intn->dlt != DLT_NULL && intn->dlt != DLT_EN10MB)
{
dolog(LOG_ERR, "Only NULL and EN10MB (Ethernet) DLT are supported as DLTs, this DLT is %" PRIu64 "\n", intn->dlt);
return false;
}
dolog(LOG_INFO, "BPF's DLT is %s\n", intn->dlt == DLT_EN10MB ? "Ethernet" : (intn->dlt == DLT_NULL ? "Null" : "??"));
if (ioctl(intn->socket, BIOCGBLEN, &intn->bufferlen))
{
dolog(LOG_ERR, "Could not get %s's BufferLen: %s (%d)\n", intn->name, strerror(errno), errno);
return false;
}
dolog(LOG_INFO, "BPF's bufferLength is %" PRIu64 "\n", intn->bufferlen);
/* Is this buffer bigger than what we have allocated? -> Upgrade */
if (intn->bufferlen > g_conf->bufferlen)
{
free(g_conf->buffer);
g_conf->bufferlen = intn->bufferlen;
g_conf->buffer = calloc(1, g_conf->bufferlen);
if (!g_conf->buffer)
{
dolog(LOG_ERR, "Couldn't increase bufferlength to %" PRIu64 "\n", g_conf->bufferlen);
dolog(LOG_ERR, "Expecting a memory shortage, exiting\n");
exit(-1);
}
}
/* Add it to the select set */
FD_SET(intn->socket, &g_conf->selectset);
if (((uint64_t)intn->socket) > g_conf->hifd)
{
g_conf->hifd = intn->socket;
}
}
/* It is a tunnel and we are in tunnel mode*/
else
{
struct if_laddrreq iflr;
int sock;
sock = socket(AF_INET, SOCK_DGRAM, 0);
if (sock < 0)
{
dolog(LOG_WARNING, "Couldn't allocate a AF_INET socket for getting interface info\n");
return false;
}
memzero(&iflr, sizeof(iflr));
strncpy(iflr.iflr_name, intn->name, sizeof(iflr.iflr_name));
/*
* This a tunnel, find out based on it's src ip
* to which master it belongs
*/
if (ioctl(sock, SIOCGLIFPHYADDR, &iflr))
{
dolog(LOG_ERR, "Could not get GIF Addresses of tunnel %s: %s (%d)\n",
intn->name, strerror(errno), errno);
close(sock);
return false;
}
close(sock);
/* Find the master */
intn->master = int_find_ipv4(true, &((struct sockaddr_in *)&iflr.addr)->sin_addr);
if (!intn->master)
{
char buf[1024];
inet_ntop(AF_INET, &((struct sockaddr_in *)&iflr.addr)->sin_addr, (char *)&buf, sizeof(buf));
dolog(LOG_ERR, "Couldn't find the master device for %s (%s)\n", intn->name, buf);
return false;
}
/* Store the addresses */
memcpy(&intn->ipv4_local[0], &((struct sockaddr_in *)&iflr.addr)->sin_addr, sizeof(intn->ipv4_local[0]));
memcpy(&intn->ipv4_remote, &((struct sockaddr_in *)&iflr.dstaddr)->sin_addr, sizeof(intn->ipv4_remote));
}
return true;
}
#endif /* ECMH_BPF */
#ifndef ECMH_BPF
struct intnode *int_create(unsigned int ifindex)
#else
struct intnode *int_create(unsigned int ifindex, bool tunnel)
#endif
{
struct intnode *intn = NULL;
struct ifreq ifreq;
int sock;
/* Resize the interface array if needed */
if ((ifindex+1) > g_conf->maxinterfaces)
{
g_conf->ints = (struct intnode *)realloc(g_conf->ints, sizeof(struct intnode)*(ifindex+1));
if (!g_conf->ints)
{
dolog(LOG_ERR, "Couldn't init() - no memory for interface array.\n");
exit(-1);
}
/* Clear out the new memory */
memzero(&g_conf->ints[g_conf->maxinterfaces], sizeof(struct intnode)*((ifindex+1)-g_conf->maxinterfaces));
/* Configure the new maximum */
g_conf->maxinterfaces = (ifindex+1);
}
intn = &g_conf->ints[ifindex];
#ifndef ECMH_BPF
dolog(LOG_DEBUG, "Creating new interface %u\n", ifindex);
#else
dolog(LOG_DEBUG, "Creating new interface %u (%s)\n", ifindex, tunnel ? "Tunnel" : "Native");
#endif
sock = socket(AF_INET, SOCK_DGRAM, 0);
if (sock < 0)
{
dolog(LOG_ERR, "Couldn't create tempory socket for ioctl's\n");
return NULL;
}
memzero(intn, sizeof(*intn));
intn->ifindex = ifindex;
/* Default to 0, we discover this after the queries has been sent */
intn->mld_version = 0;
#ifdef ECMH_BPF
intn->socket = -1;
#endif
/* Get the interface name (eth0/sit0/...) */
/* Will be used for reports etc */
memzero(&ifreq, sizeof(ifreq));
#ifdef SIOCGIFNAME
ifreq.ifr_ifindex = ifindex;
if (ioctl(sock, SIOCGIFNAME, &ifreq) != 0)
#else
if (if_indextoname(ifindex, intn->name) == NULL)
#endif
{
dolog(LOG_ERR, "Couldn't determine interfacename of link %" PRIu64 " : %s\n", intn->ifindex, strerror(errno));
int_destroy(intn);
close(sock);
return NULL;
}
#ifdef SIOCGIFNAME
/* We just requested the name, use it */
memcpy(&intn->name, &ifreq.ifr_name, sizeof(intn->name));
#else
/* Put the name in the request */
memcpy(&ifreq.ifr_name, &intn->name, sizeof(ifreq.ifr_name));
#endif
/* Get the MTU size of this interface */
/* We will use that for fragmentation */
if (ioctl(sock, SIOCGIFMTU, &ifreq) != 0)
{
dolog(LOG_ERR, "Couldn't determine MTU size for %s, link %" PRIu64 " : %s\n", intn->name, intn->ifindex, strerror(errno));
int_destroy(intn);
close(sock);
return NULL;
}
if (ifreq.ifr_mtu < 1280)
{
dolog(LOG_ERR, "MTU size for %s is %u which is less than the IPv6 minimum of 1280\n", intn->name, ifreq.ifr_mtu);
int_destroy(intn);
close(sock);
return NULL;
}
/* The accepted MTU */
intn->mtu = ifreq.ifr_mtu;
#ifndef ECMH_BPF
/* Get hardware address + type */
if (ioctl(sock, SIOCGIFHWADDR, &ifreq) != 0)
{
dolog(LOG_ERR, "Couldn't determine hardware address for %s, link %" PRIu64 " : %s\n", intn->name, intn->ifindex, strerror(errno));
int_destroy(intn);
close(sock);
return NULL;
}
memcpy(&intn->hwaddr, &ifreq.ifr_hwaddr, sizeof(intn->hwaddr));
#endif
#ifndef ECMH_BPF
/* Ignore Loopback devices */
if (intn->hwaddr.sa_family == ARPHRD_LOOPBACK)
{
int_destroy(intn);
close(sock);
return NULL;
}
#endif
#ifdef ECMH_BPF
if (!int_create_bpf(intn, tunnel))
{
int_destroy(intn);
close(sock);
return NULL;
}
#else
/* Configure the interface to receive all multicast addresses */
if (g_conf->promisc)
{
struct ifreq ifr;
int err;
memzero(&ifr, sizeof(ifr));
strncpy(ifr.ifr_name, intn->name, sizeof(ifr.ifr_name));
err = ioctl(sock, SIOCGIFFLAGS, &ifr);
if (err != 0)
{
dolog(LOG_WARNING, "Couldn't get interface flags of %s/%" PRIu64 ": %s\n",
intn->name, intn->ifindex, strerror(errno));
}
else
{
/* Should use IFF_ALLMULTI, but that is not supported... */
ifr.ifr_flags |= IFF_PROMISC;
err = ioctl(sock, SIOCSIFFLAGS, &ifr);
if (err != 0)
{
dolog(LOG_WARNING, "Couldn't get interface flags of %s/%" PRIu64 ": %s\n",
intn->name, intn->ifindex, strerror(errno));
}
else
{
dolog(LOG_DEBUG, "Interface %s/%" PRIu64 " is now promiscuous\n",
intn->name, intn->ifindex);
}
}
}
#endif
/* Cleanup the socket */
close(sock);
if ( g_conf->upstream &&
strcasecmp(intn->name, g_conf->upstream) == 0)
{
intn->upstream = true;
g_conf->upstream_id = intn->ifindex;
}
else intn->upstream = false;
/* All okay */
return intn;
}
void int_destroy(struct intnode *intn)
{
D( dolog(LOG_DEBUG, "Destroying interface %s\n", intn->name);)
#ifdef ECMH_BPF
if (intn->socket != -1)
{
close(intn->socket);
intn->socket = -1;
}
#endif
/* Resetting the MTU to zero disabled the interface */
intn->mtu = 0;
}
struct intnode *int_find(unsigned int ifindex)
{
if (ifindex >= g_conf->maxinterfaces || g_conf->ints[ifindex].mtu == 0) return NULL;
return &g_conf->ints[ifindex];
}
#ifdef ECMH_BPF
struct intnode *int_find_ipv4(bool local, struct in_addr *ipv4)
{
struct intnode *intn;
int num = 0;
unsigned int i;
for (i = 0; i < g_conf->maxinterfaces; i++)
{
intn = &g_conf->ints[i];
/* Skip uninitialized interfaces */
if (intn->mtu == 0)
{
continue;
}
for (num = 0; num < INTNODE_MAXIPV4; num++)
{
if (memcmp(local ? &intn->ipv4_local[num] : &intn->ipv4_remote, ipv4, sizeof(*ipv4)) == 0)
{
return intn;
}
/* Only one remote IPv4 address */
if (!local)
{
break;
}
}
}
return NULL;
}
#endif /* ECMH_BPF */
/*
* Store the version of MLD if it is lower than the old one or the old one was 0 ;)
* We only respond MLDv1's this way when there is a MLDv1 router on the link.
* but we respond MLDv2's when there are only MLDv2 router on the link
* Even if we build without MLDv2 support we detect the version which
* could be used to determine if a router can't fallback to v1 for instance
* later on in diagnostics. When built without MLDv2 support we always do MLDv1 though.
* Everthing higher as MLDv2 is reported as MLDv2 as we don't know about it (yet :)
*/
void int_set_mld_version(struct intnode *intn, unsigned int newversion)
{
if (newversion == 1)
{
#ifdef ECMH_SUPPORT_MLD2
if (g_conf->mld2only)
{
dolog(LOG_DEBUG, "Configured as MLDv2 Only Host, ignoring MLDv1 packet\n");
return;
}
#endif
/*
* Only reset the version number
* if it wasn't set and not v1 yet
*/
if ( intn->mld_version == 0 &&
intn->mld_version != 1)
{
if (intn->mld_version > 1)
{
dolog(LOG_DEBUG, "MLDv1 Query detected on %s, downgrading from MLDv%" PRIu64 " to MLDv1\n", intn->name, intn->mld_version);
}
else
{
dolog(LOG_DEBUG, "MLDv1 detected on %s, setting it to MLDv1\n", intn->name);
}
intn->mld_version = 1;
intn->mld_last_v1 = gettimes();
}
}
#ifdef ECMH_SUPPORT_MLD2
else
{
/*
* Current version = 1 and haven't seen a v1 for a while?
* Reset the counter
*/
if ( intn->mld_last_v1 != 0 &&
(gettimes() > (intn->mld_last_v1 + ECMH_SUBSCRIPTION_TIMEOUT)))
{
dolog(LOG_DEBUG, "MLDv1 has not been seen for %" PRIu64 " seconds on %s, allowing upgrades\n",
(intn->mld_last_v1 + ECMH_SUBSCRIPTION_TIMEOUT), intn->name);
/* Reset the version */
intn->mld_version = 0;
intn->mld_last_v1 = 0;
}
if (g_conf->mld1only)
{
dolog(LOG_DEBUG, "Configured as MLDv1 Only Host, ignoring possible upgrade to MLDv%u\n",
newversion);
return;
}
/*
* Only reset the version number
* if it wasn't set and not v1 yet and not v2 yet
*/
if ( intn->mld_version == 0 &&
intn->mld_version != 1 &&
intn->mld_version != 2)
{
dolog(LOG_DEBUG, "MLDv%u detected on %s/%" PRIu64 ", setting it to MLDv%u\n",
newversion, intn->name, intn->ifindex, newversion);
intn->mld_version = newversion;
}
}
#else /* ECMH_SUPPORT_MLD2 */
else
{
dolog(LOG_DEBUG, "MLDv%u detected on %s/%" PRIu64 " while that version is not supported\n",
newversion, intn->name, intn->mld_version);
}
#endif /* ECMH_SUPPORT_MLD2 */
}
#ifdef ECMH_BPF
/* Add or update a local interface */
void local_update(struct intnode *intn)
{
struct localnode *localn;
int num=0;
struct in_addr any;
/* Any IPv4 address */
memzero(&any, sizeof(any));
for (num=0;num<INTNODE_MAXIPV4;num++)
{
/* Empty ? */
if (memcmp(&intn->ipv4_local[num], &any, sizeof(any)) == 0)
{
continue;
}
/* Try to find it first */
localn = local_find(&intn->ipv4_local[num]);
/* Already there? */
if (localn) continue;
/* Allocate a piece of memory */
localn = (struct localnode *)calloc(1, sizeof(*localn));
if (!localn)
{
dolog(LOG_ERR, "Couldn't allocate memory for localnode\n");
continue;
}
/* Fill it in */
localn->intn = intn;
dolog(LOG_DEBUG, "Adding %s to local tunnel-intercepting-interfaces\n", intn->name);
/* Add it to the list */
listnode_add(g_conf->locals, localn);
}
}
struct localnode *local_find(struct in_addr *ipv4)
{
struct localnode *localn;
struct listnode *ln;
int num = 0;
LIST_LOOP(g_conf->locals, localn, ln)
{
for (num = 0; num < INTNODE_MAXIPV4; num++)
{
if (memcmp(&localn->intn->ipv4_local[num], ipv4, sizeof(*ipv4)) == 0)
{
return localn;
}
}
}
return NULL;
}
void local_destroy(struct localnode *localn)
{
/* Free the memory */
free(localn);
}
#endif /* ECMH_BPF */
<file_sep>/src/subscr.c
/**************************************
ecmh - Easy Cast du Multi Hub
by <NAME> <<EMAIL>>
**************************************/
#include "ecmh.h"
/* Subscription Node */
struct subscrnode *subscr_create(const struct in6_addr *ipv6, int mode)
{
struct subscrnode *subscrn = calloc(1, sizeof(*subscrn));
if (!subscrn) return NULL;
/* Fill her in */
memcpy(&subscrn->ipv6, ipv6, sizeof(*ipv6));
subscrn->mode = mode;
subscrn->refreshtime = gettimes();
D(
{
char addr[INET6_ADDRSTRLEN];
memzero(addr, sizeof(addr));
inet_ntop(AF_INET6, &subscrn->ipv6, addr, sizeof(addr));
dolog(LOG_DEBUG, "Adding subscription %s (%s)\n", addr,
subscrn->mode == MLD2_MODE_IS_INCLUDE ? "INCLUDE" : "EXCLUDE");
}
)
/* All okay */
return subscrn;
}
void subscr_destroy(struct subscrnode *subscrn)
{
if (!subscrn) return;
D(
{
char addr[INET6_ADDRSTRLEN];
memzero(addr, sizeof(addr));
inet_ntop(AF_INET6, &subscrn->ipv6, addr, sizeof(addr));
dolog(LOG_DEBUG, "Destroying subscription %s (%s)\n", addr,
subscrn->mode == MLD2_MODE_IS_INCLUDE ? "INCLUDE" : "EXCLUDE");
}
)
/* Free the node */
free(subscrn);
}
struct subscrnode *subscr_find(const struct list *list, const struct in6_addr *ipv6)
{
struct subscrnode *subscrn;
struct listnode *ln;
LIST_LOOP(list, subscrn, ln)
{
if (IN6_ARE_ADDR_EQUAL(ipv6, &subscrn->ipv6)) return subscrn;
}
return NULL;
}
bool subscr_unsub(struct list *list, const struct in6_addr *ipv6)
{
struct subscrnode *subscrn;
struct listnode *ln;
LIST_LOOP(list, subscrn, ln)
{
if (IN6_ARE_ADDR_EQUAL(ipv6, &subscrn->ipv6))
{
/* Delete the entry from the list */
list_delete_node(list, ln);
/* Destroy the item itself */
subscr_destroy(subscrn);
return true;
}
}
return false;
}
<file_sep>/tools/mtrace6/mtrace6.c
/* $KAME: mtrace6.c,v 1.22 2003/09/23 11:06:56 itojun Exp $ */
/*
* Copyright (C) 1999 WIDE Project.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are 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. Neither the name of the project nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``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 PROJECT OR CONTRIBUTORS 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.
*/
#include <sys/types.h>
#include <sys/param.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <sys/select.h>
#include <sys/queue.h>
#include <net/if.h>
#if defined(__FreeBSD__) && __FreeBSD__ >= 3
#include <net/if_var.h>
#endif
#include <netinet/in.h>
#ifndef ECMH_VERSION
#include <netinet6/in6_var.h>
#endif
#include <netinet/icmp6.h>
#include <string.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <netdb.h>
#include <err.h>
#include <ifaddrs.h>
#ifndef ECMH_VERSION
#include "trace.h"
#else
#include "../../src/trace.h"
#include "../../src/mld.h"
#include <sys/time.h>
#include <time.h>
#endif
static char *gateway, *intface, *source, *group, *receiver, *destination;
static char *linkstr;
static int mldsoc, hops = 64, maxhops = 127, waittime = 3, querylen, opt_n;
static struct sockaddr_storage *gw_sock, *src_sock, *grp_sock, *dst_sock, *rcv_sock;
static char *querypacket;
static char frombuf[1024]; /* XXX: enough size? */
int main __P((int, char *[]));
static char *proto_type __P((u_int));
static char *pr_addr __P((struct sockaddr *, int, int));
static void setqid __P((int, char *));
static void mtrace_loop __P((void));
static char *str_rflags __P((unsigned int));
static void show_ip6_result __P((unsigned int));
static void show_result __P((struct sockaddr *, int));
static void set_sockaddr __P((char *, struct addrinfo *, struct sockaddr *,
size_t));
static int is_multicast __P((struct sockaddr *));
static char *all_routers_str __P((int));
static int ip6_validaddr __P((struct sockaddr_in6 *));
static int get_my_sockaddr __P((int, struct sockaddr *, size_t));
static void set_hlim __P((int, struct sockaddr *, int));
static void set_join __P((int, char *, struct sockaddr *));
static void set_filter __P((int, int));
static void open_socket __P((void));
static void make_ip6_packet __P((void));
static void make_packet __P((void));
static void usage __P((void));
int
main(argc, argv)
int argc;
char *argv[];
{
int op;
/* get parameters */
while((op = getopt(argc, argv, "d:g:h:i:l:m:nr:w:")) != -1) {
switch(op) {
case 'd':
destination = optarg;
break;
case 'g':
gateway = optarg;
break;
case 'h':
hops = atoi(optarg);
if (hops < 0 || hops > 255) {
warnx("query/response hops must be between 0 and 255");
usage();
}
break;
case 'i':
intface = optarg;
break;
case 'l':
linkstr = optarg;
break;
case 'm':
maxhops = atoi(optarg);
if (maxhops < 0 || maxhops > 255) {
warnx("maxhops must be between 0 and 255");
usage();
}
break;
case 'n':
opt_n = 1;
break;
case 'r':
receiver = optarg;
break;
case 'w':
waittime = atoi(optarg);
break;
case '?':
default:
usage();
break;
}
}
argc -= optind;
argv += optind;
if (argc < 2)
usage();
source = argv[0];
group = argv[1];
/* option consistency check */
if (gateway && linkstr)
errx(1, "-g and -l are exclusive");
/* examine addresses and open a socket */
open_socket();
/* construct a query packet according to the specified parameters */
make_packet();
mtrace_loop();
exit(0);
/*NOTREACHED*/
}
static char *
proto_type(type)
u_int type;
{
static char buf[80];
switch (type) {
case PROTO_DVMRP:
return ("DVMRP");
case PROTO_MOSPF:
return ("MOSPF");
case PROTO_PIM:
return ("PIM");
case PROTO_CBT:
return ("CBT");
case PROTO_PIM_SPECIAL:
return ("PIM/Special");
case PROTO_PIM_STATIC:
return ("PIM/Static");
case PROTO_DVMRP_STATIC:
return ("DVMRP/Static");
case 0:
return ("None");
default:
(void) sprintf(buf, "Unknown protocol code %d", type);
return (buf);
}
}
static char *
pr_addr(addr, numeric, salen)
struct sockaddr *addr;
int numeric;
int salen;
{
static char buf[MAXHOSTNAMELEN];
int flag = 0;
if (numeric)
flag |= NI_NUMERICHOST;
getnameinfo(addr, salen, buf, sizeof(buf), NULL, 0, flag);
return (buf);
}
static void
setqid(family, query)
int family;
char *query;
{
struct tr6_query *q6;
switch(family) {
case AF_INET6:
q6 = (struct tr6_query *)((struct mld1 *)query + 1);
q6->tr_qid = (u_int32_t)random();
}
}
static void
mtrace_loop()
{
int nsoc, rcvcc;
socklen_t fromlen;
struct timeval tv, tv_wait;
fd_set *fdsp;
size_t nfdsp;
struct sockaddr_storage from_ss;
struct sockaddr *from_sock = (struct sockaddr *)&from_ss;
/* initializa random number of query ID */
gettimeofday(&tv, 0);
srandom(tv.tv_usec);
while(1) { /* XXX */
setqid(gw_sock->ss_family, querypacket);
// We set the length to sizeof(struct sockaddr_in6) as
// Linux doesn't have a sa_len...
if (sendto(mldsoc, (void *)querypacket, querylen, 0,
(struct sockaddr *)gw_sock,
sizeof(struct sockaddr_in6)) < 0)
err(1, "sendto");
tv_wait.tv_sec = waittime;
tv_wait.tv_usec = 0;
nfdsp = howmany(mldsoc + 1, NFDBITS) * sizeof(fd_mask);
fdsp = malloc(nfdsp);
if (!fdsp)
err(1, "malloc");
memset(fdsp, 0, nfdsp);
FD_SET(mldsoc, fdsp);
if ((nsoc = select(mldsoc + 1, fdsp, NULL, NULL, &tv_wait)) < 0)
err(1, "select");
free(fdsp);
if (nsoc == 0) {
printf("Timeout\n");
exit(0); /* XXX try again? */
}
fromlen = sizeof(from_ss);
if ((rcvcc = recvfrom(mldsoc, frombuf, sizeof(frombuf), 0,
from_sock, &fromlen))
< 0)
err(1, "recvfrom");
show_result(from_sock, rcvcc);
exit(0); /* XXX */
}
}
char *fwd_code[] = {"NOERR", "WRONGIF", "SPRUNE", "RPRUNE", "SCOPED", "NORT",
"WRONGLH", "NOFWD", "RP", "RPFIF", "NOMC", "HIDDEN"};
char *fwd_errcode[] = {"", "NOSPC", "OLD", "ADMIN"};
static char *
str_rflags(flag)
unsigned int flag;
{
if (0x80 & flag) { /* fatal error */
flag &= ~0x80;
if (flag >= sizeof(fwd_errcode) / sizeof(char *) ||
flag == 0) {
warnx("unknown error code(%d)", flag);
return("UNKNOWN");
}
return(fwd_errcode[flag]);
}
/* normal code */
if (flag >= sizeof(fwd_code) / sizeof(char *)) {
warnx("unknown forward code(%d)", flag);
return("UNKNOWN");
}
return(fwd_code[flag]);
}
static void
show_ip6_result(datalen)
unsigned int datalen;
{
struct mld1 *mld6_tr_resp = (struct mld1 *)frombuf;
struct mld1 *mld6_tr_query = (struct mld1 *)querypacket;
struct tr6_query *tr6_rquery = (struct tr6_query *)(mld6_tr_resp + 1);
struct tr6_query *tr6_query = (struct tr6_query *)(mld6_tr_query + 1);
struct tr6_resp *tr6_resp = (struct tr6_resp *)(tr6_rquery + 1),
*rp, *rp_end;
int i;
if (datalen < sizeof(*mld6_tr_resp) + sizeof(*tr6_rquery) +
sizeof(*tr6_resp)) {
warnx("show_ip6_result: receive data length(%d) is short",
datalen);
return;
}
switch(mld6_tr_resp->type) {
case MLD_MTRACE_RESP:
if ((datalen - sizeof(*mld6_tr_resp) - sizeof(*tr6_rquery)) %
sizeof(*tr6_resp)) {
warnx("show_ip6_result: incomplete response (%d bytes)",
datalen);
return;
}
rp_end = (struct tr6_resp *)((char *)mld6_tr_resp + datalen);
/* sanity check for the response */
if (tr6_query->tr_qid != tr6_rquery->tr_qid ||
!IN6_ARE_ADDR_EQUAL(&tr6_query->tr_src, &tr6_rquery->tr_src) ||
!IN6_ARE_ADDR_EQUAL(&tr6_query->tr_dst, &tr6_rquery->tr_dst))
return; /* XXX: bark here? */
for (i = 0, rp = tr6_resp; rp < rp_end; i++, rp++) {
struct sockaddr_in6 sa_resp, sa_upstream;
/* reinitialize the sockaddr. paranoid? */
memset((void *)&sa_resp, 0, sizeof(sa_resp));
sa_resp.sin6_family = AF_INET6;
//sa_resp.sin6_len = sizeof(sa_resp);
memset((void *)&sa_upstream, 0, sizeof(sa_upstream));
sa_upstream.sin6_family = AF_INET6;
//sa_upstream.sin6_len = sizeof(sa_upstream);
sa_resp.sin6_addr = rp->tr_lcladdr;
sa_upstream.sin6_addr = rp->tr_rmtaddr;
/* print information for the router */
printf("%3d ", -i);/* index */
/* router address and incoming/outgoing interface */
printf("%s", pr_addr((struct sockaddr *)&sa_resp, opt_n, sizeof(sa_resp)));
printf("(%s/%d->%d) ",
pr_addr((struct sockaddr *)&sa_upstream, 1, sizeof(sa_resp)),
ntohl(rp->tr_inifid), ntohl(rp->tr_outifid));
/* multicast routing protocol type */
printf("%s ", proto_type(rp->tr_rproto));
/* forwarding error code */
printf("%s", str_rflags(rp->tr_rflags & 0xff));
putchar('\n');
}
break;
default: /* impossible... */
warnx("show_ip6_result: invalid ICMPv6 type(%d)",
mld6_tr_resp->type); /* assert? */
break;
}
}
static void
show_result(from, datalen)
struct sockaddr *from;
int datalen;
{
switch(from->sa_family) {
case AF_INET6:
show_ip6_result(datalen);
break;
default:
errx(1, "show_result: illegal AF(%d) on recv", from->sa_family);
}
}
static void
set_sockaddr(addrname, hints, sap, l)
char *addrname;
struct addrinfo *hints;
struct sockaddr *sap;
size_t l;
{
struct addrinfo *res;
int ret_ga;
ret_ga = getaddrinfo(addrname, NULL, hints, &res);
if (ret_ga)
errx(1, "getaddrinfo faild: %s", gai_strerror(ret_ga));
if (!res->ai_addr)
errx(1, "getaddrinfo failed");
if (res->ai_addrlen > l)
errx(1, "sockaddr too big");
memcpy((void *)sap, (void *)res->ai_addr, l);
freeaddrinfo(res);
}
static int
is_multicast(sa)
struct sockaddr *sa;
{
switch(sa->sa_family) {
case AF_INET6:
if (IN6_IS_ADDR_MULTICAST(&((struct sockaddr_in6 *)sa)->sin6_addr))
return 1;
else
return 0;
break;
default:
return 0; /* XXX: support IPv4? */
}
}
static char *
all_routers_str(family)
int family;
{
static char s[NI_MAXHOST];
switch(family) {
case AF_INET6:
if (linkstr)
snprintf(s, sizeof(s), "fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b%%%s", linkstr);
else /* use the default link (assuming it) */
snprintf(s, sizeof(s), "fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b");
return (s);
default:
errx(1, "all_routers_str: unknown AF(%d)", family);
}
}
static int
ip6_validaddr(addr)
struct sockaddr_in6 *addr;
{
// int s;
// struct in6_ifreq ifr6;
// u_int32_t flags6;
/* we need a global address only...XXX: should be flexible? */
if (IN6_IS_ADDR_LOOPBACK(&addr->sin6_addr) ||
IN6_IS_ADDR_LINKLOCAL(&addr->sin6_addr) ||
IN6_IS_ADDR_SITELOCAL(&addr->sin6_addr))
return(0);
#if 0
/* get IPv6 dependent flags and examine them */
if ((s = socket(AF_INET6, SOCK_DGRAM, 0)) < 0)
err(1, "ip6_validaddr: socket");
strncpy(ifr6.ifr_name, ifname, sizeof(ifr6.ifr_name));
ifr6.ifr_addr = *addr;
if (ioctl(s, SIOCGIFAFLAG_IN6, &ifr6) < 0)
err(1, "ioctl(SIOCGIFAFLAG_IN6)");
close(s);
flags6 = ifr6.ifr_ifru.ifru_flags6;
if (flags6 & (IN6_IFF_ANYCAST | IN6_IFF_TENTATIVE |
IN6_IFF_DUPLICATED | IN6_IFF_DETACHED))
return(0);
#endif
return(1);
}
static int
get_my_sockaddr(family, addrp, sa_len)
int family;
struct sockaddr *addrp;
size_t sa_len;
{
struct ifaddrs *ifap, *ifa;
if (getifaddrs(&ifap) != 0) {
err(1, "getifaddrs");
/*NOTREACHED */
}
for (ifa = ifap; ifa; ifa = ifa->ifa_next) {
if (ifa->ifa_addr->sa_family != family)
continue;
// if (ifa->ifa_addr->sa_len > l)
// continue;
switch(family) {
case AF_INET6:
if (ip6_validaddr((struct sockaddr_in6 *)ifa->ifa_addr))
goto found;
}
}
freeifaddrs(ifap);
return (-1); /* not found */
found:
memcpy((void *)addrp, (void *)ifa->ifa_addr, sa_len);
freeifaddrs(ifap);
return (0);
}
static void
set_hlim(s, addr, hops)
int s, hops;
struct sockaddr *addr;
{
struct sockaddr_in6 *sin6;
int opt;
switch(addr->sa_family) {
case AF_INET6:
sin6 = (struct sockaddr_in6 *)addr;
opt = IN6_IS_ADDR_MULTICAST(&sin6->sin6_addr) ?
IPV6_MULTICAST_HOPS : IPV6_UNICAST_HOPS;
if (setsockopt(s, IPPROTO_IPV6, opt, (char *)&hops,
sizeof(hops)) == -1)
err(1, "setsockopt(%s)",
(opt == IPV6_MULTICAST_HOPS) ?
"IPV6_MULTICAST_HOPS" : "IPV6_UNICAST_HOPS");
break;
}
}
static void
set_join(s, ifname, group)
int s;
char *ifname;
struct sockaddr *group;
{
struct ipv6_mreq mreq6;
u_int ifindex;
switch(group->sa_family) {
case AF_INET6:
if ((ifindex = if_nametoindex(ifname)) == 0)
err(1, "set_join: if_nametoindex failed for %s", ifname);
mreq6.ipv6mr_multiaddr =
((struct sockaddr_in6 *)group)->sin6_addr;
mreq6.ipv6mr_interface = ifindex;
if (setsockopt(s, IPPROTO_IPV6, IPV6_JOIN_GROUP, &mreq6,
sizeof(mreq6)) < 0)
err(1, "setsockopt(IPV6_JOIN_GROUP)");
break;
}
}
static void
set_filter(s, family)
int s, family;
{
struct icmp6_filter filter6;
switch(family) {
case AF_INET6:
ICMP6_FILTER_SETBLOCKALL(&filter6);
ICMP6_FILTER_SETPASS(MLD_MTRACE_RESP, &filter6);
if (setsockopt(s, IPPROTO_ICMPV6, ICMP6_FILTER, &filter6,
sizeof(filter6)) < 0)
err(1, "setsockopt(ICMP6_FILTER)");
break;
}
}
static void
open_socket()
{
struct addrinfo hints;
static struct sockaddr_storage gw_ss, src_ss, grp_ss, dst_ss, rcv_ss;
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_INET6; /* to be independent of AF? */
hints.ai_socktype = SOCK_RAW;
hints.ai_protocol = IPPROTO_ICMPV6;
/* multicast group(must be specified) */
grp_sock = (struct sockaddr_storage *)&grp_ss;
set_sockaddr(group, &hints, (struct sockaddr *)grp_sock, sizeof(grp_ss));
if (!is_multicast((struct sockaddr *)grp_sock))
errx(1, "group(%s) is not a multicast address", group);
/* multicast source(must be specified) */
src_sock = (struct sockaddr_storage *)&src_ss;
set_sockaddr(source, &hints, (struct sockaddr *)src_sock, sizeof(src_ss));
if (is_multicast((struct sockaddr *)src_sock))
errx(1, "source(%s) is not a unicast address", source);
/* last hop gateway for the destination(if specified) */
gw_sock = (struct sockaddr_storage *)&gw_ss;
if (gateway) /* can be either multicast or unicast */
set_sockaddr(gateway, &hints, (struct sockaddr *)gw_sock, sizeof(gw_ss));
else {
char *r = all_routers_str(grp_sock->ss_family);
set_sockaddr(r, &hints, (struct sockaddr *)gw_sock, sizeof(gw_ss));
}
/* destination address for the trace */
dst_sock = (struct sockaddr_storage *)&dst_ss;
if (destination) {
set_sockaddr(destination, &hints, (struct sockaddr *)dst_sock, sizeof(dst_ss));
if (is_multicast((struct sockaddr *)dst_sock))
errx(1, "destination(%s) is not a unicast address",
destination);
}
else {
/* XXX: consider interface? */
get_my_sockaddr(grp_sock->ss_family, (struct sockaddr *)dst_sock, sizeof(dst_sock));
}
/* response receiver(if specified) */
rcv_sock = (struct sockaddr_storage *)&rcv_ss;
if (receiver) { /* can be either multicast or unicast */
set_sockaddr(receiver, &hints, (struct sockaddr *)rcv_sock, sizeof(rcv_ss));
if (is_multicast((struct sockaddr *)rcv_sock) &&
intface == NULL) {
#ifdef notyet
warnx("receive I/F is not specified for multicast"
"response(%s)", receiver);
intface = default_intface;
#else
errx(1, "receive I/F is not specified for multicast"
"response(%s)", receiver);
#endif
}
}
else {
/* XXX: consider interface? */
get_my_sockaddr(grp_sock->ss_family, (struct sockaddr *)rcv_sock, sizeof(rcv_sock));
}
if ((mldsoc = socket(hints.ai_family, hints.ai_socktype,
hints.ai_protocol)) < 0)
err(1, "socket");
/* set necessary socket options */
if (hops)
set_hlim(mldsoc, (struct sockaddr *)gw_sock, hops);
if (receiver && is_multicast((struct sockaddr *)rcv_sock))
set_join(mldsoc, intface, (struct sockaddr *)rcv_sock);
set_filter(mldsoc, grp_sock->ss_family);
}
static void
make_ip6_packet()
{
struct mld1 *mld6_tr_query;
struct tr6_query *tr6_query;
querylen = sizeof(*mld6_tr_query) + sizeof(*tr6_query);
if ((querypacket = malloc(querylen)) == NULL)
errx(1, "make_ip6_packet: malloc failed");
memset(querypacket, 0, querylen);
/* fill in MLD header */
mld6_tr_query = (struct mld1 *)querypacket;
mld6_tr_query->type = MLD_MTRACE;
mld6_tr_query->code = maxhops & 0xff;
mld6_tr_query->mca = ((struct sockaddr_in6 *)grp_sock)->sin6_addr;
/* fill in mtrace query fields */
tr6_query = (struct tr6_query *)(mld6_tr_query + 1);
tr6_query->tr_src = ((struct sockaddr_in6 *)src_sock)->sin6_addr;
tr6_query->tr_dst = ((struct sockaddr_in6 *)dst_sock)->sin6_addr;
tr6_query->tr_raddr = ((struct sockaddr_in6 *)rcv_sock)->sin6_addr;
tr6_query->tr_rhlim = 0xff & hops;
}
static void
make_packet()
{
switch(grp_sock->ss_family) {
case AF_INET6:
make_ip6_packet();
break;
default:
errx(1, "make_packet: unsupported AF(%d)", grp_sock->ss_family);
}
}
static void
usage()
{
fprintf(stderr, "usage: mtrace6 "
"[-d destination] [-g gateway] [-h hops] [-i interface] "
"[-l link] [-m maxhops] [-n] [-r response_addr] [-w waittime] "
"source group\n");
exit(1);
}
<file_sep>/src/grpint.c
/**************************************
ecmh - Easy Cast du Multi Hub
by <NAME> <<EMAIL>>
**************************************/
#include "ecmh.h"
struct grpintnode *grpint_create(const struct intnode *interface)
{
struct grpintnode *grpintn = calloc(1, sizeof(*grpintn));
if (!grpintn) return NULL;
/* Fill her in */
grpintn->ifindex = interface->ifindex;
/* Setup the list */
grpintn->subscriptions = list_new();
grpintn->subscriptions->del = (void(*)(void *))subscr_destroy;
/* All okay */
return grpintn;
}
void grpint_destroy(struct grpintnode *grpintn)
{
if (!grpintn) return;
/* Empty the subscriber list */
list_delete_all_node(grpintn->subscriptions);
/* Free the node */
free(grpintn);
}
struct grpintnode *grpint_find(const struct list *list, const struct intnode *interface)
{
struct grpintnode *grpintn;
struct listnode *ln;
LIST_LOOP(list, grpintn, ln)
{
if (grpintn->ifindex == interface->ifindex) return grpintn;
}
return NULL;
}
/*
* grpintn = The GroupInterface node
* ipv6 = Source IPv6 address
* ff3x::/96 : The source IPv6 address that wants to (not) receive this S<->G channel
* mode = MLD2_MODE_IS_INCLUDE/MLD2_MODE_IS_EXCLUDE
*/
bool grpint_refresh(struct grpintnode *grpintn, const struct in6_addr *ipv6, unsigned int mode)
{
struct subscrnode *subscrn;
/* Find our beloved group */
subscrn = subscr_find(grpintn->subscriptions, ipv6);
/* Exclude all ? -> Unsubscribe */
if ( mode == MLD2_MODE_IS_EXCLUDE &&
IN6_IS_ADDR_UNSPECIFIED(ipv6))
{
/*
* Don't refresh the subscription,
* causing it to be removed later on
* because of a timeout
*/
return true;
}
if (!subscrn)
{
/* Create the subscr node */
subscrn = subscr_create(ipv6, mode);
/* Add the group to the list */
if (subscrn)
{
listnode_add(grpintn->subscriptions, (void *)subscrn);
}
}
if (!subscrn) return false;
/* Mode still the same? */
if (mode != subscrn->mode)
{
dolog(LOG_DEBUG, "grpint_refresh() - Mode changed from %" PRIu64 " to %u\n", subscrn->mode, mode);
subscrn->mode = mode;
}
/* Refresh it */
subscrn->refreshtime = time(NULL);
/* All Okay */
return true;
}
<file_sep>/src/groups.c
/**************************************
ecmh - Easy Cast du Multi Hub
by <NAME> <<EMAIL>>
**************************************/
#include "ecmh.h"
/* Create a groupnode */
static struct groupnode *group_create(const struct in6_addr *mca);
static struct groupnode *group_create(const struct in6_addr *mca)
{
struct groupnode *groupn = calloc(1, sizeof(*groupn));
if (!groupn) return NULL;
/* Fill her in */
memcpy(&groupn->mca, mca, sizeof(*mca));
/* Setup the list */
groupn->interfaces = list_new();
groupn->interfaces->del = (void(*)(void *))grpint_destroy;
D(
{
char mca_txt[INET6_ADDRSTRLEN];
memzero(mca_txt, sizeof(mca_txt));
inet_ntop(AF_INET6, mca, mca_txt, sizeof(mca_txt));
dolog(LOG_DEBUG, "Created group %s\n", mca_txt);
}
)
/* All okay */
return groupn;
}
void group_destroy(struct groupnode *groupn)
{
if (!groupn) return;
D(
{
char mca_txt[INET6_ADDRSTRLEN];
memzero(mca_txt, sizeof(mca_txt));
inet_ntop(AF_INET6, &groupn->mca, mca_txt, sizeof(mca_txt));
dolog(LOG_DEBUG, "Destroying group %s\n", mca_txt);
}
)
/* Empty the subscriber list */
list_delete_all_node(groupn->interfaces);
/* Free the node */
free(groupn);
}
struct groupnode *group_find(const struct in6_addr *mca)
{
struct groupnode *groupn;
struct listnode *ln;
LIST_LOOP(g_conf->groups, groupn, ln)
{
if (IN6_ARE_ADDR_EQUAL(mca, &groupn->mca)) return groupn;
}
return NULL;
}
/*
* Find the groupint or create it
* mca = The IPv6 address of the Multicast group
* interface = the interface we received it on
*/
struct grpintnode *groupint_get(const struct in6_addr *mca, struct intnode *interface, bool *isnew)
{
struct groupnode *groupn;
struct grpintnode *grpintn;
uint64_t t = gettimes();
*isnew = false;
/* Find our beloved group */
groupn = group_find(mca);
if (!groupn)
{
/* Create the group node */
groupn = group_create(mca);
/* Add the group to the list */
if (groupn)
{
listnode_add(g_conf->groups, (void *)groupn);
*isnew = true;
}
}
/* Forward it if we haven't done so for quite some time */
else if ((t - groupn->lastforward) >= ECMH_SUBSCRIPTION_TIMEOUT)
{
dolog(LOG_DEBUG, "Last update was %d seconds ago -> resending\n", (int)(t - groupn->lastforward));
*isnew = true;
}
if (!groupn)
{
return NULL;
}
if (isnew)
{
groupn->lastforward = t;
}
/* Find the interface in this group */
grpintn = grpint_find(groupn->interfaces, interface);
if (!grpintn)
{
/* Create the groupinterface node */
grpintn = grpint_create(interface);
/* Add the group to the list */
if (grpintn) listnode_add(groupn->interfaces, (void *)grpintn);
}
return grpintn;
}
<file_sep>/src/mld.h
/**************************************
ecmh - Easy Cast du Multi Hub
by <NAME> <<EMAIL>>
**************************************/
/* Wrappers so we don't have to change the copied stuff ;) */
#define __u8 uint8_t
#define __u16 uint16_t
/* Determine Endianness */
#if BYTE_ORDER == LITTLE_ENDIAN
/* 1234 machines */
#define __LITTLE_ENDIAN_BITFIELD 1
#elif BYTE_ORDER == BIG_ENDIAN
/* 4321 machines */
#define __BIG_ENDIAN_BITFIELD 1
# define WORDS_BIGENDIAN 1
#elif BYTE_ORDER == PDP_ENDIAN
/* 3412 machines */
#error PDP endianness not supported yet!
#else
#error unknown endianness!
#endif
/* Per RFC */
struct mld1 {
__u8 type;
__u8 code;
__u16 csum;
__u16 mrc;
__u16 resv1;
struct in6_addr mca;
};
/* MLDv2 Report */
#ifndef ICMP6_V2_MEMBERSHIP_REPORT
#define ICMP6_V2_MEMBERSHIP_REPORT 143
#endif
/* MLDv2 Report - Experimental Code */
#ifndef ICMP6_V2_MEMBERSHIP_REPORT_EXP
#define ICMP6_V2_MEMBERSHIP_REPORT_EXP 206
#endif
/* MLDv2 Exclude/Include */
#ifndef MLD2_MODE_IS_INCLUDE
#define MLD2_MODE_IS_INCLUDE 1
#endif
#ifndef MLD2_MODE_IS_EXCLUDE
#define MLD2_MODE_IS_EXCLUDE 2
#endif
#ifndef MLD2_CHANGE_TO_INCLUDE
#define MLD2_CHANGE_TO_INCLUDE 3
#endif
#ifndef MLD2_CHANGE_TO_EXCLUDE
#define MLD2_CHANGE_TO_EXCLUDE 4
#endif
#ifndef MLD2_ALLOW_NEW_SOURCES
#define MLD2_ALLOW_NEW_SOURCES 5
#endif
#ifndef MLD2_BLOCK_OLD_SOURCES
#define MLD2_BLOCK_OLD_SOURCES 6
#endif
#ifndef MLD2_ALL_MCR_INIT
#define MLD2_ALL_MCR_INIT { { { 0xff,0x02,0,0,0,0,0,0,0,0,0,0,0,0,0,0x16 } } }
#endif
#ifndef ICMP6_ROUTER_RENUMBERING
#define ICMP6_ROUTER_RENUMBERING 138 /* router renumbering */
#endif
#ifndef ICMP6_NI_QUERY
#define ICMP6_NI_QUERY 139 /* node information request */
#endif
#ifndef ICMP6_NI_REPLY
#define ICMP6_NI_REPLY 140 /* node information reply */
#endif
#ifndef MLD_MTRACE_RESP
#define MLD_MTRACE_RESP 200 /* Mtrace response (to sender) */
#endif
#ifndef MLD_MTRACE
#define MLD_MTRACE 201 /* Mtrace messages */
#endif
#ifndef ICMP6_DST_UNREACH_BEYONDSCOPE
#define ICMP6_DST_UNREACH_BEYONDSCOPE 2 /* Beyond scope of source address */
#endif
#ifndef ICMP6_NI_SUCCESS
#define ICMP6_NI_SUCCESS 0 /* node information successful reply */
#endif
#ifndef ICMP6_NI_REFUSED
#define ICMP6_NI_REFUSED 1 /* node information request is refused */
#endif
#ifndef ICMP6_NI_UNKNOWN
#define ICMP6_NI_UNKNOWN 2 /* unknown Qtype */
#endif
#ifndef ICMP6_ROUTER_RENUMBERING_COMMAND
#define ICMP6_ROUTER_RENUMBERING_COMMAND 0 /* rr command */
#endif
#ifndef ICMP6_ROUTER_RENUMBERING_RESULT
#define ICMP6_ROUTER_RENUMBERING_RESULT 1 /* rr result */
#endif
#ifndef ICMP6_ROUTER_RENUMBERING_SEQNUM_RESET
#define ICMP6_ROUTER_RENUMBERING_SEQNUM_RESET 255 /* rr seq num reset */
#endif
/* From linux/net/ipv6/mcast.c */
/*
* These header formats should be in a separate include file, but icmpv6.h
* doesn't have in6_addr defined in all cases, there is no __u128, and no
* other files reference these.
*
* +-DLS 4/14/03
*
* Multicast Listener Discovery version 2 headers
* Modified as they are where not ANSI C compliant
*/
struct mld2_grec {
__u8 grec_type;
__u8 grec_auxwords;
__u16 grec_nsrcs;
struct in6_addr grec_mca;
/* struct in6_addr grec_src[0]; */
};
struct mld2_report {
__u8 type;
__u8 resv1;
__u16 csum;
__u16 resv2;
__u16 ngrec;
/* struct mld2_grec grec[0]; */
};
struct mld2_query {
__u8 type;
__u8 code;
__u16 csum;
__u16 mrc;
__u16 resv1;
struct in6_addr mca;
#if defined(__LITTLE_ENDIAN_BITFIELD)
uint32_t qrv:3,
suppress:1,
resv2:4;
#elif defined(__BIG_ENDIAN_BITFIELD)
uint32_t resv2:4,
suppress:1,
qrv:3;
#else
#error "Please fix <asm/byteorder.h>"
#endif
__u8 qqic;
__u16 nsrcs;
/* struct in6_addr srcs[0]; */
};
#define IGMP6_UNSOLICITED_IVAL (10*HZ)
#define MLD_QRV_DEFAULT 2
#define MLD_V1_SEEN(idev) ((idev)->mc_v1_seen && \
time_before(jiffies, (idev)->mc_v1_seen))
#define MLDV2_MASK(value, nb) ((nb)>=32 ? (value) : ((1<<(nb))-1) & (value))
#define MLDV2_EXP(thresh, nbmant, nbexp, value) \
((value) < (thresh) ? (value) : \
((MLDV2_MASK(value, nbmant) | (1<<(nbmant+nbexp))) << \
(MLDV2_MASK((value) >> (nbmant), nbexp) + (nbexp))))
#define MLDV2_QQIC(value) MLDV2_EXP(0x80, 4, 3, value)
#define MLDV2_MRC(value) MLDV2_EXP(0x8000, 12, 3, value)
<file_sep>/tools/mtrace6/Makefile
# /**************************************
# ecmh - Easy Cast du Multi Hub
# by <NAME> <<EMAIL>>
# **************************************/
#
# Tools Makefile for ecmh - <NAME> <<EMAIL>>
#
# mtrace6 is taken from the KAME distribution, see http://www.kame.net
# Copyright etc is theirs, it is only included for convienience.
BINS = mtrace6
SRCS = mtrace6.c
INCS = ../../src/trace.h
DEPS = ../../Makefile ../Makefile Makefile
OBJS = mtrace6.o
CFLAGS = -W -Wall -Wno-unused -D_GNU_SOURCE -D'ECMH_VERSION="$(ECMH_VERSION)"' $(ECMH_OPTIONS)
LDFLAGS =
RM = @rm
LINK = @echo "* Linking $@"; $(CC) $(CFLAGS) $(LDFLAGS)
-include $(OBJS:.o=.d)
all: $(BINS)
depend: clean
@echo "* Making dependencies"
@$(MAKE) -s $(OBJS)
@echo "* Making dependencies - done"
%.o: %.c $(DEPS)
@echo "* Compiling $@";
@$(CC) -c $(CFLAGS) $*.c -o $*.o
@$(CC) -MM $(CFLAGS) $*.c > $*.d
@cp -f $*.d $*.d.tmp
@sed -e 's/.*://' -e 's/\\$$//' < $*.d.tmp | fmt -1 | \
sed -e 's/^ *//' -e 's/$$/:/' >> $*.d
@rm -f $*.d.tmp
mtrace6: $(DEPS) $(OBJS) $(INCS)
$(LINK) -o $@ $(OBJS) $(LDLIBS)
ifeq ($(shell echo $(ECMH_OPTIONS) | grep -c "DEBUG"),0)
@strip $@
endif
clean:
$(RM) -f $(OBJS) $(BINS)
# Mark targets as phony
.PHONY : all clean mtrace6
<file_sep>/src/ecmh.c
/**************************************
ecmh - Easy Cast du Multi Hub
by <NAME> <<EMAIL>>
***************************************
Docs:
netdevice(7), packet(7)
RFC 2710 - Multicast Listener Discovery (MLD) for IPv6
RFC 3569 - An Overview of Source-Specific Multicast (SSM)
RFC 3590 - Source Address Selection for the Multicast Listener Discovery (MLD) Protocol
RFC 3678 - Socket Interface Extensions for Multicast Source Filters
RFC 3810 - Multicast Listener Discovery Version 2 (MLDv2) for IPv6
http://www.ietf.org/internet-drafts/draft-holbrook-idmr-igmpv3-ssm-05.txt
Using IGMPv3 and MLDv2 For Source-Specific Multicast
- Querier Election support (MLDv2 7.6.2 + 7.1)
- Not implemented otherwise ECMH would not work.
Todo:
- Protocol Robustness, send twice, first with S flag, second without.
- Force check for HopByHop
***************************************/
#include "ecmh.h"
/* Configuration Variables */
struct conf *g_conf;
volatile int g_needs_timeout = false;
/*
* 6to4 relay address 172.16.31.10
* This is because some people also run 6to4 on their machines
* and that would cause every packet to fail
*/
static const char ipv4_6to4_relay[4] = { '\xc0', '\x58', '\x63', '\x01'};
static void l2_ethtype(struct intnode *intn, const void *packet, const unsigned int len, const unsigned int ether_type);
/**************************************
Functions
**************************************/
static uint16_t inchksum(const void *data, uint32_t length);
static uint16_t inchksum(const void *data, uint32_t length)
{
register long sum = 0;
register const uint16_t *wrd = (const uint16_t *)data;
register long slen = (long)length;
while (slen >= 2)
{
sum += *wrd++;
slen -= 2;
}
if (slen > 0)
{
sum += *(const uint8_t *)wrd;
}
while (sum >> 16)
{
sum = (sum & 0xffff) + (sum >> 16);
}
return (uint16_t)sum;
}
static uint16_t ipv6_checksum(const struct ip6_hdr *ip6, uint8_t protocol, const void *data, const uint16_t length);
static uint16_t ipv6_checksum(const struct ip6_hdr *ip6, uint8_t protocol, const void *data, const uint16_t length)
{
struct
{
uint16_t length;
uint16_t zero1;
uint8_t zero2;
uint8_t next;
} pseudo;
register uint32_t chksum = 0;
pseudo.length = htons(length);
pseudo.zero1 = 0;
pseudo.zero2 = 0;
pseudo.next = protocol;
/* IPv6 Source + Dest */
chksum = inchksum(&ip6->ip6_src, sizeof(ip6->ip6_src) + sizeof(ip6->ip6_dst));
chksum += inchksum(&pseudo, sizeof(pseudo));
chksum += inchksum(data, length);
/* Wrap in the carries to reduce chksum to 16 bits. */
chksum = (chksum >> 16) + (chksum & 0xffff);
chksum += (chksum >> 16);
/* Take ones-complement and replace 0 with 0xFFFF. */
chksum = (uint16_t) ~chksum;
if (chksum == 0UL)
{
chksum = 0xffffUL;
}
return (uint16_t)chksum;
}
static struct lookup
{
uint64_t num;
const char *desc;
} icmpv6_types[] = {
{ ICMP6_DST_UNREACH, "Destination Unreachable" },
{ ICMP6_PACKET_TOO_BIG, "Packet too big" },
{ ICMP6_TIME_EXCEEDED, "Time Exceeded" },
{ ICMP6_PARAM_PROB, "Parameter Problem" },
{ ICMP6_ECHO_REQUEST, "Echo Request" },
{ ICMP6_ECHO_REPLY, "Echo Reply" },
{ ICMP6_MEMBERSHIP_QUERY, "Membership Query" },
{ ICMP6_MEMBERSHIP_REPORT, "Membership Report" },
{ ICMP6_MEMBERSHIP_REDUCTION, "Membership Reduction" },
{ ICMP6_V2_MEMBERSHIP_REPORT, "Membership Report (V2)" },
{ ICMP6_V2_MEMBERSHIP_REPORT_EXP, "Membership Report (V2) - Experimental" },
{ ND_ROUTER_SOLICIT, "ND Router Solicitation" },
{ ND_ROUTER_ADVERT, "ND Router Advertisement" },
{ ND_NEIGHBOR_SOLICIT, "ND Neighbour Solicitation" },
{ ND_NEIGHBOR_ADVERT, "ND Neighbour Advertisement" },
{ ND_REDIRECT, "ND Redirect" },
{ ICMP6_ROUTER_RENUMBERING, "Router Renumbering", },
{ ICMP6_NI_QUERY, "Node Information Query" },
{ ICMP6_NI_REPLY, "Node Information Reply" },
{ MLD_MTRACE_RESP, "Mtrace Response" },
{ MLD_MTRACE, "Mtrace Message" },
{ 0, NULL },
}, icmpv6_codes_unreach[] = {
{ ICMP6_DST_UNREACH_NOROUTE, "No route to destination" },
{ ICMP6_DST_UNREACH_ADMIN, "Administratively prohibited" },
{ ICMP6_DST_UNREACH_BEYONDSCOPE, "Beyond scope of source address" },
{ ICMP6_DST_UNREACH_ADDR, "Address Unreachable" },
{ ICMP6_DST_UNREACH_NOPORT, "Port Unreachable" },
{ 0, NULL },
}, icmpv6_codes_ttl[] = {
{ ICMP6_TIME_EXCEED_TRANSIT, "Time Exceeded during Transit", },
{ ICMP6_TIME_EXCEED_REASSEMBLY, "Time Exceeded during Reassembly" },
{ 0, NULL },
}, icmpv6_codes_param[] = {
{ ICMP6_PARAMPROB_HEADER, "Erroneous Header Field" },
{ ICMP6_PARAMPROB_NEXTHEADER, "Unrecognized Next Header" },
{ ICMP6_PARAMPROB_OPTION, "Unrecognized Option" },
{ 0, NULL },
}, icmpv6_codes_ni[] = {
{ ICMP6_NI_SUCCESS, "Node Information Successful Reply" },
{ ICMP6_NI_REFUSED, "Node Information Request Is Refused" },
{ ICMP6_NI_UNKNOWN, "Unknown Qtype" },
{ 0, NULL },
}, icmpv6_codes_renumber[] = {
{ ICMP6_ROUTER_RENUMBERING_COMMAND, "Router Renumbering Command" },
{ ICMP6_ROUTER_RENUMBERING_RESULT, "Router Renumbering Result" },
{ ICMP6_ROUTER_RENUMBERING_SEQNUM_RESET,"Router Renumbering Sequence Number Reset"},
{ 0, NULL },
}, icmpv6_codes_none[] = {
{ 0, NULL },
#ifdef DEBUG
}, mld2_grec_types[] = {
{ MLD2_MODE_IS_INCLUDE, "MLDv2 Mode Is Include" },
{ MLD2_MODE_IS_EXCLUDE, "MLDv2 Mode Is Exclude" },
{ MLD2_CHANGE_TO_INCLUDE, "MLDv2 Change to Include" },
{ MLD2_CHANGE_TO_EXCLUDE, "MLDv2 Change to Exclude" },
{ MLD2_ALLOW_NEW_SOURCES, "MLDv2 Allow New Source" },
{ MLD2_BLOCK_OLD_SOURCES, "MLDv2 Block Old Sources" },
{ 0, NULL },
#endif
};
static const char *lookup(struct lookup *l, unsigned int num);
static const char *lookup(struct lookup *l, unsigned int num)
{
unsigned int i;
for (i=0; l && l[i].desc; i++)
{
if (l[i].num != num)
{
continue;
}
return l[i].desc;
}
return "Unknown";
}
#define icmpv6_type(type) lookup(icmpv6_types, type)
static const char *icmpv6_code(unsigned int type, unsigned int code);
static const char *icmpv6_code(unsigned int type, unsigned int code)
{
struct lookup *l = NULL;
switch (type)
{
case ICMP6_DST_UNREACH: l = icmpv6_codes_unreach; break;
case ICMP6_TIME_EXCEEDED: l = icmpv6_codes_ttl; break;
case ICMP6_PARAM_PROB: l = icmpv6_codes_param; break;
case ICMP6_NI_QUERY:
case ICMP6_NI_REPLY: l = icmpv6_codes_ni; break;
case ICMP6_ROUTER_RENUMBERING: l = icmpv6_codes_renumber; break;
default: l = icmpv6_codes_none; break;
}
return lookup(l, code);
}
#ifndef ECMH_GETIFADDR
static uint8_t nibble2int(unsigned char c);
static uint8_t nibble2int(unsigned char c)
{
uint8_t n;
c = tolower(c);
if (c >= '0' && c <= '9')
{
n = c - '0';
}
else if (c >= 'a' && c <= 'f')
{
n = c - 'a' + 10;
}
else
{
assert(false);
n = 0;
}
return n;
}
#endif
/* Initialize interfaces */
static void update_interfaces(struct intnode *intn);
static void update_interfaces(struct intnode *intn)
{
static uint64_t last_update = 0;
struct intnode *specific = intn;
struct in6_addr addr;
unsigned int ifindex = 0;
bool newintn = false;
#ifdef ECMH_GETIFADDR
bool ignore = false;
struct ifaddrs *ifap, *ifa;
#else
FILE *file;
unsigned int prefixlen, scope, flags, i;
char devname[IFNAMSIZ], buf[256];
#endif /* !ECMH_GETIFADDR */
int gotlinkl = false, gotglobal = false, gotipv4 = false;
uint64_t t;
/* Only update every 5 minutes to avoid rerunning it every packet */
t = gettimes();
if ((last_update + (5*60)) > t)
{
return;
}
last_update = t;
dolog(LOG_DEBUG, "Updating Interfaces\n");
#ifndef ECMH_GETIFADDR
/* Get link local addresses from /proc/net/if_inet6 */
file = fopen("/proc/net/if_inet6", "r");
/* We can live without it though */
if (!file)
{
dolog(LOG_WARNING, "Couldn't open /proc/net/if_inet6 for figuring out local interfaces\n");
return;
}
/* Format "fe80000000000000029027fffe24bbab 02 0a 20 80 eth0" */
while (fgets(buf, sizeof(buf), file))
{
memzero(&addr, sizeof(addr));
for (i = 0; i < 16; i++)
{
addr.s6_addr[i] = (nibble2int(buf[(i*2)]) << 4) + nibble2int(buf[(i*2)+1]);
}
if (5 != sscanf(&buf[33], "%x %x %x %x %8s", &ifindex, &prefixlen, &scope, &flags, devname))
{
dolog(LOG_WARNING, "/proc/net/if_inet6 has a broken line, ignoring");
continue;
}
#else /* !ECMH_GETIFADDR */
/* FreeBSD etc style */
if (getifaddrs(&ifap) == 0)
{
for (ifa = ifap; ifa; ifa = ifa->ifa_next)
{
if (!ifa->ifa_addr)
{
if (g_conf->verbose) dolog(LOG_WARNING, "Interface %s didn't have an address!? -> skipping\n", ifa->ifa_name);
continue;
}
/*
* Ignore:
* - loopbacks
* - devices that are not up
* - devices that are not running
* - AF_LINK + AF_PACKET
*/
if ( ((ifa->ifa_flags & IFF_LOOPBACK) == IFF_LOOPBACK) ||
((ifa->ifa_flags & IFF_UP) != IFF_UP) ||
((ifa->ifa_flags & IFF_RUNNING) != IFF_RUNNING)
#ifdef AF_LINK
|| ifa->ifa_addr->sa_family == AF_LINK
#endif
#ifdef AF_PACKET
|| ifa->ifa_addr->sa_family == AF_PACKET
#endif
)
{
ignore = true;
}
else
{
ignore = false;
}
dolog(LOG_DEBUG, "%s %u (%s) [%s%s%s%s ] (%u) -> %s...\n",
ifa->ifa_name,
ifa->ifa_addr->sa_family,
ifa->ifa_addr->sa_family == AF_INET ? "IPv4" :
(ifa->ifa_addr->sa_family == AF_INET6 ? "IPv6" :
#ifdef AF_LINK
(ifa->ifa_addr->sa_family == AF_LINK ? "LINK" :
#endif
#ifdef AF_PACKET
(ifa->ifa_addr->sa_family == AF_PACKET ? "PACKET" :
#endif
"???")
#ifdef AF_LINK
)
#endif
#ifdef AF_PACKET
)
#endif
,
(ifa->ifa_flags & IFF_UP) == IFF_UP ? " Up": "",
(ifa->ifa_flags & IFF_RUNNING) == IFF_RUNNING ? " Running" : "",
(ifa->ifa_flags & IFF_LOOPBACK) == IFF_LOOPBACK ? " Loopback" : "",
(ifa->ifa_flags & IFF_POINTOPOINT) == IFF_POINTOPOINT ? " PtP" : "",
ifa->ifa_flags, ignore ? "ignoring" : "trying"
);
if (ignore)
{
continue;
}
ifindex = if_nametoindex(ifa->ifa_name);
if (ifa->ifa_addr->sa_family == AF_INET6)
{
struct sockaddr_in6 s;
memcpy(&s, (void *)ifa->ifa_addr, sizeof(s));;
memcpy(&addr, &s.sin6_addr, sizeof(addr));
}
else
{
struct sockaddr_in s;
memcpy(&s, (void *)ifa->ifa_addr, sizeof(s));;
memcpy(&addr, &s.sin_addr, sizeof(addr));
}
#endif /* !ECMH_GETIFADDR */
/* Skip everything we don't care about */
if (
#ifdef ECMH_GETIFADDR
ifa->ifa_addr->sa_family == AF_INET6 && (
#endif
!IN6_IS_ADDR_LINKLOCAL(&addr) &&
(
IN6_IS_ADDR_UNSPECIFIED(&addr) ||
IN6_IS_ADDR_LOOPBACK(&addr) ||
IN6_IS_ADDR_MULTICAST(&addr))
)
#ifdef ECMH_GETIFADDR
)
#endif /* !ECMH_GETIFADDR */
{
#if 0
char txt[INET6_ADDRSTRLEN];
memzero(txt, sizeof(txt));
inet_ntop(AF_INET6, &addr, txt, sizeof(txt));
dolog(LOG_DEBUG, "Ignoring other IPv6 address %s on interface %s\n", txt,
#ifndef ECMH_GETIFADDR
devname
#else
ifa->ifa_name
#endif /* !ECMH_GETIFADDR */
);
#endif /* if 0 */
continue;
}
if (specific)
{
intn = specific;
if (intn->ifindex == ifindex)
{
continue;
}
}
else
{
newintn = gotlinkl = gotglobal = gotipv4 = false;
intn = int_find(ifindex);
/* Not Found? -> Create the interface */
if ( !intn &&
#ifndef ECMH_BPF
(intn = int_create(ifindex)))
#else
(intn = int_create(ifindex,
(IFF_POINTOPOINT == (ifa->ifa_flags & IFF_POINTOPOINT)) ? true : false)))
#endif
{
newintn = true;
}
}
/* Did the find or creation succeed ? */
if (intn)
{
/* Link Local IPv6 address ? */
if (
#ifdef ECMH_GETIFADDR
ifa->ifa_addr->sa_family == AF_INET6 &&
#endif
IN6_IS_ADDR_LINKLOCAL(&addr))
{
/* Update the linklocal address */
memcpy(&intn->linklocal, &addr, sizeof(intn->linklocal));
gotlinkl = true;
}
else
{
#ifdef ECMH_GETIFADDR
if (ifa->ifa_addr->sa_family == AF_INET)
{
#ifdef ECMH_BPF
int num=0;
struct in_addr any;
#ifdef DEBUG
char txt[INET6_ADDRSTRLEN];
memzero(txt, sizeof(txt));
inet_ntop(AF_INET, &addr, txt, sizeof(txt));
#endif
/* Any is empty */
memzero(&any, sizeof(any));
/* Update the Local IPv4 address */
#ifdef DEBUG
dolog(LOG_DEBUG, "Updating local IPv4 address for %s: %s\n", intn->name, txt);
#else
dolog(LOG_DEBUG, "Updating local IPv4 address for %s\n", intn->name);
#endif
for (num = 0; num < INTNODE_MAXIPV4; num++)
{
/* Empty spot ? */
if (memcmp(&intn->ipv4_local[num], &any, sizeof(any)) == 0)
{
memcpy(&intn->ipv4_local[num], &addr, sizeof(intn->ipv4_local));
gotipv4 = true;
break;
}
/* Already on the interface ? */
if (memcmp(&intn->ipv4_local[num], &addr, sizeof(addr)) == 0)
{
break;
}
/* Only allow one IPv4 address on PtP links */
if ((ifa->ifa_flags & IFF_POINTOPOINT) == IFF_POINTOPOINT) break;
}
if ( gotipv4 &&
(ifa->ifa_flags & IFF_POINTOPOINT) != IFF_POINTOPOINT)
{
/* Update the locals list */
local_update(intn);
}
#else
dolog(LOG_DEBUG, "Ignoring local IPv4 address for %s\n", intn->name);
#endif /* ECMH_BPF*/
}
else if (ifa->ifa_addr->sa_family == AF_INET6)
{
#endif /* ECMH_GETIFADDR */
char txt[INET6_ADDRSTRLEN];
memzero(txt, sizeof(txt));
inet_ntop(AF_INET6, &addr, txt, sizeof(txt));
/* Update the global address */
dolog(LOG_DEBUG, "Updating global IPv6 address for %s: %s\n", intn->name, txt);
memcpy(&intn->global, &addr, sizeof(intn->global));
gotglobal = true;
#ifdef ECMH_GETIFADDR
}
else
{
dolog(LOG_ERR, "Unknown Address Family %u - Ignoring\n", ifa->ifa_addr->sa_family);
}
#endif
}
}
if (specific)
{
/* Are we done updating? */
if (gotlinkl && gotglobal) break;
}
else
{
/* Add it to the list if it is a new one and */
/* either the linklocal or global addresses are set. */
if (newintn)
{
if (gotlinkl || gotglobal || gotipv4)
{
dolog(LOG_DEBUG, "Added %s, link %" PRIu64 ", hw %s/%u with an MTU of %" PRIu64 "\n",
intn->name, intn->ifindex,
#ifndef ECMH_BPF
(intn->hwaddr.sa_family == ARPHRD_ETHER ? "Ethernet" :
(intn->hwaddr.sa_family == ARPHRD_SIT ? "sit" : "Unknown")),
intn->hwaddr.sa_family,
#else
(intn->dlt == DLT_NULL ? "Null":
(intn->dlt == DLT_EN10MB ? "Ethernet" : "Unknown")),
(unsigned int)intn->dlt,
#endif
intn->mtu);
}
else
{
dolog(LOG_DEBUG, "[%-5s] Didn't get a linklocal or global address, ignoring this address on interface %" PRIu64 "\n", intn->name, intn->ifindex);
int_destroy(intn);
}
}
}
#ifdef ECMH_GETIFADDR
}
freeifaddrs(ifap);
#endif
}
dolog(LOG_DEBUG, "Updating Interfaces - done, highest ifindex: %" PRIu64 "\n", g_conf->maxinterfaces);
#ifndef ECMH_GETIFADDR
fclose(file);
#else
#endif
}
/* Send a packet */
static void sendpacket6(struct intnode *intn, const struct ip6_hdr *iph, const uint16_t len);
static void sendpacket6(struct intnode *intn, const struct ip6_hdr *iph, const uint16_t len)
{
int sent;
#ifndef ECMH_BPF
struct sockaddr_ll sa;
memzero(&sa, sizeof(sa));
sa.sll_family = AF_PACKET;
sa.sll_protocol = htons(ETH_P_IPV6);
sa.sll_ifindex = intn->ifindex;
sa.sll_hatype = intn->hwaddr.sa_family;
sa.sll_pkttype = 0;
sa.sll_halen = 6;
/*
* Construct a Ethernet MAC address from the IPv6 destination multicast address.
* Per RFC2464
*/
sa.sll_addr[0] = 0x33;
sa.sll_addr[1] = 0x33;
sa.sll_addr[2] = iph->ip6_dst.s6_addr[12];
sa.sll_addr[3] = iph->ip6_dst.s6_addr[13];
sa.sll_addr[4] = iph->ip6_dst.s6_addr[14];
sa.sll_addr[5] = iph->ip6_dst.s6_addr[15];
/* Send the packet */
errno = 0;
sent = sendto(g_conf->rawsocket, iph, len, 0, (struct sockaddr *)&sa, sizeof(sa));
#else /* !ECMH_BPF */
register uint32_t chksum = 0;
struct ether_header hdr_eth;
struct ip hdr_ip;
struct iovec vector[3];
/* There is always ethernet to send out */
vector[0].iov_base = &hdr_eth;
vector[0].iov_len = sizeof(hdr_eth);
/*
* Construct a Ethernet MAC address from the IPv6 destination multicast address.
* Per RFC2464
*/
memzero(&hdr_eth, sizeof(hdr_eth));
hdr_eth.ether_dhost[0] = 0x33;
hdr_eth.ether_dhost[1] = 0x33;
hdr_eth.ether_dhost[2] = iph->ip6_dst.s6_addr[12];
hdr_eth.ether_dhost[3] = iph->ip6_dst.s6_addr[13];
hdr_eth.ether_dhost[4] = iph->ip6_dst.s6_addr[14];
hdr_eth.ether_dhost[5] = iph->ip6_dst.s6_addr[15];
/*
* Handle non-tunneledmode & native ethernet
*/
if (!g_conf->tunnelmode || !intn->master)
{
/* Send a Native IPv6 packet */
hdr_eth.ether_type = htons(ETH_P_IPV6);
vector[1].iov_base = (void *)iph;
vector[1].iov_len = len;
dolog(LOG_DEBUG, "Sending Native IPv6 packet over %s/%" PRIu64 "\n", intn->name, intn->ifindex);
sent = writev(intn->socket, vector, 2);
}
/*
* When this interface is a tunnel, send it over it's parent socket
* After having it encapsulated in proto-41
*/
else
{
/* Construct the proto-41 packet */
memzero(&hdr_ip, sizeof(hdr_ip));
hdr_ip.ip_v = 4;
hdr_ip.ip_hl = 5;
hdr_ip.ip_tos = 0;
hdr_ip.ip_len = htons(len + sizeof(hdr_ip));
hdr_ip.ip_id = htons(42);
hdr_ip.ip_off = 0;
hdr_ip.ip_ttl = 100;
hdr_ip.ip_p = IPPROTO_IPV6;
hdr_ip.ip_sum = 0;
/* The first ipv4_local is the interface, the rest should be empty for PtP interfaces */
memcpy(&hdr_ip.ip_src, &intn->ipv4_local[0], sizeof(hdr_ip.ip_src));
memcpy(&hdr_ip.ip_dst, &intn->ipv4_remote, sizeof(hdr_ip.ip_dst));
/* Calculate the checksum */
chksum = inchksum(&hdr_ip, sizeof(hdr_ip));
/* Wrap in the carries to reduce chksum to 16 bits. */
chksum = (chksum >> 16) + (chksum & 0xffff);
chksum += (chksum >> 16);
/* Take ones-complement and replace 0 with 0xFFFF. */
chksum = (uint16_t) ~chksum;
if (chksum == 0UL) chksum = 0xffffUL;
/* Fill in the Checksum */
hdr_ip.ip_sum = (uint16_t)chksum;
/* Send a IPv4 proto-41 packet over the master's socket */
hdr_eth.ether_type = htons(ETH_P_IP);
vector[1].iov_base = &hdr_ip;
vector[1].iov_len = sizeof(hdr_ip);
vector[2].iov_base = (void *)iph;
vector[2].iov_len = len;
dolog(LOG_DEBUG, "Sending proto-41 IPv6 packet for %s/%" PRIu64 " over %s/%" PRIu64 "\n",
intn->name, intn->ifindex, intn->master->name, intn->master->ifindex);
sent = writev(intn->master->socket, vector, 3);
}
#endif /* !ECMH_BPF */
if (sent < 0)
{
/*
* Remove the device if it doesn't exist anymore,
* can happen with dynamic tunnels etc
*/
if (errno == ENXIO)
{
dolog(LOG_DEBUG, "[%-5s] couldn't send %u bytes, received ENXIO, destroying interface %" PRIu64 "\n", intn->name, len, intn->ifindex);
/* Destroy the interface itself */
int_destroy(intn);
}
else
{
dolog(LOG_DEBUG, "[%-5s] sending %u bytes failed, mtu = %" PRIu64 ": %s (%d)\n", intn->name, len, intn->mtu, strerror(errno), errno);
}
return;
}
/* Update the global statistics */
g_conf->stat_packets_sent++;
g_conf->stat_bytes_sent+=len;
/* Update interface statistics */
intn->stat_bytes_sent+=len;
intn->stat_packets_sent++;
return;
}
/*
* This is used for the ICMPv6 reply code, to allow sending Hoplimit's :)
* Thus allowing neat tricks like traceroute6's to work.
*/
static void icmp6_send(struct intnode *intn, const struct in6_addr *src, int type, int code, void *data, unsigned int dlen);
static void icmp6_send(struct intnode *intn, const struct in6_addr *src, int type, int code, void *data, unsigned int dlen)
{
struct icmp6_hoplimit_packet
{
struct ip6_hdr ip6;
struct icmp6_hdr icmp6;
char data[1500];
} packet;
memzero(&packet, sizeof(packet));
/* Create the IPv6 packet */
packet.ip6.ip6_vfc = 0x60;
packet.ip6.ip6_plen = ntohs(sizeof(packet) -
(sizeof(packet.data) - dlen) -
sizeof(packet.icmp6.icmp6_data32) -
sizeof(packet.ip6));
packet.ip6.ip6_nxt = IPPROTO_ICMPV6;
/* Hoplimit of 64 seems to be a semi default */
packet.ip6.ip6_hlim = 64;
/*
* The source address must be a global unicast IPv6 address
* and should be associated to the interface we are sending on
*/
memcpy(&packet.ip6.ip6_src, &intn->global, sizeof(packet.ip6.ip6_src));
/* Target == Sender */
memcpy(&packet.ip6.ip6_dst, src, sizeof(*src));
/* ICMPv6 Error Report */
packet.icmp6.icmp6_type = type;
packet.icmp6.icmp6_code = code;
/* Add the data, we start at the data in the icmp6 packet */
memcpy(&packet.icmp6.icmp6_data32, data, (sizeof(packet.data) > dlen ? dlen : sizeof(packet.data)));
/* Calculate and fill in the checksum */
packet.icmp6.icmp6_cksum = ipv6_checksum(&packet.ip6, IPPROTO_ICMPV6, &packet.icmp6, sizeof(packet.icmp6) + dlen - sizeof(packet.icmp6.icmp6_data32));
dolog(LOG_DEBUG, "Sending ICMPv6 Type %s (%u) code %s (%u) on %s/%" PRIu64 "\n", icmpv6_type(type), type, icmpv6_code(type, code), code, intn->name, intn->ifindex);
sendpacket6(intn, (const struct ip6_hdr *)&packet, sizeof(packet) - (sizeof(packet.data) - dlen) - sizeof(packet.icmp6.icmp6_data32));
/* Increase ICMP sent statistics */
g_conf->stat_icmp_sent++;
intn->stat_icmp_sent++;
}
/*
* MLDv1 and MLDv2 are backward compatible when doing Queries
* aka a router implementing MLDv2 can send the same query
* and both MLDv1 and MLDv2 hosts will understand it.
* MLDv2 hosts will return a MLDv2 report, MLDv1 hosts a MLDv1 report
* ecmh will always send MLDv2 queries even though we might have
* seen MLDv1's coming in. Except when in MLDv1Only Mode.
*
* src specifies the Source IPv6 address, may be NULL to replace it with any
*/
#ifdef ECMH_SUPPORT_MLD2
static void mld_send_query(struct intnode *intn, const struct in6_addr *mca);
static void mld_send_query(struct intnode *intn, const struct in6_addr *mca)
#else
static void mld_send_query(struct intnode *intn, const struct in6_addr *mca);
static void mld_send_query(struct intnode *intn, const struct in6_addr *mca)
#endif
{
struct mld_query_packet
{
struct ip6_hdr ip6;
struct ip6_hbh hbh;
struct
{
uint8_t type;
uint8_t length;
uint16_t value;
uint8_t optpad[2];
} routeralert;
#ifdef ECMH_SUPPORT_MLD2
struct mld2_query mldq;
struct in6_addr src;
#else
struct mld1 mldq;
#endif
} packet;
unsigned int packetlen;
/* Don't send queries to upstreams */
if (intn->upstream) return;
memzero(&packet, sizeof(packet));
/* Create the IPv6 packet */
packet.ip6.ip6_vfc = 0x60;
packet.ip6.ip6_nxt = IPPROTO_HOPOPTS;
packet.ip6.ip6_hlim = 1;
/*
* The source address must be the link-local address
* of the interface we are sending on
*/
memcpy(&packet.ip6.ip6_src, &intn->linklocal, sizeof(packet.ip6.ip6_src));
/* Generaly Query -> link-scope all-nodes (fc00:e968:6179::de52:7100) */
packet.ip6.ip6_dst.s6_addr[0] = 0xff;
packet.ip6.ip6_dst.s6_addr[1] = 0x02;
packet.ip6.ip6_dst.s6_addr[15] = 0x01;
/* HopByHop Header Extension */
packet.hbh.ip6h_nxt = IPPROTO_ICMPV6;
packet.hbh.ip6h_len = 0;
/* Router Alert Option */
packet.routeralert.type = 5;
packet.routeralert.length = sizeof(packet.routeralert.value);
packet.routeralert.value = 0; /* MLD ;) */
/* Option Padding */
packet.routeralert.optpad[0] = IP6OPT_PADN;
packet.routeralert.optpad[1] = 0;
/* ICMPv6 MLD Query */
packet.mldq.type = ICMP6_MEMBERSHIP_QUERY;
packet.mldq.mrc = htons(2000);
/*
* The address to query, can be in6addr_any to
* query for everything or a specific group
*/
memcpy(&packet.mldq.mca, mca, sizeof(*mca));
#ifndef ECMH_SUPPORT_MLD2
packetlen = sizeof(packet);
#else
if (g_conf->mld1only)
{
packetlen = sizeof(packet)-sizeof(packet.src)-sizeof(struct mld2_query)+sizeof(struct mld1);
}
else
{
/* No sources given */
packetlen = sizeof(packet) - sizeof(packet.src);
packet.mldq.nsrcs = htons(0);
packet.mldq.suppress = 0;
packet.mldq.qrv = ECMH_ROBUSTNESS_FACTOR;
packet.mldq.qqic = ECMH_SUBSCRIPTION_TIMEOUT;
}
#endif
/* Calculate and fill in the checksum */
packet.ip6.ip6_plen = htons(packetlen - sizeof(packet.ip6));
packet.mldq.csum = ipv6_checksum(&packet.ip6, IPPROTO_ICMPV6, &packet.mldq, packetlen - sizeof(packet.ip6) - sizeof(packet.hbh) - sizeof(packet.routeralert));
#ifdef ECMH_SUPPORT_MLD2
if (g_conf->mld1only)
{
#endif
dolog(LOG_DEBUG, "Sending MLDv1 Query on %s/%" PRIu64 "\n", intn->name, intn->ifindex);
#ifdef ECMH_SUPPORT_MLD2
}
else
{
dolog(LOG_DEBUG, "Sending MLDv2 Query on %s/%" PRIu64 " with %u sources\n", intn->name, intn->ifindex, ntohs(packet.mldq.nsrcs));
}
#endif
sendpacket6(intn, (const struct ip6_hdr *)&packet, packetlen);
/* Increase ICMP sent statistics */
g_conf->stat_icmp_sent++;
intn->stat_icmp_sent++;
}
static void mld1_send_report(struct intnode *intn, const struct in6_addr *mca);
static void mld1_send_report(struct intnode *intn, const struct in6_addr *mca)
{
struct mld_report_packet
{
struct ip6_hdr ip6;
struct ip6_hbh hbh;
struct
{
uint8_t type;
uint8_t length;
uint16_t value;
uint8_t optpad[2];
} routeralert;
struct mld1 mld1;
} packet;
memzero(&packet, sizeof(packet));
/* Create the IPv6 packet */
packet.ip6.ip6_vfc = 0x60;
packet.ip6.ip6_plen = ntohs(sizeof(packet) - sizeof(packet.ip6));
packet.ip6.ip6_nxt = IPPROTO_HOPOPTS;
packet.ip6.ip6_hlim = 1;
/*
* The source address must be the link-local address
* of the interface we are sending on
*/
memcpy(&packet.ip6.ip6_src, &intn->linklocal, sizeof(packet.ip6.ip6_src));
/* Report -> Multicast address */
memcpy(&packet.ip6.ip6_dst, mca, sizeof(*mca));
/* HopByHop Header Extension */
packet.hbh.ip6h_nxt = IPPROTO_ICMPV6;
packet.hbh.ip6h_len = 0;
/* Router Alert Option */
packet.routeralert.type = 5;
packet.routeralert.length = sizeof(packet.routeralert.value);
packet.routeralert.value = 0; /* MLD ;) */
/* Option Padding */
packet.routeralert.optpad[0] = IP6OPT_PADN;
packet.routeralert.optpad[1] = 0;
/* ICMPv6 MLD Report */
packet.mld1.type = ICMP6_MEMBERSHIP_REPORT;
packet.mld1.mrc = 0;
memcpy(&packet.mld1.mca, mca, sizeof(*mca));
/* Calculate and fill in the checksum */
packet.mld1.csum = ipv6_checksum(&packet.ip6, IPPROTO_ICMPV6, &packet.mld1, sizeof(packet.mld1));
dolog(LOG_DEBUG, "Sending MLDv1 Report on %s/%" PRIu64 "\n", intn->name, intn->ifindex);
sendpacket6(intn, (const struct ip6_hdr *)&packet, sizeof(packet));
/* Increase ICMP sent statistics */
g_conf->stat_icmp_sent++;
intn->stat_icmp_sent++;
}
#ifdef ECMH_SUPPORT_MLD2
static void mld2_send_report(struct intnode *intn, const struct in6_addr *mca);
static void mld2_send_report(struct intnode *intn, const struct in6_addr *mca)
{
struct groupnode *groupn;
struct grpintnode *grpintn;
struct subscrnode *subscrn;
struct listnode *ln, *gn, *sn;
unsigned int length, i;
struct mld_report_packet
{
struct ip6_hdr ip6;
struct ip6_hbh hbh;
struct
{
uint8_t type;
uint8_t length;
uint16_t value;
uint8_t optpad[2];
} routeralert;
struct mld2_report mld2r;
} *packet;
struct mld2_grec *grec = NULL;
void *src = NULL;
bool any = false;
if (intn->mtu < sizeof(*packet))
{
/*
* MTU is too small to support this type of packet
* Should not happen though
*/
dolog(LOG_WARNING, "MTU too small for packet while sending MLDv2 report on interface %s/%" PRIu64 " mtu=%" PRIu64 "!?\n", intn->name, intn->ifindex, intn->mtu);
return;
}
/* Allocate a buffer matching the MTU size of this interface */
packet = (struct mld_report_packet *)calloc(1, intn->mtu);
if (!packet)
{
dolog(LOG_ERR, "Couldn't allocate memory for MLD2 Report packet, aborting\n");
exit(-1);
}
/* Create the IPv6 packet */
packet->ip6.ip6_vfc = 0x60;
packet->ip6.ip6_plen = ntohs(sizeof(*packet) - sizeof(packet->ip6));
packet->ip6.ip6_nxt = IPPROTO_HOPOPTS;
packet->ip6.ip6_hlim = 1;
/*
* The source address must be the link-local address
* of the interface we are sending on
*/
memcpy(&packet->ip6.ip6_src, &intn->linklocal, sizeof(packet->ip6.ip6_src));
/* MLDv2 Report -> All IPv6 Multicast Routers (fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5b) */
packet->ip6.ip6_dst.s6_addr[0] = 0xff;
packet->ip6.ip6_dst.s6_addr[1] = 0x02;
packet->ip6.ip6_dst.s6_addr[15] = 0x16;
/* HopByHop Header Extension */
packet->hbh.ip6h_nxt = IPPROTO_ICMPV6;
packet->hbh.ip6h_len = 0;
/* Router Alert Option */
packet->routeralert.type = 5;
packet->routeralert.length = sizeof(packet->routeralert.value);
packet->routeralert.value = 0; /* MLD ;) */
/* Option Padding */
packet->routeralert.optpad[0] = IP6OPT_PADN;
packet->routeralert.optpad[1] = 0;
/* ICMPv6 MLD Report */
packet->mld2r.type = ICMP6_V2_MEMBERSHIP_REPORT;
packet->mld2r.ngrec = 0;
length = 0;
/*
* NOTE, we need to watch the MTU size, as there
* will be more subscriptions + SSM combo's than
* the size of one MTU can fit, thus we split it when needed.
*/
/* Loop through all the registered groups */
LIST_LOOP(g_conf->groups, groupn, ln)
{
/*
* If we only need to send for this MCA
* don't count anything else
*/
if ( (mca && !IN6_ARE_ADDR_EQUAL(mca, &groupn->mca)) ||
groupn->interfaces->count == 0)
{
continue;
}
/* No sources yet for this grec */
src = NULL;
/* Loop through the interested interfaces */
LIST_LOOP(groupn->interfaces, grpintn, gn)
{
/* Skip the sending interface */
if (grpintn->ifindex == intn->ifindex)
{
continue;
}
/* Go through the subscriptions */
LIST_LOOP(grpintn->subscriptions, subscrn, sn)
{
/* Exclusion record? -> Skip it, thus excluding it */
if (subscrn->mode == MLD2_MODE_IS_EXCLUDE)
{
continue;
}
/* Any sources already? */
if (src)
{
/* No grec? */
if (!grec)
{
dolog(LOG_WARNING, "No grec but we do have a source!\n");
continue;
}
/* Unspecified address but already have sources to include? */
if (IN6_IS_ADDR_UNSPECIFIED(&subscrn->ipv6))
{
/* Remove former sources */
grec->grec_nsrcs = 0;
/* Jump to exclude mode with 0 sources -> Anything */
grec->grec_type = MLD2_MODE_IS_EXCLUDE;
/* No sources yet in this grec */
src = NULL;
any = true;
}
/* Don't add sources twice (seperate interfaces might want the same S<->G) */
for (i=0; !any && src && (i < grec->grec_nsrcs); i++)
{
src = ((char *)grec) + sizeof(*grec) + (sizeof(struct in6_addr) * grec->grec_nsrcs);
/* Skip it if it already exists */
if (memcmp(&subscrn->ipv6, src, sizeof(subscrn->ipv6)) == 0)
{
dolog(LOG_DEBUG, "Not adding source address as we have ANY already added\n");
src = NULL;
break;
}
}
/* Skip it */
if (!src)
{
continue;
}
}
/* Packet with at least one grec and one or more src's, excluding ip6 header */
if (grec)
{
length = (((char *)grec) - ((char *)packet) + sizeof(*grec) + (sizeof(struct in6_addr) * (grec->grec_nsrcs)) - sizeof(packet->ip6));
}
/* Empty packet, no grec+src's */
else
{
length = sizeof(*packet);
}
/* Would adding it not fit? -> Send it out */
if ((length + sizeof(packet->ip6) + (grec ? 0 : sizeof(*grec)) +
(any || IN6_IS_ADDR_UNSPECIFIED(&subscrn->ipv6) ? 0 : sizeof(struct in6_addr))) > intn->mtu)
{
if (!grec)
{
/* Should not happen! Would mean the MTU is smaller than a standard mld report */
dolog(LOG_WARNING, "No grec and MTU too small for packet while sending MLDv2 report on interface %s/%" PRIu64 " mtu=%" PRIu64 "!?\n", intn->name, intn->ifindex, intn->mtu);
free(packet);
return;
}
/* Take care of endianess */
packet->mld2r.ngrec = htons(packet->mld2r.ngrec);
grec->grec_nsrcs = htons(grec->grec_nsrcs);
/* Calculate and fill in the checksum */
packet->ip6.ip6_plen = htons(length);
packet->mld2r.csum = htons(0);
packet->mld2r.csum = ipv6_checksum(&packet->ip6, IPPROTO_ICMPV6, &packet->mld2r, length-sizeof(struct ip6_hbh)-sizeof(packet->routeralert));
dolog(LOG_DEBUG, "Sending2 MLDv2 Report on %s/%" PRIu64 ", ngrec=%u, length=%u sources=%u (in last grec)\n", intn->name, intn->ifindex, ntohs(packet->mld2r.ngrec), length, ntohs(grec->grec_nsrcs));
sendpacket6(intn, (const struct ip6_hdr *)packet, length + sizeof(packet->ip6));
/* Increase ICMP sent statistics */
g_conf->stat_icmp_sent++;
intn->stat_icmp_sent++;
/* Reset the MLDv2 struct */
packet->mld2r.ngrec = 0;
grec = NULL;
src = NULL;
}
/* First source to be added to this grec? */
if (!src)
{
/* A new grec */
packet->mld2r.ngrec++;
/* Already a grec in the packet? */
if (grec)
{
/* Fixup endianness */
grec->grec_nsrcs = htons(grec->grec_nsrcs);
/* Next grec */
grec = (struct mld2_grec *)(((uint8_t *)grec) + sizeof(*grec) + (sizeof(struct in6_addr) * grec->grec_nsrcs));
}
else
{
/* First grec */
grec = (struct mld2_grec *)(((uint8_t *)packet) + sizeof(*packet));
}
/* The Multicast address */
memcpy(&grec->grec_mca, &groupn->mca, sizeof(grec->grec_mca));
/* Zero sources upto now */
grec->grec_nsrcs = 0;
/* 0 Sources -> Exclude those */
grec->grec_type = MLD2_MODE_IS_EXCLUDE;
/* Nothing added yet */
any = false;
}
/* Only add non-:: addresses */
if (!IN6_IS_ADDR_UNSPECIFIED(&subscrn->ipv6))
{
/* First/Next address */
src = (struct in6_addr *)(((char *)grec) + sizeof(*grec) + (sizeof(struct in6_addr) * grec->grec_nsrcs));
/* An additional source */
grec->grec_nsrcs++;
/* State becomes include */
grec->grec_type = MLD2_MODE_IS_INCLUDE;
/* Append the source address */
memcpy(src, &subscrn->ipv6, sizeof(struct in6_addr));
}
else
{
/* We added a 'any' address, thus don't add anything else */
any = true;
}
}
}
}
/* Any groups left to send? */
if (packet->mld2r.ngrec == 0)
{
free(packet);
packet = NULL;
return;
}
length = (((char *)grec) - ((char *)packet) + sizeof(*grec) + (sizeof(struct in6_addr) * (grec->grec_nsrcs)) - sizeof(packet->ip6));
/* Take care of endianess */
packet->mld2r.ngrec = htons(packet->mld2r.ngrec);
grec->grec_nsrcs = htons(grec->grec_nsrcs);
/* Calculate and fill in the checksum */
packet->ip6.ip6_plen = htons(length);
packet->mld2r.csum = htons(0);
packet->mld2r.csum = ipv6_checksum(&packet->ip6, IPPROTO_ICMPV6, &packet->mld2r, length-sizeof(struct ip6_hbh)-sizeof(packet->routeralert));
dolog(LOG_DEBUG, "Sending2 MLDv2 Report on %s/%" PRIu64 ", ngrec=%u, length=%u sources=%u (in last grec)\n", intn->name, intn->ifindex, ntohs(packet->mld2r.ngrec), length, ntohs(grec->grec_nsrcs));
sendpacket6(intn, (const struct ip6_hdr *)packet, length + sizeof(packet->ip6));
/* Increase ICMP sent statistics */
g_conf->stat_icmp_sent++;
intn->stat_icmp_sent++;
free(packet);
}
#endif /* ECMH_SUPPORT_MLD2 */
static void mld_send_report(struct intnode *intn, const struct in6_addr *mca);
static void mld_send_report(struct intnode *intn, const struct in6_addr *mca)
{
/*
* When we haven't detected a querier on a link
* send reports as both MLDv1 and MLDv2, as
* listeners (hosts) might be interrested.
*
* Don't send packets to upstream interfaces when it is unknown what version they do
*/
#ifdef ECMH_SUPPORT_MLD2
if (!g_conf->mld2only && (g_conf->mld1only || (intn->mld_version == 0 && !intn->upstream) || intn->mld_version == 1))
#else
if ((intn->mld_version == 0 && !intn->upstream) || intn->mld_version == 1)
#endif
{
mld1_send_report(intn, mca);
}
#ifdef ECMH_SUPPORT_MLD2
if (!g_conf->mld1only && (g_conf->mld2only || intn->mld_version == 0 || intn->mld_version == 2))
{
mld2_send_report(intn, mca);
}
#endif /* EMCH_SUPPORT_MLD2 */
}
static void mld_send_report_all(struct intnode *interface, const struct in6_addr *mca);
static void mld_send_report_all(struct intnode *interface, const struct in6_addr *mca)
{
unsigned int i;
struct intnode *intn;
dolog(LOG_DEBUG, "Broadcasting group to all interfaces but %s...\n", interface->name);
/* Broadcast that we want this new group */
for (i = 0; i < g_conf->maxinterfaces; i++)
{
intn = &g_conf->ints[i];
/*
* - Skip unconfigured interfaces
* - Skip the interface it came from
*/
if ( intn->mtu == 0 ||
interface->ifindex == intn->ifindex) continue;
/* Send the MLD Report */
mld_send_report(intn, mca);
}
dolog(LOG_DEBUG, "Broadcasting group to all interfaces but %s... - done\n", interface->name);
}
#ifdef ECMH_SUPPORT_IPV4
/* IPv4 ICMP */
static void l4_ipv4_icmp(struct intnode *intn, struct ip *iph, const void *packet, const uint16_t len);
static void l4_ipv4_icmp(struct intnode *intn, struct ip *iph, const void *packet, const uint16_t len)
{
D(dolog(LOG_DEBUG, "%5s L4:IPv4 ICMP\n", intn->name);)
return;
}
#endif /* ECMH_SUPPORT_IPV4 */
#ifdef ECMH_BPF
/*
* Protocol 41 - IPv6 in IPv4 (RFC3065)
*
* We decapsulate these packets and then feed them to ecmh again
* This way we don't have to a BPF/PCAP on all the tunnel interfaces
*
*/
static void l4_ipv4_proto41(struct intnode *intn, struct ip *iph, const void *packet, const uint16_t len);
static void l4_ipv4_proto41(struct intnode *intn, struct ip *iph, const void *packet, const uint16_t len)
{
struct localnode *localn;
struct intnode *tun;
/* Ignore when we are not in tunnelmode */
if (!g_conf->tunnelmode)
{
return;
}
/* Is this a locally sourced packet? */
localn = local_find(&iph->ip_src);
/* Ignore when local */
if (localn)
{
#if 0
dolog(LOG_DEBUG, "Dropping packet originating from ourselves on %s\n", intn->name);
#endif
return;
}
/* Find the matching interface which is actually sending this */
tun = int_find_ipv4(false, &iph->ip_src);
if (!tun)
{
/* Try to update the list */
update_interfaces(NULL);
/* Try to find it again */
tun = int_find_ipv4(false, &iph->ip_src);
}
if (!tun)
{
if (g_conf->verbose)
{
char buf[1024],buf2[1024];
inet_ntop(AF_INET, &iph->ip_src, (char *)&buf, sizeof(buf));
inet_ntop(AF_INET, &iph->ip_dst, (char *)&buf2, sizeof(buf));
dolog(LOG_ERR, "Couldn't find proto-41 tunnel %s->%s\n", buf, buf2);
}
return;
}
/* Send it through our decoder again, looking as it is a native IPv6 received on intn ;) */
dolog(LOG_DEBUG, "Proto-41 from %08x->%08x on %s, tunnel %s\n", iph->ip_src, iph->ip_dst, intn->name, tun->name);
l2_ethtype(tun, packet, len, ETH_P_IPV6);
return;
}
#endif /* ECMH_BPF */
/* IPv4 */
#if defined(DEBUG) || defined(ECMH_SUPPORT_IPV4)
static void l3_ipv4(struct intnode *intn, struct ip *iph, const uint16_t len);
static void l3_ipv4(struct intnode *intn, struct ip *iph, const uint16_t len)
#else
static void l3_ipv4(struct intnode UNUSED *intn, struct ip *iph, const uint16_t len);
static void l3_ipv4(struct intnode UNUSED *intn, struct ip *iph, const uint16_t len)
#endif
{
if (iph->ip_v != 4)
{
D(dolog(LOG_DEBUG, "%5s L3:IPv4: IP version %u not supported\n", intn->name, iph->ip_v);)
return;
}
if (iph->ip_hl < 5)
{
D(dolog(LOG_DEBUG, "%5s L3IPv4: IP hlen < 5 bytes (%u)\n", intn->name, iph->ip_hl);)
return;
}
if (ntohs(iph->ip_len) > len)
{
/* This happens mostly with unknown ARPHRD_* types */
D(dolog(LOG_DEBUG, "%5s L3:IPv4: *** L3 length > L2 length (%u != %u)\n", intn->name, ntohs(iph->ip_len), len);)
#if 0
return;
#endif
}
#if 0
{
char src[100], dst[100], to4[100];
inet_ntop(AF_INET, &iph->ip_src, src, sizeof(src));
inet_ntop(AF_INET, &iph->ip_dst, dst, sizeof(dst));
inet_ntop(AF_INET, &ipv4_6to4_relay, to4, sizeof(to4));
dolog(LOG_DEBUG, "%5s L3:IPv4: IPv%01u %-16s %-16s %4u (%-16s)\n", intn->name, iph->ip_v, src, dst, ntohs(iph->ip_len), to4);
}
#endif
/* Ignore traffic from/to 6to4 relay address */
if (memcmp(&iph->ip_src, &ipv4_6to4_relay, 4) == 0 ||
memcmp(&iph->ip_dst, &ipv4_6to4_relay, 4) == 0)
{
return;
}
/* Go to Layer 4 */
#ifdef ECMH_SUPPORT_IPV4
if (iph->ip_p == 1)
{
l4_ipv4_icmp(intn, iph, (uint8_t *)iph) + (4 * iph->ip_hl), len - (4 * iph->ip_hl));
}
#ifdef ECMH_BPF
else
#endif /* ECMH_BPF */
#endif /* ECMH_SUPPORT_IPV4 */
#ifdef ECMH_BPF
if (iph->ip_p == IPPROTO_IPV6)
{
l4_ipv4_proto41(intn, iph, ((uint8_t *)iph) + (4 * iph->ip_hl), len - (4 * iph->ip_hl));
}
#endif /* ECMH_BPF */
}
static void mld_log(unsigned int level, const char *msg, const struct in6_addr *i_mca, const struct intnode *intn);
static void mld_log(unsigned int level, const char *msg, const struct in6_addr *i_mca, const struct intnode *intn)
{
char mca[INET6_ADDRSTRLEN];
memzero(mca, sizeof(mca));
inet_ntop(AF_INET6, i_mca, mca, sizeof(mca));
dolog(level, "%s for %s on %s/%" PRIu64 "\n", msg, mca, intn->name, intn->ifindex);
}
static void l4_ipv6_icmpv6_mld1_report(struct intnode *intn, struct mld1 *mld1);
static void l4_ipv6_icmpv6_mld1_report(struct intnode *intn, struct mld1 *mld1)
{
struct grpintnode *grpintn;
struct in6_addr any;
bool isnew;
#ifdef ECMH_SUPPORT_MLDV2
if (g_conf->mld2only)
{
mld_log(LOG_DEBUG, "Ignoring ICMPv6 MLDv1 Report due to MLDv2Only mode", &mld1->mca, intn);
return;
}
#endif
/*
* We have received a MLDv1 report, thus note this
* interface as having a MLDv1 listener
*/
int_set_mld_version(intn, 1);
mld_log(LOG_DEBUG, "Received a ICMPv6 MLDv1 Report", &mld1->mca, intn);
/*
* Ignore groups:
* - non multicast
* - node local multicast addresses
* - link local multicast addresses
* - multicast destination mismatch with ipv6 destination
*/
if ( !IN6_IS_ADDR_MULTICAST(&mld1->mca) ||
IN6_IS_ADDR_MC_NODELOCAL(&mld1->mca) ||
IN6_IS_ADDR_MC_LINKLOCAL(&mld1->mca))
{
return;
}
/* Find the grpintnode or create it */
grpintn = groupint_get(&mld1->mca, intn, &isnew);
if (!grpintn)
{
mld_log(LOG_WARNING, "Couldn't find or create new group", &mld1->mca, intn);
return;
}
/* No source address, so use any */
memzero(&any, sizeof(any));
if (!grpint_refresh(grpintn, &any, MLD2_MODE_IS_INCLUDE))
{
mld_log(LOG_WARNING, "Couldn't create subscription", &mld1->mca, intn);
return;
}
if (isnew)
{
mld_send_report_all(intn, &mld1->mca);
}
return;
}
static void l4_ipv6_icmpv6_mld1_reduction(struct intnode *intn, struct mld1 *mld1);
static void l4_ipv6_icmpv6_mld1_reduction(struct intnode *intn, struct mld1 *mld1)
{
struct groupnode *groupn;
struct grpintnode *grpintn;
struct in6_addr any;
#ifdef ECMH_SUPPORT_MLDV2
if (g_conf->mld2only)
{
mld_log(LOG_DEBUG, "Ignoring ICMPv6 MLDv1 Reduction due to MLDv2Only mode", &mld1->mca, intn);
return;
}
#endif
/*
* We have received a MLDv1 reduction, thus note this
* interface as having a MLDv1 listener
*/
int_set_mld_version(intn, 1);
mld_log(LOG_DEBUG, "Received a ICMPv6 MLDv1 Reduction", &mld1->mca, intn);
/*
* Ignore groups:
* - non multicast
* - node local multicast addresses
* - link local multicast addresses
*/
if ( !IN6_IS_ADDR_MULTICAST(&mld1->mca) ||
IN6_IS_ADDR_MC_NODELOCAL(&mld1->mca) ||
IN6_IS_ADDR_MC_LINKLOCAL(&mld1->mca))
{
return;
}
/* Find the groupnode */
groupn = group_find(&mld1->mca);
if (!groupn)
{
mld_log(LOG_WARNING, "Couldn't find group to reduce", &mld1->mca, intn);
return;
}
/* Find the grpintnode */
grpintn = grpint_find(groupn->interfaces, intn);
if (!grpintn)
{
mld_log(LOG_WARNING, "Couldn't find the grpint to reduce", &mld1->mca, intn);
return;
}
/* No source address, so use any */
memzero(&any, sizeof(any));
if (!subscr_unsub(grpintn->subscriptions, &any))
{
mld_log(LOG_WARNING, "Couldn't unsubscribe", &mld1->mca, intn);
return;
}
if (grpintn->subscriptions->count <= 0)
{
/* Requery if somebody still want it, as it will timeout otherwise. */
mld_log(LOG_DEBUG, "Querying for other listeners", &mld1->mca, intn);
mld_send_query(intn, &mld1->mca);
#ifdef ECMH_SUPPORT_MLD2
/* Skip Robustness */
grpintn->subscriptions->count = -ECMH_ROBUSTNESS_FACTOR;
#endif
}
return;
}
#ifdef ECMH_SUPPORT_MLD2
static void l4_ipv6_icmpv6_mld2_report(struct intnode *intn, struct mld2_report *mld2r, const uint16_t plen);
static void l4_ipv6_icmpv6_mld2_report(struct intnode *intn, struct mld2_report *mld2r, const uint16_t plen)
{
char mca[INET6_ADDRSTRLEN], srct[INET6_ADDRSTRLEN];
struct grpintnode *grpintn = NULL;
struct in6_addr *src, any;
struct mld2_grec *grec = (struct mld2_grec *)(((char *)mld2r)+sizeof(*mld2r));
unsigned int ngrec = ntohs(mld2r->ngrec), nsrcs = 0;
bool isnew = false;
#ifdef ECMH_SUPPORT_MLDV2
if (g_conf->mld1only)
{
dolog(LOG_DEBUG, "Ignoring ICMPv6 MLDv2 Report on %s/%u due to MLDv1Only mode\n", intn->name, intn->ifindex);
return;
}
#endif
/*
* We have received a MLDv2 report, thus note this
* interface as having a MLDv2 listener, unless it
* has detected MLDv1 listeners already...
*/
int_set_mld_version(intn, 2);
dolog(LOG_DEBUG, "Received a ICMPv6 MLDv2 Report (%u) on %s (grec's: %u)\n",
(unsigned int)mld2r->type, intn->name, ngrec);
if ((sizeof(*mld2r) + ngrec*sizeof(*grec)) > plen)
{
dolog(LOG_ERR, "Ignoring packet with invalid number of Group Records (would exceed packetlength)\n");
return;
}
/* Zero out just in case */
memzero(&mca, sizeof(mca));
memzero(&srct, sizeof(srct));
memzero(&any, sizeof(any));
while (ngrec > 0)
{
/* Check if we are still inside the packet */
if (((char *)grec) > (((char *)mld2r)+plen))
{
dolog(LOG_ERR, "Reached outside the packet (ngrec=%u) received on %s, length %u -> ignoring\n",
ngrec, intn->name, plen);
return;
}
grpintn = NULL;
nsrcs = ntohs(grec->grec_nsrcs);
src = (struct in6_addr *)(((char *)grec) + sizeof(*grec));
#ifdef DEBUG
inet_ntop(AF_INET6, &grec->grec_mca, mca, sizeof(mca));
dolog(LOG_DEBUG, "MLDv2 Report (grec=%u) wanting %s %s with %u sources on %s\n",
ngrec, lookup(mld2_grec_types, grec->grec_type),
mca, nsrcs, intn->name);
#endif
if ( grec->grec_type != MLD2_MODE_IS_INCLUDE &&
grec->grec_type != MLD2_MODE_IS_EXCLUDE &&
grec->grec_type != MLD2_CHANGE_TO_INCLUDE &&
grec->grec_type != MLD2_CHANGE_TO_EXCLUDE &&
grec->grec_type != MLD2_ALLOW_NEW_SOURCES &&
grec->grec_type != MLD2_BLOCK_OLD_SOURCES)
{
dolog(LOG_ERR, "Unknown Group Record Type %u/0x%x (ngrec=%u) on %s -> Ignoring Report\n",
grec->grec_type, grec->grec_type, ngrec, intn->name);
return;
}
/* Ignore node and link local multicast addresses */
if ( !IN6_IS_ADDR_MC_NODELOCAL(&grec->grec_mca) &&
!IN6_IS_ADDR_MC_LINKLOCAL(&grec->grec_mca))
{
inet_ntop(AF_INET6, &grec->grec_mca, mca, sizeof(mca));
/* Find the grpintnode or create it */
grpintn = groupint_get(&grec->grec_mca, intn, &isnew);
if (!grpintn)
{
mld_log(LOG_WARNING, "L4:IPv6:ICMPv6:MLD2_Report Couldn't find or create new group", &grec->grec_mca, intn);
}
}
if (nsrcs == 0)
{
if (grpintn)
{
if (!grpint_refresh(grpintn, &any,
grec->grec_type == MLD2_MODE_IS_EXCLUDE ||
grec->grec_type == MLD2_CHANGE_TO_EXCLUDE ||
grec->grec_type == MLD2_BLOCK_OLD_SOURCES ?
MLD2_MODE_IS_INCLUDE : MLD2_MODE_IS_EXCLUDE))
{
mld_log(LOG_WARNING, "Couldn't refresh subscription",
&grec->grec_mca, intn);
return;
}
}
}
else
{
if ((((char *)src) - ((char *)mld2r) + (nsrcs * sizeof(*src))) > plen)
{
dolog(LOG_ERR, "Ignoring packet with invalid number (%u) of sources (would exceed packetlength)\n", nsrcs);
return;
}
/* Do all source addresses */
while (nsrcs > 0)
{
/* Skip if we didn't get a grpint */
if (grpintn)
{
if (!grpint_refresh(grpintn, src,
grec->grec_type == MLD2_MODE_IS_EXCLUDE ||
grec->grec_type == MLD2_CHANGE_TO_EXCLUDE ||
grec->grec_type == MLD2_BLOCK_OLD_SOURCES ?
MLD2_MODE_IS_EXCLUDE : MLD2_MODE_IS_INCLUDE))
{
mld_log(LOG_ERR, "Couldn't subscribe sourced", src, intn);
}
}
/* Next src */
src = (struct in6_addr *)(((char *)src) + sizeof(*src));
nsrcs--;
}
}
if (isnew)
{
mld_send_report_all(intn, &grec->grec_mca);
}
/* Next grec, also skip the auxwords */
grec = (struct mld2_grec *)(((char *)src) + grec->grec_auxwords);
ngrec--;
}
return;
}
#endif /* ECMH_SUPPORT_MLD2 */
static void l4_ipv6_icmpv6_mld_query(struct intnode *intn, const uint16_t plen);
static void l4_ipv6_icmpv6_mld_query(struct intnode *intn, const uint16_t plen)
{
struct groupnode *groupn;
struct listnode *ln;
struct grpintnode *grpintn;
struct listnode *gn;
dolog(LOG_DEBUG, "Received a ICMPv6 MLD Query on %s\n", intn->name);
/* It's MLDv1 when the packet has the size of a MLDv1 packet */
if (plen == sizeof(struct mld1))
{
#ifdef ECMH_SUPPORT_MLDV2
if (g_conf->mld2only)
{
dolog(LOG_DEBUG, "Ignoring ICMPv6 MLDv2 Query on %s/%u due to MLDv2Only mode\n", intn->name, intn->ifindex);
return;
}
#endif
int_set_mld_version(intn, 1);
}
/*
* It is MLDv2 (or up) when it has anything else
* It could be MLDv3 if that ever comes out, but we don't know.
*/
else
{
#ifdef ECMH_SUPPORT_MLDV2
if (g_conf->mld1only)
{
dolog(LOG_DEBUG, "Ignoring ICMPv6 MLDv1 Query on %s/%u due to MLDv1Only mode\n", intn->name, intn->ifindex);
return;
}
#endif
int_set_mld_version(intn, 2);
}
#ifdef ECMH_SUPPORT_MLD2
/*
* If it is a yet unknown MLD send MLDv1's
* Unknown MLD's should not happen though
* as the above code just determined what
* version it is.
*/
if (!g_conf->mld2only && (g_conf->mld1only || intn->mld_version == 0 || intn->mld_version == 1))
{
#endif /* ECMH_SUPPORT_MLD2 */
/* MLDv1 sends reports one group at a time */
/*
* Walk along the list of groups
* and report all the groups we are subscribed for
*/
LIST_LOOP(g_conf->groups, groupn, ln)
{
LIST_LOOP(groupn->interfaces, grpintn, gn)
{
/* We only are sending for this interface */
if (grpintn->ifindex != intn->ifindex)
{
continue;
}
/* Report this group to the querying router */
mld_send_report(intn, &groupn->mca);
}
}
#ifdef ECMH_SUPPORT_MLD2
}
else if (!g_conf->mld1only && (g_conf->mld2only || intn->mld_version == 2))
{
/* Send all the groups to this interface */
mld2_send_report(intn, NULL);
}
else
{
dolog(LOG_DEBUG, "Did not answer query on %s\n", intn->name);
}
#endif /* ECMH_SUPPORT_MLD2 */
return;
}
/*
* Forward a multicast packet to interfaces that have subscriptions for it
*
* intn = The interface we received this packet on
* packet = The packet, starting with IPv6 header
* len = Length of the complete packet
*/
static void l4_ipv6_multicast(struct intnode *intn, struct ip6_hdr *iph, const uint16_t len);
static void l4_ipv6_multicast(struct intnode *intn, struct ip6_hdr *iph, const uint16_t len)
{
struct intnode *interface;
struct groupnode *groupn;
struct grpintnode *grpintn;
struct subscrnode *subscrn;
struct listnode *in, *in2;
/*
* Don't route multicast packets that:
* - src = multicast
* - src = unspecified
* - dst = unspecified
* - src = linklocal
* - dst = node local multicast
* - dst = link local multicast
*/
if ( IN6_IS_ADDR_MULTICAST(&iph->ip6_src) ||
IN6_IS_ADDR_UNSPECIFIED(&iph->ip6_src) ||
IN6_IS_ADDR_UNSPECIFIED(&iph->ip6_dst) ||
IN6_IS_ADDR_LINKLOCAL(&iph->ip6_src) ||
IN6_IS_ADDR_MC_NODELOCAL(&iph->ip6_dst) ||
IN6_IS_ADDR_MC_LINKLOCAL(&iph->ip6_dst))
{
return;
}
#if 0
D(
{
/* DEBUG - Causes a lot of debug output - thus disabled even for debugging */
char src[INET6_ADDRSTRLEN];
char dst[INET6_ADDRSTRLEN];
inet_ntop(AF_INET6, &iph->ip6_src, src, sizeof(src));
inet_ntop(AF_INET6, &iph->ip6_dst, dst, sizeof(dst));
dolog(LOG_DEBUG, "%5s L3:IPv6: IPv%0x %40s %40s %4u %u\n", intn->name, (int)((iph->ip6_vfc>>4)&0x0f), src, dst, ntohs(iph->ip6_plen), iph->ip6_nxt);
}
)
#endif
/* Find the group belonging to this multicast destination */
groupn = group_find(&iph->ip6_dst);
if (!groupn)
{
/* Causes a lot of debug output, be warned */
#if 0
char src[INET6_ADDRSTRLEN];
char dst[INET6_ADDRSTRLEN];
inet_ntop(AF_INET6, &iph->ip6_src, src, sizeof(src));
inet_ntop(AF_INET6, &iph->ip6_dst, dst, sizeof(dst));
dolog(LOG_DEBUG, "No subscriptions for %s (sent by %s)\n", dst, src);
#endif
return;
}
/* Increase the statistics for this group */
groupn->bytes+=len;
groupn->packets++;
LIST_LOOP(groupn->interfaces, grpintn, in)
{
/* Don't send to the interface this packet originated from */
if (intn->ifindex == grpintn->ifindex)
{
continue;
}
/* Check the subscriptions for this group */
LIST_LOOP(grpintn->subscriptions, subscrn, in2)
{
/* Unspecified or specific subscription to this address? */
if ( !IN6_ARE_ADDR_EQUAL(&subscrn->ipv6, &in6addr_any) &&
!IN6_ARE_ADDR_EQUAL(&subscrn->ipv6, &iph->ip6_src))
{
continue;
}
/*
* If it was explicitly requested to include
* packets from this source,
* don't even look further and do so.
* This is the case when an MLDv1 listener
* is on the link too for example.
*/
if (subscrn->mode != MLD2_MODE_IS_INCLUDE)
{
continue;
}
/* Get the interface */
interface = int_find(grpintn->ifindex);
if (!interface)
{
continue;
}
/* Send the packet to this interface */
sendpacket6(interface, iph, len);
/* Packet is forwarded thus proceed to next interface */
break;
}
}
}
/*
* Check the ICMPv6 message for MLD's or ICMP echo requests
*
* intn = The interface we received this packet on
* packet = The packet, starting with IPv6 header
* len = Length of the complete packet
* data = the payload
* plen = Payload length (should match up to at least icmpv6
*/
static void l4_ipv6_icmpv6(struct intnode *intn, struct ip6_hdr *iph, const uint16_t len, struct icmp6_hdr *icmpv6, const uint16_t plen);
static void l4_ipv6_icmpv6(struct intnode *intn, struct ip6_hdr *iph, const uint16_t len, struct icmp6_hdr *icmpv6, const uint16_t plen)
{
uint16_t csum;
/* Increase ICMP received statistics */
g_conf->stat_icmp_received++;
intn->stat_icmp_received++;
/*
* We are only interrested in these types
* Saves on calculating a checksum and then ignoring it anyways
*/
if ( icmpv6->icmp6_type != ICMP6_MEMBERSHIP_REPORT &&
icmpv6->icmp6_type != ICMP6_MEMBERSHIP_REDUCTION &&
#ifdef ECMH_SUPPORT_MLD2
icmpv6->icmp6_type != ICMP6_V2_MEMBERSHIP_REPORT &&
icmpv6->icmp6_type != ICMP6_V2_MEMBERSHIP_REPORT_EXP &&
#endif
icmpv6->icmp6_type != ICMP6_MEMBERSHIP_QUERY &&
icmpv6->icmp6_type != ICMP6_ECHO_REQUEST)
{
dolog(LOG_DEBUG, "Ignoring ICMPv6: %s (%u), %s (%u) received on %s\n",
icmpv6_type(icmpv6->icmp6_type), icmpv6->icmp6_type,
icmpv6_code(icmpv6->icmp6_type, icmpv6->icmp6_code), icmpv6->icmp6_code,
intn->name);
return;
}
/* Save the checksum */
csum = icmpv6->icmp6_cksum;
/* Clear it temporarily */
icmpv6->icmp6_cksum = 0;
/* Verify checksum */
icmpv6->icmp6_cksum = ipv6_checksum(iph, IPPROTO_ICMPV6, icmpv6, plen);
if (icmpv6->icmp6_cksum != csum)
{
dolog(LOG_WARNING, "CORRUPT->DROP (%s): Received a ICMPv6 %s/%s (%u:%u) with wrong checksum (%x vs %x)\n",
intn->name,
icmpv6_type(icmpv6->icmp6_type),
icmpv6_code(icmpv6->icmp6_type, icmpv6->icmp6_code),
icmpv6->icmp6_type,
icmpv6->icmp6_code,
icmpv6->icmp6_cksum,
csum);
}
dolog(LOG_DEBUG, "Received ICMPv6: %s (%u), %s (%u) received on %s\n",
icmpv6_type(icmpv6->icmp6_type), icmpv6->icmp6_type,
icmpv6_code(icmpv6->icmp6_type, icmpv6->icmp6_code), icmpv6->icmp6_code,
intn->name);
if (icmpv6->icmp6_type == ICMP6_ECHO_REQUEST)
{
/*
* We redistribute IPv6 ICMPv6 Echo Requests to the subscribers
* This allows hosts to ping a IPv6 Multicast address and see who is listening ;)
*/
/* Decrease the hoplimit, but only if not 0 yet */
if (iph->ip6_hlim > 0)
{
iph->ip6_hlim--;
}
else
{
/* dolog(LOG_DEBUG, "Hoplimit for ICMPv6 packet was already %u\n", iph->ip6_hlim); */
}
if (iph->ip6_hlim == 0)
{
g_conf->stat_hlim_exceeded++;
/* Send a time_exceed_transit error */
icmp6_send(intn, &iph->ip6_src, ICMP6_ECHO_REPLY, ICMP6_TIME_EXCEED_TRANSIT, &icmpv6->icmp6_data32, plen-sizeof(*icmpv6)+sizeof(icmpv6->icmp6_data32));
return;
}
else
{
/* Send this packet along it's way */
l4_ipv6_multicast(intn, iph, len);
}
/* Done */
return;
}
if (!(IN6_IS_ADDR_LINKLOCAL(&iph->ip6_src)))
{
mld_log(LOG_WARNING, "Ignoring non-LinkLocal MLD", &iph->ip6_src, intn);
return;
}
switch (icmpv6->icmp6_type)
{
case ICMP6_MEMBERSHIP_REPORT:
l4_ipv6_icmpv6_mld1_report(intn, (struct mld1 *)icmpv6);
break;
case ICMP6_MEMBERSHIP_REDUCTION:
l4_ipv6_icmpv6_mld1_reduction(intn, (struct mld1 *)icmpv6);
break;
#ifdef ECMH_SUPPORT_MLD2
case ICMP6_V2_MEMBERSHIP_REPORT:
case ICMP6_V2_MEMBERSHIP_REPORT_EXP:
l4_ipv6_icmpv6_mld2_report(intn, (struct mld2_report *)icmpv6, plen);
break;
#endif /* ECMH_SUPPORT_MLD2 */
case ICMP6_MEMBERSHIP_QUERY:
l4_ipv6_icmpv6_mld_query(intn, plen);
break;
default:
dolog(LOG_DEBUG, "ICMP type %s (%u), %s (%u) got through\n",
icmpv6_type(icmpv6->icmp6_type), icmpv6->icmp6_type,
icmpv6_code(icmpv6->icmp6_type, icmpv6->icmp6_code), icmpv6->icmp6_code);
break;
}
return;
}
static void l3_ipv6(struct intnode *intn, struct ip6_hdr *iph, const uint16_t len);
static void l3_ipv6(struct intnode *intn, struct ip6_hdr *iph, const uint16_t len)
{
struct ip6_ext *ipe;
uint8_t ipe_type;
uint16_t plen;
uint32_t l;
/*
* Destination must be multicast
* We don't care about unicast destinations
* Those are handled by the OS itself hopefully ;)
*/
if (!IN6_IS_ADDR_MULTICAST(&iph->ip6_dst))
{
/* dolog(LOG_ERR, "Address is not multicast!\n"); */
return;
}
/* Source should not be us (linklocal/global) */
if ( memcmp(&iph->ip6_src, &intn->linklocal, sizeof(iph->ip6_dst)) == 0 ||
memcmp(&iph->ip6_src, &intn->global, sizeof(iph->ip6_dst)) == 0)
{
dolog(LOG_DEBUG, "Skipping packet from own host on %s\n", intn->name);
return;
}
/* Save the type of the next header */
ipe_type = iph->ip6_nxt;
/* Step to the next header */
ipe = (struct ip6_ext *)(((char *)iph) + sizeof(*iph));
plen = ntohs(iph->ip6_plen);
/* Skip the headers that we know */
while ( ipe_type == IPPROTO_HOPOPTS ||
ipe_type == IPPROTO_ROUTING ||
ipe_type == IPPROTO_DSTOPTS ||
ipe_type == IPPROTO_AH)
{
/* Save the type of the next header */
ipe_type = ipe->ip6e_nxt;
/* Step to the next header */
l = ((ipe->ip6e_len*8)+8);
plen -= l;
ipe = (struct ip6_ext *)(((char *)ipe) + l);
/* Check for corrupt packets */
if ((char *)ipe > (((char *)iph)+len))
{
dolog(LOG_WARNING, "CORRUPT->DROP (%s): Header chain beyond packet data\n", intn->name);
return;
}
}
/* Check for ICMP */
if (ipe_type == IPPROTO_ICMPV6)
{
/* Take care of ICMPv6 */
l4_ipv6_icmpv6(intn, iph, len, (struct icmp6_hdr *)ipe, plen);
return;
}
/* Handle multicast packets */
if (IN6_IS_ADDR_MULTICAST(&iph->ip6_dst))
{
/* Decrease the hoplimit, but only if not 0 yet */
if (iph->ip6_hlim > 0)
{
iph->ip6_hlim--;
}
else
{
D(dolog(LOG_DEBUG, "Hoplimit for UDP packet was already %u\n", iph->ip6_hlim);)
}
if (iph->ip6_hlim == 0)
{
g_conf->stat_hlim_exceeded++;
}
else
{
l4_ipv6_multicast(intn, iph, len);
}
return;
}
/* Ignore the rest */
return;
}
static void l2_ethtype(struct intnode *intn, const void *packet, const unsigned int len, const unsigned int ether_type)
{
switch (ether_type)
{
case ETH_P_IP:
/* Might have proto-41 tunnels in there */
l3_ipv4(intn, (struct ip *)packet, len);
break;
case ETH_P_IPV6:
l3_ipv6(intn, (struct ip6_hdr *)packet, len);
break;
default:
/* We don't care about anything else... */
break;
}
}
#ifdef ECMH_BPF
static void l2_eth(struct intnode *intn, struct ether_header *eth, const unsigned int len);
static void l2_eth(struct intnode *intn, struct ether_header *eth, const unsigned int len)
{
l2_ethtype(intn, ((uint8_t *)eth + sizeof(*eth)), len-sizeof(*eth), ntohs(eth->ether_type));
}
#endif
static void init(void);
static void init(void)
{
g_conf = calloc(1, sizeof(*g_conf));
if (!g_conf)
{
dolog(LOG_ERR, "Couldn't init() - no memory for configuration\n");
exit(-1);
}
/*
* 32k of buffer should be enough
* we can then have ~30 packets in
* the same buffer-read
*/
g_conf->bufferlen = (32*1024);
#ifndef ECMH_BPF
/* Raw socket is not open yet */
g_conf->rawsocket = -1;
#else
FD_ZERO(&g_conf->selectset);
g_conf->tunnelmode = true;
g_conf->locals = list_new();
g_conf->locals->del = (void(*)(void *))local_destroy;
#endif /* ECMH_BPF */
/* Initialize our configuration */
g_conf->maxgroups = 42; /* XXX: Todo: Not verified yet... */
g_conf->maxinterfaces = 0;
g_conf->daemonize = true;
#ifdef ECMH_BPF
g_conf->promisc = true; /* Almost required for BPF because of the tunnels */
#else
g_conf->promisc = false; /* Sometimes needed, but usually not */
#endif
/* Initialize our list of groups */
g_conf->groups = list_new();
g_conf->groups->del = (void(*)(void *))group_destroy;
/* Initialize our counters */
g_conf->stat_starttime = gettimes();
g_conf->stat_packets_received = 0;
g_conf->stat_packets_sent = 0;
g_conf->stat_bytes_received = 0;
g_conf->stat_bytes_sent = 0;
g_conf->stat_icmp_received = 0;
g_conf->stat_icmp_sent = 0;
g_conf->stat_hlim_exceeded = 0;
}
static void sighup(int i);
static void sighup(int i)
{
/* Reset the signal */
signal(i, &sighup);
}
/* Send MLD reports */
static void sigusr2(int i);
static void sigusr2(int i)
{
struct intnode *intn;
signal(i, SIG_IGN);
if (g_conf->upstream)
{
intn = int_find(g_conf->upstream_id);
if (intn)
{
#ifdef ECMH_SUPPORT_MLD2
mld2_send_report(intn, NULL);
#else
mld1_send_report(intn, NULL);
#endif
}
}
signal(i, &sigusr2);
}
/* Dump the statistical information */
static void sigusr1(int i);
static void sigusr1(int i)
{
struct intnode *intn;
struct groupnode *groupn;
struct listnode *ln;
struct grpintnode *grpintn;
struct listnode *gn;
struct subscrnode *subscrn;
struct listnode *ssn;
uint64_t time_tee;
char addr[INET6_ADDRSTRLEN];
unsigned int subscriptions = 0, j, count;
unsigned int uptime_s, uptime_m, uptime_h, uptime_d;
/* Ignore further signals */
signal(i, SIG_IGN);
/* Get the current time */
time_tee = gettimes();
uptime_s = time_tee - g_conf->stat_starttime;
uptime_d = uptime_s / (24*60*60);
uptime_s -= uptime_d * 24*60*60;
uptime_h = uptime_s / (60*60);
uptime_s -= uptime_h * 60*60;
uptime_m = uptime_s / 60;
uptime_s -= uptime_m * 60;
/* Rewind the file to the start */
rewind(g_conf->stat_file);
/* Truncate the file */
ftruncate(fileno(g_conf->stat_file), (off_t)0);
/* Dump out all the groups with their information */
fprintf(g_conf->stat_file, "*** Subscription Information Dump\n");
fprintf(g_conf->stat_file, "\n");
LIST_LOOP(g_conf->groups, groupn, ln)
{
inet_ntop(AF_INET6, &groupn->mca, addr, sizeof(addr));
fprintf(g_conf->stat_file, "Group : %s\n", addr);
fprintf(g_conf->stat_file, "\tBytes : %" PRIu64 "\n", groupn->bytes);
fprintf(g_conf->stat_file, "\tPackets: %" PRIu64 "\n", groupn->packets);
LIST_LOOP(groupn->interfaces, grpintn, gn)
{
intn = int_find(grpintn->ifindex);
if (!intn)
{
continue;
}
fprintf(g_conf->stat_file, "\tInterface: %s (%" PRIi64 ")\n",
intn->name, grpintn->subscriptions->count);
LIST_LOOP(grpintn->subscriptions, subscrn, ssn)
{
int d = time_tee - subscrn->refreshtime;
if (d < 0)
{
d = -i;
}
inet_ntop(AF_INET6, &subscrn->ipv6, addr, sizeof(addr));
fprintf(g_conf->stat_file, "\t\t%s %s (%u seconds old)\n",
addr,
subscrn->mode == MLD2_MODE_IS_INCLUDE ? "INCLUDE" : "EXCLUDE",
d);
subscriptions++;
}
}
fprintf(g_conf->stat_file, "\n");
}
fprintf(g_conf->stat_file, "*** Subscription Information Dump (end - %" PRIi64 " groups, %u subscriptions)\n", g_conf->groups->count, subscriptions);
fprintf(g_conf->stat_file, "\n");
/* Dump all the interfaces */
fprintf(g_conf->stat_file, "*** Interface Dump\n");
fprintf(g_conf->stat_file, "\n");
for (count=0, j=0; j < g_conf->maxinterfaces; j++)
{
intn = &g_conf->ints[j];
if (intn->mtu == 0)
{
continue;
}
count++;
fprintf(g_conf->stat_file, "Interface: %s\n", intn->name);
fprintf(g_conf->stat_file, " Index number : %" PRIu64 "\n", intn->ifindex);
fprintf(g_conf->stat_file, " MTU : %" PRIu64 "\n", intn->mtu);
#ifdef ECMH_BPF
/* Tunnel has a master interface? */
if (intn->master)
{
inet_ntop(AF_INET, &intn->master->ipv4_local, addr, sizeof(addr));
fprintf(g_conf->stat_file, " Master interface : %s (%" PRIu64 "/%s)\n", intn->master->name, intn->master->ifindex, addr);
inet_ntop(AF_INET, &intn->ipv4_remote, addr, sizeof(addr));
fprintf(g_conf->stat_file, " IPv4 Remote : %s\n", addr);
}
#endif /* ECMH_BPF */
fprintf(g_conf->stat_file, " Interface Type : %s (%" PRIu64 ")\n",
#ifndef ECMH_BPF
(intn->hwaddr.sa_family == ARPHRD_ETHER ? "Ethernet" :
(intn->hwaddr.sa_family == ARPHRD_SIT ? "sit" : "Unknown")),
(uint64_t)intn->hwaddr.sa_family
#else
(intn->dlt == DLT_NULL ? "Null":
(intn->dlt == DLT_EN10MB ? "Ethernet" : "Unknown")),
intn->dlt
#endif
);
inet_ntop(AF_INET6, &intn->linklocal, addr, sizeof(addr));
fprintf(g_conf->stat_file, " Link-local address : %s\n", addr);
inet_ntop(AF_INET6, &intn->global, addr, sizeof(addr));
fprintf(g_conf->stat_file, " Global unicast address : %s\n", addr);
if (intn->mld_version == 0)
fprintf(g_conf->stat_file, " MLD version : none\n");
else
fprintf(g_conf->stat_file, " MLD version : v%" PRIu64 "\n", intn->mld_version);
fprintf(g_conf->stat_file, " Packets received : %" PRIu64 "\n", intn->stat_packets_received);
fprintf(g_conf->stat_file, " Packets sent : %" PRIu64 "\n", intn->stat_packets_sent);
fprintf(g_conf->stat_file, " Bytes received : %" PRIu64 "\n", intn->stat_bytes_received);
fprintf(g_conf->stat_file, " Bytes sent : %" PRIu64 "\n", intn->stat_bytes_sent);
fprintf(g_conf->stat_file, " ICMP's received : %" PRIu64 "\n", intn->stat_icmp_received);
fprintf(g_conf->stat_file, " ICMP's sent : %" PRIu64 "\n", intn->stat_icmp_sent);
fprintf(g_conf->stat_file, "\n");
}
fprintf(g_conf->stat_file, "*** Interface Dump (end - %u interfaces)\n", count);
fprintf(g_conf->stat_file, "\n");
/* Dump out some generic program statistics */
strftime(addr, sizeof(addr), "%Y-%m-%d %H:%M:%S", gmtime(&g_conf->stat_starttime));
fprintf(g_conf->stat_file, "*** Statistics Dump\n");
fprintf(g_conf->stat_file, "\n");
fprintf(g_conf->stat_file, "Version : ecmh %s\n", ECMH_VERSION);
fprintf(g_conf->stat_file, "Git Hash : %s\n", ECMH_GITHASH);
fprintf(g_conf->stat_file, "Started : %s GMT\n", addr);
fprintf(g_conf->stat_file, "Uptime : %u days %02u:%02u:%02u\n", uptime_d, uptime_h, uptime_m, uptime_s);
#ifdef ECMH_BPF
fprintf(g_conf->stat_file, "\n");
fprintf(g_conf->stat_file, "Tunnelmode : %s\n", g_conf->tunnelmode ? "Active" : "Disabled");
#endif /* ECMH_BPF */
fprintf(g_conf->stat_file, "\n");
fprintf(g_conf->stat_file, "Interfaces Monitored : %u\n", count);
fprintf(g_conf->stat_file, "Groups Managed : %" PRIi64 "\n", g_conf->groups->count);
fprintf(g_conf->stat_file, "Total Subscriptions : %u\n", subscriptions);
#ifdef ECMH_SUPPORT_MLD2
fprintf(g_conf->stat_file, "v2 Robustness Factor : %u\n", ECMH_ROBUSTNESS_FACTOR);
#endif
fprintf(g_conf->stat_file, "Subscription Timeout : %u\n", ECMH_SUBSCRIPTION_TIMEOUT * ECMH_ROBUSTNESS_FACTOR);
fprintf(g_conf->stat_file, "\n");
fprintf(g_conf->stat_file, "Packets Received : %" PRIu64 "\n", g_conf->stat_packets_received);
fprintf(g_conf->stat_file, "Packets Sent : %" PRIu64 "\n", g_conf->stat_packets_sent);
fprintf(g_conf->stat_file, "Bytes Received : %" PRIu64 "\n", g_conf->stat_bytes_received);
fprintf(g_conf->stat_file, "Bytes Sent : %" PRIu64 "\n", g_conf->stat_bytes_sent);
fprintf(g_conf->stat_file, "ICMP's received : %" PRIu64 "\n", g_conf->stat_icmp_received);
fprintf(g_conf->stat_file, "ICMP's sent : %" PRIu64 "\n", g_conf->stat_icmp_sent);
fprintf(g_conf->stat_file, "Hop Limit Exceeded : %" PRIu64 "\n", g_conf->stat_hlim_exceeded);
fprintf(g_conf->stat_file, "\n");
fprintf(g_conf->stat_file, "*** Statistics Dump (end)\n");
/* Flush the information to disk */
fflush(g_conf->stat_file);
dolog(LOG_INFO, "Dumped statistics into %s\n", ECMH_DUMPFILE);
/* Reset the signal */
signal(i, &sigusr1);
}
/* Let's tell everybody we are a querier and ask */
/* them which groups they want to receive. */
static void send_mld_querys(void);
static void send_mld_querys(void)
{
struct intnode *intn;
struct in6_addr any;
unsigned int i;
dolog(LOG_DEBUG, "Sending MLD Queries\n");
/* We want to know about all the groups */
memzero(&any, sizeof(any));
/* Send MLD query's */
/* Use listloop2 as the node can disappear in sendpacket() */
for (i=0; i < g_conf->maxinterfaces; i++)
{
intn = &g_conf->ints[i];
if (intn->mtu == 0)
{
continue;
}
mld_send_query(intn, &any);
}
dolog(LOG_DEBUG, "Sending MLD Queries - done\n");
}
static void timeout_signal(int i);
static void timeout_signal(int i)
{
/*
* Mark it to be ignored, this avoids double timeouts
* one never knows if it takes too long to handle
* the first one.
*/
signal(i, SIG_IGN);
/* Set the needs_timeout */
g_needs_timeout = true;
}
static void timeout(void);
static void timeout(void)
{
struct groupnode *groupn;
struct listnode *ln, *ln2;
struct grpintnode *grpintn;
struct listnode *gn, *gn2;
struct subscrnode *subscrn;
struct listnode *ssn, *ssn2;
uint64_t time_tee;
int64_t i;
dolog(LOG_DEBUG, "Timeout\n");
/* Update the complete interfaces list */
update_interfaces(NULL);
/* Get the current time */
time_tee = gettimes();
/* Timeout all the groups that didn't refresh yet */
LIST_LOOP2(g_conf->groups, groupn, ln, ln2)
{
printf("Groups\n");
LIST_LOOP2(groupn->interfaces, grpintn, gn, gn2)
{
printf("Group Interfaces\n");
LIST_LOOP2(grpintn->subscriptions, subscrn, ssn, ssn2)
{
/* Calculate the difference */
i = time_tee - subscrn->refreshtime;
if (i < 0)
{
i = -i;
}
/* Dead too long? */
if (i > (ECMH_SUBSCRIPTION_TIMEOUT * ECMH_ROBUSTNESS_FACTOR))
{
/* Dead too long -> delete it */
list_delete_node(grpintn->subscriptions, ssn);
/* Destroy the subscription itself */
subscr_destroy(subscrn);
}
}
LIST_LOOP2_END
#ifndef ECMH_SUPPORT_MLD2
if (grpintn->subscriptions->count == 0)
#else
if (grpintn->subscriptions->count <= (-ECMH_ROBUSTNESS_FACTOR))
#endif
{
/* Delete from the list */
list_delete_node(groupn->interfaces, gn);
/* Destroy the grpint */
grpint_destroy(grpintn);
}
}
LIST_LOOP2_END
if (groupn->interfaces->count == 0)
{
/* Delete from the list */
list_delete_node(g_conf->groups, ln);
/* Destroy the group */
group_destroy(groupn);
}
}
LIST_LOOP2_END
/* Send out MLD queries */
send_mld_querys();
dolog(LOG_DEBUG, "Timeout - done\n");
}
static bool handleinterfaces(void *buffer);
static bool handleinterfaces(void *buffer)
{
int i = 0, len;
struct intnode *intn = NULL;
#ifndef ECMH_BPF
struct sockaddr_ll sa;
socklen_t salen;
salen = sizeof(sa);
memzero(&sa, sizeof(sa));
len = recvfrom(g_conf->rawsocket, buffer, g_conf->bufferlen, 0, (struct sockaddr *)&sa, &salen);
if (len == -1)
{
dolog(LOG_ERR, "Couldn't Read from RAW Socket\n");
return false;
}
/*
* Ignore:
* - loopback traffic
* - any packets that originate from this host
*/
if ( sa.sll_hatype == ARPHRD_LOOPBACK ||
sa.sll_pkttype == PACKET_OUTGOING)
{
return true;
}
/* Update statistics */
g_conf->stat_packets_received++;
g_conf->stat_bytes_received+=len;
/* The interface we need to find */
i = sa.sll_ifindex;
intn = int_find(i);
if (!intn)
{
/* Create a new interface */
intn = int_create(i);
if (intn)
{
/* Determine linklocal address etc. */
update_interfaces(intn);
}
}
if (intn)
{
intn->stat_packets_received++;
intn->stat_bytes_received+=len;
/* Handle the packet */
l2_ethtype(intn, buffer, len, ntohs(sa.sll_protocol));
}
else
{
dolog(LOG_ERR, "Couldn't find interface link %u\n", i);
}
return true;
#else /* !ECMH_BPF */
void *bp, *ep, *rbuffer = buffer;
struct bpf_hdr *bhp;
fd_set fd_read;
struct timeval timeout;
/* What we want to know */
memcpy(&fd_read, &g_conf->selectset, sizeof(fd_read));
memzero(&timeout, sizeof(timeout));
timeout.tv_sec = 5;
i = select(g_conf->hifd+1, &fd_read, NULL, NULL, &timeout);
if (i < 0)
{
if (errno == EINTR)
{
return true;
}
dolog(LOG_ERR, "Select failed\n");
return false;
}
if (i == 0)
{
return true;
}
for (i = 0; ((uint64_t)i) < g_conf->maxinterfaces; i++)
{
intn = &g_conf->ints[i];
if (intn->mtu == 0)
{
continue;
}
if ( intn->socket == -1 ||
!FD_ISSET(intn->socket, &fd_read))
{
continue;
}
len = read(intn->socket, rbuffer, intn->bufferlen);
if (len < 0)
{
dolog(LOG_ERR, "Couldn't read from BPF device: %s (%d)\n", strerror(errno), errno);
return false;
}
bp = buffer = rbuffer;
bhp = (struct bpf_hdr *)bp;
for ( ep = ((uint8_t *)bp) + bhp->bh_caplen;
bp < ep;
bp = ((uint8_t *)bp) + BPF_WORDALIGN(bhp->bh_caplen + bhp->bh_hdrlen))
{
bhp = (struct bpf_hdr *)bp;
buffer = ((uint8_t *)bp) + bhp->bh_hdrlen;
intn->stat_packets_received++;
intn->stat_bytes_received += bhp->bh_caplen;
/* Layer 2 packet */
l2_eth(intn, buffer, bhp->bh_caplen);
}
} /* Interfaces */
#endif /* !ECMH_BPF */
return true;
}
/* Long options */
static struct option const long_options[] = {
{"foreground", no_argument, NULL, 'f'},
{"upstream", required_argument, NULL, 'i'},
{"promisc", no_argument, NULL, 'p'},
{"nopromisc", no_argument, NULL, 'P'},
{"user", required_argument, NULL, 'u'},
{"tunnelmode", no_argument, NULL, 't'},
{"notunnelmode", no_argument, NULL, 'T'},
{"verbose", no_argument, NULL, 'v'},
{"version", no_argument, NULL, 'V'},
#ifdef ECMH_SUPPORT_MLD2
{"mld1only", no_argument, NULL, '1'},
{"mld2only", no_argument, NULL, '2'},
#endif
{NULL, 0, NULL, 0},
};
int main(int argc, char *argv[])
{
int i, drop_uid = 0, drop_gid = 0, option_index = 0;
unsigned int j;
struct passwd *passwd;
bool quit = false;
struct intnode *intn;
#ifdef _LINUX
struct sched_param schedparam;
#endif
init();
/* Handle arguments */
while ((i = getopt_long(argc, argv, "fi:pPu:"
#ifdef ECMH_BPF
"tT"
#endif
"vV"
#ifdef ECMH_SUPPORT_MLD2
"12"
#endif
, long_options, &option_index)) != EOF)
{
switch (i)
{
case 0:
/* Long option without a small letter */
break;
case 'f':
g_conf->daemonize = false;
break;
case 'i':
if (g_conf->upstream)
{
fprintf(stderr, "Only one upstream interface (was: %s) can be specified\n", g_conf->upstream);
return -1;
}
g_conf->upstream = strdup(optarg);
break;
case 'p':
g_conf->promisc = true;
break;
case 'P':
g_conf->promisc = false;
break;
case 'u':
passwd = getpwnam(optarg);
if (!passwd)
{
fprintf(stderr, "Couldn't find user %s, aborting\n", optarg);
return -1;
}
drop_uid = passwd->pw_uid;
drop_gid = passwd->pw_gid;
break;
#ifdef ECMH_BPF
case 't':
g_conf->tunnelmode = true;
break;
case 'T':
g_conf->tunnelmode = false;
break;
#endif
case 'v':
g_conf->verbose = true;
break;
case 'V':
printf(ECMH_VERSION_STRING, ECMH_VERSION, ECMH_GITHASH);
return 0;
#ifdef ECMH_SUPPORT_MLD2
case '1':
g_conf->mld1only = true;
g_conf->mld2only = false;
break;
case '2':
g_conf->mld1only = false;
g_conf->mld2only = true;
break;
#endif
default:
fprintf(stderr,
"%s [-f] [-u username] [-i interface]"
#ifdef ECMH_BPF
" [-t|-T]"
#endif
" [-v] [-V]"
#ifdef ECMH_SUPPORT_MLD2
" [-1|-2]"
#endif
" [-p|-P]"
"\n"
"\n"
"-f, --foreground don't daemonize\n"
"-u, --user username drop (setuid+setgid) to user after startup\n"
"-i, --upstream interface upstream interface\n"
#ifdef ECMH_BPF
"-t, --tunnelmode Don't attach to tunnels, but use proto-41 decapsulation (default)\n"
"-T, --notunnelmode Attach to tunnels seperatly\n"
#endif
"-v, --verbose Verbose Operation\n"
"-V, --version Report version and exit\n"
#ifdef ECMH_SUPPORT_MLD2
"-1, --mld1only Act as a MLDv1 only host\n"
"-2, --mld2only Act as a MLDv2 only host (*)\n"
#endif
,
argv[0]);
fprintf(stderr,
"-p, --promisc Make interfaces promisc"
#ifdef ECMH_BPF
" (default)"
#endif
"\n"
"-P, --nopromisc Don't make interfaces promisc"
#ifndef ECMH_BPF
" (default)"
#endif
"\n"
"\n"
"Report bugs to <NAME> <<EMAIL>>.\n"
"Also see the website at http://unfix.org/projects/ecmh/\n"
"\n"
"* = RFC incompliant as it ignores MLDv1 reports completely\n"
"Recommended is running without the 'only' options as that is\n"
"the mode allows fallback from MLDv2 to MLDv1 as per the RFC\n");
return -1;
}
}
/* Daemonize */
if (g_conf->daemonize)
{
int pid = fork();
if (pid < 0)
{
fprintf(stderr, "Couldn't fork\n");
return -1;
}
/* Exit the mother fork */
if (pid != 0)
{
return 0;
}
/* Child fork */
setsid();
/* Cleanup stdin/out/err */
freopen("/dev/null","r",stdin);
freopen("/dev/null","w",stdout);
freopen("/dev/null","w",stderr);
}
/* Handle a SIGHUP to reload the config */
signal(SIGHUP, &sighup);
/* Handle SIGTERM/INT/KILL to cleanup the pid file and exit */
signal(SIGTERM, &cleanpid);
signal(SIGINT, &cleanpid);
signal(SIGKILL, &cleanpid);
/* Timeout handling */
signal(SIGALRM, &timeout_signal);
alarm(ECMH_SUBSCRIPTION_TIMEOUT);
/* Dump operations */
signal(SIGUSR1, &sigusr1);
signal(SIGUSR2, &sigusr2);
/* Show our version in the startup logs ;) */
dolog(LOG_INFO, ECMH_VERSION_STRING, ECMH_VERSION, ECMH_GITHASH);
#ifdef ECMH_BPF
dolog(LOG_INFO, "Tunnelmode is %s\n", g_conf->tunnelmode ? "Active" : "Disabled");
#endif
dolog(LOG_INFO, "Determining names using %s\n",
#ifdef SIOCGIFNAME
"SIOCGIFNAME ioctl"
#else
"if_indextoname"
#endif
);
if (g_conf->upstream)
{
dolog(LOG_INFO, "Using %s as an upstream interface\n", g_conf->upstream);
}
#ifdef ECMH_SUPPORT_MLD2
if (g_conf->mld1only)
{
dolog(LOG_INFO, "MLDv1 Only Mode, only MLDv1 Queries and Reports will be sent\n");
}
else if (g_conf->mld2only)
{
dolog(LOG_INFO, "MLDv2 Only Mode, only MLDv2 Queries will be sent\n");
}
#endif
/* Save our PID */
savepid();
/* Open our dump file */
g_conf->stat_file = fopen(ECMH_DUMPFILE, "w");
if (!g_conf->stat_file)
{
dolog(LOG_ERR, "Couldn't open dumpfile %s\n", ECMH_DUMPFILE);
return -1;
}
#ifndef ECMH_BPF
/*
* Allocate a single PACKET socket which can send and receive
* anything we want (anything ???.... anythinggg... ;)
* This is only available on Linux though
*/
g_conf->rawsocket = socket(PF_PACKET, SOCK_DGRAM, htons(ETH_P_ALL));
if (g_conf->rawsocket < 0)
{
dolog(LOG_ERR, "Couldn't allocate a RAW socket\n");
return -1;
}
#endif /* ECMH_BPF */
g_conf->buffer = calloc(1, g_conf->bufferlen);
if (!g_conf->buffer)
{
dolog(LOG_INFO, "Couldn't allocate memory for buffer: %s (%d)\n", strerror(errno), errno);
return -1;
}
/* Fix our priority, we need to be near realtime */
if (setpriority(PRIO_PROCESS, getpid(), -15) == -1)
{
dolog(LOG_WARNING, "Couldn't raise priority to -15, if streams are shaky, upgrade your cpu or fix this\n");
}
#ifdef _LINUX
/* Change scheduler for higher accuracy */
memzero(&schedparam, sizeof(schedparam));
schedparam.sched_priority = 99;
if (sched_setscheduler(0, SCHED_FIFO, &schedparam) == -1)
{
dolog(LOG_WARNING, "Couldn't configure the scheduler, errno = %i\n",errno);
}
#endif
/*
* Drop our root priveleges.
* We don't need them anymore anyways
*/
if (drop_uid != 0)
{
setuid(drop_uid);
}
if (drop_gid != 0)
{
setgid(drop_gid);
}
/* Update the complete interfaces list */
update_interfaces(NULL);
send_mld_querys();
while (!g_conf->quit && !quit)
{
/* Was a timeout set? */
if (g_needs_timeout)
{
/* Run timeout routine */
timeout();
/* Turn it off */
g_needs_timeout = false;
/* Reset the alarm */
signal(SIGALRM, &timeout_signal);
alarm(ECMH_SUBSCRIPTION_TIMEOUT);
}
quit = !handleinterfaces(g_conf->buffer);
}
/* Dump the stats one last time */
sigusr1(SIGUSR1);
/* Show the message in the log */
dolog(LOG_INFO, "Shutdown, thank you for using ecmh\n");
/* Cleanup the nodes
* First the groups, otherwise the references to the
* names are gone when we need them when displaying
* the group deletions from the interfaces ;)
*/
list_delete_all_node(g_conf->groups);
#ifdef ECMH_BPF
/* Clear the locals */
list_delete_all_node(g_conf->locals);
#endif
/* Get rid of the interfaces too now */
for (j = 0; j < g_conf->maxinterfaces; j++)
{
intn = &g_conf->ints[j];
if (intn->mtu == 0)
{
continue;
}
int_destroy(intn);
}
/* Free the interfaces memory block */
free(g_conf->ints);
list_free(g_conf->groups);
/* Close files and sockets */
fclose(g_conf->stat_file);
#ifndef ECMH_BPF
close(g_conf->rawsocket);
#endif
if (g_conf->buffer)
{
free(g_conf->buffer);
}
/* Free the config memory */
free(g_conf);
g_conf = NULL;
cleanpid(SIGINT);
return 0;
}
<file_sep>/src/linklist.h
/*
* Generic linked list
* Copyright (C) 1997, 2000 <NAME>
* customized for ecmh by <NAME>
*/
#ifndef __LINKLIST_H
#define __LINKLIST_H
#include "ecmh.h"
struct listnode
{
struct listnode *next;
struct listnode *prev;
void *data;
};
struct list
{
struct listnode *head;
struct listnode *tail;
int64_t count;
void (*del)(void *val);
};
#define nextnode(X) ((X) = (X)->next)
#define listhead(X) ((X)->head)
#define listcount(X) ((X)->count)
#define list_isempty(X) ((X)->head == NULL && (X)->tail == NULL)
#define getdata(X) ((X)->data)
/* Prototypes. */
struct list *list_new(void);
void list_free(struct list *);
void listnode_add(struct list *, void *);
void list_delete (struct list *);
void list_delete_all_node (struct list *);
void list_delete_node (struct list *, struct listnode *);
/* List iteration macro. */
#define LIST_LOOP(L,V,N) \
for ((N) = (L)->head; (N); (N) = (N)->next) \
if (((V) = (N)->data) != NULL)
/* List iteration macro. */
#define LIST_LOOP2(L,V,N,M) \
for ((M) = (L)->head; (M);) \
{\
(N) = (M); \
(M) = (N)->next; \
if (((V) = (N)->data) != NULL)
#define LIST_LOOP2_END }
#endif /* __LINKLIST_H */
<file_sep>/src/common.h
/*****************************************************
ecmh - Easy Cast du Multi Hub - Common Functions
******************************************************
$Author: fuzzel $
$Id: common.h,v 1.2 2005/02/09 17:58:06 fuzzel Exp $
$Date: 2005/02/09 17:58:06 $
*****************************************************/
void dolog(int level, const char *fmt, ...) ATTR_FORMAT(printf, 2, 3);
int huprunning(void);
void savepid(void);
void cleanpid(int i);
uint64_t gettimes(void);
<file_sep>/src/grpint.h
/**************************************
ecmh - Easy Cast du Multi Hub
by <NAME> <<EMAIL>>
**************************************/
/* The node used to hold the interfaces which a group joined */
struct grpintnode
{
uint64_t ifindex; /* The interface */
struct list *subscriptions; /* Subscriber list */
};
struct grpintnode *grpint_create(const struct intnode *interface);
void grpint_destroy(struct grpintnode *grpintn);
struct grpintnode *grpint_find(const struct list *list, const struct intnode *interface);
bool grpint_refresh(struct grpintnode *grpintn, const struct in6_addr *ipv6, unsigned int mode);
<file_sep>/src/groups.h
/**************************************
ecmh - Easy Cast du Multi Hub
by <NAME> <<EMAIL>>
**************************************/
/* The node used to hold the groups we joined */
struct groupnode
{
struct in6_addr mca; /* The Multicast IPv6 address (group) */
struct list *interfaces; /* The list of grpint nodes (interfaces) that */
/* are interrested in this node */
time_t lastforward; /* The last time we forwarded a report for this group */
uint64_t bytes; /* Number of received bytes */
uint64_t packets; /* Number of received packets */
};
void group_destroy(struct groupnode *groupn);
struct groupnode *group_find(const struct in6_addr *mca);
struct grpintnode *groupint_get(const struct in6_addr *mca, struct intnode *interface, bool *isnew);
<file_sep>/README.md
# ecmh - Easy Cast du Multi Hub
[Easy Cast du Multi Hub (ecmh)](http://unfix.org/projects/ecmh/)
is a network daemon that relays and aggregates multicast packets from/to network interfaces.
This allows IPv6 multicast routing on Linux and other OS's that
do not implement IPv6 multicast routing. It also allows IPv4 to
IPv6 and IPv6 to IPv4 translation of multicast traffic.
Allowing multicast where it is not available at the moment.
It also has a tunnel mode so that it can detect multicast
packets being tunneled inside protocol 41 (IPv6 in IPv4)
tunnels [RFC3056](https://tools.ietf.org/html/rfc3056).
This is for instance very handy for
projects like [SixXS](http://www.sixxs.net) where we can
install this daemon on the POPs and let it easily do
multicast IPv6 allowing the m6bone (http://www.m6bone.net)
to grow and provide IPv6 multicast and because of the
translation also IPv4 multicast everywhere we would want it to be.
For a larger explaination see the [ecmh webpage](http://unfix.org/projects/ecmh/).
## Compilation
* Linux
Either get the debian package or use ```make help``` in this directory (not src)
* FreeBSD 5 (GNU make)
use ```make help``` to see the options
* FreeBSD 5 (BSD make)
```cd src;``` uncomment the 3 lines in the Makefile to get it working
* FreeBSD 4
```cd src;``` uncomment the 3 lines in the Makefile to get it working
Requires the libgnugetopt port. Make it from the 'src' dir'
## License
The license for ecmh is the BSD 3-clause license.
## Author
The author of ecmh is [<NAME>](http://jeroen.massar.ch).
| c016b5929cb4c5332f8a700d4ddbe76704faffa2 | [
"Markdown",
"C",
"Makefile",
"Shell"
] | 22 | C | hitarthdoc/ecmh | 523110291b67accbb90d918287d30c565d6aff4c | 3995a982824bc3315522175d1645c99cc4108546 |
refs/heads/master | <file_sep>#include "drake/bindings/pydrake/systems/lcm_py_bind_cpp_serializers.h"
#include "drake/bindings/pydrake/systems/lcm_pybind.h"
#include "drake/lcmt_contact_results_for_viz.hpp"
#include "drake/lcmt_image_array.hpp"
#include "drake/lcmt_quaternion.hpp"
namespace drake {
namespace pydrake {
namespace pysystems {
namespace pylcm {
void BindCppSerializers() {
// N.B. At least one type should be bound to ensure the template is defined.
// N.B. These should be placed in the same order as the headers.
BindCppSerializer<drake::lcmt_contact_results_for_viz>("drake");
BindCppSerializer<drake::lcmt_image_array>("drake");
BindCppSerializer<drake::lcmt_quaternion>("drake");
}
} // namespace pylcm
} // namespace pysystems
} // namespace pydrake
} // namespace drake
| 1b6ce4d730844f948a2de9d68e340e3c93fc8722 | [
"C++"
] | 1 | C++ | nadah09/drake | b07f2af6410dd437609f14c7959b65f36f644731 | a382efec7722ec6b5f4417dd309fea23f091cc8f |
refs/heads/master | <repo_name>soolaugust/design-pattern-demo<file_sep>/src/proxy/Service.java
package proxy;
// 需要使用的服务
public class Service {
public void method(){}
}
<file_sep>/src/chain/of/responsibility/HandlerInterface.java
package chain.of.responsibility;
// 处理者接口
public interface HandlerInterface {
// 处理函数
// true表示已处理完,不需要继续处理
// false表示传递给下一个处理者
boolean handle(Object request);
}<file_sep>/src/chain/of/responsibility/BlockHandler.java
package chain.of.responsibility;
// 处理完后终止传递
public class BlockHandler implements HandlerInterface {
@Override
public boolean handle(Object request) {
System.out.printf("request %s is received, block the chain\n", request.toString());
return true;
}
}
<file_sep>/src/observer/PublisherInterface.java
package observer;
interface PublisherInterface {
boolean subscribe(String eventType , SubscriberInterface subscriber);
boolean unSubscribe(String eventType , SubscriberInterface subscriber);
void onEvent(String event);
}<file_sep>/src/observer/Publisher.java
package observer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Publisher implements PublisherInterface {
Map<String, List<SubscriberInterface>> subscriberMap = new HashMap();
@Override
public boolean subscribe(String eventType, SubscriberInterface subscriber) {
// 第一次订阅事件,创建订阅列表并加入订阅者
if(!subscriberMap.containsKey(eventType)){
List<SubscriberInterface> subscribers = new ArrayList<>();
subscribers.add(subscriber);
subscriberMap.put(eventType, subscribers);
}
// 已经订阅的,不做任何反应
if(subscriberMap.get(eventType).contains(subscriber)){
return true;
}
// 将订阅者加入到订阅列表
subscriberMap.get(eventType).add(subscriber);
return true;
}
@Override
public boolean unSubscribe(String eventType, SubscriberInterface subscriber) {
// 如果不存在订阅类型,返回失败
if (!subscriberMap.containsKey(eventType)){
return false;
}
// 如果之前没有订阅,不做任何反应
if(!subscriberMap.get(eventType).contains(subscriber)){
return true;
}
subscriberMap.get(eventType).remove(subscriber);
return true;
}
@Override
public void onEvent(String event){
// 遍历订阅者列表,并调用接受接口
for(SubscriberInterface subscriber : subscriberMap.get(event)){
subscriber.onReceive(event);
}
}
}
<file_sep>/README.md
# design-pattern-demo
## 详情
* [观察者模式](https://mp.weixin.qq.com/s?__biz=Mzg4MTIwMTkxNQ==&mid=2247483888&idx=1&sn=5b5425d7613427dc1266c82d91408b83&chksm=cf68c664f81f4f72609392f88a2ddafda30773b718ecb1e2367bd4b81c506d3bcd8299d1cd7a&token=<PASSWORD>&lang=zh_CN#rd)
* [观察者模式实战](https://mp.weixin.qq.com/s?__biz=Mzg4MTIwMTkxNQ==&mid=2247483898&idx=1&sn=3f37d4b39922636f14df11e575997965&chksm=cf68c66ef81f4f785d53d6d5c213de6f69ea5df3e6bab8cb5a5d28995a510e54654ae3ff591d&token=<PASSWORD>&lang=zh_CN#rd)<file_sep>/src/observer/Application.java
package observer;
public class Application {
private static final String EVENT_1 = "event1";
private static final String EVENT_2 = "event2";
public static void main(String[] args){
// 定义对象
PublisherInterface publisher = new Publisher();
SubscriberInterface subscriber1 = new Subscriber();
SubscriberInterface subscriber2 = new Subscriber();
// subscriber1订阅事件1,subscriber2订阅事件2
publisher.subscribe(EVENT_1, subscriber1);
publisher.subscribe(EVENT_2, subscriber2);
// 触发事件1, subscriber1响应
publisher.onEvent(EVENT_1);
// subscriber1取消订阅事件1
publisher.unSubscribe(EVENT_1, subscriber1);
// 触发事件1, 因为没有订阅者,不响应
publisher.onEvent(EVENT_1);
// 触发事件2,subscriber2响应
publisher.onEvent(EVENT_2);
}
}
// 输出如下
// receive event: event1
// receive event: event2
| 63e9bba2a330ee7a29aa77a2078e9b45b3686a27 | [
"Markdown",
"Java"
] | 7 | Java | soolaugust/design-pattern-demo | f72c079a2da9f75a3faba839f2608894bd747c38 | 24a3e8bcfd4cc77ffd057b35ab19b7d7bb91ad46 |
refs/heads/master | <repo_name>Giffee/DiplomaProject<file_sep>/app/src/main/java/com/sergey_kost/diploma/diplomaproject/HelpActivity.java
package com.sergey_kost.diploma.diplomaproject;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MenuItem;
import android.widget.TextView;
public class HelpActivity extends AppCompatActivity {
TextView helpDescription;
TextView helpCommands;
TextView helpCommandsExamples;
TextView helpAboutAuthor;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_help);
helpDescription = findViewById(R.id.helpDescription);
helpCommands = findViewById(R.id.helpCommands);
helpCommandsExamples = findViewById(R.id.helpCommandsExamples);
helpAboutAuthor = findViewById(R.id.helpAboutAuthor);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setHomeButtonEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(true);
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// back button clicked, go to parent activity.
this.finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
} | a29dd21723e05712456fd7e26776a7469b286948 | [
"Java"
] | 1 | Java | Giffee/DiplomaProject | 19fb85cbd9cb94fc4ab17564a5e87efeb4a1392d | f527d4eb26d98778ea4857064b0ffa36c55d25d1 |
refs/heads/gh-pages | <repo_name>mrdcs92/calculator<file_sep>/calculator.js
/*
<button> elements for the buttons, <button>7</button>
<input> element for the display
.value changes contents of the display
*/
/*global math*/
var div = document.createElement('div');
div.id = 'calculator';
document.body.appendChild(div);
var inputArea = document.createElement('input');
inputArea.id = 'inputArea';
div.appendChild(inputArea);
var buttons = ['7','8','9','+','4','5','6','-','1','2','3','*','0','.','C','/','(',')','Del','='];
buttons.forEach(makeButton);
function makeButton(text) {
var button = document.createElement('button');
button.id = 'button' + text;
button.textContent = text;
div.appendChild(button);
button.addEventListener("click", buttonPress, false);
}
function buttonPress(event) {
var buttonValue = event.target.textContent;
var inputArea = document.getElementById('inputArea');
switch (buttonValue) {
case '=':
inputArea.value = math.eval(inputArea.value);
break;
case 'Del':
var length = ((inputArea.value).length);
inputArea.value = (inputArea.value).substring(0, length-1);
break;
case 'C':
inputArea.value = '';
break;
default:
if ((buttonValue) === '+' || (buttonValue) === '-' || (buttonValue) === '*' || (buttonValue) === '/') {
(inputArea.value) += ' ' + (buttonValue) + ' ';
}
else {
(inputArea.value) += (buttonValue);
}
}
} | 3e73a580078eea4b0855bb8891d4a95749c81b38 | [
"JavaScript"
] | 1 | JavaScript | mrdcs92/calculator | fcc5df5ad197e3b3df1e95df85e996f617a44ce6 | ee41c8ecb65328527a1e99e56dabc4d00d01e025 |
refs/heads/master | <repo_name>ntkathole/testblame<file_sep>/setup.py
from setuptools import setup
setup(
name='TestBlame',
version="0.1",
description="collect the failed tests from junit report and send across report based on there commit history",
author="<NAME>",
author_email="<EMAIL>",
py_module=['testblame'],
install_requires=[
'Click',
],
entry_points='''
[console_scripts]
testblame=testblame:cli
''',
)
<file_sep>/setup.sh
#! /bin/bash
echo "export SENDGRID_API_KEY='<KEY>'" > sendgrid.env
echo "sendgrid.env" >> .gitignore
source ./sendgrid.env
pip install -r requirements.txt
pip install --editable .
echo "Test Blame Installed Successfully!"
| ae4c7f2bef3c7b419cf12e6d2d117e17437b3a28 | [
"Python",
"Shell"
] | 2 | Python | ntkathole/testblame | 6e9fcac9c47f3867da48dcf7ee9e5ab990338970 | 82587891722ee5dd431c90a8cf5bb25fb8f69371 |
refs/heads/master | <repo_name>Mehigh17/ImageMatcher<file_sep>/src/main/tests/ImageDataProviderTest.java
package main.tests;
import javafx.scene.image.Image;
import main.services.ImageDataProvider;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
import java.util.HashMap;
import static org.junit.jupiter.api.Assertions.*;
class ImageDataProviderTest {
private ImageDataProvider _imgDataProvider = new ImageDataProvider();
@Test
public void GetGrayscaleDistance_TwoDistributionsGiven_Pass() {
var dist1 = new HashMap<Integer, Integer>(){{
put(0, 10);
put(3, 50);
put(5, 25);
}};
var dist2 = new HashMap<Integer, Integer>(){{
put(0, 3);
put(4, 20);
put(5, 10);
}};
var distance = _imgDataProvider.getGrayscaleDistance(dist1, dist2);
assertEquals(distance, 92);
}
@Test
public void GetGrayscaleDistribution_NulImageGiven_ThrowException() {
assertThrows(Exception.class, () -> _imgDataProvider.getGrayscaleDistribution(null));
}
/**
* A JavaFX runtime instance has to be initialized before test which is cumbersome so don't do this explicitly here.
* TODO: Implement TestFX library (https://github.com/TestFX/TestFX)
*/
@Test
public void GetGrayscaleDistribution_ValidImageGiven_Pass(){
var image = new Image("file:files/testImage1.png");
// ... rest of the test here
}
}<file_sep>/src/main/controllers/MainController.java
package main.controllers;
import javafx.fxml.FXML;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.image.Image;
import javafx.stage.DirectoryChooser;
import javafx.stage.FileChooser;
import main.services.ImageComparator;
import main.services.ImageDataProvider;
import javax.xml.transform.Result;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.TreeMap;
public class MainController {
@FXML
private Button selectFileButton;
@FXML
private Button selectDirectoryButton;
@FXML
private Button computeButton;
private ImageDataProvider _imageDataProvider;
private ImageComparator _comparator;
private Image _selectedImage;
private List<Image> _loadedImages;
public MainController() {
_imageDataProvider = new ImageDataProvider();
_comparator = new ImageComparator(_imageDataProvider);
_loadedImages = new ArrayList<>();
}
public void bttDirectoryClicked() {
var dirChooser = new DirectoryChooser();
dirChooser.setTitle("Path to Images");
var dir = dirChooser.showDialog(null);
if(dir != null && dir.isDirectory() && dir.exists())
{
_loadedImages.clear();
for (File file : dir.listFiles()) {
var img = new Image(String.format("file:%s", file.getAbsolutePath()));
if(!img.isError())
_loadedImages.add(img);
}
}
}
public void bttFileClicked() {
var fileChooser = new FileChooser();
fileChooser.getExtensionFilters().addAll(
new FileChooser.ExtensionFilter("All Images", "*.*"),
new FileChooser.ExtensionFilter("PNG", "*.png"),
new FileChooser.ExtensionFilter("JPG", "*.jpg")
);
fileChooser.setTitle("Open Reference Image");
var file = fileChooser.showOpenDialog(null);
if(file == null || !file.exists())
return;
var fileProtocol = String.format("file:%s", file.getAbsolutePath());
var image = new Image(fileProtocol);
_selectedImage = image;
HashMap<Integer, Integer> distribution;
try {
distribution = _imageDataProvider.getGrayscaleDistribution(image);
} catch (Exception e) {
popError("Couldn't load the grayscale distribution for the reference image.");
return;
}
ResultsController.Instance.updateBarChart(distribution, file);
}
public void bttComputeClicked() {
if(_selectedImage == null) {
popError("Please select a reference image.");
} else if(_loadedImages.isEmpty()) {
popError("Please select a directory containing images to compare to.");
} else {
TreeMap<Integer, Image> imageDistances;
try {
imageDistances = _comparator.getImageDistances(_selectedImage, _loadedImages);
} catch (Exception e) {
popError("Couldn't compute grayscale distance for the selected images.");
return;
}
ResultsController.Instance.updateDistanceResults(imageDistances);
Image closestImage;
try {
closestImage = _comparator.getClosestImage(_selectedImage, _loadedImages);
} catch (Exception e) {
popError("Couldn't fetch the closest image to the reference image.");
return;
}
//closestImageView.setImage(closestImage);
}
}
private void popError(String message) {
var alert = new Alert(Alert.AlertType.ERROR);
alert.setTitle("Error");
alert.setHeaderText("An error occurred!");
alert.setContentText(message);
alert.showAndWait();
}
}
<file_sep>/README.md
# Image Matcher
## Description
The mechanism of this project is simple.
It gives you the closest image to your reference image by calculating an **absolute grayscale distance** to the reference.
The difference from a **normalized grayscale distance** it that pixel count cannot influence the final comparison while the absolute distance can give you significantly different results from what you expect. *(the normalized image computation is to be implemented later in the project)*
Before calculating the grayscale distance, the images are transformed into a dictionary of 256 sets, with the key being the grayscale opacity and the value of the set being the number of occurrences of that grayscale value.
### Grayscale distance formula

## Preview

<file_sep>/src/main/controllers/ResultsController.java
package main.controllers;
import javafx.collections.FXCollections;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.chart.BarChart;
import javafx.scene.chart.XYChart;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import main.models.ResultModel;
import java.io.File;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.ResourceBundle;
import java.util.TreeMap;
public class ResultsController implements Initializable {
/**
* This method is a placeholder until the DI container is implemented
* TODO: Implement a MessageBus through an IoC container
*/
public static ResultsController Instance; // To be removed
@FXML
private BarChart barChart;
@FXML
private ImageView referenceImageView;
@FXML
private TableView<ResultModel> resultData;
@FXML
private TableColumn<ResultModel, String> filePath;
@FXML
private TableColumn<ResultModel, Integer> distance;
@Override
public void initialize(URL url, ResourceBundle resourceBundle) {
Instance = this; // To be removed
filePath.setCellValueFactory(new PropertyValueFactory<>("FilePath"));
distance.setCellValueFactory(new PropertyValueFactory<>("Distance"));
}
public void updateBarChart(HashMap<Integer, Integer> refDistr, File refFile) {
var series = new XYChart.Series();
refDistr.forEach((k, v) -> {
series.getData().add(new XYChart.Data(String.format("%s", k), v));
});
barChart.setData(FXCollections.observableArrayList(series));
var chartTitle = String.format("Grayscale distribution for '%s'", refFile.getName());
barChart.setTitle(chartTitle);
}
public void updateDistanceResults(TreeMap<Integer, Image> distances) {
var list = new ArrayList<ResultModel>();
distances.forEach((k, v) -> {
list.add(new ResultModel(v.getUrl(), k));
});
resultData.setItems(FXCollections.observableArrayList(list));
referenceImageView.setImage(distances.get(distances.firstKey()));
}
}
<file_sep>/src/main/utils/ColorHelper.java
package main.utils;
import javafx.scene.paint.Color;
public final class ColorHelper {
public static int getGrayscale(Color color) {
return (int) (((color.getRed() + color.getGreen() + color.getBlue()) / 3.0) * 255);
}
}
| f5b565406025ee301adf8dd851a7228474b72827 | [
"Markdown",
"Java"
] | 5 | Java | Mehigh17/ImageMatcher | 62f9445afab395b98facdf76de2969b6b565ce41 | 6ff8ea1ecf96d593d5466b75980899ec3cc9f7ae |
refs/heads/develop | <file_sep>'use strict'
const PIPELINE_CONFIGS = 'pipeline_configs'
let execPipeline = require('../../core/pipelines/execute-pipeline-command')
let query = require('../../db/queries')
let success = require('../utils/responses/success')
let created = require('../utils/responses/created')
let error = require('../utils/responses/error')
module.exports = {
/**
* Sends a list of pipelines
*
* @param req
* @param res
*/
getList: (req, res) => {
query.all(PIPELINE_CONFIGS)
.then(success.bind(res))
.catch(error.bind(res))
},
/**
* Get a single pipeline config
*
* @param req
* @param res
*/
getPipeline: (req, res) => {
query.first(req.params.id, PIPELINE_CONFIGS)
.then(success.bind(res))
.catch(error.bind(res))
},
/**
* Create a pipeline
*
* @param req
* @param res
*/
createPipeline: (req, res) => {
query.insert(req.body, PIPELINE_CONFIGS)
.then(id => {
query.first(id, PIPELINE_CONFIGS)
.then(created.bind(res))
.catch(error.bind(res))
})
.catch(error.bind(res))
},
/**
* Start a new pipeline execution
*
* @param req
* @param res
*/
executePipeline: (req, res) => {
try {
const PIPELINE_ID = req.params.id
const USER_ID = req.user.id
const PARAMS = req.body
const CALLBACK = (id) => {
success.call(res, {
data: {
pipeline_execution_id: id
}
})
}
let options = {
input: PARAMS,
userId: USER_ID
}
execPipeline(PIPELINE_ID, options, CALLBACK)
} catch (err) {
error.call(res, err)
}
}
}
<file_sep>export default ['$scope', '$http', '$uibModalInstance', 'data', function($scope, $http, $uibModalInstance, data) {
$scope.form = {
name: ''
}
$http.get('/api/projects').then(response => {
$scope.projects = response.data.data
// If there was pre-filled data provided, use the project_id
if (typeof data !== 'undefined' && typeof data.project_id !== 'undefined') {
$scope.form.project_id = data.project_id.toString()
} /*else {
// Otherwise, use the first project as the selected one
$scope.form.project_id = $scope.projects[0].id.toString()
}*/
})
$scope.ok = () => {
$http
.post('/api/pipelines', {
project_id: $scope.form.project_id,
name: $scope.form.name
})
.then(res => {
$uibModalInstance.close(res.data.data)
})
}
$scope.cancel = () => $uibModalInstance.dismiss('cancel')
}]
<file_sep>import angular from 'angular'
import 'angular-ui-bootstrap'
import 'angular-ui-router'
import 'angular-moment'
import 'angular-socket-io'
import routerAdder from './helpers/add-route'
import authInterceptor from './helpers/auth-interceptor'
import controllers from './controllers'
const app = angular.module('mission-control', [
'ui.router',
'ui.bootstrap',
'angularMoment',
'btford.socket-io'
])
const addRoute = routerAdder(app)
// Configure router with default route
app.config(['$urlRouterProvider', ($urlRouterProvider) => {
// For any unmatched url, redirect to /dashboard
$urlRouterProvider.otherwise('/dashboard')
}])
// Configure default $http request options and catch 401s with interceptor
app.config(['$httpProvider', ($httpProvider) => {
// Automatically send credentials (cookies)
$httpProvider.defaults.withCredentials = true
// Register $http middleware/"interceptor" for re-authenticating
$httpProvider.interceptors.push(authInterceptor)
}])
// Configure socket-io
app.factory('socket', ['socketFactory', function(socketFactory) {
return socketFactory({
ioSocket: io.connect() // using this syntax here in case we need to set options for socket.io later
})
}])
// Provide filter for using "unsafe" html
app.filter('unsafe', ['$sce', function($sce) {
return function(input) { return $sce.trustAsHtml(input) }
}])
// Provide quick way to check key length for an object
app.filter('keysLength', function() {
return function(input) { return Object.keys(input).length }
})
app.run(controllers.socketManager)
app.run(controllers.user)
app.run(controllers.login)
app.run(controllers.modals)
app.run(controllers.helpers)
// Routes
addRoute('dashboard', '/dashboard', 'dashboard.html', controllers.dashboard)
addRoute('projects', '/projects', 'projects.html', controllers.projects)
// addRoute('project', '/project/:project', '/project/project.html', controllers.project)
addRoute('pipelines', '/pipelines', 'pipelines.html', controllers.pipelines)
addRoute('pipeline-execution-details', '/pipelines/executions/{id}', 'pipeline-execution-details.html', controllers.pipelineExecutionDetails)
addRoute('pipeline', '/pipelines/{id}', 'pipeline.html', controllers.pipeline)
addRoute('configure-pipeline', '/pipelines/{id}/configure', 'configure-pipeline.html', controllers.configurePipeline)
addRoute('health', '/health', 'health.html', controllers.health)
addRoute('applications', '/resources/applications', '/resources/applications.html', controllers.applications)
addRoute('application-builds', '/resources/application-builds', '/resources/application-builds.html', controllers.applicationBuilds)
addRoute('servers', '/resources/servers', '/resources/servers.html', controllers.servers)
addRoute('files', '/resources/files', '/resources/files.html', controllers.files)
addRoute('credentials', '/resources/credentials', '/resources/credentials.html', controllers.credentials)
addRoute('github-repositories', '/resources/github-repositories', '/resources/github-repositories.html', controllers.githubRepositories)
addRoute('configuration', '/settings/general/configuration', '/settings/general/configuration.html', controllers.configuration)
addRoute('users', '/settings/general/users', '/settings/general/users.html', controllers.users)
addRoute('slack', '/settings/notifications/slack', '/settings/notifications/slack.html', controllers.slack)
addRoute('email', '/settings/notifications/email', '/settings/notifications/email.html', controllers.email)
| c38052144a334a47276cae548da64d589a8312d5 | [
"JavaScript"
] | 3 | JavaScript | nater1067/mc-core | 728feeaa109f80af78f81e990ce5c974d4d22f3e | 0fb01269f2965d50b50e6b61ecaf0931d9b9e2c6 |
refs/heads/master | <repo_name>Guolewen/Sreedhar2011<file_sep>/table1.py
import pandas as pd
from collections import Counter
import time
import numpy as np
facility = pd.read_csv(r'D:\wooldride_econometrics\paper_liq_replicating\Sreedhar\data\facility.csv')
facilitydates = pd.read_csv(r'D:\wooldride_econometrics\paper_liq_replicating\Sreedhar\data\facilitydates.csv')
facilitysponsor = pd.read_csv(r'D:\wooldride_econometrics\paper_liq_replicating\Sreedhar\data\facilitysponsor.csv')
lendershares = pd.read_csv(r'D:\wooldride_econometrics\paper_liq_replicating\Sreedhar\data\lendershares.csv')
company = pd.read_csv(r'D:\wooldride_econometrics\paper_liq_replicating\Sreedhar\data\company.csv')
currfacpricing = pd.read_csv(r'D:\wooldride_econometrics\paper_liq_replicating\Sreedhar\data\currfacpricing.csv')
performancepricing = pd.read_csv(r'D:\wooldride_econometrics\paper_liq_replicating\Sreedhar\data\performancepricing.csv')
def classify_lead_bank(x, **kwargs):
if x['LenderRole'] in kwargs['lendroles'] and x['BankAllocation'] > 25:
return 1
elif x['LenderRole'] == 'Sole Lender':
return 1
elif x['LeadArrangerCredit'] == 'Yes':
return 1
else:
return 0
def deal_fees(currfacpricing):
def upfront_fee(x):
queried_upfront = x[x['Fee'] == 'Upfront Fee']
queried_annual = x[x['Fee'] == 'Annual Fee']
if queried_upfront.empty and queried_annual.empty:
return [np.NaN, np.NaN]
elif len(queried_upfront) == 1 and queried_annual.empty:
return [np.float64(queried_upfront['MaxBps']), np.NaN]
elif len(queried_annual) == 1 and queried_upfront.empty:
return [np.NaN, np.float64(queried_annual['MaxBps'])]
elif len(queried_upfront) == 1 and len(queried_annual) == 1:
return [np.float64(queried_upfront['MaxBps']), np.float64(queried_annual['MaxBps'])]
else:
return None
drop_dup = currfacpricing.drop_duplicates(subset='FacilityID').reset_index(drop=True)
drop_dup[['UpfrontFee', 'AnnualFee']] = pd.DataFrame(currfacpricing.groupby(['FacilityID']).apply(upfront_fee).to_list())
return drop_dup
def assign_lead_bank(lendershares):
lendershares['LeadBankIndicator'] = lendershares[['LenderRole', 'BankAllocation', 'LeadArrangerCredit']].apply(classify_lead_bank, axis=1,
lendroles=['Agent', 'Admin agent', 'Arranger'
, 'Lead bank'])
return lendershares
def merge_facility_with_lendshares(facility, lendershares, fee_df):
merged_df = facility.merge(lendershares[['FacilityID', 'LenderRole', 'BankAllocation', 'Lender',
'LeadArrangerCredit', 'LeadBankIndicator']], how='left', on='FacilityID')
merged_df = fee_df[['FacilityID', 'AllInDrawn', 'AllInUndrawn', 'UpfrontFee', 'AnnualFee']].merge(merged_df, how='left', on="FacilityID")
usa = merged_df[(merged_df['CountryOfSyndication'] == 'USA') & (merged_df['LeadBankIndicator']==1)]
timeperiod = usa[(usa['FacilityStartDate'] > 19860100) & (usa['FacilityStartDate'] < 20040100)].reset_index(drop=True)
# merge the company and delete firms with SICCode starting with 6
comp_merged = timeperiod.merge(company[['CompanyID', 'PrimarySICCode']], how='left', left_on='BorrowerCompanyID',
right_on='CompanyID')
sample = comp_merged[(comp_merged['PrimarySICCode'] < 6000) | (comp_merged['PrimarySICCode'] >= 7000)].reset_index(drop=True)
return sample
def calculate_relation_variables(sample):
def calculate_rels(x, **kwargs):
print('f id', x['FacilityID'])
borrower_id = x['BorrowerCompanyID']
lender = x['Lender']
begin = x['FacilityStartDate'] - 50000
end = x['FacilityStartDate'] - 1
sample = kwargs['sample']
# query through the whole sample to find out the borrowers' previous 5 year records
queried_sample = sample[(sample['BorrowerCompanyID'] == borrower_id) & (sample['FacilityStartDate'] >= begin) &
(sample['FacilityStartDate'] <= end)]
if queried_sample.empty:
return [0, 0, 0]
else:
same_lender = queried_sample[queried_sample['Lender'] == lender]
if same_lender.empty:
return [0, 0, 0]
else:
rel_amount = same_lender['FacilityAmt'].sum() / queried_sample['FacilityAmt'].sum()
rel_number = len(same_lender) / len(queried_sample)
return [1, rel_amount, rel_number]
sample[['REL_Dummy', 'REL_Amount', 'REL_Number']] = sample.apply(calculate_rels, axis=1, result_type='expand', sample=sample)
final = sample.drop_duplicates(subset=['FacilityID']).reset_index(drop=True)
# assign the highest values to REL variables
final['REL_Dummy'] = sample.groupby(['FacilityID'])['REL_Dummy'].max().reset_index(drop=True)
final['REL_Amount'] = sample.groupby(['FacilityID'])['REL_Amount'].max().reset_index(drop=True)
final['REL_Number'] = sample.groupby(['FacilityID'])['REL_Number'].max().reset_index(drop=True)
return final
def panel_a(final):
final['Year'] = final['FacilityStartDate'].apply(lambda x: str(x)[0:4])
panel_a = final.groupby(['Year', 'REL_Dummy']).size().unstack(level=-1)
panel_a['Total'] = panel_a[0.0] + panel_a[1.0]
panel_a = panel_a.append(panel_a.sum().rename("Total").to_frame().transpose())
return panel_a
def panel_b(final):
def extractsic(x):
number = int(x)
if number < 1000:
return '0'
else:
return str(number)[0]
final['FirstSCICode'] = final['PrimarySICCode'].apply(extractsic)
panel_b = final.groupby(['FirstSCICode', 'REL_Dummy']).size().unstack(level=-1)
panel_b['Total'] = panel_b[0.0] + panel_b[1.0]
panel_b = panel_b.append(panel_b.sum().rename("Total").to_frame().transpose())
return panel_b
def panel_c(final):
panel_c = final.groupby(['PrimaryPurpose', 'REL_Dummy']).size().unstack(level=-1)
panel_c = panel_c.fillna(0)
panel_c['Total'] = panel_c[0.0] + panel_c[1.0]
panel_c = panel_c.append(panel_c.sum().rename("Total").to_frame().transpose())
return panel_c
if __name__ == '__main__':
t1 = time.time()
fees = deal_fees(currfacpricing)
assigned_df = assign_lead_bank(lendershares)
sample = merge_facility_with_lendshares(facility, assigned_df, fees)
final = calculate_relation_variables(sample)
print(panel_a(final))
print(panel_b(final))
print(panel_c(final))
t2 = time.time()
print("Total Runtime is", t2 - t1)
"""
Panel A
REL_Dummy 0.0 1.0 Total
1986 96 2 98
1987 805 53 858
1988 1678 254 1932
1989 1488 384 1872
1990 1170 476 1646
1991 1072 473 1545
1992 1235 545 1780
1993 1551 665 2216
1994 1780 949 2729
1995 1690 967 2657
1996 2550 1096 3646
1997 3414 1421 4835
1998 2661 1091 3752
1999 3201 1082 4283
2000 2846 1464 4310
2001 2475 1226 3701
2002 2653 1107 3760
2003 2729 1323 4052
Total 35094 14578 49672
Panel B
REL_Dummy 0.0 1.0 Total
0 193 69 262
1 2516 1073 3589
2 5745 2489 8234
3 9414 3633 13047
4 5132 2587 7719
5 5385 2124 7509
7 4290 1633 5923
8 2352 960 3312
9 67 10 77
Total 35094 14578 49672
Panel C
REL_Dummy 0.0 1.0 Total
Acquis. line 2172.0 695.0 2867.0
CP backup 1093.0 1386.0 2479.0
Capital expend. 84.0 22.0 106.0
Corp. purposes 9732.0 3723.0 13455.0
Cred Enhanc 42.0 27.0 69.0
Debt Repay. 6856.0 3723.0 10579.0
Debtor-in-poss. 269.0 187.0 456.0
ESOP 84.0 21.0 105.0
Equip. Purch. 170.0 45.0 215.0
Exit financing 29.0 24.0 53.0
IPO Relat. Finan. 52.0 12.0 64.0
LBO 2565.0 384.0 2949.0
Lease finance 13.0 4.0 17.0
Mort. Warehse. 6.0 1.0 7.0
Other 413.0 200.0 613.0
Proj. finance 508.0 92.0 600.0
Purch. Hardware 1.0 1.0 2.0
Purch. Software/Servs. 1.0 0.0 1.0
Real estate 184.0 50.0 234.0
Rec. Prog. 20.0 7.0 27.0
Recap. 1069.0 347.0 1416.0
Securities Purchase 61.0 15.0 76.0
Ship finance 2.0 0.0 2.0
Spinoff 291.0 48.0 339.0
Stock buyback 215.0 64.0 279.0
Takeover 3513.0 1636.0 5149.0
TelcomBuildout 56.0 28.0 84.0
Trade finance 40.0 12.0 52.0
Undisclosed 3.0 0.0 3.0
Work. cap. 5550.0 1824.0 7374.0
Total 35094.0 14578.0 49672.0
Total Runtime is 250.94556164741516
""" | 4d04e3ea1bd2f00e3367a00392bb0a84189fbaf0 | [
"Python"
] | 1 | Python | Guolewen/Sreedhar2011 | 44fa9fa6fe4452d9447168d7131db03ae11eade2 | 56f37b523cb7d79fce890e6b912627d1301533dd |
refs/heads/master | <repo_name>felixlberg/nativescript-app<file_sep>/src/app/web/web.component.ts
import { Component } from "@angular/core";
import { Page } from "tns-core-modules/ui/page";
@Component({
moduleId: module.id,
templateUrl: "./web.component.html",
})
export class WebComponent {
public webViewSrc: string = "https://www.google.com";
}
<file_sep>/CHNGELOG.md
# Changelog
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [Unreleased]
### Added
- Dynamic implementations in web.component of website URLs in home.component.html
## [0.0.2] - 2018-10-13
### Added
- Home Component
- Test Component
- Web View Component
- Image Routing
### Fixed
- Wrong Image Path
## [0.0.1] - 2018-10-22
### Added
- Added tns-template-blank-ng (Initial commit)
<file_sep>/src/app/home/home.component.ts
import { Component, OnInit } from "@angular/core";
import { Router, NavigationExtras } from "@angular/router";
import { alert, confirm, prompt, login, action, inputType } from "tns-core-modules/ui/dialogs";
import { EventData } from "tns-core-modules/data/observable";
@Component({
selector: "Home",
moduleId: module.id,
templateUrl: "./home.component.html",
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
ngOnInit(): void { }
}
<file_sep>/src/app/test/test.module.ts
import { NgModule, NO_ERRORS_SCHEMA } from "@angular/core";
import { NativeScriptCommonModule } from "nativescript-angular/common";
import { TestRoutingModule } from "./test-routing.module";
import { TestComponent } from "./test.component";
@NgModule({
imports: [
NativeScriptCommonModule,
TestRoutingModule
],
declarations: [
TestComponent
],
schemas: [
NO_ERRORS_SCHEMA
]
})
export class TestModule { }
| de9be957fcd8235f2dd1e66e9e5e6ebd862fc823 | [
"Markdown",
"TypeScript"
] | 4 | TypeScript | felixlberg/nativescript-app | c7466ee81aafc98a92ed4482b03577137d52855e | 501fbc78c9664cb7315c8cd1553016def554e93b |
refs/heads/main | <file_sep>import React from 'react';
import {View,Image} from 'react-native';
const Webstep = () => (
<Image source={require('../assets/wtlogo.png')}
style={{width:150,height:70}}
/>
)
export default Webstep<file_sep>import React from 'react';
import {View,Image} from 'react-native';
const Shadow = () => (
<Image source={require('../assets/logo.png')}
style={{width:40,height:20}}
/>
)
export default Shadow | 2e8ce2de4dcdd5f42045ba00b784a1b4fb47b3d3 | [
"JavaScript"
] | 2 | JavaScript | sujoy21198/Team | 11cf63733d5e491b2a4d27b34b77076e51ac153c | 1c6f122861c716fab63fbb80fce7a5b1b5ace51c |
refs/heads/master | <repo_name>jesp209i/ParkingLotSystem<file_sep>/BusinessLogic/IParkingLot.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BusinessLogic
{
public interface IParkingLot
{
void ParkingACar(Car car);
void ParkedCarLeaving(Car car);
Car FindCar(Car car);
IReadOnlyList<Car> AllCars();
}
}
<file_sep>/README.md
# ParkingLotSystem
3. sem Teknik opgave om tråde
<file_sep>/ParkingLotSystem/Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BusinessLogic;
namespace ParkingLotSystem
{
class Program
{
static void Main(string[] args)
{
List<Car> cars = new List<Car> {
new Car("BE 30393"),
new Car("DE 10191"),
new Car("BH 34567"),
new Car("AB 12345"),
new Car("CD 23456")};
IParkingLot p = new ParkingLot();
foreach (Car c in cars)
{
p.ParkingACar(c);
p.FindCar(c);
p.AllCars();
p.ParkedCarLeaving(c);
p.FindCar(c);
}
}
}
}
<file_sep>/BusinessLogic/Car.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BusinessLogic
{
public class Car
{
public string RegNo { get; set; }
public Car(string regNo)
{
RegNo = regNo;
}
}
}
<file_sep>/BusinessLogic/ParkingLot.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BusinessLogic
{
public class ParkingLot : IParkingLot
{
public List<Car> ParkedCars { get; set; }
private static object parkingLotLock = new object();
public ParkingLot()
{
ParkedCars = new List<Car>();
}
public void ParkingACar(Car parkingCar)
{
lock(parkingLotLock)
{
ParkedCars.Add(parkingCar);
Console.WriteLine("Bilen {0} er ankommet til parkeringspladsen", parkingCar.RegNo);
}
}
public void ParkedCarLeaving(Car parkedCar)
{
lock (parkingLotLock)
{
ParkedCars.Remove(parkedCar);
Console.WriteLine("Bilen {0} forlader parkeringspladsen", parkedCar.RegNo);
}
}
public IReadOnlyList<Car> AllCars()
{
lock (parkingLotLock) {
Console.WriteLine("følgende biler findes på parkeringspladsen lige nu:");
foreach(Car c in ParkedCars)
{
Console.WriteLine("\t - {0}", c.RegNo);
}
return ParkedCars;
}
}
public Car FindCar(Car car)
{
Car resultCar = null;
if (ParkedCars.Contains(car))
{
resultCar = car;
Console.WriteLine("Bilen {0} findes på pladsen", car.RegNo);
}
else
{
Console.WriteLine("{0} findes ikke på pladsen", car.RegNo);
}
return resultCar;
}
}
}
| 3dc731f8fba4f6997c5c3ddea027e980de36a083 | [
"Markdown",
"C#"
] | 5 | C# | jesp209i/ParkingLotSystem | fd297c6e604cdc3d80ea6f89ef5903563e2c832b | 55e42262355d298f7e3436b0657de5569564f260 |
refs/heads/master | <repo_name>fgpayano/laravel_teachme<file_sep>/app/Http/Controllers/TicketsController.php
<?php namespace App\Http\Controllers;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Entities\Ticket;
use App\Entities\TicketComment;
use Illuminate\Auth\Guard;
use Illuminate\Routing\Redirector;
class TicketsController extends Controller {
private $request = null;
private $auth = null;
private $redirect = null;
public function __construct(Request $request, Guard $auth, Redirector $redirect)
{
$this->request = $request;
$this->auth = $auth;
$this->redirect = $redirect;
}
public function latest()
{
$tickets = Ticket::orderBy('created_at', 'DESC')->paginate(10);
return view('tickets/list', compact('tickets'));
}
public function popular()
{
dd('popular');
}
public function open()
{
dd('open');
}
public function closed()
{
dd('closed');
}
public function details($id)
{
$ticket = Ticket::findOrFail($id);
return view('tickets/details', compact('ticket'));
}
public function create()
{
return view('tickets.create');
}
public function store()
{
$this->validate($this->request, [
'title' => 'required|max:100'
]);
$ticket = $this->auth->user()->tickets()->create([
'title' => $this->request->get('title'),
'status' => 'open'
]);
return $this->redirect->route('tickets.details', $ticket->id);
}
}
<file_sep>/app/Http/Controllers/CommentsController.php
<?php namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use App\Entities\TicketComment;
use App\Entities\Ticket;
use Illuminate\Http\Request;
use Illuminate\Auth\Guard;
use App\Http\Requests;
class CommentsController extends Controller {
public function submit($id, Request $request, Guard $auth)
{
$this->validate($request, [
'comment' => 'required|max:250',
'website' => 'url'
]);
$comment = new TicketComment($request->all());
$comment->user_id = $auth->id();
$ticket = Ticket::findOrfail($id);
$ticket->comments()->save($comment);
session()->flash('success', 'Tu comentario fue guardado exitosamente');
return redirect()->back();
}
}
<file_sep>/app/Entities/Entity.php
<?php
namespace App\Entities;
use Illuminate\Database\Eloquent\Model;
class Entity extends Model
{
public static function getClass()
{
$class = get_class(new static);
return $class;
}
}<file_sep>/database/seeds/UserTableSeeder.php
<?php
use App\Entities\User;
use Faker\Factory as Faker;
use Faker\Generator;
class UserTableSeeder extends BaseSeeder {
public function __construct()
{
$this->createAdmin();
}
public function getModel()
{
return new User();
}
public function getDummyData(Generator $faker)
{
return [
"name" => $faker->name,
"email" => $faker->email,
"password" => bcrypt("<PASSWORD>")
];
}
private function createAdmin()
{
$this->create([
"name" => "<NAME>",
"email" => "<EMAIL>",
"password" => bcrypt("<PASSWORD>")
]);
}
} <file_sep>/database/seeds/TicketTableSeeder.php
<?php
use App\Entities\Ticket;
use Faker\Factory as Faker;
use Faker\Generator;
class TicketTableSeeder extends BaseSeeder {
protected $total = 100;
public function getModel()
{
return new Ticket();
}
public function getDummyData(Generator $faker)
{
return [
"title" => $faker->sentence(),
"status" => $faker->randomElement(["open", "closed"]),
"user_id" => $this->getRandomId("User")
];
}
}<file_sep>/app/Components/HtmlBuilder.php
<?php
namespace App\Components;
use Collective\Html\HtmlBuilder as CollectiveHtmlBuilder;
use Illuminate\View\Factory as View;
use Illuminate\Config\Repository as Config;
use Illuminate\Routing\UrlGenerator;
class HtmlBuilder extends CollectiveHtmlBuilder{
private $view;
private $config;
protected $url;
public function __construct(UrlGenerator $url, View $view, Config $config)
{
$this->view = $view;
$this->config = $config;
$this->url = $url;
}
public function menu($arrElements)
{
if (! is_array($arrElements))
{
$arrElements = $this->config->get($arrElements);
}
return $this->view->make('partials/menu', compact('arrElements'));
}
public function doActiveClass ($className = "", $value = "")
{
}
}<file_sep>/app/Http/Controllers/VotesController.php
<?php namespace App\Http\Controllers;
use App\Http\Requests;
use App\Entities\Ticket;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class VotesController extends Controller {
public function submit($id)
{
$ticket = Ticket::findOrFail($id);
currentUser()->vote($ticket);
return redirect()->back();
}
public function destroy($id)
{
$ticket = Ticket::findOrFail($id);
currentUser()->unvote($ticket);
return redirect()->back();
}
}
<file_sep>/database/seeds/TicketVoteTableSeeder.php
<?php
use App\Entities\TicketVote;
use Faker\Factory as Faker;
use Faker\Generator;
class TicketVoteTableSeeder extends BaseSeeder {
public function getModel()
{
return new TicketVote();
}
public function getDummyData(Generator $faker)
{
return [
"ticket_id" => $this->getRandomId("Ticket"),
"user_id" => $this->getRandomId("User")
];
}
}<file_sep>/database/seeds/TicketCommentTableSeeder.php
<?php
use App\Entities\TicketComment;
use Faker\Factory as Faker;
use Faker\Generator;
class TicketCommentTableSeeder extends BaseSeeder {
public function getModel()
{
return new TicketComment();
}
public function getDummyData(Generator $faker)
{
return [
"website" => $faker->url(),
"comment" => $faker->paragraph(),
"user_id" => $this->getRandomId("User"),
"ticket_id" => $this->getRandomId("Ticket")
];
}
} | f5d164a2863fe34be06f7b25201f931a9bb9919f | [
"PHP"
] | 9 | PHP | fgpayano/laravel_teachme | 1489aaf6953deb807728a95d961b62a3a83bfd88 | f0f48760dab516b58284552ae9952581841cf70a |
refs/heads/master | <file_sep>export PATH="$PATH:/root/vendor/bin"
<file_sep># docker-php
A Dockerfile that installs an Nginx / PHP-FPM based environment that also contains Solr 4, MariaDB, Redis, ElasticSearch and MailHog.
## Usage
### Install the common instances (MariaDB and Mailhog)
```bash
$ docker pull mariadb
$ docker run --name mariadb -e MYSQL_ROOT_PASSWORD=<PASSWORD> -p 3307:3306 -d mariadb:latest
$ docker pull mailhog/mailhog
$ docker run -d -p 8025:8025 -p 1080:8025 --name mailhog mailhog/mailhog
```
### Build docker-php
Navigate to docker-php directory and run the build script.
```bash
$ docker build -t="citrussolutions/docker-php" .
```
### Launch the containers with Docker-compose
With docker-compose you can easily configure the necessary settings for each site. This is done by copying the docker-compose.yml in this directory to your project root and checking the PLATFORM and port settings.
The port settings are defined for each project separately to expose necessary services to the host so that all the sites could technically be on simulatenously. The first HTTP port should be 8080, SSH port 2220, Solr port 8980 and ElasticSearch port 9200. It is advisable to assign the ports company-wide to allow easier co-operation.
You also need to add your public SSH key as the environment variable SSH_PUBLIC_KEY to either the docker_compose.yml file itself or as ~/docker.env.
After that, just run docker-compose up and it should work.
However, you always need to manually start the common containers:
```bash
$ docker start mariadb mailhog
```
### Logging in
Usually there should be no need to login to the Docker instance – all coding and Drush usage should happen on the host.
```
$ docker exec -it projectname_web_1 bash
```
In addition to a specified name, you can log in using the ID you can fetch with docker ps.
### Restarting services
If you need to change the service configs, you can restart nginx / php5-fpm with the following (after logging in):
```
$ supervisorctl restart nginx
```
<file_sep>#!/bin/bash
# Choose the correct configs based on env
rm /etc/nginx/sites-enabled/default
if [ "$PLATFORM" = "drupal" ] ; then
ln -s /etc/nginx/sites-available/drupal.conf /etc/nginx/sites-enabled
elif [ "$PLATFORM" = "livehelperchat" ] ; then
ln -s /etc/nginx/sites-available/livehelperchat.conf /etc/nginx/sites-enabled
elif [ "$PLATFORM" = "magento" ] ; then
ln -s /etc/nginx/sites-available/magento.conf /etc/nginx/sites-enabled
curl -o /usr/local/bin/magerun http://files.magerun.net/n98-magerun-latest.phar
chmod ugo+rx /usr/local/bin/magerun
fi
mkdir /var/run/sshd
mkdir -p /root/.ssh
chmod 700 /root/.ssh
chmod 600 /root/.ssh/*
if [ ! -z "$SSH_PUBLIC_KEY" ]; then
echo "$SSH_PUBLIC_KEY" >> ~/.ssh/authorized_keys
fi
chown -Rf root:root /root/.ssh
# configure sshd to block authentication via password
sed -i.bak 's/#PasswordAuthentication yes/PasswordAuthentication no/' /etc/ssh/sshd_config
rm /etc/ssh/sshd_config.bak
# start all the services
/usr/local/bin/supervisord -n
<file_sep>FROM debian:stable-slim
MAINTAINER <NAME> <<EMAIL>>
# Let the container know that there is no tty
ENV DEBIAN_FRONTEND noninteractive
RUN apt-get update
RUN apt-get -y upgrade
# Basic Requirements
RUN apt-get -y install mysql-client nginx php-fpm php-mysql pwgen python-setuptools curl git unzip vim-nox
# Application Requirements
RUN apt-get -y install php-curl php-gd php-intl php-pear php-imagick php-imap php-mbstring php-mcrypt php-memcache php-pspell php-recode php-tidy php-xmlrpc php-xml php-xsl php-ldap php-pgsql php-redis php-mcrypt openssh-server varnish
#postgresql-client
RUN curl -o /tmp/composer.phar https://getcomposer.org/installer
RUN cd /tmp; php ./composer.phar
RUN chmod 0755 /tmp/composer.phar
RUN mv /tmp/composer.phar /usr/local/bin/composer
RUN cd /root; composer require drush/drush "<9"
ADD ./bashrc.sh /root/.bashrc
RUN chmod 0755 /root/.bashrc
# SMTP support
RUN apt-get -y install ssmtp && echo "FromLineOverride=YES\nmailhub=mailhog:1025" > /etc/ssmtp/ssmtp.conf && \
echo 'sendmail_path = "/usr/sbin/ssmtp -t"' > /etc/php/7.0/fpm/conf.d/mail.ini
# nginx config
RUN sed -i -e"s/keepalive_timeout\s*65/keepalive_timeout 2/" /etc/nginx/nginx.conf
RUN sed -i -e"s/keepalive_timeout 2/keepalive_timeout 2;\n\tclient_max_body_size 100m/" /etc/nginx/nginx.conf
RUN echo "daemon off;" >> /etc/nginx/nginx.conf
# php-fpm config
RUN sed -i -e "s/;cgi.fix_pathinfo=1/cgi.fix_pathinfo=0/g" /etc/php/7.0/fpm/php.ini
RUN sed -i -e "s/upload_max_filesize\s*=\s*2M/upload_max_filesize = 100M/g" /etc/php/7.0/fpm/php.ini
RUN sed -i -e "s/memory_limit\s*=\s*128M/memory_limit = 512M/g" /etc/php/7.0/fpm/php.ini
RUN sed -i -e "s/post_max_size\s*=\s*8M/post_max_size = 100M/g" /etc/php/7.0/fpm/php.ini
RUN sed -i -e "s/;daemonize\s*=\s*yes/daemonize = no/g" /etc/php/7.0/fpm/php-fpm.conf
RUN sed -i -e "s/pid\s*=\s*\/run\/php\/php7.0-fpm.pid/pid = \/run\/php-fpm.pid/g" /etc/php/7.0/fpm/php-fpm.conf
RUN sed -i -e "s/;catch_workers_output\s*=\s*yes/catch_workers_output = yes/g" /etc/php/7.0/fpm/pool.d/www.conf
RUN sed -i -e "s/listen\s*=\s*\/run\/php\/php7.0-fpm.sock/listen = \/run\/php-fpm.sock/g" /etc/php/7.0/fpm/pool.d/www.conf
RUN find /etc/php/7.0/cli/conf.d/ -name "*.ini" -exec sed -i -re 's/^(\s*)#(.*)/\1;\2/g' {} \;
# nginx site conf
ADD ./drupal-site.conf /etc/nginx/sites-available/drupal.conf
ADD ./magento-site.conf /etc/nginx/sites-available/magento.conf
ADD ./livehelperchat-site.conf /etc/nginx/sites-available/livehelperchat.conf
# Supervisor Config
RUN /usr/bin/easy_install supervisor
RUN /usr/bin/easy_install supervisor-stdout
ADD ./supervisord.conf /etc/supervisord.conf
# Initialization and Startup Script
ADD ./start.sh /start.sh
RUN chmod 755 /start.sh
# private expose
EXPOSE 80
EXPOSE 8080
EXPOSE 22
CMD ["/bin/bash", "/start.sh"]
| ddaa22b412c84ff72b077f02165da33273a3c5ab | [
"Markdown",
"Dockerfile",
"Shell"
] | 4 | Shell | CitrusSolutions/docker-php | bf9bdd2202ff7eeb50f1e05588ac7159ad18f467 | b0c584f5953ae09c2455030eb9f5036dfcb6eb17 |
refs/heads/master | <repo_name>luanachen/IngresseChallenge<file_sep>/IngresseChallenge/Model/Channel.swift
//
// Channel.swift
// IngresseChallenge
//
// Created by Luana on 11/04/18.
// Copyright © 2018 lccj. All rights reserved.
//
import Foundation
typealias Channel = [ChannelElement]
struct ChannelElement: Codable {
let score: Double
let show: Show
}
struct Show: Codable {
let id: Int
let name: String
let genres: [String]?
let premiered: String?
let image: Image?
let summary: String?
enum CodingKeys: String, CodingKey {
case id, name, genres, premiered, image, summary
}
}
struct Image: Codable {
let medium, original: String
}
<file_sep>/IngresseChallenge/Controller/ChannelTableViewController.swift
//
// ChannelTableViewController.swift
// IngresseChallenge
//
// Created by Luana on 11/04/18.
// Copyright © 2018 lccj. All rights reserved.
//
import UIKit
import AlamofireImage
import SVProgressHUD
class ChannelTableViewController: UITableViewController {
// MARK: - Properties
var channelsArray: [Show]?
let favoriteKey = "favorites"
var favorites = [Int]()
let userDefaults = UserDefaults.standard
// MARK: - Outlets
@IBOutlet var searchBar: UISearchBar!
// MARK: - View Cicle
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.backBarButtonItem?.tintColor = UIColor.black
tableView.register(UINib(nibName: "ChannelCell", bundle: nil), forCellReuseIdentifier: "customCell")
searchBar.delegate = self
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(true)
self.tableView.reloadData()
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.channelsArray?.count ?? 0
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "customCell", for: indexPath) as? ChannelCell else { return UITableViewCell() }
if let channel = channelsArray?[indexPath.row] {
cell.titleLabel.text = channel.name
let genres = channel.genres?.compactMap{$0}.joined(separator: " | ")
cell.genreLabel.text = genres
if let imageString = channel.image?.original {
if let imageURL = URL(string: imageString) {
cell.posterImage.af_setImage(withURL: imageURL)
} else {
cell.posterImage.image = UIImage(named: "movie_placeholder")
}
}
cell.posterImage.isHidden = false
cell.favoriteButton.isHidden = false
cell.favID = channel.id
cell.updateSelection()
cell.favoriteButton.setImage(#imageLiteral(resourceName: "filled_star"), for: .selected)
let tintedStar = UIImage(named: "empty_star")?.tinted(with: .lightGray)
cell.favoriteButton.setImage(tintedStar, for: .normal)
return cell
}
return cell
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 120
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let storyboard = UIStoryboard(name: "Main", bundle: Bundle.main)
let destinationVC = storyboard.instantiateViewController(withIdentifier: "DetailsViewController") as! DetailsViewController
guard let channel = self.channelsArray?[indexPath.row] else { return }
destinationVC.selectedChannel = channel
self.navigationController?.pushViewController(destinationVC, animated: true)
}
}
// MARK: - UISearchBarDelegate
extension ChannelTableViewController: UISearchBarDelegate {
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
guard !searchText.isEmpty else {
channelsArray?.removeAll()
tableView.reloadData()
return
}
}
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
searchBar.resignFirstResponder()
SVProgressHUD.show()
if let text = searchBar.text {
let text = text.replacingOccurrences(of: " ", with: "+")
GetAPIData().fetchChannels(by: text) { (channels) in
self.channelsArray = channels.compactMap { $0.show }
self.tableView.reloadData()
self.tableView.allowsSelection = true
}
SVProgressHUD.dismiss()
}
}
}
// MARK: Extension - UIImage
extension UIImage {
func tinted(with color: UIColor) -> UIImage? {
UIGraphicsBeginImageContextWithOptions(size, false, scale)
defer { UIGraphicsEndImageContext() }
color.set()
withRenderingMode(.alwaysTemplate)
.draw(in: CGRect(origin: .zero, size: size))
return UIGraphicsGetImageFromCurrentImageContext()
}
}
<file_sep>/Podfile
platform :ios, '9.0'
target 'IngresseChallenge' do
# Comment the next line if you're not using Swift and don't want to use dynamic frameworks
use_frameworks!
# Pods for IngresseChallenge
pod 'Alamofire', '~> 4.7'
pod 'AlamofireImage', '~> 3.3'
pod 'SVProgressHUD'
end
<file_sep>/IngresseChallenge/Gateway/GetAPIData.swift
//
// GetAPIData.swift
// CarRepairFinder
//
// Created by Luana on 05/03/18.
// Copyright © 2018 lccj. All rights reserved.
//
import UIKit
import Alamofire
class GetAPIData {
func fetchChannels(by name: String, completionHandler: @escaping (Channel) -> ()) {
var channelsArray = Channel()
guard let url = URL(string: "http://api.tvmaze.com/search/shows?q=\(name)") else { return }
Alamofire.request(url).responseJSON { (response) in
if response.result.isSuccess {
channelsArray = self.updateResult(response.data)
} else {
print("Error with request: \(String(describing: response.result.error))")
let alerta = UIAlertController(title: "Alerta", message: "Erro ao receber dados, por favor reporte o problema. :(", preferredStyle: .alert)
let actionOk = UIAlertAction(title: "Ok", style: .default, handler: nil)
alerta.addAction(actionOk)
UIApplication.shared.keyWindow?.rootViewController?.present(alerta, animated: true, completion: nil)
}
completionHandler(channelsArray)
}
}
func updateResult(_ data: Data?) -> Channel{
var channels = Channel()
do {
let decoder = JSONDecoder()
if let data = data {
channels = try decoder.decode(Channel.self, from: data)
} else { print("no data retrieved") }
} catch {
print("Error while parsing json: \(error)")
}
return channels
}
}
<file_sep>/IngresseChallenge/Controller/ChannelCell.swift
//
// ChannelCell.swift
// IngresseChallenge
//
// Created by Luana on 11/04/18.
// Copyright © 2018 lccj. All rights reserved.
//
import UIKit
class ChannelCell: UITableViewCell {
// MARK: - Properties
var favID = 0
let userDefaults = UserDefaults.standard
var index: IndexPath!
// MARK: - Outlets
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var genreLabel: UILabel!
@IBOutlet weak var posterImage: UIImageView!
@IBOutlet weak var favoriteButton: UIButton!
// MARK: - View Cicle
override func awakeFromNib() {
super.awakeFromNib()
}
// MARK: - Action
@IBAction func favoriteButton(_ sender: UIButton) {
favoriteButton.setImage(#imageLiteral(resourceName: "filled_star"), for: .selected)
favoriteButton.setImage(#imageLiteral(resourceName: "empty_star"), for: .normal )
sender.isSelected = !sender.isSelected
let key = "\(favID)"
userDefaults.set(sender.isSelected, forKey: key)
userDefaults.synchronize()
}
// MARK: - Methods
func updateSelection() {
let key = "\(favID)"
let isFav = userDefaults.bool(forKey: key)
favoriteButton.isSelected = isFav
}
}
<file_sep>/IngresseChallenge/Controller/DetailsViewController.swift
//
// DetailsViewController.swift
// IngresseChallenge
//
// Created by Luana on 11/04/18.
// Copyright © 2018 lccj. All rights reserved.
//
import UIKit
class DetailsViewController: UIViewController {
// MARK: - Properties
var favID = 0
var userDefaults = UserDefaults.standard
var selectedChannel: Show?
// MARK: - Outlets
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var genreLabel: UILabel!
@IBOutlet weak var synopsisTextField: UITextView!
@IBOutlet weak var releaseDayLabel: UILabel!
@IBOutlet weak var favoriteButton: UIButton!
// MARK: - View Cicle
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.title = selectedChannel?.name
self.title = selectedChannel?.name
self.titleLabel.text = selectedChannel?.name
self.genreLabel.text = selectedChannel?.genres?.compactMap{$0}.joined(separator: " | ")
self.releaseDayLabel.text = selectedChannel?.premiered
let synopsis = selectedChannel?.summary
self.synopsisTextField.text = synopsis?.removeHtmlFromString(inPutString: synopsis!)
if let imageString = selectedChannel?.image?.original {
if let imageURL = URL(string: imageString) {
imageView.af_setImage(withURL: imageURL)
}
}
guard let id = selectedChannel?.id else { return }
favID = id
favoriteButton.isSelected = userDefaults.bool(forKey: "\(favID)")
favoriteButton.setImage(#imageLiteral(resourceName: "filled_star"), for: .selected)
let tintedStar = UIImage(named: "empty_star")?.tinted(with: .lightGray)
favoriteButton.setImage(tintedStar, for: .normal)
}
override func viewWillDisappear(_ animated: Bool) {
if self.isMovingToParentViewController {
selectedChannel = nil
}
}
// MARK: - Action
@IBAction func favoriteButton(_ sender: UIButton) {
favoriteButton.setImage(#imageLiteral(resourceName: "filled_star"), for: .selected)
let tintedStar = UIImage(named: "empty_star")?.tinted(with: .lightGray)
favoriteButton.setImage(tintedStar, for: .normal)
sender.isSelected = !sender.isSelected
userDefaults.set(sender.isSelected, forKey: "\(favID)")
userDefaults.synchronize()
}
}
// MARK: Extension - String
extension String{
func removeHtmlFromString(inPutString: String) -> String{
return inPutString.replacingOccurrences(of: "<[^>]+>", with: "", options: .regularExpression, range: nil)
}
}
| cf402b1ba2f230120d90627a44e8e156858a5840 | [
"Swift",
"Ruby"
] | 6 | Swift | luanachen/IngresseChallenge | 8bab0cc9798ef1807dbac64bd52c865f24466477 | b96ecb2a65340622d22157c037514783c9d98205 |
refs/heads/main | <repo_name>asim9895/graphql_social_media<file_sep>/utils/validation.js
const user = require('../graphql/main/user');
const validateRegisterUser = (username, email, password, confirmPassword) => {
const errors = {};
if (username.trim() === '') {
errors.username = 'Username is Empty';
}
if (email.trim() === '') {
errors.email = 'Email is Empty';
} else {
const regex = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if (!email.match(regex)) {
errors.email = 'Enter valid email Address';
}
}
if (password === '') {
errors.password = '<PASSWORD>';
} else if (password !== <PASSWORD>Password) {
errors.password = '<PASSWORD>';
}
return {
errors,
valid: Object.keys(errors).length < 1,
};
};
const validateLoginUser = (username, password) => {
const errors = {};
if (username.trim() === '') {
errors.username = 'Username is Empty';
}
if (password.trim() === '') {
errors.password = '<PASSWORD>';
}
return {
errors,
valid: Object.keys(errors).length < 1,
};
};
module.exports = { validateRegisterUser, validateLoginUser };
<file_sep>/graphql/main/user.js
const User = require('../../models/User');
const config = require('config');
const jwt = require('jsonwebtoken');
const bcrypt = require('bcrypt');
const jwtSecret = config.get('jwtSecret');
const { UserInputError } = require('apollo-server');
const {
validateRegisterUser,
validateLoginUser,
} = require('../../utils/validation');
module.exports = {
Mutation: {
async registerUser(
_,
{ registerInput: { username, email, password, confirmPassword } },
context,
info
) {
const { valid, errors } = validateRegisterUser(
username,
email,
password,
confirmPassword
);
if (!valid) {
throw new UserInputError('Errors', { errors });
}
const emailExists = await User.findOne({ email: email.toLowerCase() });
if (emailExists) {
throw new UserInputError('email is taken', {
errors: {
email: 'Email Already Exists',
},
});
}
const usernameExists = await User.findOne({
username: username.toLowerCase(),
});
if (usernameExists) {
throw new UserInputError('username is taken', {
errors: {
username: 'Username Taken',
},
});
}
const user = new User({
username,
email,
password,
created: new Date().toISOString(),
});
const salt = await bcrypt.genSalt(10);
user.password = await bcrypt.hash(password, salt);
const res = await user.save();
const token = jwt.sign(
{
id: res.id,
email: res.email,
username: res.username,
},
jwtSecret
);
return {
...res._doc,
id: res._id,
token,
};
},
async loginUser(_, { username, password }, context, info) {
const { valid, errors } = validateLoginUser(username, password);
if (!valid) {
throw new UserInputError('Errors', { errors });
}
const user = await User.findOne({ username });
if (!user) {
errors.general = 'User Does Not Exists';
throw new UserInputError('no user exists', {
errors,
});
}
const isMatch = await bcrypt.compare(password, user.password);
if (!isMatch) {
errors.general = 'Incorrect Password';
throw new UserInputError('password not correct', {
errors,
});
}
const token = jwt.sign(
{
id: user.id,
email: user.email,
username: user.username,
},
jwtSecret
);
return {
...user._doc,
id: user._id,
token,
};
},
},
};
<file_sep>/README.md
Website Link:
https://graphql-socialmedia.netlify.app/
<file_sep>/client/src/pages/SinglePost.js
import React, { useContext, useState } from 'react';
import { useMutation, useQuery } from '@apollo/react-hooks';
import { FETCH_POST_QUERY } from '../graphql/Queries';
import {
Grid,
Image,
Card,
Button,
Label,
Icon,
Form,
} from 'semantic-ui-react';
import moment from 'moment';
import { AuthContext } from '../context/auth';
import LikeButton from '../components/LikeButton';
import DeleteButton from '../components/DeleteButton';
import { CREATE_COMMENT } from '../graphql/Mutations';
const SinglePost = ({ match, history }) => {
const postId = match.params.postId;
const { user } = useContext(AuthContext);
const { data } = useQuery(FETCH_POST_QUERY, {
variables: {
postId,
},
});
const [comment, setcomment] = useState('');
const [createComment] = useMutation(CREATE_COMMENT, {
variables: {
postId,
body: comment,
},
update() {
setcomment('');
},
});
const deletePostCallback = () => {
history.push('/');
};
return !data ? (
<h1>loading post...</h1>
) : (
<Grid style={{ marginTop: 20 }}>
<Grid.Row>
<Grid.Column width={2}>
<Image
floated='right'
size='small'
src='https://react.semantic-ui.com/images/avatar/large/daniel.jpg'
/>
</Grid.Column>
<Grid.Column width={10}>
<Card fluid>
<Card.Content>
<Card.Header>{data.getPost.username}</Card.Header>
<Card.Meta>{moment(data.getPost.created).fromNow()}</Card.Meta>
<Card.Description>{data.getPost.body}</Card.Description>
</Card.Content>
<hr />
<Card.Content extra>
<LikeButton
user={user}
post={{
id: data.getPost.id,
likeCount: data.getPost.likeCount,
likes: data.getPost.likes,
}}
/>
<Button labelPosition='right' as='div'>
<Button basic color='blue'>
<Icon name='comment outline' />
</Button>
<Label basic color='blue' pointing='left'>
{data.getPost.commentCount}
</Label>
</Button>
{user && user.username === data.getPost.username && (
<DeleteButton
postId={data.getPost.id}
callback={deletePostCallback}
/>
)}
</Card.Content>
</Card>
{user && (
<Card fluid>
<Card.Content>
<p>Post a comment</p>
<Form onSubmit={createComment}>
<div className='ui action input fluid'>
<Form.Input
type='text'
placeholder='Post a comment'
name='comment'
value={comment}
onChange={(e) => setcomment(e.target.value)}
/>
<Button
type='submit'
color='teal'
size='small'
disabled={comment.trim() === ''}>
Create Comment
</Button>
</div>
</Form>
</Card.Content>
</Card>
)}
<h3>Comments</h3>
{data.getPost.comments &&
data.getPost.comments.map((comment) => (
<Card fluid key={comment.id}>
<Card.Content>
{user && user.username === comment.username && (
<DeleteButton
postId={data.getPost.id}
commentId={comment.id}
/>
)}
<Card.Header>{comment.username}</Card.Header>
<Card.Meta>{moment(comment.created).fromNow()}</Card.Meta>
<Card.Description>{comment.body}</Card.Description>
</Card.Content>
</Card>
))}
</Grid.Column>
</Grid.Row>
</Grid>
);
};
export default SinglePost;
<file_sep>/database/mongoose.js
const mongoose = require('mongoose');
const config = require('config');
const mongodbURL = config.get('mongodbURL');
const connectdb = async () => {
try {
await mongoose.connect(mongodbURL, {
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: true,
});
console.log('mongodb connected');
} catch (error) {
console.log(error);
}
};
module.exports = connectdb;
<file_sep>/client/src/components/DeleteButton.js
import React, { useState } from 'react';
import { Button, Confirm, Icon } from 'semantic-ui-react';
import { DELETE_POST, DELETE_COMMENT } from '../graphql/Mutations';
import { useMutation } from '@apollo/react-hooks';
import { FETCH_POSTS_QUERY } from '../graphql/Queries';
const DeleteButton = ({ postId, callback, commentId }) => {
const mutation = commentId ? DELETE_COMMENT : DELETE_POST;
const [confirmDelete, setconfirmDelete] = useState(false);
const [deletePost] = useMutation(mutation, {
variables: {
postId,
commentId,
},
update(proxy) {
setconfirmDelete(false);
if (!commentId) {
const data = proxy.readQuery({
query: FETCH_POSTS_QUERY,
});
data.getPosts = data.getPosts.filter((p) => p.id !== postId);
proxy.writeQuery({ query: FETCH_POSTS_QUERY, data });
}
if (callback) callback();
},
});
return (
<div>
<Button
color='red'
floated='right'
onClick={() => setconfirmDelete(true)}>
<Icon name='trash' style={{ margin: 0 }} />
</Button>
<Confirm
open={confirmDelete}
onCancel={() => setconfirmDelete(false)}
onConfirm={deletePost}
/>
</div>
);
};
export default DeleteButton;
<file_sep>/client/src/components/LikeButton.js
import React, { useEffect, useState } from 'react';
import { Button, Icon, Label } from 'semantic-ui-react';
import { useMutation } from '@apollo/react-hooks';
import { LIKE_POST } from '../graphql/Mutations';
import { Link } from 'react-router-dom';
const LikeButton = ({ user, post: { id, likeCount, likes } }) => {
const [like, setlike] = useState(false);
useEffect(() => {
if (user && likes.find((like) => like.username === user.username)) {
setlike(true);
} else setlike(false);
}, [user, likes]);
const [likePost] = useMutation(LIKE_POST, {
variables: {
postId: id,
},
});
const likeButton = user ? (
like ? (
<Button color='red'>
<Icon name='heart' />
</Button>
) : (
<Button color='red' basic>
<Icon name='heart' />
</Button>
)
) : (
<Button color='red' basic as={Link} to='/login'>
<Icon name='heart' />
</Button>
);
return (
<Button as='div' labelPosition='right' onClick={likePost}>
{likeButton}
<Label basic color='red' pointing='left'>
{likeCount}
</Label>
</Button>
);
};
export default LikeButton;
| d688254a580b21f3a5f2ab887bed92632d33eb1c | [
"JavaScript",
"Markdown"
] | 7 | JavaScript | asim9895/graphql_social_media | fe09064a3f4648b25da041ad2523cc3c5d5e2499 | 38691ddcd526f72f7d0969152c863fd2074b24c4 |
refs/heads/main | <repo_name>EricTronGit/SolarSystem<file_sep>/solarsystem/src/pages/saturne.jsx
import saturne from "../assets/saturn.png";
function Saturne(){
return(
<div className="saturne">
<span className="textTitre">Saturne</span>
<div className="imgMercuryContainer">
<img className="imgMercury" src={saturne} alt="saturne"></img>
</div>
</div>
)
}
export default Saturne;<file_sep>/solarsystem/src/pages/mars.jsx
import { useState } from "react";
import { Spring } from "react-spring/renderprops-universal";
import mars from "../assets/mars.png";
function Mars() {
let [appearTextTopLeft, setAppearTextTopLeft] = useState(false);
let [appearTextTopRight, setAppearTextTopRight] = useState(false);
let [appearTextBotLeft, setAppearTextBotLeft] = useState(false);
let [appearTextBotRight, setAppearTextBotRight] = useState(false);
document.addEventListener('scroll', function(e) {
if (window.scrollY > 3900) {
setAppearTextTopLeft(true);
}
if (window.scrollY > 4000) {
setAppearTextTopRight(true);
}
if (window.scrollY > 4100) {
setAppearTextBotLeft(true);
}
if (window.scrollY > 4200) {
setAppearTextBotRight(true);
}
});
return (
<div className="Mars">
<span className="textTitre">Mars</span>
{appearTextTopLeft &&
<Spring config={{delay: 600}}
from={{ opacity: 0 }}
to={{ opacity: 1 }}>
{props => <p className="textInfoVenusTopLeft" style={props}>Mars est une planète tellurique, comme le sont Mercure, Vénus et la Terre, environ dix fois moins massive que la Terre mais dix fois plus massive que la Lune.</p>}
</Spring>
}
{appearTextTopRight &&
<Spring config={{delay: 600}}
from={{ opacity: 0 }}
to={{ opacity: 1 }}>
{props => <p className="textInfoSunTopRight" style={props}>La période de rotation de Mars est du même ordre que celle de la Terre et son obliquité lui confère un cycle des saisons similaire à celui que nous connaissons.</p>}
</Spring>
}
{appearTextBotLeft &&
<Spring config={{delay: 600}}
from={{ opacity: 0 }}
to={{ opacity: 1 }}>
{props => <p className="textInfoSunBotLeft" style={props}>Mars possède deux petits satellites naturels, <u>Phobos et Déimos</u>.</p>}
</Spring>
}
{appearTextBotRight &&
<Spring config={{delay: 600}}
from={{ opacity: 0 }}
to={{ opacity: 1 }}>
{props => <p className="textInfoSunBotRight" style={props}>L'eau liquide en surface et que des formes de vie similaires à celles existant sur Terre pouvaient s'y être développées, thème très fécond en science-fiction.</p>}
</Spring>
}
<div className="imgMercuryContainer">
<img className="imgMercury" src={mars} alt="mars"></img>
</div>
</div>
);
}
export default Mars;<file_sep>/solarsystem/src/pages/venus.jsx
import { useState } from "react";
import { Spring } from "react-spring/renderprops-universal";
import ModalVenus from "../modal/modal.jsx";
import venus from "../assets/venus.png";
function Venus (){
const [show, setShow] = useState(false);
const handleClose = () => setShow(false);
const handleShow = () => setShow(true);
let [appearTextTopLeftVenus, setAppearTextTopLeftVenus] = useState(false);
let [appearTextTopRightVenus, setAppearTextTopRightVenus] = useState(false);
let [appearTextBotLeftVenus, setAppearTextBotLeftVenus] = useState(false);
let [appearTextBotRightVenus, setAppearTextBotRightVenus] = useState(false);
document.addEventListener('scroll', function(e) {
if (window.scrollY > 1600) {
setAppearTextTopLeftVenus(true);
}
if (window.scrollY > 1700) {
setAppearTextTopRightVenus(true);
}
if (window.scrollY > 1800) {
setAppearTextBotLeftVenus(true);
}
if (window.scrollY > 1900) {
setAppearTextBotRightVenus(true);
}
});
return(
<div className="venus">
<span className="textTitre">Venus</span>
<ModalVenus close={handleClose} textHeader="Venus" textBody="test" show={show}></ModalVenus>
{appearTextTopLeftVenus &&
<Spring config={{delay: 600}}
from={{ opacity: 0 }}
to={{ opacity: 1 }}>
{props => <p className="textInfoVenusTopLeft" style={props}>Vénus est la deuxième planète du Système solaire, c'est la sixième plus grosse aussi bien par la masse que le diamètre. Elle doit son nom à la déesse romaine de l'amour.</p>}
</Spring>
}
{appearTextTopRightVenus &&
<Spring config={{delay: 600}}
from={{ opacity: 0 }}
to={{ opacity: 1 }}>
{props => <p className="textInfoSunTopRight" style={props}>Vénus orbite autour du Soleil à une distance moyenne d'environ 108 millions de kilomètres et complète une orbite tous les 224,7 jours terrestres.</p>}
</Spring>
}
{appearTextBotLeftVenus &&
<Spring config={{delay: 600}}
from={{ opacity: 0 }}
to={{ opacity: 1 }}>
{props => <p className="textInfoSunBotLeft" style={props}>La température de surface de Vénus (462°C) varie peu selon les latitudes et longitudes.</p>}
</Spring>
}
{appearTextBotRightVenus &&
<Spring config={{delay: 600}}
from={{ opacity: 0 }}
to={{ opacity: 1 }}>
{props => <p className="textInfoSunBotRight" style={props}>L'exploration de Vénus à l'aide de sondes spatiales commence au début des années 1960, peu après l'envoi du premier satellite artificiel en orbite, Spoutnik 1.</p>}
</Spring>
}
<div className="imgMercuryContainer">
<img className="imgMercury" src={venus} alt="venus" onClick={handleShow}></img>
</div>
</div>
)
}
export default Venus;<file_sep>/solarsystem/src/modal/modal.jsx
import { Modal } from "react-bootstrap";
function ModalTemplate(props) {
const handleClose = () =>{
props.close(false);
}
return (
<div>
<Modal size="lg" className="modalContainer" show={props.show} onHide={handleClose} animation={true}>
<Modal.Header className="modalHeaderFooter" closeButton>
<Modal.Title>En savoir plus sur {props.textHeader}</Modal.Title>
</Modal.Header>
<Modal.Body className="modalBody">
{props.textBody}
</Modal.Body>
</Modal>
</div>
);
}
export default ModalTemplate;
<file_sep>/solarsystem/src/pages/uranus.jsx
import uranus from "../assets/uranus.png";
function Uranus(){
return (
<div className="uranus">
<span className="textTitre">Uranus</span>
<div className="imgMercuryContainer">
<img className="imgMercury" src={uranus} alt="uranus"></img>
</div>
</div>
)
}
export default Uranus;<file_sep>/solarsystem/src/pages/neptune.jsx
import neptune from "../assets/neptune.png";
function Neptune(){
return(
<div className="neptune">
<span className="textTitre">Neptune</span>
<div className="imgMercuryContainer">
<img className="imgMercury" src={neptune} alt="neptune"></img>
</div>
</div>
)
}
export default Neptune;<file_sep>/solarsystem/src/pages/jupiter.jsx
import { useState } from "react";
import { Spring } from "react-spring/renderprops-universal";
import jupiter from "../assets/jupiter.png";
import ModalTemplate from "../modal/modal";
function Jupiter(){
const [show, setShow] = useState(false);
const handleClose = () => setShow(false);
const handleShow = () => setShow(true);
let [appearTextTopLeft, setAppearTextTopLeft] = useState(false);
let [appearTextTopRight, setAppearTextTopRight] = useState(false);
let [appearTextBotLeft, setAppearTextBotLeft] = useState(false);
let [appearTextBotRight, setAppearTextBotRight] = useState(false);
document.addEventListener('scroll', function(e) {
if (window.scrollY > 6000) {
setAppearTextTopLeft(true);
}
if (window.scrollY > 6200) {
setAppearTextTopRight(true);
}
if (window.scrollY > 6400) {
setAppearTextBotLeft(true);
}
if (window.scrollY > 6500) {
setAppearTextBotRight(true);
}
});
return(
<div className="jupiter">
<span className="textTitre">Jupiter</span>
<ModalTemplate close={handleClose} textHeader="Jupiter" textBody="pouet Jupiter" show={show}></ModalTemplate>
{appearTextTopLeft &&
<Spring config={{delay: 900}}
from={{ opacity: 0 }}
to={{ opacity: 1 }}>
{props => <p className="textInfoSunTopLeft" style={props}>Jupiter est une planète géante gazeusea. Il s'agit de la plus grosse planète du Système solaire, plus volumineuse et massive que toutes les autres planètes réunies.</p>}
</Spring>
}
{appearTextTopRight &&
<Spring config={{delay: 900}}
from={{ opacity: 0 }}
to={{ opacity: 1 }}>
{props => <p className="textInfoSunTopRight" style={props}>Visible à l'œil nu dans le ciel nocturne, Jupiter est habituellement le quatrième objet le plus brillant de la voûte céleste, après le Soleil, la Lune et Vénus.</p>}
</Spring>
}
{appearTextBotLeft &&
<Spring config={{delay: 900}}
from={{ opacity: 0 }}
to={{ opacity: 1 }}>
{props => <p className="textInfoSunBotLeft" style={props}>Comme sur les autres planètes gazeuses, des vents violents, de près de 600 km/h, parcourent les couches supérieures de la planète.</p>}
</Spring>
}
{appearTextBotRight &&
<Spring config={{delay: 900}}
from={{ opacity: 0 }}
to={{ opacity: 1 }}>
{props => <p className="textInfoSunBotRight" style={props}>Regroupant Jupiter et les objets se trouvant dans sa sphère d'influence, le système jovien est une composante majeure du Système solaire externe.</p>}
</Spring>
}
<div className="imgMercuryContainer">
<img className="imgMercury" src={jupiter} alt="jupiter" onClick={handleShow}></img>
</div>
</div>
)
}
export default Jupiter; | 8ef8fef5c4fe3571b7cf9fee3288ffca690120b4 | [
"JavaScript"
] | 7 | JavaScript | EricTronGit/SolarSystem | 94c858a8987ab66fba6c1419feb81d83ae7d61c6 | ff259f6835d272fd218fa6f814b7bcbd2981acfd |
refs/heads/master | <file_sep>class Solution {
# XOR: number with itself is 0, with 0 its the number, order doesn't matter its commutative
public:
int singleNumber(vector<int>& nums) {
int x = 0;
for (int num : nums) {
x ^= num;
}
return x;
}
};
<file_sep>class Solution {
int sumFunc(int num) {
int sum = 0;
while (num) {
int digit = num % 10;
num /= 10;
sum += digit * digit;
}
return sum;
}
public:
bool isHappy(int n) {
unordered_set<int> visited;
while (true) {
if (n == 1) return true;
n = sumFunc(n);
if (visited.count(n) == 1) return false;
visited.insert(n);
}
}
};
<file_sep># april-challenge
https://leetcode.com/explore/other/card/30-day-leetcoding-challenge
also learning c++
<file_sep>class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
// canonical form, choosing to sort the the word
unordered_map<string, vector<string>> store;
for (string word : strs) {
string sorted = word;
sort(sorted.begin(), sorted.end());
store[sorted].push_back(word);
}
vector<vector<string>> res;
for (pair<string, vector<string>> element : store) {
res.push_back(element.second);
}
return res;
}
};
<file_sep>class Solution {
public:
// can only count x when x+1 is present in the arr
int countElements(vector<int>& arr) {
set<int> store;
for (int a : arr) {
store.insert(a);
}
int res = 0;
for (int a : arr) {
if (store.count(a+1) == 1) {
res++;
}
}
return res;
}
};
<file_sep>class Solution {
public:
int maxSubArray(vector<int>& nums) {
int sum = INT_MIN;
int curr = 0;
for (int num : nums) {
curr += num;
sum = max(curr, sum);
curr = max(0, curr);
}
return sum;
}
};
| a3831157f3124b8d9f13eae9d48644b32a5e6324 | [
"Markdown",
"C++"
] | 6 | C++ | zainhuda/april-challenge | 92f2702d90a5d113b65ef5b354a0de14892abf96 | 803bd02bd0cd4bd9c1b5a7760aa4d655e2442262 |
refs/heads/master | <file_sep># food_tripping
Django rest Api for finding narest 10 best restaurants with rating along with ubergo fare to travel to these restaurants from your location.
# Software Requirement
Django,
Django Rest Framework,
Django Rest Swagger
# Uses
python manage.py runserver
<file_sep>from rest_framework import serializers
from food_via_trip.models import Location
class LocationSerailizer(serializers.ModelSerializer):
class Meta:
model = Location
fields = ('location_id', 'entity_id', 'entity_type', 'lat', 'long', 'address')<file_sep>import uuid
from operator import itemgetter
import requests
from django.conf import settings
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView
from food_via_trip.models import Location
from food_via_trip.serializers import LocationSerailizer
# Create your views here.
class LocationInfoList(APIView):
def get(self, request):
locations = Location.objects.all()
serializer = LocationSerailizer(locations, many=True)
return Response(serializer.data, status=status.HTTP_200_OK)
class GenerateLocationInfo(APIView):
@staticmethod
def post(request):
"""
Find location info by address
---
parameters:
- name: address
description: your location address
required: true
"""
if not request.data.get('address'):
return Response("Please provide address!", status=status.HTTP_400_BAD_REQUEST)
address = request.data.get('address')
if Location.objects.filter(address=address).exists():
location = Location.objects.get(address=address)
return Response({'location_id' : location.location_id}, status=status.HTTP_200_OK)
locationFromAddress = settings.GLOBAL_SETTINGS['LOCATION_BASE_URI'] + '?query=' + address
header = {"User-agent": "curl/7.43.0", "Accept": "application/json",
"user_key": settings.GLOBAL_SETTINGS['USER_KEY']}
response = requests.get(locationFromAddress, headers=header)
if not response:
return Response("Zomoto Api didn't responding", status=status.HTTP_500_INTERNAL_SERVER_ERROR)
# not storing entire data of the response just storing useful one
resp_json_payload = response.json()['location_suggestions'][0]
data = {'location_id': str(uuid.uuid4()), 'entity_id': resp_json_payload['entity_id'],
'entity_type': resp_json_payload['entity_type'], 'lat': resp_json_payload['latitude'],
'long': resp_json_payload['longitude'], 'address': address}
serializer = LocationSerailizer(data=data)
if serializer.is_valid():
serializer.save()
return Response(data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
class PopulateRestaurantWithFare(APIView):
@staticmethod
def get(request, location_id):
print location_id
if not location_id:
return Response("Please provide id!", status=status.HTTP_400_BAD_REQUEST)
if not Location.objects.filter(location_id=location_id).exists():
return Response("ID doesn't exists", status=status.HTTP_404_NOT_FOUND)
query = Location.objects.get(location_id=location_id)
entity_id = query.entity_id
entity_type = query.entity_type
start_lat = query.lat
start_long = query.long
restaurants = settings.GLOBAL_SETTINGS['LOCATION_DETAILS_BASE_URI'] + '?entity_id=' + str(
entity_id) + '&entity_type=' + str(entity_type)
header = {"User-agent": "curl/7.43.0", "Accept": "application/json",
"user_key": settings.GLOBAL_SETTINGS['USER_KEY']}
response = requests.get(restaurants, headers=header)
if not response:
return Response("Zomoto Api didn't responding", status=status.HTTP_500_INTERNAL_SERVER_ERROR)
resp_json_payload = response.json()['best_rated_restaurant']
result = []
# fetch top 10 best rated restaurant
for restaurant in resp_json_payload:
name = restaurant['restaurant']['name']
end_lat = restaurant['restaurant']['location']['latitude']
end_long = restaurant['restaurant']['location']['longitude']
rating = restaurant['restaurant']['user_rating']['aggregate_rating']
calculateFare = settings.GLOBAL_SETTINGS[
'TAXI_FARE_BASE_URI'] + '?server_token=' + settings.GLOBAL_SETTINGS[
'SERVER_TOKEN'] + '&start_latitude=' + str(
start_lat) + '&start_longitude=' + str(start_long) + '&end_latitude=' + str(
end_lat) + '&end_longitude=' + str(end_long)
try:
api_response = requests.get(calculateFare)
api_response_json_payload = api_response.json()
except requests.exceptions.ConnectionError:
return Response('Uber api not responding', status=status.HTTP_500_INTERNAL_SERVER_ERROR)
if api_response_json_payload:
try:
# some times uber api behaves weired distance is too much 100 miles. Handling in try except
prices = api_response_json_payload['prices']
for price in prices:
# since pool is cheapest assuming that
if 'UberGo' in price['localized_display_name'].encode('utf8'):
result.append({'name': name, 'rating': rating, 'fare': price['low_estimate']})
break
except Exception as e:
pass
sorted_data = sorted(result, key=itemgetter('fare'))
print result
res = {'price_rating': sorted_data}
return Response(res, status=status.HTTP_200_OK)
<file_sep>from __future__ import unicode_literals
from django.apps import AppConfig
class FoodViaTripConfig(AppConfig):
name = 'food_via_trip'
<file_sep>from __future__ import unicode_literals
from django.db import models
import uuid
# Create your models here.
class Location(models.Model):
location_id = models.CharField(max_length=255, unique=True, blank=False)
entity_id = models.IntegerField()
entity_type = models.CharField(max_length=20)
lat = models.FloatField()
long = models.FloatField()
address = models.CharField(max_length=255, blank=True)
def __str__(self):
return self.address
<file_sep>from django.conf.urls import url
from food_via_trip import views
urlpatterns = [
url(r'^all-location/$', views.LocationInfoList.as_view(), name='LocationInfoList'),
url(r'^location/$', views.GenerateLocationInfo.as_view(), name='GenerateLocationInfo'),
url(r'^fare/(?P<location_id>[0-9a-z-]+)/$', views.PopulateRestaurantWithFare.as_view(),
name='PopulateRestaurantWithFare'),
]
| bfb6a9701e9dec5b4e7c8f557dd1e09cb5a33a73 | [
"Markdown",
"Python"
] | 6 | Markdown | Applebit/food_tripping | dcc6e5667b9ebb4f9dc11dba88ca35990458a408 | 9150504c73123f12921634d22af82e2064c648a7 |
refs/heads/master | <repo_name>Pratzn/heroku-cv<file_sep>/public/js/custom.js
/*=========================================
Template Name: New - Personal Portfolio Template
Author: assiathemes
Version: 1.0
=========================================*/
$(document).on('ready', function () {
"use strict"; // Start of use strict
/*---------------------------------------------------*/
/* Preloader
/*---------------------------------------------------*/
$(window).on("load",function (){
$('.loading').delay(1000).fadeOut(1000);
});
/*---------------------------------------------------*/
/* magnificPopup
/*---------------------------------------------------*/
$('.work-popup').magnificPopup({type:'image'});
/*---------------------------------------------------*/
/* navbar Scroll
/*---------------------------------------------------*/
$(".navbar a").on('click', function(event) {
if (this.hash !== "") {
event.preventDefault();
var hash = this.hash;
$('html, body').animate({
scrollTop: $(hash).offset().top
}, 900, function(){
window.location.hash = hash;
});
}
});
/*------------------------------------------------------------*/
/* Closes responsive menu when a scroll trigger link is clicked
/*------------------------------------------------------------*/
$('a').click(function() {
$('.navbar-collapse').collapse('hide');
});
/*----------------------------------------------------------------*/
/* Activate scrollspy to add active class to navbar items on scroll
/*-----------------------------------------------------------------*/
$('body').scrollspy({
target: '#mainNav',
offset: 54
});
/*---------------------------------------------------*/
/* Collapse the navbar when page is scrolled
/*---------------------------------------------------*/
//
$(window).scroll(function() {
if ($("#mainNav").offset().top > 100) {
$("#mainNav").addClass("navbar-shrink");
} else {
$("#mainNav").removeClass("navbar-shrink");
}
});
/*---------------------------------------------------*/
/* Counter
/*---------------------------------------------------*/
$('.numbre').counterUp({
delay: 50,
time: 2000
});
/*---------------------------------------------------*/
/* Filter Item work
/*---------------------------------------------------*/
$(".work ul li").click(function(){
var value = $(this).attr('data-filter');
if(value == "all")
{
$('.filter').show('1000');
}
else
{
$(".filter").not('.'+value).hide('3000');
$('.filter').filter('.'+value).show('3000');
}
});
$('.work ul li').on('click', function () {
$(this).addClass('active').siblings().removeClass('active');
});
/*---------------------------------------------------*/
/* button Back to top
/*---------------------------------------------------*/
var offset = 250;
var duration = 300;
jQuery(window).scroll(function() {
if (jQuery(this).scrollTop() > offset) {
jQuery('.back-to-top').fadeIn(duration);
} else {
jQuery('.back-to-top').fadeOut(duration);
}
});
jQuery('.back-to-top').click(function(event) {
event.preventDefault();
jQuery('html, body').animate({scrollTop: 0}, duration);
return false;
});
});
<file_sep>/README.md
# CV Heroku Cloud App
using [Express 4](http://expressjs.com/).
This application supports the [Getting Started with Node on Heroku](https://devcenter.heroku.com/articles/getting-started-with-nodejs) article - check it out.
## Running Locally
```sh
$ npm install
$ npm start or node index.js
```
Your app should now be running on [localhost:3000](http://localhost:3000/).
<file_sep>/reactive.js
const https = require('https');
function reactiveCall(){
https.get('https://pratz.herokuapp.com', (response) => {
// Continuously update stream with data
var body = '';
response.on('data', function(d) {
body += d;
});
response.on('end', function() {
console.log('result: '+ body);
});
});
}
setInterval(reactiveCall,30000);
| fbc90a9a085aeb4602550d2b7b2aa9e3e1186f83 | [
"JavaScript",
"Markdown"
] | 3 | JavaScript | Pratzn/heroku-cv | 841b7b99ea8d783a202397babfba60e791850f08 | bde125ff46e7f634aae098e1988416659088f1fa |
refs/heads/master | <repo_name>romabug/angularResful<file_sep>/学习笔记.js
CLI常用命令
ng new project-name - 创建一个新项目,置为默认设置
ng new project_name --routing (pls routing files)
ng build - 构建/编译应用
ng test - 运行单元测试
ng e2e - 运行端到端(end-to-end)测试
ng serve - 启动一个小型web服务器,用于托管应用
ng deploy - 即开即用,部署到Github Pages或者Firebase
// test it
// try jenkins
组件| ng g component home/component/my-new-component
//src/app/home/component(指令其他等等都可以用该方式生成)
指令| ng g directive my-new-directive
管道| ng g pipe my-new-pipe
服务| ng g service my-new-service
类| ng g class my-new-class
接口| ng g interface my-new-interface
枚举| ng g enum my-new-enum
模块|ng g module my-module
| a11d5b845f0f0078a09dd294c23198fc9f49a903 | [
"JavaScript"
] | 1 | JavaScript | romabug/angularResful | 8780d7b5cd6588a68eb309f15f9577f20acc46d7 | 0d39c2b6b7cda79752bf8dc59410d333bc79d9ff |
refs/heads/main | <file_sep>import random
import numpy as np
import collections
class MonteCarlo:
def __init__(self, root_node, root_player):
self.root_node = root_node
self.root_player = root_player
self.child_finder = None
self.node_evaluator = lambda child, montecarlo: None
self.isInside = root_node.isInside
self.directions = root_node.directions
self.tree = []
self.width = 12
self.weight = np.array(
[
[90, -80, 50, 15, 15, 50, -80, 90],
[-80, -500, 6, 6, 6, 6, -500, -80],
[50, 6, 8, 8, 8, 8, 6, 50],
[15, 6, 8, 3, 3, 8, 6, 15],
[15, 6, 8, 3, 3, 8, 6, 15],
[50, 6, 8, 8, 8, 8, 6, 50],
[-80, -500, 6, 6, 6, 6, -500, -80],
[90, -80, 50, 15, 15, 50, -80, 90],
]
)
def make_choice(self):
"""
挑最高分的樹移動,這裡樹的分數完全 depend on leaf_node
"""
best_children = []
score = []
tmp_parent = []
tmp_child = []
step_id = []
candidate = []
best_leaf = None
for i, child in enumerate(self.root_node.children):
self.traversal(child, i)
if self.tree:
for tree in self.tree:
for key, value in tree.items():
# state 轉 1D 找哪邊非 0
score.append(value[0])
tmp_child.append(np.where(value[1] != 0))
tmp_parent.append(np.where(value[2] != 0))
step_id.append(value[3])
idx = [i for i, j in enumerate(step_id) if j == max(step_id)]
best_score = float("-inf")
# 找最深而且分數最好的
for id_ in idx:
if score[id_] > best_score:
best_score = score[id_]
best_leaf = self.tree[id_].copy()
# 回去找誰走過來的
leaf_p = []
leaf_id = 0
for _, v in best_leaf.items():
leaf_p = np.where(v[2] != 0)
leaf_id = v[3]
best_root = best_leaf
search = 0
while True:
if leaf_id == 0:
break
for i, c in enumerate(tmp_child):
if len(c[0]) == len(leaf_p[0]):
res = np.equal(c, leaf_p)
if len(tuple(res)) != 1:
break
leaf_id -= 1
leaf_p = tmp_parent[i]
best_root = self.tree[i]
break
search += 1
if search > len(tmp_child):
break
for _, v in best_root.items():
value = v[0]
move = v[5]
candidate.append([value, move])
b_score = float("-inf")
b_m = []
for candi in candidate:
score = candi[0]
if score > b_score:
b_score = score
b_m = candi[1]
else:
# 即將結束
b_score = float("-inf")
b_m = []
for i, child in enumerate(self.root_node.children):
score = child.win_value
if score > b_score:
b_score = score
b_m = child.move
return b_m
def traversal(self, root_tree, id):
weight_cp = self.weight.copy()
for child in root_tree.children:
if child != []:
self.evaluate(child)
self.tree.append(
{
child.total_step: [
child.win_value,
child.state.flatten(),
child.parent.state.flatten(),
id,
child.move,
child.parent.move,
]
}
)
self.traversal(child, id + 1)
self.weight = weight_cp
def evaluate(self, child):
op_score = 0
player_score = 0
p_num = 0
c_num = 0
for i in range(8):
for j in range(8):
if child.state[i][j] == self.root_player:
p_num += 1
child.total_step += 1
# 如果佔角了,就可以考慮爬邊
if i == 0 and j == 0:
self.weight[0][1] = 80
self.weight[1][0] = 80
if i == 0 and j == 7:
self.weight[0][6] = 80
self.weight[1][7] = 80
if i == 7 and j == 0:
self.weight[6][0] = 80
self.weight[7][1] = 80
if i == 7 and j == 0:
self.weight[7][6] = 80
self.weight[6][7] = 80
player_score += self.weight[i][j]
if child.state[i][j] == -self.root_player:
c_num += 1
child.total_step += 1
op_score += self.weight[i][j]
eat = p_num - c_num
# 開盤:
if child.total_step <= 12:
weight = self.changeWeight()
score = player_score - op_score + eat * 3
# 中盤:
elif child.total_step <= 50 and child.total_step > 12:
score = player_score - op_score + eat * 5
# 尾盤:
elif child.total_step > 50:
score = player_score - op_score + eat * 10
child.win_value = score
def changeWeight(self):
first_12_weight = np.array(
[
[90, -60, 30, 3, 3, 30, -60, 90],
[-60, -500, 1, 1, 1, 1, -500, -60],
[30, 1, 10, 10, 10, 10, 1, 30],
[3, 1, 10, 1, 1, 10, 1, 3],
[3, 1, 10, 1, 1, 10, 1, 3],
[30, 1, 10, 10, 10, 10, 1, 30],
[-60, -500, 1, 1, 1, 1, -500, -60],
[90, -60, 30, 3, 3, 30, -60, 90],
]
)
return first_12_weight
def simulate(self, expansion_count=1):
for i in range(expansion_count):
current_node = self.root_node
while current_node.expanded:
current_node = current_node.get_preferred_child()
self.expand(current_node)
def expand(self, node):
self.child_finder(node)
score = 0
for child in node.children:
is_finish, score = self.node_evaluator(child, self)
node.update_win_value(score)
if not child.is_scorable():
self.random_rollout(child)
child.children = []
if len(node.children):
node.expanded = True
def random_rollout(self, node):
self.child_finder(node)
child = random.choice(node.children)
node.children = []
node.add_child(child)
is_finish, score = self.node_evaluator(child, self)
node.update_win_value(score)
if not is_finish:
self.random_rollout(child)
<file_sep>import numpy as np
from TestNode import Node
from copy import deepcopy
from MCTS import MonteCarlo
# 紀錄原本的玩家先手還後手
base_player = 0
def test(board):
"""
測試蒙地卡羅樹搜尋,調整 montecarlo.simulate() 次數,可以增加或減少預判後面幾步
對於黑白棋而言,解尾盤非常重要
Args:
board: 當前盤面,物件 Board 的所有資訊
Return:
best_move: 找到的最佳移動
"""
global base_player
total_step = board.total_step
base_player = board.current_player
node = Node(board, base_player)
montecarlo = MonteCarlo(node, base_player)
montecarlo.child_finder = child_finder
montecarlo.node_evaluator = node_evaluator
if total_step <= 12:
montecarlo.simulate(3)
elif total_step <= 24 and total_step > 12:
# 8 , 5
montecarlo.simulate(5)
elif total_step <= 48 and total_step > 24:
# 16 , 10, 8
montecarlo.simulate(10)
else:
# 25 , 15 , 10
montecarlo.simulate(15)
best_move = montecarlo.make_choice()
return best_move
def child_finder(node):
"""
定義子節點怎麼找的
Args:
node: 現在的節點
"""
global base_player
valid = node.get_valid_state(node.current_player, node.valid_moves)
if valid != []:
for move in valid:
child = Node(deepcopy(node), base_player)
child.action(move)
child.move = move
child.current_player = -child.current_player
child.mov = len(child.compute_available_move(child.current_player))
node.add_child(child)
def node_evaluator(self, node):
"""
評估子節點的好壞
Args:
node: 現在的節點
Return:
是否結束: True or False
getScore: 該節點分數
"""
global base_player
opponent = -self.current_player
chose_player_valid_moves = self.compute_available_move(self.current_player)
opponent_valid_moves = self.compute_available_move(opponent)
state_count_chose = (self.state == self.current_player).sum()
state_count_opponent = (self.state == opponent).sum()
eat = state_count_chose - state_count_opponent
step = step = len(np.where(self.state != 0)[0])
# 如果這手是真正的玩家 (Player) 的,就看要步要調整權重
if self.current_player == base_player:
weightChange(self, self.move[0], self.move[1])
# 吃子數
eat = state_count_chose - state_count_opponent
if chose_player_valid_moves.shape[0] == 0 or opponent_valid_moves.shape[0] == 0:
if self.current_player == base_player and eat > 0:
# 玩家贏
return True, 2000
elif eat == 0:
# 平手
return True, 750
else:
# 輸
return True, -2000
# 繼續
else:
return (
False,
getScore(self, step, eat, self.move, self.mov, self.current_player),
)
def changeWeight():
"""
前 12 手盡量下在 "箱" 裡
權重不一樣,從這裡拿
Return:
前 12 手權重
"""
first_12_weight = np.array(
[
[90, -60, 30, 3, 3, 30, -60, 90],
[-60, -100, 1, 1, 1, 1, -100, -60],
[30, 1, 10, 10, 10, 10, 1, 30],
[3, 1, 10, 1, 1, 10, 1, 3],
[3, 1, 10, 1, 1, 10, 1, 3],
[30, 1, 10, 10, 10, 10, 1, 30],
[-60, -100, 1, 1, 1, 1, -100, -60],
[90, -60, 30, 3, 3, 30, -60, 90],
]
)
return first_12_weight
def getScore(self, step, eat, action, mov, current_player):
"""
算子節點分數
Args:
step: 總步數
eat: 吃子數
action: 移動
mov: 對手行動力剩餘
current_player: 現在玩家
Return:
score: 分數
"""
global base_player
# 開盤: 前 12 手盡量下在 "箱"
if step <= 12:
self.weight = changeWeight()
score = self.weight[action[0]][action[1]] - mov * 5
# 中盤: 以封鎖對手行動力加上佔好位置為主
elif step <= 45 and step > 12:
score = self.weight[action[0]][action[1]] * 3 - (mov * 8 / int(step ** 0.5))
# 尾盤: 考慮吃最多
else:
score = eat
return score
# 更改權重
def weightChange(self, x, y):
"""
玩家如果搶到角了,就可以考慮佔邊戰術
權重不一樣,從這裡更改
Args:
x: 棋盤位置 row
y: 棋盤位置 colume
"""
if x == 0 and y == 0:
self.weight[x + 1][y + 1] = 90
for i in range(1, 7):
self.weight[x + i][y] = (10 - i) * 2
self.weight[x][y + i] = (10 - i) * 2
elif x == 7 and y == 0:
self.weight[x - 1][y + 1] = 90
for i in range(1, 7):
self.weight[x - i][y] = (10 - i) * 2
self.weight[x][y + i] = (10 - i) * 2
elif x == 7 and y == 7:
self.weight[x - 1][y - 1] = 90
for i in range(1, 7):
self.weight[x - i][y] = (10 - i) * 2
self.weight[x][y - i] = (10 - i) * 2
elif x == 0 and y == 7:
self.weight[x + 1][y - 1] = 90
for i in range(1, 7):
self.weight[x + i][y] = (10 - i) * 2
self.weight[x][y - i] = (10 - i) * 2
<file_sep># Exp-monte-carlo-tree-search-reversi
## 成果:100 盤對上隨機對手 96 勝 3 負 1 平

<file_sep>from random import choice
import numpy as np
from Board import Board
class Opponent:
def __init__(self, level="random"):
assert level in ["random", "minmax", "alphabeta"]
self._move = MOVE_FUNC[level]
self.name = "Opponent"
def first_move(self, valid_moves, state):
return choice(valid_moves)
def move(self, _, valid_moves):
return choice(valid_moves)
def random_move(valid_moves):
return choice(valid_moves)
def minmax(board):
pass
def alphabeta(board):
pass
MOVE_FUNC = {"random": random_move, "minmax": minmax, "alphabeta": alphabeta}
<file_sep>import numpy as np
import time
import logging
from opponents import Opponent
from player import Player
from Board import Board
def main():
NUM_RUNS = 100
opponent = Opponent("random")
player = Player()
b = Board(player, opponent)
result = []
player_loss = 0
player_no = 0
draw = 0
for i in range(NUM_RUNS):
player_first = i % 2
if player_first:
player_no = 1
print(f"Player Go First -> O")
else:
player_no = -1
print(f"Player Go Second -> X")
res, state, step = b.play(player_first=player_first)
if state == player_no:
print(f" Player Win : {max(step)}")
print(f" AI Loss : {min(step)}")
print("\n")
if state == -player_no:
print(f" AI Win:{max(step)}")
print(f" Player Loss : {min(step)}")
print("\n")
player_loss += 1
if state == 0:
draw += 1
print(f"Draw :{step[0]}")
print("\n")
print(
f"Player Win : {i - player_loss - draw +1}, Loss {player_loss} ,Draw : {draw}"
)
main()
<file_sep>import numpy as np
class Board:
def __init__(self, player, opponent):
"""
player representation: (first_player: O, second_player: X)
Args:
player: an Object which has required functions
opponent: an Object which has required functions
"""
self.n_side = 8 # (rows,cols)
self.player = player
self.opponent = opponent
self.total_step = 0
self.weight = np.array(
[
[90, -80, 50, 15, 15, 50, -80, 90],
[-80, -500, 6, 6, 6, 6, -500, -80],
[50, 6, 8, 8, 8, 8, 6, 50],
[15, 6, 8, 3, 3, 8, 6, 15],
[15, 6, 8, 3, 3, 8, 6, 15],
[50, 6, 8, 8, 8, 8, 6, 50],
[-80, -500, 6, 6, 6, 6, -500, -80],
[90, -80, 50, 15, 15, 50, -80, 90],
]
)
self.thunder_point = [
[1, 1],
[0, 1],
[1, 0],
[1, 6],
[0, 6],
[1, 7],
[6, 1],
[6, 0],
[7, 1],
[6, 6],
[7, 6],
[6, 7],
]
# 012
# 3#4
# 567
self.directions = (
(-1, -1),
(-1, 0),
(-1, 1),
(0, -1),
(0, 1),
(1, -1),
(1, 0),
(1, 1),
)
# 黑色 = O (先行): 1, 白色 = X: -1
self.isInside = (
lambda r, c: True
if (0 <= r < self.n_side and 0 <= c < self.n_side)
else False
)
def __set_state(self):
self.state = np.zeros((self.n_side, self.n_side))
self.state[self.n_side // 2 - 1, self.n_side // 2 - 1] = -1
self.state[self.n_side // 2, self.n_side // 2] = -1
self.state[self.n_side // 2 - 1, self.n_side // 2] = 1
self.state[self.n_side // 2, self.n_side // 2 - 1] = 1
def reset(self):
"""
重製局面
"""
self.__set_state()
self.current_player = 1
self.valid_moves = {1: [], -1: []}
self.valid_moves_loc = []
self.thunder_point = [
[1, 1],
[0, 1],
[1, 0],
[1, 6],
[0, 6],
[1, 7],
[6, 1],
[6, 0],
[7, 1],
[6, 6],
[7, 6],
[6, 7],
]
self.weight = np.array(
[
[90, -80, 50, 15, 15, 50, -80, 90],
[-80, -500, 6, 6, 6, 6, -500, -80],
[50, 6, 8, 8, 8, 8, 6, 50],
[15, 6, 8, 3, 3, 8, 6, 15],
[15, 6, 8, 3, 3, 8, 6, 15],
[50, 6, 8, 8, 8, 8, 6, 50],
[-80, -500, 6, 6, 6, 6, -500, -80],
[90, -80, 50, 15, 15, 50, -80, 90],
]
)
self.total_step = 0
for row, col in np.argwhere(self.state != 0):
for d in self.directions:
this_row = row + d[0]
this_col = col + d[1]
if (
self.isInside(this_row, this_col)
and self.state[this_row, this_col] == 0
and (this_row, this_col) not in self.valid_moves_loc
):
self.valid_moves_loc.append((this_row, this_col))
self.valid_moves[1] = self.compute_available_move(1)
self.valid_moves[-1] = self.compute_available_move(-1)
def __action(self, action):
"""
決定下棋的位置
Args:
action: A tuple of location on board (row, col)
"""
self.total_step += 1
row, col = action
assert self.state[row, col] == 0, "There has been already set"
assert action in self.valid_moves[self.current_player][:, :2], "wrong choose"
self.state[row, col] = self.current_player
self.valid_moves_loc.remove((row, col))
for d in self.directions:
this_row, this_col = row + d[0], col + d[1]
if (
self.isInside(this_row, this_col)
and self.state[this_row, this_col] == 0
and (this_row, this_col) not in self.valid_moves_loc
):
self.valid_moves_loc.append((this_row, this_col))
flip_direction = np.where(
(self.valid_moves[self.current_player][:, :2] == [row, col]).all(axis=1)
)
for i in self.valid_moves[self.current_player][flip_direction]:
d = self.directions[i[-1]]
this_row, this_col = row, col
while True:
this_row += d[0]
this_col += d[1]
if self.isInside(this_row, this_col):
if self.state[this_row, this_col] == -self.current_player:
self.state[this_row, this_col] = self.current_player
else:
break
else:
break
self.valid_moves[1] = self.compute_available_move(1)
self.valid_moves[-1] = self.compute_available_move(-1)
def compute_available_move(self, chose_player):
"""
計算玩家能夠下棋的位置
Args:
chose_player: An integer to stand for player.
Return:
a list of (row, col)
"""
valid_moves = []
for row, col in self.valid_moves_loc:
for idx, d in enumerate(self.directions):
this_row, this_col = row + d[0], col + d[1]
if (
self.isInside(this_row, this_col)
and self.state[this_row, this_col] == -chose_player
):
while True:
this_row += d[0]
this_col += d[1]
if self.isInside(this_row, this_col):
if self.state[this_row, this_col] == chose_player:
valid_moves.append((row, col, idx))
break
elif self.state[this_row, this_col] == -chose_player:
continue
else:
break
else:
break
valid_moves = np.array(valid_moves)
return valid_moves
def is_game_finished(self, chose_player):
"""
確認該局是否結束以及若結束確認該位是否獲勝。
Args:
chose_player: An integer to stand for player.
Returns:
(Boolean, Integer): (是否結束, 獲勝玩家 1: 黑棋, -1: 白棋, 0: 平手)
"""
opponent = -chose_player
chose_player_valid_moves = self.compute_available_move(chose_player)
opponent_valid_moves = self.compute_available_move(opponent)
if (
chose_player_valid_moves.shape[0] == 0
and opponent_valid_moves.shape[0] == 0
):
state_count_chose = (self.state == chose_player).sum()
state_count_opponent = (self.state == opponent).sum()
if state_count_chose > state_count_opponent:
return (True, chose_player, [state_count_chose, state_count_opponent])
elif state_count_chose == state_count_opponent:
return (True, 0, [state_count_chose, state_count_opponent])
else:
return (True, opponent, [state_count_chose, state_count_opponent])
else:
return (False, 0, [999, 999])
def play(self, player_first=False):
"""
一局遊戲的執行函式
Args:
player_first: Boolean
"""
self.reset()
players = [self.player, self.opponent]
if player_first:
# format: idx = (row,col)
idx = self.player.first_move(
self.get_valid_state(self.current_player), self.state
)
self.__action(idx)
offset = 0
player_no = 1
else:
idx = self.opponent.first_move(
self.get_valid_state(self.current_player), self.state
)
self.__action(idx)
offset = 1
player_no = -1
isFinished = (False, None)
while isFinished[0] == False:
offset = (offset + 1) % 2
# 第一手已經在上面先走了,所以這邊先換人下
self.current_player = -self.current_player
current_player_ = players[offset]
vaild = self.get_valid_state(self.current_player)
if vaild != []:
idx = current_player_.move(
self, self.get_valid_state(self.current_player),
)
self.__action(idx)
self.print_state()
isFinished = self.is_game_finished(self.current_player)
if isFinished[1] == player_no:
self.print_state()
return (True, isFinished[1], isFinished[2])
else:
self.print_state()
return (False, isFinished[1], isFinished[2])
def print_state(self):
"""
輸出局面 O:第一位玩家, X:第二位玩家, #:未下棋位置
e.g.
['X' 'X' 'O' 'X' 'X' 'X' 'O' 'O']
['X' 'X' 'X' 'X' 'X' 'X' 'O' 'O']
['X' 'X' 'X' 'X' 'X' 'X' 'X' 'O']
['O' 'O' 'X' 'X' 'X' 'X' 'X' 'O']
['O' 'X' 'O' 'X' 'O' 'X' 'X' 'O']
['X' 'O' 'O' 'O' 'O' 'O' 'O' 'O']
['O' 'X' 'X' 'O' 'X' 'O' 'O' 'O']
['O' 'O' 'O' 'X' 'O' 'O' 'O' 'O']
"""
for i in self.state:
print(np.where(i == 1, "O", np.where(i == -1, "X", "#")))
print("\n")
def get_valid_state(self, chose_player):
"""
取得玩家可以下棋位置的 list
Args:
chose_player: An integer to stand for player.
return:
a list of (row, col)
"""
if self.valid_moves[chose_player] != []:
return np.unique(self.valid_moves[chose_player][:, :2], axis=0)
else:
return []
<file_sep>import random
from math import log, sqrt
import numpy as np
class Node:
def __init__(self, board, baseplayer):
self.state = board.state
self.valid_moves = board.valid_moves
self.valid_moves_loc = board.valid_moves_loc
self.isInside = board.isInside
self.directions = board.directions
self.current_player = board.current_player
self.baseplayer = baseplayer
self.weight = board.weight
self.win_value = 0
self.score = 0
self.visits = 0
self.mov = 0
self.total_step = 0
self.parent = None
self.children = []
self.move = []
self.tree = []
self.expanded = False
def update_win_value(self, value):
self.win_value = value
self.visits += 1
def add_child(self, child):
self.children.append(child)
child.parent = self
def add_children(self, children):
for child in children:
self.add_child(child)
def get_preferred_child(self):
"""
挑最高分的子樹
"""
best_score = float("-inf")
for child in self.children:
if child.win_value > best_score:
best_score = child.win_value
best_child = child
return best_child
def get_score(self, root_node):
return self.win_value
def is_scorable(self):
return self.visits != None
# TODO: 改成繼承的方式去寫
def get_valid_state(self, chose_player, valid_moves):
"""
取得玩家可以下棋位置的 list
Args:
chose_player: An integer to stand for player.
return:
a list of (row, col)
"""
if valid_moves[chose_player] != []:
return np.unique(valid_moves[chose_player][:, :2], axis=0)
else:
return []
def compute_available_move(self, chose_player):
"""
計算玩家能夠下棋的位置
Args:
chose_player: An integer to stand for player.
Return:
a list of (row, col)
"""
valid_moves = []
for row, col in self.valid_moves_loc:
for idx, d in enumerate(self.directions):
this_row, this_col = row + d[0], col + d[1]
if (
self.isInside(this_row, this_col)
and self.state[this_row, this_col] == -chose_player
):
while True:
this_row += d[0]
this_col += d[1]
if self.isInside(this_row, this_col):
if self.state[this_row, this_col] == chose_player:
valid_moves.append((row, col, idx))
break
elif self.state[this_row, this_col] == -chose_player:
continue
else:
break
else:
break
valid_moves = np.array(valid_moves)
return valid_moves
def print_state(self):
"""
輸出局面 O:第一位玩家, X:第二位玩家, #:未下棋位置
e.g.
['X' 'X' 'O' 'X' 'X' 'X' 'O' 'O']
['X' 'X' 'X' 'X' 'X' 'X' 'O' 'O']
['X' 'X' 'X' 'X' 'X' 'X' 'X' 'O']
['O' 'O' 'X' 'X' 'X' 'X' 'X' 'O']
['O' 'X' 'O' 'X' 'O' 'X' 'X' 'O']
['X' 'O' 'O' 'O' 'O' 'O' 'O' 'O']
['O' 'X' 'X' 'O' 'X' 'O' 'O' 'O']
['O' 'O' 'O' 'X' 'O' 'O' 'O' 'O']
"""
for i in self.state:
print(np.where(i == 1, "O", np.where(i == -1, "X", "#")))
print("\n")
def action(self, action):
"""
決定下棋的位置
Args:
action: A tuple of location on board (row, col)
"""
row, col = action
assert self.state[row, col] == 0, "There has been already set"
assert action in self.valid_moves[self.current_player][:, :2], "wrong choose"
self.state[row, col] = self.current_player
self.valid_moves_loc.remove((row, col))
for d in self.directions:
this_row, this_col = row + d[0], col + d[1]
if (
self.isInside(this_row, this_col)
and self.state[this_row, this_col] == 0
and (this_row, this_col) not in self.valid_moves_loc
):
self.valid_moves_loc.append((this_row, this_col))
flip_direction = np.where(
(self.valid_moves[self.current_player][:, :2] == [row, col]).all(axis=1)
)
for i in self.valid_moves[self.current_player][flip_direction]:
d = self.directions[i[-1]]
this_row, this_col = row, col
while True:
this_row += d[0]
this_col += d[1]
if self.isInside(this_row, this_col):
if self.state[this_row, this_col] == -self.current_player:
self.state[this_row, this_col] = self.current_player
else:
break
else:
break
self.valid_moves[1] = self.compute_available_move(1)
self.valid_moves[-1] = self.compute_available_move(-1)
<file_sep># 組員: 姓名一 (學號一), options[姓名二 (學號二), 姓名三 (學號三)]
from random import choice
import time
import logging
import numpy as np
from TestMCTS import test
TIMEOUT = 10
def profile(func):
def wrap(*args, **kwargs):
s = time.time()
result = func(*args, **kwargs)
duration = time.time() - s
if duration > TIMEOUT:
logging.warning(f"Time Limit Exceeded: {duration}")
logging.info(f"using {duration} sec")
return result
return wrap
class Player:
# TODO: 把第一步隨機改掉
def __init__(self):
self.name = "Player"
pass
def first_move(self, valid_moves, state):
# 第一步隨機
return choice(valid_moves)
@profile
def move(self, board, _):
"""
策略 1: 無論如何,有角點就下,然後更新旁邊邊的權重,方便爬邊
"""
pior = []
for state in _:
if list(state) == [0, 0]:
pior.append(state)
if list(state) == [0, 7]:
pior.append(state)
if list(state) == [7, 0]:
pior.append(state)
if list(state) == [7, 7]:
pior.append(state)
if pior != []:
move = list(choice(pior))
if move == [0, 0]:
board.weight[0][1] = 50
board.weight[1][0] = 50
board.weight[1][1] = 20
board.thunder_point.remove([0, 1])
board.thunder_point.remove([1, 0])
board.thunder_point.remove([1, 1])
if move == [0, 7]:
board.weight[0][6] = 50
board.weight[1][7] = 50
board.weight[1][6] = 20
board.thunder_point.remove([0, 6])
board.thunder_point.remove([1, 7])
board.thunder_point.remove([1, 6])
if move == [7, 0]:
board.weight[6][0] = 50
board.weight[7][1] = 50
board.weight[6][1] = 20
board.thunder_point.remove([6, 0])
board.thunder_point.remove([7, 1])
board.thunder_point.remove([6, 1])
if move == [7, 7]:
board.weight[7][6] = 50
board.weight[6][7] = 50
board.weight[6][6] = 20
board.thunder_point.remove([7, 6])
board.thunder_point.remove([6, 7])
board.thunder_point.remove([6, 6])
return move
"""
策略 2:
根據步數決定搜尋深度,50 步到達最大
"""
move = test(board)
"""
策略 3:
因為搜尋的時候不夠深,所以有時候雷點的分數比較高,但這卻是爛步
"""
_ = list(_)
if list(move) in board.thunder_point and len(_) != 0:
best_score = -10000
best_move = []
for mov in _:
score = board.weight[mov[0]][mov[1]]
if score > best_score:
best_score = score
best_move = [mov]
elif score == best_score:
best_move.append(mov)
return choice(best_move)
return move
| 8c6cc616753df53fa34c715d2faa49407ad1534d | [
"Markdown",
"Python"
] | 8 | Python | licaiwang/Exp-monte-carlo-tree-search-reversi | 13219d641319e6e22526b47ff6bf499f8a4e6617 | 9714d638b0f38ef5f4e8fa6bffb725ae29293a06 |
refs/heads/master | <repo_name>Loganathasanjeev/ustproject<file_sep>/remainder.sql
-- phpMyAdmin SQL Dump
-- version 4.8.3
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1:3306
-- Generation Time: Oct 24, 2019 at 06:09 AM
-- Server version: 5.7.23
-- PHP Version: 7.2.10
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: `remainder`
--
-- --------------------------------------------------------
--
-- Table structure for table `remainder_details`
--
DROP TABLE IF EXISTS `remainder_details`;
CREATE TABLE IF NOT EXISTS `remainder_details` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`Name` varchar(20) NOT NULL,
`Date` date NOT NULL,
`Details` varchar(100) NOT NULL,
PRIMARY KEY (`ID`)
) ENGINE=MyISAM AUTO_INCREMENT=16 DEFAULT CHARSET=latin1;
--
-- Dumping data for table `remainder_details`
--
INSERT INTO `remainder_details` (`ID`, `Name`, `Date`, `Details`) VALUES
(15, 'Deepak', '1998-10-26', 'Birthday'),
(14, 'Vijay', '1998-11-04', 'Birthday');
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
<file_sep>/UST.py
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
passwd="",
database="remainder"
)
mycursor = mydb.cursor()
def printfun(res):
for x in res:
print(x)
def insert():
name=input("Enter the reminder Name:")
date=input("Enter the reminder Date in the format (YYYY.MM.DD):")
details=input("Enter the reminder Details:")
mySql_insert_query = """INSERT INTO `remainder_details`(`Name`, `Date`, `Details`) VALUES (%s, %s, %s) """
recordTuple = (name, date, details)
sc=mycursor.execute(mySql_insert_query, recordTuple)
if sc!=1:
print("Successfully Inserted:")
else:
print("Not Inserted")
return
viewall()
def update():
viewall()
idv=int(input("Enter the ID to be Updated:"))
name=input("Enter the reminder Name to update:")
date=input("Enter the reminder Date in the format (YYYY.MM.DD) to update:")
details=input("Enter the reminder Details to update:")
query = """ UPDATE remainder_details SET Name = %s , Date = %s , Details = %s WHERE id = %s """
data = (name,date,details,idv)
sc=mycursor.execute(query,data)
if sc!=1:
print(" Succesfully Updated")
else:
print("Not Updated")
return
viewall()
def delete():
viewall()
idv=int(input("Enter the ID to be Deleted:"))
sql = """DELETE FROM remainder_details WHERE ID = %s"""
sc=mycursor.execute(sql,(idv,))
if sc!=1:
print(" Successfully Deleted")
else:
print("Not Deleted")
return
viewall()
def viewall():
print("(id,Name,Date,Details)")
mycursor.execute("SELECT * FROM remainder_details")
printfun(mycursor.fetchall())
while(1):
print("Enter your choice \n 1. Insert a Reminder \n 2. View all Reminders \n 3. Update a Reminder \n 4. Delete a Reminder \n 5. Exit \n")
n=int(input())
if n==1:
insert()
elif n==2:
viewall()
elif n==3:
update()
elif n==4:
delete()
elif n==5:
break
| 7238dc14fd13489f93013a58c04812e8bd757172 | [
"SQL",
"Python"
] | 2 | SQL | Loganathasanjeev/ustproject | 9e62a914da1044197cba16a2677c259fb0c6e8af | f8353b6afe0a428f435dbe689e9622b45bc0d41d |
refs/heads/master | <file_sep>livegraffiti
============
A program that uses a video feed to show live progress of your light graffiti
<file_sep>#include "testApp.h"
//--------------------------------------------------------------
void testApp::setup() {
ofBackground(0,0,0);
videoPlayer.loadMovie("smalll.mov");
videoPlayer.setLoopState(OF_LOOP_NORMAL);
videoPlayer.play();
// videoPlayer.setPaused(true);
videoPlayer.setFrame(targetFrame = 0);
int winW, winH;
winW = 600;
winH = 400;
ofSetWindowShape(winW, winH);
// a pixel must be brighter than this to turn into the secondary color (monchormatic display)
treshold = 450;
ofSetLogLevel(OF_LOG_VERBOSE);
//need this for alpha to come through
// ofEnableAlphaBlending();
// allocate our image buffers
// rgb.allocate(videoPlayer.getWidth(), videoPlayer.getHeight());
// rgb2.allocate(videoPlayer.getWidth(),videoPlayer.getHeight());
// maskImg.allocate(videoPlayer.getWidth(),videoPlayer.getHeight());
// fbo.allocate(rgb2.getWidth()+10, rgb2.getHeight()+10);
}
//--------------------------------------------------------------
void testApp::update(){
if(videoPlayer.isPaused()) videoPlayer.setFrame(targetFrame);
videoPlayer.update();
}
//--------------------------------------------------------------
void testApp::draw(){
ofBackground(0,0,0);
drawGrid();
videoPlayer.draw(0,0);
}
void testApp::drawGrid(){
ofPushStyle();
int gridX = 0;
int gridY = 50;
gridCellSize = 5;
gridSpacing = 5;
unsigned char * pixels = videoPlayer.getPixels();
for(int py=0; py<videoPlayer.getHeight(); py++){
for(int px=0; px<videoPlayer.getWidth(); px++){
int pindex = (py * videoPlayer.getWidth() + px)*3;
if(pixels[pindex]+pixels[pindex+1]+pixels[pindex+2] > treshold){
ofSetColor(0, 0, 255);
} else {
ofSetColor(255,255,0);
}
// ofSetColor(pixels[pindex],
// pixels[pindex+1],
// pixels[pindex+2]); // red, 50% transparent
ofRect(gridX+(gridCellSize+gridSpacing)*px,
gridY+(gridCellSize+gridSpacing)*py,
gridCellSize,
gridCellSize);
}
}
ofPopStyle();
}
//--------------------------------------------------------------
void testApp::mousePressed(int x, int y, int button) {
}
//--------------------------------------------------------------
void testApp::keyPressed (int key){
if (key == ' '){
videoPlayer.setPaused(!videoPlayer.isPaused());
}
if (key == OF_KEY_RIGHT){
videoPlayer.setPaused(true);
targetFrame = targetFrame+1;
if(targetFrame >= videoPlayer.getTotalNumFrames()){
targetFrame = 0;
}
ofLog(OF_LOG_VERBOSE, "Current frame: " + ofToString(targetFrame));
}
if (key == OF_KEY_LEFT && targetFrame > 0){
videoPlayer.setPaused(true);
targetFrame = targetFrame-1;
ofLog(OF_LOG_VERBOSE, "Current frame: " + ofToString(targetFrame));
}
if(key == OF_KEY_DOWN){ treshold--; ofLog(OF_LOG_VERBOSE, "Treshold: " + ofToString(treshold)); }
if(key == OF_KEY_UP){ treshold++; ofLog(OF_LOG_VERBOSE, "Treshold: " + ofToString(treshold)); }
if (key == '['){}
}
//--------------------------------------------------------------
void testApp::keyReleased(int key){
}
//--------------------------------------------------------------
void testApp::mouseMoved(int x, int y ){
}
//--------------------------------------------------------------
void testApp::mouseDragged(int x, int y, int button){
}
//--------------------------------------------------------------
void testApp::mouseReleased(int x, int y, int button){
}
//--------------------------------------------------------------
void testApp::windowResized(int w, int h){
}
//--------------------------------------------------------------
void testApp::gotMessage(ofMessage msg){
}
//--------------------------------------------------------------
void testApp::dragEvent(ofDragInfo dragInfo){
}
//--------------------------------------------------------------
void testApp::exit()
{
}
<file_sep>#pragma once
#include "ofMain.h"
#include "ofxOpenCv.h"
#include "ofxUI.h"
class testApp : public ofBaseApp{
public:
// OF-basics
void setup();
void update();
void draw();
// event-handlers
void keyPressed(int key);
void keyReleased(int key);
void mouseMoved(int x, int y );
void mouseDragged(int x, int y, int button);
void mousePressed(int x, int y, int button);
void mouseReleased(int x, int y, int button);
void windowResized(int w, int h);
void dragEvent(ofDragInfo dragInfo);
void gotMessage(ofMessage msg);
// camera video grabber
ofVideoGrabber grabber;
// video player
ofVideoPlayer videoPlayer;
int targetFrame;
// image objects; "normal" webcam image, manipulated webcam image and grayscale (mask) image
ofxCvColorImage rgb, rgb2;
ofxCvGrayscaleImage maskImg;
// screenbuffer
ofFbo fbo;
// webcam image dimensions
int vidW, vidH;
// UI-stuff
bool bDrawUI;
ofxUICanvas *gui;
void exit();
void guiEvent(ofxUIEventArgs &e);
// grid
int gridCellSize;
int gridSpacing;
int treshold;
void drawGrid();
};
| 1791f5552e390749070ce22599bd2759b07785d6 | [
"Markdown",
"C++"
] | 3 | Markdown | markkorput/OF-lowresser | 722f6caf807da7498b7e7af5e94fb01b903a71f6 | ce6089caf8c6307635abc1d1cdc7d5775bace6bd |
refs/heads/master | <repo_name>AminSamir83/boolean<file_sep>/index.php
<?php
/**
* Created by PhpStorm.
* User: HP
* Date: 08/11/2018
* Time: 11:53
*/
$a="0";
$b="TRUE";
$c=FALSE;
$d=($a OR $b);
$e=($a AND $c);
$f=($a XOR $b);
echo "FALSE TRUE FALSE TRUE FALSE TRUE"
?> | 9888363992cf664ac108c9aecd33cae781a1d1c7 | [
"PHP"
] | 1 | PHP | AminSamir83/boolean | b06c7e13c0a98983d0e5a0cccf02a1c9ba7ceadd | 374456c155636b0a7b9fcb9ce45fd1b36b714cb6 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.